### Setup Kunkun Project Development Environment Source: https://context7_llms Provides instructions for setting up the development environment for the Kunkun project. This includes installing Node.js, pnpm, Bun, Deno, Rust, protobuf, and cmake. It also covers cloning the repository and installing dependencies. ```bash git clone https://github.com/kunkunsh/kunkun.git --recursive pnpm install pnpm prepare ``` -------------------------------- ### Install and Run Kunkun Extension Development Source: https://context7_llms Commands to install dependencies, build the extension, and start the development server with watch mode. The build process generates a `dist/index.js` file, which is the entry point for the extension. ```bash bun install bun run build # build the extension, generate dist/index.js file, this is the entry file of the extension, make sure it's listed in the package.json bun dev # start the development server, basically running `build` with watch mode ``` -------------------------------- ### Math Library Example (RPC Style) Source: https://context7_llms Example demonstrating how to create a math library in Deno and call its methods from a web worker or iframe using the RPC style. ```APIDOC ## Deno Math Library (RPC Style) ### Description This section provides an example of creating a math library in Deno that can be invoked remotely using the RPC API. It outlines the necessary type definitions and the requirement for `async` functions. ### API Definition (types.ts) ```typescript export interface MathLibAPI { add(a: number, b: number): Promise subtract(a: number, b: number): Promise } ``` ### Notes - All API methods exposed by the Deno library must be `async` functions, returning a `Promise`. - This ensures correct handling of return types when communicating over the RPC channel. ``` -------------------------------- ### System Info Usage Examples Source: https://docs.kunkun.sh/developer/api/sysinfo Examples demonstrating how to use the System Info API, including refreshing CPU data and retrieving CPU information. ```APIDOC ## System Info Usage Examples ### Description This section provides code examples for interacting with the System Info API. ### Refresh CPU and Get CPU Info This example shows how to refresh the CPU data and then retrieve detailed CPU information. ```javascript // Import the sysInfo module import { sysInfo } from "@kksh/api/ui/template"; // Or other import paths like @kksh/api/ui/custom or @kksh/api/headless // Refresh CPU information await sysInfo.refreshCpu(); // Get detailed CPU information const cpuInfo = await sysInfo.cpuInfo(); // Log details for each CPU cpuInfo.cpus.forEach((cpu) => { console.log("name: ", cpu.name); console.log("frequency: ", cpu.frequency); console.log("cpu_usage: ", cpu.cpu_usage); console.log("vendor_id: ", cpu.vendor_id); console.log("brand: ", cpu.brand); }); ``` ### Available Import Paths * Template (worker): `@kksh/api/ui/template` * Custom (iframe): `@kksh/api/ui/custom` * Headless (worker): `@kksh/api/headless` ``` -------------------------------- ### Install Protobuf Compiler on Windows using Chocolatey Source: https://context7_llms This snippet shows how to install the protobuf compiler and OpenSSL on Windows using Chocolatey, a package manager for Windows. It also includes setting environment variables required for protobuf compilation. ```powershell choco install protoc choco install openssl # Then configure the environment variables (yours may differ): # - OPENSSL_DIR: C:\Program Files\OpenSSL-Win64 # - OPENSSL_INCLUDE_DIR: C:\Program Files\OpenSSL-Win64\include # - OPENSSL_LIB_DIR: C:\Program Files\OpenSSL-Win64\lib ``` -------------------------------- ### Configure 'fetch:all' Permission in package.json Source: https://context7_llms Provides an example of how to configure the necessary 'fetch:all' permission in the `package.json` file to enable the Kunkun Fetch API. ```json { ... "permissions": ["fetch:all"], ... } ``` -------------------------------- ### Install Kunkun Extension Template Source: https://context7_llms Command to initialize a new Kunkun extension project using a scaffolding template. This command helps set up the basic project structure for extension development. ```bash npm init kunkun@latest # choose a template ``` -------------------------------- ### Sample package.json for Kunkun Extension Source: https://context7_llms An example of a `package.json` file used in Kunkun extensions. It demonstrates the necessary configurations for an extension, including potential fields like 'description' which can be modified to test manifest validation. ```json { "name": "my-kunkun-extension", "version": "1.0.0", "description": "A sample Kunkun extension", "main": "index.js", "kunkun": { "extensionId": "com.example.myextension" } } ``` -------------------------------- ### Add Clipboard Read Permission Source: https://context7_llms Specifies the necessary permissions for a Kunkun extension in the package.json file. This example demonstrates how to add permission to read clipboard text. ```json { "kunkun": { "permissions": [ "clipboard:read-text" ] } } ``` -------------------------------- ### Svelte Button Component Example Source: https://context7_llms Demonstrates the basic usage of the Button component from the '@kksh/svelte5' package. This package is designed for Svelte 5 and provides access to most Shadcn UI components. ```svelte ``` -------------------------------- ### NPM Package Configuration Source: https://context7_llms Essential fields in package.json for publishing to NPM. Includes 'files' for published content, 'license', and 'repository' for provenance. The 'name' is recommended to start with 'kunkun-ext'. ```json { "name": "kunkun-ext-your-package-name", "version": "1.0.0", "files": [ "dist" ], "license": "MIT", "repository": "https://github.com/your-username/your-repo-name" } ``` -------------------------------- ### Configure Open API Permissions in package.json Source: https://context7_llms Provides examples of how to configure permissions for the Open API in the `package.json` manifest file. This includes allowing specific URLs, folders, and files, as well as denying certain paths. Dependencies: None. Input: Manifest file configuration. Output: Controlled access for Open API. ```json { "permissions": [ { "permission": "open:url", "allow": [ { "url": "https://kunkun.sh" }, { "url": "https://kunkun.sh/**" }, { "url": "http://kunkun.sh" }, { "url": "mailto://**@gmail.com" } ] } ], "... } ``` ```json { "permissions": [ { "permission": "open:folder", "allow": [ { "path": "$DESKTOP/**" }, { "path": "$DOWNLOAD" }, { "path": "$DOCUMENT/dev/*" } ] } ], "... } ``` ```json { "permissions": [ { "permission": "open:file", "allow": [ { "path": "$DESKTOP/**" }, { "path": "$DOWNLOAD/schema.json" } ], "deny": [ { "path": "$DESKTOP/malicious.sh" } ] } ], "... } ``` -------------------------------- ### Construct file paths with Path API Source: https://context7_llms Shows how to use the Path API to join directory paths and get the desktop directory. This API is simple and does not require any special permissions. Dependencies: None. Input: Path components (strings). Output: Constructed file path (string). ```typescript const videoPath = await path.join(await path.desktopDir(), 'kunkun.mp4') // sample output: /Users/kksh/Desktop/kunkun.mp4 ``` -------------------------------- ### Grant File Search Permission (JSON) Source: https://context7_llms Configuration in package.json to enable the fs:search permission. The 'allow' array specifies the directories where file searches are permitted. The example allows searching within the Downloads directory. ```json { ... "permissions": [ { "permission": "fs:search", "allow": [ { "path": "$DOWNLOAD" } ] }, ], ... ``` -------------------------------- ### Get OS platform information with OS API Source: https://context7_llms Demonstrates how to retrieve the operating system platform using the OS API. This can be useful for adapting application behavior based on the user's OS. Dependencies: None. Input: None. Output: String representing the OS platform (e.g., "windows", "macos", "linux"). ```typescript const platform = await os.platform() console.log(platform) // "windows" | "macos" | "linux" ``` -------------------------------- ### Granting File Read Access with Path Aliases Source: https://docs.kunkun.sh/developer/api/fs This JSON snippet demonstrates how to configure permissions in package.json to allow reading a specific file using path aliases. It specifies the 'fs:read' permission and lists allowed paths, including examples for different operating systems using $HOME and $APPDATA. ```json { "permissions": [ "os:all", { "permission": "fs:read", "allow": [ { "path": "$HOME/Library/Application Support/Code/User/globalStorage/alefragnani.project-manager/projects.json" }, { "path": "$HOME/.config/Code/User/globalStorage/alefragnani.project-manager/projects.json" }, { "path": "$APPDATA/Code/User/globalStorage/alefragnani.project-manager/projects.json" } ] } ] } ``` -------------------------------- ### CSS Steps Component Styling Source: https://docs.kunkun.sh/api-docs Styles for an ordered steps component, featuring numbered bullets and connecting guide lines. It uses CSS counters for numbering and provides customization for bullet size, margin, and start index. ```css .sl-steps{--bullet-size: calc(var(--sl-line-height) * 1rem);--bullet-margin: .375rem;list-style:none;counter-reset:steps-counter var(--sl-steps-start, 0);padding-inline-start:0}.sl-steps>li{counter-increment:steps-counter;position:relative;padding-inline-start:calc(var(--bullet-size) + 1rem);padding-bottom:1px;min-height:calc(var(--bullet-size) + var(--bullet-margin))}.sl-steps>li+li{margin-top:0}.sl-steps>li:before{content:counter(steps-counter);position:absolute;top:0;inset-inline-start:0;width:var(--bullet-size);height:var(--bullet-size);line-height:var(--bullet-size);font-size:var(--sl-text-xs);font-weight:600;text-align:center;color:var(--sl-color-white);background-color:var(--sl-color-gray-6);border-radius:99rem;box-shadow:inset 0 0 0 1px var(--sl-color-gray-5)}.sl-steps>li:after{--guide-width: 1px;content:"";position:absolute;top:calc(var(--bullet-size) + var(--bullet-margin));bottom:var(--bullet-margin);inset-inline-start:calc((var(--bullet-size) - var(--guide-width)) / 2);width:var(--guide-width);background-color:var(--sl-color-hairline-light)}.sl-steps>li>:first-child{--lh: calc(1em * var(--sl-line-height));--shift-y: calc(.5 * (var(--bullet-size) - var(--lh)));transform:translateY(var(--shift-y));margin-bottom:var(--shift-y)}.sl-steps>li>:first-child:where(h1,h2,h3,h4,h5,h6){--lh: calc(1em * var(--sl-line-height-headings))}@supports (--prop: 1lh){.sl-steps>li>:first-child{--lh: 1lh}} ``` -------------------------------- ### Initialize Theme and Show App - JavaScript Source: https://docs.api.kunkun.sh/interfaces/index.IEvent Initializes the application theme from local storage and controls the display of the application body. It uses a timeout to ensure the application is ready before showing the page. ```javascript IEvent | @kksh/apidocument.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os";document.body.style.display="none";setTimeout(() => app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Example Drizzle Proxy Driver for HTTP Backend (TypeScript) Source: https://context7_llms An example of a Drizzle proxy driver implementation that communicates with a remote HTTP backend. This driver sends SQL queries and parameters to a specified endpoint and handles the response. It's useful for scenarios where the database backend is exposed via an API. ```typescript import { drizzle } from 'drizzle-orm/pg-proxy'; const db = drizzle(async (sql, params, method) => { try { const rows = await axios.post('http://localhost:3000/query', { sql, params, method }); return { rows: rows.data }; } catch (e: any) { console.error('Error from pg proxy server: ', e.response.data) return { rows: [] }; } }); ``` -------------------------------- ### Path API Source: https://context7_llms The Path API provides utilities for interacting with file paths. Refer to the official documentation for detailed descriptions and examples. ```APIDOC ## Path API ### Description Provides utilities for interacting with file paths. This API is based on Tauri's path API. ### Documentation Refer to https://docs.api.kunkun.sh/interfaces/index.IPath for detailed descriptions and examples. ### Source https://v2.tauri.app/reference/javascript/api/namespacepath/#_top ``` -------------------------------- ### Create and Execute Bash Script Source: https://docs.kunkun.sh/developer/api/shell Demonstrates how to create a bash script using `makeBashScript` and then execute it. It shows how to capture the output and provides an alternative method for spawning the command and handling its streams (`stdout`, `stderr`) and events (`close`, `error`). ```javascript const cmd = shell.makeBashScript("echo \"Hello World\"") const output = await cmd.execute() console.log(output.stdout); // or spawn the command let stdout = "" let stderr = "" cmd.on("close", (data) => { console.log(`command finished with code ${data.code} and signal ${data.signal}`) // sample output: "command finished with code 0 and signal null" }) cmd.on("error", (error) => { console.error(error) }) cmd.stdout.on("data", (line) => { stdout += line }) cmd.stderr.on("data", (line) => { stderr += line }) await cmd.spawn() ``` -------------------------------- ### Get Application Language - Kunkun API Source: https://context7_llms Retrieves the language preference of the application. This API is part of the App module within the Kunkun API. ```typescript app.language().then((lang) => { console.log("Language:", lang); }); ``` -------------------------------- ### Create and Execute Deno Command Source: https://context7_llms Demonstrates creating a Deno command using the shell API and executing it. This requires appropriate Deno permissions declared in package.json. ```typescript // Assuming 'shell' is imported and available const denoCommand = shell.createDenoCommand("deno --version"); const result = await denoCommand.execute(); console.log(result.stdout); ``` -------------------------------- ### Vue Button Component Usage Source: https://context7_llms Demonstrates how to use the Button component from the `@kksh/vue/button` package in a Vue application. It shows a simple example of rendering a button with text. ```vue ``` -------------------------------- ### Initialize Project with Headless Command Template (Terminal) Source: https://docs.kunkun.sh/extensions/headless-command This command initializes a new Kunkun project using the latest version of kunkun and selecting the template option, which is suitable for creating headless command extensions. ```bash npm init kunkun@latest # choose the template ``` -------------------------------- ### KV API Operations Source: https://docs.kunkun.sh/developer/api/kv This section demonstrates how to use the KV API for common operations like checking existence, setting, and getting values. ```APIDOC ## KV API Operations ### Description Demonstrates basic usage of the KV API, including checking if a key exists, setting a value, and retrieving it. ### Method N/A (This is a client-side API wrapper) ### Endpoint N/A (This is a client-side API wrapper) ### Parameters #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript import { kv } from "@kksh/api/ui/template"; // Or other import paths kv.exists("test").then((exists) => { console.log("KV exists:", exists); }); kv.set("test", Math.random().toString()).then(() => { kv.get("test").then((value) => { console.log("KV value:", value); }); }); ``` ### Response #### Success Response (200) - **exists** (boolean) - Indicates whether the key exists. - **value** (any) - The retrieved value associated with the key. Note: Data is stored as JSON string and will be parsed. #### Response Example ```json { "exists": true } ``` ```json { "value": "some_random_string" } ``` ### Caution The data is stored as JSON string in the database, so data passed to `set` must be serializable with `JSON.stringify`. It doesn’t have to be a string, but it will be converted to string when stored, and `JSON.parse` will be called when retrieved. ``` -------------------------------- ### Open URLs, Folders, and Files with Open API Source: https://context7_llms Illustrates how to use the Open API to open URLs in the default browser, open folders in the default file explorer, and open files with their default application. Requires specific permissions declared in the manifest file. Dependencies: 'open:url', 'open:folder', or 'open:file' permissions. Input: URL (string), Folder path (string), File path (string). Output: Opens the specified resource. ```typescript open.url("https://kunkun.sh") // open url in default app open.folder("/Users/kksh/Downloads/") // open folder open.file("/Users/kksh/Downloads/schema.mp4") // open file in default app ``` -------------------------------- ### Svelte Command Palette Implementation Source: https://context7_llms Demonstrates how to implement a command palette using the `@kksh/svelte5` library. It includes various command items categorized into suggestions and settings, with icons and shortcuts. ```svelte No results found. Calendar Search Emoji Launch Profile ⌘P Mail ⌘B Settings ⌘S ``` -------------------------------- ### onDragOver Event Listener - TypeScript Source: https://docs.api.kunkun.sh/interfaces/index.IEvent Provides a method to get the position of a dragged item. It accepts a callback function that receives a DragOverPayload. ```typescript onDragOver: (callback: (payload: [DragOverPayload](../types/index.DragOverPayload.html)) => void) => void ``` -------------------------------- ### Database API: Add Data (JavaScript) Source: https://docs.kunkun.sh/developer/api/db Demonstrates how to add data entries to the extension's database using the `db.add` function. It shows how to provide data, an optional data type for categorization, and a search text for indexing. Data must be serialized to a string, especially for objects. ```javascript import { db } from "@kksh/api/ui/template"; await db.add({ data: JSON.stringify({ name: "Kunkun" }), dataType: "preference", searchText: "preference", }); ``` ```javascript import { db } from "@kksh/api/ui/custom"; await db.add({ data: JSON.stringify({ name: "Kunkun" }), dataType: "preference", searchText: "preference", }); ``` ```javascript import { db } from "@kksh/api/headless"; await db.add({ data: JSON.stringify({ name: "Kunkun" }), dataType: "preference", searchText: "preference", }); ``` -------------------------------- ### onDragDrop Event Listener - TypeScript Source: https://docs.api.kunkun.sh/interfaces/index.IEvent Provides a method to get files dropped on the window. It accepts a callback function that receives a DragDropPayload. ```typescript onDragDrop: (callback: (payload: [DragDropPayload](../types/index.DragDropPayload.html)) => void) => void ``` -------------------------------- ### Initialize Deno Project and Add Dependency Source: https://docs.kunkun.sh/developer/api/deno Commands to initialize a new Deno project in a subdirectory and add the Kunkun API package from JSR. This sets up the basic structure for Deno scripts. ```bash deno init deno-src den o add jsr:@kunkun/api ``` -------------------------------- ### Fetch and Display CPU Information Source: https://docs.kunkun.sh/developer/api/sysinfo Demonstrates how to refresh CPU data and then retrieve and log detailed information about each CPU core. This includes frequency, usage, vendor ID, and brand. ```typescript await sysInfo.refreshCpu() const cpuInfo = await sysInfo.cpuInfo() cpuInfo.cpus.forEach((cpu) => { console.log("name: ", cpu.name) console.log("frequency: ", cpu.frequency) console.log("cpu_usage: ", cpu.cpu_usage) console.log("vendor_id: ", cpu.vendor_id) console.log("brand: ", cpu.brand) }) ``` -------------------------------- ### Searching for Files using fs.fileSearch in JavaScript Source: https://docs.kunkun.sh/developer/api/fs This JavaScript code demonstrates how to search for files using the fs.fileSearch API. It allows specifying search locations, a query string for the filename, and various other options to refine the search. ```javascript const searchRes = await fs.fileSearch({ locations: [await path.downloadDir()], query: "file.txt", }); ``` -------------------------------- ### Import System Info from UI Custom Source: https://docs.kunkun.sh/developer/api/sysinfo Imports the sysInfo module from a custom UI integration. This allows for more flexibility in how system information is displayed and interacted with in a custom frontend setup. ```typescript import { sysInfo } from "@kksh/api/ui/custom"; ``` -------------------------------- ### Manual Deno RPC Channel Configuration Source: https://docs.kunkun.sh/developer/api/deno Demonstrates manual configuration of an RPC channel in Deno using `@kunkun/kkrpc`. It shows how to set up `DenoStdio` and `RPCChannel` to establish a bidirectional communication channel for API calls. ```typescript import { DenoStdio, RPCChannel } from "@kunkun/kkrpc" import { type MathLibAPI } from "../types.ts" // Define your API methods (that will be exposed to the other side) export const mathLib: MathLibAPI = { add: async (a: number, b: number) => a + b, subtract: async (a: number, b: number) => a - b } const stdio = new DenoStdio(Deno.stdin.readable, Deno.stdout.writable) const channel = new RPCChannel(stdio, mathLib) const api = channel.getApi() ``` -------------------------------- ### Integrate Google Analytics Tracking Source: https://docs.kunkun.sh/extensions/security/permissions Initializes Google Analytics by creating a dataLayer and configuring the gtag function with a specific tracking ID. This is a standard setup for web analytics. ```javascript window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'G-0CV6E8FN6E'); ``` -------------------------------- ### Enable VSCode Intellisense for Extension Manifest Source: https://context7_llms This JSON configuration snippet shows how to enable VSCode's built-in intellisense for Kunkun extension manifests by referencing the schema URL in the package.json file. This helps prevent errors by highlighting missing fields and incorrect data types. ```json { "$schema": "https://schema.kunkun.sh", ... } ``` -------------------------------- ### Initialize PostHog Analytics Source: https://docs.kunkun.sh/api-docs This snippet initializes PostHog, a product analytics platform. It includes the necessary script to load the PostHog array and then calls the init function with the API key and host. This enables event tracking and user analytics. ```javascript !function(t,e){ var o,n,p,r; e.__SV|| (window.posthog=e,e._i=[],e.init=function(i,s,a){ function g(t,e){ var o=e.split("."); 2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){ t.push([e].concat(Array.prototype.slice.call(arguments,0))) } } (p=t.createElement("script")).type="text/javascript",p.async=!0,p.src=s.api_host+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r); var u=e; void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){ var e="posthog"; return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e },u.people.toString=function(){ return u.toString(1)+".people (stub)" },o="capture identify alias people.set people.set_once set_config register register_once unregister opt_out_capturing has_opted_out_capturing opt_in_capturing reset isFeatureEnabled onFeatureFlags getFeatureFlag getFeatureFlagPayload reloadFeatureFlags group updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures getActiveMatchingSurveys getSurveys onSessionId".split(" "),n=0;n { updateTheme(theme) }); ```