@bleedingdev/modern-js-sandpack-react 3.2.0-ultramodern.116 → 3.2.0-ultramodern.118
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/templates/mwa.js +32 -35
- package/dist/esm/templates/mwa.mjs +32 -35
- package/dist/esm-node/templates/mwa.mjs +32 -35
- package/dist/types/templates/mwa.d.ts +24 -27
- package/package.json +2 -2
- package/scripts/template.mts +1 -33
|
@@ -33,42 +33,39 @@ __webpack_require__.d(__webpack_exports__, {
|
|
|
33
33
|
const external_common_js_namespaceObject = require("./common.js");
|
|
34
34
|
const MWAFiles = {
|
|
35
35
|
...external_common_js_namespaceObject.commonFiles,
|
|
36
|
-
".browserslistrc": "chrome >= 87\nedge >= 88\nfirefox >= 78\nsafari >= 14\n",
|
|
37
|
-
".gitignore": ".DS_Store\n\n.pnp\n.pnp.js\n.env.local\n.env.*.local\n.history\n*.log*\n\nnode_modules/\n.yarn-integrity\n.pnpm-store/\n*.tsbuildinfo\n.changeset/pre.json\n\ndist/\ncoverage/\nrelease/\noutput/\noutput_resource/\nlog/\n\n.vscode/**/*\n!.vscode/settings.json\n!.vscode/extensions.json\n.idea/\n\n**/*/typings/auto-generated\n\nmodern.config.local.*\n",
|
|
38
36
|
".mise.toml": "[tools]\npnpm = \"11.5.2\"\n",
|
|
39
|
-
".
|
|
40
|
-
"AGENTS.md": "# UltraModern Agent Contract\n\nThis
|
|
41
|
-
"
|
|
42
|
-
"lefthook.yml": "pre-commit:\n commands:\n
|
|
43
|
-
"oxfmt.config.ts": "import { defineConfig } from 'oxfmt';\nimport ultracite from 'ultracite/oxfmt';\n\nexport default defineConfig({\n extends: [ultracite],\n ignorePatterns: [\n '.agents',\n 'dist',\n 'node_modules',\n '.modern',\n '.modernjs',\n '**/routeTree.gen.ts',\n ],\n singleQuote: true,\n});\n",
|
|
44
|
-
"oxlint.config.ts": "import { defineConfig } from 'oxlint';\nimport core from 'ultracite/oxlint/core';\nimport react from 'ultracite/oxlint/react';\n\nexport default defineConfig({\n env: {\n browser: true,\n node: true,\n },\n extends: [core, react],\n ignorePatterns: [\n '.agents',\n 'dist',\n 'node_modules',\n '.modern',\n '.modernjs',\n '**/routeTree.gen.ts',\n ],\n});\n",
|
|
45
|
-
"
|
|
46
|
-
"
|
|
47
|
-
"
|
|
48
|
-
"
|
|
49
|
-
"
|
|
50
|
-
"
|
|
51
|
-
".
|
|
52
|
-
".agents/skills-lock.json": "{\n \"schemaVersion\":
|
|
53
|
-
"
|
|
54
|
-
"
|
|
55
|
-
"scripts/validate-ultramodern.mjs": "import { execFileSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nconst configPath = path.resolve(process.cwd(), 'modern.config.ts');\nconst templateManifestPath = path.resolve(process.cwd(), '.modernjs/mv-template-manifest.json');\nconst packageSourcePath = path.resolve(\n process.cwd(),\n '.modernjs/ultramodern-package-source.json',\n);\nconst readText = (relativePath) =>\n fs.readFileSync(path.resolve(process.cwd(), relativePath), 'utf-8');\nconst readJson = (relativePath) => JSON.parse(readText(relativePath));\nconst readPnpmConfig = (key) => {\n const env = Object.fromEntries(\n Object.entries(process.env).filter(\n ([envKey]) => !/^(?:npm|pnpm)_config_/iu.test(envKey),\n ),\n );\n const output = execFileSync('pnpm', ['config', 'get', key, '--json'], {\n cwd: process.cwd(),\n encoding: 'utf-8',\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n }).trim();\n return output ? JSON.parse(output) : undefined;\n};\nconst enableTailwind = true;\nconst expectedPnpmVersion = '11.5.2';\nconst activePnpmVersion = execFileSync('pnpm', ['--version'], {\n cwd: process.cwd(),\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'pipe'],\n}).trim();\n\nif (activePnpmVersion !== expectedPnpmVersion) {\n console.error(\n `Generated app requires pnpm ${expectedPnpmVersion}; active pnpm is ${activePnpmVersion}. Run mise install, then rerun pnpm from the activated shell`,\n );\n process.exit(1);\n}\n\nif (!fs.existsSync(configPath)) {\n console.error('modern.config.ts not found');\n process.exit(1);\n}\n\nconst content = fs.readFileSync(configPath, 'utf-8');\nconst requiredTokens = [\n 'presetUltramodern(',\n 'appTools()',\n 'enableModuleFederationSSR',\n 'enableBffRequestId',\n 'enableTelemetryExporters',\n 'i18nPlugin(',\n 'localePathRedirect: true',\n 'ULTRAMODERN_SITE_URL',\n 'MODERN_PUBLIC_SITE_URL must be set for production builds',\n 'globalVars',\n];\nconst missing = requiredTokens.filter((token) => !content.includes(token));\n\nif (missing.length > 0) {\n console.error(`Ultramodern contract check failed. Missing tokens: ${missing.join(', ')}`);\n process.exit(1);\n}\n\nif (!fs.existsSync(templateManifestPath)) {\n console.error('.modernjs/mv-template-manifest.json not found');\n process.exit(1);\n}\n\nconst templateManifest = JSON.parse(fs.readFileSync(templateManifestPath, 'utf-8'));\nconst requiredDeniedPaths = [\n '.git/**',\n '.npmrc',\n '.yarnrc',\n '.env',\n '.env.*',\n 'node_modules/**',\n 'dist/**',\n];\nconst requiredPostMaterialization = [\n 'ultramodern-contract-check',\n 'agent-skill-postinstall-allowed',\n 'github-workflow-security-enforced',\n 'package-source-retained',\n 'pnpm-11-policy-enforced',\n 'rstest-smoke-tests',\n 'template-manifest-retained',\n];\nconst requiredPaths = [\n\n 'AGENTS.md',\n '.agents/skills-lock.json',\n '.codex/hooks.json',\n '.github/renovate.json',\n '.github/workflows/ultramodern-gates.yml',\n 'lefthook.yml',\n 'scripts/bootstrap-agent-skills.mjs',\n\n '.mise.toml',\n '.modernjs/ultramodern-package-source.json',\n 'oxlint.config.ts',\n 'oxfmt.config.ts',\n 'pnpm-workspace.yaml',\n 'rstest.config.mts',\n 'scripts/check-i18n-strings.mjs',\n\n 'postcss.config.mjs',\n 'tailwind.config.ts',\n\n 'config/public/locales/en/translation.json',\n 'config/public/locales/cs/translation.json',\n 'config/favicon.svg',\n 'config/public/assets/ultramodern-logo.svg',\n 'src/modern-app-env.d.ts',\n 'src/routes/index.css',\n 'src/routes/layout.tsx',\n 'src/routes/[lang]/page.tsx',\n 'tests/ultramodern.contract.test.ts',\n];\nconst manifestErrors = [];\n\nfor (const requiredPath of requiredPaths) {\n if (!fs.existsSync(path.resolve(process.cwd(), requiredPath))) {\n console.error(`${requiredPath} not found`);\n process.exit(1);\n }\n}\n\nif (fs.existsSync(path.resolve(process.cwd(), 'src/routes/page.tsx'))) {\n console.error('src/routes/page.tsx must move under src/routes/[lang]/page.tsx');\n process.exit(1);\n}\n\nif (\n !enableTailwind &&\n (fs.existsSync(path.resolve(process.cwd(), 'postcss.config.mjs')) ||\n fs.existsSync(path.resolve(process.cwd(), 'tailwind.config.ts')))\n) {\n console.error('Tailwind config files must not be written when Tailwind is disabled');\n process.exit(1);\n}\n\n\nconst workflowContent = fs.readFileSync(\n path.resolve(process.cwd(), '.github/workflows/ultramodern-gates.yml'),\n 'utf-8',\n);\nconst renovateConfig = JSON.parse(\n fs.readFileSync(path.resolve(process.cwd(), '.github/renovate.json'), 'utf-8'),\n);\nfor (const requiredSnippet of [\n 'permissions:\\n contents: read',\n 'pull_request:',\n 'persist-credentials: false',\n 'jdx/mise-action',\n 'pnpm install --frozen-lockfile',\n 'pnpm run ultramodern:check',\n 'pnpm run build',\n 'MODERN_PUBLIC_SITE_URL: http://localhost:8080',\n 'timeout-minutes:',\n 'egress-policy: audit',\n]) {\n if (!workflowContent.includes(requiredSnippet)) {\n console.error(`Generated workflow must retain ${requiredSnippet.split('\\n')[0]}`);\n process.exit(1);\n }\n}\nif (workflowContent.includes('pull_request_target')) {\n console.error('Generated workflow must not use pull_request_target');\n process.exit(1);\n}\nfor (const match of workflowContent.matchAll(/^\\s*uses:\\s*([^@\\s]+)@([^\\s#]+)/gmu)) {\n const [, actionName, actionRef] = match;\n if (!/^[a-f0-9]{40}$/u.test(actionRef)) {\n console.error(`Generated workflow must pin ${actionName}@${actionRef} to a commit SHA`);\n process.exit(1);\n }\n}\nif (\n renovateConfig.dependencyDashboard !== true ||\n renovateConfig.minimumReleaseAge !== '1 day' ||\n !renovateConfig.extends?.includes('helpers:pinGitHubActionDigests') ||\n !renovateConfig.packageRules?.some(\n (rule) =>\n rule.dependencyDashboardApproval === true && rule.matchUpdateTypes?.includes('major'),\n )\n) {\n console.error('Generated Renovate config must retain dashboard, release-age, action pinning, and major-approval policy');\n process.exit(1);\n}\n\n\nif (templateManifest.schemaVersion !== 1) {\n manifestErrors.push('schemaVersion');\n}\n\nif (templateManifest.source?.type !== 'builtin') {\n manifestErrors.push('source.type');\n}\n\nif (\n !Array.isArray(templateManifest.integrity?.checksums) ||\n !templateManifest.integrity.checksums.some(\n (checksum) =>\n checksum.algorithm === 'sha256' &&\n checksum.scope === 'source-tree' &&\n /^[0-9a-f]{64}$/u.test(checksum.value),\n )\n) {\n manifestErrors.push('integrity.checksums[source-tree]');\n}\n\nfor (const deniedPath of requiredDeniedPaths) {\n if (!templateManifest.materialization?.deniedPaths?.includes(deniedPath)) {\n manifestErrors.push(`materialization.deniedPaths:${deniedPath}`);\n }\n}\n\nif (templateManifest.lifecyclePolicy?.denyByDefault !== true) {\n manifestErrors.push('lifecyclePolicy.denyByDefault');\n}\nif (\n JSON.stringify(templateManifest.lifecyclePolicy?.allowedScripts) !==\n JSON.stringify(['postinstall'])\n) {\n manifestErrors.push('lifecyclePolicy.allowedScripts');\n}\n\nfor (const token of requiredPostMaterialization) {\n if (!templateManifest.validation?.postMaterializationValidation?.includes(token)) {\n manifestErrors.push(`validation.postMaterializationValidation:${token}`);\n }\n}\n\nif (manifestErrors.length > 0) {\n console.error(\n `Ultramodern template manifest check failed. Invalid fields: ${manifestErrors.join(', ')}`,\n );\n process.exit(1);\n}\n\nconst packageJson = JSON.parse(\n fs.readFileSync(path.resolve(process.cwd(), 'package.json'), 'utf-8'),\n);\nconst packageSource = JSON.parse(fs.readFileSync(packageSourcePath, 'utf-8'));\nconst routePage = readText('src/routes/[lang]/page.tsx');\nconst routeCss = readText('src/routes/index.css');\nconst modernConfig = readText('modern.config.ts');\nconst enLocale = readJson('config/public/locales/en/translation.json');\nconst csLocale = readJson('config/public/locales/cs/translation.json');\nconst unresolvedTemplateMarker = String.fromCodePoint(123, 123);\nif (JSON.stringify(packageJson).includes(unresolvedTemplateMarker)) {\n console.error('package.json contains unresolved template markers');\n process.exit(1);\n}\nif (JSON.stringify(packageSource).includes(unresolvedTemplateMarker)) {\n console.error('package source metadata contains unresolved template markers');\n process.exit(1);\n}\n\nfor (const [fileName, text] of [\n ['src/routes/[lang]/page.tsx', routePage],\n ['src/routes/index.css', routeCss],\n ['modern.config.ts', modernConfig],\n]) {\n if (text.includes('lf3-static.bytednsdoc.com')) {\n console.error(`${fileName} must not depend on remote starter assets`);\n process.exit(1);\n }\n}\n\nfor (const requiredSnippet of [\n '<Helmet',\n 'htmlAttributes={{',\n 'dir: languageDirections[currentLanguage]',\n 'lang: currentLanguage',\n '<title>{pageTitle}</title>',\n '<meta name=\"description\" content={pageDescription} />',\n '<main id=\"starter-main\" className=\"starter-main\">',\n '<h1 id=\"starter-heading\" className=\"title\">',\n 'src=\"/assets/ultramodern-logo.svg\"',\n 'height={96}',\n 'width={96}',\n '<span aria-hidden=\"true\" className=\"arrow-right\" />',\n]) {\n if (!routePage.includes(requiredSnippet)) {\n console.error(`Generated route page must retain starter correctness snippet: ${requiredSnippet}`);\n process.exit(1);\n }\n}\n\nfor (const forbiddenSnippet of ['src=\"https://', '<div className=\"title\">']) {\n if (routePage.includes(forbiddenSnippet)) {\n console.error(`Generated route page must not contain ${forbiddenSnippet}`);\n process.exit(1);\n }\n}\n\nfor (const requiredSnippet of [\n 'width=device-width, initial-scale=1.0, viewport-fit=cover',\n \"title: 'UltraModern.js Starter'\",\n]) {\n if (!modernConfig.includes(requiredSnippet)) {\n console.error(`modern.config.ts must retain ${requiredSnippet}`);\n process.exit(1);\n }\n}\nif (modernConfig.includes('user-scalable=no') || modernConfig.includes('maximum-scale')) {\n console.error('modern.config.ts must not disable user zoom');\n process.exit(1);\n}\n\nfor (const requiredSnippet of [\n 'min-block-size: 100dvh',\n 'grid-template-columns: repeat(auto-fit, minmax(min(100%, 17rem), 1fr))',\n ':focus-visible',\n '@media (prefers-reduced-motion: reduce)',\n '.skip-link',\n]) {\n if (!routeCss.includes(requiredSnippet)) {\n console.error(`Starter CSS must retain ${requiredSnippet}`);\n process.exit(1);\n }\n}\nif (routeCss.includes('width: 1100px') || /\\.card:focus(?!-visible)/u.test(routeCss)) {\n console.error('Starter CSS must not reintroduce fixed grid width or focus transform styling');\n process.exit(1);\n}\n\nfor (const [localeName, locale] of [\n ['en', enLocale],\n ['cs', csLocale],\n]) {\n if (\n typeof locale.home?.meta?.title !== 'string' ||\n typeof locale.home?.meta?.description !== 'string' ||\n typeof locale.home?.skipLink !== 'string'\n ) {\n console.error(`${localeName} locale must include starter metadata and skip-link copy`);\n process.exit(1);\n }\n}\n\nconst skillsLock = JSON.parse(\n fs.readFileSync(path.resolve(process.cwd(), '.agents/skills-lock.json'), 'utf-8'),\n);\n\nconst requiredScripts = {\n format: 'oxfmt .',\n 'format:check': 'oxfmt --check .',\n 'i18n:check': 'node ./scripts/check-i18n-strings.mjs',\n lint: 'oxlint .',\n 'lint:fix': 'oxlint . --fix',\n\n postinstall: 'oxfmt . && node ./scripts/bootstrap-agent-skills.mjs',\n 'skills:check': 'node ./scripts/bootstrap-agent-skills.mjs --check',\n 'skills:install': 'node ./scripts/bootstrap-agent-skills.mjs',\n\n test: 'rstest run',\n};\n\nfor (const [scriptName, scriptCommand] of Object.entries(requiredScripts)) {\n if (packageJson.scripts?.[scriptName] !== scriptCommand) {\n console.error(`Missing or invalid package script: ${scriptName}`);\n process.exit(1);\n }\n}\n\nconst i18nCheckScript = readText('scripts/check-i18n-strings.mjs');\nif (\n !i18nCheckScript.includes(\"from '@modern-js/code-tools'\") ||\n !i18nCheckScript.includes('runSingleAppI18nCheck')\n) {\n console.error('i18n:check must call @modern-js/code-tools');\n process.exit(1);\n}\n\nif (\n !packageJson.scripts?.typecheck?.includes('effect-tsgo') ||\n !packageJson.scripts.typecheck.includes('get-exe-path')\n) {\n console.error('typecheck must use effect-tsgo as the TypeScript checker');\n process.exit(1);\n}\n\nconst expectedUltramodernCheck =\n 'pnpm format:check && pnpm lint && pnpm typecheck && pnpm i18n:check && pnpm test && pnpm skills:check && node ./scripts/validate-ultramodern.mjs';\nif (packageJson.scripts?.['ultramodern:check'] !== expectedUltramodernCheck) {\n console.error('ultramodern:check must run format, lint, typecheck, i18n, tests, and contract validation');\n process.exit(1);\n}\n\nif (packageJson.private !== true) {\n console.error('Generated app package must be private by default');\n process.exit(1);\n}\n\nconst miseConfig = fs.readFileSync(path.resolve(process.cwd(), '.mise.toml'), 'utf-8');\nif (!miseConfig.includes(`pnpm = \"${expectedPnpmVersion}\"`)) {\n console.error(`Generated app must pin pnpm ${expectedPnpmVersion} in .mise.toml`);\n process.exit(1);\n}\n\nif (packageJson.packageManager !== `pnpm@${expectedPnpmVersion}`) {\n console.error(`Generated app package must pin pnpm@${expectedPnpmVersion}`);\n process.exit(1);\n}\n\nif (packageJson.engines?.pnpm !== `>=${expectedPnpmVersion} <11.6.0`) {\n console.error(`Generated app package must require pnpm >=${expectedPnpmVersion} <11.6.0`);\n process.exit(1);\n}\n\nif (packageJson.pnpm !== undefined) {\n console.error('Generated app must keep pnpm policy in pnpm-workspace.yaml, not package.json');\n process.exit(1);\n}\n\nif (readPnpmConfig('minimumReleaseAge') !== 1440) {\n console.error('pnpm minimumReleaseAge must be 1440');\n process.exit(1);\n}\nif (readPnpmConfig('minimumReleaseAgeStrict') !== true) {\n console.error('pnpm minimumReleaseAgeStrict must be true');\n process.exit(1);\n}\nif (readPnpmConfig('minimumReleaseAgeIgnoreMissingTime') !== false) {\n console.error('pnpm minimumReleaseAgeIgnoreMissingTime must be false');\n process.exit(1);\n}\nconst expectedMinimumReleaseAgeExcludes = [\n '@bleedingdev/modern-js-*',\n '@tanstack/react-router',\n '@tanstack/router-core',\n '@typescript/native-preview',\n '@typescript/native-preview-*',\n '@types/react',\n];\nif (\n JSON.stringify(readPnpmConfig('minimumReleaseAgeExclude')) !==\n JSON.stringify(expectedMinimumReleaseAgeExcludes)\n) {\n console.error('pnpm minimumReleaseAgeExclude must allow only approved latest-lane package cohorts');\n process.exit(1);\n}\nif (readPnpmConfig('trustPolicy') !== 'no-downgrade') {\n console.error('pnpm trustPolicy must be no-downgrade');\n process.exit(1);\n}\nfor (const [key, expected] of [\n ['trustPolicyIgnoreAfter', 1440],\n ['blockExoticSubdeps', true],\n ['engineStrict', true],\n ['pmOnFail', 'error'],\n ['verifyDepsBeforeRun', 'error'],\n ['strictDepBuilds', true],\n]) {\n if (readPnpmConfig(key) !== expected) {\n console.error(`pnpm ${key} must be ${String(expected)}`);\n process.exit(1);\n }\n}\nif (\n JSON.stringify(readPnpmConfig('allowBuilds')) !==\n JSON.stringify({\n '@swc/core': true,\n 'core-js': true,\n esbuild: true,\n lefthook: true,\n 'msgpackr-extract': true,\n sharp: true,\n workerd: true,\n })\n) {\n console.error('pnpm allowBuilds must approve only the generated app build dependencies');\n process.exit(1);\n}\nif (\n JSON.stringify(readPnpmConfig('onlyBuiltDependencies')) !==\n JSON.stringify(['@swc/core', 'core-js', 'esbuild', 'lefthook', 'msgpackr-extract', 'sharp', 'workerd'])\n) {\n console.error('pnpm onlyBuiltDependencies must approve only the generated app build dependencies');\n process.exit(1);\n}\n\nif (packageJson.modernjs?.preset !== 'presetUltramodern') {\n console.error('package.json must declare presetUltramodern metadata');\n process.exit(1);\n}\n\nif (\n packageJson.modernjs?.packageSource?.config !== './.modernjs/ultramodern-package-source.json'\n) {\n console.error('package.json must retain package source metadata location');\n process.exit(1);\n}\n\nif (packageJson.modernjs?.packageSource?.strategy !== packageSource.strategy) {\n console.error('package.json package source strategy must match package source metadata');\n process.exit(1);\n}\n\nif (packageSource.schemaVersion !== 1) {\n console.error('Package source metadata must use schemaVersion 1');\n process.exit(1);\n}\n\nif (packageSource.preset !== 'presetUltramodern') {\n console.error('Package source metadata must declare presetUltramodern');\n process.exit(1);\n}\n\nif (packageSource.strategy !== 'workspace' && packageSource.strategy !== 'install') {\n console.error('Package source strategy must be workspace or install');\n process.exit(1);\n}\n\nconst declaredModernPackages = packageSource.modernPackages?.packages;\nif (!Array.isArray(declaredModernPackages) || declaredModernPackages.length === 0) {\n console.error('Package source metadata must declare the generated Modern package cohort');\n process.exit(1);\n}\n\nconst invalidModernPackages = declaredModernPackages.filter(\n (packageName) => typeof packageName !== 'string' || !packageName.startsWith('@modern-js/'),\n);\nif (invalidModernPackages.length > 0) {\n console.error(`Package source metadata contains invalid Modern packages: ${invalidModernPackages.join(', ')}`);\n process.exit(1);\n}\n\nconst packageJsonModernDependencies = [\n ...new Set(\n ['dependencies', 'devDependencies']\n .flatMap((section) => Object.keys(packageJson[section] ?? {}))\n .filter((packageName) => packageName.startsWith('@modern-js/')),\n ),\n];\nconst missingMetadataPackages = packageJsonModernDependencies.filter(\n (packageName) => !declaredModernPackages.includes(packageName),\n);\nif (missingMetadataPackages.length > 0) {\n console.error(`Package source metadata must include package.json Modern dependencies: ${missingMetadataPackages.join(', ')}`);\n process.exit(1);\n}\n\nconst expectedModernSpecifier = packageSource.modernPackages?.specifier;\nif (typeof expectedModernSpecifier !== 'string' || expectedModernSpecifier.length === 0) {\n console.error('Package source metadata must provide a Modern package specifier');\n process.exit(1);\n}\nif (\n packageSource.strategy === 'install' &&\n expectedModernSpecifier !== templateManifest.template?.version\n) {\n console.error(\n `Package source Modern specifier ${expectedModernSpecifier} must match template version ${templateManifest.template?.version}`,\n );\n process.exit(1);\n}\n\nconst expectedModernDependency = (packageName) => {\n const alias = packageSource.modernPackages?.aliases?.[packageName];\n return typeof alias === 'string'\n ? `npm:${alias}@${expectedModernSpecifier}`\n : expectedModernSpecifier;\n};\n\nfor (const section of ['dependencies', 'devDependencies']) {\n for (const packageName of declaredModernPackages) {\n if (\n packageJson[section]?.[packageName] &&\n packageJson[section][packageName] !== expectedModernDependency(packageName)\n ) {\n console.error(`${section}.${packageName} must match package source metadata`);\n process.exit(1);\n }\n }\n}\n\nif (\n packageJson.devDependencies?.['@modern-js/create'] !==\n expectedModernDependency('@modern-js/create')\n) {\n console.error('devDependencies.@modern-js/create must match package source metadata');\n process.exit(1);\n}\n\nfor (const dependency of ['@modern-js/plugin-i18n', 'i18next', 'react-i18next']) {\n if (!packageJson.dependencies?.[dependency]) {\n console.error(`Missing dependency: ${dependency}`);\n process.exit(1);\n }\n}\n\nfor (const dependency of [\n '@effect/tsgo',\n '@modern-js/adapter-rstest',\n '@modern-js/code-tools',\n '@modern-js/create',\n '@rstest/core',\n '@typescript/native-preview',\n 'happy-dom',\n\n '@tailwindcss/postcss',\n 'postcss',\n 'tailwindcss',\n\n 'oxlint',\n 'oxfmt',\n 'ultracite',\n\n 'lefthook',\n\n]) {\n if (!packageJson.devDependencies?.[dependency]) {\n console.error(`Missing devDependency: ${dependency}`);\n process.exit(1);\n }\n}\n\n\nif (\n packageJson.devDependencies?.tailwindcss !== '^4.3.0' ||\n packageJson.devDependencies?.['@tailwindcss/postcss'] !== '^4.3.0'\n) {\n console.error('Tailwind CSS dependencies must use the UltraModern default baseline');\n process.exit(1);\n}\n\n\n\n\nconst privateSource = skillsLock.sources?.find(\n (source) => source.repository === 'https://github.com/TechsioCZ/skills',\n);\nconst privateSkills = new Set(privateSource?.baseline?.map((skill) => skill.name));\nfor (const skillName of ['plan-graph', 'dag', 'subagent-graph', 'helm', 'debugger-mode']) {\n if (!privateSkills.has(skillName)) {\n console.error(`Missing private skill allowlist entry: ${skillName}`);\n process.exit(1);\n }\n}\n\n\nconsole.log('Ultramodern contract check passed.');\n",
|
|
56
|
-
"tests/tsconfig.json": "{\n \"extends\": \"../tsconfig.json\",\n \"compilerOptions\": {\n \"types\": [\"@rstest/core/globals\"]\n },\n \"include\": [\"./\"]\n}\n",
|
|
57
|
-
"
|
|
58
|
-
"
|
|
59
|
-
"
|
|
60
|
-
"
|
|
61
|
-
".github/renovate.json": "{\n \"$schema\": \"https://docs.renovatebot.com/renovate-schema.json\",\n \"extends\": [\n \"config:recommended\",\n \"helpers:pinGitHubActionDigests\"\n ],\n \"dependencyDashboard\": true,\n \"minimumReleaseAge\": \"1 day\",\n \"prConcurrentLimit\": 5,\n \"prHourlyLimit\": 2,\n \"rangeStrategy\": \"bump\",\n \"schedule\": [\n \"before 5am on monday\"\n ],\n \"timezone\": \"Etc/UTC\",\n \"packageRules\": [\n {\n \"matchManagers\": [\n \"github-actions\"\n ],\n \"groupName\": \"github-actions\",\n \"labels\": [\n \"dependencies\",\n \"github-actions\",\n \"security\"\n ]\n },\n {\n \"matchManagers\": [\n \"npm\"\n ],\n \"matchUpdateTypes\": [\n \"patch\",\n \"minor\"\n ],\n \"groupName\": \"npm minor and patch updates\",\n \"labels\": [\n \"dependencies\",\n \"npm\"\n ]\n },\n {\n \"matchUpdateTypes\": [\n \"major\"\n ],\n \"dependencyDashboardApproval\": true,\n \"labels\": [\n \"dependencies\",\n \"major\"\n ]\n }\n ]\n}\n",
|
|
62
|
-
".
|
|
63
|
-
"
|
|
64
|
-
"
|
|
65
|
-
"
|
|
66
|
-
"
|
|
67
|
-
"
|
|
68
|
-
"
|
|
69
|
-
"
|
|
70
|
-
"
|
|
71
|
-
"config/public/locales/cs/translation.json": '{\n "home": {\n "bff": {\n "response": "Odpoved Effect HttpApi:"\n },\n "cards": {\n "bff": {\n "body": "Pridej serverovou logiku, kdyz route potrebuje typovana data nebo mutace.",\n "title": "BFF + Effect"\n },\n "config": {\n "body": "Upravuj vychozi hodnoty v modern.config.ts podle rustu aplikace.",\n "title": "Konfigurace presetUltramodern"\n },\n "gates": {\n "body": "Pred releasem spust ultramodern:check, testy, typecheck, lint a build.",\n "title": "Ultramodern kontroly"\n },\n "guide": {\n "body": "Zacni jednou aplikaci a pridej routy, API nebo balicky az kdyz pomuzou.",\n "title": "UltraModern.js pruvodce"\n }\n },\n "description": {\n "afterConfig": "podle rustu aplikace a udrzuj",\n "afterPreset": "profilem. Lad",\n "end": "zelene pri pridavani rout, API a workspace balicku.",\n "intro": "Zacni s verejnym"\n },\n "language": {\n "cs": "Cestina",\n "en": "Anglictina",\n "switcher": "Jazyk"\n },\n "logoAlt": "Logo UltraModern.js",\n "meta": {\n "description": "Lokalizovany starter aplikace UltraModern.js se silnymi vychozimi hodnotami pro komplexni produkty.",\n "title": "UltraModern.js Starter"\n },\n "name": "Jednoduchy starter aplikace",\n "skipLink": "Preskocit na obsah",\n "title": "UltraModern.js Starter"\n }\n}\n'
|
|
37
|
+
".gitignore": "node_modules/\ndist/\nbuild/\n.modernjs/cache/\n.modernjs/agent-reference-repos-tmp/\n",
|
|
38
|
+
"AGENTS.md": "# UltraModern Agent Contract\n\nThis workspace is generated as an agent-ready UltraModern.js SuperApp shell.\nAgents should treat the files under `.agents/skills` as local project\ninstructions, not optional reading.\n\n## Quality Gates\n\n- `pnpm lint` runs Oxlint with the Ultracite preset.\n- `pnpm format` runs oxfmt.\n- `pnpm typecheck` runs effect-tsgo as the TypeScript checker.\n- `pnpm i18n:boundaries` verifies workspace source boundaries through `@modern-js/code-tools`.\n- `pnpm contract:check` verifies the generated workspace contract.\n- `pnpm mf:types` verifies Module Federation type outputs after builds.\n- `pnpm check` is a local convenience aggregate for the primitive gates.\n- Generated CI runs primitive gates as separate matrix jobs instead of calling `pnpm check`.\n- Generated Codex stop hooks and subagent-stop hooks run `pnpm format && pnpm lint:fix && pnpm check`.\n- `postinstall` formats the generated tree, initializes Git when needed, installs agent skills and reference repos, then installs `lefthook`. Generated `lefthook.yml` runs separate format and lint-fix commands on pre-commit; pre-push runs read-only primitive gates in parallel.\n\n## Localized Routes\n\nGenerated apps keep locale-prefixed entry routes under `src/routes/[lang]`,\nstatic language links, and canonical plus `hreflang` metadata. A new workspace\nstarts shell-only; `create <domain> --vertical` adds route-owned metadata,\nlocalized resources, and Effect BFF surfaces for that domain. Runtime i18n is\nnot enabled in the starter because the current React 19 + Module Federation\nstreaming SSR stack must render predictably first. Production builds fail unless\n`MODERN_PUBLIC_SITE_URL` is set per deployed app, so canonical URLs always use\nthe production origin.\n\n## Required Skill Baseline\n\nUse these skills when the task touches the matching subsystem:\n\n- `rsbuild-best-practices`: Modern.js app build configuration, Rsbuild options, assets, type checking, and build debugging.\n- `rspack-best-practices`: Rspack-level bundling, CSS, assets, profiling, and production build behavior.\n- `rspack-tracing`: Rspack build failures, slow builds, crash localization, and trace analysis.\n- `rsdoctor-analysis`: Evidence-based bundle analysis from `rsdoctor-data.json`, including duplicate packages, large chunks, and retained modules.\n- `rslib-best-practices`: Shared packages, generated libraries, declaration output, and Rslib configuration.\n- `rslib-modern-package`: Package contracts for shared libraries, exports, side effects, dependency placement, README, and release readiness.\n- `rstest-best-practices`: Rstest configuration, test writing, mocking, snapshots, coverage, and CI test behavior.\n- `mf`: Module Federation docs, Modern.js integration, DTS/type checks, shared dependency checks, runtime errors, and observability troubleshooting.\n\nThe public `module-federation/agent-skills` repository is installed during `pnpm install` and `pnpm skills:install`. `pnpm skills:check` fails when the required public `mf` skill is missing.\n\n## Private Skills\n\nScriptedAlchemy/TechsioCZ skills are private and are cloned only when the current developer is authorized for `TechsioCZ/skills`.\n\n```bash\npnpm skills:install\n```\n\nThe installer copies only the pinned private skills from `.agents/skills-lock.json`: `plan-graph`, `dag`, `subagent-graph`, `helm`, and `debugger-mode`.\n\n## Agent Reference Repositories\n\nThe workspace installs read-only source references under `repos/` by default during `pnpm install` using `git subtree add --squash`. These repositories are reference material for coding agents, not application source:\n\n- `repos/effect` from `Effect-TS/effect`.\n- `repos/ultramodern.js` from `BleedingDev/ultramodern.js`.\n\nAgents may read files under `repos/` to understand upstream patterns, APIs, and project conventions. Do not edit files under `repos/`, import from them, or make production code depend on them. To skip this setup, run installs with `ULTRAMODERN_SKIP_AGENT_REPOS=1`.\n\n## Project Priorities\n\n- Keep `presetUltramodern` as the single preset.\n- Keep the initial workspace shell-only unless a user explicitly asks for a\n starter vertical.\n- Use `create <domain> --vertical` as the growth path for real business\n MicroVerticals.\n- Prefer Effect for BFF code.\n- Prefer TanStack Router for app routing.\n- Keep UI-kit or design-system code as ordinary vertical or shared package code, not a special core path.\n- Keep generated packages explicit and publishable: stable `exports`, correct declarations, small public APIs, and clear ownership metadata.\n- Do not add migration tooling or codemods unless the project owner explicitly asks for migration work.\n\n## Skill Provenance\n\nThe vendored Rstack skills, public Module Federation skill, and private TechsioCZ skill set are pinned in `.agents/skills-lock.json`. Do not update, remove, or replace them casually. If a skill needs updating, update the lock file and run the affected primitive gate plus `pnpm check`.\n",
|
|
39
|
+
"README.md": "# modern-app\n\nGenerated UltraModern SuperApp workspace.\n\nThis workspace keeps `presetUltramodern(...)` as the single public\nUltraModern.js 3.0 SuperApp surface and starts with an explicit shell:\n\n- `apps/shell-super-app` owns shell route assembly, Module Federation host\n wiring, shared SSR/i18n runtime setup, and the boundary debugger.\n- `packages/shared-*` provide placeholders for cross-workspace contracts,\n design tokens, and Effect API sharing.\n- `verticals/*` is intentionally empty until a real business domain is added.\n\nAdd a full-stack MicroVertical when the product needs one:\n\n```bash\npnpm dlx @bleedingdev/modern-js-create transportation --vertical\npnpm dlx @bleedingdev/modern-js-create payments --vertical\n```\n\nEach added vertical owns its UI/routes, browser-safe Module Federation exposes,\nprivate-first route metadata, localized URLs, public-route opt-ins, CSS prefix,\nEffect BFF handlers, local API contract, and typed client surface. Server\nhandlers and Effect client/contract modules stay out of browser exposes.\n\n## Private-First Public Surfaces\n\nGenerated app routes are private and non-indexable by default. Private app,\nauth, tenant, dashboard, and internal routes publish no discovery output unless\nroute metadata explicitly marks them `public && indexable`. The default scaffold\ntherefore emits only a disallowing `robots.txt`; sitemap, web manifest,\n`llms.txt`, API catalog, security.txt, and JSON-LD output stay omitted until a\nsafe public route or public docs/help/product surface exists.\n\nRun the scaffold validator before adding business code and after every\n`--vertical` mutation:\n\n```bash\nmise install\npnpm install\npnpm check\npnpm build\n```\n\nGenerated CI does not call the local aggregate. It runs format, lint,\ntypecheck, skills, i18n boundary validation, contract validation, and build as\nseparate matrix jobs so failures are isolated and parallelizable.\n\nBy default, `pnpm install` also prepares read-only agent reference repositories\nunder `repos/` for Effect and UltraModern.js source lookup using squashed git\nsubtrees. Disable this setup with\n`ULTRAMODERN_SKIP_AGENT_REPOS=1 pnpm install`, or rerun it\nexplicitly with `pnpm agents:refs:install`.\n\nThe topology and ownership metadata are generated under `topology/`. The\nworkspace also ships `.github/workflows/ultramodern-workspace-gates.yml` and\n`.github/renovate.json` with read-only workflow permissions, commit-pinned\nactions, frozen installs, StepSecurity audit-mode runner hardening, dependency\ndashboard review, one-day release age, grouped updates, and manual approval for\nmajor upgrades.\n\nPackage source metadata is generated at\n`.modernjs/ultramodern-package-source.json`. The default strategy keeps\nUltraModern.js runtime and tooling packages on `workspace:*` for monorepo\ndevelopment. To create a workspace that can install those packages outside the\nmonorepo, generate with `--ultramodern-package-source install`; generated shared\npackages still use `workspace:*` because they are part of this workspace.\n\n## Cloudflare Proof\n\nDeploy the generated apps, then pass each deployed app's generated public URL\nenv key into the proof step. A shell-only workspace only needs the shell URL;\nadded verticals use the same `ULTRAMODERN_PUBLIC_URL_<APP_ID>` pattern with\nhyphens converted to underscores and uppercased.\n\n```bash\npnpm cloudflare:deploy\nULTRAMODERN_PUBLIC_URL_SHELL_SUPER_APP=https://shell-super-app.example.workers.dev \\\npnpm cloudflare:proof -- --require-public-urls\n```\n\n## Troubleshooting\n\n| Symptom | Current check | Owner |\n| --- | --- | --- |\n| Package cohort mismatch | Regenerate with one package source strategy, run `mise install`, then rerun `pnpm install` from the activated shell. | Generated workspace package source metadata |\n| Install failure | Check the active Node/pnpm from `mise install`; rerun `pnpm install` after the shell sees the pinned versions. | Toolchain setup |\n| Build failure | Run the matching primitive gate (`pnpm lint`, `pnpm typecheck`, `pnpm i18n:boundaries`, `pnpm contract:check`) before `pnpm build`; fix the owning failure first. | Owning package or generated contract |\n| Missing public URL | Set the env key from `.modernjs/ultramodern-generated-contract.json`, for example `ULTRAMODERN_PUBLIC_URL_SHELL_SUPER_APP`. | Deployment operator |\n| Cloudflare credentials | Confirm Wrangler credentials before `pnpm cloudflare:deploy`; local checks do not prove live Worker access. | Deployment operator |\n| Asset or CSS 404 | Rebuild with `pnpm build` or `pnpm cloudflare:deploy` and inspect emitted Modern/Rspack asset paths instead of hardcoding CSS URLs. | Framework/runtime asset pipeline |\n| Federation manifest failure | Run the shell and vertical build scripts, then check each deployed `/mf-manifest.json` URL used by the shell. | Module Federation owner |\n",
|
|
40
|
+
"lefthook.yml": "pre-commit:\n commands:\n format:\n run: pnpm format\n stage_fixed: true\n lint-fix:\n run: pnpm lint:fix\n stage_fixed: true\n\npre-push:\n parallel: true\n commands:\n format:\n run: pnpm format:check\n lint:\n run: pnpm lint\n typecheck:\n run: pnpm typecheck\n skills:\n run: pnpm skills:check\n i18n-boundaries:\n run: pnpm i18n:boundaries\n contract:\n run: pnpm contract:check\n",
|
|
41
|
+
"oxfmt.config.ts": "import { defineConfig } from 'oxfmt';\nimport ultracite from 'ultracite/oxfmt';\n\nexport default defineConfig({\n extends: [ultracite],\n ignorePatterns: [\n '.agents',\n '**/*.json',\n 'dist',\n 'node_modules',\n 'repos/**',\n '.modern',\n '.modernjs',\n '**/routeTree.gen.ts',\n ],\n singleQuote: true,\n});\n",
|
|
42
|
+
"oxlint.config.ts": "import { defineConfig } from 'oxlint';\nimport core from 'ultracite/oxlint/core';\nimport react from 'ultracite/oxlint/react';\n\nexport default defineConfig({\n env: {\n browser: true,\n node: true,\n },\n extends: [core, react],\n ignorePatterns: [\n '.agents',\n 'dist',\n 'node_modules',\n 'repos/**',\n '.modern',\n '.modernjs',\n '**/routeTree.gen.ts',\n ],\n});\n",
|
|
43
|
+
"pnpm-workspace.yaml": "packages:\n - apps/*\n - verticals/*\n - packages/*\n\nminimumReleaseAge: 1440\nminimumReleaseAgeStrict: true\nminimumReleaseAgeIgnoreMissingTime: false\nminimumReleaseAgeExclude:\n - '@bleedingdev/modern-js-*'\n - '@tanstack/react-router'\n - '@tanstack/router-core'\n - '@typescript/native-preview'\n - '@typescript/native-preview-*'\n - '@types/react'\ntrustPolicy: no-downgrade\ntrustPolicyIgnoreAfter: 1440\nblockExoticSubdeps: true\nengineStrict: true\npmOnFail: error\nverifyDepsBeforeRun: error\nstrictDepBuilds: true\n\npeerDependencyRules:\n allowedVersions:\n react: '>=19.0.0'\n typescript: '>=6.0.0'\n\noverrides:\n '@tanstack/react-router': 1.170.15\n node-fetch: '^3.3.2'\n\nallowBuilds:\n '@swc/core': true\n core-js: true\n esbuild: true\n lefthook: true\n msgpackr-extract: true\n sharp: true\n workerd: true\n",
|
|
44
|
+
".codex/hooks.json": "{\n \"Stop\": [\n {\n \"command\": \"pnpm format && pnpm lint:fix && pnpm check\",\n \"timeout\": 600000,\n \"statusMessage\": \"Running UltraModern quality gates\"\n }\n ],\n \"SubagentStop\": [\n {\n \"command\": \"pnpm format && pnpm lint:fix && pnpm check\",\n \"timeout\": 600000,\n \"statusMessage\": \"Running UltraModern quality gates\"\n }\n ]\n}\n",
|
|
45
|
+
"scripts/bootstrap-agent-skills.mjs": "import { execFileSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nconst root = process.cwd();\nconst lockPath = path.join(root, '.agents/skills-lock.json');\nconst checkOnly = process.argv.includes('--check');\nconst force = process.argv.includes('--force');\n\nconst readJson = filePath => JSON.parse(fs.readFileSync(filePath, 'utf-8'));\n\nconst run = (command, args, options = {}) =>\n execFileSync(command, args, {\n cwd: options.cwd ?? root,\n encoding: 'utf-8',\n stdio: options.stdio ?? ['ignore', 'pipe', 'pipe'],\n });\n\nconst commandExists = command => {\n try {\n run(command, ['--version'], { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n};\n\nconst runShell = script =>\n run('sh', ['-lc', script], {\n stdio: 'inherit',\n });\n\nconst installGit = () => {\n if (commandExists('git')) {\n return;\n }\n\n if (commandExists('brew')) {\n run('brew', ['install', 'git'], { stdio: 'inherit' });\n } else if (process.platform === 'linux' && commandExists('apt-get')) {\n const sudo =\n typeof process.getuid === 'function' && process.getuid() === 0\n ? ''\n : 'sudo ';\n runShell(`${sudo}apt-get update && ${sudo}apt-get install -y git`);\n } else if (process.platform === 'linux' && commandExists('dnf')) {\n const sudo =\n typeof process.getuid === 'function' && process.getuid() === 0\n ? ''\n : 'sudo ';\n runShell(`${sudo}dnf install -y git`);\n } else if (process.platform === 'linux' && commandExists('yum')) {\n const sudo =\n typeof process.getuid === 'function' && process.getuid() === 0\n ? ''\n : 'sudo ';\n runShell(`${sudo}yum install -y git`);\n } else if (process.platform === 'linux' && commandExists('apk')) {\n runShell('apk add --no-cache git');\n }\n\n if (!commandExists('git')) {\n throw new Error(\n 'Git is required for UltraModern setup. Install git and run pnpm skills:install again.',\n );\n }\n};\n\nconst isInsideGitWorkTree = () => {\n try {\n return run('git', ['rev-parse', '--is-inside-work-tree']).trim() === 'true';\n } catch {\n return false;\n }\n};\n\nconst initializeGitRepository = () => {\n if (isInsideGitWorkTree()) {\n return;\n }\n\n try {\n run('git', ['init', '-b', 'main'], { stdio: 'inherit' });\n } catch {\n run('git', ['init'], { stdio: 'inherit' });\n run('git', ['branch', '-M', 'main'], { stdio: 'inherit' });\n }\n};\n\nconst installLefthook = () => {\n try {\n run('lefthook', ['install'], { stdio: 'inherit' });\n } catch (error) {\n console.warn(`Unable to install lefthook hooks: ${error.message}`);\n }\n};\n\nconst removeTree = dir =>\n fs.rmSync(dir, {\n force: true,\n maxRetries: 5,\n recursive: true,\n retryDelay: 100,\n });\n\nconst cloneSource = (source, targetDir) => {\n if (source.commit) {\n run('git', ['init', targetDir]);\n run('git', ['remote', 'add', 'origin', source.repository], {\n cwd: targetDir,\n });\n run('git', ['fetch', '--depth', '1', '--quiet', 'origin', source.commit], {\n cwd: targetDir,\n });\n run(\n 'git',\n [\n '-c',\n 'advice.detachedHead=false',\n 'checkout',\n '--detach',\n '--quiet',\n 'FETCH_HEAD',\n ],\n { cwd: targetDir },\n );\n return;\n }\n\n const repo = source.repository.replace(/^https:\\/\\/github.com\\//u, '');\n try {\n run('gh', [\n 'repo',\n 'clone',\n repo,\n targetDir,\n '--',\n '--depth',\n '1',\n '--quiet',\n ]);\n } catch {\n run('git', [\n 'clone',\n '--depth',\n '1',\n '--quiet',\n source.repository,\n targetDir,\n ]);\n }\n};\n\nconst resolveSkillDir = (sourceRoot, skillName) => {\n const candidates = [\n path.join(sourceRoot, skillName),\n path.join(sourceRoot, 'skills', skillName),\n path.join(sourceRoot, 'skills', 'engineering', skillName),\n path.join(sourceRoot, 'skills', 'productivity', skillName),\n ];\n return candidates.find(candidate =>\n fs.existsSync(path.join(candidate, 'SKILL.md')),\n );\n};\n\nif (!fs.existsSync(lockPath)) {\n console.error('Missing .agents/skills-lock.json');\n process.exit(1);\n}\n\nconst lock = readJson(lockPath);\nconst installDir = path.join(root, lock.installDir ?? '.agents/skills');\nconst sources = lock.sources ?? [];\nconst requiredCloneSources = sources.filter(\n source => source.install === 'clone',\n);\nconst optionalCloneSources = sources.filter(\n source => source.install === 'clone-if-authorized',\n);\nconst requiredSkills = [\n ...(lock.baseline ?? []),\n ...requiredCloneSources.flatMap(source => source.baseline ?? []),\n].filter(\n (skill, index, skills) =>\n skills.findIndex(candidate => candidate.name === skill.name) === index,\n);\n\nif (checkOnly) {\n const missingRequired = requiredSkills\n .map(skill => skill.name)\n .filter(\n skillName => !fs.existsSync(path.join(installDir, skillName, 'SKILL.md')),\n );\n const missingOptional = optionalCloneSources.flatMap(source =>\n (source.baseline ?? [])\n .map(skill => skill.name)\n .filter(\n skillName =>\n !fs.existsSync(path.join(installDir, skillName, 'SKILL.md')),\n ),\n );\n\n if (missingRequired.length > 0) {\n console.error(\n `Required agent skills not installed: ${missingRequired.join(', ')}. Run pnpm skills:install.`,\n );\n process.exit(1);\n }\n\n if (missingOptional.length > 0) {\n console.warn(\n `Private skills not installed: ${missingOptional.join(', ')}. Run pnpm skills:install if you have access.`,\n );\n } else {\n console.log('Required and private agent skills are installed.');\n process.exit(0);\n }\n console.log('Required agent skills are installed.');\n process.exit(0);\n}\n\nfs.mkdirSync(installDir, { recursive: true });\ninstallGit();\ninitializeGitRepository();\n\nfor (const source of [...requiredCloneSources, ...optionalCloneSources]) {\n const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ultramodern-skills-'));\n try {\n try {\n cloneSource(source, tempDir);\n } catch (error) {\n if (source.install === 'clone-if-authorized') {\n console.warn(\n `Skipping ${source.repository}; current developer may not have access.`,\n );\n continue;\n }\n throw error;\n }\n for (const skill of source.baseline ?? []) {\n const sourceSkillDir = resolveSkillDir(tempDir, skill.name);\n if (!sourceSkillDir) {\n throw new Error(\n `Skill ${skill.name} not found in ${source.repository}`,\n );\n }\n const targetSkillDir = path.join(installDir, skill.name);\n if (fs.existsSync(targetSkillDir)) {\n if (!force) {\n console.log(`Skipping existing ${skill.name}`);\n continue;\n }\n removeTree(targetSkillDir);\n }\n fs.cpSync(sourceSkillDir, targetSkillDir, { recursive: true });\n console.log(`Installed ${skill.name}`);\n }\n } finally {\n removeTree(tempDir);\n }\n}\n\ninstallLefthook();\n",
|
|
46
|
+
"scripts/setup-agent-reference-repos.mjs": "import { spawnSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nconst root = process.cwd();\nconst args = new Set(process.argv.slice(2));\nconst checkOnly = args.has('--check');\nconst configPath = path.join(root, '.agents', 'agent-reference-repos.json');\nconst manifestPath = path.join(root, '.modernjs', 'agent-reference-repos.json');\n\nconst truthy = value => /^(1|true|yes|on)$/i.test(String(value ?? ''));\nconst falsy = value => /^(0|false|no|off)$/i.test(String(value ?? ''));\n\nconst skipRequested =\n truthy(process.env.ULTRAMODERN_SKIP_AGENT_REPOS) ||\n falsy(process.env.ULTRAMODERN_AGENT_REPOS);\nconst required = truthy(process.env.ULTRAMODERN_AGENT_REPOS_REQUIRED);\nconst refresh = truthy(process.env.ULTRAMODERN_AGENT_REPOS_REFRESH);\n\nconst gitIdentityEnv = {\n GIT_AUTHOR_NAME:\n process.env.GIT_AUTHOR_NAME || 'UltraModern Agent Reference Setup',\n GIT_AUTHOR_EMAIL:\n process.env.GIT_AUTHOR_EMAIL || 'ultramodern-agent-refs@local',\n GIT_COMMITTER_NAME:\n process.env.GIT_COMMITTER_NAME || 'UltraModern Agent Reference Setup',\n GIT_COMMITTER_EMAIL:\n process.env.GIT_COMMITTER_EMAIL || 'ultramodern-agent-refs@local',\n};\n\nconst log = message => console.log(`[agent-reference-repos] ${message}`);\nconst warn = message => console.warn(`[agent-reference-repos] ${message}`);\n\nfunction fail(message) {\n if (required || checkOnly) {\n throw new Error(message);\n }\n warn(message);\n}\n\nfunction readJson(filePath) {\n return JSON.parse(fs.readFileSync(filePath, 'utf-8'));\n}\n\nfunction run(command, commandArgs, options = {}) {\n const result = spawnSync(command, commandArgs, {\n cwd: options.cwd ?? root,\n encoding: 'utf-8',\n env: {\n ...process.env,\n ...gitIdentityEnv,\n ...(options.env ?? {}),\n },\n stdio: options.stdio ?? ['ignore', 'pipe', 'pipe'],\n timeout: options.timeout ?? 120000,\n });\n\n if (result.error) {\n throw result.error;\n }\n if (result.status !== 0) {\n const stderr = result.stderr?.trim();\n throw new Error(\n `${command} ${commandArgs.join(' ')} failed${\n stderr ? `: ${stderr}` : ''\n }`,\n );\n }\n return result.stdout?.trim() ?? '';\n}\n\nfunction assertSafeRepoPath(relativePath) {\n if (\n typeof relativePath !== 'string' ||\n relativePath.length === 0 ||\n path.isAbsolute(relativePath) ||\n relativePath.split(/[\\\\/]+/).includes('..') ||\n !relativePath.startsWith('repos/')\n ) {\n throw new Error(`Unsafe reference repository path: ${relativePath}`);\n }\n}\n\nfunction hasGit() {\n const result = spawnSync('git', ['--version'], {\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n return result.status === 0;\n}\n\nfunction hasGitSubtree() {\n const result = spawnSync('git', ['subtree', '-h'], {\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n return (\n (result.status === 0 || result.status === 129) &&\n result.stdout.includes('usage: git subtree')\n );\n}\n\nfunction isGitWorkTree() {\n const result = spawnSync('git', ['rev-parse', '--is-inside-work-tree'], {\n cwd: root,\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n return result.status === 0 && result.stdout.trim() === 'true';\n}\n\nfunction hasCommits() {\n const result = spawnSync('git', ['rev-parse', '--verify', 'HEAD'], {\n cwd: root,\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n return result.status === 0;\n}\n\nfunction porcelainStatus() {\n return run('git', ['status', '--porcelain'], { timeout: 30000 });\n}\n\nfunction commitInstallerChanges(message) {\n run('git', ['commit', '--no-verify', '-m', message], {\n timeout: 120000,\n });\n}\n\nfunction ensureGitRepository() {\n if (!isGitWorkTree()) {\n if (checkOnly) {\n fail('workspace is not a git repository');\n return false;\n }\n log('initializing git repository for agent reference subtrees');\n run('git', ['init'], { timeout: 30000 });\n }\n\n if (!hasCommits()) {\n if (checkOnly) {\n fail('workspace has no initial git commit');\n return false;\n }\n log('creating initial workspace commit before adding reference subtrees');\n run('git', ['add', '-A'], { timeout: 30000 });\n commitInstallerChanges('Initialize UltraModern workspace');\n return true;\n }\n\n const status = porcelainStatus();\n if (status) {\n fail(\n 'workspace has uncommitted changes; commit or stash them before installing reference subtrees',\n );\n return false;\n }\n\n return true;\n}\n\nfunction remoteCommit(repo) {\n let output = run('git', ['ls-remote', repo.url, `refs/heads/${repo.ref}`], {\n timeout: 120000,\n });\n if (!output) {\n output = run('git', ['ls-remote', repo.url, repo.ref], {\n timeout: 120000,\n });\n }\n const [commit] = output.split(/\\s+/);\n if (!/^[a-f0-9]{40}$/i.test(commit ?? '')) {\n throw new Error(`Could not resolve ${repo.url}#${repo.ref}`);\n }\n return commit;\n}\n\nfunction subtreeCommitExists(repo) {\n const result = spawnSync(\n 'git',\n [\n 'log',\n '--grep',\n `git-subtree-dir: ${repo.path}`,\n '--format=%H',\n '-n',\n '1',\n ],\n {\n cwd: root,\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'pipe'],\n },\n );\n return result.status === 0 && result.stdout.trim().length > 0;\n}\n\nfunction installedManifestEntry(repo) {\n if (!fs.existsSync(manifestPath)) {\n return undefined;\n }\n try {\n const manifest = readJson(manifestPath);\n return manifest.repositories?.find(entry => entry.id === repo.id);\n } catch {\n return undefined;\n }\n}\n\nfunction assertSubtreePresent(repo) {\n assertSafeRepoPath(repo.path);\n const targetPath = path.join(root, repo.path);\n if (!fs.existsSync(targetPath)) {\n fail(`${repo.path} is missing`);\n return undefined;\n }\n if (!subtreeCommitExists(repo)) {\n fail(`${repo.path} is present but has no git-subtree commit evidence`);\n return undefined;\n }\n return (\n installedManifestEntry(repo) ?? {\n id: repo.id,\n name: repo.name,\n url: repo.url,\n ref: repo.ref,\n path: repo.path,\n readOnly: repo.readOnly !== false,\n status: 'present',\n strategy: 'git-subtree-squash',\n }\n );\n}\n\nfunction addSubtree(repo) {\n assertSafeRepoPath(repo.path);\n const targetPath = path.join(root, repo.path);\n const existing = fs.existsSync(targetPath);\n\n if (existing && !refresh) {\n return assertSubtreePresent(repo);\n }\n\n if (existing && refresh) {\n fail(\n `${repo.path} already exists; refresh for subtree references is intentionally manual`,\n );\n return undefined;\n }\n\n if (checkOnly) {\n fail(`${repo.path} is missing`);\n return undefined;\n }\n\n const commit = remoteCommit(repo);\n log(`adding ${repo.name} as git subtree at ${repo.path} (${commit})`);\n run('git', ['fetch', '--depth', '1', repo.url, repo.ref], {\n timeout: 300000,\n });\n run(\n 'git',\n [\n 'subtree',\n 'add',\n '--prefix',\n repo.path,\n 'FETCH_HEAD',\n '--squash',\n '-m',\n `Add ${repo.name} agent reference repo`,\n ],\n { timeout: 600000 },\n );\n\n return {\n schemaVersion: 1,\n id: repo.id,\n name: repo.name,\n url: repo.url,\n ref: repo.ref,\n commit,\n path: repo.path,\n readOnly: repo.readOnly !== false,\n strategy: 'git-subtree-squash',\n status: 'installed',\n installedAt: new Date().toISOString(),\n };\n}\n\nfunction writeManifest(entries) {\n fs.mkdirSync(path.dirname(manifestPath), { recursive: true });\n fs.writeFileSync(\n manifestPath,\n `${JSON.stringify(\n {\n schemaVersion: 1,\n generatedAt: new Date().toISOString(),\n strategy: 'git-subtree-squash',\n installDir: 'repos',\n repositories: entries,\n },\n null,\n 2,\n )}\\n`,\n );\n}\n\nfunction commitManifestIfChanged() {\n const status = run('git', ['status', '--porcelain', '--', manifestPath], {\n timeout: 30000,\n });\n if (!status) {\n return;\n }\n run('git', ['add', manifestPath], { timeout: 30000 });\n commitInstallerChanges('Record agent reference repo manifest');\n}\n\nfunction main() {\n if (!fs.existsSync(configPath)) {\n fail('Missing .agents/agent-reference-repos.json');\n return;\n }\n\n const config = readJson(configPath);\n const enabled = config.defaultEnabled !== false && !skipRequested;\n\n if (!enabled) {\n log('setup skipped; set ULTRAMODERN_SKIP_AGENT_REPOS=0 to enable it again');\n return;\n }\n\n if (!hasGit()) {\n fail('git is required to install agent reference repositories');\n return;\n }\n if (!hasGitSubtree()) {\n fail('git subtree is required to install agent reference repositories');\n return;\n }\n if (!ensureGitRepository()) {\n return;\n }\n\n const entries = [];\n for (const repo of config.repositories ?? []) {\n const result = checkOnly ? assertSubtreePresent(repo) : addSubtree(repo);\n if (result) {\n entries.push(result);\n }\n }\n\n if (!checkOnly) {\n writeManifest(entries);\n commitManifestIfChanged();\n }\n}\n\ntry {\n main();\n} catch (error) {\n if (required || checkOnly) {\n console.error(`[agent-reference-repos] ${error.message}`);\n process.exitCode = 1;\n } else {\n warn(error.message);\n }\n}\n",
|
|
47
|
+
".github/renovate.json": "{\n \"$schema\": \"https://docs.renovatebot.com/renovate-schema.json\",\n \"extends\": [\"config:recommended\", \"helpers:pinGitHubActionDigests\"],\n \"dependencyDashboard\": true,\n \"minimumReleaseAge\": \"1 day\",\n \"prConcurrentLimit\": 5,\n \"prHourlyLimit\": 2,\n \"rangeStrategy\": \"bump\",\n \"schedule\": [\"before 5am on monday\"],\n \"timezone\": \"Etc/UTC\",\n \"packageRules\": [\n {\n \"matchManagers\": [\"github-actions\"],\n \"groupName\": \"github-actions\",\n \"labels\": [\"dependencies\", \"github-actions\", \"security\"]\n },\n {\n \"matchManagers\": [\"npm\"],\n \"matchUpdateTypes\": [\"patch\", \"minor\"],\n \"groupName\": \"npm minor and patch updates\",\n \"labels\": [\"dependencies\", \"npm\"]\n },\n {\n \"matchUpdateTypes\": [\"major\"],\n \"dependencyDashboardApproval\": true,\n \"labels\": [\"dependencies\", \"major\"]\n }\n ]\n}\n",
|
|
48
|
+
".github/workflows/ultramodern-workspace-gates.yml": "name: Ultramodern Workspace Gates\n\non:\n push:\n pull_request:\n\npermissions:\n contents: read\n\ndefaults:\n run:\n shell: bash\n\nenv:\n FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true\n\nconcurrency:\n group: ultramodern-workspace-gates-${{ github.workflow }}-${{ github.ref }}\n cancel-in-progress: true\n\njobs:\n workspace-gate:\n name: ${{ matrix.name }}\n runs-on: ubuntu-latest\n timeout-minutes: 30\n strategy:\n fail-fast: false\n matrix:\n include:\n - name: Format\n command: pnpm format:check\n - name: Lint\n command: pnpm lint\n - name: Typecheck\n command: pnpm typecheck\n - name: Skills\n command: pnpm skills:check\n - name: I18n Boundaries\n command: pnpm i18n:boundaries\n - name: Contract\n command: pnpm contract:check\n - name: Build\n command: pnpm build\n steps:\n - name: Harden Runner\n uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 # v2\n with:\n egress-policy: audit\n\n - name: Checkout\n uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n with:\n fetch-depth: 1\n persist-credentials: false\n\n - name: Setup Node.js\n uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0\n with:\n node-version: 24\n\n - name: Setup mise\n uses: jdx/mise-action@5ac50f778e26fac95da98d50503682459e86d566 # v3.2.0\n\n - name: Install Dependencies\n run: mise exec -- pnpm install --frozen-lockfile\n\n - name: Run ${{ matrix.name }}\n env:\n MODERN_PUBLIC_SITE_URL: http://localhost:8080\n run: mise exec -- ${{ matrix.command }}\n",
|
|
49
|
+
".agents/agent-reference-repos.json": "{\n \"schemaVersion\": 1,\n \"defaultEnabled\": true,\n \"strategy\": \"git-subtree-squash\",\n \"installDir\": \"repos\",\n \"repositories\": [\n {\n \"id\": \"effect\",\n \"name\": \"Effect\",\n \"url\": \"https://github.com/Effect-TS/effect.git\",\n \"ref\": \"main\",\n \"path\": \"repos/effect\",\n \"readOnly\": true\n },\n {\n \"id\": \"ultramodern-js\",\n \"name\": \"UltraModern.js\",\n \"url\": \"https://github.com/BleedingDev/ultramodern.js.git\",\n \"ref\": \"main-ultramodern\",\n \"path\": \"repos/ultramodern.js\",\n \"readOnly\": true\n }\n ]\n}\n",
|
|
50
|
+
".agents/skills-lock.json": "{\n \"schemaVersion\": 1,\n \"source\": {\n \"repository\": \"https://github.com/rstackjs/agent-skills\",\n \"commit\": \"61c948b42512e223bad44b83af4080eba48b2677\",\n \"license\": \"MIT\",\n \"licensePath\": \".agents/rstackjs-agent-skills-LICENSE\"\n },\n \"installDir\": \".agents/skills\",\n \"sources\": [\n {\n \"id\": \"rstack-agent-skills\",\n \"visibility\": \"public\",\n \"repository\": \"https://github.com/rstackjs/agent-skills\",\n \"commit\": \"61c948b42512e223bad44b83af4080eba48b2677\",\n \"license\": \"MIT\",\n \"licensePath\": \".agents/rstackjs-agent-skills-LICENSE\",\n \"install\": \"vendored\"\n },\n {\n \"id\": \"module-federation-agent-skills\",\n \"visibility\": \"public\",\n \"repository\": \"https://github.com/module-federation/agent-skills\",\n \"commit\": \"07bb5b6c43ad457609e00c081b72d4c42508ec76\",\n \"install\": \"clone\",\n \"baseline\": [\n {\n \"name\": \"mf\",\n \"path\": \".agents/skills/mf\",\n \"reason\": \"Module Federation docs, config inspection, type checking, shared dependency checks, and observability troubleshooting\"\n }\n ]\n },\n {\n \"id\": \"techsiocz-private\",\n \"visibility\": \"private\",\n \"repository\": \"https://github.com/TechsioCZ/skills\",\n \"install\": \"clone-if-authorized\",\n \"baseline\": [\n {\n \"name\": \"plan-graph\",\n \"reason\": \"Build and validate DAGs from .plan.md files\"\n },\n {\n \"name\": \"dag\",\n \"reason\": \"Inspect current plan frontiers and blocked lanes\"\n },\n {\n \"name\": \"subagent-graph\",\n \"reason\": \"Design dependency-aware multi-agent launch graphs\"\n },\n {\n \"name\": \"helm\",\n \"reason\": \"Steer already-running multi-agent work\"\n },\n {\n \"name\": \"debugger-mode\",\n \"reason\": \"Run hypothesis-driven debugging with runtime evidence\"\n }\n ]\n }\n ],\n \"baseline\": [\n {\n \"name\": \"rsbuild-best-practices\",\n \"path\": \".agents/skills/rsbuild-best-practices\",\n \"reason\": \"Modern.js application build configuration and Rsbuild troubleshooting\"\n },\n {\n \"name\": \"rspack-best-practices\",\n \"path\": \".agents/skills/rspack-best-practices\",\n \"reason\": \"Rspack bundling, CSS, asset, profiling, and production behavior\"\n },\n {\n \"name\": \"rspack-tracing\",\n \"path\": \".agents/skills/rspack-tracing\",\n \"reason\": \"Trace-backed Rspack failure and performance debugging\"\n },\n {\n \"name\": \"rsdoctor-analysis\",\n \"path\": \".agents/skills/rsdoctor-analysis\",\n \"reason\": \"Evidence-backed bundle composition, duplication, and retained-module analysis\"\n },\n {\n \"name\": \"rslib-best-practices\",\n \"path\": \".agents/skills/rslib-best-practices\",\n \"reason\": \"Rslib shared package and design-system library authoring\"\n },\n {\n \"name\": \"rslib-modern-package\",\n \"path\": \".agents/skills/rslib-modern-package\",\n \"reason\": \"Modern package contracts, exports, declarations, side effects, and release readiness\"\n },\n {\n \"name\": \"rstest-best-practices\",\n \"path\": \".agents/skills/rstest-best-practices\",\n \"reason\": \"Rstest configuration, test writing, mocking, snapshots, coverage, and CI behavior\"\n },\n {\n \"name\": \"mf\",\n \"path\": \".agents/skills/mf\",\n \"reason\": \"Module Federation docs, config inspection, type checking, shared dependency checks, and observability troubleshooting\"\n }\n ],\n \"excludedByDefault\": [\n \"migrate-to-rsbuild\",\n \"migrate-to-rslib\",\n \"migrate-to-rslint\",\n \"migrate-to-rstest\",\n \"rsbuild-v2-upgrade\",\n \"rspack-v2-upgrade\",\n \"rspress-v2-upgrade\"\n ]\n}\n",
|
|
51
|
+
".agents/rstackjs-agent-skills-LICENSE": "MIT License\n\nCopyright (c) 2026 RstackJS Contributors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n",
|
|
52
|
+
".agents/skills/rsbuild-best-practices/SKILL.md": "---\nname: rsbuild-best-practices\ndescription: Rsbuild best practices for config, CLI workflow, type checking, bundle optimization, assets, and debugging. Use when writing, reviewing, or troubleshooting Rsbuild projects.\n---\n\n# Rsbuild Best Practices\n\nApply these rules when writing or reviewing Rsbuild projects.\n\n## Configuration\n\n- Use `rsbuild.config.ts` and `defineConfig`\n- Use `tools.rspack` or `tools.bundlerChain` only when no first-class Rsbuild option exists\n- Define explicit `source.entry` values for multi-page applications\n- In TypeScript projects, prefer `tsconfig.json` path aliases first\n\n## CLI\n\n- Use `rsbuild` for local development\n- Use `rsbuild build` for production build\n- Use `rsbuild preview` only for local production preview\n- Use `rsbuild inspect` to inspect final Rsbuild/Rspack configs\n\n## Type checking\n\n- Use `@rsbuild/plugin-type-check` for integrated dev/build type checks\n- Or run `tsc --noEmit`/`vue-tsc --noEmit` as an explicit script step\n\n## Bundle size optimization\n\n- Prefer dynamic `import()` for non-critical code paths\n- Prefer lightweight libraries where possible\n- Keep browserslist aligned with real compatibility requirements\n\n## Asset management\n\n- Import source-managed assets from project source directories, not from `public`\n- Reference `public` files by absolute URL path\n\n## Security\n\n- Do not publish `.map` files to public servers/CDNs when production source maps are enabled\n\n## Debugging\n\n- Run with `DEBUG=rsbuild` when diagnosing config resolution or plugin behavior\n- Read generated files in `dist/.rsbuild` to confirm final config, not assumed config\n\n## Profiling\n\n- Use Node CPU profiling (`--cpu-prof`) when JavaScript-side overhead is suspected\n- Use `RSPACK_PROFILE=OVERVIEW` and analyze trace output for compiler-phase bottlenecks\n\n## Documentation\n\n- For the latest (v2) docs, read http://rsbuild.rs/llms.txt\n- For Rsbuild v1 docs, read http://v1.rsbuild.rs/llms.txt\n",
|
|
53
|
+
".agents/skills/rslib-best-practices/SKILL.md": '---\nname: rslib-best-practices\ndescription: Rslib best practices for config, CLI workflow, output, declaration files, dependency handling, build optimization and toolchain integration. Use when writing, reviewing, or troubleshooting Rslib projects.\n---\n\n# Rslib Best Practices\n\nApply these rules when writing or reviewing Rslib library projects.\n\n## Configuration\n\n- Use `rslib.config.ts` and `defineConfig`\n- Check Rslib-specific configurations first (e.g., `lib.*`), and also leverage Rsbuild configurations (e.g., `source.*`, `output.*`, `tools.*`) as needed\n- For deep-level or advanced configuration needs, use `tools.rspack` or `tools.bundlerChain` to access Rspack\'s native configurations\n- In TypeScript projects, prefer `tsconfig.json` path aliases\n\n## CLI\n\n- Use `rslib` to build\n- Use `rslib --watch` to build in watch mode for local development\n- Use `rslib inspect` to inspect final Rslib/Rsbuild/Rspack configs\n\n## Output\n\n- Prefer to build pure-ESM package with `"type": "module"` in `package.json`\n- Prefer to use bundleless mode with `output.target` set to `\'web\'` when building component libraries\n- Prefer to use bundle mode when building Node.js utility libraries\n- Ensure `exports` field in `package.json` is correctly configured and matches the actual JavaScript output and declaration files output of different formats (ESM, CJS, etc.)\n\n## Declaration files\n\n- Prefer to enable declaration file generation with `lib.dts: true` or detailed configurations\n- For faster type generation, enable `lib.dts.tsgo` experimental feature with `@typescript/native-preview` installed\n\n## Dependencies\n\n- Prefer to place dependencies to be bundled in `devDependencies` in bundle mode and dependencies in `dependencies` and `peerDependencies` will be automatically externalized (not bundled) by default\n- Verify the build output and dependency specifiers in `package.json` carefully to ensure no missing dependency errors occur when consumers install and use this package\n\n## Build optimization\n\n- Keep syntax target in `lib.syntax` aligned with real compatibility requirements to enable better optimizations\n- Avoid format-specific APIs in source code for better compatibility with different output formats\n- Prefer lightweight dependencies to reduce bundle size\n\n## Toolchain integration\n\n- Prefer to use Rstest with `@rstest/adapter-rslib` for writing tests\n- Prefer to use Rspress for writing library documentation, with `@rspress/plugin-preview` and `@rspress/plugin-api-docgen` for component previews and API docs\n\n## Debugging\n\n- Run with `DEBUG=rsbuild` when diagnosing config resolution or plugin behavior\n- Read generated files in `dist/.rsbuild` to confirm final Rsbuild/Rspack config, not assumed config\n\n## Documentation\n\n- For the latest Rslib docs, read https://rslib.rs/llms.txt\n',
|
|
54
|
+
".agents/skills/rslib-modern-package/SKILL.md": '---\nname: rslib-modern-package\ndescription: Opinionated Rslib recommendations for modern JS/TS npm package design covering pure ESM, strict TypeScript, explicit exports, small stable APIs, pragmatic dependencies, accurate sideEffects, correct declarations, package validation, provenance, README.md, and AGENTS.md. Use when the user wants to make a JS/TS package more modern, check whether the current package setup is healthy, review package.json/exports/types/dependencies/docs/release readiness, or apply a modern library baseline.\n---\n\n# Rslib Modern Package\n\nUse this skill when creating a new Rslib library, modernizing an existing JS/TS package, or reviewing a package against an opinionated modern library standard.\n\nThis skill is opinionated: it describes a recommended modern package contract and may suggest breaking changes when they make the package simpler, safer, and easier for modern consumers.\n\n## Standard\n\nDefault recommendation for new JS/TS libraries:\n\n- ESM-first, preferably pure ESM.\n- Strict TypeScript and correct declaration files.\n- Explicit public API through `package.json#exports`.\n- Small named-export API surface.\n- Few runtime dependencies, without treating zero dependencies as a religion.\n- Small, tree-shakeable output with accurate `sideEffects`.\n- Clear dependency placement: runtime dependencies, peer dependencies, optional dependencies, and dev dependencies are not interchangeable.\n- Published package is tested as an artifact, not just as source files.\n- Release flow is automated, traceable, and SemVer-aware.\n- README.md explains usage for humans; AGENTS.md preserves package invariants for future agents.\n\n## Workflow\n\n1. **Inspect the package contract first**\n - Read `package.json`, lockfile/package manager, `rslib.config.*`, `tsconfig*`, CI/release config, README.md, AGENTS.md, and existing `dist` output.\n - Identify package kind: Node utility, browser library, isomorphic utility, CLI, UI/component library, framework plugin, SDK, or adapter.\n - List supported runtimes, current entry points, deep imports, runtime dependencies, peer dependencies, optional integrations, files with side effects, and published files.\n - Run `npm pack --dry-run` early when changing package shape so the real tarball contents guide the review.\n\n2. **Define target environments explicitly**\n - Do not say "supports modern environments" without defining them.\n - Verify the current Node.js release schedule before choosing `engines`.\n - As of May 9, 2026, Node.js 22 and 24 are LTS, and Node.js 20 is EOL. For new Node-facing packages, recommend `engines.node >=22` unless real consumers need an older runtime.\n - Browser packages should state whether they require native ESM, a bundler, Workers support, SSR compatibility, DOM APIs, CSS processing, or specific browser baselines.\n - Compatibility drops are breaking changes: old Node/browser versions, undocumented deep imports, default/named export shape, bundled vs external dependency behavior, and import side effects.\n\n3. **Prefer pure ESM, but explain compatibility cost**\n - New packages should use `"type": "module"` and ESM source/output.\n - Rslib\'s default format is ESM; keep that default unless there is a clear reason to add another format.\n - Evaluate compatibility from real consumers and supported runtimes instead of assuming every historical module format is required.\n - Modern Node.js can load synchronous ESM from CommonJS via `require(esm)`; do not assume CJS consumers always require a separate CJS build.\n - If you rely on `require(esm)` compatibility, document and test its constraints: supported Node versions, no top-level `await` in the loaded graph, namespace-object return shape, default export behavior, and CJS/ESM cycle limits.\n - Prefer Node built-in specifiers such as `node:fs/promises`.\n\n4. **Make `exports` the public API**\n - Treat `package.json#exports` as the product contract.\n - Export only paths users are meant to import.\n - Do not allow imports like `pkg/dist/foo.js` by exporting `./dist/*`. That makes the generated output layout part of the public API and turns internal file moves into breaking changes.\n - Instead, expose only intentional public paths such as `pkg` and `pkg/foo.js`, mapped to the actual files in `dist`.\n - Keep subpath style consistent: either all with extensions such as `./foo.js`, or all without extensions. Prefer paths with extensions when browser import maps matter.\n - Keep `"types"` first inside conditional exports.\n - Adding `exports` to an older package can be breaking because undeclared deep imports stop working.\n - Add `./package.json` only when consumers legitimately need package metadata.\n\n5. **Design a small API surface**\n - Prefer named exports for multi-API packages.\n - Avoid default-export objects that gather every function into one object.\n - Public functions should be few, stable, well-named, and semver-maintained.\n - Keep internal types, caches, helper functions, adapter details, and error internals private unless they are part of the contract.\n - Avoid top-level work during import: file scans, network calls, timers, process mutation, global registration, DOM access, prototype mutation, or environment detection with side effects.\n - Async APIs that may be canceled should accept `AbortSignal`.\n - Prefer stable error classes, error codes, or typed error shapes over string matching.\n\n6. **Use Rslib as the implementation path, not the whole standard**\n - For detailed Rslib configuration guidance, use the `rslib-best-practices` skill.\n - In this skill, only check whether Rslib output, declarations, `package.json#exports`, `files`, dependencies, and docs agree with the modern package contract.\n - Keep Rslib configuration small and intentional; avoid adding build complexity that does not improve the package contract.\n\n7. **Keep dependencies small and intentional**\n - Start from platform APIs, not from dependency search.\n - Prefer built-ins when the runtime supports them: `URL`, `URLSearchParams`, `Intl`, `fetch`, `AbortController`, `structuredClone`, `crypto.randomUUID`, Web Streams, `TextEncoder`, `TextDecoder`, `node:fs/promises`, and `node:crypto`.\n - Small runtime dependencies are fine when they reduce maintenance risk or implementation complexity.\n - Avoid large utility packages for one or two helpers.\n - Evaluate dependencies for ESM support, `exports`, types, transitive dependency count, package size, license, maintenance activity, security history, install scripts, side effects, native install fragility, and granular imports.\n - Put required runtime packages in `dependencies`.\n - Put host-owned frameworks and toolchains in `peerDependencies`, such as React, Vue, Svelte, Rspack, Rsbuild, webpack, TypeScript, and framework runtimes.\n - Keep peer ranges reasonably broad; do not pin peers to a patch version unless required.\n - Put build tools, test tools, type tools, docs tools, and Rsbuild/Rspack plugins in `devDependencies`.\n - Use `optionalDependencies` or optional peers via `peerDependenciesMeta` for optional integrations.\n\n8. **Make TypeScript strict and package-oriented**\n - Prefer TypeScript source for TS libraries; otherwise use high-quality JSDoc plus generated declarations.\n - With TypeScript 6 or tsgo-era defaults, strict checking may already be enabled; preserve that default and do not turn it off. For older TypeScript versions or inherited configs, set `strict: true` explicitly.\n - In Rslib projects, consider enabling `lib.dts.tsgo` to speed up declaration generation when the project can use tsgo.\n - Keep `module` and `moduleResolution` aligned with how declarations are emitted and how consumers resolve the package; NodeNext and bundler-style resolution are both valid in the right toolchain.\n - Use `verbatimModuleSyntax` so type-only imports/exports are explicit.\n - Use `isolatedDeclarations` when practical so exported APIs are explicit enough for declaration-oriented tooling.\n - Emit declarations; use declaration maps when editor navigation matters.\n - Use `import type` and `export type` for type-only dependencies.\n - Do not rely on consumers setting `skipLibCheck` to hide broken package types.\n - Test declarations as consumers see them, especially when using subpath exports.\n\n9. **Keep `sideEffects` accurate**\n - Use `sideEffects: false` only when importing package files has no top-level side effects.\n - If CSS, polyfills, registrations, global listeners, prototype changes, or other import-time mutations exist, list the files with side effects instead.\n - Do not set `sideEffects: false` just to improve bundle size; incorrect values can remove required CSS or setup code.\n - Do not change globals just because a file is imported. If setup is required, expose an explicit `setup()` or `install()` function and let users call it themselves.\n\n10. **Make `package.json` authoritative**\n - Required modern shape: `"type": "module"`, explicit `exports`, correct declarations, `files` allowlist, accurate `sideEffects`, sensible `engines`, and release scripts.\n - Include README.md, AGENTS.md, and LICENSE in `files` when they exist.\n - `files` should prevent tests, fixtures, private docs, build caches, local configs, and large generated artifacts from leaking into the tarball.\n - Avoid stale `main`/`module` fields unless compatibility evidence requires them; if kept, they must agree with `exports`.\n - Keep runtime dependency fields accurate. A package that works locally only because a runtime dependency is in `devDependencies` is broken.\n\n11. **Validate the published artifact**\n - Run normal lint, typecheck, tests, and `rslib build`.\n - Smoke test built ESM output.\n - Run type-level tests when the public API is type-heavy.\n - Run `npm pack --dry-run` and inspect included files.\n - In Rslib, prefer `rsbuild-plugin-publint` to run publint after build; use `npx publint` as a CLI fallback.\n - In Rslib, prefer `rsbuild-plugin-arethetypeswrong` to run Are The Types Wrong after build when declarations are shipped; use `npx --yes @arethetypeswrong/cli --pack .` as a CLI fallback.\n - Install the packed tarball into clean consumer fixtures for important packages.\n - Test ESM import, bundler import for browser/component libraries, CLI execution for `bin` packages, and every public subpath export.\n\n12. **Prepare README.md and AGENTS.md before publishing**\n - Always check whether both files exist before publishing or modernizing a package.\n - If either file is missing, recommend adding it; for implementation tasks, create a concise version unless the user asks not to.\n - README.md should include: package name, one-sentence purpose, install/usage, key features or API links, supported environments, docs/related links, changelog or contribution link, and license.\n - AGENTS.md should include: stack, package contract, common commands, source layout, code style, validation commands, and release checklist.\n - Keep both files synchronized with `package.json#exports`, supported runtimes, and actual Rslib output.\n\n13. **Publish with supply-chain hygiene**\n - Follow SemVer and document breaking changes.\n - Maintain a changelog for user-visible changes.\n - Use prerelease versions and dist-tags for beta/next channels.\n - Prefer CI publishing with npm provenance or trusted publishing.\n - Avoid long-lived publish tokens where trusted publishing is available.\n - Remember that a published package name/version pair cannot be reused safely.\n\n## Review Red Flags\n\n- `exports` is missing, points to files not emitted by Rslib, or allows public imports such as `pkg/dist/foo.js`.\n- `module`/`main` fields disagree with `exports`.\n- Type declarations do not match runtime entry points.\n- Runtime dependency is accidentally listed only in `devDependencies`.\n- React/Vue/Svelte/Rspack/Rsbuild/webpack/TypeScript is bundled or placed in `dependencies` when it should be a peer.\n- `sideEffects: false` is set while importing CSS, polyfills, global registrations, global listeners, or prototype changes.\n- Package has install scripts without a strong reason.\n- Top-level import reads user files, starts timers, touches the network, mutates globals, or assumes `window`/`process`.\n- Published tarball contains private source maps, tests/fixtures that are not useful to consumers, large generated docs, local config secrets, or build caches.\n\n## Checklist\n\n- [ ] Supported environments are explicit.\n- [ ] Package is ESM-first, preferably pure ESM.\n- [ ] `package.json` has `"type": "module"`.\n- [ ] Public entry points are declared in `exports`.\n- [ ] No accidental reliance on undeclared deep imports.\n- [ ] Rslib output, declarations, `exports`, and `files` agree.\n- [ ] TypeScript strict mode is enabled.\n- [ ] Declarations are emitted and validated.\n- [ ] Runtime dependencies are justified and small.\n- [ ] Host frameworks/toolchains are peers.\n- [ ] Build/test/type/docs tools are dev dependencies.\n- [ ] `sideEffects` is accurate.\n- [ ] `npm pack --dry-run` has been inspected.\n- [ ] `publint` passes.\n- [ ] Are The Types Wrong check passes when declarations are shipped.\n- [ ] Built ESM smoke test passes.\n- [ ] README.md exists.\n- [ ] AGENTS.md exists.\n- [ ] Release flow uses SemVer, changelog, and provenance/trusted publishing when available.\n\n## Documentation\n\n- For the latest Rslib docs, read https://rslib.rs/llms.txt\n- Shipping ESM for CommonJS consumers: https://nodejs.github.io/package-examples/04-cjs-esm-interop/shipping-esm-for-cjs/\n',
|
|
55
|
+
".agents/skills/rspack-best-practices/SKILL.md": "---\nname: rspack-best-practices\ndescription: Rspack best practices for config, CLI workflow, type checking, CSS, bundle optimization, assets and profiling. Use when writing, reviewing, or troubleshooting Rspack projects.\n---\n\n# Rspack Best Practices\n\nApply these rules when writing or reviewing Rspack projects.\n\n## Configuration\n\n- Use `rspack.config.ts` and `defineConfig`\n- Define explicit `entry` values for multi-page applications\n- Keep one main config and branch by `process.env.NODE_ENV` only when needed\n- Keep rule conditions narrow and explicit (`test`, `include`, `exclude`, `resourceQuery`)\n- Prefer built-in Rspack plugins/loaders over community JS alternatives when equivalent features exist\n\n## CLI\n\nIf `@rspack/cli` is installed:\n\n- Use `rspack dev` for local development\n- Use `rspack build` for production build\n- Use `rspack preview` only for local production preview\n\n## Type checking\n\n- Use `ts-checker-rspack-plugin` for integrated dev/build type checks\n- Or run `tsc --noEmit`/`vue-tsc --noEmit` as an explicit script step\n\n## CSS\n\nChoose one strategy:\n\n- Built-in CSS (`type: 'css' | 'css/auto' | 'css/module'`) for modern setups\n- `css-loader` + `CssExtractRspackPlugin` for webpack migration compatibility\n- `style-loader` for pure style-in-JS runtime injection scenarios\n\nOptional:\n\n- Use `builtin:lightningcss-loader` when goals are syntax downgrade + vendor prefixing\n- Use `sass-loader`/`less-loader` for preprocessing Sass/Less files\n- Use `@tailwindcss/webpack` for Tailwind CSS integration\n\n## Bundle size optimization\n\n- Prefer dynamic `import()` for non-critical code paths\n- Prefer lightweight libraries where possible\n- Keep `target` aligned with real compatibility requirements\n\n## Asset management\n\n- Import source-managed assets from project source directories, not from `public`\n- Reference `public` files by absolute URL path\n- Prefer asset modules (`asset`, `asset/resource`, `asset/inline`, `asset/source`) over legacy `file-loader`/`url-loader`/`raw-loader`\n\n## Profiling\n\n- Use Node CPU profiling (`--cpu-prof`) when JavaScript-side overhead is suspected\n- Use `RSPACK_PROFILE=OVERVIEW` and analyze trace output for compiler-phase bottlenecks\n- Replace known slow stacks first (`babel-loader`, PostCSS, terser) with Rspack built-ins when feasible\n\n## Security\n\n- Do not publish `.map` files to public servers/CDNs when production source maps are enabled\n\n## Documentation\n\n- For the latest (v2) docs, read http://rspack.rs/llms.txt\n- For Rspack v1 docs, read http://v1.rspack.rs/llms.txt\n",
|
|
56
|
+
".agents/skills/rstest-best-practices/SKILL.md": "---\nname: rstest-best-practices\ndescription: Rstest best practices for config, CLI workflow, test writing, mocking, snapshot testing, DOM testing, coverage, multi-project setup, CI integration, performance and debugging. Use when writing, reviewing, or troubleshooting Rstest test projects.\n---\n\n# Rstest Best Practices\n\nApply these rules when writing or reviewing Rstest test projects.\n\n## Configuration\n\n- Use `rstest.config.ts` and `defineConfig` from `@rstest/core`\n- Prefer explicit imports `import { test, expect, describe } from '@rstest/core'` over `globals: true`\n- For Rsbuild projects, use `@rstest/adapter-rsbuild` with `extends: withRsbuildConfig()` to reuse build config\n- For Rslib projects, use `@rstest/adapter-rslib` with `extends: withRslibConfig()` to reuse build config\n- Use `setupFiles` for shared test setup (e.g., custom matchers, cleanup hooks)\n- When using Rsbuild plugins (e.g., `@rsbuild/plugin-react`), add them via the `plugins` field\n- For deep-level or advanced build configuration needs, use `tools.rspack` or `tools.bundlerChain`\n\n## CLI\n\n- Use `rstest` or `rstest run` to run tests (`run` disables watch mode, suitable for CI)\n- Use `rstest --watch` or `rstest watch` for local development with file watching\n- Use `rstest list` to list all test files and test names\n- Use `rstest -u` to update snapshots\n- Use `--reporter=verbose` when debugging test failures for detailed output\n- Use `--config` (`-c`) to specify a custom config file path\n\n## Test writing\n\n- Import test APIs from `@rstest/core`: `test`, `describe`, `expect`, `beforeEach`, `afterEach`, etc.\n- Use `test` or `it` for test cases; use `describe` for grouping related tests\n- Use `.only` to focus on specific tests during development, but never commit `.only` to the codebase\n- Use `.skip` or `.todo` to mark incomplete or temporarily skipped tests\n- Prefer small, focused test cases that test a single behavior\n- For async error paths, prefer `await expect(fn()).rejects.toThrow(ErrorClass)` (or `.rejects.toMatchObject({ ... })`) over `try/catch` with `expect.fail` or `.catch(e => e)` patterns — the matcher form fails clearly if the promise unexpectedly resolves, keeps the assertion in one chain, and avoids forgetting to assert the throw at all\n- For async happy paths, use `await expect(fn()).resolves.toEqual(...)` for the same reason\n- Use `includeSource` for in-source testing of small utility functions (Rust-style `import.meta.rstest`)\n- For in-source tests, wrap test code in `if (import.meta.rstest) { ... }` and define `import.meta.rstest` as `false` in production build config\n\n## Test environment\n\n- Use `testEnvironment: 'node'` (default) for Node.js / server-side code\n- Use `testEnvironment: 'jsdom'` or `testEnvironment: 'happy-dom'` for DOM / browser API testing\n- Install `jsdom` or `happy-dom` as a dev dependency when using DOM environments\n- Prefer `happy-dom` for faster DOM testing; use `jsdom` when better browser API compatibility is needed\n- For real browser testing, use `@rstest/browser` with Playwright\n- Use inline project configs to run different test environments within one project (e.g., `node` and `jsdom` projects)\n\n## React / Vue testing\n\n- For React: use `@rsbuild/plugin-react` plugin and `@testing-library/react` for component testing\n- For Vue: use `@rsbuild/plugin-vue` plugin and `@testing-library/vue` for component testing\n- Create a `rstest.setup.ts` with `expect.extend(jestDomMatchers)` and `afterEach(() => cleanup())` for Testing Library\n- Add the setup file to `setupFiles` in config\n- For SSR testing, use `testEnvironment: 'node'` and test with `react-dom/server` or framework-specific SSR APIs\n\n## Mocking\n\n- Use `rs.mock('./module')` to mock modules\n- Use `rs.fn()` to create mock functions\n- Use `rs.spyOn(object, 'method')` to spy on methods\n- Prefer `clearMocks`, `resetMocks`, or `restoreMocks` config options to automatically clean up mocks between tests\n- Use factory functions in `rs.mock('./module', () => ({ ... }))` to provide mock implementations\n\n## Snapshot testing\n\n- Use `toMatchSnapshot()` for general snapshot testing\n- Use `toMatchInlineSnapshot()` for small, readable inline snapshots\n- Use `toMatchFileSnapshot()` for large or structured outputs (e.g., HTML, generated code)\n- Keep snapshots concise — only include relevant data, avoid timestamps and session IDs\n- Use `expect.addSnapshotSerializer()` to mask paths or sensitive data in snapshots\n- Use `path-serializer` to normalize file paths across platforms\n- Review snapshot changes carefully in code review\n\n## Coverage\n\n- Enable coverage with `--coverage` CLI flag or `coverage.enabled: true` in config\n- Install `@rstest/coverage-istanbul` for the Istanbul coverage provider\n- Use `coverage.include` to specify source files for coverage (e.g., `['src/**/*.{js,ts,tsx}']`)\n- Use `coverage.thresholds` to enforce minimum coverage requirements\n- Use `coverage.reporters` to generate reports in different formats (e.g., `text`, `lcov`, `html`)\n\n## Multi-project testing\n\n- Use `projects` field in root config to define multiple test projects\n- For monorepos, use glob patterns like `'packages/*'` to auto-discover sub-projects\n- Use `defineProject` helper in sub-project configs\n- Extract shared config and use `mergeRstestConfig` to compose project configs\n- Global options (`reporters`, `pool`, `isolate`, `coverage`, `bail`) must be set at the root level, not in projects\n\n## CI integration\n\n- Use `rstest run` (not `rstest watch`) in CI\n- Use `--shard` for parallel test execution across CI machines (e.g., `--shard 1/3`)\n- Use `--reporter=blob` with `rstest merge-reports` to combine sharded results\n- Use `--reporter=junit` with `outputPath` for CI report integration\n- The `github-actions` reporter is auto-enabled in GitHub Actions for inline error annotations\n- Use `--bail` to stop early on first failure when appropriate\n\n## Performance\n\n- Disable `isolate` (`--no-isolate`) when tests have no side effects for faster execution via module cache reuse\n- Use `pool.maxWorkers` to control parallelism based on available resources\n- Keep test build fast by avoiding unnecessary Rspack plugins in test config\n- Use test filtering (`rstest <pattern>` or `-t <name>`) to run only relevant tests during development\n- Leverage watch mode's incremental re-runs for fast local feedback\n\n## Debugging\n\n- Run with `DEBUG=rstest` to enable debug mode, which writes final configs and build outputs to disk\n- Read generated files in `dist/.rstest-temp/.rsbuild/` to confirm final Rstest/Rsbuild/Rspack config\n- Use VS Code's JavaScript Debug Terminal to run `rstest` with breakpoints\n- Use `--reporter=verbose` for detailed per-test output\n- Use `--printConsoleTrace` to trace console calls to their source\n- Add VS Code launch config for debugging specific test files with `@rstest/core/bin/rstest.js`\n\n## Profiling\n\n- Use Rsdoctor with `RSDOCTOR=true rstest run` to analyze test build performance\n- Use `samply` for native profiling of both main and worker processes\n- Use Node.js `--heap-prof` for memory profiling\n\n## Toolchain integration\n\n- Use the official VS Code extension (`rstack.rstest`) for in-editor test running and debugging\n- For Rslib libraries, use `@rstest/adapter-rslib` for config reuse\n- For Rsbuild apps, use `@rstest/adapter-rsbuild` for config reuse\n- Use `process.env.RSTEST` to detect test environment and apply test-specific config\n\n## Documentation\n\n- For the latest Rstest docs, read https://rstest.rs/llms.txt\n",
|
|
57
|
+
".agents/skills/rsdoctor-analysis/SKILL.md": "---\nname: rsdoctor-analysis\ndescription: Use when analyzing Rspack/Webpack bundles from local `rsdoctor-data.json` and producing evidence-based optimization recommendations.\n---\n\n# Rsdoctor Analysis Assistant Skill\n\nUse the globally installed `rsdoctor-agent` CLI from `@rsdoctor/agent-cli` only after a real `rsdoctor-data.json` path exists. Keep analysis read-only unless the user explicitly asks for install/config setup.\n\nResponse order (required): High-Priority Issues -> Proposed Solutions -> Optional Reference-Chain Follow-up Choices -> Next Deep-Dive Issue Categories (Not commands).\n\n## Core Workflow\n\n1. Reuse current-session results and valid `.rsdoctor-analysis-cache.json` entries before doing new work.\n2. Locate `rsdoctor-data.json` fast: user-provided path, then `dist/rsdoctor-data.json`, `output/rsdoctor-data.json`, `static/rsdoctor-data.json`, `.rsdoctor/rsdoctor-data.json`, then one bounded `rg --files` search excluding `node_modules` and `.git`. Treat `manifest.json` only as an index.\n3. If data exists, skip all plugin version/config/build generation logic. Update cache when useful.\n4. If data is missing, stop analysis: do not run `rsdoctor-agent` analysis commands, do not run the Analysis Gate, and either ask for the data path or run the Generation Gate below only when setup/generation is required.\n5. After a real data file exists, run Analysis Gate at most once before the first `rsdoctor-agent` data-fetch command: verify global `@rsdoctor/agent-cli` with `npm view @rsdoctor/agent-cli version` and `rsdoctor-agent --version`; install latest only if missing/outdated, a version-related error occurs, or the user asks to refresh.\n6. Fetch only the Default Evidence Set first; run independent fetches in parallel when possible; synthesize findings in the required response order.\n\nPerformance rules: parallelize independent checks, cache only derived facts (`dataFile`, `dataFileMtime`, `pluginName`, `pluginVersion`, dependency/config/plugin modification times), and invalidate cache when paths disappear, modification times change, the user asks to refresh, or cached values fail. Speculative plugin checks must not trigger generation; use them only after confirming the data file is missing.\n\n## Generation Gate\n\nIdentify `pluginName` (`@rsdoctor/rspack-plugin` or `@rsdoctor/webpack-plugin`) and determine `pluginVersion` from local files first: `package.json`, lockfile, then `node_modules/<plugin>/package.json`; use `pnpm why` / `npm ls` only as fallback.\n\nUse this exact if/else decision tree; do not merge branches:\n\n```text\nif pluginName is missing:\n install/register the matching Rsdoctor plugin, then configure output.mode='brief' and output.options.type=['json']; build with RSDOCTOR=true only\nelse if pluginVersion is unknown:\n resolve pluginVersion first; if still unknown, configure output.mode='brief' and output.options.type=['json']; build with RSDOCTOR=true only\nelse if pluginVersion >= 1.5.11:\n do not edit plugin config just for JSON; build with RSDOCTOR_OUTPUT=json and RSDOCTOR=true if needed\nelse: # pluginVersion < 1.5.11\n MUST configure output.mode='brief' and output.options.type=['json']; build with RSDOCTOR=true only\n```\n\nPreflight every build command: `RSDOCTOR_OUTPUT=json` is allowed only in the `pluginVersion >= 1.5.11` branch. For missing, unknown, or `< 1.5.11`, it is forbidden. For `< 1.5.11`, generating `rsdoctor-data.json` requires the plugin config below:\n\n```ts\noutput: {\n mode: 'brief',\n options: {\n type: ['json'],\n },\n}\n```\n\n## Evidence and Command Bounds\n\nDefault Evidence Set:\n\n| Summary key | Evidence source | Bounds |\n| -------------------- | ------------------------------------------ | --------------------------------------------- |\n| `buildCost` | `build summary` | filtered fields only |\n| `assetsTop` | top assets by raw/gzip size | fixed Top-N |\n| `packagesTop` | top packages by gzip size | fixed Top-N; avoid full `packages list` pages |\n| `duplicatePackages` | E1001 duplicate package summary | first-pass summary only |\n| `crossChunkPackages` | E1002 cross-chunk duplication summary | first-pass summary only |\n| `retainedModulesTop` | `tree-shaking retained-modules --limit 10` | filtered fields only; no `--compact` |\n\nScope rules:\n\n- Use `rsdoctor-agent` for bundle data access only after `rsdoctor-data.json` exists; prefer parallel independent fetches; bound output with `--filter`, pagination, and `--limit`.\n- Default analysis stays within the Default Evidence Set. For non-default analysis, choose minimal fields from [references/rsdoctor-data-types.md](references/rsdoctor-data-types.md) and patterns from [references/common-analysis-patterns.md](references/common-analysis-patterns.md).\n- Treat chain tracing, broad commands, optimization edits, splitChunks experiments, and build re-runs as opt-in follow-ups that require user confirmation.\n- For duplicate packages and tree-shaking issues, identify issues first; trace reference/import chains only after user confirmation.\n- Prefer `tree-shaking retained-modules --emitted-only --category side-effects --limit 10` with narrow `--filter` for side-effects investigations.\n- For retained emitted modules, use `tree-shaking retained-modules` with `--emitted-only`, bounded `--category`, `--sort gzipSize`, `--limit`, and narrow `--filter`; do not pass `--compact`.\n- Use `tree-shaking summary` only as fallback for missing fields or aggregate context. Treat `tree-shaking bailout-reasons` as high-volume; run it only when explicitly requested and pass target `--modules` (max 100).\n- If any command exceeds `5k` tokens, `500 KB` raw output, or a few hundred transcript lines, stop broad fetching and switch to targeted compact queries.\n\n## Output and Recovery\n\nOutput format:\n\n1. Issues found in the current build and recommended fixes:\n - Group each issue with its fix recommendation.\n - Include concrete evidence (size/time/count/path/rule code) and priority.\n - For duplicate packages and tree-shaking issues, include a short \"continue tracing vs stop here\" choice.\n2. Whether deeper analysis is still needed:\n - List remaining issue categories only, not commands.\n\nFor Top-N insights, prefer a table: `Name | Volume/Time | Count | Recommendation`.\n\nRecovery rules:\n\n- `rsdoctor-data.json` missing: do not run `rsdoctor-agent`; ask for the data path or run Generation Gate, then use the matching install reference if setup is needed.\n- Command not found: run Analysis Gate, then retry with `rsdoctor-agent`.\n- `query` reports unknown tool: run `list` and use a catalog tool name, or switch to direct `<group> <subcommand>` mode.\n- JSON read error: verify file path, JSON validity, and permissions.\n- In Codex, do not run `install`, `build`, global CLI installation, version checks, or `rsdoctor-agent...` inside sandbox. Run Rsdoctor CLI setup and data-fetch commands outside sandbox so they can access project files and dependencies normally.\n\nReferences: commands/options [references/command-map.md](references/command-map.md); install/config/data location [references/install-rsdoctor.md](references/install-rsdoctor.md), [references/install-rsdoctor-rspack.md](references/install-rsdoctor-rspack.md), [references/install-rsdoctor-webpack.md](references/install-rsdoctor-webpack.md), [references/install-rsdoctor-common.md](references/install-rsdoctor-common.md); raw data fields [references/rsdoctor-data-types.md](references/rsdoctor-data-types.md); common patterns [references/common-analysis-patterns.md](references/common-analysis-patterns.md).\n",
|
|
58
|
+
".agents/skills/rsdoctor-analysis/references/command-map.md": "# Rsdoctor Skill Command Map\n\nStable CLI entry:\n\n- Install and verify the global CLI first:\n - `npm view @rsdoctor/agent-cli version`\n - `rsdoctor-agent --version`\n - If missing or outdated: `npm install -g @rsdoctor/agent-cli@latest`\n- Run data-fetch commands directly with `rsdoctor-agent <group> <subcommand> [options]`.\n\nTop-level command mode:\n\n- `list`\n- `query <tool-name> --data-file <path> [--input <json>]`\n\n`query` catalog (current):\n\n- `chunks_list`\n- `packages_direct_dependencies`\n- `packages_duplicates`\n- `packages_similar`\n- `build_summary`\n- `bundle_optimize`\n- `errors_list`\n- `tree_shaking_summary`\n\nOption scopes:\n\n- `--data-file <path>`:\n - required for `query`, direct `<group> <subcommand>`, and `ai <group> <subcommand>`\n - not required for `list`, `ai --describe`, `ai --schema`\n- `--input <json>`: optional for `query`\n- `--filter <...>`: supported by every data-fetch function; use it to return only required fields selected from `@rsdoctor/types` / [rsdoctor-data-types.md](rsdoctor-data-types.md)\n- `--compact`: add whenever possible to keep CLI JSON compact. Do not use it with `tree-shaking retained-modules`; use `--filter` and `--limit` instead.\n\n## Chunks\n\n- `chunks list` -> List all chunks. Pagination: `--page-number`, `--page-size`\n- `chunks by-id --id <n>` -> Get chunk detail by numeric id\n- `chunks large` -> Find oversized chunks. High-noise in default analysis; avoid unless the user asks for chunk deep dive.\n\n## Modules\n\n- `modules by-id --id <id>` -> Module detail by id\n- `modules by-path --path \"<path>\"` -> Module lookup by path\n- `modules issuer --id <id>` -> Issuer/import chain (recommended as second-pass, after user confirms chain tracing)\n- `modules exports` -> Module exports info\n- `modules side-effects` -> Non-tree-shakeable modules. Fallback only for side-effects analysis; use `--page-size 10`, narrow filters, and stop if output exceeds `5k` tokens or `500 KB`.\n\n## Packages\n\n- `packages list` -> Package list with size/duplication info. Do not read full pages in default analysis; use fixed Top-N package summaries or narrowly filtered/package-targeted queries.\n- `packages by-name --name <pkg>` -> Package lookup by name\n- `packages dependencies` -> Dependency graph. Pagination: `--page-number`, `--page-size`\n- `packages direct-dependencies` -> Direct third-party package dependencies imported by project/local packages. Tool name: `packages_direct_dependencies`\n- `packages duplicates` -> Duplicate package detection (first-pass summary before optional chain tracing)\n- `packages similar` -> Similar package detection\n\n## Assets\n\n- `assets list` -> Asset list with size info\n- `assets diff --baseline <path> --current <path>` -> Compare two builds\n- `assets media` -> Media optimization guidance\n\n## Loaders\n\n- `loaders hot-files` -> Slowest loader/file pairs. Options: `--page-number`, `--page-size`, `--min-costs`\n- `loaders directories` -> Loader times by directory. Options: `--page-number`, `--page-size`, `--min-total-costs`\n\n## Build\n\n- `build summary` -> Build summary and costs\n- `build entrypoints` -> Entrypoints\n- `build config` -> Build config snapshot\n- `build optimize` -> Bundle optimization inputs. High-noise in default analysis; avoid unless the user asks for bundle optimization deep dive or default evidence is insufficient. Options: `--step`, `--side-effects-page-number`, `--side-effects-page-size` (recommend `--side-effects-page-size 10`).\n\n## Bundle\n\n- `bundle optimize` -> Alias of `build optimize`\n\n## Errors\n\n- `errors list` -> All errors and warnings\n- `errors by-code --code <code>` -> Filter by code. For default E1001/E1002 summaries, prefer local JSON summarization.\n- `errors by-level --level <level>` -> Filter by level\n\n## Rules\n\n- `rules list` -> Rule scan results\n\n## Server\n\n- `server port` -> Current JSON data file path\n\n## Tree-Shaking\n\n- `tree-shaking summary` -> Overall tree-shaking health summary (can be very large; filter with fields from `rsdoctor-data-types`, compact where useful, and use aggregated results)\n- `tree-shaking retained-modules` -> Retained emitted modules by category for tree-shaking diagnosis. Useful options: `--emitted-only`, `--category cjs,barrel,side-effects`, `--sort gzipSize`, `--limit <n>`, and `--filter id,path,packageName,version,category,size,chunks,bailoutReason,recommendation`. Does not support `--compact`.\n- `tree-shaking bailout-reasons --modules <module-list>` -> Non-tree-shakeable modules by bailout reason for the provided modules. High-volume; only run when explicitly requested, always pass `--modules`, and include at most 100 modules per command.\n- `tree-shaking exports-analysis` -> Export-level tree-shaking opportunities\n\n`tree-shaking retained-modules` returns retained module rows with:\n\n| Field | Meaning |\n| ------------------------- | --------------------------------------------- |\n| `id` | Module id |\n| `path` | Module path |\n| `packageName` / `version` | Owning package |\n| `category` | `cjs`, `barrel`, `side-effects`, or `unknown` |\n| `size` | Source, parsed, and gzip sizes when available |\n| `chunks` | Chunk id/name/assets |\n| `bailoutReason` | Original bailout/retention reason |\n| `recommendation` | Optional short recommendation |\n",
|
|
59
|
+
".agents/skills/rsdoctor-analysis/references/common-analysis-patterns.md": "# Common Analysis Patterns\n\nUse this reference for common Rspack/Webpack bundle analysis questions after locating `rsdoctor-data.json`.\n\n## Similar Packages\n\nUse direct dependency package data to inspect similar packages. Start with `packages direct-dependencies` or `query packages_direct_dependencies`, then check known package families and other potentially similar packages.\n\nSuggested flow:\n\n1. Fetch direct dependency package data with `packages direct-dependencies` or `query packages_direct_dependencies`. Use `--filter` fields for package name, version, issuer/dependency relation, and size when available.\n2. Treat this direct dependency list as the replacement-candidate set. Do not make replacement recommendations from indirect package-only evidence.\n3. Check the known families below. The presence of one package from a family is fine; only consider replacement when multiple packages from the same family are present.\n4. After known-family checks, inspect the direct dependency list for other potentially similar packages not listed below. Treat these as candidates only when package purpose overlaps clearly; avoid speculative replacement advice.\n5. Use `packages similar` or `query packages_similar` as an additional signal, not the only source of evidence.\n\nSimilar package families:\n\n1. `lodash`, `lodash-es`\n - Consider migrating from `lodash` to `lodash-es` for better tree-shaking support when both are present.\n2. `dayjs`, `moment`, `date-fns`, `js-joda`\n - Consider replacing `moment` with `dayjs` for smaller bundle size when both are present and project requirements allow it.\n3. `antd`, `material-ui`, `semantic-ui-react`, `arco-design`\n4. `axios`, `node-fetch`\n5. `redux`, `mobx`, `zustand`, `recoil`, `jotai`\n6. `chalk`, `colors`, `picocolors`, `kleur`\n7. `fs-extra`, `graceful-fs`\n\nIf there are no similar packages, simply say there are no similar packages. Do not list packages that merely exist in the project.\n\nKeep the response simple: name only coexisting known-family packages or other direct-dependency candidates with clear overlap, explain why coexistence is worth reviewing, and give one replacement direction if the evidence supports it.\n\n## Media Asset Analysis\n\nUse `assets media` or `bundle optimize` when checking oversized image, font, or video assets. Return recommendations only for assets that are actually oversized or relevant to the user's question.\n\nImage thresholds:\n\n- Mobile: one image file should ideally be under `60 KB`; Base64 SVG should ideally be under `7 KB`.\n- PC: one image file should ideally be under `200 KB`; Base64 SVG should ideally be under `20 KB`.\n\nImage recommendations:\n\n- Compress large images with image compression tools such as `@rsbuild/plugin-image-compress` (`svgo` for SVG and `@napi-rs/image` for other images).\n- Optimize SVG paths with tools such as SVGO.\n- Consider whether SVG is necessary for the asset.\n- Choose formats by compression characteristics:\n - PNG works best for images with few colors and sharp boundaries, such as text or simple patterns.\n - JPG works best for natural images with gradients and irregular transitions, such as landscapes and portraits.\n - Base64 is suitable for important small images that should avoid extra requests and render immediately. Base64 increases binary size by about one third, but after gzip the increase is usually no more than about 10%.\n\nFont thresholds:\n\n- Prefer `.woff2`.\n- Keep a single font file under `100 KB` when possible.\n- Keep total font size under `300 KB` for the page, and under `200 KB` for mobile when possible.\n- Avoid font formats other than `ttf`, `woff`, and `woff2` unless there is a compatibility requirement.\n\nFont recommendations:\n\n- Prefer system fonts when custom fonts are not required.\n- Use `font-display: swap` or `@font-face unicode-range` for more efficient loading.\n- Ensure server-side Gzip or Brotli compression is enabled.\n- Consider variable fonts when they replace multiple weight or width files.\n\nVideo thresholds:\n\n- Keep a single video file under `500 KB` when possible.\n- Keep total video resources loaded on a page under `1 MB` when possible.\n\nVideo recommendations:\n\n- Compress video files with tools such as HandBrake or FFmpeg.\n- Use MP4 (H.264) as the compatibility default.\n- Use WebM (VP9) when modern-browser compression benefits justify it.\n- Lazy-load non-critical videos.\n- Use HLS or DASH for long videos.\n- Remove unused videos.\n- Tune `preload`:\n - `none`: do not download until playback starts; useful for videos unlikely to be played.\n - `metadata`: downloads metadata only, often around 3% of file size.\n - `auto`: downloads the full video; use only when playback is very likely.\n\n## Bundle Optimize\n\nUse `bundle optimize` / `build optimize` as an aggregate optimization pass. It can combine evidence from:\n\n- Duplicate package rules (`getRuleInfo` / `errors list` / rule details).\n- Similar package checks (`packages similar` / `query packages_similar`).\n- Media asset checks (`assets media`).\n- Chunk checks (`chunks list`, `chunks large`, or chunk details) for oversized resources and `splitChunks` recommendations.\n\nDo not run `bundle optimize` / `build optimize` in the default analysis path. Use it only for a user-requested optimization deep dive or when the compact default evidence set is missing required fields.\n\nWhen using it, keep output compact with `--compact`, narrow `--filter` fields, and pagination options such as `--side-effects-page-size 10`. If the command still returns thousands of lines, stop and switch to narrower supporting commands.\n\nDo not treat aggregate output as enough by itself when the recommendation needs concrete evidence. Fetch the narrow supporting data before recommending a config or dependency change.\n\n## Build Performance\n\nUse these as short recommendation candidates when Rsdoctor evidence points to build-time cost, loader cost, too many modules, or slow dev rebuilds. Source: [Rsbuild build performance guide](https://rsbuild.rs/zh/guide/optimization/build-performance).\n\n- Start with build performance analysis. Use measured bottlenecks before recommending config changes. Use Rsdoctor loader costs data.\n- General improvements: upgrade Rsbuild, enable `performance.buildCache` for faster rebuilds, reduce module count, and keep Tailwind CSS v3 `content` narrow and correct.\n- Tooling choices: prefer SWC over Babel transforms, avoid Less-heavy pipelines when possible, and prefer faster minification such as Rsbuild/Rspack SWC minification over Terser when compatible.\n- Sass handling: do not send already-built `node_modules/**/*.css` through `sass-loader`; prefer third-party `dist/*.css` outputs when available. Compile third-party `.scss` / `.sass` only when Sass source features are required, such as variables, mixins, functions, or theme customization, and use an allowlist for those packages instead of all `node_modules`.\n- Less projects: if many Less files are present, consider `@rsbuild/plugin-less` parallel compilation.\n- Development mode: consider `dev.lazyCompilation`, Rspack `experiments.nativeWatcher`, cheaper or disabled dev source maps, and a narrower development Browserslist.\n- Rsdoctor loader evidence: if `sass-loader` time is concentrated in third-party package directories and those packages ship CSS artifacts, recommend importing the CSS artifact or narrowing Sass rule `include` to app source plus specific allowlisted theme packages.\n- Call out tradeoffs: development Browserslist and source map changes can make dev output differ from production or reduce debugging detail.\n\n## Retained Module Tree-shaking Analysis\n\nUse `tree-shaking retained-modules` for first-pass tree-shaking evidence when the goal is to find retained emitted modules by reason category. Prefer it over broad `tree-shaking summary` when the user asks for top retained modules, CommonJS retention, barrel imports, side effects, or gzip-size priority.\n\nRecommended first-pass command shape:\n\n```bash\nrsdoctor-agent tree-shaking retained-modules \\\n --data-file dist/rsdoctor-data.json \\\n --emitted-only \\\n --category cjs,barrel,side-effects \\\n --sort gzipSize \\\n --limit 10 \\\n --filter id,path,packageName,version,category,size,chunks,bailoutReason,recommendation\n```\n\nGuidance:\n\n1. Keep `--emitted-only` by default so findings map to shipped bundle impact.\n2. Use `--category cjs,barrel,side-effects` for optimization scans; narrow `--category` when the user asks about one class.\n3. Sort by `gzipSize` for bundle impact, unless the user asks for source or parsed size.\n4. Keep `--limit` bounded. Use `--limit 10` for default analysis. Increase to `50` only for user-requested deep dives.\n5. Do not add `--compact`; `tree-shaking retained-modules` output size is controlled with `--limit` and `--filter`.\n6. Report rows as `Path | Package | Category | Gzip/Parsed Size | Chunks | Bailout | Recommendation`.\n7. Treat results as first-pass evidence. Use `modules issuer` only after the user asks to trace who imported a retained module.\n\n## Common Questions\n\n### Why is a module not tree-shaken?\n\nExample: \"Why is `node_modules/rc-tree/lib/util.js` not tree-shaken?\"\n\n- Start with `tree-shaking retained-modules` filtered to id, path, package, category, size, chunks, bailout reason, and recommendation when the module appears in emitted output.\n- Use `tree-shaking summary` only when retained modules do not include the needed field or the question needs broader aggregate context.\n- Return the module's `bailoutReason`.\n- Explain the bailout in plain language.\n- Show `issuerPath` only when the user asks for chain tracing or when it is necessary to explain the issue.\n\n### Who imported a module?\n\nExample: \"Who imported `lodash-es/constant.js`?\"\n\n- Use module lookup by path, then issuer/import-chain data.\n- Show the dependency chain using arrow notation or a tree.\n\n### Show modules with side effects\n\nExample: \"Show all modules with side effects.\"\n\n- Prefer `tree-shaking retained-modules --emitted-only --category side-effects` for emitted side-effect modules.\n- Fall back to `tree-shaking summary` or the relevant module-side-effects command only when retained-module output is insufficient.\n- Filter to module id, path, package, size, chunks, bailout reason, and recommendation.\n- List modules with non-empty `bailoutReason` containing `side_effects`.\n- Use `--limit 10` for default output. Increase only after user confirmation.\n- If falling back to `tree-shaking summary` or `modules side-effects`, use `--page-size 10` or `--side-effects-page-size 10`, keep the same narrow fields, and stop expanding when one command exceeds `5k` tokens or `500 KB` raw output.\n- Sort by size, give priority to the largest emitted modules.\n\n### Why is a package duplicated?\n\nExample: \"Why is package X duplicated?\"\n\n- Use duplicate package rule data (`E1001` / `E1002`) and package graph fields.\n- Show which chunks and modules contain the duplicate versions.\n- Explain the dependency path if the user asks to continue chain tracing.\n\n### Which modules are not tree-shaken because of side effects?\n\n- Use the E1007 rule results directly to identify modules that are not tree-shaken due to side effects. By `tree-shaking summary`.\n- If further details are needed, you may also use `tree-shaking retained-modules --emitted-only --category side-effects` and filter to module id, path, package, size, chunks, bailout reason, and recommendation.\n- List modules with `bailoutReason` containing `side_effects`.\n- Use `--limit 10` by default and the same `5k` token / `500 KB` raw-output stop rule for fallback commands.\n- Show `issuerPath` when needed to identify the import source.\n\n## Output Style\n\n- For dependency chains, use a tree or arrow notation.\n- For module details, use a table or key-value list.\n- For explanations, use concise, plain language.\n- Avoid listing all packages or assets when the finding is empty.\n",
|
|
60
|
+
".agents/skills/rsdoctor-analysis/references/install-rsdoctor-common.md": "# Common Steps for Rsdoctor Installation\n\nThis document contains common steps that apply to both Rspack and Webpack projects.\n\n## Step 3: Locate the rsdoctor-data.json\n\nFirst, use the fast path to check whether `rsdoctor-data.json` already exists. If the user provided a path, check that path first. Otherwise check common build artifact/output locations before any package-manager, install, config, or build command:\n\n- `dist/rsdoctor-data.json` (most common)\n- `output/rsdoctor-data.json`\n- `static/rsdoctor-data.json`\n- `.rsdoctor/rsdoctor-data.json` (if using custom reportDir)\n\nIf common paths do not contain the file, run one bounded local file search that excludes expensive directories, for example `rg --files -g 'rsdoctor-data.json' -g '!node_modules' -g '!**/.git/**'`. If `rsdoctor-data.json` is found, skip the generation/version gate and go directly to JSON analysis. If it is not found, do not run any `rsdoctor-agent` analysis command; ask for the data path or generate the file first.\n\nFor repeated analysis in the same repository, use a lightweight project-local cache such as `.rsdoctor-analysis-cache.json`. Reuse it only when the cached data-file path still exists and cached modification times match the current `rsdoctor-data.json`, dependency files (`package.json`, lock files), relevant build config files, and plugin `package.json` if recorded. Refresh the cache after locating a new data file or confirming a plugin version.\n\nWhen the runtime supports parallel execution, run independent local initialization checks concurrently: common path checks, bounded `rg --files` lookup, and local plugin-version file reads. Do not run `rsdoctor-agent` CLI checks until a real `rsdoctor-data.json` path exists. Treat plugin-version results as speculative until the data file is confirmed missing; never let parallel plugin checks trigger generation by themselves.\n\nIf you cannot find the file, ask the user to provide the path to `rsdoctor-data.json`. If the file truly does not exist and generation/setup is required, check the installed `@rsdoctor/rspack-plugin` or `@rsdoctor/webpack-plugin` version before changing config or running a build. The `@rsdoctor/agent-cli` version does not prove plugin support for `RSDOCTOR_OUTPUT=json`.\n\nRequired version gate (use exactly this if/else order):\n\n1. Identify `pluginName`: `@rsdoctor/rspack-plugin` or `@rsdoctor/webpack-plugin`.\n2. Determine `pluginVersion` from local files first: dependency declarations in `package.json`, lockfile entries, then installed `node_modules/<plugin>/package.json`. Use package-manager output such as `pnpm why @rsdoctor/rspack-plugin` / `npm ls @rsdoctor/rspack-plugin` only as a fallback.\n3. Choose one branch; do not merge branches:\n\n```text\nif pluginName is missing:\n install/register the matching Rsdoctor plugin, then MUST configure output.mode='brief' and output.options.type=['json']; build with RSDOCTOR=true only\nelse if pluginVersion is unknown:\n resolve pluginVersion first; if still unknown, MUST configure output.mode='brief' and output.options.type=['json']; build with RSDOCTOR=true only\nelse if pluginVersion >= 1.5.11:\n do not modify plugin config just for JSON; build with RSDOCTOR_OUTPUT=json and RSDOCTOR=true if needed\nelse: # pluginVersion < 1.5.11\n MUST configure output.mode='brief' and output.options.type=['json']; build with RSDOCTOR=true only\n```\n\nPreflight every build command: `RSDOCTOR_OUTPUT=json` is allowed only in the `pluginVersion >= 1.5.11` branch. For missing, unknown, or `< 1.5.11` versions, a command such as `RSDOCTOR_OUTPUT=json RSDOCTOR=true pnpm run build:rspack` is incorrect.\n\nThe file is typically generated in the same directory as your build output (e.g., `dist`, `output`, `static`). For plugin versions < `1.5.11`, configure a custom output directory using the `output.reportDir` option:\n\n```js\n// Example for Rspack: use RsdoctorRspackPlugin\n// Example for Webpack: use RsdoctorWebpackPlugin\nnew RsdoctorRspackPlugin({\n // or RsdoctorWebpackPlugin\n disableClientServer: true,\n output: {\n mode: 'brief',\n options: {\n type: ['json'],\n },\n reportDir: './dist', // Custom output directory (defaults to build output directory)\n },\n});\n```\n\n---\n\n## Step 4: Use JSON file for analysis\n\nOnce you have the `rsdoctor-data.json` file, you can use it for analysis. This JSON file contains all the build analysis data and can be used without starting the Rsdoctor server.\n\nAnalyze the JSON file with the `rsdoctor-agent` CLI from the repository root or another directory that can access the JSON file:\n\n```bash\nrsdoctor-agent build summary --data-file ./dist/rsdoctor-data.json --filter \"<fields>\"\n```\n\nKeep analysis output small:\n\n- Reuse already returned results from context/history first, then run only missing queries.\n- Use `--filter` on data-fetch commands to return only fields required for the current question.\n- Use first-pass summaries for duplicate packages and tree-shaking issues; ask before continuing reference-chain tracing.\n- Stop broad commands when one response exceeds `5k` tokens (o200k_base) or `500 KB` raw output, then switch to filtered or targeted queries.\n\nFor command names, option scopes, tree-shaking command selection, and `--filter` guidance, use [command-map.md](command-map.md). For raw data field names, use [rsdoctor-data-types.md](rsdoctor-data-types.md).\n\n**Benefits of JSON Mode:**\n\n- ✅ No need to keep the build process running\n- ✅ Works in CI/CD environments\n- ✅ Can be shared and version controlled\n- ✅ Faster analysis for large projects\n- ✅ No server connection required\n\nNote: `rsdoctor-data.json` can be large in complex projects. Add it to `.gitignore` if you do not want to commit it.\n",
|
|
61
|
+
".agents/skills/rsdoctor-analysis/references/install-rsdoctor-rspack.md": "# Install Rsdoctor Plugin for Rspack Projects\n\nThis guide covers installation for Rspack-based projects, including:\n\n- Rspack CLI\n- Rsbuild\n- Modern.js\n- Rslib\n- Rspress\n\n## Step 1: Install Dependencies\n\nFor projects based on Rspack, such as Rsbuild or Rslib:\n\n**Note:** Prefer using the latest versions of the above dependencies when available.\n\n```bash\nnpm add @rsdoctor/rspack-plugin -D\npnpm add @rsdoctor/rspack-plugin -D\n```\n\n## Step 2: Register Plugin\n\nAfter the dependency installation, check the installed `@rsdoctor/rspack-plugin` version before changing config or running a build. Do not infer plugin capabilities from `@rsdoctor/agent-cli --version`.\n\nRequired version gate (use exactly this if/else order):\n\n1. Set `pluginName = '@rsdoctor/rspack-plugin'`.\n2. Determine `pluginVersion` from local files first: dependency declarations in `package.json`, lockfile entries, then `node_modules/@rsdoctor/rspack-plugin/package.json` if installed. Use `pnpm why @rsdoctor/rspack-plugin` / `npm ls @rsdoctor/rspack-plugin` only as a fallback. When repeating analysis, reuse a valid `.rsdoctor-analysis-cache.json` plugin entry before re-reading files; invalidate it if `package.json`, lock files, or the plugin package file modification time changed.\n3. Choose one branch; do not merge branches:\n\n```text\nif @rsdoctor/rspack-plugin is missing:\n install/register @rsdoctor/rspack-plugin, then configure output.mode='brief' and output.options.type=['json']; build with RSDOCTOR=true only\nelse if pluginVersion is unknown:\n resolve pluginVersion first; if still unknown, configure output.mode='brief' and output.options.type=['json']; build with RSDOCTOR=true only\nelse if pluginVersion >= 1.5.11:\n do not modify plugin config just for JSON; build with RSDOCTOR_OUTPUT=json and RSDOCTOR=true if needed\nelse: # pluginVersion < 1.5.11\n MUST configure output.mode='brief' and output.options.type=['json']; build with RSDOCTOR=true only\n```\n\nPreflight every build command: `RSDOCTOR_OUTPUT=json` is allowed only in the `pluginVersion >= 1.5.11` branch. For missing, unknown, or `< 1.5.11`, `RSDOCTOR_OUTPUT=json` is forbidden. For example, when `@rsdoctor/rspack-plugin` is `1.5.7`, this command is incorrect:\n\n```bash\nRSDOCTOR_OUTPUT=json RSDOCTOR=true pnpm run build:rspack\n```\n\nBelow are configuration examples for old Rspack plugin versions, unknown versions, missing plugins, or projects that still need to register the plugin:\n\n### Rspack CLI\n\nInitialize the plugin in the [plugins](https://www.rspack.rs/config/plugins.html#plugins) of `rspack.config.ts`:\n\n```ts title=\"rspack.config.ts\"\nimport { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin';\n\nexport default {\n plugins: [\n // Only register the plugin when RSDOCTOR is true, as the plugin will increase the build time.\n process.env.RSDOCTOR &&\n new RsdoctorRspackPlugin({\n disableClientServer: true,\n // Required for @rsdoctor/rspack-plugin < 1.5.11.\n output: {\n mode: 'brief',\n options: {\n type: ['json'],\n },\n },\n }),\n ],\n};\n```\n\n### Rsbuild/Rslib/Modern.js\n\nSee [Rsbuild - Use Rsdoctor](https://rsbuild.rs/guide/debug/rsdoctor) for more details.\nIf this is Modern.js project can see [tools.rspack](https://modernjs.dev/configure/app/tools/rspack) of `modern.config.ts`:\n\nFor `@rsdoctor/rspack-plugin` < `1.5.11`, configure JSON output in `rsbuild.config.ts`:\n\n```ts title=\"rsbuild.config.ts\"\nimport { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin';\n\nexport default {\n tools: {\n rspack: {\n plugins: [\n process.env.RSDOCTOR === 'true' &&\n new RsdoctorRspackPlugin({\n disableClientServer: true, // Prevent starting local server\n output: {\n mode: 'brief', // Required for plugin versions < 1.5.11\n options: {\n type: ['json'], // Only generate JSON data\n },\n },\n }),\n ],\n },\n },\n};\n```\n\n### Rspress\n\nFor Rspress projects, configure the plugin in `builderConfig.tools.rspack`:\n\n```ts title=\"rspress.config.ts\"\nimport { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin';\nimport { defineConfig } from 'rspress/config';\n\nexport default defineConfig({\n builderConfig: {\n tools: {\n rspack: {\n plugins: [\n process.env.RSDOCTOR === 'true' &&\n new RsdoctorRspackPlugin({\n disableClientServer: true, // Prevent starting local server\n output: {\n mode: 'brief', // Required for plugin versions < 1.5.11\n options: {\n type: ['json'], // Only generate JSON data\n },\n },\n }),\n ],\n },\n },\n },\n});\n```\n\n## Step 3 & 4: Locate and Use rsdoctor-data.json\n\nFor steps on locating the `rsdoctor-data.json` file and using it for analysis, see the [common installation guide](./install-rsdoctor-common.md).\n",
|
|
62
|
+
".agents/skills/rsdoctor-analysis/references/install-rsdoctor-webpack.md": "# Install Rsdoctor Plugin for Webpack Projects\n\nThis guide covers installation for Webpack projects (webpack >= 5).\n\n## Step 1: Install Dependencies\n\nRsdoctor only supports webpack >= 5.\n\nFor projects based on webpack:\n\n```bash\nnpm add @rsdoctor/webpack-plugin -D\npnpm add @rsdoctor/webpack-plugin -D\n```\n\n## Step 2: Register Plugin\n\nAfter the dependency installation, check the installed `@rsdoctor/webpack-plugin` version before changing config or running a build. Do not infer plugin capabilities from `@rsdoctor/agent-cli --version`.\n\nRequired version gate (use exactly this if/else order):\n\n1. Set `pluginName = '@rsdoctor/webpack-plugin'`.\n2. Determine `pluginVersion` from local files first: dependency declarations in `package.json`, lockfile entries, then `node_modules/@rsdoctor/webpack-plugin/package.json` if installed. Use `pnpm why @rsdoctor/webpack-plugin` / `npm ls @rsdoctor/webpack-plugin` only as a fallback. When repeating analysis, reuse a valid `.rsdoctor-analysis-cache.json` plugin entry before re-reading files; invalidate it if `package.json`, lock files, or the plugin package file modification time changed.\n3. Choose one branch; do not merge branches:\n\n```text\nif @rsdoctor/webpack-plugin is missing:\n install/register @rsdoctor/webpack-plugin, then configure output.mode='brief' and output.options.type=['json']; build with RSDOCTOR=true only\nelse if pluginVersion is unknown:\n resolve pluginVersion first; if still unknown, configure output.mode='brief' and output.options.type=['json']; build with RSDOCTOR=true only\nelse if pluginVersion >= 1.5.11:\n do not modify plugin config just for JSON; build with RSDOCTOR_OUTPUT=json and RSDOCTOR=true if needed\nelse: # pluginVersion < 1.5.11\n MUST configure output.mode='brief' and output.options.type=['json']; build with RSDOCTOR=true only\n```\n\nPreflight every build command: `RSDOCTOR_OUTPUT=json` is allowed only in the `pluginVersion >= 1.5.11` branch. For missing, unknown, or `< 1.5.11`, `RSDOCTOR_OUTPUT=json` is forbidden. For example, when `@rsdoctor/webpack-plugin` is `1.5.7`, this command is incorrect:\n\n```bash\nRSDOCTOR_OUTPUT=json RSDOCTOR=true pnpm run build\n```\n\n### Webpack\n\nFor old Webpack plugin versions, unknown versions, missing plugins, or projects that still need to register the plugin, initialize it in the [plugins](https://webpack.js.org/configuration/plugins/#plugins) of `webpack.config.js`:\n\n```js title=\"webpack.config.js\"\nconst { RsdoctorWebpackPlugin } = require('@rsdoctor/webpack-plugin');\n\nmodule.exports = {\n // ...\n plugins: [\n // Only register the plugin when RSDOCTOR is true, as the plugin will increase the build time.\n process.env.RSDOCTOR &&\n new RsdoctorWebpackPlugin({\n disableClientServer: true,\n // Required for @rsdoctor/webpack-plugin < 1.5.11.\n output: {\n mode: 'brief',\n options: {\n type: ['json'],\n },\n },\n }),\n ].filter(Boolean),\n};\n```\n\n## Step 3 & 4: Locate and Use rsdoctor-data.json\n\nFor steps on locating the `rsdoctor-data.json` file and using it for analysis, see the [common installation guide](./install-rsdoctor-common.md).\n",
|
|
63
|
+
".agents/skills/rsdoctor-analysis/references/install-rsdoctor.md": "# Install Rsdoctor Plugin\n\nThis documentation has been split into project-specific guides:\n\n## Choose Your Project Type\n\n- **For Rspack/Rsbuild/Modern.js projects:** See [install-rsdoctor-rspack.md](./install-rsdoctor-rspack.md)\n- **For Webpack projects:** See [install-rsdoctor-webpack.md](./install-rsdoctor-webpack.md)\n\n## Quick Decision Guide\n\n**Determine your project type:**\n\n1. **Check project type** (`projectType`):\n - If project uses **Rspack** (including Rsbuild, Rslib, or any Rspack-based project) → Use `projectType: 'rspack'` → See [install-rsdoctor-rspack.md](./install-rsdoctor-rspack.md)\n - If project uses **Webpack** (webpack >= 5) → Use `projectType: 'webpack'` → See [install-rsdoctor-webpack.md](./install-rsdoctor-webpack.md)\n\n2. **Check framework** (`framework`):\n - If using **Rspack CLI** → `framework: 'rspack'` → See [install-rsdoctor-rspack.md](./install-rsdoctor-rspack.md)\n - If using **Rsbuild** → `framework: 'rsbuild'` → See [install-rsdoctor-rspack.md](./install-rsdoctor-rspack.md)\n - If using **Modern.js** → `framework: 'modern.js'` → See [install-rsdoctor-rspack.md](./install-rsdoctor-rspack.md)\n - If using **Rslib** → `framework: 'rslib'` → See [install-rsdoctor-rspack.md](./install-rsdoctor-rspack.md)\n - If using **Rspress** → `framework: 'rspress'` → See [install-rsdoctor-rspack.md](./install-rsdoctor-rspack.md)\n - If using **Webpack** → `framework: 'webpack'` → See [install-rsdoctor-webpack.md](./install-rsdoctor-webpack.md)\n\n**Decision flow:**\n\n```\nUser's project\n├─ Is it Rspack-based? (Rsbuild, Rslib, Rspress, etc.)\n│ ├─ Yes → projectType: 'rspack'\n│ │ ├─ Rspack CLI? → framework: 'rspack' → install-rsdoctor-rspack.md\n│ │ ├─ Rsbuild? → framework: 'rsbuild' → install-rsdoctor-rspack.md\n│ │ ├─ Rslib? → framework: 'rslib' → install-rsdoctor-rspack.md\n│ │ ├─ Rspress? → framework: 'rspress' → install-rsdoctor-rspack.md\n│ │ └─ Modern.js? → framework: 'modern.js' → install-rsdoctor-rspack.md\n│ └─ No → Is it Webpack >= 5?\n│ └─ Yes → projectType: 'webpack', framework: 'webpack' → install-rsdoctor-webpack.md\n```\n",
|
|
64
|
+
".agents/skills/rsdoctor-analysis/references/rsdoctor-data-types.md": "# Rsdoctor Data Type Context\n\nUse this reference when a task requires understanding raw `rsdoctor-data.json` fields, schema, or nested data attributes.\n\n## Source of Truth\n\nRead type definitions from the published npm package `@rsdoctor/types`. Do not use local repository `dist/` artifacts unless the user explicitly asks for local development branch behavior.\n\nBrief JSON output has this wrapper shape:\n\n```ts\nimport type { Manifest, SDK } from '@rsdoctor/types';\n\nexport interface RsdoctorDataJson {\n data: SDK.BuilderStoreData;\n clientRoutes: Manifest.RsdoctorManifestClientRoutes[];\n}\n```\n\nThe core payload type is `SDK.BuilderStoreData`.\n\n## npm Lookup Flow\n\nPrefer the npm registry/package interface.\n\nUse the latest published package unless the user gives a specific Rsdoctor package version or asks to match an installed project version.\n\n```bash\nnpm view @rsdoctor/types version dist.tarball --json\n```\n\nIf command execution is unavailable, use the registry endpoint directly:\n\n```text\nhttps://registry.npmjs.org/@rsdoctor%2Ftypes/latest\n```\n\nRead the `dist.tarball` URL from the response, download the tarball, and inspect `.d.ts` files under `package/dist/`.\n\nIf matching an installed project version is important:\n\n1. Inspect the project package versions for `@rsdoctor/rspack-plugin`, `@rsdoctor/webpack-plugin`, `@rsdoctor/core`, `@rsdoctor/sdk`, or `@rsdoctor/types`.\n2. Query the matching type package:\n\n```bash\nnpm view @rsdoctor/types@<version> version dist.tarball --json\n```\n\n3. If that exact version does not exist, use the closest compatible published `@rsdoctor/types` version and state the version mismatch.\n\n## Files to Inspect\n\nStart here:\n\n- `package/dist/index.d.ts`: namespace exports. `SDK` comes from `./sdk/index.js`; `Manifest` comes from `./manifest.js`.\n- `package/dist/sdk/index.d.ts`: exports all SDK data subtypes.\n- `package/dist/sdk/result.d.ts`: defines `BuilderStoreData`, the `rsdoctor-data.json.data` payload.\n- `package/dist/manifest.d.ts`: defines client routes and manifest types.\n\nThen load nested files as needed:\n\n- `package/dist/sdk/module.d.ts`: `moduleGraph`, modules, dependencies, source ranges, module code, tree-shaking-linked module data.\n- `package/dist/sdk/chunk.d.ts`: `chunkGraph`, assets, chunks, entrypoints.\n- `package/dist/sdk/package.d.ts`: `packageGraph`, package dependency data, duplicate package reports, other reports.\n- `package/dist/sdk/loader.d.ts`: loader timing/input/output data.\n- `package/dist/sdk/resolver.d.ts`: resolver data.\n- `package/dist/sdk/plugin.d.ts`: plugin hook/tap timing data.\n- `package/dist/sdk/summary.d.ts`: build summary/cost data.\n- `package/dist/sdk/config.d.ts`: collected bundler config data.\n- `package/dist/sdk/envinfo.d.ts`: environment info data.\n- `package/dist/rule/data.d.ts`: `errors`/rule store data.\n\n## Field Map\n\n`SDK.BuilderStoreData` contains:\n\n- `hash`: build hash.\n- `root`: project root.\n- `pid`: process id.\n- `envinfo`: environment information.\n- `errors`: rule/error store data.\n- `configs`: collected bundler config data.\n- `summary`: build summary data.\n- `resolver`: resolver events.\n- `loader`: loader transform events.\n- `plugin`: plugin hook/tap events.\n- `moduleGraph`: module graph data.\n- `chunkGraph`: asset/chunk/entrypoint graph data.\n- `packageGraph`: package/dependency graph data.\n- `moduleCodeMap`: module source/code map data.\n- `treeShaking`: optional tree-shaking data.\n- `otherReports`: optional extra report payloads.\n\nIn brief JSON mode, `moduleCodeMap` is normally `{}` and `treeShaking` is normally absent unless generated by a mode that includes it.\n\n## Usage Guidance\n\n- Cite the npm package version used when explaining fields.\n- Distinguish wrapper fields (`data`, `clientRoutes`) from `SDK.BuilderStoreData` fields.\n- When a nested field is unclear, inspect the specific `.d.ts` file instead of guessing.\n- Use these types to construct `@rsdoctor/agent-cli --filter` field selections before each data fetch. Prefer the smallest field set that can answer the current question.\n- Match filters to the relevant data domain: chunks from `chunkGraph`, modules and tree-shaking module details from `moduleGraph`/`treeShaking`, packages from `packageGraph`, loader cost from `loader`, build cost from `summary`, and rule findings from `errors`.\n- For analysis recommendations, prefer `@rsdoctor/agent-cli` commands. Use these types for schema explanation, prompt grounding, or validating raw JSON field names.\n",
|
|
65
|
+
".agents/skills/rspack-tracing/SKILL.md": '---\nname: rspack-tracing\ndescription: Comprehensive guide and toolkit for diagnosing Rspack build issues. Quickly identify where crashes/errors occur, or perform detailed performance profiling to resolve bottlenecks. Use when the user encounters build failures, slow builds, or wants to optimize Rspack performance.\n---\n\n# Rspack Tracing & Performance Profiling\n\n## When to Use This Skill\n\nUse this skill when you need to:\n\n1. Diagnose why an Rspack build is slow.\n2. Understand which plugins or loaders are taking the most time.\n3. Analyze a user-provided Rspack trace file.\n4. Guide a user to capture a performance profile.\n\n## Workflow\n\n### 1. Capture a Trace\n\nFirst, ask the user to run their build with tracing enabled.\n\n```bash\n# Set environment variables for logging to a file\nRSPACK_PROFILE=TRACE RSPACK_TRACE_LAYER=logger RSPACK_TRACE_OUTPUT=./trace.json pnpm build\n```\n\nThis will generate a trace file in a timestamped directory like `.rspack-profile-{timestamp}-{pid}/trace.json`.\n\nSee [references/tracing-guide.md](references/tracing-guide.md) for more details on configuration.\n\n### 2. Quick Diagnosis for Crashes/Errors\n\nIf the user wants to identify **which stage a crash or error occurred in**, use `tail` to quickly view the last events without running the full analysis:\n\n```bash\n# Navigate to the generated profile directory\ncd .rspack-profile-*/\n\n# View the last 20 events to see where the build failed\ntail -n 20 trace.json\n```\n\nThe last events will show the span names and targets where the build stopped, helping to quickly pinpoint the problematic stage, plugin, or loader.\n\n### 3. Full Performance Analysis\n\nFor detailed performance profiling (not just crash diagnosis), ask the user to run the bundled analysis script on the generated trace file.\n\n```bash\n# Navigate to the generated profile directory\ncd .rspack-profile-*/\n\n# Run the analysis script\nnode ${CLAUDE_PLUGIN_ROOT}/skills/tracing/scripts/analyze_trace.js trace.json\n```\n\n### 4. Interpret Results\n\nUse the output from the script to identify bottlenecks.\nConsult [references/bottlenecks.md](references/bottlenecks.md) to map span names to actionable fixes.\n\n### 5. Locate Slow Plugins\n\nBased on the "Top Slowest Hooks" from the analysis script:\n\n1. **Identify the Hook**: Note the hook name (e.g., `hook:CompilationOptimizeChunks`).\n2. **Inspect Configuration**: Read `rspack.config.js` or `rsbuild.config.ts`.\n3. **Map Hook to Plugin**: Look for plugins and their sources that tap into that specific hook.\n4. **Output**: Output the paths, lines and columns of the suspected plugin source code.\n\n## Common Scenarios & Quick Fixes\n\n- [Bottleneck Reference](references/bottlenecks.md): Mapping spans to concepts.\n- [Tracing Guide](references/tracing-guide.md): Detailed usage of `RSPACK_PROFILE`.\n',
|
|
66
|
+
".agents/skills/rspack-tracing/references/bottlenecks.md": "# Understanding Rspack Performance Bottlenecks\n\nThis reference maps internal Rspack tracing spans to high-level concepts to help you identify performance issues.\n\n## Core Compilation Phases\n\n| Span Name | Description | Potential Bottlenecks |\n| :---------------------- | :------------------------------------------------------------- | :-------------------------------------------------------------------------------- |\n| `tracing::profiling` | The entire build process. | Overall slowness. |\n| `compiler::make` | **Make Phase**: Resolving, loading, and parsing modules. | Heavy loaders (babel/swc with complex configs), too many files, slow file system. |\n| `compiler::seal` | **Seal Phase**: Optimizing, splitting chunks, generating code. | Complex code splitting, heavy minification, many modules. |\n| `compiler::emit_assets` | **Emit Phase**: Writing files to disk. | Slow disk I/O, huge output files. |\n\n## Detailed Spans\n\n### Make Phase (Module Processing)\n\n- `resolver::resolve`: Resolving import paths.\n - **High Time?**: Check for complex `resolve.alias` or `resolve.modules`, or too many standard fallbacks.\n- `loader::run_loaders`: Executing loaders (JavaScript/Rust).\n - **High Time?**: Identify which loader is slow. If `sass-loader` or `babel-loader` is slow, consider caching (`cache: true` in config) or using `swc-loader`.\n- `parser::parse`: Parsing source code into AST.\n - **High Time?**: Large files?\n\n### Seal Phase (Optimization)\n\n- `compilation::code_generation`: Generating final code from AST.\n- `compilation::optimize_chunks`: Splitting chunks (SplitChunksPlugin).\n - `k_means_splitter`: If you see this, complex splitting logic is running.\n- `js_minimizer`: Minification (SwcJsMinimizer).\n - **High Time?**: Disable minimization in dev (`optimization.minimize: false`) for speed.\n\n### General\n\n- `read_file`: Reading files from disk.\n- `write_file`: Writing artifacts to disk.\n\n## Common Fixes\n\n1. **Slow `make` phase**:\n - Use `experiments.cache` (Persistent Cache).\n - Exclude `node_modules` from expensive loaders.\n - Switch to lighter loaders (e.g. `swc-loader` vs `babel-loader`).\n2. **Slow `seal` phase**:\n - Reduce `splitChunks` complexity.\n - Disable `sourcemap` in production if acceptable cost.\n - Upgrade to latest Rspack (performance improvements are frequent).\n",
|
|
67
|
+
".agents/skills/rspack-tracing/references/tracing-guide.md": "# Rspack Tracing Guide\n\nTracing allows you to visualize exactly what Rspack is doing during a build.\n\n## Enabling Tracing\n\nRspack uses several environment variables to control tracing.\n\n**Command:**\n\n```bash\nRSPACK_PROFILE=TRACE RSPACK_TRACE_LAYER=logger RSPACK_TRACE_OUTPUT=./trace.json rspack build\n```\n\n### Variables\n\n**`RSPACK_PROFILE`**: Controls the granularity of the trace.\n\n- `TRACE`: Captures all spans. (Recommended for deep analysis)\n- `DEBUG`, `INFO`, `WARN`, `ERROR`, `CRITICAL`\n- `OFF`: Disables tracing.\n\n**`RSPACK_TRACE_LAYER`**: Controls the output format.\n\n- `logger`: Outputs standard JSON logging (required for the analysis script).\n\n## Output\n\nAfter running the command, Rspack will generate the file specified in `RSPACK_TRACE_OUTPUT`.\n\n## Using the Skill's Analysis Tool\n\nThis skill includes a script to summarize the trace file.\n\n```bash\n# Run the included script\nnode scripts/analyze_trace.js <path-to-trace-file>\n```\n",
|
|
68
|
+
".agents/skills/rspack-tracing/scripts/analyze_trace.js": "#!/usr/bin/env node\n\nconst fs = require('fs');\nconst path = require('path');\n\n// Parse duration string (e.g., \"1.23ms\", \"456.78µs\", \"0.12s\") to milliseconds\nfunction parseDuration(durationStr) {\n if (!durationStr) return 0;\n\n const match = durationStr.match(/^([\\d.]+)(ms|µs|s|ns)$/);\n if (!match) return 0;\n\n const value = parseFloat(match[1]);\n const unit = match[2];\n\n switch (unit) {\n case 's':\n return value * 1000;\n case 'ms':\n return value;\n case 'µs':\n return value / 1000;\n case 'ns':\n return value / 1000000;\n default:\n return value;\n }\n}\n\n// Get trace file path\nconst tracePath = process.argv[2] || path.join(__dirname, 'trace.json');\n\nif (!fs.existsSync(tracePath)) {\n console.error(`Error: Trace file not found at ${tracePath}`);\n console.error('Usage: node analyze_trace.js <path-to-trace.json>');\n process.exit(1);\n}\n\nconsole.log(`Analyzing trace file: ${tracePath}\\n`);\n\ntry {\n const fileContent = fs.readFileSync(tracePath, 'utf8');\n\n // Parse line-delimited JSON\n const events = fileContent\n .trim()\n .split('\\n')\n .map(line => {\n try {\n return JSON.parse(line);\n } catch (err) {\n return null;\n }\n })\n .filter(Boolean);\n\n if (!events.length) {\n console.error('No valid trace events found.');\n process.exit(1);\n }\n\n console.log('=== Rspack Build Performance Analysis ===\\n');\n console.log(`Total events: ${events.length}\\n`);\n\n // Categorize events by target\n const pluginStats = new Map();\n const loaderStats = new Map();\n\n events.forEach(event => {\n const target = event.target;\n const timeField = event.fields?.['time.busy'];\n\n if (!timeField) return;\n\n const duration = parseDuration(timeField);\n\n if (target === 'Plugin Analysis') {\n // Plugin performance\n const pluginName = event.span?.name;\n if (!pluginName) return;\n\n if (!pluginStats.has(pluginName)) {\n pluginStats.set(pluginName, {\n count: 0,\n total: 0,\n max: 0,\n min: Infinity,\n });\n }\n\n const stat = pluginStats.get(pluginName);\n stat.count++;\n stat.total += duration;\n stat.max = Math.max(stat.max, duration);\n stat.min = Math.min(stat.min, duration);\n } else if (target === 'Loader Analysis') {\n // Loader performance\n let loaderName = event.span?.name;\n\n // For pitch phase (span.name is null), use resource path\n if (!loaderName) {\n const resource = event.fields?.resource;\n if (resource) {\n // Extract filename from resource path\n const cleanResource = resource.replace(/^\"|\"$/g, ''); // Remove quotes\n const filename = cleanResource.split('/').pop();\n loaderName = `Loader pitch for ${filename}`;\n } else {\n loaderName = 'Loader pitch (unknown resource)';\n }\n }\n\n if (!loaderStats.has(loaderName)) {\n loaderStats.set(loaderName, {\n count: 0,\n total: 0,\n max: 0,\n min: Infinity,\n });\n }\n\n const stat = loaderStats.get(loaderName);\n stat.count++;\n stat.total += duration;\n stat.max = Math.max(stat.max, duration);\n stat.min = Math.min(stat.min, duration);\n }\n });\n\n // Display Plugin Analysis\n if (pluginStats.size > 0) {\n console.log('🔌 Plugin Analysis (by name):');\n console.log('─'.repeat(80));\n\n const sortedPlugins = [...pluginStats.entries()].sort(\n (a, b) => b[1].total - a[1].total,\n );\n\n sortedPlugins.forEach(([name, stat]) => {\n const avg = stat.total / stat.count;\n console.log(`${name}`);\n console.log(\n ` Total: ${stat.total.toFixed(2)}ms | Count: ${stat.count} | ` +\n `Avg: ${avg.toFixed(2)}ms | Max: ${stat.max.toFixed(2)}ms | Min: ${stat.min.toFixed(2)}ms`,\n );\n console.log('');\n });\n\n const totalPluginTime = [...pluginStats.values()].reduce(\n (sum, stat) => sum + stat.total,\n 0,\n );\n console.log(`Total Plugin Time: ${totalPluginTime.toFixed(2)}ms\\n`);\n }\n\n // Display Loader Analysis\n if (loaderStats.size > 0) {\n console.log('\\n🔧 Loader Analysis (by name):');\n console.log('─'.repeat(80));\n\n const sortedLoaders = [...loaderStats.entries()].sort(\n (a, b) => b[1].total - a[1].total,\n );\n\n sortedLoaders.forEach(([name, stat]) => {\n const avg = stat.total / stat.count;\n console.log(`${name}`);\n console.log(\n ` Total: ${stat.total.toFixed(2)}ms | Count: ${stat.count} | ` +\n `Avg: ${avg.toFixed(2)}ms | Max: ${stat.max.toFixed(2)}ms | Min: ${stat.min.toFixed(2)}ms`,\n );\n console.log('');\n });\n\n const totalLoaderTime = [...loaderStats.values()].reduce(\n (sum, stat) => sum + stat.total,\n 0,\n );\n console.log(`Total Loader Time: ${totalLoaderTime.toFixed(2)}ms\\n`);\n }\n} catch (err) {\n console.error('Error processing trace file:', err);\n process.exit(1);\n}\n"
|
|
72
69
|
};
|
|
73
70
|
exports.MWAFiles = __webpack_exports__.MWAFiles;
|
|
74
71
|
for(var __rspack_i in __webpack_exports__)if (-1 === [
|