@specdest/devkit 0.4.6 → 0.4.9

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.
Files changed (131) hide show
  1. package/README.md +52 -20
  2. package/dist/npm/canonical-project-operations.d.ts +5 -0
  3. package/dist/npm/canonical-project-operations.js +5 -0
  4. package/dist/npm/canonical-project.d.ts +21 -0
  5. package/dist/npm/canonical-project.js +115 -0
  6. package/dist/npm/canonical-source.d.ts +26 -0
  7. package/dist/npm/canonical-source.js +248 -0
  8. package/dist/npm/catalog-snapshot.d.ts +53 -0
  9. package/dist/npm/catalog-snapshot.js +35 -0
  10. package/dist/npm/cli.d.ts +2 -0
  11. package/dist/npm/cli.js +18 -0
  12. package/dist/npm/commands.d.ts +15 -0
  13. package/dist/npm/commands.js +182 -0
  14. package/dist/npm/flow.d.ts +48 -0
  15. package/dist/npm/flow.js +430 -0
  16. package/dist/npm/git-catalog.d.ts +40 -0
  17. package/dist/npm/git-catalog.js +222 -0
  18. package/dist/npm/index.d.ts +4 -0
  19. package/dist/npm/index.js +32 -0
  20. package/dist/npm/installer-primitives.d.ts +3 -0
  21. package/dist/npm/installer-primitives.js +50 -0
  22. package/dist/npm/predefined-packages/abac.d.ts +2 -0
  23. package/dist/npm/predefined-packages/abac.js +22 -0
  24. package/dist/npm/predefined-packages/auth.d.ts +2 -0
  25. package/dist/npm/predefined-packages/auth.js +21 -0
  26. package/dist/npm/predefined-packages/convex.d.ts +2 -0
  27. package/dist/npm/predefined-packages/convex.js +53 -0
  28. package/dist/npm/predefined-packages/expo.d.ts +2 -0
  29. package/dist/npm/predefined-packages/expo.js +88 -0
  30. package/dist/npm/predefined-packages/firebase-hosting.d.ts +2 -0
  31. package/dist/npm/predefined-packages/firebase-hosting.js +24 -0
  32. package/dist/npm/predefined-packages/health.d.ts +10 -0
  33. package/dist/npm/predefined-packages/health.js +52 -0
  34. package/dist/npm/predefined-packages/husky.d.ts +2 -0
  35. package/dist/npm/predefined-packages/husky.js +57 -0
  36. package/dist/npm/predefined-packages/index.d.ts +12 -0
  37. package/dist/npm/predefined-packages/index.js +97 -0
  38. package/dist/npm/predefined-packages/install.d.ts +19 -0
  39. package/dist/npm/predefined-packages/install.js +86 -0
  40. package/dist/npm/predefined-packages/local-logging.d.ts +2 -0
  41. package/dist/npm/predefined-packages/local-logging.js +17 -0
  42. package/dist/npm/predefined-packages/logging.d.ts +2 -0
  43. package/dist/npm/predefined-packages/logging.js +21 -0
  44. package/dist/npm/predefined-packages/multi-tenancy.d.ts +2 -0
  45. package/dist/npm/predefined-packages/multi-tenancy.js +21 -0
  46. package/dist/npm/predefined-packages/nps.d.ts +2 -0
  47. package/dist/npm/predefined-packages/nps.js +32 -0
  48. package/dist/npm/predefined-packages/oxfmt.d.ts +2 -0
  49. package/dist/npm/predefined-packages/oxfmt.js +22 -0
  50. package/dist/npm/predefined-packages/oxlint.d.ts +2 -0
  51. package/dist/npm/predefined-packages/oxlint.js +35 -0
  52. package/dist/npm/predefined-packages/package-json.d.ts +3 -0
  53. package/dist/npm/predefined-packages/package-json.js +61 -0
  54. package/dist/npm/predefined-packages/payments.d.ts +2 -0
  55. package/dist/npm/predefined-packages/payments.js +31 -0
  56. package/dist/npm/predefined-packages/playwright.d.ts +2 -0
  57. package/dist/npm/predefined-packages/playwright.js +35 -0
  58. package/dist/npm/predefined-packages/project-signals.d.ts +4 -0
  59. package/dist/npm/predefined-packages/project-signals.js +39 -0
  60. package/dist/npm/predefined-packages/registry.d.ts +3 -0
  61. package/dist/npm/predefined-packages/registry.js +63 -0
  62. package/dist/npm/predefined-packages/resolver.d.ts +8 -0
  63. package/dist/npm/predefined-packages/resolver.js +35 -0
  64. package/dist/npm/predefined-packages/sentry.d.ts +2 -0
  65. package/dist/npm/predefined-packages/sentry.js +29 -0
  66. package/dist/npm/predefined-packages/shadcn.d.ts +2 -0
  67. package/dist/npm/predefined-packages/shadcn.js +23 -0
  68. package/dist/npm/predefined-packages/storybook.d.ts +2 -0
  69. package/dist/npm/predefined-packages/storybook.js +25 -0
  70. package/dist/npm/predefined-packages/stryker.d.ts +2 -0
  71. package/dist/npm/predefined-packages/stryker.js +48 -0
  72. package/dist/npm/predefined-packages/supabase.d.ts +2 -0
  73. package/dist/npm/predefined-packages/supabase.js +335 -0
  74. package/dist/npm/predefined-packages/tailwind.d.ts +2 -0
  75. package/dist/npm/predefined-packages/tailwind.js +18 -0
  76. package/dist/npm/predefined-packages/tanstack-form.d.ts +2 -0
  77. package/dist/npm/predefined-packages/tanstack-form.js +19 -0
  78. package/dist/npm/predefined-packages/tanstack-query.d.ts +2 -0
  79. package/dist/npm/predefined-packages/tanstack-query.js +15 -0
  80. package/dist/npm/predefined-packages/tanstack-router.d.ts +2 -0
  81. package/dist/npm/predefined-packages/tanstack-router.js +18 -0
  82. package/dist/npm/predefined-packages/types.d.ts +38 -0
  83. package/dist/npm/predefined-packages/types.js +1 -0
  84. package/dist/npm/predefined-packages/vite.d.ts +2 -0
  85. package/dist/npm/predefined-packages/vite.js +127 -0
  86. package/dist/npm/predefined-packages/vitest.d.ts +2 -0
  87. package/dist/npm/predefined-packages/vitest.js +20 -0
  88. package/dist/npm/predefined-packages/zod.d.ts +2 -0
  89. package/dist/npm/predefined-packages/zod.js +18 -0
  90. package/dist/npm/project-check.d.ts +14 -0
  91. package/dist/npm/project-check.js +118 -0
  92. package/dist/npm/project-context.d.ts +52 -0
  93. package/dist/npm/project-context.js +206 -0
  94. package/dist/npm/project-rules.d.ts +25 -0
  95. package/dist/npm/project-rules.js +75 -0
  96. package/dist/npm/project-runtime.d.ts +21 -0
  97. package/dist/npm/project-runtime.js +41 -0
  98. package/dist/npm/project-status.d.ts +32 -0
  99. package/dist/npm/project-status.js +70 -0
  100. package/dist/npm/project-sync.d.ts +7 -0
  101. package/dist/npm/project-sync.js +143 -0
  102. package/dist/npm/remote-installer.d.ts +35 -0
  103. package/dist/npm/remote-installer.js +351 -0
  104. package/dist/npm/rule-id-migrations.d.ts +6 -0
  105. package/dist/npm/rule-id-migrations.js +19 -0
  106. package/dist/npm/schemas.d.ts +64 -0
  107. package/dist/npm/schemas.js +194 -0
  108. package/dist/npm/slack.d.ts +16 -0
  109. package/dist/npm/slack.js +131 -0
  110. package/dist/npm/state.d.ts +14 -0
  111. package/dist/npm/state.js +231 -0
  112. package/dist/npm/supabase-local.d.ts +2 -0
  113. package/dist/npm/supabase-local.js +62 -0
  114. package/package.json +18 -12
  115. package/src/canonical-project-operations.js +0 -438
  116. package/src/canonical-project.js +0 -136
  117. package/src/canonical-source.js +0 -250
  118. package/src/catalog-snapshot.js +0 -39
  119. package/src/catalog.js +0 -117
  120. package/src/cli.js +0 -14
  121. package/src/fuzz.js +0 -291
  122. package/src/git-catalog.js +0 -177
  123. package/src/index.js +0 -36
  124. package/src/installer-primitives.js +0 -198
  125. package/src/project-operations.js +0 -189
  126. package/src/project-targeting.js +0 -48
  127. package/src/remote-installer.js +0 -479
  128. package/src/rule-profile.js +0 -61
  129. package/src/setup-requirements.js +0 -82
  130. package/src/shared-file.js +0 -131
  131. package/src/sync-core.js +0 -390
@@ -0,0 +1,18 @@
1
+ import { detectDependency } from "./package-json.js";
2
+ export const tanstackRouterRecipe = {
3
+ id: 'tanstack-router',
4
+ recipeVersion: '1.0.0',
5
+ role: 'integration',
6
+ requires: ['vite'],
7
+ async detect(projectRoot) {
8
+ return await detectDependency(projectRoot, '@tanstack/react-router', '@tanstack/react-router');
9
+ },
10
+ async apply(_projectRoot, detection, _resolution) {
11
+ if (!detection.present) {
12
+ throw new Error('TanStack Router is not installed; creating router configuration is not supported by `add tanstack-router` yet.');
13
+ }
14
+ if (!detection.compatible)
15
+ throw new Error(detection.reason ?? 'Existing TanStack Router integration is not compatible.');
16
+ return { source: 'adopted' };
17
+ },
18
+ };
@@ -0,0 +1,38 @@
1
+ export type PackageSource = 'adopted' | 'installed';
2
+ export type PackageDetection = {
3
+ present: boolean;
4
+ compatible: boolean;
5
+ detectedVersion: string | null;
6
+ reason?: string;
7
+ };
8
+ export type PackageVariant = {
9
+ id: string;
10
+ when: string[];
11
+ };
12
+ export type PackageResolution = {
13
+ variant: string | null;
14
+ };
15
+ export type PackageSetupRequirement = {
16
+ kind: 'package';
17
+ packageId: string;
18
+ required: boolean;
19
+ when?: 'git';
20
+ };
21
+ export type PackageApplyContext = {
22
+ runCommand(command: string, args: string[], options: {
23
+ cwd: string;
24
+ }): Promise<void>;
25
+ };
26
+ export type PackageRecipe = {
27
+ id: string;
28
+ recipeVersion: string;
29
+ role: string;
30
+ requires?: string[];
31
+ conflicts?: string[];
32
+ variants?: PackageVariant[];
33
+ setupRequirements?: PackageSetupRequirement[];
34
+ detect(projectRoot: string): Promise<PackageDetection>;
35
+ apply(projectRoot: string, detection: PackageDetection, resolution: PackageResolution, context: PackageApplyContext): Promise<{
36
+ source: PackageSource;
37
+ }>;
38
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import type { PackageRecipe } from './types.ts';
2
+ export declare const viteRecipe: PackageRecipe;
@@ -0,0 +1,127 @@
1
+ import { basename } from 'node:path';
2
+ import { ensurePnpmBuildPolicy, mergeMissing, updatePackageJson, writeProjectFileIfMissing } from "./install.js";
3
+ import { detectDependency } from "./package-json.js";
4
+ const dependencies = {
5
+ react: '19.2.3',
6
+ 'react-dom': '19.2.3',
7
+ };
8
+ const devDependencies = {
9
+ '@types/react': '19.2.7',
10
+ '@types/react-dom': '19.2.3',
11
+ '@vitejs/plugin-react': '5.1.2',
12
+ typescript: '6.0.3',
13
+ vite: '7.3.0',
14
+ };
15
+ function packageName(projectRoot) {
16
+ const normalized = basename(projectRoot).toLowerCase().replace(/[^a-z0-9._-]+/gu, '-');
17
+ return normalized || 'specdest-app';
18
+ }
19
+ async function installVite(projectRoot, context) {
20
+ await updatePackageJson(projectRoot, (pkg) => ({
21
+ ...pkg,
22
+ name: pkg.name ?? packageName(projectRoot),
23
+ private: pkg.private ?? true,
24
+ type: pkg.type ?? 'module',
25
+ packageManager: pkg.packageManager ?? 'pnpm@11.6.0',
26
+ engines: {
27
+ ...pkg.engines,
28
+ node: pkg.engines?.node ?? '>=24.0.0',
29
+ pnpm: pkg.engines?.pnpm ?? '>=11.0.0',
30
+ },
31
+ scripts: mergeMissing(pkg.scripts, {
32
+ dev: 'vite',
33
+ build: 'tsc -b && vite build',
34
+ typecheck: 'tsc -b',
35
+ preview: 'vite preview',
36
+ }),
37
+ dependencies: mergeMissing(pkg.dependencies, dependencies),
38
+ devDependencies: mergeMissing(pkg.devDependencies, devDependencies),
39
+ }));
40
+ await ensurePnpmBuildPolicy(projectRoot);
41
+ await writeProjectFileIfMissing(projectRoot, 'index.html', `<!doctype html>
42
+ <html lang="en">
43
+ <head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /></head>
44
+ <body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body>
45
+ </html>
46
+ `);
47
+ await writeProjectFileIfMissing(projectRoot, 'src/main.tsx', `import { StrictMode } from 'react';
48
+ import { createRoot } from 'react-dom/client';
49
+ import App from './App';
50
+
51
+ createRoot(document.getElementById('root')!).render(
52
+ <StrictMode>
53
+ <App />
54
+ </StrictMode>,
55
+ );
56
+ `);
57
+ await writeProjectFileIfMissing(projectRoot, 'src/App.tsx', `export default function App() {
58
+ return <main>Specdest app</main>;
59
+ }
60
+ `);
61
+ await writeProjectFileIfMissing(projectRoot, 'vite.config.ts', `import { defineConfig } from 'vite';
62
+ import react from '@vitejs/plugin-react';
63
+
64
+ export default defineConfig({ plugins: [react()] });
65
+ `);
66
+ await writeProjectFileIfMissing(projectRoot, 'tsconfig.json', `{
67
+ "files": [],
68
+ "references": [
69
+ { "path": "./tsconfig.app.json" },
70
+ { "path": "./tsconfig.node.json" }
71
+ ]
72
+ }
73
+ `);
74
+ await writeProjectFileIfMissing(projectRoot, 'tsconfig.app.json', `{
75
+ "compilerOptions": {
76
+ "target": "ES2022",
77
+ "useDefineForClassFields": true,
78
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
79
+ "skipLibCheck": true,
80
+ "module": "ESNext",
81
+ "moduleResolution": "Bundler",
82
+ "allowImportingTsExtensions": true,
83
+ "resolveJsonModule": true,
84
+ "isolatedModules": true,
85
+ "noEmit": true,
86
+ "jsx": "react-jsx",
87
+ "strict": true
88
+ },
89
+ "include": ["src"]
90
+ }
91
+ `);
92
+ await writeProjectFileIfMissing(projectRoot, 'tsconfig.node.json', `{
93
+ "compilerOptions": {
94
+ "composite": true,
95
+ "skipLibCheck": true,
96
+ "module": "ESNext",
97
+ "moduleResolution": "Bundler",
98
+ "allowImportingTsExtensions": true,
99
+ "noEmit": true
100
+ },
101
+ "include": ["vite.config.ts"]
102
+ }
103
+ `);
104
+ await context.runCommand('pnpm', ['install', '--no-frozen-lockfile'], { cwd: projectRoot });
105
+ }
106
+ export const viteRecipe = {
107
+ id: 'vite',
108
+ recipeVersion: '1.2.0',
109
+ role: 'frontend',
110
+ setupRequirements: [
111
+ { kind: 'package', packageId: 'oxlint', required: true },
112
+ { kind: 'package', packageId: 'husky', required: true, when: 'git' },
113
+ ],
114
+ conflicts: ['expo'],
115
+ async detect(projectRoot) {
116
+ return await detectDependency(projectRoot, 'vite', 'Vite');
117
+ },
118
+ async apply(projectRoot, detection, _resolution, context) {
119
+ if (detection.present) {
120
+ if (!detection.compatible)
121
+ throw new Error(detection.reason ?? 'Existing Vite setup is not compatible.');
122
+ return { source: 'adopted' };
123
+ }
124
+ await installVite(projectRoot, context);
125
+ return { source: 'installed' };
126
+ },
127
+ };
@@ -0,0 +1,2 @@
1
+ import type { PackageRecipe } from './types.ts';
2
+ export declare const vitestRecipe: PackageRecipe;
@@ -0,0 +1,20 @@
1
+ import { installPackageJsonPatch } from "./install.js";
2
+ import { detectDependency } from "./package-json.js";
3
+ export const vitestRecipe = {
4
+ id: 'vitest',
5
+ recipeVersion: '1.1.0',
6
+ role: 'integration',
7
+ requires: ['vite'],
8
+ async detect(projectRoot) {
9
+ return await detectDependency(projectRoot, 'vitest', 'Vitest');
10
+ },
11
+ async apply(projectRoot, detection, _resolution, context) {
12
+ if (detection.present)
13
+ return { source: 'adopted' };
14
+ await installPackageJsonPatch(projectRoot, context.runCommand, {
15
+ devDependencies: { vitest: '4.1.0' },
16
+ scripts: { test: 'vitest run', 'test:watch': 'vitest' },
17
+ });
18
+ return { source: 'installed' };
19
+ },
20
+ };
@@ -0,0 +1,2 @@
1
+ import type { PackageRecipe } from './types.ts';
2
+ export declare const zodRecipe: PackageRecipe;
@@ -0,0 +1,18 @@
1
+ import { installPackageJsonPatch } from "./install.js";
2
+ import { detectDependency } from "./package-json.js";
3
+ export const zodRecipe = {
4
+ id: 'zod',
5
+ recipeVersion: '1.1.0',
6
+ role: 'integration',
7
+ async detect(projectRoot) {
8
+ return await detectDependency(projectRoot, 'zod', 'Zod');
9
+ },
10
+ async apply(projectRoot, detection, _resolution, context) {
11
+ if (detection.present)
12
+ return { source: 'adopted' };
13
+ await installPackageJsonPatch(projectRoot, context.runCommand, {
14
+ dependencies: { zod: '4.3.6' },
15
+ });
16
+ return { source: 'installed' };
17
+ },
18
+ };
@@ -0,0 +1,14 @@
1
+ export declare function runWithConcurrency<T, R>(items: T[], limit: number, worker: (item: T, index: number) => Promise<R>): Promise<R[]>;
2
+ export declare function canonicalCheck(projectRoot: string, source: any, options?: any): Promise<{
3
+ exitCode: number;
4
+ results: {
5
+ [k: string]: any;
6
+ };
7
+ executions: {
8
+ ids: any[];
9
+ checkerPath: any;
10
+ exitCode: any;
11
+ stdout: any;
12
+ stderr: any;
13
+ }[];
14
+ }>;
@@ -0,0 +1,118 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { loadCanonicalProjectContext, prepareCanonicalManifest } from "./project-runtime.js";
3
+ import { assertPredefinedPackageState } from "./predefined-packages/health.js";
4
+ import { readInstalledState, writeChecksState } from "./state.js";
5
+ function execute(command, args, cwd) {
6
+ return new Promise((resolve, reject) => {
7
+ const child = spawn(command, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
8
+ let stdout = '';
9
+ let stderr = '';
10
+ child.stdout.setEncoding('utf8');
11
+ child.stderr.setEncoding('utf8');
12
+ child.stdout.on('data', (chunk) => {
13
+ stdout += chunk;
14
+ });
15
+ child.stderr.on('data', (chunk) => {
16
+ stderr += chunk;
17
+ });
18
+ child.on('error', reject);
19
+ child.on('close', (code) => resolve({ exitCode: code ?? 1, stdout, stderr }));
20
+ });
21
+ }
22
+ export async function runWithConcurrency(items, limit, worker) {
23
+ const concurrency = Math.max(1, Math.min(Math.floor(limit), items.length || 1));
24
+ const results = new Array(items.length);
25
+ let nextIndex = 0;
26
+ await Promise.all(Array.from({ length: concurrency }, async () => {
27
+ while (nextIndex < items.length) {
28
+ const index = nextIndex++;
29
+ results[index] = await worker(items[index], index);
30
+ }
31
+ }));
32
+ return results;
33
+ }
34
+ export async function canonicalCheck(projectRoot, source, options = {}) {
35
+ await assertPredefinedPackageState(projectRoot);
36
+ const current = await readInstalledState(projectRoot);
37
+ const { applicable, canonicalCheckRoot, checkerRuntimeRoot } = await loadCanonicalProjectContext(projectRoot, source, { offline: false, withCheckers: true, refresh: options.refresh ?? false });
38
+ const byId = new Map(applicable.map((entry) => [entry.id, entry]));
39
+ const results = {};
40
+ const groups = new Map();
41
+ const executor = options.executor ?? execute;
42
+ const targetMode = options.mode ?? 'full';
43
+ let targetFiles = options.files ?? null;
44
+ if (targetMode === 'staged' && targetFiles === null) {
45
+ const staged = await executor('git', ['diff', '--cached', '--name-only', '-z', '--diff-filter=ACMR'], projectRoot);
46
+ if (staged.exitCode !== 0)
47
+ throw new Error(staged.stderr || 'Unable to read staged files');
48
+ targetFiles = staged.stdout.split('\0').filter(Boolean);
49
+ }
50
+ const normalizedTargetFiles = (targetFiles ?? []).map((file) => String(file).replaceAll('\\', '/'));
51
+ let exitCode = 0;
52
+ for (const [id, installed] of Object.entries(current.installed).sort(([a], [b]) => a.localeCompare(b))) {
53
+ const entry = byId.get(id);
54
+ if (!entry || installed.kind !== 'rule')
55
+ continue;
56
+ const prepared = await prepareCanonicalManifest(source, entry, canonicalCheckRoot, checkerRuntimeRoot);
57
+ if (!prepared?.checkerPath) {
58
+ if ((entry.enforcement ?? 'guidance') === 'guidance')
59
+ continue;
60
+ results[id] = {
61
+ status: 'fail',
62
+ exitCode: 1,
63
+ stderr: 'Canonical checker unavailable for enforced installed rule.',
64
+ };
65
+ exitCode = 1;
66
+ continue;
67
+ }
68
+ if (prepared.execution === 'manual')
69
+ continue;
70
+ const baseKey = prepared.checkerKey ??
71
+ `path:${prepared.checkerPath}:${JSON.stringify(prepared.checkerArgs ?? [])}`;
72
+ const key = `${baseKey}:targeting:${prepared.targeting?.scope ?? 'repository'}:execution:${prepared.execution ?? 'automatic'}`;
73
+ const group = groups.get(key) ?? {
74
+ checkerPath: prepared.checkerPath,
75
+ checkerArgs: prepared.checkerArgs ?? [],
76
+ targeting: prepared.targeting ?? { scope: 'repository' },
77
+ ids: [],
78
+ };
79
+ group.ids.push(id);
80
+ groups.set(key, group);
81
+ }
82
+ const groupExecutions = await runWithConcurrency([...groups.values()], options.concurrency ?? 6, async (group) => {
83
+ const args = [group.checkerPath, ...group.checkerArgs];
84
+ if (targetMode !== 'full' && group.targeting.scope !== 'repository') {
85
+ args.push('--target-mode', targetMode);
86
+ for (const file of normalizedTargetFiles)
87
+ args.push('--target-file', file);
88
+ }
89
+ const execution = await executor('node', args, projectRoot);
90
+ return { group, execution };
91
+ });
92
+ for (const { group, execution } of groupExecutions) {
93
+ const result = { status: execution.exitCode === 0 ? 'pass' : 'fail', ...execution };
94
+ for (const id of group.ids)
95
+ results[id] = result;
96
+ if (execution.exitCode !== 0)
97
+ exitCode = 1;
98
+ }
99
+ const orderedResults = Object.fromEntries(Object.entries(results).sort(([a], [b]) => a.localeCompare(b)));
100
+ if (targetMode === 'full') {
101
+ await writeChecksState(projectRoot, {
102
+ schemaVersion: 2,
103
+ checkedAt: new Date().toISOString(),
104
+ results: Object.fromEntries(Object.entries(orderedResults).map(([id, result]) => [id, { status: result.status }])),
105
+ });
106
+ }
107
+ return {
108
+ exitCode,
109
+ results: orderedResults,
110
+ executions: groupExecutions.map(({ group, execution }) => ({
111
+ ids: [...group.ids].sort(),
112
+ checkerPath: group.checkerPath,
113
+ exitCode: execution.exitCode,
114
+ stdout: execution.stdout,
115
+ stderr: execution.stderr,
116
+ })),
117
+ };
118
+ }
@@ -0,0 +1,52 @@
1
+ export declare const RULE_PROFILE_RELATIVE_PATH = ".spd/rules.json";
2
+ export declare const PROJECT_TYPES: readonly string[];
3
+ export declare const EMPTY_RULE_PROFILE: Readonly<{
4
+ schemaVersion: 1;
5
+ projectType: null;
6
+ capabilities: never[];
7
+ include: never[];
8
+ exclude: never[];
9
+ }>;
10
+ export declare function validateRuleProfile(profile: unknown): {
11
+ schemaVersion: number;
12
+ projectType: string | null;
13
+ capabilities: unknown[];
14
+ include: unknown[];
15
+ exclude: {
16
+ id: string;
17
+ reason: string;
18
+ }[];
19
+ };
20
+ export declare function readRuleProfile(projectRoot: string): Promise<{
21
+ schemaVersion: number;
22
+ projectType: string | null;
23
+ capabilities: unknown[];
24
+ include: unknown[];
25
+ exclude: {
26
+ id: string;
27
+ reason: string;
28
+ }[];
29
+ }>;
30
+ export declare function assertKnownRuleOverrides(entries: any[], profile: any): void;
31
+ export declare function resolveProjectType(stack: string | null, profile?: any): any;
32
+ export declare const STACK_PACKAGES: Record<string, string[]>;
33
+ export declare function ruleApplies(entry: any, stack: string | null, profile?: any, packageIds?: Iterable<string>): boolean;
34
+ export declare function projectRuleApplies(entry: any, stack: string | null, profile?: any, entries?: any[], packageIds?: Iterable<string>): any;
35
+ export declare function applicableCatalogEntries(entries: any[], stack: string | null, profile?: any, packageIds?: Iterable<string>): any[];
36
+ export declare function detectProjectStack(projectRoot: string): Promise<string | null>;
37
+ export declare function resolveProjectStack(projectRoot: string): Promise<any>;
38
+ export declare function loadProjectContext(projectRoot: string, entries: any[]): Promise<{
39
+ stack: any;
40
+ profile: {
41
+ schemaVersion: number;
42
+ projectType: string | null;
43
+ capabilities: unknown[];
44
+ include: unknown[];
45
+ exclude: {
46
+ id: string;
47
+ reason: string;
48
+ }[];
49
+ };
50
+ projectType: any;
51
+ applicable: any[];
52
+ }>;
@@ -0,0 +1,206 @@
1
+ import { readFile, readdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { PackageJsonSchema, RuleProfileSchema, parseWithSchema } from "./schemas.js";
4
+ import { ensureMetadataNamespace, readInstalledState } from "./state.js";
5
+ export const RULE_PROFILE_RELATIVE_PATH = '.spd/rules.json';
6
+ export const PROJECT_TYPES = Object.freeze([
7
+ 'product',
8
+ 'static-site',
9
+ 'tooling',
10
+ 'backend',
11
+ 'monorepo',
12
+ 'generic',
13
+ ]);
14
+ export const EMPTY_RULE_PROFILE = Object.freeze({
15
+ schemaVersion: 1,
16
+ projectType: null,
17
+ capabilities: [],
18
+ include: [],
19
+ exclude: [],
20
+ });
21
+ function uniqueStrings(values, label) {
22
+ if (!Array.isArray(values ?? []))
23
+ throw new Error(`Invalid ${label}`);
24
+ return [
25
+ ...new Set((values ?? [])
26
+ .map(String)
27
+ .map((value) => value.trim())
28
+ .filter(Boolean)),
29
+ ].sort();
30
+ }
31
+ export function validateRuleProfile(profile) {
32
+ const validated = parseWithSchema(RuleProfileSchema, profile, '.spd/rules.json profile');
33
+ const projectType = validated.projectType == null ? null : validated.projectType.trim();
34
+ if (validated.projectType != null && !projectType)
35
+ throw new Error('Invalid rule profile projectType');
36
+ const capabilities = uniqueStrings(validated.capabilities, 'rule profile capabilities');
37
+ const include = uniqueStrings(validated.include, 'rule profile include');
38
+ const exclude = (validated.exclude ?? [])
39
+ .map((item) => {
40
+ if (!item ||
41
+ typeof item !== 'object' ||
42
+ !String(item.id ?? '').trim() ||
43
+ !String(item.reason ?? '').trim()) {
44
+ throw new Error('Rule exclusions require both id and non-empty reason');
45
+ }
46
+ return { id: String(item.id).trim(), reason: String(item.reason).trim() };
47
+ })
48
+ .sort((a, b) => a.id.localeCompare(b.id));
49
+ return { schemaVersion: 1, projectType, capabilities, include, exclude };
50
+ }
51
+ export async function readRuleProfile(projectRoot) {
52
+ await ensureMetadataNamespace(projectRoot);
53
+ try {
54
+ return validateRuleProfile(JSON.parse(await readFile(join(projectRoot, RULE_PROFILE_RELATIVE_PATH), 'utf8')));
55
+ }
56
+ catch (error) {
57
+ if (error?.code === 'ENOENT')
58
+ return { ...EMPTY_RULE_PROFILE, capabilities: [], include: [], exclude: [] };
59
+ throw error;
60
+ }
61
+ }
62
+ export function assertKnownRuleOverrides(entries, profile) {
63
+ const ids = new Set(entries.filter((entry) => entry.kind === 'rule').map((entry) => entry.id));
64
+ for (const id of profile.include ?? [])
65
+ if (!ids.has(id))
66
+ throw new Error(`Unknown included rule: ${id}`);
67
+ for (const item of profile.exclude ?? [])
68
+ if (!ids.has(item.id))
69
+ throw new Error(`Unknown excluded rule: ${item.id}`);
70
+ }
71
+ export function resolveProjectType(stack, profile = EMPTY_RULE_PROFILE) {
72
+ return profile.projectType ?? (stack ? 'product' : 'generic');
73
+ }
74
+ export const STACK_PACKAGES = {
75
+ 'stack-vite-supabase': ['vite', 'supabase'],
76
+ 'stack-vite-convex': ['vite', 'convex'],
77
+ 'stack-expo-supabase': ['expo', 'supabase'],
78
+ 'stack-expo-convex': ['expo', 'convex'],
79
+ };
80
+ function effectivePackages(stack, packageIds = []) {
81
+ return new Set([...(stack ? (STACK_PACKAGES[stack] ?? []) : []), ...packageIds]);
82
+ }
83
+ export function ruleApplies(entry, stack, profile = EMPTY_RULE_PROFILE, packageIds = []) {
84
+ const included = new Set(profile.include ?? []);
85
+ const excluded = new Set((profile.exclude ?? []).map((item) => item.id));
86
+ if (excluded.has(entry.id))
87
+ return false;
88
+ if (included.has(entry.id))
89
+ return true;
90
+ if (entry.applicableStacks?.length && (!stack || !entry.applicableStacks.includes(stack)))
91
+ return false;
92
+ const packages = effectivePackages(stack, packageIds);
93
+ if (entry.requiredPackages?.some((id) => !packages.has(id)))
94
+ return false;
95
+ return capabilitySatisfied(entry, profile);
96
+ }
97
+ function profileDefinition(entries, projectType) {
98
+ if (projectType === 'product')
99
+ return null;
100
+ const module = entries.find((entry) => entry.kind === 'module' && entry.id === 'project-profiles');
101
+ const definition = module?.projectProfiles?.[projectType];
102
+ if (!definition)
103
+ throw new Error(`Canonical project profile not found: ${projectType}`);
104
+ return definition;
105
+ }
106
+ function capabilitySatisfied(entry, profile) {
107
+ const capabilities = new Set(profile.capabilities ?? []);
108
+ return !entry.requiredCapabilities?.some((capability) => !capabilities.has(capability));
109
+ }
110
+ export function projectRuleApplies(entry, stack, profile = EMPTY_RULE_PROFILE, entries = [], packageIds = []) {
111
+ const included = new Set(profile.include ?? []);
112
+ const excluded = new Set((profile.exclude ?? []).map((item) => item.id));
113
+ if (excluded.has(entry.id))
114
+ return false;
115
+ if (included.has(entry.id))
116
+ return true;
117
+ const projectType = resolveProjectType(stack, profile);
118
+ if (projectType === 'product')
119
+ return ruleApplies(entry, stack, profile, packageIds);
120
+ const definition = profileDefinition(entries, projectType);
121
+ return definition.ruleIds.includes(entry.id) && capabilitySatisfied(entry, profile);
122
+ }
123
+ export function applicableCatalogEntries(entries, stack, profile = EMPTY_RULE_PROFILE, packageIds = []) {
124
+ return entries
125
+ .filter((entry) => entry.kind === 'rule')
126
+ .filter((entry) => projectRuleApplies(entry, stack, profile, entries, packageIds))
127
+ .sort((a, b) => a.id.localeCompare(b.id));
128
+ }
129
+ function stackFromDependencies(deps) {
130
+ const frontends = [
131
+ deps.expo ? 'expo' : null,
132
+ deps.vite || deps['@vitejs/plugin-react'] ? 'vite' : null,
133
+ ].filter(Boolean);
134
+ const backends = [
135
+ deps.convex ? 'convex' : null,
136
+ deps['@supabase/supabase-js'] ? 'supabase' : null,
137
+ ].filter(Boolean);
138
+ if (frontends.length > 1)
139
+ throw new Error(`Conflicting frontend packages detected: ${frontends.sort().join(', ')}`);
140
+ if (backends.length > 1)
141
+ throw new Error(`Conflicting backend packages detected: ${backends.sort().join(', ')}`);
142
+ if (frontends.length !== 1 || backends.length !== 1)
143
+ return null;
144
+ return `stack-${frontends[0]}-${backends[0]}`;
145
+ }
146
+ async function readPackageDependencies(path) {
147
+ try {
148
+ const pkg = parseWithSchema(PackageJsonSchema, JSON.parse(await readFile(path, 'utf8')), `package.json at ${path}`);
149
+ return { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };
150
+ }
151
+ catch (error) {
152
+ if (error?.code === 'ENOENT')
153
+ return null;
154
+ throw error;
155
+ }
156
+ }
157
+ export async function detectProjectStack(projectRoot) {
158
+ const dependencySets = [];
159
+ const rootDeps = await readPackageDependencies(join(projectRoot, 'package.json'));
160
+ if (rootDeps)
161
+ dependencySets.push(rootDeps);
162
+ for (const group of ['apps', 'packages']) {
163
+ let children = [];
164
+ try {
165
+ children = await readdir(join(projectRoot, group), { withFileTypes: true });
166
+ }
167
+ catch (error) {
168
+ if (error?.code !== 'ENOENT')
169
+ throw error;
170
+ }
171
+ for (const child of children.filter((entry) => entry.isDirectory())) {
172
+ const deps = await readPackageDependencies(join(projectRoot, group, child.name, 'package.json'));
173
+ if (deps)
174
+ dependencySets.push(deps);
175
+ }
176
+ }
177
+ const detected = new Set(dependencySets.map(stackFromDependencies).filter(Boolean));
178
+ if (detected.size === 1)
179
+ return [...detected][0];
180
+ if (detected.size > 1)
181
+ throw new Error(`Multiple canonical stacks detected: ${[...detected].sort().join(', ')}`);
182
+ return stackFromDependencies(Object.assign({}, ...dependencySets));
183
+ }
184
+ export async function resolveProjectStack(projectRoot) {
185
+ const detectedStack = await detectProjectStack(projectRoot);
186
+ if (detectedStack)
187
+ return detectedStack;
188
+ const installedState = await readInstalledState(projectRoot);
189
+ const requestedStacks = (installedState.requested ?? []).filter((id) => id.startsWith('stack-'));
190
+ return requestedStacks.length === 1 ? requestedStacks[0] : null;
191
+ }
192
+ export async function loadProjectContext(projectRoot, entries) {
193
+ const stack = await resolveProjectStack(projectRoot);
194
+ const installedState = await readInstalledState(projectRoot);
195
+ const packageIds = Object.entries(installedState.installed ?? {})
196
+ .filter(([, value]) => value?.kind === 'package')
197
+ .map(([id]) => id);
198
+ const profile = await readRuleProfile(projectRoot);
199
+ assertKnownRuleOverrides(entries, profile);
200
+ return {
201
+ stack,
202
+ profile,
203
+ projectType: resolveProjectType(stack, profile),
204
+ applicable: applicableCatalogEntries(entries, stack, profile, packageIds),
205
+ };
206
+ }
@@ -0,0 +1,25 @@
1
+ export declare function aiInstructionText(): string;
2
+ export declare function canonicalRules(projectRoot: string, source: any, options?: any): Promise<{
3
+ stack: any;
4
+ profile: {
5
+ schemaVersion: number;
6
+ projectType: string | null;
7
+ capabilities: unknown[];
8
+ include: unknown[];
9
+ exclude: {
10
+ id: string;
11
+ reason: string;
12
+ }[];
13
+ };
14
+ detail: boolean;
15
+ rules: {
16
+ content?: any;
17
+ id: any;
18
+ name: any;
19
+ category: any;
20
+ enforcement: any;
21
+ aiLoad: any;
22
+ summary: any;
23
+ composedOf: any;
24
+ }[];
25
+ }>;