@specdest/devkit 0.4.8 → 0.4.10
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/README.md +26 -24
- package/dist/npm/canonical-project.d.ts +12 -1
- package/dist/npm/canonical-project.js +10 -4
- package/dist/npm/canonical-source.d.ts +14 -2
- package/dist/npm/canonical-source.js +46 -14
- package/dist/npm/catalog-snapshot.d.ts +32 -26
- package/dist/npm/catalog-snapshot.js +11 -4
- package/dist/npm/cli.js +5 -2
- package/dist/npm/client-only-boundary.d.ts +1 -0
- package/dist/npm/client-only-boundary.js +29 -0
- package/dist/npm/commands.d.ts +6 -0
- package/dist/npm/commands.js +33 -8
- package/dist/npm/flow.js +52 -18
- package/dist/npm/git-catalog.d.ts +33 -32
- package/dist/npm/git-catalog.js +49 -17
- package/dist/npm/index.d.ts +0 -1
- package/dist/npm/index.js +13 -3
- package/dist/npm/installer-primitives.d.ts +3 -3
- package/dist/npm/predefined-packages/expo.js +5 -1
- package/dist/npm/predefined-packages/index.d.ts +1 -0
- package/dist/npm/predefined-packages/index.js +44 -3
- package/dist/npm/predefined-packages/install.js +3 -2
- package/dist/npm/predefined-packages/supabase.js +297 -26
- package/dist/npm/predefined-packages/types.d.ts +7 -0
- package/dist/npm/predefined-packages/vite.js +5 -1
- package/dist/npm/project-check.d.ts +8 -0
- package/dist/npm/project-check.js +52 -7
- package/dist/npm/project-context.d.ts +14 -4
- package/dist/npm/project-context.js +37 -18
- package/dist/npm/project-rules.d.ts +4 -1
- package/dist/npm/project-rules.js +15 -6
- package/dist/npm/project-runtime.d.ts +4 -1
- package/dist/npm/project-runtime.js +19 -5
- package/dist/npm/project-status.js +17 -3
- package/dist/npm/project-sync.js +13 -5
- package/dist/npm/remote-installer.d.ts +35 -4
- package/dist/npm/remote-installer.js +75 -36
- package/dist/npm/rule-id-migrations.d.ts +6 -0
- package/dist/npm/rule-id-migrations.js +19 -0
- package/dist/npm/schemas.d.ts +64 -0
- package/dist/npm/schemas.js +194 -0
- package/dist/npm/slack.d.ts +16 -0
- package/dist/npm/slack.js +131 -0
- package/dist/npm/state.js +71 -22
- package/dist/npm/supabase-local.d.ts +2 -0
- package/dist/npm/supabase-local.js +62 -0
- package/package.json +9 -7
- package/dist/npm/fuzz.d.ts +0 -138
- package/dist/npm/fuzz.js +0 -327
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
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,270 @@ 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
|
+
`;
|
|
211
|
+
const productionOperations = `#!/usr/bin/env bash
|
|
212
|
+
set -euo pipefail
|
|
213
|
+
cd "$(dirname "\${BASH_SOURCE[0]}")/../.."
|
|
214
|
+
|
|
215
|
+
operation="\${1:-}"
|
|
216
|
+
case "$operation" in
|
|
217
|
+
reconcile|migrationGen|migrate|push|squash|generate|release) ;;
|
|
218
|
+
*) echo 'Unsupported production database operation' >&2; exit 2 ;;
|
|
219
|
+
esac
|
|
220
|
+
|
|
221
|
+
# No production configuration is accessed before the human-only check.
|
|
222
|
+
node scripts/safety/require-human-remote-operation.cjs --operation "prod.db.$operation"
|
|
223
|
+
source ./supabase/.env.production
|
|
224
|
+
: "\${SUPABASE_DB_URL:?SUPABASE_DB_URL must be configured}"
|
|
225
|
+
export SUPABASE_DB_URL
|
|
226
|
+
|
|
227
|
+
case "$operation" in
|
|
228
|
+
reconcile)
|
|
229
|
+
node scripts/db/generate-production-reconcile.cjs
|
|
230
|
+
;;
|
|
231
|
+
migrationGen)
|
|
232
|
+
pnpm exec supabase db schema declarative sync --experimental --no-apply --name schema_change
|
|
233
|
+
;;
|
|
234
|
+
migrate)
|
|
235
|
+
bash "$0" reconcile
|
|
236
|
+
bash "$0" migrationGen
|
|
237
|
+
pnpm exec supabase db push --db-url "$SUPABASE_DB_URL" --include-all
|
|
238
|
+
;;
|
|
239
|
+
push)
|
|
240
|
+
pnpm exec supabase db push --db-url "$SUPABASE_DB_URL" --yes
|
|
241
|
+
;;
|
|
242
|
+
squash)
|
|
243
|
+
pnpm exec supabase migration squash --db-url "$SUPABASE_DB_URL" --yes
|
|
244
|
+
;;
|
|
245
|
+
generate)
|
|
246
|
+
types_tmp="$(mktemp ./src/__generated__/.db-types-XXXXXX)"
|
|
247
|
+
trap 'rm -f "$types_tmp"' EXIT
|
|
248
|
+
pnpm exec supabase gen types typescript --db-url "$SUPABASE_DB_URL" > "$types_tmp"
|
|
249
|
+
mv "$types_tmp" src/__generated__/database.ts
|
|
250
|
+
trap - EXIT
|
|
251
|
+
;;
|
|
252
|
+
release)
|
|
253
|
+
bash "$0" reconcile
|
|
254
|
+
bash "$0" migrationGen
|
|
255
|
+
bash "$0" push
|
|
256
|
+
bash "$0" squash
|
|
257
|
+
bash "$0" generate
|
|
258
|
+
;;
|
|
259
|
+
esac
|
|
260
|
+
`;
|
|
16
261
|
async function installSupabase(projectRoot, context) {
|
|
17
|
-
const pkg = await updatePackageJson(projectRoot, (
|
|
18
|
-
...
|
|
19
|
-
name:
|
|
20
|
-
private:
|
|
21
|
-
packageManager:
|
|
262
|
+
const pkg = await updatePackageJson(projectRoot, (currentPackage) => ({
|
|
263
|
+
...currentPackage,
|
|
264
|
+
name: currentPackage.name ?? projectPackageName(projectRoot),
|
|
265
|
+
private: currentPackage.private ?? true,
|
|
266
|
+
packageManager: currentPackage.packageManager ?? 'pnpm@11.6.0',
|
|
22
267
|
engines: {
|
|
23
|
-
...
|
|
24
|
-
node:
|
|
25
|
-
pnpm:
|
|
268
|
+
...currentPackage.engines,
|
|
269
|
+
node: currentPackage.engines?.node ?? '>=24.0.0',
|
|
270
|
+
pnpm: currentPackage.engines?.pnpm ?? '>=11.0.0',
|
|
26
271
|
},
|
|
27
|
-
scripts: mergeMissing(
|
|
272
|
+
scripts: mergeMissing(currentPackage.scripts, {
|
|
28
273
|
'supabase:start': 'supabase start',
|
|
29
274
|
'supabase:stop': 'supabase stop',
|
|
30
275
|
'db:types:local': 'supabase gen types typescript --local',
|
|
31
276
|
}),
|
|
32
|
-
dependencies: mergeMissing(
|
|
277
|
+
dependencies: mergeMissing(currentPackage.dependencies, {
|
|
33
278
|
'@supabase/supabase-js': '2.103.0',
|
|
34
279
|
}),
|
|
35
|
-
devDependencies: mergeMissing(
|
|
36
|
-
supabase: '2.
|
|
280
|
+
devDependencies: mergeMissing(currentPackage.devDependencies, {
|
|
281
|
+
supabase: '2.118.0',
|
|
37
282
|
}),
|
|
38
283
|
}));
|
|
39
284
|
await ensurePnpmBuildPolicy(projectRoot);
|
|
@@ -50,24 +295,50 @@ declarative_schema_path = "./schemas"
|
|
|
50
295
|
await writeProjectFileIfMissing(projectRoot, 'supabase/schemas/000_base.sql', 'create schema if not exists public;\n');
|
|
51
296
|
await writeProjectFileIfMissing(projectRoot, 'src/__generated__/database.ts', bootstrapDatabaseTypes);
|
|
52
297
|
await writeProjectFileIfMissing(projectRoot, 'src/__generated__/schema.ts', bootstrapSchema);
|
|
53
|
-
await writeProjectFileIfMissing(projectRoot, '
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
298
|
+
await writeProjectFileIfMissing(projectRoot, 'scripts/safety/require-human-remote-operation.cjs', humanRemoteGuard);
|
|
299
|
+
await writeProjectFileIfMissing(projectRoot, 'scripts/db/generate-production-reconcile.cjs', productionReconcile);
|
|
300
|
+
await writeProjectFileIfMissing(projectRoot, 'scripts/db/run-production-operation.sh', productionOperations);
|
|
301
|
+
const supabaseScripts = `scripts:
|
|
302
|
+
local:
|
|
303
|
+
db:
|
|
304
|
+
start: pnpm exec supabase start
|
|
305
|
+
stop: pnpm exec supabase stop
|
|
306
|
+
status: pnpm exec supabase status
|
|
307
|
+
migrationGen: pnpm exec supabase db schema declarative sync --experimental --no-apply --name schema_change
|
|
308
|
+
generate: pnpm exec supabase gen types typescript --local > src/__generated__/database.ts
|
|
309
|
+
prod:
|
|
310
|
+
db:
|
|
311
|
+
reconcile: node scripts/safety/require-human-remote-operation.cjs --operation prod.db.reconcile && bash scripts/db/run-production-operation.sh reconcile
|
|
312
|
+
migrationGen: node scripts/safety/require-human-remote-operation.cjs --operation prod.db.migrationGen && bash scripts/db/run-production-operation.sh migrationGen
|
|
313
|
+
migrate: node scripts/safety/require-human-remote-operation.cjs --operation prod.db.migrate && bash scripts/db/run-production-operation.sh migrate
|
|
314
|
+
push: node scripts/safety/require-human-remote-operation.cjs --operation prod.db.push && bash scripts/db/run-production-operation.sh push
|
|
315
|
+
squash: node scripts/safety/require-human-remote-operation.cjs --operation prod.db.squash && bash scripts/db/run-production-operation.sh squash
|
|
316
|
+
generate: node scripts/safety/require-human-remote-operation.cjs --operation prod.db.generate && bash scripts/db/run-production-operation.sh generate
|
|
317
|
+
release: node scripts/safety/require-human-remote-operation.cjs --operation prod.db.release && bash scripts/db/run-production-operation.sh release
|
|
318
|
+
`;
|
|
319
|
+
const scriptPath = join(projectRoot, 'package-scripts.yml');
|
|
320
|
+
let existingScripts;
|
|
321
|
+
try {
|
|
322
|
+
existingScripts = await readFile(scriptPath, 'utf8');
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
if (error.code !== 'ENOENT')
|
|
326
|
+
throw error;
|
|
327
|
+
}
|
|
328
|
+
if (existingScripts === undefined) {
|
|
329
|
+
await writeFile(scriptPath, supabaseScripts);
|
|
330
|
+
}
|
|
331
|
+
else if (existingScripts === 'scripts:\n check: pnpm run typecheck\n') {
|
|
332
|
+
// Only extend Devkit's untouched NPS bootstrap; never rewrite project-owned scripts.
|
|
333
|
+
await writeFile(scriptPath, supabaseScripts.replace('scripts:\n', existingScripts));
|
|
334
|
+
}
|
|
65
335
|
await context.runCommand('pnpm', ['install', '--no-frozen-lockfile'], { cwd: projectRoot });
|
|
66
336
|
}
|
|
67
337
|
export const supabaseRecipe = {
|
|
68
338
|
id: 'supabase',
|
|
69
|
-
recipeVersion: '1.
|
|
339
|
+
recipeVersion: '1.3.0',
|
|
70
340
|
role: 'backend',
|
|
341
|
+
setupRequirements: [{ kind: 'package', packageId: 'nps', required: true }],
|
|
71
342
|
conflicts: ['convex'],
|
|
72
343
|
async detect(projectRoot) {
|
|
73
344
|
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.
|
|
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
|
}>;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
+
import { clientOnlyBoundaryViolations } from "./client-only-boundary.js";
|
|
3
|
+
import { readRuleProfile } from "./project-context.js";
|
|
2
4
|
import { loadCanonicalProjectContext, prepareCanonicalManifest } from "./project-runtime.js";
|
|
3
5
|
import { assertPredefinedPackageState } from "./predefined-packages/health.js";
|
|
4
6
|
import { readInstalledState, writeChecksState } from "./state.js";
|
|
@@ -9,12 +11,28 @@ function execute(command, args, cwd) {
|
|
|
9
11
|
let stderr = '';
|
|
10
12
|
child.stdout.setEncoding('utf8');
|
|
11
13
|
child.stderr.setEncoding('utf8');
|
|
12
|
-
child.stdout.on('data', (chunk) => {
|
|
13
|
-
|
|
14
|
+
child.stdout.on('data', (chunk) => {
|
|
15
|
+
stdout += chunk;
|
|
16
|
+
});
|
|
17
|
+
child.stderr.on('data', (chunk) => {
|
|
18
|
+
stderr += chunk;
|
|
19
|
+
});
|
|
14
20
|
child.on('error', reject);
|
|
15
21
|
child.on('close', (code) => resolve({ exitCode: code ?? 1, stdout, stderr }));
|
|
16
22
|
});
|
|
17
23
|
}
|
|
24
|
+
export async function runWithConcurrency(items, limit, worker) {
|
|
25
|
+
const concurrency = Math.max(1, Math.min(Math.floor(limit), items.length || 1));
|
|
26
|
+
const results = new Array(items.length);
|
|
27
|
+
let nextIndex = 0;
|
|
28
|
+
await Promise.all(Array.from({ length: concurrency }, async () => {
|
|
29
|
+
while (nextIndex < items.length) {
|
|
30
|
+
const index = nextIndex++;
|
|
31
|
+
results[index] = await worker(items[index], index);
|
|
32
|
+
}
|
|
33
|
+
}));
|
|
34
|
+
return results;
|
|
35
|
+
}
|
|
18
36
|
export async function canonicalCheck(projectRoot, source, options = {}) {
|
|
19
37
|
await assertPredefinedPackageState(projectRoot);
|
|
20
38
|
const current = await readInstalledState(projectRoot);
|
|
@@ -33,6 +51,18 @@ export async function canonicalCheck(projectRoot, source, options = {}) {
|
|
|
33
51
|
}
|
|
34
52
|
const normalizedTargetFiles = (targetFiles ?? []).map((file) => String(file).replaceAll('\\', '/'));
|
|
35
53
|
let exitCode = 0;
|
|
54
|
+
const profile = await readRuleProfile(projectRoot);
|
|
55
|
+
if (profile.capabilities.includes('client-only')) {
|
|
56
|
+
const findings = await clientOnlyBoundaryViolations(projectRoot);
|
|
57
|
+
results['client-only-boundary'] = {
|
|
58
|
+
status: findings.length ? 'fail' : 'pass',
|
|
59
|
+
exitCode: findings.length ? 1 : 0,
|
|
60
|
+
stderr: findings.join('\n'),
|
|
61
|
+
diagnostics: findings.map((message) => ({ message })),
|
|
62
|
+
};
|
|
63
|
+
if (findings.length)
|
|
64
|
+
exitCode = 1;
|
|
65
|
+
}
|
|
36
66
|
for (const [id, installed] of Object.entries(current.installed).sort(([a], [b]) => a.localeCompare(b))) {
|
|
37
67
|
const entry = byId.get(id);
|
|
38
68
|
if (!entry || installed.kind !== 'rule')
|
|
@@ -41,13 +71,18 @@ export async function canonicalCheck(projectRoot, source, options = {}) {
|
|
|
41
71
|
if (!prepared?.checkerPath) {
|
|
42
72
|
if ((entry.enforcement ?? 'guidance') === 'guidance')
|
|
43
73
|
continue;
|
|
44
|
-
results[id] = {
|
|
74
|
+
results[id] = {
|
|
75
|
+
status: 'fail',
|
|
76
|
+
exitCode: 1,
|
|
77
|
+
stderr: 'Canonical checker unavailable for enforced installed rule.',
|
|
78
|
+
};
|
|
45
79
|
exitCode = 1;
|
|
46
80
|
continue;
|
|
47
81
|
}
|
|
48
82
|
if (prepared.execution === 'manual')
|
|
49
83
|
continue;
|
|
50
|
-
const baseKey = prepared.checkerKey ??
|
|
84
|
+
const baseKey = prepared.checkerKey ??
|
|
85
|
+
`path:${prepared.checkerPath}:${JSON.stringify(prepared.checkerArgs ?? [])}`;
|
|
51
86
|
const key = `${baseKey}:targeting:${prepared.targeting?.scope ?? 'repository'}:execution:${prepared.execution ?? 'automatic'}`;
|
|
52
87
|
const group = groups.get(key) ?? {
|
|
53
88
|
checkerPath: prepared.checkerPath,
|
|
@@ -58,7 +93,7 @@ export async function canonicalCheck(projectRoot, source, options = {}) {
|
|
|
58
93
|
group.ids.push(id);
|
|
59
94
|
groups.set(key, group);
|
|
60
95
|
}
|
|
61
|
-
const groupExecutions = await
|
|
96
|
+
const groupExecutions = await runWithConcurrency([...groups.values()], options.concurrency ?? 6, async (group) => {
|
|
62
97
|
const args = [group.checkerPath, ...group.checkerArgs];
|
|
63
98
|
if (targetMode !== 'full' && group.targeting.scope !== 'repository') {
|
|
64
99
|
args.push('--target-mode', targetMode);
|
|
@@ -67,7 +102,7 @@ export async function canonicalCheck(projectRoot, source, options = {}) {
|
|
|
67
102
|
}
|
|
68
103
|
const execution = await executor('node', args, projectRoot);
|
|
69
104
|
return { group, execution };
|
|
70
|
-
})
|
|
105
|
+
});
|
|
71
106
|
for (const { group, execution } of groupExecutions) {
|
|
72
107
|
const result = { status: execution.exitCode === 0 ? 'pass' : 'fail', ...execution };
|
|
73
108
|
for (const id of group.ids)
|
|
@@ -83,5 +118,15 @@ export async function canonicalCheck(projectRoot, source, options = {}) {
|
|
|
83
118
|
results: Object.fromEntries(Object.entries(orderedResults).map(([id, result]) => [id, { status: result.status }])),
|
|
84
119
|
});
|
|
85
120
|
}
|
|
86
|
-
return {
|
|
121
|
+
return {
|
|
122
|
+
exitCode,
|
|
123
|
+
results: orderedResults,
|
|
124
|
+
executions: groupExecutions.map(({ group, execution }) => ({
|
|
125
|
+
ids: [...group.ids].sort(),
|
|
126
|
+
checkerPath: group.checkerPath,
|
|
127
|
+
exitCode: execution.exitCode,
|
|
128
|
+
stdout: execution.stdout,
|
|
129
|
+
stderr: execution.stderr,
|
|
130
|
+
})),
|
|
131
|
+
};
|
|
87
132
|
}
|
|
@@ -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:
|
|
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:
|
|
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:
|
|
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:
|
|
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([
|
|
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 [
|
|
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
|
-
|
|
20
|
-
|
|
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(
|
|
26
|
-
const include = uniqueStrings(
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
-
})
|
|
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,16 +71,19 @@ 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
|
}
|
|
83
|
+
const backendOnlyRuleIds = new Set(['db-schema-static-validation']);
|
|
69
84
|
export function ruleApplies(entry, stack, profile = EMPTY_RULE_PROFILE, packageIds = []) {
|
|
85
|
+
if (profile.capabilities?.includes('client-only') && backendOnlyRuleIds.has(entry.id))
|
|
86
|
+
return false;
|
|
70
87
|
const included = new Set(profile.include ?? []);
|
|
71
88
|
const excluded = new Set((profile.exclude ?? []).map((item) => item.id));
|
|
72
89
|
if (excluded.has(entry.id))
|
|
@@ -94,6 +111,8 @@ function capabilitySatisfied(entry, profile) {
|
|
|
94
111
|
return !entry.requiredCapabilities?.some((capability) => !capabilities.has(capability));
|
|
95
112
|
}
|
|
96
113
|
export function projectRuleApplies(entry, stack, profile = EMPTY_RULE_PROFILE, entries = [], packageIds = []) {
|
|
114
|
+
if (profile.capabilities?.includes('client-only') && backendOnlyRuleIds.has(entry.id))
|
|
115
|
+
return false;
|
|
97
116
|
const included = new Set(profile.include ?? []);
|
|
98
117
|
const excluded = new Set((profile.exclude ?? []).map((item) => item.id));
|
|
99
118
|
if (excluded.has(entry.id))
|
|
@@ -115,7 +134,7 @@ export function applicableCatalogEntries(entries, stack, profile = EMPTY_RULE_PR
|
|
|
115
134
|
function stackFromDependencies(deps) {
|
|
116
135
|
const frontends = [
|
|
117
136
|
deps.expo ? 'expo' : null,
|
|
118
|
-
|
|
137
|
+
deps.vite || deps['@vitejs/plugin-react'] ? 'vite' : null,
|
|
119
138
|
].filter(Boolean);
|
|
120
139
|
const backends = [
|
|
121
140
|
deps.convex ? 'convex' : null,
|
|
@@ -131,7 +150,7 @@ function stackFromDependencies(deps) {
|
|
|
131
150
|
}
|
|
132
151
|
async function readPackageDependencies(path) {
|
|
133
152
|
try {
|
|
134
|
-
const pkg = JSON.parse(await readFile(path, 'utf8'));
|
|
153
|
+
const pkg = parseWithSchema(PackageJsonSchema, JSON.parse(await readFile(path, 'utf8')), `package.json at ${path}`);
|
|
135
154
|
return { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };
|
|
136
155
|
}
|
|
137
156
|
catch (error) {
|