@crasi/bisque-cli 0.0.0-stage → 0.3.0
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/LICENSE +21 -0
- package/README.md +25 -2
- package/dist/bin.js +997 -0
- package/dist/bin.js.map +7 -0
- package/dist/index.js +966 -0
- package/dist/index.js.map +7 -0
- package/dist/review.js +157 -0
- package/dist/review.js.map +7 -0
- package/dist/types/bin.d.ts +2 -0
- package/dist/types/commands.d.ts +65 -0
- package/dist/types/config.d.ts +38 -0
- package/dist/types/index.d.ts +6 -0
- package/dist/types/introspect.d.ts +48 -0
- package/dist/types/review.d.ts +74 -0
- package/dist/types/sql.d.ts +31 -0
- package/dist/types/templates.d.ts +10 -0
- package/package.json +56 -3
package/dist/bin.js
ADDED
|
@@ -0,0 +1,997 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/bin.ts
|
|
4
|
+
import { resolve as resolve2 } from "node:path";
|
|
5
|
+
import { PRODUCT as PRODUCT5 } from "@crasi/bisque-core";
|
|
6
|
+
|
|
7
|
+
// src/commands.ts
|
|
8
|
+
import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "node:fs";
|
|
9
|
+
import { basename, dirname as dirname2, join as join2, relative } from "node:path";
|
|
10
|
+
import { ENV, PRODUCT as PRODUCT4, pkg as pkg3, runtimeOrigin } from "@crasi/bisque-core";
|
|
11
|
+
import { breakingChanges, contractDiff, describeChange } from "@crasi/bisque-contract";
|
|
12
|
+
import { localize, migrateDraft, validateDraft } from "@crasi/bisque-spec";
|
|
13
|
+
|
|
14
|
+
// src/config.ts
|
|
15
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
16
|
+
import { dirname, join, resolve } from "node:path";
|
|
17
|
+
import { pathToFileURL } from "node:url";
|
|
18
|
+
import { createJiti } from "jiti";
|
|
19
|
+
import { PRODUCT, pkg } from "@crasi/bisque-core";
|
|
20
|
+
import * as ownContract from "@crasi/bisque-contract";
|
|
21
|
+
var CANDIDATES = [PRODUCT.configFile, `src/${PRODUCT.configFile}`];
|
|
22
|
+
function findConfig(root, explicit) {
|
|
23
|
+
if (explicit) {
|
|
24
|
+
const p = resolve(root, explicit);
|
|
25
|
+
if (!existsSync(p)) throw new Error(`no config at ${p}`);
|
|
26
|
+
return p;
|
|
27
|
+
}
|
|
28
|
+
for (const c of CANDIDATES) if (existsSync(join(root, c))) return join(root, c);
|
|
29
|
+
throw new Error(`no ${PRODUCT.configFile} found in ${root} or ${root}/src. Run \`${PRODUCT.cli} init\` first.`);
|
|
30
|
+
}
|
|
31
|
+
async function loadConfig(root, explicit) {
|
|
32
|
+
const configPath = findConfig(root, explicit);
|
|
33
|
+
const jiti = createJiti(pathToFileURL(configPath).href, { interopDefault: true, moduleCache: false });
|
|
34
|
+
const mod = await jiti.import(configPath);
|
|
35
|
+
const contract = mod.default ?? mod.contract ?? mod.bisque;
|
|
36
|
+
if (!contract || typeof contract !== "object" || !("resources" in contract)) throw new Error(`${configPath} must export the contract (export default defineBisque({...}))`);
|
|
37
|
+
let lib = ownContract;
|
|
38
|
+
try {
|
|
39
|
+
lib = await jiti.import(pkg("contract"));
|
|
40
|
+
} catch {
|
|
41
|
+
}
|
|
42
|
+
const manifest = lib.toManifest(contract);
|
|
43
|
+
return { root, configPath, contract, manifest, hash: await lib.contractHash(manifest), fixtures: mod.fixtures };
|
|
44
|
+
}
|
|
45
|
+
var readJson = (p) => existsSync(p) ? JSON.parse(readFileSync(p, "utf8")) : null;
|
|
46
|
+
var writeJson = (p, v) => {
|
|
47
|
+
mkdirSync(dirname(p), { recursive: true });
|
|
48
|
+
writeFileSync(p, `${JSON.stringify(v, null, 2)}
|
|
49
|
+
`);
|
|
50
|
+
};
|
|
51
|
+
var files = (root) => ({
|
|
52
|
+
review: join(root, PRODUCT.reviewFile),
|
|
53
|
+
lock: join(root, PRODUCT.lockFile),
|
|
54
|
+
introspected: join(root, ".bisque/introspect.json")
|
|
55
|
+
});
|
|
56
|
+
var readReview = (root) => readJson(files(root).review);
|
|
57
|
+
var writeReview = (root, r) => writeJson(files(root).review, r);
|
|
58
|
+
var readLock = (root) => readJson(files(root).lock);
|
|
59
|
+
var writeLock = (root, l) => writeJson(files(root).lock, l);
|
|
60
|
+
var readIntrospected = (root) => readJson(files(root).introspected);
|
|
61
|
+
var writeIntrospected = (root, i) => writeJson(files(root).introspected, i);
|
|
62
|
+
|
|
63
|
+
// src/introspect.ts
|
|
64
|
+
var SYSTEM_TABLE = /^(audit_log|audit_logs|.*_audit|migrations?|schema_migrations|.*_logs?|sessions?|.*_tokens?|webhooks?|jobs?|.*_queue)$/i;
|
|
65
|
+
var USER_TABLE = /^(profiles|users|accounts|memberships)$/i;
|
|
66
|
+
var INTERNAL_COLUMN = /(password|secret|token|api_key|apikey|hash|salt|storage_path|_path$|ip_address|user_agent|raw_|^internal_|_internal$)/i;
|
|
67
|
+
var AUDIT_COLUMN = /^(created_by|updated_by|deleted_by)$/;
|
|
68
|
+
var QUANTITY = /(qty|quantity|amount|price|value|cost|total|count|weight|volume|duration|days|hours)/i;
|
|
69
|
+
var MONTHISH = /(^|_)(month|period|ym)$/i;
|
|
70
|
+
function planTables(tables) {
|
|
71
|
+
const plans = tables.map((table) => {
|
|
72
|
+
const warnings = [];
|
|
73
|
+
let include = true, reason;
|
|
74
|
+
if (SYSTEM_TABLE.test(table.name)) {
|
|
75
|
+
include = false;
|
|
76
|
+
reason = "system table";
|
|
77
|
+
} else if (USER_TABLE.test(table.name)) {
|
|
78
|
+
include = false;
|
|
79
|
+
reason = "user accounts: personal data";
|
|
80
|
+
} else if (table.schema !== "public") {
|
|
81
|
+
include = false;
|
|
82
|
+
reason = `schema ${table.schema}`;
|
|
83
|
+
}
|
|
84
|
+
const fields = table.columns.map((column) => {
|
|
85
|
+
const w = [];
|
|
86
|
+
if (INTERNAL_COLUMN.test(column.name)) return { column, include: false, reason: "looks internal", warnings: [`'${column.name}' looks internal: exclude?`] };
|
|
87
|
+
if (AUDIT_COLUMN.test(column.name)) return { column, include: false, reason: "audit column", warnings: [] };
|
|
88
|
+
if (column.type === "number" && QUANTITY.test(column.name) && !/\b(unit|in |pieces|boxes|ron|eur|usd|%|percent|days|hours|kg|g\b)/i.test(column.comment ?? ""))
|
|
89
|
+
w.push(`'${column.name}' unit unknown`);
|
|
90
|
+
if (MONTHISH.test(column.name) && column.type === "string" && !column.comment) w.push(`'${column.name}' format unknown`);
|
|
91
|
+
if (column.type === "json") w.push(`'${column.name}' is JSON: describe its shape or exclude`);
|
|
92
|
+
return { column, include: true, warnings: w };
|
|
93
|
+
});
|
|
94
|
+
if (table.columns.some((c) => c.name === "valid_from")) warnings.push("value depends on valid_from: consider a derived resource");
|
|
95
|
+
return { table, include, reason, fields, refs: [], warnings };
|
|
96
|
+
});
|
|
97
|
+
const included = new Set(plans.filter((p) => p.include).map((p) => p.table.name));
|
|
98
|
+
for (const p of plans) {
|
|
99
|
+
for (const f of p.fields) {
|
|
100
|
+
if (!f.column.references) continue;
|
|
101
|
+
if (included.has(f.column.references)) p.refs.push(f.column.name);
|
|
102
|
+
else if (f.include && p.include) f.warnings.push(`'${f.column.name}' references ${f.column.references}, which is excluded`);
|
|
103
|
+
}
|
|
104
|
+
const undescribed = p.fields.filter((f) => f.include && !f.column.comment && !f.column.references && f.column.name !== "id").length;
|
|
105
|
+
if (p.include && undescribed) p.warnings.unshift(`${undescribed} fields have no description`);
|
|
106
|
+
}
|
|
107
|
+
return plans;
|
|
108
|
+
}
|
|
109
|
+
function scorePlans(plans, glossaryTerms = 0, derived = 0) {
|
|
110
|
+
const fields = plans.filter((p) => p.include).flatMap((p) => p.fields.filter((f) => f.include && f.column.name !== "id"));
|
|
111
|
+
const described = fields.filter((f) => f.column.comment || f.column.references).length;
|
|
112
|
+
const describedShare = fields.length ? described / fields.length : 0;
|
|
113
|
+
const unresolved = plans.filter((p) => p.include).reduce((a, p) => a + p.warnings.length + p.fields.reduce((b, f) => b + f.warnings.length, 0), 0);
|
|
114
|
+
return { ...qualityFormula(describedShare, glossaryTerms, derived, unresolved), describedShare, glossaryTerms, derived };
|
|
115
|
+
}
|
|
116
|
+
function qualityFormula(describedShare, glossaryTerms, derived, warnings) {
|
|
117
|
+
const s = 45 * describedShare + 30 * Math.min(1, glossaryTerms / 4) + 15 * Math.min(1, derived / 1) + 10 * Math.max(0, 1 - warnings / 10);
|
|
118
|
+
return { score: Math.round(s) };
|
|
119
|
+
}
|
|
120
|
+
var pad = (s, n) => s.length >= n ? `${s} ` : s + " ".repeat(n - s.length);
|
|
121
|
+
function formatIntrospection(plans, score) {
|
|
122
|
+
const lines = [];
|
|
123
|
+
for (const p of plans) {
|
|
124
|
+
const n = p.fields.filter((f) => f.include).length;
|
|
125
|
+
if (!p.include) {
|
|
126
|
+
lines.push(`${pad(p.table.name, 16)}${pad(`${p.table.columns.length} fields`, 12)}\u2717 excluded by default (${p.reason})`);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
const head = `${pad(p.table.name, 16)}${pad(`${n} fields`, 12)}refs: ${p.refs.length ? p.refs.join(", ") : "\u2014"}`;
|
|
130
|
+
const warns = [...p.warnings, ...p.fields.flatMap((f) => f.warnings)];
|
|
131
|
+
lines.push(warns.length ? `${pad(head, 46)}\u26A0 ${warns[0]}` : head);
|
|
132
|
+
for (const w of warns.slice(1)) lines.push(`${" ".repeat(28)}\u26A0 ${w}`);
|
|
133
|
+
}
|
|
134
|
+
lines.push(
|
|
135
|
+
`Contract quality score: ${score.score}/100 (descriptions ${Math.round(score.describedShare * 100)}%, glossary ${score.glossaryTerms} terms, derived ${score.derived})`
|
|
136
|
+
);
|
|
137
|
+
return lines.join("\n");
|
|
138
|
+
}
|
|
139
|
+
function zodFor(c) {
|
|
140
|
+
if (c.enum) return `z.enum(${JSON.stringify(c.enum)})`;
|
|
141
|
+
switch (c.type) {
|
|
142
|
+
case "number":
|
|
143
|
+
return "z.number()";
|
|
144
|
+
case "boolean":
|
|
145
|
+
return "z.boolean()";
|
|
146
|
+
case "date":
|
|
147
|
+
return "z.string().date()";
|
|
148
|
+
case "datetime":
|
|
149
|
+
return "z.string().datetime({ offset: true })";
|
|
150
|
+
case "array":
|
|
151
|
+
return `z.array(${mapItem(c.sqlType)})`;
|
|
152
|
+
case "json":
|
|
153
|
+
return "z.unknown()";
|
|
154
|
+
default:
|
|
155
|
+
return "z.string()";
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
function mapItem(sqlType) {
|
|
159
|
+
const t = sqlType.replace(/\[\]$/, "").toLowerCase();
|
|
160
|
+
return /^(int|numeric|real|double|float|bigint|smallint)/.test(t) ? "z.number()" : "z.string()";
|
|
161
|
+
}
|
|
162
|
+
var q = (s) => JSON.stringify(s);
|
|
163
|
+
var key = (s) => /^[A-Za-z_$][\w$]*$/.test(s) ? s : q(s);
|
|
164
|
+
function emitContract(plans, opts) {
|
|
165
|
+
const out = [];
|
|
166
|
+
out.push(`import { defineBisque, ref, z } from ${q(opts.importFrom)};`);
|
|
167
|
+
out.push("");
|
|
168
|
+
out.push("/**");
|
|
169
|
+
out.push(" * Drafted by `bisque introspect --from supabase`. This is the security boundary");
|
|
170
|
+
out.push(" * between your data and the model: read every line, then run `bisque review`.");
|
|
171
|
+
out.push(" *");
|
|
172
|
+
out.push(" * TODO(review): describe units and formats, add glossary terms, and promote");
|
|
173
|
+
out.push(" * numbers your screens compute (prices in force, totals) to derived resources.");
|
|
174
|
+
out.push(" */");
|
|
175
|
+
out.push("export default defineBisque({");
|
|
176
|
+
out.push(` app: ${q(opts.app)},`);
|
|
177
|
+
out.push(` version: "0.1.0",`);
|
|
178
|
+
out.push(" glossary: {");
|
|
179
|
+
out.push(' // TODO(review): business words users will type, e.g. sales: "Value of delivered orders, excl. VAT"');
|
|
180
|
+
out.push(" },");
|
|
181
|
+
out.push(" resources: {");
|
|
182
|
+
for (const p of plans) {
|
|
183
|
+
if (!p.include) {
|
|
184
|
+
out.push(` // ${p.table.name}: excluded (${p.reason})`);
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
out.push(` ${key(p.table.name)}: {`);
|
|
188
|
+
if (p.table.comment) out.push(` describe: ${q(p.table.comment)},`);
|
|
189
|
+
for (const w of p.warnings) out.push(` // \u26A0 ${w}`);
|
|
190
|
+
out.push(" fields: {");
|
|
191
|
+
for (const f of p.fields) {
|
|
192
|
+
const c = f.column;
|
|
193
|
+
if (!f.include) {
|
|
194
|
+
out.push(` // ${c.name}: excluded (${f.reason})`);
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
let expr = c.references && p.refs.includes(c.name) ? `ref(${q(c.references)})` : zodFor(c);
|
|
198
|
+
if (c.nullable && !c.primaryKey) expr += ".nullable()";
|
|
199
|
+
if (c.comment) expr += `.describe(${q(c.comment)})`;
|
|
200
|
+
const warn = f.warnings.length ? ` // \u26A0 ${f.warnings.join("; ")}` : !c.comment && !c.references && c.name !== "id" ? " // TODO(review): describe" : "";
|
|
201
|
+
out.push(` ${key(c.name)}: ${expr},${warn}`);
|
|
202
|
+
}
|
|
203
|
+
out.push(" },");
|
|
204
|
+
out.push(" },");
|
|
205
|
+
}
|
|
206
|
+
out.push(" },");
|
|
207
|
+
out.push(" intents: {");
|
|
208
|
+
out.push(" // Writes go here, one per host function (see agents.md, step S4).");
|
|
209
|
+
out.push(" },");
|
|
210
|
+
out.push(" slots: {");
|
|
211
|
+
out.push(" // TODO: name the places on your pages where views may appear.");
|
|
212
|
+
out.push(` "home.main": { accepts: ["spec"], size: "wide", label: "on the home page" },`);
|
|
213
|
+
out.push(" },");
|
|
214
|
+
out.push(` theme: { accent: "color", surface: "color", ink: "color", radius: "length", font: ["sans", "mono"] },`);
|
|
215
|
+
out.push("});");
|
|
216
|
+
out.push("");
|
|
217
|
+
return out.join("\n");
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// src/review.ts
|
|
221
|
+
import { PRODUCT as PRODUCT2 } from "@crasi/bisque-core";
|
|
222
|
+
import { sharedFieldKeys } from "@crasi/bisque-contract";
|
|
223
|
+
function unbounded(name, s, path = "") {
|
|
224
|
+
if (!s || typeof s !== "object") return [];
|
|
225
|
+
const out = [];
|
|
226
|
+
const at = path ? `${path}` : name;
|
|
227
|
+
if (Array.isArray(s.anyOf)) for (const x of s.anyOf) out.push(...unbounded(name, x, path));
|
|
228
|
+
const idLike = /(^id$|Id$|Ids$|_id$|_ids$)/.test(at.replace(/\[\]$/g, "").split(".").pop() ?? "");
|
|
229
|
+
if (s.type === "string" && s.maxLength == null && !s.enum && !s.format && s.const == null && !s.pattern && !idLike) out.push(at);
|
|
230
|
+
if (s.type === "array") {
|
|
231
|
+
if (s.maxItems == null) out.push(`${at}[]`);
|
|
232
|
+
out.push(...unbounded(name, s.items, `${at}[]`));
|
|
233
|
+
}
|
|
234
|
+
if (s.type === "object") for (const [k, v] of Object.entries(s.properties ?? {})) out.push(...unbounded(name, v, path ? `${path}.${k}` : k));
|
|
235
|
+
return [...new Set(out)];
|
|
236
|
+
}
|
|
237
|
+
async function runDerivedChecks(fx) {
|
|
238
|
+
const out = [];
|
|
239
|
+
for (const d of fx?.derived ?? []) {
|
|
240
|
+
const rows = (await d.rows()).filter((r) => d.where ? d.where(r) : true);
|
|
241
|
+
const actual = Math.round(rows.reduce((a, r) => a + (Number(r[d.field]) || 0), 0) * 100) / 100;
|
|
242
|
+
const expected = Math.round((typeof d.expected === "function" ? await d.expected() : d.expected) * 100) / 100;
|
|
243
|
+
out.push({ label: d.label, resource: d.resource, field: d.field, actual, expected, ok: Math.abs(actual - expected) < 5e-3 });
|
|
244
|
+
}
|
|
245
|
+
return out;
|
|
246
|
+
}
|
|
247
|
+
function contractQuality(m) {
|
|
248
|
+
const fields = Object.values(m.resources).flatMap(
|
|
249
|
+
(r) => Object.entries(r.fields).filter(([f]) => f !== "id").map(([, d]) => d)
|
|
250
|
+
);
|
|
251
|
+
const described = fields.filter((d) => d.describe || d.label || d.ref).length;
|
|
252
|
+
const describedShare = fields.length ? described / fields.length : 0;
|
|
253
|
+
const glossaryTerms = Object.keys(m.glossary ?? {}).length;
|
|
254
|
+
const derived = Object.values(m.resources).filter((r) => r.derived).length;
|
|
255
|
+
return { ...qualityFormula(describedShare, glossaryTerms, derived, 0), describedShare, glossaryTerms, derived };
|
|
256
|
+
}
|
|
257
|
+
var fmt = (n) => n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
|
258
|
+
async function buildReview(m, opts = {}) {
|
|
259
|
+
const items = [];
|
|
260
|
+
const exposed = Object.entries(m.resources).map(([r, d]) => d.derived ? `${r}(derived)` : `${r}(${Object.keys(d.fields).length} fields)`);
|
|
261
|
+
items.push({ id: "exposed", section: "EXPOSED", text: exposed.join(" "), level: "info" });
|
|
262
|
+
if (opts.introspected) {
|
|
263
|
+
const ex = [...opts.introspected.excluded.map((e) => e.table), ...opts.introspected.excludedFields.map((e) => `${e.table}.${e.field}`)];
|
|
264
|
+
if (ex.length) items.push({ id: "excluded", section: "EXCLUDED", text: ex.join(", "), level: "risky", note: "confirm" });
|
|
265
|
+
}
|
|
266
|
+
for (const key2 of sharedFieldKeys(m))
|
|
267
|
+
items.push({ id: `share:${key2}`, section: "SHARED WITH MODEL", text: `${key2} (values: share)`, level: "risky", note: "confirm: these values reach the model" });
|
|
268
|
+
for (const [name, i] of Object.entries(m.intents)) {
|
|
269
|
+
const loose = unbounded(name, i.args);
|
|
270
|
+
let level = "ok", note = "ok";
|
|
271
|
+
if (i.money && i.policy !== "confirm") {
|
|
272
|
+
level = "blocking";
|
|
273
|
+
note = "writes money: needs confirm";
|
|
274
|
+
} else if (i.destructive && i.policy !== "confirm") {
|
|
275
|
+
level = "blocking";
|
|
276
|
+
note = "destructive: needs confirm";
|
|
277
|
+
} else if (i.policy === "silent") {
|
|
278
|
+
level = "risky";
|
|
279
|
+
note = "writes without telling the user";
|
|
280
|
+
} else if (loose.length) {
|
|
281
|
+
level = "risky";
|
|
282
|
+
note = `unbounded args: ${loose.join(", ")}`;
|
|
283
|
+
}
|
|
284
|
+
items.push({ id: `intent:${name}:${i.policy}`, section: "INTENTS", text: `${name.padEnd(16)}${i.policy.padEnd(12)}`, level, note });
|
|
285
|
+
}
|
|
286
|
+
if (m.automations) {
|
|
287
|
+
const a = m.automations;
|
|
288
|
+
items.push({
|
|
289
|
+
id: "automations",
|
|
290
|
+
section: "AUTOMATIONS",
|
|
291
|
+
text: `run ${a.cadence === "hour" ? "hourly" : "daily"} (${a.timeZone}), \u2264 ${a.maxPerUser} per user, roles ${a.roles === "*" ? "all" : a.roles.join(", ")}`,
|
|
292
|
+
level: "info"
|
|
293
|
+
});
|
|
294
|
+
for (const ch of Object.keys(a.channels))
|
|
295
|
+
items.push({
|
|
296
|
+
id: `channel:${ch}`,
|
|
297
|
+
section: "AUTOMATIONS",
|
|
298
|
+
text: `channel ${ch}`,
|
|
299
|
+
level: "risky",
|
|
300
|
+
note: "confirm: sends rows out of the app, to each automation's owner only"
|
|
301
|
+
});
|
|
302
|
+
for (const [name, i] of Object.entries(m.intents))
|
|
303
|
+
if (i.automate)
|
|
304
|
+
items.push({ id: `automate:${name}`, section: "AUTOMATIONS", text: `${name} automate`, level: "risky", note: "confirm: runs unattended, with no toast or undo" });
|
|
305
|
+
}
|
|
306
|
+
const checks = await runDerivedChecks(opts.fixtures);
|
|
307
|
+
for (const [r, d] of Object.entries(m.resources)) {
|
|
308
|
+
if (!d.derived) continue;
|
|
309
|
+
const mine = checks.filter((c) => c.resource === r);
|
|
310
|
+
if (!mine.length) items.push({ id: `derived:${r}`, section: "DERIVED", text: `${r}: no fixture check`, level: "risky", note: "add one to fixtures.derived" });
|
|
311
|
+
for (const c of mine)
|
|
312
|
+
items.push({
|
|
313
|
+
id: `derived:${r}:${c.label}`,
|
|
314
|
+
section: "DERIVED",
|
|
315
|
+
text: `${r}.${c.field} ${c.label} \u03A3 ${fmt(c.actual)}${c.ok ? " = host screen \u2713" : ` \u2260 host screen ${fmt(c.expected)}`}`,
|
|
316
|
+
level: c.ok ? "ok" : "blocking",
|
|
317
|
+
note: c.ok ? void 0 : "re-use the host's own calculation"
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
const undescribed = Object.entries(m.resources).flatMap(
|
|
321
|
+
([r, d]) => Object.entries(d.fields).filter(([f, x]) => f !== "id" && !x.describe && !x.label && !x.ref).map(([f]) => `${r}.${f}`)
|
|
322
|
+
);
|
|
323
|
+
if (undescribed.length)
|
|
324
|
+
items.push({ id: "undescribed", section: "UNREVIEWED", text: `${undescribed.length} fields without a description or label`, level: "info", note: "read" });
|
|
325
|
+
return items;
|
|
326
|
+
}
|
|
327
|
+
function formatReview(m, items, signed, hash) {
|
|
328
|
+
const status = signed && signed.contractHash === hash ? `signed by ${signed.signer} on ${signed.signedAt.slice(0, 10)}` : "not yet signed";
|
|
329
|
+
const lines = [`${PRODUCT2.name} review sheet: ${m.app} contract ${m.version} (${status})`];
|
|
330
|
+
let last = "";
|
|
331
|
+
for (const it of items) {
|
|
332
|
+
const head = it.section === last ? "" : it.section;
|
|
333
|
+
last = it.section;
|
|
334
|
+
const mark = it.level === "ok" ? "ok" : it.level === "blocking" ? `\u2717 ${it.note}` : it.level === "risky" ? `<- ${it.note}` : it.note ? `<- ${it.note}` : "";
|
|
335
|
+
lines.push(`${head.padEnd(20)}${it.text}${mark ? ` ${mark}` : ""}`.trimEnd());
|
|
336
|
+
}
|
|
337
|
+
const blocking = items.filter((i) => i.level === "blocking");
|
|
338
|
+
if (blocking.length) lines.push(`
|
|
339
|
+
${blocking.length} item(s) must be fixed before this contract can be signed.`);
|
|
340
|
+
else if (!signed || signed.contractHash !== hash) lines.push(`Sign: ${PRODUCT2.cli} review --sign "you@${m.app}" (blocks ${PRODUCT2.cli} push until signed)`);
|
|
341
|
+
return lines.join("\n");
|
|
342
|
+
}
|
|
343
|
+
function signReview(m, hash, items, signer, now = /* @__PURE__ */ new Date()) {
|
|
344
|
+
const blocking = items.filter((i) => i.level === "blocking");
|
|
345
|
+
if (blocking.length) throw new Error(`cannot sign: ${blocking.map((b) => `${b.text.trim()} (${b.note})`).join("; ")}`);
|
|
346
|
+
if (!signer.trim()) throw new Error("--sign needs the signer's name or email");
|
|
347
|
+
return {
|
|
348
|
+
app: m.app,
|
|
349
|
+
version: m.version,
|
|
350
|
+
contractHash: hash,
|
|
351
|
+
signer: signer.trim(),
|
|
352
|
+
signedAt: now.toISOString(),
|
|
353
|
+
acknowledged: items.filter((i) => i.level === "risky").map((i) => i.id)
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
function unacknowledged(items, r) {
|
|
357
|
+
const ack = new Set(r?.acknowledged ?? []);
|
|
358
|
+
return items.filter((i) => i.level === "risky" && !ack.has(i.id));
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// src/sql.ts
|
|
362
|
+
function mapType(sqlType) {
|
|
363
|
+
const t = sqlType.toLowerCase().trim();
|
|
364
|
+
if (t.endsWith("[]")) return "array";
|
|
365
|
+
if (/^(int|integer|bigint|smallint|serial|bigserial|numeric|decimal|real|double|float)/.test(t)) return "number";
|
|
366
|
+
if (/^bool/.test(t)) return "boolean";
|
|
367
|
+
if (/^date$/.test(t)) return "date";
|
|
368
|
+
if (/^(timestamp|timestamptz|time)/.test(t)) return "datetime";
|
|
369
|
+
if (/^jsonb?$/.test(t)) return "json";
|
|
370
|
+
return "string";
|
|
371
|
+
}
|
|
372
|
+
function stripComments(sql) {
|
|
373
|
+
return sql.replace(/--[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
|
|
374
|
+
}
|
|
375
|
+
function statements(sql) {
|
|
376
|
+
const out = [];
|
|
377
|
+
let cur = "", depth = 0, quote = null, dollar = null;
|
|
378
|
+
for (let i = 0; i < sql.length; i++) {
|
|
379
|
+
const ch = sql[i];
|
|
380
|
+
if (dollar) {
|
|
381
|
+
if (sql.startsWith(dollar, i)) {
|
|
382
|
+
cur += dollar;
|
|
383
|
+
i += dollar.length - 1;
|
|
384
|
+
dollar = null;
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
cur += ch;
|
|
388
|
+
continue;
|
|
389
|
+
}
|
|
390
|
+
if (quote) {
|
|
391
|
+
cur += ch;
|
|
392
|
+
if (ch === quote && sql[i + 1] === quote) {
|
|
393
|
+
cur += sql[++i];
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
if (ch === quote) quote = null;
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
if (ch === "'" || ch === '"') {
|
|
400
|
+
quote = ch;
|
|
401
|
+
cur += ch;
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
const m = /^\$[A-Za-z_]*\$/.exec(sql.slice(i, i + 40));
|
|
405
|
+
if (m) {
|
|
406
|
+
dollar = m[0];
|
|
407
|
+
cur += dollar;
|
|
408
|
+
i += dollar.length - 1;
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
if (ch === "(") depth++;
|
|
412
|
+
if (ch === ")") depth--;
|
|
413
|
+
if (ch === ";" && depth === 0) {
|
|
414
|
+
if (cur.trim()) out.push(cur.trim());
|
|
415
|
+
cur = "";
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
cur += ch;
|
|
419
|
+
}
|
|
420
|
+
if (cur.trim()) out.push(cur.trim());
|
|
421
|
+
return out;
|
|
422
|
+
}
|
|
423
|
+
function splitTop(s) {
|
|
424
|
+
const out = [];
|
|
425
|
+
let cur = "", depth = 0, quote = false;
|
|
426
|
+
for (const ch of s) {
|
|
427
|
+
if (ch === "'") quote = !quote;
|
|
428
|
+
if (!quote && ch === "(") depth++;
|
|
429
|
+
if (!quote && ch === ")") depth--;
|
|
430
|
+
if (!quote && ch === "," && depth === 0) {
|
|
431
|
+
out.push(cur.trim());
|
|
432
|
+
cur = "";
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
cur += ch;
|
|
436
|
+
}
|
|
437
|
+
if (cur.trim()) out.push(cur.trim());
|
|
438
|
+
return out;
|
|
439
|
+
}
|
|
440
|
+
var ident = (s) => s.replace(/"/g, "").trim();
|
|
441
|
+
var tableName = (q2) => {
|
|
442
|
+
const parts = ident(q2).split(".");
|
|
443
|
+
return parts.length > 1 ? { schema: parts[0], name: parts[1] } : { schema: "public", name: parts[0] };
|
|
444
|
+
};
|
|
445
|
+
function parseEnum(check2, col) {
|
|
446
|
+
const re = new RegExp(`\\b${col}\\b\\s+in\\s*\\(([^)]*)\\)`, "i");
|
|
447
|
+
const m = re.exec(check2);
|
|
448
|
+
if (!m) return void 0;
|
|
449
|
+
const vals = [...m[1].matchAll(/'((?:[^']|'')*)'/g)].map((x) => x[1].replace(/''/g, "'"));
|
|
450
|
+
return vals.length ? vals : void 0;
|
|
451
|
+
}
|
|
452
|
+
var CONSTRAINT_START = /^(constraint|primary\s+key|foreign\s+key|unique|check|exclude)\b/i;
|
|
453
|
+
function parseColumn(def) {
|
|
454
|
+
if (CONSTRAINT_START.test(def)) return null;
|
|
455
|
+
const m = /^("?[A-Za-z_][\w]*"?)\s+(.+)$/s.exec(def);
|
|
456
|
+
if (!m) return null;
|
|
457
|
+
const name = ident(m[1]);
|
|
458
|
+
const rest = m[2];
|
|
459
|
+
const typeM = /^([A-Za-z_][\w ]*?(?:\([^)]*\))?(?:\[\])?)(?=\s+(?:not|null|primary|references|default|check|unique|generated|constraint|collate)\b|\s*$)/i.exec(rest);
|
|
460
|
+
const sqlType = (typeM?.[1] ?? rest.split(/\s+/)[0]).trim();
|
|
461
|
+
const ref = /\breferences\s+("?[\w.]+"?)/i.exec(rest);
|
|
462
|
+
const checkM = /\bcheck\s*\(([\s\S]*)\)/i.exec(rest);
|
|
463
|
+
const primaryKey = /\bprimary\s+key\b/i.test(rest);
|
|
464
|
+
return {
|
|
465
|
+
name,
|
|
466
|
+
sqlType,
|
|
467
|
+
type: mapType(sqlType),
|
|
468
|
+
nullable: !/\bnot\s+null\b/i.test(rest) && !primaryKey,
|
|
469
|
+
primaryKey,
|
|
470
|
+
references: ref ? tableName(ref[1]).name : void 0,
|
|
471
|
+
enum: checkM ? parseEnum(checkM[1], name) : void 0,
|
|
472
|
+
hasDefault: /\bdefault\b/i.test(rest)
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
function parseMigrations(files2) {
|
|
476
|
+
const tables = /* @__PURE__ */ new Map();
|
|
477
|
+
const sorted = [...files2].sort((a, b) => a.name.localeCompare(b.name));
|
|
478
|
+
for (const f of sorted) {
|
|
479
|
+
for (const raw of statements(stripComments(f.sql))) {
|
|
480
|
+
const st = raw.replace(/\s+/g, " ").trim();
|
|
481
|
+
let m;
|
|
482
|
+
if (m = /^create table (?:if not exists )?("?[\w.]+"?) \((.*)\)(?: [^)]*)?$/is.exec(st)) {
|
|
483
|
+
const { schema, name } = tableName(m[1]);
|
|
484
|
+
const t = { name, schema, columns: [] };
|
|
485
|
+
for (const def of splitTop(m[2])) {
|
|
486
|
+
const col = parseColumn(def);
|
|
487
|
+
if (col) {
|
|
488
|
+
t.columns.push(col);
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
applyConstraint(t, def);
|
|
492
|
+
}
|
|
493
|
+
tables.set(name, t);
|
|
494
|
+
continue;
|
|
495
|
+
}
|
|
496
|
+
if (m = /^drop table (?:if exists )?("?[\w.]+"?)/i.exec(st)) {
|
|
497
|
+
tables.delete(tableName(m[1]).name);
|
|
498
|
+
continue;
|
|
499
|
+
}
|
|
500
|
+
if (m = /^alter table (?:only )?(?:if exists )?("?[\w.]+"?) (.*)$/is.exec(st)) {
|
|
501
|
+
const t = tables.get(tableName(m[1]).name);
|
|
502
|
+
if (!t) continue;
|
|
503
|
+
for (const action of splitTop(m[2])) alterTable(t, action);
|
|
504
|
+
continue;
|
|
505
|
+
}
|
|
506
|
+
if (m = /^comment on column ("?[\w.]+"?) is '((?:[^']|'')*)'$/is.exec(st)) {
|
|
507
|
+
const parts = ident(m[1]).split(".");
|
|
508
|
+
const [tn, cn] = parts.slice(-2);
|
|
509
|
+
const col = tables.get(tn)?.columns.find((c) => c.name === cn);
|
|
510
|
+
if (col) col.comment = m[2].replace(/''/g, "'");
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
if (m = /^comment on table ("?[\w.]+"?) is '((?:[^']|'')*)'$/is.exec(st)) {
|
|
514
|
+
const t = tables.get(tableName(m[1]).name);
|
|
515
|
+
if (t) t.comment = m[2].replace(/''/g, "'");
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
return [...tables.values()];
|
|
520
|
+
}
|
|
521
|
+
function applyConstraint(t, def) {
|
|
522
|
+
const fk = /foreign key \(([^)]+)\) references ("?[\w.]+"?)/i.exec(def);
|
|
523
|
+
if (fk) {
|
|
524
|
+
const col = t.columns.find((c) => c.name === ident(fk[1]));
|
|
525
|
+
if (col) col.references = tableName(fk[2]).name;
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
const pk = /primary key \(([^)]+)\)/i.exec(def);
|
|
529
|
+
if (pk)
|
|
530
|
+
for (const n of pk[1].split(",").map(ident)) {
|
|
531
|
+
const c = t.columns.find((x) => x.name === n);
|
|
532
|
+
if (c) {
|
|
533
|
+
c.primaryKey = true;
|
|
534
|
+
c.nullable = false;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
const check2 = /check \(([\s\S]*)\)/i.exec(def);
|
|
538
|
+
if (check2) for (const c of t.columns) c.enum = parseEnum(check2[1], c.name) ?? c.enum;
|
|
539
|
+
}
|
|
540
|
+
function alterTable(t, action) {
|
|
541
|
+
let m;
|
|
542
|
+
if (m = /^add column (?:if not exists )?(.*)$/is.exec(action)) {
|
|
543
|
+
const col = parseColumn(m[1]);
|
|
544
|
+
if (col) {
|
|
545
|
+
t.columns = t.columns.filter((c) => c.name !== col.name);
|
|
546
|
+
t.columns.push(col);
|
|
547
|
+
}
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
if (m = /^drop column (?:if exists )?("?\w+"?)/i.exec(action)) {
|
|
551
|
+
t.columns = t.columns.filter((c) => c.name !== ident(m[1]));
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
if (m = /^rename column ("?\w+"?) to ("?\w+"?)/i.exec(action)) {
|
|
555
|
+
const c = t.columns.find((x) => x.name === ident(m[1]));
|
|
556
|
+
if (c) c.name = ident(m[2]);
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
if (m = /^alter column ("?\w+"?) (set|drop) not null/i.exec(action)) {
|
|
560
|
+
const c = t.columns.find((x) => x.name === ident(m[1]));
|
|
561
|
+
if (c) c.nullable = m[2].toLowerCase() === "drop";
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
if (m = /^alter column ("?\w+"?) (?:set data )?type ([\w ()[\]]+?)(?: using .*)?$/is.exec(action)) {
|
|
565
|
+
const c = t.columns.find((x) => x.name === ident(m[1]));
|
|
566
|
+
if (c) {
|
|
567
|
+
c.sqlType = m[2].trim();
|
|
568
|
+
c.type = mapType(c.sqlType);
|
|
569
|
+
}
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
if (m = /^add (?:constraint "?\w+"? )?(.*)$/is.exec(action)) applyConstraint(t, m[1]);
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// src/templates.ts
|
|
576
|
+
import { PRODUCT as PRODUCT3, pkg as pkg2 } from "@crasi/bisque-core";
|
|
577
|
+
function configStub(app, importFrom) {
|
|
578
|
+
return `import { defineBisque, z } from "${importFrom}";
|
|
579
|
+
|
|
580
|
+
// ${PRODUCT3.name} contract (stub: 0 resources). Run \`npx --no ${PRODUCT3.cli} introspect --from supabase\`
|
|
581
|
+
// to draft it from your schema, then \`npx --no ${PRODUCT3.cli} review\`.
|
|
582
|
+
export default defineBisque({
|
|
583
|
+
app: ${JSON.stringify(app)},
|
|
584
|
+
version: "0.1.0",
|
|
585
|
+
resources: {},
|
|
586
|
+
slots: {
|
|
587
|
+
"home.main": { accepts: ["spec"], size: "wide", label: "on the home page" },
|
|
588
|
+
},
|
|
589
|
+
theme: { accent: "color", surface: "color", ink: "color", radius: "length", font: ["sans", "mono"] },
|
|
590
|
+
});
|
|
591
|
+
`;
|
|
592
|
+
}
|
|
593
|
+
function tokenRoute(supabase) {
|
|
594
|
+
if (supabase)
|
|
595
|
+
return `import { mintBisqueToken } from "${pkg2("next/server")}";
|
|
596
|
+
import { createClient } from "@/lib/supabase/server";
|
|
597
|
+
|
|
598
|
+
// Mints a short-lived ${PRODUCT3.name} session token for the signed-in user.
|
|
599
|
+
// The secret key never leaves the server.
|
|
600
|
+
export async function POST() {
|
|
601
|
+
const { data } = await (await createClient()).auth.getUser();
|
|
602
|
+
if (!data.user) return new Response(null, { status: 401 });
|
|
603
|
+
return mintBisqueToken({
|
|
604
|
+
secret: process.env.${PRODUCT3.envPrefix}SECRET_KEY!,
|
|
605
|
+
app: ${JSON.stringify("TODO-app-id")},
|
|
606
|
+
tenant: "TODO-tenant", // your tenant or workspace id
|
|
607
|
+
user: data.user.id,
|
|
608
|
+
role: "member", // map your roles here
|
|
609
|
+
ttl: 900,
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
`;
|
|
613
|
+
return `import { mintBisqueToken } from "${pkg2("next/server")}";
|
|
614
|
+
|
|
615
|
+
// Mints a short-lived ${PRODUCT3.name} session token for the signed-in user.
|
|
616
|
+
export async function POST(req: Request) {
|
|
617
|
+
const user = null as null | { id: string }; // TODO: read your session from req
|
|
618
|
+
if (!user) return new Response(null, { status: 401 });
|
|
619
|
+
return mintBisqueToken({ secret: process.env.${PRODUCT3.envPrefix}SECRET_KEY!, app: "TODO-app-id", tenant: "TODO-tenant", user: user.id, role: "member", ttl: 900 });
|
|
620
|
+
}
|
|
621
|
+
`;
|
|
622
|
+
}
|
|
623
|
+
function cspSnippet(_app) {
|
|
624
|
+
return `connect-src ${PRODUCT3.conductorUrl}`;
|
|
625
|
+
}
|
|
626
|
+
function artifactsMigration() {
|
|
627
|
+
const t = PRODUCT3.artifactsTable;
|
|
628
|
+
return `-- ${PRODUCT3.name} artifacts (generated by \`${PRODUCT3.cli} init\`). Specs and manifests only, never data.
|
|
629
|
+
create table if not exists public.${t} (
|
|
630
|
+
id text not null,
|
|
631
|
+
rev int not null check (rev > 0),
|
|
632
|
+
tenant text not null,
|
|
633
|
+
owner text not null,
|
|
634
|
+
owner_name text,
|
|
635
|
+
visibility text not null default 'private' check (visibility in ('private', 'workspace')),
|
|
636
|
+
status text not null default 'live' check (status in ('live', 'broken', 'disabled', 'archived')),
|
|
637
|
+
draft jsonb not null,
|
|
638
|
+
contract_version text not null,
|
|
639
|
+
format int not null default 1,
|
|
640
|
+
slot text not null,
|
|
641
|
+
history jsonb,
|
|
642
|
+
hidden_by text[] not null default '{}',
|
|
643
|
+
is_head boolean not null default true,
|
|
644
|
+
created_at timestamptz not null default now(),
|
|
645
|
+
updated_at timestamptz not null default now(),
|
|
646
|
+
updated_by text not null,
|
|
647
|
+
primary key (id, rev)
|
|
648
|
+
);
|
|
649
|
+
|
|
650
|
+
create unique index if not exists ${t}_head on public.${t} (id) where is_head;
|
|
651
|
+
create index if not exists ${t}_slot on public.${t} (tenant, slot) where is_head;
|
|
652
|
+
|
|
653
|
+
alter table public.${t} enable row level security;
|
|
654
|
+
|
|
655
|
+
create policy ${t}_read on public.${t} for select to authenticated
|
|
656
|
+
using (owner = auth.uid()::text or visibility = 'workspace');
|
|
657
|
+
|
|
658
|
+
create policy ${t}_insert on public.${t} for insert to authenticated
|
|
659
|
+
with check (owner = auth.uid()::text and updated_by = auth.uid()::text);
|
|
660
|
+
|
|
661
|
+
create policy ${t}_update on public.${t} for update to authenticated
|
|
662
|
+
using (owner = auth.uid()::text or visibility = 'workspace');
|
|
663
|
+
|
|
664
|
+
-- Non-owners may only change hidden_by (Hide for me).
|
|
665
|
+
create or replace function public.${t}_guard() returns trigger language plpgsql as $$
|
|
666
|
+
begin
|
|
667
|
+
if old.owner <> auth.uid()::text and (
|
|
668
|
+
new.draft is distinct from old.draft or new.visibility is distinct from old.visibility or
|
|
669
|
+
new.status is distinct from old.status or new.owner is distinct from old.owner or
|
|
670
|
+
new.is_head is distinct from old.is_head
|
|
671
|
+
) then
|
|
672
|
+
raise exception '${PRODUCT3.name}: only the owner can change this artifact';
|
|
673
|
+
end if;
|
|
674
|
+
return new;
|
|
675
|
+
end $$;
|
|
676
|
+
|
|
677
|
+
create trigger ${t}_guard before update on public.${t}
|
|
678
|
+
for each row execute function public.${t}_guard();
|
|
679
|
+
|
|
680
|
+
-- Compare-and-set save: lock the head, check its revision, retire it and insert
|
|
681
|
+
-- the next one in one transaction. Runs as the caller, so the policies above apply.
|
|
682
|
+
create or replace function public.${t}_save(p_row jsonb, p_expected_rev int) returns int
|
|
683
|
+
language plpgsql security invoker as $$
|
|
684
|
+
declare
|
|
685
|
+
cur int;
|
|
686
|
+
begin
|
|
687
|
+
select rev into cur from public.${t} where id = p_row->>'id' and is_head for update;
|
|
688
|
+
if cur is distinct from p_expected_rev then
|
|
689
|
+
raise exception '${PRODUCT3.name}: artifact was changed by someone else' using errcode = '40001';
|
|
690
|
+
end if;
|
|
691
|
+
if cur is not null then
|
|
692
|
+
update public.${t} set is_head = false where id = p_row->>'id' and rev = cur;
|
|
693
|
+
end if;
|
|
694
|
+
insert into public.${t}
|
|
695
|
+
select * from jsonb_populate_record(null::public.${t}, p_row || jsonb_build_object('rev', coalesce(cur, 0) + 1, 'is_head', true));
|
|
696
|
+
return coalesce(cur, 0) + 1;
|
|
697
|
+
end $$;
|
|
698
|
+
`;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// src/commands.ts
|
|
702
|
+
var ok = (out) => ({ code: 0, out });
|
|
703
|
+
var fail = (out) => ({ code: 1, out });
|
|
704
|
+
function detect(root) {
|
|
705
|
+
const pkg4 = readJson(join2(root, "package.json")) ?? {};
|
|
706
|
+
const deps = { ...pkg4.dependencies, ...pkg4.devDependencies };
|
|
707
|
+
const appDir = ["src/app", "app"].find((d) => existsSync2(join2(root, d))) ?? null;
|
|
708
|
+
return {
|
|
709
|
+
next: !!deps.next,
|
|
710
|
+
appDir,
|
|
711
|
+
srcDir: existsSync2(join2(root, "src")),
|
|
712
|
+
typescript: !!deps.typescript || existsSync2(join2(root, "tsconfig.json")),
|
|
713
|
+
supabase: existsSync2(join2(root, "supabase")) || !!deps["@supabase/supabase-js"],
|
|
714
|
+
name: (pkg4.name ?? basename(root)).replace(/^@[^/]+\//, "")
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
function initPlan(root) {
|
|
718
|
+
const d = detect(root);
|
|
719
|
+
const steps = [];
|
|
720
|
+
const base = d.srcDir ? "src/" : "";
|
|
721
|
+
const importFrom = d.next ? pkg3("next") : pkg3("contract");
|
|
722
|
+
const pkgs = [pkg3("react"), d.next ? pkg3("next") : pkg3("contract")];
|
|
723
|
+
steps.push({ id: "install", action: "run", command: `npm install ${pkgs.join(" ")}`, note: "install the SDK" });
|
|
724
|
+
const cfg = `${base}${PRODUCT4.configFile}`;
|
|
725
|
+
if (!existsSync2(join2(root, cfg))) steps.push({ id: "config", action: "write", path: cfg, content: configStub(d.name, importFrom), note: "stub: 0 resources" });
|
|
726
|
+
if (d.next && d.appDir) {
|
|
727
|
+
const route = `${d.appDir}/api/${PRODUCT4.slug}/token/route.ts`;
|
|
728
|
+
if (!existsSync2(join2(root, route)))
|
|
729
|
+
steps.push({ id: "token-route", action: "write", path: route, content: tokenRoute(d.supabase), note: "mints a 15-minute session token server-side" });
|
|
730
|
+
} else {
|
|
731
|
+
steps.push({
|
|
732
|
+
id: "token-route",
|
|
733
|
+
action: "manual",
|
|
734
|
+
note: `add a POST route that calls mintBisqueToken() from ${pkg3("next/server")} (or signToken from ${pkg3("core")}) with the signed-in user`
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
steps.push({
|
|
738
|
+
id: "env",
|
|
739
|
+
action: "append-env",
|
|
740
|
+
path: d.next ? ".env.local" : ".env",
|
|
741
|
+
content: `${ENV.publishableKey}=
|
|
742
|
+
${ENV.secretKey}=
|
|
743
|
+
`,
|
|
744
|
+
note: "fill from the dashboard; the secret stays server-side"
|
|
745
|
+
});
|
|
746
|
+
if (d.supabase) {
|
|
747
|
+
const dir = "supabase/migrations";
|
|
748
|
+
const exists = existsSync2(join2(root, dir)) && readdirSync(join2(root, dir)).some((f) => f.includes(PRODUCT4.artifactsTable));
|
|
749
|
+
if (!exists)
|
|
750
|
+
steps.push({
|
|
751
|
+
id: "artifacts-table",
|
|
752
|
+
action: "write",
|
|
753
|
+
path: `${dir}/${stamp()}_${PRODUCT4.artifactsTable}.sql`,
|
|
754
|
+
content: artifactsMigration(),
|
|
755
|
+
note: "artifact store in your own database (decision D1)"
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
steps.push({ id: "csp", action: "manual", content: cspSnippet(d.name), note: `Add to your CSP: ${cspSnippet(d.name)}` });
|
|
759
|
+
steps.push({ id: "next", action: "manual", command: `npx --no ${PRODUCT4.cli} introspect --from supabase`, note: "draft the contract from your schema" });
|
|
760
|
+
return { detected: d, steps };
|
|
761
|
+
}
|
|
762
|
+
function stamp(now = /* @__PURE__ */ new Date()) {
|
|
763
|
+
return now.toISOString().replace(/[-:T]/g, "").slice(0, 14);
|
|
764
|
+
}
|
|
765
|
+
function init(root, opts = {}) {
|
|
766
|
+
const plan = initPlan(root);
|
|
767
|
+
if (opts.agent) return ok([JSON.stringify(plan, null, 2)]);
|
|
768
|
+
const d = plan.detected;
|
|
769
|
+
const out = [
|
|
770
|
+
`\u2713 Detected ${[d.next ? `Next.js${d.appDir ? " (App Router)" : ""}` : "no Next.js", d.typescript ? "TypeScript" : null, d.supabase ? "Supabase" : null].filter(Boolean).join(", ")}`
|
|
771
|
+
];
|
|
772
|
+
for (const s of plan.steps) {
|
|
773
|
+
if (s.action === "write" && s.path) {
|
|
774
|
+
if (!opts.dryRun) {
|
|
775
|
+
mkdirSync2(dirname2(join2(root, s.path)), { recursive: true });
|
|
776
|
+
writeFileSync2(join2(root, s.path), s.content);
|
|
777
|
+
}
|
|
778
|
+
out.push(`\u2713 Wrote ${s.path.padEnd(34)}(${s.note})`);
|
|
779
|
+
} else if (s.action === "append-env" && s.path) {
|
|
780
|
+
const p = join2(root, s.path);
|
|
781
|
+
const cur = existsSync2(p) ? readFileSync2(p, "utf8") : "";
|
|
782
|
+
const missing = s.content.split("\n").filter((l) => l && !cur.includes(l.split("=")[0]));
|
|
783
|
+
if (missing.length && !opts.dryRun) writeFileSync2(p, `${cur}${cur && !cur.endsWith("\n") ? "\n" : ""}${missing.join("\n")}
|
|
784
|
+
`);
|
|
785
|
+
out.push(missing.length ? `\u2713 Added ${missing.map((l) => l.split("=")[0]).join(", ")} to ${s.path} (${s.note})` : `\u2713 ${s.path} already has the keys`);
|
|
786
|
+
} else if (s.action === "run") out.push(`\u2192 Run: ${s.command}`);
|
|
787
|
+
else if (s.id === "next") out.push(`Next: ${s.command}`);
|
|
788
|
+
else out.push(`! ${s.note}`);
|
|
789
|
+
}
|
|
790
|
+
return ok(out);
|
|
791
|
+
}
|
|
792
|
+
function introspect(root, opts) {
|
|
793
|
+
if (opts.from !== "supabase") return fail([`--from ${opts.from} is not supported in v1 (supabase only)`]);
|
|
794
|
+
const dir = join2(root, "supabase/migrations");
|
|
795
|
+
if (!existsSync2(dir)) return fail([`no supabase/migrations in ${root}`]);
|
|
796
|
+
const sqlFiles = readdirSync(dir).filter((f) => f.endsWith(".sql") && !f.includes(PRODUCT4.artifactsTable));
|
|
797
|
+
const tables = parseMigrations(sqlFiles.map((name) => ({ name, sql: readFileSync2(join2(dir, name), "utf8") })));
|
|
798
|
+
const plans = planTables(tables);
|
|
799
|
+
const score = scorePlans(plans);
|
|
800
|
+
const out = formatIntrospection(plans, score).split("\n");
|
|
801
|
+
const d = detect(root);
|
|
802
|
+
const target = opts.out ?? `${d.srcDir ? "src/" : ""}${PRODUCT4.configFile}`;
|
|
803
|
+
const existing = existsSync2(join2(root, target)) ? readFileSync2(join2(root, target), "utf8") : "";
|
|
804
|
+
const isStub = !existing || existing.includes("stub: 0 resources");
|
|
805
|
+
if (!opts.dryRun) {
|
|
806
|
+
if (isStub || opts.force) {
|
|
807
|
+
writeFileSync2(join2(root, target), emitContract(plans, { app: d.name, importFrom: d.next ? pkg3("next") : pkg3("contract") }));
|
|
808
|
+
out.push(`\u2713 Wrote ${target}`);
|
|
809
|
+
} else {
|
|
810
|
+
const draft = join2(root, ".bisque/contract.draft.ts");
|
|
811
|
+
mkdirSync2(dirname2(draft), { recursive: true });
|
|
812
|
+
writeFileSync2(draft, emitContract(plans, { app: d.name, importFrom: d.next ? pkg3("next") : pkg3("contract") }));
|
|
813
|
+
out.push(`! ${target} already has a contract; wrote the draft to ${relative(root, draft)} (pass --force to overwrite)`);
|
|
814
|
+
}
|
|
815
|
+
writeIntrospected(root, {
|
|
816
|
+
excluded: plans.filter((p) => !p.include).map((p) => ({ table: p.table.name, reason: p.reason ?? "" })),
|
|
817
|
+
excludedFields: plans.filter((p) => p.include).flatMap((p) => p.fields.filter((f) => !f.include && f.reason !== "audit column").map((f) => ({ table: p.table.name, field: f.column.name, reason: f.reason ?? "" })))
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
out.push(`Next: describe what the draft marks, then \`${PRODUCT4.cli} review\``);
|
|
821
|
+
return ok(out);
|
|
822
|
+
}
|
|
823
|
+
async function review(root, opts = {}) {
|
|
824
|
+
const l = await loadConfig(root, opts.config);
|
|
825
|
+
const items = await buildReview(l.manifest, { fixtures: l.fixtures, introspected: readIntrospected(root) ?? void 0 });
|
|
826
|
+
if (opts.json) return ok([JSON.stringify({ app: l.manifest.app, version: l.manifest.version, hash: l.hash, items }, null, 2)]);
|
|
827
|
+
if (opts.sign !== void 0) {
|
|
828
|
+
try {
|
|
829
|
+
const r = signReview(l.manifest, l.hash, items, opts.sign);
|
|
830
|
+
writeReview(root, r);
|
|
831
|
+
return ok([formatReview(l.manifest, items, r, l.hash), `\u2713 Signed by ${r.signer}. Wrote ${PRODUCT4.reviewFile}; commit it with the contract.`]);
|
|
832
|
+
} catch (e) {
|
|
833
|
+
return fail([formatReview(l.manifest, items, null, l.hash), `\u2717 ${e.message}`]);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
return ok([formatReview(l.manifest, items, readReview(root), l.hash)]);
|
|
837
|
+
}
|
|
838
|
+
async function check(root, opts = {}) {
|
|
839
|
+
const l = await loadConfig(root, opts.config);
|
|
840
|
+
const m = l.manifest;
|
|
841
|
+
const out = [];
|
|
842
|
+
const errors = [];
|
|
843
|
+
const lock = readLock(root);
|
|
844
|
+
const quality = contractQuality(m);
|
|
845
|
+
let renames = {};
|
|
846
|
+
if (lock) {
|
|
847
|
+
const diff = contractDiff(lock.manifest, m);
|
|
848
|
+
renames = diff.renames;
|
|
849
|
+
out.push(`contract ${lock.version} -> ${m.version}${lock.hash === l.hash ? " (unchanged)" : ""}`);
|
|
850
|
+
if (lock.hash !== l.hash && lock.version === m.version) errors.push("the contract changed but its version did not");
|
|
851
|
+
const breaking = breakingChanges(diff);
|
|
852
|
+
if (breaking.length && semverMajor(lock.version) === semverMajor(m.version) && semverMajor(m.version) > 0)
|
|
853
|
+
out.push(` ! ${breaking.length} breaking change(s) without a major version bump`);
|
|
854
|
+
for (const c of diff.changes) out.push(` ${c.kind.endsWith("removed") ? "-" : c.kind.endsWith("added") ? "+" : "~"} ${describeChange(c)}`);
|
|
855
|
+
} else {
|
|
856
|
+
out.push(`contract ${m.version} (no lock yet: first push)`);
|
|
857
|
+
}
|
|
858
|
+
if (opts.artifacts) {
|
|
859
|
+
const list = readJson(join2(root, opts.artifacts));
|
|
860
|
+
const arts = (Array.isArray(list) ? list : list?.artifacts ?? []).filter((a) => a.status === "live" || a.status === "broken");
|
|
861
|
+
let migrated = 0;
|
|
862
|
+
const broken = [];
|
|
863
|
+
for (const a of arts) {
|
|
864
|
+
const next = Object.keys(renames).length ? migrateDraft(a.draft, renames) : a.draft;
|
|
865
|
+
if (next && JSON.stringify(next) !== JSON.stringify(a.draft)) migrated++;
|
|
866
|
+
const v = validateDraft(next ?? a.draft, m, { role: opts.role ?? "member" });
|
|
867
|
+
if (!v.ok) broken.push({ a, why: v.problems[0]?.message ?? "invalid" });
|
|
868
|
+
}
|
|
869
|
+
out.push(`artifacts ${arts.length} checked${migrated ? `, ${migrated} auto-migrated (renamedFrom)` : ""}${broken.length ? `, ${broken.length} will break` : ", none break"}`);
|
|
870
|
+
for (const { a, why } of broken.slice(0, 20))
|
|
871
|
+
out.push(` ${a.id} "${localize(a.draft.body.title, m.defaultLocale, m.defaultLocale)}" (${a.visibility}, owner ${a.ownerName ?? a.owner}): ${why}`);
|
|
872
|
+
if (broken.length && !opts.acceptBreaking) errors.push(`${broken.length} artifact(s) would break. Add renamedFrom, keep the field, or pass --accept-breaking`);
|
|
873
|
+
}
|
|
874
|
+
const items = await buildReview(m, { fixtures: l.fixtures, introspected: readIntrospected(root) ?? void 0 });
|
|
875
|
+
const intentItems = items.filter((i) => i.section === "INTENTS");
|
|
876
|
+
const loose = intentItems.filter((i) => i.note?.startsWith("unbounded"));
|
|
877
|
+
const unconfirmed = intentItems.filter((i) => i.level === "blocking");
|
|
878
|
+
const silent = intentItems.filter((i) => i.note === "writes without telling the user");
|
|
879
|
+
out.push(
|
|
880
|
+
`intents ${loose.length ? `\u26A0 ${loose.map((i) => `${i.text.trim().split(/\s+/)[0]} ${i.note}`).join("; ")}` : "\u2713 all args bounded"} ${unconfirmed.length ? `\u2717 ${unconfirmed.map((i) => `${i.text.trim().split(/\s+/)[0]}: ${i.note}`).join("; ")}` : "\u2713 money and destructive intents use confirm"}${silent.length ? ` \u26A0 silent: ${silent.map((i) => i.text.trim().split(/\s+/)[0]).join(", ")}` : ""}`
|
|
881
|
+
);
|
|
882
|
+
for (const u of unconfirmed) errors.push(`${u.text.trim().split(/\s+/)[0]} ${u.note}`);
|
|
883
|
+
const derived = await runDerivedChecks(l.fixtures);
|
|
884
|
+
const dq = lock?.quality != null ? ` (${quality.score - lock.quality >= 0 ? "+" : ""}${quality.score - lock.quality})` : "";
|
|
885
|
+
const dtext = derived.map(
|
|
886
|
+
(c) => c.ok ? `\u2713 derived '${c.resource}' ${c.label} matches (\u03A3 ${c.actual.toLocaleString("en-US", { minimumFractionDigits: 2 })})` : `\u2717 derived '${c.resource}' ${c.label}: \u03A3 ${c.actual} \u2260 host ${c.expected}`
|
|
887
|
+
);
|
|
888
|
+
const noFixture = Object.entries(m.resources).filter(([r, d]) => d.derived && !derived.some((c) => c.resource === r)).map(([r]) => `\u26A0 derived '${r}' has no fixture check`);
|
|
889
|
+
out.push(`quality ${quality.score}/100${dq} ${[...dtext, ...noFixture].join(" ")}`.trimEnd());
|
|
890
|
+
for (const c of derived.filter((x) => !x.ok)) errors.push(`derived '${c.resource}' ${c.label} does not match the host screen`);
|
|
891
|
+
const signed = readReview(root);
|
|
892
|
+
if (!signed || signed.contractHash !== l.hash)
|
|
893
|
+
errors.push(`review sheet not signed for this contract (run \`${PRODUCT4.cli} review\`, then \`${PRODUCT4.cli} review --sign <you>\`)`);
|
|
894
|
+
else {
|
|
895
|
+
const open = unacknowledged(items, signed);
|
|
896
|
+
out.push(`review \u2713 signed by ${signed.signer}${open.length ? ` \u26A0 ${open.length} new risky item(s) since signing` : ""}`);
|
|
897
|
+
if (open.length) errors.push("new risky items since the review was signed; review and sign again");
|
|
898
|
+
}
|
|
899
|
+
if (opts.writeLock && !errors.length) writeLock(root, { version: m.version, hash: l.hash, manifest: m, quality: quality.score });
|
|
900
|
+
if (errors.length) {
|
|
901
|
+
out.push(`exit 1: ${errors[0]}`);
|
|
902
|
+
for (const e of errors.slice(1)) out.push(` ${e}`);
|
|
903
|
+
return fail(out);
|
|
904
|
+
}
|
|
905
|
+
out.push("\u2713 ok");
|
|
906
|
+
return ok(out);
|
|
907
|
+
}
|
|
908
|
+
function semverMajor(v) {
|
|
909
|
+
return Number(v.split(".")[0]) || 0;
|
|
910
|
+
}
|
|
911
|
+
async function push(root, opts = {}) {
|
|
912
|
+
const l = await loadConfig(root, opts.config);
|
|
913
|
+
const r = readReview(root);
|
|
914
|
+
if (!r) return fail([`\u2717 ${PRODUCT4.reviewFile} not found. Run \`${PRODUCT4.cli} review\` and sign it; push refuses an unsigned contract (\xA77.7).`]);
|
|
915
|
+
if (r.contractHash !== l.hash) return fail([`\u2717 the review was signed for a different contract (${r.version}, ${r.contractHash.slice(0, 12)}\u2026). Review and sign again.`]);
|
|
916
|
+
const blocking = (await buildReview(l.manifest, { fixtures: l.fixtures })).filter((i) => i.level === "blocking");
|
|
917
|
+
if (blocking.length) return fail(blocking.map((b) => `\u2717 ${b.text.trim()} ${b.note}`));
|
|
918
|
+
const body = { manifest: l.manifest, review: { contractHash: r.contractHash, signer: r.signer, signedAt: r.signedAt } };
|
|
919
|
+
const url = (opts.url ?? process.env[ENV.conductorUrl] ?? PRODUCT4.conductorUrl).replace(/\/$/, "");
|
|
920
|
+
if (opts.dryRun) return ok([`would push ${l.manifest.app}@${l.manifest.version} (${JSON.stringify(body).length} bytes, names and schemas only) to ${url}`]);
|
|
921
|
+
const secret = opts.secret ?? process.env[ENV.secretKey];
|
|
922
|
+
if (!secret) return fail([`\u2717 ${ENV.secretKey} is not set`]);
|
|
923
|
+
const f = opts.fetch ?? fetch;
|
|
924
|
+
const res = await f(`${url}/v1/apps/${encodeURIComponent(l.manifest.app)}/contracts`, {
|
|
925
|
+
method: "POST",
|
|
926
|
+
headers: { authorization: `Bearer ${secret}`, "content-type": "application/json" },
|
|
927
|
+
body: JSON.stringify(body)
|
|
928
|
+
});
|
|
929
|
+
if (!res.ok) return fail([`\u2717 conductor returned ${res.status}: ${await res.text()}`]);
|
|
930
|
+
writeLock(root, { version: l.manifest.version, hash: l.hash, manifest: l.manifest, quality: contractQuality(l.manifest).score, pushedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
931
|
+
return ok([`\u2713 Pushed ${l.manifest.app}@${l.manifest.version} (signed by ${r.signer})`, `\u2713 Wrote ${PRODUCT4.lockFile}`]);
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
// src/bin.ts
|
|
935
|
+
var USAGE = `${PRODUCT5.cli} <command> [options]
|
|
936
|
+
|
|
937
|
+
init [--agent] [--dry-run] scaffold config, token route, env keys, artifacts table
|
|
938
|
+
introspect --from supabase [--out f] draft the contract from supabase/migrations/*.sql
|
|
939
|
+
review [--sign "<name>"] [--json] print the review sheet; sign it to unblock push
|
|
940
|
+
check [--artifacts f.json] [--accept-breaking] [--write-lock]
|
|
941
|
+
CI gate: contract diff, breaking artifacts, intents, derived totals
|
|
942
|
+
push [--url u] [--dry-run] publish names and schemas (requires a signed review)
|
|
943
|
+
|
|
944
|
+
--cwd <dir> run against another directory
|
|
945
|
+
--config <file> path to ${PRODUCT5.configFile}`;
|
|
946
|
+
function parse(argv) {
|
|
947
|
+
const [cmd, ...rest] = argv;
|
|
948
|
+
const flags = {};
|
|
949
|
+
for (let i = 0; i < rest.length; i++) {
|
|
950
|
+
const a = rest[i];
|
|
951
|
+
if (!a.startsWith("--")) continue;
|
|
952
|
+
const k = a.slice(2);
|
|
953
|
+
const v = rest[i + 1];
|
|
954
|
+
if (v !== void 0 && !v.startsWith("--")) {
|
|
955
|
+
flags[k] = v;
|
|
956
|
+
i++;
|
|
957
|
+
} else flags[k] = true;
|
|
958
|
+
}
|
|
959
|
+
return { cmd, flags };
|
|
960
|
+
}
|
|
961
|
+
async function main() {
|
|
962
|
+
const { cmd, flags } = parse(process.argv.slice(2));
|
|
963
|
+
const root = resolve2(typeof flags.cwd === "string" ? flags.cwd : process.cwd());
|
|
964
|
+
const s = (k) => typeof flags[k] === "string" ? flags[k] : void 0;
|
|
965
|
+
const config = s("config");
|
|
966
|
+
let r;
|
|
967
|
+
switch (cmd) {
|
|
968
|
+
case "init":
|
|
969
|
+
r = init(root, { agent: !!flags.agent, dryRun: !!flags["dry-run"] });
|
|
970
|
+
break;
|
|
971
|
+
case "introspect":
|
|
972
|
+
r = introspect(root, { from: s("from") ?? "supabase", out: s("out"), dryRun: !!flags["dry-run"], force: !!flags.force });
|
|
973
|
+
break;
|
|
974
|
+
case "review":
|
|
975
|
+
r = await review(root, { sign: s("sign") ?? (flags.sign === true ? "" : void 0), config, json: !!flags.json });
|
|
976
|
+
break;
|
|
977
|
+
case "check":
|
|
978
|
+
r = await check(root, { config, artifacts: s("artifacts"), acceptBreaking: !!flags["accept-breaking"], writeLock: !!flags["write-lock"], role: s("role") });
|
|
979
|
+
break;
|
|
980
|
+
case "push":
|
|
981
|
+
r = await push(root, { config, url: s("url"), dryRun: !!flags["dry-run"] });
|
|
982
|
+
break;
|
|
983
|
+
default:
|
|
984
|
+
console.log(USAGE);
|
|
985
|
+
return cmd && cmd !== "help" && cmd !== "--help" ? 1 : 0;
|
|
986
|
+
}
|
|
987
|
+
for (const line of r.out) (r.code ? console.error : console.log)(line);
|
|
988
|
+
return r.code;
|
|
989
|
+
}
|
|
990
|
+
main().then(
|
|
991
|
+
(c) => process.exit(c),
|
|
992
|
+
(e) => {
|
|
993
|
+
console.error(`\u2717 ${e instanceof Error ? e.message : String(e)}`);
|
|
994
|
+
process.exit(1);
|
|
995
|
+
}
|
|
996
|
+
);
|
|
997
|
+
//# sourceMappingURL=bin.js.map
|