### setup(api) Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/plugins.html 插件 setup 钩子,每次配置解析只执行一次。可使用 api.expose() / api.useExposed() 共享能力,并通过 pre / post 声明依赖顺序。 ```APIDOC ## setup(api) ### Description 插件 setup 钩子,每次配置解析只执行一次。 ### Method setup ### Parameters - **api** - Required - 插件 API 对象,提供 `expose` 和 `useExposed` 方法 ### 使用示例 ```javascript const key = Symbol.for('example.config') const provider = { name: 'example:provider', setup(api) { api.expose(key, { enabled: true }) }, } const consumer = { name: 'example:consumer', pre: ['example:provider'], setup(api) { const config = api.useExposed(key) }, } ``` ``` -------------------------------- ### Install and run Nasti commands Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Commands to install Nasti as a dev dependency, start the development server, and create a production build. Requires Node.js ^20.19.0 or >=22.12.0. ```bash # 安装 npm install -D @nasti-toolchain/nasti # 启动开发服务器 npx nasti dev # 生产构建 npx nasti build ``` -------------------------------- ### 插件 setup 与跨插件 API 示例 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/plugins.html 展示插件 setup 与跨插件 API 的使用,通过 api.expose() 和 api.useExposed() 共享能力,并用 pre 声明依赖顺序。 ```javascript const key = Symbol.for('example.config') const provider = { name: 'example:provider', setup(api) { api.expose(key, { enabled: true }) }, } const consumer = { name: 'example:consumer', pre: ['example:provider'], setup(api) { const config = api.useExposed(key) }, } ``` -------------------------------- ### Install monaco-editor Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Install the monaco-editor package as a dependency. ```bash npm install monaco-editor ``` -------------------------------- ### Electron main process example Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Example main process that creates a BrowserWindow. It uses ESM, so __dirname is derived from import.meta.url. In development, it loads the dev server URL from an environment variable; otherwise it loads the built renderer HTML. ```ts // src/electron/main.ts import { app, BrowserWindow } from 'electron' import path from 'node:path' import { fileURLToPath } from 'node:url' // ESM 没有隐式 __dirname;此处路径相对于最终输出文件。 const currentDir = path.dirname(fileURLToPath(import.meta.url)) async function createWindow() { const win = new BrowserWindow({ width: 1200, height: 800, webPreferences: { preload: path.join(currentDir, 'preload.cjs'), contextIsolation: true, sandbox: true, }, }) // 开发模式下 Nasti 会通过环境变量传入 dev server URL if (process.env.NASTI_DEV_SERVER_URL) { await win.loadURL(process.env.NASTI_DEV_SERVER_URL) } else { await win.loadFile(path.join(currentDir, 'renderer/index.html')) } } app.whenReady().then(createWindow) ``` -------------------------------- ### Build and Run WebGPU Playground Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Commands to build and run the playground-webgpu example using vgpu. ```sh pnpm build pnpm --filter playground-webgpu dev pnpm --filter playground-webgpu build ``` -------------------------------- ### Install React and Nasti dependencies Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/react.html Initializes a new project and installs React, React DOM, and the Nasti toolchain along with TypeScript type definitions. ```bash # 初始化项目 npm init -y npm install react react-dom npm install -D @nasti-toolchain/nasti @types/react @types/react-dom typescript ``` -------------------------------- ### Install vgpu Dependencies Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Install vgpu and @vgpu/wgsl in the consuming app workspace, not the monorepo root. ```sh pnpm --filter add vgpu pnpm --filter add -D @vgpu/wgsl @webgpu/types ``` -------------------------------- ### Configure environments in defineConfig Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/config.html Example showing how to define client and lynx environments within the Nasti configuration, including HTML entry points and external drivers. ```javascript export default defineConfig({ environments: { client: { html: 'src/renderer/index.html', }, lynx: { consumer: 'client', driver: 'rspeedy', }, }, }) ``` -------------------------------- ### Start Electron dev server with npx nasti electron Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/electron.html Starts the renderer dev server and spawns Electron. Use --no-spawn to only compile main/preload without launching Electron (CI scenario), and --no-restart to disable auto-restart on main/preload changes. ```bash # 启动渲染进程 dev server 并 spawn Electron npx nasti electron # 仅编译主/preload,不启动 Electron(CI 场景) npx nasti electron --no-spawn # 禁用主/preload 变更自动重启 npx nasti electron --no-restart ``` -------------------------------- ### Vapor Mode 单文件 opt-in 示例 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/vue.html 通过在 script setup 或 template 上添加 vapor 属性启用 Vapor Mode。 ```html ``` ```html ``` -------------------------------- ### Install Electron with npm Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Install Electron as a dev dependency. The version can be chosen as needed, with support for versions 41, 42, and 43+. ```bash npm install -D electron@^41 ``` -------------------------------- ### Install monaco-editor and @nasti-toolchain/nasti Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/monaco.html Install the monaco-editor package and the Nasti toolchain as a dev dependency. Required before using the monacoEditorPlugin. ```shell npm install monaco-editor npm install -D @nasti-toolchain/nasti ``` -------------------------------- ### Install Vue compiler-sfc optional dependency Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Required to enable Vue support in Nasti. Install as a dev dependency. ```bash npm install -D @vue/compiler-sfc ``` -------------------------------- ### ESM main process usage with import.meta.url Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/electron.html Shows how to use import.meta.url to get the current directory in an ESM main process, since __dirname is not available. Also demonstrates top-level await for initialization before app.ready. Avoid top-level await app.whenReady(); use app.whenReady().then(createWindow) instead. ```javascript import path from 'node:path' import { fileURLToPath } from 'node:url' // 相对于最终输出文件;ESM 没有隐式 __dirname const currentDir = path.dirname(fileURLToPath(import.meta.url)) const preload = path.join(currentDir, 'preload.cjs') // app.ready 前必须完成的初始化要显式 await await import('./setup.mjs') ``` -------------------------------- ### Use pack API from electron-packager Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Example of using the 'pack' function from the experimental electron-packager package. It takes an input directory and output ASAR path, with an optional unpack list. ```js // 在已链接该 workspace package 的构建工具中使用 import { pack } from '@nasti-toolchain/electron-packager' await pack({ input: '/absolute/staged-app', // 已包含 package.json、main 和运行时依赖 output: '/absolute/release/app.asar', // 父目录须存在;不覆盖已有输出 unpack: ['node_modules/native-addon'], }) ``` -------------------------------- ### Development commands for Electron Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Start the renderer dev server and Electron, with auto-restart on main/preload changes. Use --no-spawn to compile once and exit, suitable for CI. ```bash # 同时启动渲染进程 dev server + Electron,主/preload 变更自动重启 nasti electron ``` ```bash # 一次性编译主/preload 后关闭服务器并退出(适合 CI) nasti electron --no-spawn ``` -------------------------------- ### Build native bindings for electron-packager Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Explicitly build the native bindings and optional CLI for the experimental Rust-based electron-packager. This is not done automatically during dependency installation. ```bash pnpm --filter @nasti-toolchain/electron-packager build ``` -------------------------------- ### Configure monacoEditorPlugin in nasti.config.ts Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Example configuration for the monacoEditorPlugin, showing languageWorkers, customWorkers, publicPath, and globalAPI options. ```typescript // nasti.config.ts import { defineConfig, monacoEditorPlugin } from '@nasti-toolchain/nasti' export default defineConfig({ plugins: [ monacoEditorPlugin({ // 默认全部启用:editorWorkerService / css / html / json / typescript languageWorkers: ['editorWorkerService', 'json', 'typescript'], // 自定义 Worker(如 monaco-graphql) customWorkers: [ { label: 'graphql', entry: 'monaco-graphql/esm/graphql.worker' }, ], // Worker URL 前缀,可指向 CDN 绝对 URL publicPath: 'monacoeditorwork', // 兼容旧 API:将 monaco 暴露到 window.monaco globalAPI: false, }), ], }) ``` -------------------------------- ### rolldownOptions configuration for tree-shaking and manual code splitting Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/config.html Set build.rolldownOptions to combine input-side options (treeshake, resolve, external) with output-side options (advancedChunks, chunkFileNames). Nasti takes over input and plugins, and output.dir is always set by build.outDir. The example marks modules under /barrel/ as having no side effects and groups node_modules dependencies into vendor chunks, with dynamic import inlining possible only for a single chunk output. ```javascript export default defineConfig({ build: { rolldownOptions: { // Tree-shaking(input 选项) treeshake: { moduleSideEffects: [{ test: /\/barrel\//, sideEffects: false }], }, // 代码拆分(output 选项) output: { advancedChunks: { groups: [ { name: 'react-vendor', test: /node_modules[\\/]react/, priority: 20 }, { name: 'vendor', test: /node_modules/, priority: 10 }, ], }, chunkFileNames: 'assets/chunks/[name].[hash].js', }, }, }, }) ``` -------------------------------- ### Configure Rspeedy as external environment driver Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Use this configuration to let Rspeedy take over the 'lynx' environment while keeping Nasti's CLI, logging, and multi-environment orchestration. The bridge plugin is provided via pluginRspeedyBridge() and offers build, serve, watchChange, close, setup(api), api.expose/useExposed, and afterBuildApp(results, api, context). ```TypeScript export default defineConfig({ environments: { lynx: { consumer: 'client', driver: 'rspeedy', }, }, plugins: [pluginRspeedyBridge()], }) ``` -------------------------------- ### startElectronDev Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/electron.html 启动开发模式,监听主进程和 preload 变更并自动重启。 ```APIDOC ## startElectronDev ### Description 启动开发模式,监听主进程和 preload 变更并自动重启。 ### Method startElectronDev ### Endpoint startElectronDev(options) ### Parameters #### Options - **root** (string) - Required - 项目根目录路径。 ### Request Example ```js await startElectronDev({ root: '.' }) ``` ### Response #### Success Response - 无返回值(Promise) ``` -------------------------------- ### buildStart / buildEnd Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/plugins.html 构建生命周期钩子。 ```APIDOC ## buildStart / buildEnd ### Description 构建生命周期钩子。 ### Method buildStart, buildEnd ### Parameters - **buildStart()** - 无参数 - **buildEnd(error?: Error)** - `error` (Error) - Optional - 构建失败时的错误对象 ### Returns - **void** ``` -------------------------------- ### Electron main process (src/electron/main.ts) Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/electron.html Creates a BrowserWindow with preload, contextIsolation, and sandbox enabled. Loads the dev server URL from NASTI_DEV_SERVER_URL in development, otherwise loads the built renderer index.html. ```typescript // src/electron/main.ts import { app, BrowserWindow } from 'electron' import path from 'node:path' async function createWindow() { const win = new BrowserWindow({ width: 1200, height: 800, webPreferences: { preload: path.resolve(__dirname, 'preload.cjs'), contextIsolation: true, sandbox: true, }, }) // Nasti 在 dev 模式下会将渲染进程 URL 注入 NASTI_DEV_SERVER_URL if (process.env.NASTI_DEV_SERVER_URL) { await win.loadURL(process.env.NASTI_DEV_SERVER_URL) } else { await win.loadFile(path.resolve(__dirname, 'renderer/index.html')) } } app.whenReady().then(createWindow) ``` -------------------------------- ### 启动开发服务器、构建和预览 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/getting-started.html 三个 CLI 命令:启动开发服务器(npx nasti dev)、生产构建(npx nasti build)和预览构建产物(npx nasti preview)。 ```bash # 启动开发服务器 npx nasti dev # 生产构建 npx nasti build # 预览构建产物 npx nasti preview ``` -------------------------------- ### Build and pack with CLI (shell) Source: https://github.com/zixiao-labs/nasti/blob/main/packages/electron-packager/README.md Build the package with pnpm and run the optional CLI to pack a staged app into an ASAR. The CLI supports repeated --unpack flags for exact relative paths or directories. ```shell # 仓库根,推荐使用与主工程一致的 Node 24 开发环境: pnpm install --frozen-lockfile pnpm --filter @nasti-toolchain/electron-packager build cd packages/electron-packager # 或单独 npm run build:binding / npm run build:cli # 可选 CLI:普通 cargo build/test 不开启 binding、不需要 Node 动态符号 cargo build --release --locked ./target/release/nasti-electron-packager pack /absolute/staged-app /absolute/output/app.asar \ --unpack node_modules/native-addon \ --unpack assets/helper # 仅诊断 CLI wrapper 调用已构建 binary: npm run pack -- /absolute/staged-app /absolute/output/app.asar --unpack assets/helper ``` -------------------------------- ### nasti electron-build 命令语法 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/cli.html Electron 生产构建命令语法,等价于 nasti build --target electron。 ```bash nasti electron-build [root] [options] # 产物: # dist/renderer/ Web 渲染层 # dist/main.cjs 主进程 # dist/preload.cjs Preload ``` -------------------------------- ### Force Vapor Mode at environment level Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Enable Vapor Mode for all ``` -------------------------------- ### Use transformRequest and ssrLoadModule in server-consumer dev Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Shows how to transform and load SSR modules without starting an HTTP listener. transformEnvironmentRequest is equivalent to environments.ssr.transformRequest. The returned code is runner-ready with __vite_ssr_* helpers, not browser ESM; externalized modules return null. ```TypeScript const server = await createServer({ /* Nasti config */ }) const transformed = await server.transformEnvironmentRequest('ssr', '/src/server.ts') // 等价入口:server.environments.ssr.transformRequest('/src/server.ts') const exports = await server.ssrLoadModule('/src/server.ts') const graph = server.environments.ssr.moduleGraph const entry = graph.getModuleByUrl('/src/server.ts') // entry.importedModules / dependency.importers 是真实的双向依赖关系 await server.close() ``` -------------------------------- ### buildElectron Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/electron.html 执行生产构建,编译 Electron 主进程、preload 和渲染进程代码。 ```APIDOC ## buildElectron ### Description 执行生产构建,编译 Electron 主进程、preload 和渲染进程代码。 ### Method buildElectron ### Endpoint buildElectron(options) ### Parameters #### Options - **root** (string) - Required - 项目根目录路径。 ### Request Example ```js await buildElectron({ root: '.' }) ``` ### Response #### Success Response - 无返回值(Promise) ``` -------------------------------- ### Package.json for electron-builder Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Configuration for packaging with electron-builder. The main entry points to the built output, and the build script runs the Nasti build followed by electron-builder. ```json { "main": "dist/main.mjs", "scripts": { "build": "nasti electron-build && electron-builder" }, "build": { "files": ["dist/**"], "directories": { "output": "release" } } } ``` -------------------------------- ### 与 electron-builder 配合的 package.json 配置 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/electron.html 展示如何配置 package.json 以使用 electron-builder 打包,包括 main 入口指向 dist/main.mjs 和构建脚本。 ```json // package.json { "main": "dist/main.mjs", "scripts": { "build": "nasti electron-build && electron-builder" }, "build": { "files": ["dist/**"], "directories": { "buildResources": "build", "output": "release" } } } ``` -------------------------------- ### Build Electron production with npx nasti electron-build Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/electron.html Builds the Electron app for production. Equivalent to `npx nasti build --target electron`. The output layout places renderer files in dist/renderer, main process in main.cjs (or main.mjs if mainFormat=esm), and preload in preload.cjs (or preload.mjs if preloadFormat=esm). ```bash npx nasti electron-build # 等价于: npx nasti build --target electron ``` -------------------------------- ### Enable ESM main process with mainFormat: 'esm' Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/electron.html Configures Nasti to use ESM for the main process while keeping preload as CJS for sandbox compatibility. Requires Electron 28 or higher; Nasti errors if Electron is below 28 and ESM is configured. ESM preload must be .mjs and require sandbox: false, and dynamic Node imports require contextIsolation: true. ```javascript export default defineConfig({ target: 'electron', electron: { mainFormat: 'esm', preloadFormat: 'cjs', // preload 保持 cjs 以兼容 sandbox }, }) ``` -------------------------------- ### Import WGSL Shader as String Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Imports a .wgsl file as a raw string and creates a shader module after obtaining a GPUDevice. ```ts import code from './compute.wgsl' // 在取得 GPUDevice 后: const shader = device.createShaderModule({ code }) ``` -------------------------------- ### Nasti CLI Commands Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Lists all Nasti CLI commands: dev, build, preview, electron, and electron-build, with their options and flags. ```bash # 开发服务器 nasti dev [root] [--port 3000] [--host] [--open] # 生产构建(Web / Electron) nasti build [root] [--outDir dist] [--sourcemap] [--minify | --no-minify] [--keep-names] [--mangle-props ] [--target web|electron] # 预览构建产物 nasti preview [root] [--port 4173] # Electron 开发模式(需预装 electron ^41) nasti electron [root] [--port 3000] [--no-spawn] [--no-restart] # Electron 生产构建(等价于 nasti build --target electron) nasti electron-build [root] [--outDir dist] [--minify | --no-minify] ``` -------------------------------- ### nasti build 使用示例 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/cli.html 展示了基本构建、生成 source map 以及自定义输出目录的用法。 ```bash # 基本构建 nasti build # 带 source map nasti build --sourcemap # 自定义输出目录 nasti build --outDir output ``` -------------------------------- ### 配置 bundledDev 实验选项 Source: https://github.com/zixiao-labs/nasti/blob/main/NASTI_2.0_PLAN.md TypeScript 配置接口定义,用于启用 bundledDev 实验性选项。它默认为 false,并在 serve 命令时通过 isBundledDev 控制打包还是非打包路径。 ```typescript interface NastiConfig { experimental?: ExperimentalOptions } interface ExperimentalOptions { /** dev 用 Rolldown dev() 引擎整体打包 client 环境后从内存服务。@experimental @default false */ bundledDev?: boolean } // config/defaults.ts: experimental:{ bundledDev:false } // resolveConfig: isBundledDev = command==='serve' && !!experimental.bundledDev // server/index.ts: if(experimental.bundledDev) else <现有 unbundled> ``` -------------------------------- ### 编程式 API 使用示例 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/electron.html 使用 @nasti-toolchain/nasti 的 buildElectron 和 startElectronDev 函数进行生产构建和开发模式启动。 ```javascript import { buildElectron, startElectronDev } from '@nasti-toolchain/nasti' // 生产构建 await buildElectron({ root: '.' }) // 开发模式 await startElectronDev({ root: '.' }) ``` -------------------------------- ### Electron 项目结构 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/electron.html 展示 Nasti Electron 项目的目录结构,包含渲染进程入口、主进程和 preload 脚本。 ```text my-electron-app/ ├── index.html # 渲染进程入口 ├── src/ │ ├── main.tsx # 渲染进程 JS │ ├── App.tsx │ └── electron/ │ ├── main.ts # 主进程入口 │ └── preload.ts # Preload 脚本 └── nasti.config.ts ``` -------------------------------- ### buildStart / buildEnd 钩子签名 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/plugins.html 构建生命周期钩子。 ```typescript buildStart(): void buildEnd(error?: Error): void ``` -------------------------------- ### Production build output structure Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Shows the directory structure after a production build. The renderer is in 'dist/renderer', and the main and preload outputs are 'main.mjs' and 'preload.cjs' respectively, unless configured otherwise. ```text dist/ ├── renderer/ # Web 渲染层 ├── main.mjs # 上述 ESM 配置;默认 CJS 配置输出 main.cjs └── preload.cjs # Preload 脚本 ``` -------------------------------- ### Native WebGPU Config with webgpuPlugin Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Configuration for native WebGPU using the webgpuPlugin from @nasti-toolchain/nasti. Do not enable both shader plugins simultaneously. ```ts // nasti.config.ts import { defineConfig, webgpuPlugin } from '@nasti-toolchain/nasti' export default defineConfig({ plugins: [webgpuPlugin()], }) ``` -------------------------------- ### vgpu Config with wgslVitePlugin Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Configuration for vgpu using wgslVitePlugin from @vgpu/wgsl/loader-vite. ```ts // nasti.config.ts import { defineConfig } from '@nasti-toolchain/nasti' import { wgslVitePlugin } from '@vgpu/wgsl/loader-vite' export default defineConfig({ plugins: [wgslVitePlugin()], }) ``` -------------------------------- ### 安装 Electron 依赖 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/electron.html 使用 npm 安装 Nasti 工具链和 Electron 41 及以上版本。开发时会检测已安装版本,低于 minVersion 将提示警告。 ```bash npm install -D @nasti-toolchain/nasti electron@^41 ``` -------------------------------- ### nasti build 命令语法 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/cli.html 生产构建命令语法,输出到 dist/ 目录。 ```bash nasti build [root] [options] ``` -------------------------------- ### Basic Nasti Configuration (nasti.config.ts) Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Base configuration for a Nasti project. Sets framework to 'react', server port 3000 with host and open enabled, build output to 'dist' with sourcemaps and minification, and an alias '@' pointing to '/src'. The plugins array is for Vite plugins. ```TypeScript // nasti.config.ts import { defineConfig } from '@nasti-toolchain/nasti' export default defineConfig({ // 框架: 'react' | 'vue' | 'auto'(自动检测) framework: 'react', server: { port: 3000, host: true, // 监听所有地址 open: true, // 自动打开浏览器 }, build: { outDir: 'dist', sourcemap: true, minify: true, }, resolve: { alias: { '@': '/src', }, }, // 直接使用 Vite 插件 plugins: [], }) ``` -------------------------------- ### 安装 Vue SFC 编译器依赖 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/vue.html 安装 Vue 3 单文件组件编译器作为可选依赖。 ```bash npm install vue npm install -D @vue/compiler-sfc ``` -------------------------------- ### Electron Vue project structure Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/electron.html Shows the recommended directory layout for an Electron app with a Vue renderer, including renderer and electron folders and the nasti.config.ts file. ```text my-electron-vue-app/ ├── src/ │ ├── renderer/ │ │ ├── index.html │ │ ├── main.ts │ │ └── App.vue │ └── electron/ │ ├── main.ts │ └── preload.ts └── nasti.config.ts ``` -------------------------------- ### 运行 Electron smoke 测试 Source: https://github.com/zixiao-labs/nasti/blob/main/packages/electron-packager/README.md 从仓库根运行,需可用的桌面环境(Linux CI 需自行配置显示服务)。 ```sh # 从仓库根运行,需可用的桌面环境(Linux CI 需自行配置显示服务): pnpm build pnpm --filter @nasti-toolchain/electron-packager build npx -y --package=electron@44.7.0 -c 'node scripts/electron-smoke.mjs "$(command -v electron)" --napi' ``` -------------------------------- ### createEnvironmentDriver(environment) Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/plugins.html 创建环境驱动的钩子,用于将外部工具链(如 Rspeedy)接入 Nasti 环境。 ```APIDOC ## createEnvironmentDriver(environment) ### Description 创建环境驱动钩子,用于将外部工具链(如 Rspeedy)接入 Nasti 环境。需要返回一个驱动对象,包含 `build`、`serve`、`watchChange`、`close` 方法。 ### 方法 createEnvironmentDriver ### 参数 - **environment** (Environment) - Required - 环境对象,包含 `options`,可检查 `environment.options.driver` 值。 ### 返回 - **驱动对象** - 包含以下方法: - **build({ config })** - Async - 执行构建,返回 `{ output: [] }` - **serve({ config })** - Async - 启动开发服务器,返回 `{ localUrls: [] }` - **watchChange(file, event)** - 监听文件变化 - **close()** - Async - 关闭驱动 - **undefined** - 如果不需要处理该环境则可以返回 undefined ### 示例 ```javascript const pluginRspeedyBridge = () => ({ name: 'nasti:rspeedy', async createEnvironmentDriver(environment) { if (environment.options.driver !== 'rspeedy') return const { createRspeedy } = await import('@lynx-js/rspeedy') let instance return { name: 'rspeedy', async build({ config }) { instance = await createRspeedy({ cwd: config.root }) // 调用 Rspeedy build,并把产物归一为 EnvironmentBuildResult return { output: [] } }, async serve({ config }) { // 启动 Rspeedy dev server,返回 localUrls / networkUrls return { localUrls: [] } }, watchChange(file, event) {}, async close() {}, } }, afterBuildApp(results, api, context) { // 通过 context 跨环境读取 entries / manifest / stats 并聚合产物 }, }) ``` ``` -------------------------------- ### config(config, env) Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/plugins.html 在配置解析前修改配置。 ```APIDOC ## config(config, env) ### Description 在配置解析前修改配置。 ### Method config ### Parameters - **config** (NastiConfig) - Required - 当前配置 - **env.mode** (string) - Required - 模式,如 'development' | 'production' - **env.command** (string) - Required - 命令,如 'build' | 'serve' ### Returns - **NastiConfig** - 修改后的配置 - **null** - 不修改 ``` -------------------------------- ### pack(options) Source: https://github.com/zixiao-labs/nasti/blob/main/packages/electron-packager/README.md Archives a staged Electron app directory into an ASAR file. Returns a Promise that resolves when the archive is complete or rejects on failure. ```APIDOC ## pack(options) ### Description Archives a staged Electron app directory into an ASAR file. Returns a Promise that resolves when the archive is complete or rejects on failure. ### Method N/A (Node API) ### Endpoint N/A (Node API) ### Parameters #### Options Object - **input** (string) - Required - Absolute path to the staged app directory. - **output** (string) - Required - Absolute path to the output ASAR file (e.g., `/absolute/output/app.asar`). - **unpack** (string[]) - Optional - Array of exact relative file or directory paths within the input that should be unpacked. Each entry must exist in the input. Directory matches itself and all descendants under `directory/`. No glob semantics; `*` is not a wildcard. Must use `/` separators; absolute paths, `..`, `.`, empty segments, and backslashes are not accepted. ### Request Example ```js import { pack } from '@nasti-toolchain/electron-packager'; await pack({ input: '/absolute/staged-app', output: '/absolute/output/app.asar', unpack: ['node_modules/native-addon', 'assets/helper'], }); ``` ### Response #### Success Response - Resolves with `void` when the archive is successfully created. #### Error Handling - Rejects with an error if binding is missing or cannot be loaded (import error suggests `npm run build:binding`). - Rejects with an error if argument conversion, scanning, I/O, or other operations fail. - Output parent directory must already exist. - `app.asar` and `app.asar.unpacked` must not already exist; existing files are not overwritten. ``` -------------------------------- ### configureServer(server) Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/plugins.html 自定义开发服务器。返回函数会在内部中间件之后执行。 ```APIDOC ## configureServer(server) ### Description 自定义开发服务器。返回函数会在内部中间件之后执行。 ### Method configureServer ### Parameters - **server** (DevServer) - Required - 开发服务器实例 ### Returns - **void** - **() => void** - 可选,稍后执行的函数 ``` -------------------------------- ### React entry file and App component Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/react.html Entry point and main component for a React app with Nasti. The main.tsx file mounts the App component, and App.tsx demonstrates a counter with state. ```typescript // src/main.tsx import { createRoot } from 'react-dom/client' import App from './App' createRoot(document.getElementById('root')!).render() ``` ```typescript // src/App.tsx import { useState } from 'react' export default function App() { const [count, setCount] = useState(0) return (

Nasti + React

) } ``` -------------------------------- ### 创建项目结构 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/getting-started.html 项目结构示例,与 Vite 一致,包含入口 HTML、源码目录、静态资源和可选配置文件。 ```text my-project/ ├── index.html # 入口 HTML ├── src/ │ ├── main.tsx # JS 入口 │ └── App.tsx ├── public/ # 静态资源 └── nasti.config.ts # 配置文件(可选) ``` -------------------------------- ### Vue 组件示例 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/vue.html 包含 script setup、template 和 scoped style 的单文件组件。 ```html ``` -------------------------------- ### 完整配置示例 (nasti.config.ts) Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/config.html 使用 defineConfig 函数定义 Nasti 配置,包含 resolve、server、build 等选项。该示例展示了所有常用配置项,可作为配置文件的起点。 ```typescript import { defineConfig } from '@nasti-toolchain/nasti' export default defineConfig({ root: '.', base: '/', mode: 'development', framework: 'react', logLevel: 'info', envPrefix: ['NASTI_', 'VITE_'], resolve: { alias: { '@': '/src' }, extensions: ['.ts', '.tsx', '.js', '.jsx'], }, server: { port: 3000, host: true, open: true, cors: true, hmr: true, }, build: { outDir: 'dist', assetsDir: 'assets', sourcemap: true, minify: true, emptyOutDir: true, target: 'es2022', }, plugins: [], }) ``` -------------------------------- ### Configure Nasti with nasti.config.ts Source: https://github.com/zixiao-labs/nasti/blob/main/website/index.html Define your project configuration using the defineConfig helper in nasti.config.ts. ```typescript // nasti.config.ts import { defineConfig } from '@nasti-toolchain/nasti' export default defineConfig({ framework: 'react', server: { port: 3000 }, build: { outDir: 'dist' }, }) ``` -------------------------------- ### nasti preview 命令语法 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/cli.html 本地预览生产构建产物的命令语法。 ```bash nasti preview [root] [options] ``` -------------------------------- ### Nasti Config 接口和 EnvironmentOptions(types.ts) Source: https://github.com/zixiao-labs/nasti/blob/main/NASTI_2.0_PLAN.md Nasti 的配置接口,定义了 environments 映射到 EnvironmentOptions(含 consumer、resolve、build)。默认环境为 client 和 ssr。ResolvedConfig 中的 environments 类型为 Record。 ```typescript interface NastiConfig { environments?: Record // 默认 { client, ssr } // ... } interface EnvironmentOptions { consumer?: 'client' | 'server' resolve?: ResolveConfig build?: BuildConfig } // ResolvedConfig.environments: Record ``` -------------------------------- ### 创建配置文件 nasti.config.ts Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/getting-started.html 创建可选的配置文件,配置框架、服务器、解析别名等。注意 Nasti 会自动检测框架类型,如依赖 react 或 vue 则自动启用对应插件。 ```typescript import { defineConfig } from '@nasti-toolchain/nasti' export default defineConfig({ framework: 'react', server: { port: 3000, host: true, }, resolve: { alias: { '@': '/src', }, }, }) ``` -------------------------------- ### 定义 NastiEnvironment 类(src/core/environment.ts) Source: https://github.com/zixiao-labs/nasti/blob/main/NASTI_2.0_PLAN.md Nasti 的单图环境类,收敛了 Vite 的多环境分层。定义了每个 environment 的核心属性,如 name、consumer、config、plugins、pluginContainer、moduleGraph 和 hot,其中 hot 在 client 使用 WebSocket,其余为 noop/in-memory。init 方法用于创建 pluginContainer。 ```typescript // src/core/environment.ts(新增) class NastiEnvironment { name: string consumer: 'client' | 'server' mode: 'dev' | 'build' config: ResolvedConfig // env 选项 over top-level(保持 client 镜像) plugins: NastiPlugin[] // applyToEnvironment 过滤后 pluginContainer: PluginContainer // 带 environment 构造 moduleGraph: ModuleGraph // per-env hot: HotChannel // client=ws;其余=noop/in-memory async init() { /* 建 pluginContainer */ } } ``` -------------------------------- ### Node API pack() usage (JavaScript) Source: https://github.com/zixiao-labs/nasti/blob/main/packages/electron-packager/README.md Use the default ESM entry to pack a staged app directory into an ASAR. The unpack option is optional and must contain exact relative paths or directories. ```javascript import { pack } from '@nasti-toolchain/electron-packager'; await pack({ input: '/absolute/staged-app', output: '/absolute/output/app.asar', unpack: ['node_modules/native-addon', 'assets/helper'], // 可省略 }); ``` -------------------------------- ### CLI: nasti-electron-packager pack Source: https://github.com/zixiao-labs/nasti/blob/main/packages/electron-packager/README.md Command-line interface to archive a staged app directory into an ASAR file. Accepts input and output paths and optional unpack patterns. ```APIDOC ## CLI: nasti-electron-packager pack ### Description Command-line interface to archive a staged app directory into an ASAR file. Accepts input and output paths and optional unpack patterns. ### Method N/A (CLI command) ### Endpoint N/A (CLI command) ### Parameters #### Positional Arguments - **input** (string) - Required - Absolute path to the staged app directory. - **output** (string) - Required - Absolute path to the output ASAR file (e.g., `/absolute/output/app.asar`). #### Options - **--unpack** (string) - Optional - Can be repeated. Each value must be an exact relative file or directory path within the input. Directory matches itself and all descendants under `directory/`. No glob semantics; `*` is not a wildcard. Must use `/` separators; absolute paths, `..`, `.`, empty segments, and backslashes are not accepted. ### Request Example ```sh ./target/release/nasti-electron-packager pack /absolute/staged-app /absolute/output/app.asar \ --unpack node_modules/native-addon \ --unpack assets/helper ``` ### Response #### Success Response - Exits with code 0 on success. #### Error Handling - Exits with non-zero code and prints error message on failure. - Output parent directory must already exist. - `app.asar` and `app.asar.unpacked` must not already exist; existing files are not overwritten. ``` -------------------------------- ### 运行验证命令 Source: https://github.com/zixiao-labs/nasti/blob/main/packages/electron-packager/README.md 安装 devDependencies 后运行这些命令以进行格式化、测试、clippy 检查和构建。 ```sh cargo fmt --check cargo test cargo clippy -- -D warnings cargo clippy --features binding -- -D warnings npm run build npm test npm run benchmark ``` -------------------------------- ### Electron production build output layout Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/electron.html Shows the directory structure produced by the Electron build. The renderer folder contains the web layer, while main.cjs and preload.cjs are the main and preload scripts, with .mjs variants when ESM formats are configured. ```text dist/ ├── renderer/ # Web 渲染层(同 nasti build) │ ├── index.html │ └── assets/ ├── main.cjs # 主进程(mainFormat=esm 时为 main.mjs) └── preload.cjs # Preload(preloadFormat=esm 时为 preload.mjs) ``` -------------------------------- ### Create Monaco Editor instance Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Application code to create a Monaco Editor instance with TypeScript language and dark theme. ```typescript import * as monaco from 'monaco-editor' monaco.editor.create(document.getElementById('editor')!, { value: 'function hi() { console.log("hello monaco") }', language: 'typescript', theme: 'vs-dark', automaticLayout: true, }) ``` -------------------------------- ### configResolved(config) Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/plugins.html 读取最终配置。 ```APIDOC ## configResolved(config) ### Description 读取最终配置。 ### Method configResolved ### Parameters - **config** (ResolvedConfig) - Required - 最终解析后的配置 ### Returns - **void** ``` -------------------------------- ### 安装 Vapor Mode 依赖 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/vue.html Vapor Mode 需要 Vue 3.6 或更高版本。 ```bash npm install vue@^3.6.0-0 npm install -D @vue/compiler-sfc@^3.6.0-0 ``` -------------------------------- ### Electron 配置示例 Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/electron.html nasti.config.ts 中配置 target 为 'electron',指定主进程、preload、renderer 入口,以及 mainFormat、preloadFormat、nodeTarget、autoRestart、minVersion、external 等选项。 ```typescript // nasti.config.ts import { defineConfig } from '@nasti-toolchain/nasti' export default defineConfig({ target: 'electron', framework: 'auto', // 自动识别 React / Vue electron: { main: 'src/electron/main.ts', preload: 'src/electron/preload.ts', renderer: 'src/renderer/index.html', mainFormat: 'esm', // 输出 main.mjs;未配置时仍默认 cjs preloadFormat: 'cjs', nodeTarget: 'node22', autoRestart: true, minVersion: 41, external: ['electron'], }, }) ``` -------------------------------- ### Vue renderer entry with standard SFC Source: https://github.com/zixiao-labs/nasti/blob/main/README.md Standard Vue renderer entry that creates the app and mounts it. The renderer uses standard SFCs. ```ts // src/renderer/main.ts import { createApp } from 'vue' import App from './App.vue' createApp(App).mount('#app') ``` -------------------------------- ### 安装 Nasti Source: https://github.com/zixiao-labs/nasti/blob/main/website/pages/getting-started.html 使用 npm 安装 Nasti 开发依赖。 ```bash npm install -D @nasti-toolchain/nasti ```