=============== LIBRARY RULES =============== From library maintainers: - skip packages marked as `"private": true` - need most detailed document for "@idlebox/common" and "@idlebox/node" ### Example HTML Structure for esbuild Plugin (HTML) Source: https://github.com/gongt/baobao/blob/master/@build-script/esbuild-html-entry/README.md This is an example of an HTML file that can be used as an entry point with the esbuild HTML Entry Plugin. The plugin will process the first encountered script and link tags. Note that only the first of multiple tags of the same type will be considered. ```html Test App

This is a test

``` -------------------------------- ### Build Event Protocol - Start Event JSON Source: https://github.com/gongt/baobao/blob/master/@mpis/shared/README.md This JSON structure represents a 'start' event for a build process. It includes a brand identifier, the event type, a title for the build command, and the process ID. This format helps in tracking the lifecycle of individual build tasks. ```json { "__brand__": "BPCM", "event": "start", // success failed "title": "some-build-command", "pid": process.pid // "output": "" } ``` -------------------------------- ### Install source-map-support (TypeScript) Source: https://github.com/gongt/baobao/blob/master/@idlebox/source-map-support/README.md Demonstrates how to import and install the source-map-support package in TypeScript. This is the primary method for enabling source map support in Node.js applications. ```typescript import { install } from '@idlebox/source-map-support'; install(); ``` ```typescript import '@idlebox/source-map-support/register'; ``` -------------------------------- ### Monitor Build Events from Standard Input using CLI Source: https://github.com/gongt/baobao/blob/master/@mpis/client/README.md A command-line interface tool that reads from standard input to detect build start, success, or failure events. It uses regular expressions to match specific lines or patterns in the input stream. Requires either --success or --error flags to be set. ```bash tsc -p . -w | \ build-protocol-client --stdin \ --success "Found 0 errors" \ --finish "Watching for file changes\." \ --start "Starting (incremental)? compilation" ``` -------------------------------- ### Node.js System Utilities with @idlebox/node Source: https://context7.com/gongt/baobao/llms.txt Provides examples for common Node.js tasks including recursive file searching, process lifecycle management, and filesystem operations. ```typescript import { findUpUntil, findUp, findUpUntilSync, shutdown, setExitCodeIfNot, registerNodejsExitHandler, exists, ensureDir, emptyDir } from '@idlebox/node'; const packageJson = await findUpUntil({ from: process.cwd(), file: 'package.json' }); for await (const file of findUp({ from: __dirname, file: 'package.json' })) { console.log('找到:', file); } registerNodejsExitHandler(); shutdown(0); await ensureDir('./dist/output'); await emptyDir('./dist'); ``` -------------------------------- ### Advanced File Watching with @idlebox/chokidar Source: https://context7.com/gongt/baobao/llms.txt This snippet demonstrates how to use the @idlebox/chokidar package for advanced file watching. It covers starting the watcher with options like debouncing and event filtering, adding and removing files, checking watcher status, and dynamically listening to or unlistening from events. The watcher must be disposed of to clean up resources. ```typescript import { startChokidar, WatchHelper, type IExtraOptions } from '@idlebox/chokidar'; // 快速启动监控 const watcher = startChokidar( (changedFiles) => { console.log('文件变化:', changedFiles); // 执行重建逻辑 }, { debounceMs: 500, // 防抖延迟 watchingEvents: ['add', 'change', 'unlink'], // 监听的事件 ignoreInitial: true, // 忽略初始扫描 cwd: './src' // 工作目录 } ); // 添加监控文件 watcher.add('./src/**/*.ts'); watcher.add(['./config.json', './tsconfig.json']); // 移除监控 watcher.delete('./src/temp.ts'); // 重置所有监控 watcher.reset(); // 获取监控状态 console.log('监控文件数:', watcher.size); console.log('是否为空:', watcher.empty); console.log('监控列表:', watcher.watches); // 动态监听/取消监听事件 watcher.listen('addDir'); // 开始监听目录添加 watcher.unlisten('unlink'); // 停止监听文件删除 // 清理资源 await watcher.dispose(); ``` -------------------------------- ### Build Event Protocol with @mpis/shared Source: https://context7.com/gongt/baobao/llms.txt This example illustrates the use of the @mpis/shared package for defining a message protocol for build systems. It shows how to import `BuildEvent` types, create messages using `make_message`, and check message validity with `is_message` for inter-process communication and state synchronization. ```typescript import { BuildEvent, make_message, is_message, type IMessageObject } from '@mpis/shared'; // 构建事件类型 BuildEvent.Start // 构建开始 BuildEvent.Success // 构建成功 BuildEvent.Failed // 构建失败 // 创建消息 const startMsg = make_message({ event: BuildEvent.Start, title: 'TypeScript 编译', pid: process.pid, message: '开始编译...' }); const successMsg = make_message({ event: BuildEvent.Success, title: 'TypeScript 编译', pid: process.pid, message: '编译完成', output: '编译输出内容...' }); const failedMsg = make_message({ event: BuildEvent.Failed, title: 'TypeScript 编译', pid: process.pid, message: '编译失败', error: 'TypeError', output: '错误详情...' }); // 检查是否为有效消息 if (is_message(data)) { console.log(data.event, data.message); } ``` -------------------------------- ### Browser-Specific Fetch with Retry using @idlebox/browser Source: https://context7.com/gongt/baobao/llms.txt This example demonstrates the `retryFetch` function from the @idlebox/browser package, which enhances the standard fetch API by adding automatic retries with configurable delays and timeouts. It also shows how to integrate with `AbortController` for request cancellation. ```typescript import { retryFetch } from '@idlebox/browser'; // 带重试的 fetch 请求 const response = await retryFetch('https://api.example.com/data', { retries: 3, // 重试次数 delay: 800, // 重试间隔(毫秒) timeout: 3500, // 每次请求超时 method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'value' }) }); const data = await response.json(); // 支持 AbortController 取消 const controller = new AbortController(); setTimeout(() => controller.abort(), 10000); const result = await retryFetch('https://api.example.com/slow', { signal: controller.signal, retries: 5, timeout: 2000 }); ``` -------------------------------- ### TRPC Socket.IO Server Setup Source: https://github.com/gongt/baobao/blob/master/@gongt/trpc-lib/README.md Server-side implementation for integrating TRPC with Socket.IO. It sets up a Socket.IO server and uses createSocketIoMiddleware to handle TRPC requests. ```typescript import { createSocketIoMiddleware } from '@gongt/trpc-lib/server'; import { initTRPC } from '@trpc/server'; const io = new SocketIO.Server({ path: '/socket.io/', addTrailingSlash: true, transports: ['websocket', 'polling'], }); export const trpc = initTRPC.context().create({}); export const appRouter = trpc.router(...); io.of('/trpc').use( createSocketIoMiddleware({ router: appRouter, }), ); ``` -------------------------------- ### Execute Command and Monitor Build Events via CLI Source: https://github.com/gongt/baobao/blob/master/@mpis/client/README.md Executes a specified command and simultaneously monitors its standard output and standard error for build events. Similar to the stdin mode, it uses flags like --start, --finish, --success, and --error to define event triggers. The command and its arguments must follow the '--' separator. ```bash build-protocol-client [--start <开始>] --finish <完成> [--success <成功>] [--error <错误>] -- <命令> [<参数>...] ``` -------------------------------- ### TRPC Socket.IO Client Setup Source: https://github.com/gongt/baobao/blob/master/@gongt/trpc-lib/README.md Client-side implementation for establishing a TRPC connection over Socket.IO. It utilizes SocketIoLink to connect to a TRPC server endpoint. ```typescript import { createTRPCClient } from '@trpc/client'; import { SocketIoLink } from '@gongt/trpc-lib/client'; const client = createTRPCClient({ links: [ SocketIoLink({ url: 'ws://localhost:3000/socket.io/', namespace: '/trpc', }), ], }); ``` -------------------------------- ### unipm: Universal Package Manager CLI Source: https://context7.com/gongt/baobao/llms.txt unipm acts as a universal package manager, automatically detecting and using pnpm, yarn, npm, or rush. It provides a unified command-line interface for common package management tasks like installing, uninstalling, running scripts, and initializing projects. It also forwards unknown commands to the detected package manager. ```bash # Install dependencies unpm install lodash unpm add lodash --dev # or -D # Uninstall dependencies unpm uninstall lodash unpm remove lodash unpm rm lodash # Run scripts unpm run build unpm run test # Initialize project unpm init # View package information unpm show lodash # Publish package unpm publish # Format package.json unpm format-package unpm format-package -i # write back to file # Other commands will be passed directly to the detected package manager unpm outdated unpm audit ``` -------------------------------- ### Cross-Platform Utility Functions with @idlebox/common Source: https://context7.com/gongt/baobao/llms.txt This example showcases various utility functions from the @idlebox/common package. It includes array manipulation (unique, unique by reference), creating reusable filters, managing callback lists, converting caught errors to Error objects, and asynchronous utilities like sleep and TimeoutError. These functions are designed to be cross-platform. ```typescript import { arrayUnique, arrayUniqueReference, uniqueFilter, convertCaughtError, CallbackList, sleep, TimeoutError } from '@idlebox/common'; // 数组去重(返回新数组) const unique = arrayUnique([1, 2, 2, 3, 3, 3]); // [1, 2, 3] // 原地数组去重 const arr = [1, 2, 2, 3]; arrayUniqueReference(arr); // arr 变为 [1, 2, 3] // 创建可复用的去重过滤器 const filter = uniqueFilter<{ id: number }>(item => String(item.id)); const items1 = [{ id: 1 }, { id: 2 }].filter(filter); const items2 = [{ id: 2 }, { id: 3 }].filter(filter); // 跨数组去重 // 回调列表管理 const callbacks = new CallbackList<[string, number]>(); callbacks.add((msg, code) => console.log(msg, code)); callbacks.add((msg, code) => { if (code === 0) return false; // 返回 false 停止执行后续回调 }); callbacks.run('消息', 0); // 执行所有回调 // 错误转换 try { throw 'string error'; } catch (e) { const error = convertCaughtError(e); // 转换为 Error 对象 console.error(error.message); } // 异步工具 await sleep(1000); // 等待 1 秒 // 超时错误 throw new TimeoutError(5000); ``` -------------------------------- ### Execute Build Commands via CLI and Scripts Source: https://github.com/gongt/baobao/blob/master/@mpis/run/README.md Demonstrates how to trigger the build system using pnpm exec or by integrating it into package.json scripts. ```bash pnpm exec run build pnpm exec run watch pnpm exec run clean ``` ```json { "scripts": { "prepack": "mpis-run build --clean", "build": "mpis-run build", "watch": "mpis-run watch", "clean": "mpis-run clean" } } ``` -------------------------------- ### Execute Job Graph with Dependencies Source: https://github.com/gongt/baobao/blob/master/@idlebox/dependency-graph/README.md Demonstrates how to build and execute a job graph using the dependency-graph library. It defines custom job classes (CleanJob, BuildJob, PublishJob) with their respective execution logic and sets up their dependencies. The startup() method initiates the execution of the graph. ```typescript import { JobGraphBuilder, Job } from '@idlebox/dependency-graph'; class CleanJob extends Job { async override async _execute() {} } class BuildJob extends Job { async override async _execute() {} } class PublishJob extends Job { async override async _execute() {} } const graph = new JobGraphBuilder(); graph.addNode(new CleanJob("清理", [])); graph.addNode(new BuildJob("编译", ["清理"])); graph.addNode(new PublishJob("发布", ["编译"])); await graph.startup(); ``` -------------------------------- ### Using the Script with Fallback to esbuild Source: https://github.com/gongt/baobao/blob/master/@idlebox/esbuild-executer/README.md This code snippet demonstrates how to use the script. It first tries to import pre-compiled JavaScript code from `../dist/index.js`. If the file is not found, it falls back to using esbuild to compile the TypeScript file. ```APIDOC ## Using the Script with Fallback to esbuild ### Description This code snippet demonstrates how to use the script. It first tries to import pre-compiled JavaScript code from `../dist/index.js`. If the file is not found, it falls back to using esbuild to compile the TypeScript file. ### Method Not Applicable (Client-side script execution) ### Endpoint Not Applicable ### Parameters None ### Request Example ```javascript let exports; try { // 首先尝试加载编译好的代码 exports = await import('../dist/index.js'); } catch (e) { if (e.code === 'ERR_MODULE_NOT_FOUND') { // 如果没有,则使用esbuild编译 const { importFile } = await import('@idlebox/esbuild-executer') const tsFile = import.meta.resolve("../src/index.ts"); exports = await importFile(tsFile); } throw e; } export const x = exports.x; ``` ### Response None (Direct execution) ### Response Example None ``` -------------------------------- ### Configure esbuild with HTML Entry Plugin (JavaScript) Source: https://github.com/gongt/baobao/blob/master/@build-script/esbuild-html-entry/README.md This snippet shows how to integrate the HtmlEntryPlugin into your esbuild build process. It requires `metafile: true` and places the plugin first in the `plugins` array. The output is directed to 'lib' with hashed entry names. ```javascript import { HtmlEntryPlugin } from '@gongt/esbuild-html-entry' const ctx = await esbuild.context({ entryPoints: ['src/index.html'], outdir: 'lib', entryNames: '[name]-[hash]', metafile: true, // <-- this is required plugins: [ new ESBuildHtmlEntry(), // should be first in most case ], }); await ctx.rebuild(); await ctx.dispose(); ``` -------------------------------- ### Define esbuild Configuration with Build Protocol (TypeScript) Source: https://github.com/gongt/baobao/blob/master/@mpis/esbuild/README.md Demonstrates how to define esbuild configurations statically or dynamically using the `defineEsbuild` function from the @build-script/build-protocol library. The function accepts an instance name and configuration options or a factory function. Plugins are automatically appended. ```typescript /** 这是 esbuild.ts */ // 静态定义 await defineEsbuild('instance-name', { entryPoints: {}, // ... options ... plugins: [], // 插件会被自动插入到最后 }); // 动态定义 await defineEsbuild('instance-name', (isDev: boolean) => { return { entryPoints: {}, // ... options ... }; }); ``` -------------------------------- ### Build System CLI (@mpis/run) Source: https://context7.com/gongt/baobao/llms.txt Command-line interface for managing single-project builds, cleaning, and watching for changes. ```APIDOC ## CLI /mpis-run ### Description Executes build tasks and manages project lifecycles. ### Commands - **build**: Compile the project. - **watch**: Start file watching mode. - **clean**: Remove build artifacts. ### Options - **--clean**: Perform a clean build. - **--debug**: Enable debug mode. - **--dump-config**: Display current configuration. ``` -------------------------------- ### dependency-injection API Source: https://context7.com/gongt/baobao/llms.txt A lightweight dependency injection container supporting async initialization without decorators. ```APIDOC ## globalInjector.registerService(token, provider) ### Description Registers a service class or instance against a specific injection token. ### Parameters - **token** (InjectToken) - Required - The unique identifier for the service. - **provider** (Class/Instance) - Required - The implementation to register. ## globalInjector.createInstance(Class, ...args) ### Description Creates an instance of a class, automatically resolving dependencies and running initialization. ### Parameters - **Class** (Constructor) - Required - The class to instantiate. - **args** (any[]) - Optional - Manual constructor arguments. ``` -------------------------------- ### Build Protocol Client Initialization Source: https://github.com/gongt/baobao/blob/master/@mpis/client/README.md Initializes the connection to the build protocol server using the TypeScript client library. ```APIDOC ## Build Protocol Client Initialization ### Description Initializes and connects to the build protocol server to enable event reporting. ### Method N/A (Library Method) ### Endpoint `@mpis/client` ### Request Example ```ts import { BuildProtocolClient } from '@mpis/client'; const protocol = BuildProtocolClient(); await protocol.connect().catch((err) => { console.error('构建连接失败', err.message); }); ``` ``` -------------------------------- ### Initialize and Configure CustomFileWriter Source: https://github.com/gongt/baobao/blob/master/@build-script/esbuild-custom-writer/README.md Demonstrates how to import, instantiate, and register the CustomFileWriter plugin within an esbuild context. It includes a hook for modifying file metadata or content before the write operation. ```typescript import { CustomFileWriter } from '@build-script/esbuild-custom-writer'; const writePipeline = new CustomFileWriter(/* options */); writePipeline.onEmitFile((file: IFile) => { return file; }); const ctx = await esbuild.context({ /// ...blabla plugins: [writePipeline], }); ``` -------------------------------- ### Initialize Global and Module Loggers Source: https://github.com/gongt/baobao/blob/master/@idlebox/logger/README.md Demonstrates how to create a root logger for application-wide logging and scoped loggers for specific modules. The root logger is initialized with a tag, while module loggers use a colon-separated naming convention. ```typescript import { logger, createRootLogger } from "@idlebox/logger"; createRootLogger('myapp'); logger.log`debug message`; import { createLogger } from "@idlebox/logger"; const moduleLogger = createLogger('myapp:module'); moduleLogger.log`debug message`; ``` -------------------------------- ### Connect to Build Protocol Server using TypeScript API Source: https://github.com/gongt/baobao/blob/master/@mpis/client/README.md Establishes a connection to the build protocol server using the client library. Handles connection errors by logging them to the console. ```typescript import { BuildProtocolClient } from '@mpis/client'; const protocol = BuildProtocolClient(); await protocol.connect().catch((err) => { console.error('构建连接失败', err.message); }); ``` -------------------------------- ### CLI Build Protocol Monitoring Source: https://github.com/gongt/baobao/blob/master/@mpis/client/README.md Command-line interface documentation for monitoring build processes via stdin or direct command execution. ```APIDOC ## CLI Build Protocol Monitoring ### Description Monitors build processes for start, success, and error events using regex patterns on standard output. ### Usage - **Stdin Mode**: `build-protocol-client --stdin [--start ] --finish [--success ] [--error ]` - **Command Mode**: `build-protocol-client [--start ] --finish [--success ] [--error ] -- [args...]` ### Parameters - **--start** (string) - Optional - Regex pattern to identify the start of a build. - **--finish** (string) - Required - Regex pattern to identify the completion of a build. - **--success** (string) - Required (if error not set) - Regex pattern to identify a successful build. - **--error** (string) - Required (if success not set) - Regex pattern to identify a failed build. ### Example ```bash tsc -p . -w | \ build-protocol-client --stdin \ --success "Found 0 errors" \ --finish "Watching for file changes\\." \ --start "Starting (incremental)? compilation" ``` ``` -------------------------------- ### Single Project Build Tool: @mpis/run CLI Commands Source: https://context7.com/gongt/baobao/llms.txt This section outlines the command-line interface (CLI) commands provided by the @mpis/run package for managing single-project builds. It covers basic build, clean, watch, debug, and configuration inspection operations. ```bash # 构建项目 mpis-run build # 清理后构建 mpis-run build --clean # 监听模式 mpis-run watch # 清理构建产物 mpis-run clean # 调试模式 mpis-run build --debug # 查看配置 mpis-run build --dump-config ``` -------------------------------- ### Run esbuild Build or Watch Mode (Bash) Source: https://github.com/gongt/baobao/blob/master/@mpis/esbuild/README.md Shows how to execute an esbuild script using ts-node. The script will enter watch mode if the process arguments include '-w' or '--watch', otherwise it will perform a single build. An optional environment variable `BUILD_PROTOCOL_SERVER` can be set. ```bash # BUILD_PROTOCOL_SERVER=node:ipc ts-node ./esbuild.ts ``` -------------------------------- ### 使用 @idlebox/cli 构建命令行应用程序 Source: https://context7.com/gongt/baobao/llms.txt 演示如何初始化 CLI 应用、配置静态与动态子命令,以及访问应用运行状态。该库整合了参数解析、日志记录和进程退出处理。 ```typescript import { makeApplication, app } from '@idlebox/cli'; const cli = makeApplication({ name: 'my-tool', description: '我的命令行工具', logPrefix: 'mytool' }); cli.initialize(async (argv, command) => { console.log('初始化完成'); }); await cli.simple( { args: { '--force, -f': { flag: true, description: '强制执行' } } }, async (args) => { const force = args.flag(['--force', '-f']); } ); await cli.static( { 'build': './commands/build.js', 'watch': './commands/watch.js', 'clean': './commands/clean.js', }, [ { command: 'build', description: '构建项目' }, { command: 'watch', description: '监听模式构建' }, { command: 'clean', description: '清理构建产物' }, ] ); await cli.dynamic('./commands', ['*.js']); console.log(app.debug, app.verbose, app.silent, app.showHelp, app.command); ``` -------------------------------- ### @idlebox/cli - CLI Application Infrastructure Source: https://context7.com/gongt/baobao/llms.txt Integrates args, logger, and exit handlers for building CLI applications. ```APIDOC ## @idlebox/cli - CLI Application Infrastructure ### Description Integrates args, logger, and exit handlers for building CLI applications. ### Method N/A (Library Usage) ### Endpoint N/A (Library Usage) ### Parameters N/A ### Request Example N/A ### Response N/A ## Usage Examples ```typescript import { makeApplication, app } from '@idlebox/cli'; // Auto-read from package.json const cli = makeApplication(); // Manual configuration const cli = makeApplication({ name: 'my-tool', description: 'My command-line tool', logPrefix: 'mytool' }); // Add initialization callback cli.initialize(async (argv, command) => { console.log('Initialization complete'); }); // Simple mode (no subcommands) await cli.simple( { args: { '--force, -f': { flag: true, description: 'Force execution' } } }, async (args) => { const force = args.flag(['--force', '-f']); // Execute main logic } ); // Static subcommand mode await cli.static( { 'build': './commands/build.js', 'watch': './commands/watch.js', 'clean': './commands/clean.js', }, [ { command: 'build', description: 'Build project' }, { command: 'watch', description: 'Watch mode build' }, { command: 'clean', description: 'Clean build artifacts' }, ] ); // Dynamic subcommand mode (load from directory) await cli.dynamic('./commands', ['*.js']); // Access application state console.log(app.debug); // --debug flag passed? console.log(app.verbose); // --debug -d passed twice? console.log(app.silent); // --silent flag passed? console.log(app.showHelp); // --help flag passed? console.log(app.command); // Current subcommand name ``` ``` -------------------------------- ### Configure package.json for Custom Publisher Source: https://github.com/gongt/baobao/blob/master/@mpis/publisher/README.md To use the custom publisher, set private to true to prevent accidental publishing and define the prepublishHook script to execute your custom logic. ```json { "private": true, "scripts": { "prepublishHook": "echo 'Running prepublish hook...'" } } ``` -------------------------------- ### Dependency Injection with @idlebox/dependency-injection Source: https://context7.com/gongt/baobao/llms.txt Illustrates a lightweight dependency injection container that supports asynchronous initialization and constructor dependency injection without decorators. ```typescript import { globalInjector, createInjectToken, initialization, makeClassInjectable, injectConstructorDependency, type IInjectable } from '@idlebox/dependency-injection'; const DatabaseToken = createInjectToken('Database'); const LoggerToken = createInjectToken('Logger'); class UserService implements IInjectable { constructor(private readonly name: string, private readonly db: IDatabase, private readonly logger: ILogger) {} async [initialization]() { this.logger.log('UserService 初始化完成'); } async getUser(id: number) { return this.db.query(`SELECT * FROM users WHERE id = ${id}`); } } makeClassInjectable(UserService); injectConstructorDependency(UserService, 1, DatabaseToken); injectConstructorDependency(UserService, 2, LoggerToken); globalInjector.registerService(DatabaseToken, DatabaseService); const userService = await globalInjector.createInstance(UserService, 'users'); ``` -------------------------------- ### CLI Commands for Publisher Source: https://github.com/gongt/baobao/blob/master/@mpis/publisher/README.md Use the publisher CLI to execute pack or publish workflows. Supports various flags like --access, --dry-run, and --registry. ```bash publisher pack [--out xxx.tgz] publisher publish [--access public] [--dry-run] [--force] [--no-git-checks] [--publish-branch master] [--report-summary] [--tag latest] [--registry https://registry.npmjs.org] ``` -------------------------------- ### Manage Monorepo Packages with package-tools Source: https://context7.com/gongt/baobao/llms.txt A suite of tools for monorepo maintenance, including change detection, version bumping, and publishing workflows. ```bash package-tools detect-package-change package-tools detect-package-change --bump package-tools detect-package-change --json package-tools monorepo-publish package-tools monorepo-cnpm-sync package-tools monorepo-list package-tools monorepo-upgrade package-tools monorepo-tsconfig package-tools run-if-version-mismatch --flush -- pnpm publish --no-git-checks ``` -------------------------------- ### systemd-unit-generator: Generate Systemd Unit Files with Type Checking Source: https://context7.com/gongt/baobao/llms.txt The @gongt/systemd-unit-generator package simplifies the creation of Systemd unit files by providing a type-safe API. It allows developers to define service, timer, and other unit configurations programmatically. The generated output is a string representation of a valid Systemd unit file. No external dependencies are required beyond Node.js. ```typescript import { createUnit } from '@gongt/systemd-unit-generator'; // Create a service unit const serviceUnit = createUnit('service', { Unit: { Description: 'My Application Service', After: ['network.target'], Wants: ['network-online.target'] }, Service: { Type: 'simple', ExecStart: '/usr/bin/node /app/server.js', Restart: 'always', RestartSec: 5, User: 'appuser', WorkingDirectory: '/app', Environment: ['NODE_ENV=production', 'PORT=3000'] }, Install: { WantedBy: ['multi-user.target'] } }); // Output the unit file content console.log(serviceUnit.toString()); // Example of generated file content: // [Unit] // Description=My Application Service // After=network.target // Wants=network-online.target // // [Service] // Type=simple // ExecStart=/usr/bin/node /app/server.js // Restart=always // RestartSec=5 // User=appuser // WorkingDirectory=/app // Environment=NODE_ENV=production // Environment=PORT=3000 // // [Install] // WantedBy=multi-user.target ``` -------------------------------- ### Configure Build Commands in commands.json Source: https://github.com/gongt/baobao/blob/master/@mpis/run/README.md Defines the build pipeline, including command execution, package-specific binaries, and shared command definitions. It supports custom titles, working directories, and watch mode arguments. ```jsonc { "$schema": "../node_modules/@mpis/run/commands.schema.json", "build": [ { "command": ["codegen", "src"] }, { "title": "autoindex", "command": { "package": "@build-script/autoindex", "binary": "autoindex", "arguments": ["src"] } }, "some-common-command", { "title": "typescript", "command": ["mpis-tsc", "-p", "src"], "watch": ["--watch"] } ], "commands": { "some-common-command": { "title": "common command", "command": ["some-command", "--arg=value"] } }, "clean": ["dist", "lib"] } ``` -------------------------------- ### Generate Multiple Files Source: https://github.com/gongt/baobao/blob/master/@build-script/codegen/README.md Illustrates how to use the builder.file method to create and append content to multiple files simultaneously. This is useful for generating complex modules or components. ```typescript import type { GenerateContext } from '@build-script/codegen'; export async function generate(builder: GenerateContext) { const someOtherFile1 = builder.file("base-name-of-file.tsx"); // 生成的文件名为 base-name-of-file.generated.tsx someOtherFile1.append("export function foo() { return
; }"); return 'console.log("Hello, world!");'; } ``` -------------------------------- ### MPIS Build Configuration with @mpis/run Source: https://context7.com/gongt/baobao/llms.txt This TypeScript configuration file (`mpis.config.ts`) demonstrates how to define build processes and dependencies using the @mpis/run package. It specifies workers (build tasks) with their commands, arguments, working directories, and dependencies, as well as a clean target. ```typescript // mpis.config.ts 配置示例 export default { workers: [ { id: 'typescript', command: 'tsc', args: ['--build', '--watch'], cwd: '.' }, { id: 'esbuild', command: 'esbuild', args: ['src/index.ts', '--bundle', '--outfile=dist/index.js'], dependsOn: ['typescript'] } ], clean: ['./dist', './lib'] }; ``` -------------------------------- ### File Monitoring API (@idlebox/chokidar) Source: https://context7.com/gongt/baobao/llms.txt Provides an interface for file system monitoring with support for debouncing, event filtering, and lifecycle management. ```APIDOC ## File Monitoring API ### Description Provides high-level file monitoring capabilities with debouncing and event management. ### Method N/A (Class-based API) ### Endpoint @idlebox/chokidar ### Parameters #### Options - **debounceMs** (number) - Optional - Debounce delay in milliseconds. - **watchingEvents** (string[]) - Optional - List of events to listen for (e.g., 'add', 'change', 'unlink'). - **ignoreInitial** (boolean) - Optional - Whether to ignore initial scan. ### Response - **watcher** (Object) - Returns a watcher instance with methods: add(), delete(), reset(), listen(), unlisten(), and dispose(). ``` -------------------------------- ### API: execute Source: https://github.com/gongt/baobao/blob/master/@idlebox/esbuild-executer/README.md The `execute` function is identical to `importFile`, but it also sets `process.argv[1]` to the path of the executed file, which can be useful for scripts that inspect their own execution path. ```APIDOC ## API: execute ### Description The `execute` function is identical to `importFile`, but it also sets `process.argv[1]` to the path of the executed file, which can be useful for scripts that inspect their own execution path. ### Method Not Applicable (Function call) ### Endpoint Not Applicable ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { execute } from '@idlebox/esbuild-executer' const tsFile = import.meta.resolve("./your-script.ts"); // Must be a fileUrl await execute(tsFile); ``` ### Response #### Success Response (200) None (Execution completes) #### Response Example None ``` -------------------------------- ### CLI Commands for Publisher Source: https://github.com/gongt/baobao/blob/master/@mpis/publisher/README.md Commands to execute custom pack and publish workflows with lifecycle hooks. ```APIDOC ## CLI Commands ### Description The publisher tool intercepts standard pack and publish flows to allow for custom script execution via `prepublishHook`. ### Commands - **publisher pack** [--out ] - **publisher publish** [--access ] [--dry-run] [--force] [--no-git-checks] [--publish-branch ] [--report-summary] [--tag ] [--registry ] ### Configuration Add a `prepublishHook` script to your `package.json` to execute custom logic during the process. ### Example Configuration { "private": true, "scripts": { "prepublishHook": "echo 'Running prepublish hook...'" } } ``` -------------------------------- ### 使用 @idlebox/logger 进行多级别日志记录 Source: https://context7.com/gongt/baobao/llms.txt 展示如何初始化根日志器、使用不同级别记录日志、扩展子日志器以及动态控制日志输出级别。该工具支持 Node.js 和浏览器环境,并提供颜色高亮输出。 ```typescript import { createRootLogger, logger, EnableLogLevel } from '@idlebox/logger'; createRootLogger('my-app', EnableLogLevel.debug); logger.fatal`致命错误: ${error}`; logger.error`错误: ${message}`; logger.warn`警告: ${message}`; logger.success`成功: ${message}`; logger.info`信息: ${message}`; logger.log`普通日志: ${message}`; logger.debug`调试: ${message}`; logger.verbose`详细: ${message}`; const dbLogger = logger.extend('database'); dbLogger.info`数据库连接成功`; logger.enable(EnableLogLevel.warn); if (logger.debug.isEnabled) { logger.debug`详细调试信息: ${expensiveComputation()}`; } ``` -------------------------------- ### API: importFile Source: https://github.com/gongt/baobao/blob/master/@idlebox/esbuild-executer/README.md The `importFile` function compiles a TypeScript file using esbuild and imports it. It requires the input file path to be an absolute `fileUrl`. ```APIDOC ## API: importFile ### Description The `importFile` function compiles a TypeScript file using esbuild and imports it. It requires the input file path to be an absolute `fileUrl`. ### Method Not Applicable (Function call) ### Endpoint Not Applicable ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { importFile } from '@idlebox/esbuild-executer' const tsFile = import.meta.resolve("./your-file.ts"); // Must be a fileUrl const module = await importFile(tsFile); ``` ### Response #### Success Response (200) - **module** (object) - The imported module object. #### Response Example ```json { "exportedValue": "someValue" } ``` ``` -------------------------------- ### Browser Fetch API (@idlebox/browser) Source: https://context7.com/gongt/baobao/llms.txt Provides a robust fetch implementation with built-in retry logic and timeout handling. ```APIDOC ## POST /retryFetch ### Description Performs a fetch request with automatic retries and timeout support. ### Method POST ### Parameters #### Request Body - **retries** (number) - Optional - Number of retry attempts. - **delay** (number) - Optional - Delay between retries in ms. - **timeout** (number) - Optional - Timeout per request in ms. - **signal** (AbortSignal) - Optional - AbortController signal for cancellation. ### Response #### Success Response (200) - **response** (Response) - Standard Fetch API Response object. ``` -------------------------------- ### @idlebox/logger - Simple Logging System Source: https://context7.com/gongt/baobao/llms.txt Provides multi-level logging for Node.js and browser environments with color output and log level control. ```APIDOC ## @idlebox/logger - Simple Logging System ### Description Provides multi-level logging for Node.js and browser environments with color output and log level control. ### Method N/A (Library Usage) ### Endpoint N/A (Library Usage) ### Parameters N/A ### Request Example N/A ### Response N/A ## Usage Examples ```typescript import { createRootLogger, logger, EnableLogLevel } from '@idlebox/logger'; // Create root logger createRootLogger('my-app', EnableLogLevel.debug); // Use global logger logger.fatal`Fatal error: ${error}`; logger.error`Error: ${message}`; logger.warn`Warning: ${message}`; logger.success`Success: ${message}`; logger.info`Info: ${message}`; logger.log`Log: ${message}`; logger.debug`Debug: ${message}`; logger.verbose`Verbose: ${message}`; // Create child logger const dbLogger = logger.extend('database'); dbLogger.info`Database connection successful`; // Dynamically control log level logger.enable(EnableLogLevel.warn); // Check if log is enabled if (logger.debug.isEnabled) { logger.debug`Detailed debug info: ${expensiveComputation()}`; } // Log level enum // EnableLogLevel.auto - Auto-detect (via DEBUG environment variable) // EnableLogLevel.verbose - Show all logs // EnableLogLevel.debug - Show debug and above // EnableLogLevel.log - Show log and above // EnableLogLevel.info - Show info and above // EnableLogLevel.warn - Show warn and above // EnableLogLevel.error - Show only error ``` ``` -------------------------------- ### Configure Rollup for Manual Chunk Splitting Source: https://github.com/gongt/baobao/blob/master/@build-script/vite-plugin-chunk-tree/README.md This snippet demonstrates how to use the createManualChunks function from the vite-plugin-split-vendor package to configure manual chunking for Rollup. The configuration object passed to createManualChunks is identical to the one used for Vite. The generated callback is then assigned to the manualChunks option in Rollup's output configuration. ```typescript import { createManualChunks } from "@build-script/vite-plugin-split-vendor"; const chunks = createManualChunks({ // 这里的配置和vite的配置一样 ... }); const rollupOptions = { output: { manualChunks: chunks.callback, }, }; ``` -------------------------------- ### Configure Vite for Manual Vendor Chunk Splitting Source: https://github.com/gongt/baobao/blob/master/@build-script/vite-plugin-chunk-tree/README.md This snippet shows how to integrate the splitVendorPlugin into a Vite project's configuration. It defines specific packages like 'react', 'antd', and 'lodash' to be bundled into separate chunks named '_lib', 'react', 'antd', and 'lodash' respectively. This helps in optimizing the build by isolating frequently updated or large dependency groups. ```typescript import { splitVendorPlugin } from "@build-script/vite-plugin-chunk-tree"; export default defineConfig(async (config) => { return { plugins: [ splitVendorPlugin({ internalChunk: '_lib', chunks: [ { name: "react", packages: ["react", "react-dom", "react-router"] }, { name: "antd", packages: ["antd", "@ant-design/icons"] }, { name: "lodash", packages: ["lodash", "lodash-es"] }, ] }), ], } }); ``` -------------------------------- ### Handling Subcommands Source: https://github.com/gongt/baobao/blob/master/@idlebox/args/README.md Shows how to extract subcommands from the argument list, allowing for nested parsing logic where flags can appear before or after the command. ```typescript const argv = ['clone', '--work-tree=/tmp/xxx', '--depth=5', 'https://xxxx', '--verbose']; const args = createArgsReader(argv); const subArgs = args.requireCommand(['clone', 'pull', 'push']); subArgs.single(['--depth']); // -> '5' ``` -------------------------------- ### Parse CLI Arguments with @idlebox/args Source: https://context7.com/gongt/baobao/llms.txt Provides a flexible API for parsing command-line flags, options, positional arguments, and subcommands. ```typescript import { createArgsReader } from '@idlebox/args'; const args = createArgsReader(['--verbose', '-d', '--output', 'dist', 'build', 'src']); const debugLevel = args.flag(['--debug', '-d']); const verbose = args.flag(['--verbose', '-v']); const output = args.single(['--output', '-o']); const includes = args.multiple(['--include', '-I']); const command = args.at(0); const targets = args.range(1); const subcmd = args.command(['build', 'watch', 'clean']); if (subcmd?.value === 'build') { const clean = subcmd.flag(['--clean']); } const unused = args.unused(); ``` -------------------------------- ### Unconditional esbuild Execution Source: https://github.com/gongt/baobao/blob/master/@idlebox/esbuild-executer/README.md This snippet shows how to unconditionally use esbuild to compile and import a TypeScript file. It directly imports the `importFile` function from `@idlebox/esbuild-executer` and uses it to load the specified TypeScript file. ```APIDOC ## Unconditional esbuild Execution ### Description This snippet shows how to unconditionally use esbuild to compile and import a TypeScript file. It directly imports the `importFile` function from `@idlebox/esbuild-executer` and uses it to load the specified TypeScript file. ### Method Not Applicable (Client-side script execution) ### Endpoint Not Applicable ### Parameters None ### Request Example ```javascript import { importFile } from '@idlebox/esbuild-executer' const tsFile = import.meta.resolve("../src/index.ts"); const exports = await importFile(tsFile) export const x = exports.x; ``` ### Response None (Direct execution) ### Response Example None ``` -------------------------------- ### Deep Object Merging with @idlebox/deepmerge Source: https://context7.com/gongt/baobao/llms.txt Demonstrates how to perform deep object merges with custom strategies for primitives, arrays, and special types. It also shows how to use the custom symbol for class-specific merge logic. ```typescript import { deepmerge, custom, type MergeStrategy } from '@idlebox/deepmerge'; const a = { name: 'test', config: { debug: true, port: 3000 } }; const b = { version: '1.0', config: { port: 8080 } }; const result = deepmerge(a, b); const strategy: MergeStrategy = { primitive: (left, right, keyPath) => right ?? left, array: (left, right, keyPath) => [...left, ...(Array.isArray(right) ? right : [])], object: (left, right, keyPath) => undefined, special: new Map([ [Date, (left, right) => right ?? left], [Map, (left, right) => new Map([...left, ...(right ?? [])])], ]) }; const merged = deepmerge(a, b, strategy); class Config { constructor(public value: number) {} [custom](other: any, keyPath: string[]) { return new Config(this.value + (other?.value ?? 0)); } } ``` -------------------------------- ### Load Inherited JSON Configuration Source: https://github.com/gongt/baobao/blob/master/@idlebox/json-extends-loader/README.md Demonstrates how to use the loadInheritedJson function to load a configuration file that supports inheritance. The function accepts a file path and an optional configuration object to customize behavior like working directory. ```typescript import { loadInheritedJson } from '@idlebox/json-extends-loader'; const config = loadInheritedJson('src/tsconfig.json', { cwd: __dirname }); ```