@specdest/devkit 0.4.8 → 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 (47) hide show
  1. package/README.md +26 -24
  2. package/dist/npm/canonical-project.d.ts +12 -1
  3. package/dist/npm/canonical-project.js +10 -4
  4. package/dist/npm/canonical-source.d.ts +14 -2
  5. package/dist/npm/canonical-source.js +46 -14
  6. package/dist/npm/catalog-snapshot.d.ts +32 -26
  7. package/dist/npm/catalog-snapshot.js +11 -4
  8. package/dist/npm/cli.js +5 -2
  9. package/dist/npm/commands.d.ts +6 -0
  10. package/dist/npm/commands.js +33 -8
  11. package/dist/npm/flow.js +52 -18
  12. package/dist/npm/git-catalog.d.ts +33 -32
  13. package/dist/npm/git-catalog.js +49 -17
  14. package/dist/npm/index.d.ts +0 -1
  15. package/dist/npm/index.js +13 -3
  16. package/dist/npm/installer-primitives.d.ts +3 -3
  17. package/dist/npm/predefined-packages/expo.js +5 -1
  18. package/dist/npm/predefined-packages/index.d.ts +1 -0
  19. package/dist/npm/predefined-packages/index.js +44 -3
  20. package/dist/npm/predefined-packages/install.js +3 -2
  21. package/dist/npm/predefined-packages/supabase.js +271 -20
  22. package/dist/npm/predefined-packages/types.d.ts +7 -0
  23. package/dist/npm/predefined-packages/vite.js +5 -1
  24. package/dist/npm/project-check.d.ts +8 -0
  25. package/dist/npm/project-check.js +38 -7
  26. package/dist/npm/project-context.d.ts +14 -4
  27. package/dist/npm/project-context.js +32 -18
  28. package/dist/npm/project-rules.d.ts +4 -1
  29. package/dist/npm/project-rules.js +15 -6
  30. package/dist/npm/project-runtime.d.ts +4 -1
  31. package/dist/npm/project-runtime.js +19 -5
  32. package/dist/npm/project-status.js +17 -3
  33. package/dist/npm/project-sync.js +13 -5
  34. package/dist/npm/remote-installer.d.ts +35 -4
  35. package/dist/npm/remote-installer.js +75 -36
  36. package/dist/npm/rule-id-migrations.d.ts +6 -0
  37. package/dist/npm/rule-id-migrations.js +19 -0
  38. package/dist/npm/schemas.d.ts +64 -0
  39. package/dist/npm/schemas.js +194 -0
  40. package/dist/npm/slack.d.ts +16 -0
  41. package/dist/npm/slack.js +131 -0
  42. package/dist/npm/state.js +71 -22
  43. package/dist/npm/supabase-local.d.ts +2 -0
  44. package/dist/npm/supabase-local.js +62 -0
  45. package/package.json +10 -7
  46. package/dist/npm/fuzz.d.ts +0 -138
  47. package/dist/npm/fuzz.js +0 -327
@@ -1,4 +1,6 @@
1
- import { ensurePnpmBuildPolicy, mergeMissing, projectPackageName, updatePackageJson, writeProjectFileIfMissing } from "./install.js";
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { ensurePnpmBuildPolicy, mergeMissing, projectPackageName, updatePackageJson, writeProjectFileIfMissing, } from "./install.js";
2
4
  import { detectDependency } from "./package-json.js";
3
5
  const bootstrapDatabaseTypes = `export type Database = {
4
6
  public: {
@@ -13,27 +15,220 @@ const bootstrapDatabaseTypes = `export type Database = {
13
15
  const bootstrapSchema = `// generated schema placeholder; regenerate after defining database tables.
14
16
  export {};
15
17
  `;
18
+ const humanRemoteGuard = `const HUMAN_ACK = 'I_AM_A_HUMAN_RUNNING_REMOTE_INFRASTRUCTURE';
19
+
20
+ const operationIndex = process.argv.indexOf('--operation');
21
+ const operation = operationIndex >= 0 ? process.argv[operationIndex + 1] : undefined;
22
+
23
+ if (!operation) {
24
+ console.error('Remote-operation guard requires --operation <name>.');
25
+ process.exit(1);
26
+ }
27
+
28
+ if (process.env.SPECDEST_HUMAN_REMOTE_ACK !== HUMAN_ACK) {
29
+ console.error(
30
+ \`Blocked \${operation}: set SPECDEST_HUMAN_REMOTE_ACK=\${HUMAN_ACK} only from an interactive human shell.\`,
31
+ );
32
+ process.exit(1);
33
+ }
34
+
35
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
36
+ console.error(\`Blocked \${operation}: remote infrastructure commands require an interactive TTY.\`);
37
+ process.exit(1);
38
+ }
39
+
40
+ console.log(\`Human-only remote operation approved: \${operation}\`);
41
+ `;
42
+ const productionReconcile = `const { spawnSync } = require('node:child_process');
43
+ const fs = require('node:fs');
44
+ const path = require('node:path');
45
+
46
+ const MIGRATION_PREFIX = /^(\\d{14})_/;
47
+
48
+ function formatMigrationTimestamp(date) {
49
+ const pad = (value) => String(value).padStart(2, '0');
50
+ return [
51
+ date.getUTCFullYear(),
52
+ pad(date.getUTCMonth() + 1),
53
+ pad(date.getUTCDate()),
54
+ pad(date.getUTCHours()),
55
+ pad(date.getUTCMinutes()),
56
+ pad(date.getUTCSeconds()),
57
+ ].join('');
58
+ }
59
+
60
+ function parseMigrationTimestamp(value) {
61
+ const year = Number(value.slice(0, 4));
62
+ const month = Number(value.slice(4, 6)) - 1;
63
+ const day = Number(value.slice(6, 8));
64
+ const hour = Number(value.slice(8, 10));
65
+ const minute = Number(value.slice(10, 12));
66
+ const second = Number(value.slice(12, 14));
67
+ return new Date(Date.UTC(year, month, day, hour, minute, second));
68
+ }
69
+
70
+ function nextMigrationTimestamp({ migrationsDir, now }) {
71
+ const current = formatMigrationTimestamp(now);
72
+ const latest = fs
73
+ .readdirSync(migrationsDir)
74
+ .map((name) => name.match(MIGRATION_PREFIX)?.[1])
75
+ .filter(Boolean)
76
+ .sort()
77
+ .at(-1);
78
+
79
+ if (!latest) {
80
+ const previousSecond = new Date(now);
81
+ previousSecond.setUTCSeconds(previousSecond.getUTCSeconds() - 1);
82
+ return formatMigrationTimestamp(previousSecond);
83
+ }
84
+
85
+ const next = parseMigrationTimestamp(latest);
86
+ next.setUTCSeconds(next.getUTCSeconds() + 1);
87
+ const candidate = formatMigrationTimestamp(next);
88
+ if (candidate >= current) {
89
+ throw new Error(
90
+ 'Cannot place production reconciliation before the next generated migration; retry after the clock advances.',
91
+ );
92
+ }
93
+ return candidate;
94
+ }
95
+
96
+ function isIdentifier(value) {
97
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(value) || (value.startsWith('"') && value.endsWith('"'));
98
+ }
99
+
100
+ function matchesQualifiedStatement(trimmed, prefix, suffix) {
101
+ if (!trimmed.startsWith(prefix) || !trimmed.endsWith(suffix)) return false;
102
+ return isIdentifier(trimmed.slice(prefix.length, -suffix.length));
103
+ }
104
+
105
+ function isReplaySafeStatement(line) {
106
+ const trimmed = line.trim();
107
+ if (!trimmed) return false;
108
+ if (
109
+ ['ALTER TABLE public.', 'ALTER TABLE "public".'].some((prefix) =>
110
+ matchesQualifiedStatement(trimmed, prefix, ' ENABLE ROW LEVEL SECURITY;'),
111
+ )
112
+ ) {
113
+ return true;
114
+ }
115
+ return ['ALTER VIEW public.', 'ALTER VIEW "public".'].some((prefix) =>
116
+ [
117
+ ' SET (security_invoker=true);',
118
+ ' SET (security_invoker = true);',
119
+ ].some((suffix) => matchesQualifiedStatement(trimmed, prefix, suffix)),
120
+ );
121
+ }
122
+
123
+ function isIgnorableDiffPreamble(line) {
124
+ return line.trim() === 'SET check_function_bodies = false;';
125
+ }
126
+
127
+ function extractReplaySafeSql(sql) {
128
+ const safe = [];
129
+ const unsafe = [];
130
+ for (const line of sql.split(/\\r?\\n/)) {
131
+ if (!line.trim() || isIgnorableDiffPreamble(line)) continue;
132
+ if (isReplaySafeStatement(line)) safe.push(line.trim());
133
+ else unsafe.push(line);
134
+ }
135
+ return {
136
+ safeSql: safe.length > 0 ? \`\${safe.join('\\n')}\\n\` : '',
137
+ unsafeSql: unsafe.length > 0 ? \`\${unsafe.join('\\n')}\\n\` : '',
138
+ };
139
+ }
140
+
141
+ function persistMigration({ migrationsDir, sql, now = new Date() }) {
142
+ if (!sql.trim()) return null;
143
+ fs.mkdirSync(migrationsDir, { recursive: true });
144
+ const timestamp = nextMigrationTimestamp({ migrationsDir, now });
145
+ const outputPath = path.join(migrationsDir, \`\${timestamp}_production_reconcile.sql\`);
146
+ fs.writeFileSync(outputPath, \`\${sql.trimEnd()}\\n\`, { flag: 'wx' });
147
+ return outputPath;
148
+ }
149
+
150
+ function persistReview({ reviewPath, sql }) {
151
+ if (!sql.trim()) return null;
152
+ fs.mkdirSync(path.dirname(reviewPath), { recursive: true });
153
+ fs.writeFileSync(reviewPath, \`\${sql.trimEnd()}\\n\`);
154
+ return reviewPath;
155
+ }
156
+
157
+ function run() {
158
+ const dbUrl = process.env.SUPABASE_DB_URL;
159
+ if (!dbUrl) throw new Error('SUPABASE_DB_URL is required');
160
+
161
+ const result = spawnSync(
162
+ 'pnpm',
163
+ ['exec', 'supabase', 'db', 'diff', '--from', dbUrl, '--to', 'migrations'],
164
+ {
165
+ cwd: process.cwd(),
166
+ encoding: 'utf8',
167
+ env: process.env,
168
+ maxBuffer: 50 * 1024 * 1024,
169
+ stdio: ['inherit', 'pipe', 'inherit'],
170
+ },
171
+ );
172
+
173
+ if (result.error) throw result.error;
174
+ if (result.status !== 0) process.exit(result.status ?? 1);
175
+
176
+ const rawSql = result.stdout ?? '';
177
+ if (rawSql) process.stdout.write(rawSql);
178
+ const { safeSql, unsafeSql } = extractReplaySafeSql(rawSql);
179
+
180
+ if (unsafeSql) {
181
+ const reviewPath = persistReview({
182
+ reviewPath: path.resolve('supabase/.temp/production-reconcile-review.sql'),
183
+ sql: rawSql,
184
+ });
185
+ console.error(
186
+ \`Blocked production reconciliation: non-replay-safe drift detected. Review \${reviewPath}.\`,
187
+ );
188
+ process.exit(1);
189
+ }
190
+
191
+ const migrationPath = persistMigration({
192
+ migrationsDir: path.resolve('supabase/migrations'),
193
+ sql: safeSql,
194
+ });
195
+ if (migrationPath) console.error(\`Created replay-safe reconciliation migration at \${migrationPath}\`);
196
+ else console.error('No production schema drift detected.');
197
+ }
198
+
199
+ if (require.main === module) run();
200
+
201
+ module.exports = {
202
+ extractReplaySafeSql,
203
+ formatMigrationTimestamp,
204
+ isReplaySafeStatement,
205
+ nextMigrationTimestamp,
206
+ persistMigration,
207
+ persistReview,
208
+ run,
209
+ };
210
+ `;
16
211
  async function installSupabase(projectRoot, context) {
17
- const pkg = await updatePackageJson(projectRoot, (pkg) => ({
18
- ...pkg,
19
- name: pkg.name ?? projectPackageName(projectRoot),
20
- private: pkg.private ?? true,
21
- packageManager: pkg.packageManager ?? 'pnpm@11.6.0',
212
+ const pkg = await updatePackageJson(projectRoot, (currentPackage) => ({
213
+ ...currentPackage,
214
+ name: currentPackage.name ?? projectPackageName(projectRoot),
215
+ private: currentPackage.private ?? true,
216
+ packageManager: currentPackage.packageManager ?? 'pnpm@11.6.0',
22
217
  engines: {
23
- ...pkg.engines,
24
- node: pkg.engines?.node ?? '>=24.0.0',
25
- pnpm: pkg.engines?.pnpm ?? '>=11.0.0',
218
+ ...currentPackage.engines,
219
+ node: currentPackage.engines?.node ?? '>=24.0.0',
220
+ pnpm: currentPackage.engines?.pnpm ?? '>=11.0.0',
26
221
  },
27
- scripts: mergeMissing(pkg.scripts, {
222
+ scripts: mergeMissing(currentPackage.scripts, {
28
223
  'supabase:start': 'supabase start',
29
224
  'supabase:stop': 'supabase stop',
30
225
  'db:types:local': 'supabase gen types typescript --local',
31
226
  }),
32
- dependencies: mergeMissing(pkg.dependencies, {
227
+ dependencies: mergeMissing(currentPackage.dependencies, {
33
228
  '@supabase/supabase-js': '2.103.0',
34
229
  }),
35
- devDependencies: mergeMissing(pkg.devDependencies, {
36
- supabase: '2.108.0',
230
+ devDependencies: mergeMissing(currentPackage.devDependencies, {
231
+ supabase: '2.118.0',
37
232
  }),
38
233
  }));
39
234
  await ensurePnpmBuildPolicy(projectRoot);
@@ -50,24 +245,80 @@ declarative_schema_path = "./schemas"
50
245
  await writeProjectFileIfMissing(projectRoot, 'supabase/schemas/000_base.sql', 'create schema if not exists public;\n');
51
246
  await writeProjectFileIfMissing(projectRoot, 'src/__generated__/database.ts', bootstrapDatabaseTypes);
52
247
  await writeProjectFileIfMissing(projectRoot, 'src/__generated__/schema.ts', bootstrapSchema);
53
- await writeProjectFileIfMissing(projectRoot, 'package-scripts.yml', `scripts:
248
+ await writeProjectFileIfMissing(projectRoot, 'scripts/safety/require-human-remote-operation.cjs', humanRemoteGuard);
249
+ await writeProjectFileIfMissing(projectRoot, 'scripts/db/generate-production-reconcile.cjs', productionReconcile);
250
+ const supabaseScripts = `scripts:
251
+ local:
252
+ db:
253
+ start: nps db.local.start
254
+ stop: nps db.local.stop
255
+ status: nps db.local.status
256
+ migrate: nps db.local.migrate
257
+ generate: nps db.local.generate
258
+ reset: nps db.local.reset
259
+ prod:
260
+ db:
261
+ migrate: nps db.prod.migrate
54
262
  db:
263
+ local:
264
+ start: pnpm exec supabase start
265
+ stop: pnpm exec supabase stop
266
+ status: pnpm exec supabase status
267
+ migrate: nps db.schema.sync && pnpm exec supabase db reset
268
+ generate: pnpm exec supabase gen types typescript --local > src/__generated__/database.ts
269
+ reset: pnpm exec supabase db reset
270
+ prod:
271
+ migrate: node scripts/safety/require-human-remote-operation.cjs --operation db.prod.migrate && nps db.migrate.prod
55
272
  schema:
56
- sync: supabase db schema declarative sync --experimental --no-apply --name declarative_schema
273
+ sync: pnpm exec supabase db schema declarative sync --experimental --no-apply --name declarative_schema
274
+ migrationGen: pnpm exec supabase db schema declarative sync --experimental --no-apply --name schema_change
57
275
  migrate:
276
+ reconcileRemote: |-
277
+ node scripts/safety/require-human-remote-operation.cjs --operation db.migrate.reconcileRemote
278
+ SUPABASE_DB_URL="$SUPABASE_DB_URL" node scripts/db/generate-production-reconcile.cjs
58
279
  prod: |-
59
- nps db.schema.sync &&
60
- supabase db push --db-url "$SUPABASE_DB_URL" --include-all
280
+ node scripts/safety/require-human-remote-operation.cjs --operation db.migrate.prod
281
+ nps db.migrate.reconcileRemote
282
+ nps db.schema.sync
283
+ pnpm exec supabase db push --db-url "$SUPABASE_DB_URL" --include-all
284
+ squashYes: |-
285
+ node scripts/safety/require-human-remote-operation.cjs --operation db.migrate.squashYes
286
+ set -e
287
+ pnpm exec supabase migration squash --db-url "$SUPABASE_DB_URL" --yes
288
+ push:
289
+ remoteYes: |-
290
+ node scripts/safety/require-human-remote-operation.cjs --operation db.push.remoteYes
291
+ pnpm exec supabase db push --db-url "$SUPABASE_DB_URL" --yes
292
+ release:
293
+ remote: >-
294
+ node scripts/safety/require-human-remote-operation.cjs --operation db.release.remote && nps db.migrate.reconcileRemote && nps db.migrationGen && nps db.push.remoteYes && nps db.migrate.squashYes && nps db.generate.remote
61
295
  generate:
62
296
  remote: |-
63
- supabase gen types typescript --db-url "$SUPABASE_DB_URL" > src/__generated__/database.ts
64
- `);
297
+ pnpm exec supabase gen types typescript --db-url "$SUPABASE_DB_URL" > src/__generated__/database.ts
298
+ `;
299
+ const scriptPath = join(projectRoot, 'package-scripts.yml');
300
+ let existingScripts;
301
+ try {
302
+ existingScripts = await readFile(scriptPath, 'utf8');
303
+ }
304
+ catch (error) {
305
+ if (error.code !== 'ENOENT')
306
+ throw error;
307
+ }
308
+ if (existingScripts === undefined) {
309
+ await writeFile(scriptPath, supabaseScripts);
310
+ }
311
+ else if (existingScripts === 'scripts:\n check: pnpm run typecheck\n') {
312
+ // Only extend Devkit's untouched NPS bootstrap; never rewrite project-owned scripts.
313
+ await writeFile(scriptPath, supabaseScripts.replace('scripts:\n', existingScripts));
314
+ }
65
315
  await context.runCommand('pnpm', ['install', '--no-frozen-lockfile'], { cwd: projectRoot });
66
316
  }
67
317
  export const supabaseRecipe = {
68
318
  id: 'supabase',
69
- recipeVersion: '1.1.1',
319
+ recipeVersion: '1.3.0',
70
320
  role: 'backend',
321
+ setupRequirements: [{ kind: 'package', packageId: 'nps', required: true }],
71
322
  conflicts: ['convex'],
72
323
  async detect(projectRoot) {
73
324
  return await detectDependency(projectRoot, '@supabase/supabase-js', '@supabase/supabase-js');
@@ -12,6 +12,12 @@ export type PackageVariant = {
12
12
  export type PackageResolution = {
13
13
  variant: string | null;
14
14
  };
15
+ export type PackageSetupRequirement = {
16
+ kind: 'package';
17
+ packageId: string;
18
+ required: boolean;
19
+ when?: 'git';
20
+ };
15
21
  export type PackageApplyContext = {
16
22
  runCommand(command: string, args: string[], options: {
17
23
  cwd: string;
@@ -24,6 +30,7 @@ export type PackageRecipe = {
24
30
  requires?: string[];
25
31
  conflicts?: string[];
26
32
  variants?: PackageVariant[];
33
+ setupRequirements?: PackageSetupRequirement[];
27
34
  detect(projectRoot: string): Promise<PackageDetection>;
28
35
  apply(projectRoot: string, detection: PackageDetection, resolution: PackageResolution, context: PackageApplyContext): Promise<{
29
36
  source: PackageSource;
@@ -105,8 +105,12 @@ export default defineConfig({ plugins: [react()] });
105
105
  }
106
106
  export const viteRecipe = {
107
107
  id: 'vite',
108
- recipeVersion: '1.1.1',
108
+ recipeVersion: '1.2.0',
109
109
  role: 'frontend',
110
+ setupRequirements: [
111
+ { kind: 'package', packageId: 'oxlint', required: true },
112
+ { kind: 'package', packageId: 'husky', required: true, when: 'git' },
113
+ ],
110
114
  conflicts: ['expo'],
111
115
  async detect(projectRoot) {
112
116
  return await detectDependency(projectRoot, 'vite', 'Vite');
@@ -1,6 +1,14 @@
1
+ export declare function runWithConcurrency<T, R>(items: T[], limit: number, worker: (item: T, index: number) => Promise<R>): Promise<R[]>;
1
2
  export declare function canonicalCheck(projectRoot: string, source: any, options?: any): Promise<{
2
3
  exitCode: number;
3
4
  results: {
4
5
  [k: string]: any;
5
6
  };
7
+ executions: {
8
+ ids: any[];
9
+ checkerPath: any;
10
+ exitCode: any;
11
+ stdout: any;
12
+ stderr: any;
13
+ }[];
6
14
  }>;
@@ -9,12 +9,28 @@ function execute(command, args, cwd) {
9
9
  let stderr = '';
10
10
  child.stdout.setEncoding('utf8');
11
11
  child.stderr.setEncoding('utf8');
12
- child.stdout.on('data', (chunk) => { stdout += chunk; });
13
- child.stderr.on('data', (chunk) => { stderr += chunk; });
12
+ child.stdout.on('data', (chunk) => {
13
+ stdout += chunk;
14
+ });
15
+ child.stderr.on('data', (chunk) => {
16
+ stderr += chunk;
17
+ });
14
18
  child.on('error', reject);
15
19
  child.on('close', (code) => resolve({ exitCode: code ?? 1, stdout, stderr }));
16
20
  });
17
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
+ }
18
34
  export async function canonicalCheck(projectRoot, source, options = {}) {
19
35
  await assertPredefinedPackageState(projectRoot);
20
36
  const current = await readInstalledState(projectRoot);
@@ -41,13 +57,18 @@ export async function canonicalCheck(projectRoot, source, options = {}) {
41
57
  if (!prepared?.checkerPath) {
42
58
  if ((entry.enforcement ?? 'guidance') === 'guidance')
43
59
  continue;
44
- results[id] = { status: 'fail', exitCode: 1, stderr: 'Canonical checker unavailable for enforced installed rule.' };
60
+ results[id] = {
61
+ status: 'fail',
62
+ exitCode: 1,
63
+ stderr: 'Canonical checker unavailable for enforced installed rule.',
64
+ };
45
65
  exitCode = 1;
46
66
  continue;
47
67
  }
48
68
  if (prepared.execution === 'manual')
49
69
  continue;
50
- const baseKey = prepared.checkerKey ?? `path:${prepared.checkerPath}:${JSON.stringify(prepared.checkerArgs ?? [])}`;
70
+ const baseKey = prepared.checkerKey ??
71
+ `path:${prepared.checkerPath}:${JSON.stringify(prepared.checkerArgs ?? [])}`;
51
72
  const key = `${baseKey}:targeting:${prepared.targeting?.scope ?? 'repository'}:execution:${prepared.execution ?? 'automatic'}`;
52
73
  const group = groups.get(key) ?? {
53
74
  checkerPath: prepared.checkerPath,
@@ -58,7 +79,7 @@ export async function canonicalCheck(projectRoot, source, options = {}) {
58
79
  group.ids.push(id);
59
80
  groups.set(key, group);
60
81
  }
61
- const groupExecutions = await Promise.all([...groups.values()].map(async (group) => {
82
+ const groupExecutions = await runWithConcurrency([...groups.values()], options.concurrency ?? 6, async (group) => {
62
83
  const args = [group.checkerPath, ...group.checkerArgs];
63
84
  if (targetMode !== 'full' && group.targeting.scope !== 'repository') {
64
85
  args.push('--target-mode', targetMode);
@@ -67,7 +88,7 @@ export async function canonicalCheck(projectRoot, source, options = {}) {
67
88
  }
68
89
  const execution = await executor('node', args, projectRoot);
69
90
  return { group, execution };
70
- }));
91
+ });
71
92
  for (const { group, execution } of groupExecutions) {
72
93
  const result = { status: execution.exitCode === 0 ? 'pass' : 'fail', ...execution };
73
94
  for (const id of group.ids)
@@ -83,5 +104,15 @@ export async function canonicalCheck(projectRoot, source, options = {}) {
83
104
  results: Object.fromEntries(Object.entries(orderedResults).map(([id, result]) => [id, { status: result.status }])),
84
105
  });
85
106
  }
86
- return { exitCode, results: orderedResults };
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
+ };
87
118
  }
@@ -7,22 +7,29 @@ export declare const EMPTY_RULE_PROFILE: Readonly<{
7
7
  include: never[];
8
8
  exclude: never[];
9
9
  }>;
10
- export declare function validateRuleProfile(profile: any): {
10
+ export declare function validateRuleProfile(profile: unknown): {
11
11
  schemaVersion: number;
12
12
  projectType: string | null;
13
13
  capabilities: unknown[];
14
14
  include: unknown[];
15
- exclude: any;
15
+ exclude: {
16
+ id: string;
17
+ reason: string;
18
+ }[];
16
19
  };
17
20
  export declare function readRuleProfile(projectRoot: string): Promise<{
18
21
  schemaVersion: number;
19
22
  projectType: string | null;
20
23
  capabilities: unknown[];
21
24
  include: unknown[];
22
- exclude: any;
25
+ exclude: {
26
+ id: string;
27
+ reason: string;
28
+ }[];
23
29
  }>;
24
30
  export declare function assertKnownRuleOverrides(entries: any[], profile: any): void;
25
31
  export declare function resolveProjectType(stack: string | null, profile?: any): any;
32
+ export declare const STACK_PACKAGES: Record<string, string[]>;
26
33
  export declare function ruleApplies(entry: any, stack: string | null, profile?: any, packageIds?: Iterable<string>): boolean;
27
34
  export declare function projectRuleApplies(entry: any, stack: string | null, profile?: any, entries?: any[], packageIds?: Iterable<string>): any;
28
35
  export declare function applicableCatalogEntries(entries: any[], stack: string | null, profile?: any, packageIds?: Iterable<string>): any[];
@@ -35,7 +42,10 @@ export declare function loadProjectContext(projectRoot: string, entries: any[]):
35
42
  projectType: string | null;
36
43
  capabilities: unknown[];
37
44
  include: unknown[];
38
- exclude: any;
45
+ exclude: {
46
+ id: string;
47
+ reason: string;
48
+ }[];
39
49
  };
40
50
  projectType: any;
41
51
  applicable: any[];
@@ -1,8 +1,16 @@
1
1
  import { readFile, readdir } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
+ import { PackageJsonSchema, RuleProfileSchema, parseWithSchema } from "./schemas.js";
3
4
  import { ensureMetadataNamespace, readInstalledState } from "./state.js";
4
5
  export const RULE_PROFILE_RELATIVE_PATH = '.spd/rules.json';
5
- export const PROJECT_TYPES = Object.freeze(['product', 'static-site', 'tooling', 'backend', 'monorepo', 'generic']);
6
+ export const PROJECT_TYPES = Object.freeze([
7
+ 'product',
8
+ 'static-site',
9
+ 'tooling',
10
+ 'backend',
11
+ 'monorepo',
12
+ 'generic',
13
+ ]);
6
14
  export const EMPTY_RULE_PROFILE = Object.freeze({
7
15
  schemaVersion: 1,
8
16
  projectType: null,
@@ -13,25 +21,31 @@ export const EMPTY_RULE_PROFILE = Object.freeze({
13
21
  function uniqueStrings(values, label) {
14
22
  if (!Array.isArray(values ?? []))
15
23
  throw new Error(`Invalid ${label}`);
16
- return [...new Set((values ?? []).map(String).map((value) => value.trim()).filter(Boolean))].sort();
24
+ return [
25
+ ...new Set((values ?? [])
26
+ .map(String)
27
+ .map((value) => value.trim())
28
+ .filter(Boolean)),
29
+ ].sort();
17
30
  }
18
31
  export function validateRuleProfile(profile) {
19
- if (!profile || typeof profile !== 'object' || Array.isArray(profile) || profile.schemaVersion !== 1) {
20
- throw new Error('Invalid .spd/rules.json profile');
21
- }
22
- const projectType = profile.projectType == null ? null : String(profile.projectType).trim();
23
- if (profile.projectType != null && !projectType)
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)
24
35
  throw new Error('Invalid rule profile projectType');
25
- const capabilities = uniqueStrings(profile.capabilities, 'rule profile capabilities');
26
- const include = uniqueStrings(profile.include, 'rule profile include');
27
- if (!Array.isArray(profile.exclude ?? []))
28
- throw new Error('Invalid rule profile exclude');
29
- const exclude = (profile.exclude ?? []).map((item) => {
30
- if (!item || typeof item !== 'object' || !String(item.id ?? '').trim() || !String(item.reason ?? '').trim()) {
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()) {
31
44
  throw new Error('Rule exclusions require both id and non-empty reason');
32
45
  }
33
46
  return { id: String(item.id).trim(), reason: String(item.reason).trim() };
34
- }).sort((a, b) => a.id.localeCompare(b.id));
47
+ })
48
+ .sort((a, b) => a.id.localeCompare(b.id));
35
49
  return { schemaVersion: 1, projectType, capabilities, include, exclude };
36
50
  }
37
51
  export async function readRuleProfile(projectRoot) {
@@ -57,14 +71,14 @@ export function assertKnownRuleOverrides(entries, profile) {
57
71
  export function resolveProjectType(stack, profile = EMPTY_RULE_PROFILE) {
58
72
  return profile.projectType ?? (stack ? 'product' : 'generic');
59
73
  }
60
- const STACK_PACKAGES = {
74
+ export const STACK_PACKAGES = {
61
75
  'stack-vite-supabase': ['vite', 'supabase'],
62
76
  'stack-vite-convex': ['vite', 'convex'],
63
77
  'stack-expo-supabase': ['expo', 'supabase'],
64
78
  'stack-expo-convex': ['expo', 'convex'],
65
79
  };
66
80
  function effectivePackages(stack, packageIds = []) {
67
- return new Set([...(stack ? STACK_PACKAGES[stack] ?? [] : []), ...packageIds]);
81
+ return new Set([...(stack ? (STACK_PACKAGES[stack] ?? []) : []), ...packageIds]);
68
82
  }
69
83
  export function ruleApplies(entry, stack, profile = EMPTY_RULE_PROFILE, packageIds = []) {
70
84
  const included = new Set(profile.include ?? []);
@@ -115,7 +129,7 @@ export function applicableCatalogEntries(entries, stack, profile = EMPTY_RULE_PR
115
129
  function stackFromDependencies(deps) {
116
130
  const frontends = [
117
131
  deps.expo ? 'expo' : null,
118
- (deps.vite || deps['@vitejs/plugin-react']) ? 'vite' : null,
132
+ deps.vite || deps['@vitejs/plugin-react'] ? 'vite' : null,
119
133
  ].filter(Boolean);
120
134
  const backends = [
121
135
  deps.convex ? 'convex' : null,
@@ -131,7 +145,7 @@ function stackFromDependencies(deps) {
131
145
  }
132
146
  async function readPackageDependencies(path) {
133
147
  try {
134
- const pkg = JSON.parse(await readFile(path, 'utf8'));
148
+ const pkg = parseWithSchema(PackageJsonSchema, JSON.parse(await readFile(path, 'utf8')), `package.json at ${path}`);
135
149
  return { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };
136
150
  }
137
151
  catch (error) {
@@ -6,7 +6,10 @@ export declare function canonicalRules(projectRoot: string, source: any, options
6
6
  projectType: string | null;
7
7
  capabilities: unknown[];
8
8
  include: unknown[];
9
- exclude: any;
9
+ exclude: {
10
+ id: string;
11
+ reason: string;
12
+ }[];
10
13
  };
11
14
  detail: boolean;
12
15
  rules: {
@@ -9,11 +9,18 @@ function ruleSummary(entry) {
9
9
  return String(entry.summary).trim();
10
10
  const content = String(entry.content ?? '').replace(/\r\n?/gu, '\n');
11
11
  const intent = content.match(/(?:^|\n)## Intent\s*\n+([^#][\s\S]*?)(?=\n## |$)/u)?.[1]?.trim();
12
- const source = intent || content
13
- .split('\n')
14
- .map((line) => line.trim())
15
- .find((line) => line && !line.startsWith('#')) || entry.name || entry.id;
16
- return source.replace(/^\*\*Rule:\*\*\s*/u, '').replace(/\s+/gu, ' ').slice(0, 240).trim();
12
+ const source = intent ||
13
+ content
14
+ .split('\n')
15
+ .map((line) => line.trim())
16
+ .find((line) => line && !line.startsWith('#')) ||
17
+ entry.name ||
18
+ entry.id;
19
+ return source
20
+ .replace(/^\*\*Rule:\*\*\s*/u, '')
21
+ .replace(/\s+/gu, ' ')
22
+ .slice(0, 240)
23
+ .trim();
17
24
  }
18
25
  export function aiInstructionText() {
19
26
  return [
@@ -41,7 +48,9 @@ export async function canonicalRules(projectRoot, source, options = {}) {
41
48
  }
42
49
  else if (options.failed) {
43
50
  const state = await readChecksState(projectRoot);
44
- const failed = new Set(Object.entries(state.results ?? {}).filter(([, value]) => value.status === 'fail').map(([id]) => id));
51
+ const failed = new Set(Object.entries(state.results ?? {})
52
+ .filter(([, value]) => value.status === 'fail')
53
+ .map(([id]) => id));
45
54
  selected = selected.filter((entry) => failed.has(entry.id));
46
55
  detail = true;
47
56
  }
@@ -10,7 +10,10 @@ export declare function loadCanonicalProjectContext(projectRoot: string, source:
10
10
  projectType: string | null;
11
11
  capabilities: unknown[];
12
12
  include: unknown[];
13
- exclude: any;
13
+ exclude: {
14
+ id: string;
15
+ reason: string;
16
+ }[];
14
17
  };
15
18
  applicable: any[];
16
19
  canonicalCheckRoot: any;