@marktiderman/genesis-cli 1.0.3 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,7 +1,718 @@
1
1
  #!/usr/bin/env node
2
+ import { createRequire } from 'module';
3
+ import { studioSetupSql } from '@marktiderman/genesis-studio-server';
2
4
  import { Command } from 'commander';
3
5
  import * as fs from 'fs/promises';
4
- import 'path';
6
+ import * as path from 'path';
7
+
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __esm = (fn, res) => function __init() {
11
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
+ };
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+
18
+ // src/introspect/comments.ts
19
+ function parse(comment, keys, where) {
20
+ if (!comment) return {};
21
+ const at = comment.indexOf(MARKER);
22
+ if (at < 0) return { description: comment.trim() || void 0 };
23
+ const description = comment.slice(0, at).trim() || void 0;
24
+ const raw = comment.slice(at + MARKER.length).trim();
25
+ let value;
26
+ try {
27
+ value = JSON.parse(raw);
28
+ } catch {
29
+ throw new CommentSettingsError(`${where}: the text after ${MARKER} must be one JSON object.`);
30
+ }
31
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
32
+ throw new CommentSettingsError(`${where}: the text after ${MARKER} must be one JSON object.`);
33
+ }
34
+ const settings = {};
35
+ for (const [key, v] of Object.entries(value)) {
36
+ if (!keys.includes(key)) {
37
+ throw new CommentSettingsError(`${where}: unknown ${MARKER} setting "${key}". Allowed: ${keys.join(", ")}.`);
38
+ }
39
+ if (typeof v !== "string") throw new CommentSettingsError(`${where}: ${MARKER} "${key}" must be a string.`);
40
+ settings[key] = v;
41
+ }
42
+ return { ...description ? { description } : {}, ...Object.keys(settings).length ? { settings } : {} };
43
+ }
44
+ function parseTableComment(comment, table) {
45
+ return parse(comment, TABLE_KEYS, table);
46
+ }
47
+ function parseColumnComment(comment, column) {
48
+ return parse(comment, FIELD_KEYS, column);
49
+ }
50
+ var MARKER, TABLE_KEYS, FIELD_KEYS, CommentSettingsError;
51
+ var init_comments = __esm({
52
+ "src/introspect/comments.ts"() {
53
+ MARKER = "@genesis";
54
+ TABLE_KEYS = ["label", "labelField", "description"];
55
+ FIELD_KEYS = ["label", "description", "widget"];
56
+ CommentSettingsError = class extends Error {
57
+ };
58
+ }
59
+ });
60
+
61
+ // src/introspect/model.ts
62
+ function storageTypeOf(dbType) {
63
+ const t = dbType.toLowerCase().replace(/\[\]$/, "");
64
+ if (/^(smallint|integer|bigint|int2|int4|int8|real|double precision|float4|float8|numeric|decimal|money)\b/.test(t)) {
65
+ return "number";
66
+ }
67
+ if (t === "boolean" || t === "bool") return "boolean";
68
+ if (/^(date|timestamp|timestamptz|time|timetz|interval)\b/.test(t)) return "datetime";
69
+ if (t === "json" || t === "jsonb") return "json";
70
+ return "string";
71
+ }
72
+ var init_model = __esm({
73
+ "src/introspect/model.ts"() {
74
+ }
75
+ });
76
+
77
+ // src/introspect/postgres.ts
78
+ async function introspectPostgres(sql, schemas) {
79
+ const columns = await sql`
80
+ select n.nspname as schema, c.relname as table,
81
+ obj_description(c.oid, 'pg_class') as table_comment,
82
+ a.attname as column,
83
+ format_type(a.atttypid, a.atttypmod) as db_type,
84
+ t.typcategory = 'A' as is_array,
85
+ a.attnotnull as not_null,
86
+ (a.atthasdef or a.attidentity <> '') as has_default,
87
+ (a.attgenerated <> '' or a.attidentity <> '') as generated,
88
+ (select array_agg(e.enumlabel::text order by e.enumsortorder)
89
+ from pg_enum e
90
+ where e.enumtypid = case when t.typcategory = 'A' then t.typelem else t.oid end) as enum_values,
91
+ col_description(c.oid, a.attnum) as column_comment
92
+ from pg_class c
93
+ join pg_namespace n on n.oid = c.relnamespace
94
+ join pg_attribute a on a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped
95
+ join pg_type t on t.oid = a.atttypid
96
+ where c.relkind in ('r', 'p', 'v', 'm', 'f')
97
+ and n.nspname = any(${schemas})
98
+ order by n.nspname, c.relname, a.attnum`;
99
+ const keys = await sql`
100
+ select n.nspname as schema, c.relname as table,
101
+ array_agg(a.attname::text order by k.ord) as columns
102
+ from pg_constraint con
103
+ join pg_class c on c.oid = con.conrelid
104
+ join pg_namespace n on n.oid = c.relnamespace
105
+ cross join lateral unnest(con.conkey) with ordinality as k(attnum, ord)
106
+ join pg_attribute a on a.attrelid = c.oid and a.attnum = k.attnum
107
+ where con.contype = 'p' and n.nspname = any(${schemas})
108
+ group by n.nspname, c.relname`;
109
+ const links = await sql`
110
+ select n.nspname as schema, c.relname as table, a.attname as column,
111
+ rn.nspname as ref_schema, rc.relname as ref_table, ra.attname as ref_column
112
+ from pg_constraint con
113
+ join pg_class c on c.oid = con.conrelid
114
+ join pg_namespace n on n.oid = c.relnamespace
115
+ join pg_attribute a on a.attrelid = c.oid and a.attnum = con.conkey[1]
116
+ join pg_class rc on rc.oid = con.confrelid
117
+ join pg_namespace rn on rn.oid = rc.relnamespace
118
+ join pg_attribute ra on ra.attrelid = rc.oid and ra.attnum = con.confkey[1]
119
+ where con.contype = 'f' and array_length(con.conkey, 1) = 1
120
+ and n.nspname = any(${schemas})`;
121
+ const keyOf = new Map(keys.map((k) => [`${k.schema}.${k.table}`, k.columns]));
122
+ const linkOf = new Map(links.map((l) => [`${l.schema}.${l.table}.${l.column}`, l]));
123
+ const tables = /* @__PURE__ */ new Map();
124
+ for (const row of columns) {
125
+ const name = `${row.schema}.${row.table}`;
126
+ let table = tables.get(name);
127
+ if (!table) {
128
+ const comment2 = parseTableComment(row.table_comment, name);
129
+ table = {
130
+ name,
131
+ schema: row.schema,
132
+ table: row.table,
133
+ key: keyOf.get(name) ?? [],
134
+ columns: [],
135
+ ...comment2.description ? { description: comment2.description } : {},
136
+ ...comment2.settings ? { settings: comment2.settings } : {}
137
+ };
138
+ tables.set(name, table);
139
+ }
140
+ const comment = parseColumnComment(row.column_comment, `${name}.${row.column}`);
141
+ const link = linkOf.get(`${name}.${row.column}`);
142
+ table.columns.push({
143
+ name: row.column,
144
+ dbType: row.db_type,
145
+ type: storageTypeOf(row.db_type),
146
+ array: row.is_array,
147
+ nullable: !row.not_null,
148
+ hasDefault: row.has_default,
149
+ generated: row.generated,
150
+ ...row.enum_values ? { enumValues: row.enum_values } : {},
151
+ ...link ? { references: { resource: `${link.ref_schema}.${link.ref_table}`, field: link.ref_column } } : {},
152
+ ...comment.description ? { description: comment.description } : {},
153
+ ...comment.settings ? { settings: comment.settings } : {}
154
+ });
155
+ }
156
+ return [...tables.values()];
157
+ }
158
+ var init_postgres = __esm({
159
+ "src/introspect/postgres.ts"() {
160
+ init_comments();
161
+ init_model();
162
+ }
163
+ });
164
+
165
+ // src/introspect/openapi.ts
166
+ function clean(description) {
167
+ if (!description) return void 0;
168
+ return description.replace(NOTES, "").trim() || void 0;
169
+ }
170
+ function introspectOpenApi(doc, schema = "public") {
171
+ const definitions = doc.definitions ?? doc.components?.schemas;
172
+ if (!definitions) throw new Error("This OpenAPI document has no definitions. Is it a PostgREST (Supabase /rest/v1/) spec?");
173
+ return Object.keys(definitions).sort().map((tableName) => {
174
+ const def = definitions[tableName];
175
+ const name = `${schema}.${tableName}`;
176
+ const required = new Set(def.required ?? []);
177
+ const key = [];
178
+ const columns = Object.entries(def.properties ?? {}).map(([column, prop]) => {
179
+ if (PK.test(prop.description ?? "")) key.push(column);
180
+ const fk = FK.exec(prop.description ?? "");
181
+ const isArray = prop.type === "array";
182
+ const format = (isArray ? prop.items?.format : prop.format) ?? prop.type ?? "text";
183
+ const dbType = isArray ? `${format}[]` : format;
184
+ const comment2 = parseColumnComment(clean(prop.description), `${name}.${column}`);
185
+ return {
186
+ name: column,
187
+ dbType,
188
+ type: storageTypeOf(format),
189
+ array: isArray,
190
+ // PostgREST lists NOT NULL columns without a default as required;
191
+ // the rest may be null or are filled by the database.
192
+ nullable: !required.has(column),
193
+ hasDefault: prop.default !== void 0,
194
+ generated: false,
195
+ ...prop.enum ? { enumValues: prop.enum.map(String) } : {},
196
+ ...fk ? { references: { resource: `${schema}.${fk[1]}`, field: fk[2] } } : {},
197
+ ...comment2.description ? { description: comment2.description } : {},
198
+ ...comment2.settings ? { settings: comment2.settings } : {}
199
+ };
200
+ });
201
+ const comment = parseTableComment(def.description, name);
202
+ return {
203
+ name,
204
+ schema,
205
+ table: tableName,
206
+ key,
207
+ columns,
208
+ ...comment.description ? { description: comment.description } : {},
209
+ ...comment.settings ? { settings: comment.settings } : {}
210
+ };
211
+ });
212
+ }
213
+ var PK, FK, NOTES;
214
+ var init_openapi = __esm({
215
+ "src/introspect/openapi.ts"() {
216
+ init_comments();
217
+ init_model();
218
+ PK = /<pk\/>/;
219
+ FK = /<fk table='([^']+)' column='([^']+)'\/>/;
220
+ NOTES = /\s*Note:\s*This is a (?:Primary|Foreign) Key[^<]*<(?:pk|fk)[^>]*\/>/g;
221
+ }
222
+ });
223
+
224
+ // src/introspect/emit.ts
225
+ function quote(value) {
226
+ return JSON.stringify(value);
227
+ }
228
+ function propKey(name) {
229
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : quote(name);
230
+ }
231
+ function typeName(table) {
232
+ const pascal = `${table.schema}_${table.table}`.split(/[^A-Za-z0-9]+/).filter(Boolean).map((p) => p[0].toUpperCase() + p.slice(1)).join("");
233
+ return `${/^[0-9]/.test(pascal) ? "T" : ""}${pascal}Row`;
234
+ }
235
+ function tsType(column) {
236
+ const base = column.enumValues?.length ? column.enumValues.map(quote).join(" | ") : TS_TYPE[column.type];
237
+ const element = column.array ? base.includes("|") ? `(${base})[]` : `${base}[]` : base;
238
+ return column.nullable ? `${element} | null` : element;
239
+ }
240
+ function field(column) {
241
+ const parts = [`name: ${quote(column.name)}`, `type: ${quote(column.type)}`, `dbType: ${quote(column.dbType)}`];
242
+ if (column.array) parts.push("array: true");
243
+ if (column.nullable) parts.push("nullable: true");
244
+ if (column.nullable || column.hasDefault || column.generated) parts.push("optional: true");
245
+ if (column.hasDefault) parts.push("hasDefault: true");
246
+ if (column.generated) parts.push("generated: true");
247
+ if (column.enumValues) parts.push(`enumValues: [${column.enumValues.map(quote).join(", ")}]`);
248
+ if (column.references) {
249
+ parts.push(`references: { resource: ${quote(column.references.resource)}, field: ${quote(column.references.field)} }`);
250
+ }
251
+ const label = column.settings?.label;
252
+ const description = column.settings?.description ?? column.description;
253
+ if (label) parts.push(`label: ${quote(label)}`);
254
+ if (description) parts.push(`description: ${quote(description)}`);
255
+ if (column.settings?.widget) parts.push(`widget: ${quote(column.settings.widget)}`);
256
+ return ` { ${parts.join(", ")} },`;
257
+ }
258
+ function emitContracts(tables, options) {
259
+ const sorted = [...tables].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
260
+ const out = [
261
+ "// Generated by `genesis introspect` \u2014 do not edit by hand.",
262
+ `// Source: ${options.source}`,
263
+ "//",
264
+ "// Re-run `genesis introspect` after a schema change and review the diff.",
265
+ "// Labels, widgets and descriptions come from `@genesis {...}` settings in",
266
+ "// table and column comments. Pass `contracts` to createStudioHandler: it",
267
+ "// wins over discovery for presentation, while types, keys and every",
268
+ "// permission still come from the live database.",
269
+ "",
270
+ "export const contracts = {"
271
+ ];
272
+ for (const table of sorted) {
273
+ out.push(` ${quote(table.name)}: {`);
274
+ out.push(` name: ${quote(table.name)},`);
275
+ out.push(` key: ${table.key.length === 1 ? quote(table.key[0]) : `[${table.key.map(quote).join(", ")}]`},`);
276
+ if (table.settings?.label) out.push(` label: ${quote(table.settings.label)},`);
277
+ if (table.settings?.labelField) out.push(` labelField: ${quote(table.settings.labelField)},`);
278
+ const description = table.settings?.description ?? table.description;
279
+ if (description) out.push(` description: ${quote(description)},`);
280
+ out.push(" fields: [");
281
+ for (const column of table.columns) out.push(field(column));
282
+ out.push(" ],");
283
+ out.push(" },");
284
+ }
285
+ out.push("} as const;", "");
286
+ out.push("/** Every resource in this contract, `schema.table`. */");
287
+ out.push("export type GenesisResource = keyof typeof contracts;", "");
288
+ for (const table of sorted) {
289
+ out.push(`/** A row of \`${table.name}\`, as the studio handler returns it. */`);
290
+ out.push(`export interface ${typeName(table)} {`);
291
+ for (const column of table.columns) out.push(` ${propKey(column.name)}: ${tsType(column)};`);
292
+ out.push("}", "");
293
+ }
294
+ out.push("/** Row types by resource. */");
295
+ out.push("export interface GenesisRows {");
296
+ for (const table of sorted) out.push(` ${quote(table.name)}: ${typeName(table)};`);
297
+ out.push("}", "");
298
+ return out.join("\n");
299
+ }
300
+ var TS_TYPE;
301
+ var init_emit = __esm({
302
+ "src/introspect/emit.ts"() {
303
+ TS_TYPE = {
304
+ string: "string",
305
+ number: "number",
306
+ boolean: "boolean",
307
+ // The studio handler sends dates and timestamps as Postgres text, exactly.
308
+ datetime: "string",
309
+ json: "unknown"
310
+ };
311
+ }
312
+ });
313
+
314
+ // src/introspect/index.ts
315
+ var introspect_exports = {};
316
+ __export(introspect_exports, {
317
+ CommentSettingsError: () => CommentSettingsError,
318
+ emitContracts: () => emitContracts,
319
+ introspectOpenApi: () => introspectOpenApi,
320
+ introspectPostgres: () => introspectPostgres,
321
+ parseColumnComment: () => parseColumnComment,
322
+ parseTableComment: () => parseTableComment
323
+ });
324
+ var init_introspect = __esm({
325
+ "src/introspect/index.ts"() {
326
+ init_postgres();
327
+ init_openapi();
328
+ init_emit();
329
+ init_comments();
330
+ }
331
+ });
332
+
333
+ // src/studio/wire-route.ts
334
+ function routeTags(source) {
335
+ const tags = [];
336
+ const stack = [];
337
+ const re = /<Route\b|<\/Route>/g;
338
+ let m;
339
+ while (m = re.exec(source)) {
340
+ if (m[0] === "</Route>") {
341
+ const open = stack.pop();
342
+ if (open) open.close = m.index;
343
+ continue;
344
+ }
345
+ let i = m.index + "<Route".length;
346
+ let depth = 0;
347
+ let quote2 = null;
348
+ for (; i < source.length; i++) {
349
+ const ch = source[i];
350
+ if (quote2) {
351
+ if (ch === quote2 && source[i - 1] !== "\\") quote2 = null;
352
+ continue;
353
+ }
354
+ if (ch === '"' || ch === "'" || ch === "`") quote2 = ch;
355
+ else if (ch === "{") depth++;
356
+ else if (ch === "}") depth--;
357
+ else if (depth === 0 && ch === ">") break;
358
+ }
359
+ const selfClosing = source[i - 1] === "/";
360
+ const tag = { start: m.index, openEnd: i + 1, selfClosing, text: source.slice(m.index, i + 1) };
361
+ tags.push(tag);
362
+ if (!selfClosing) stack.push(tag);
363
+ re.lastIndex = i + 1;
364
+ }
365
+ return tags;
366
+ }
367
+ function wireStudioRoute(source, route, pageImportPath) {
368
+ const tags = routeTags(source);
369
+ const relative = route.replace(/^\//, "");
370
+ const existing = tags.find((t) => new RegExp(`path=["'](/?${relative.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
371
+ if (existing) {
372
+ return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
373
+ }
374
+ const layouts = tags.filter((t) => !t.selfClosing && t.close !== void 0 && /Layout|Shell/.test(t.text));
375
+ const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
376
+ if (roots.length !== 1) {
377
+ return {
378
+ skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
379
+ };
380
+ }
381
+ const layout = roots[0];
382
+ const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
383
+ if (base && !relative.startsWith(`${base}/`)) {
384
+ return {
385
+ skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
386
+ };
387
+ }
388
+ const childPath = base ? relative.slice(base.length + 1) : relative;
389
+ const guard = GUARD.exec(source)?.[1];
390
+ const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
391
+ const before = source.slice(0, layout.close);
392
+ const lastLine = before.slice(before.lastIndexOf("\n", before.lastIndexOf("<Route")) + 1);
393
+ const indent = /^\s*/.exec(lastLine)?.[0] ?? " ";
394
+ const closeLineStart = source.lastIndexOf("\n", layout.close) + 1;
395
+ const routeLine = `${indent}<Route path="${childPath}" element={${element}} />
396
+ `;
397
+ let next = source.slice(0, closeLineStart) + routeLine + source.slice(closeLineStart);
398
+ const lazy = /const \w+ = lazy\(\(\) => import\(["'][^"']+["']\)\);?\n/g;
399
+ let lastLazy = null;
400
+ let mm;
401
+ while (mm = lazy.exec(next)) lastLazy = mm;
402
+ if (lastLazy) {
403
+ const at = lastLazy.index + lastLazy[0].length;
404
+ next = `${next.slice(0, at)}const DataStudioPage = lazy(() => import("${pageImportPath}"));
405
+ ${next.slice(at)}`;
406
+ } else {
407
+ const imports = /^import .*;\s*$/gm;
408
+ let lastImport = null;
409
+ while (mm = imports.exec(next)) lastImport = mm;
410
+ const at = lastImport ? lastImport.index + lastImport[0].length + 1 : 0;
411
+ next = `${next.slice(0, at)}import DataStudioPage from "${pageImportPath}";
412
+ ${next.slice(at)}`;
413
+ }
414
+ return { content: next, ...guard ? { guard } : {} };
415
+ }
416
+ var GUARD;
417
+ var init_wire_route = __esm({
418
+ "src/studio/wire-route.ts"() {
419
+ GUARD = /<((?:[A-Z]\w*)?(?:Admin|Staff)\w*(?:Guard|Route|Only)|RequireAdmin|RequireStaff)>/;
420
+ }
421
+ });
422
+
423
+ // src/studio/init.ts
424
+ var init_exports = {};
425
+ __export(init_exports, {
426
+ detectHost: () => detectHost,
427
+ planStudioInit: () => planStudioInit
428
+ });
429
+ function has(facts, name) {
430
+ return Boolean(facts.packageJson.dependencies?.[name] ?? facts.packageJson.devDependencies?.[name]);
431
+ }
432
+ function detectHost(facts) {
433
+ if (has(facts, "next") && (facts.exists("app") || facts.exists("src/app"))) return "next";
434
+ if (has(facts, "@tanstack/react-start") && facts.exists("src/routes")) return "tanstack-start";
435
+ return "supabase-function";
436
+ }
437
+ function planStudioInit(facts, options = {}) {
438
+ const host = options.host ?? detectHost(facts);
439
+ const route = (options.route ?? "/admin/data").replace(/\/+$/, "") || "/admin/data";
440
+ const role = options.loginRole ?? "genesis_studio_login";
441
+ if (!ROLE.test(role)) throw new Error(`"${role}" isn't a plain Postgres role name.`);
442
+ if (!/^\/[A-Za-z0-9/_-]*$/.test(route)) throw new Error(`"${route}" isn't a simple path like /admin/data.`);
443
+ const files = [];
444
+ const steps = [];
445
+ const supabaseDir = facts.exists("supabase");
446
+ const migrationPath = supabaseDir ? `supabase/migrations/${facts.timestamp}_genesis_studio.sql` : "genesis-studio.sql";
447
+ files.push({
448
+ path: migrationPath,
449
+ content: [
450
+ "-- Genesis Data Studio: its own database login, and the audit trail every edit is written to.",
451
+ "-- Generated by `genesis studio init`. Review it, then apply it like any migration. Safe to run again.",
452
+ "--",
453
+ `-- ${role} can do nothing on its own (NOINHERIT): the studio switches it to the signed-in user's`,
454
+ "-- role for each request, so row-level security applies to everything it shows or saves.",
455
+ "-- Its password is set outside this file (see the steps `genesis studio init` printed).",
456
+ "",
457
+ "do $$",
458
+ "begin",
459
+ ` if not exists (select 1 from pg_roles where rolname = '${role}') then`,
460
+ ` create role ${role} login noinherit;`,
461
+ " end if;",
462
+ "end $$;",
463
+ `grant authenticated to ${role};`,
464
+ "",
465
+ studioSetupSql({ loginRole: role })
466
+ ].join("\n")
467
+ });
468
+ const install = [...PACKAGES];
469
+ const pagePath = route.replace(/^\//, "");
470
+ if (host === "next") {
471
+ const base = facts.exists("src/app") ? "src/app" : "app";
472
+ const group = (facts.list?.(base) ?? []).filter((d) => /^\(.+\)$/.test(d) && facts.exists(`${base}/${d}/layout.tsx`));
473
+ const appDir = group.length === 1 ? `${base}/${group[0]}` : base;
474
+ const ssr = has(facts, "@supabase/ssr");
475
+ if (!ssr && !has(facts, "@supabase/supabase-js")) install.push("@supabase/supabase-js");
476
+ files.push({
477
+ path: `${appDir}/api/studio/route.ts`,
478
+ content: `// The Data Studio's server: every table, as the signed-in user. Generated by \`genesis studio init\`.
479
+ import { supabaseStudio } from "@marktiderman/genesis-studio-server";
480
+
481
+ export const runtime = "nodejs";
482
+
483
+ export const POST = supabaseStudio({
484
+ url: process.env["NEXT_PUBLIC_SUPABASE_URL"]!,
485
+ database: process.env["STUDIO_DATABASE_URL"]!,
486
+ // Server-side details of anything that goes wrong; users only see a plain message.
487
+ onError: (error) => console.error("[genesis-studio]", error),
488
+ // Who may open the studio. The default is any signed-in user, who sees exactly what row-level
489
+ // security already lets them see. Narrow it to staff with, e.g.:
490
+ // who: (claims) => (claims.app_metadata as { role?: string } | undefined)?.role === "admin",
491
+ });
492
+ `
493
+ });
494
+ files.push({
495
+ path: `${appDir}/${pagePath}/page.tsx`,
496
+ content: `"use client";
497
+ // The Data Studio page. Generated by \`genesis studio init\`.
498
+ import { useMemo } from "react";
499
+ import { ${ssr ? "createBrowserClient" : "createClient"} } from "${ssr ? "@supabase/ssr" : "@supabase/supabase-js"}";
500
+ import { DataStudio } from "@marktiderman/genesis-studio";
501
+ import { createSupabaseStudioProvider } from "@marktiderman/genesis-studio-server/client";
502
+ import "@marktiderman/genesis-studio/standalone.css";
503
+
504
+ export default function DataStudioPage() {
505
+ const provider = useMemo(() => {
506
+ // Dot access: Next.js inlines a public variable into the browser bundle only for process.env.NAME.
507
+ const supabase = ${ssr ? "createBrowserClient" : "createClient"}(process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!);
508
+ return createSupabaseStudioProvider(supabase, { url: "/api/studio" });
509
+ }, []);
510
+ // "plain": no frame of its own, so it sits under the app's header and nav like its other pages.
511
+ return <DataStudio provider={provider} title="Data" variant="plain" />;
512
+ }
513
+ `
514
+ });
515
+ steps.push(
516
+ `Set the login's password once, in the Supabase SQL editor (never in a migration): alter role ${role} with password '<a long random password>';`,
517
+ `Add STUDIO_DATABASE_URL to .env.local and your host's settings: the session pooler string from Supabase \u2192 Connect, with the user changed to ${role}.<project-ref> and that password.`,
518
+ `Apply ${migrationPath}, then open ${route}.`
519
+ );
520
+ } else if (host === "tanstack-start") {
521
+ planTanstackStart(facts, route, files, steps, role);
522
+ } else {
523
+ const lovable = facts.read(LOVABLE_CLIENT);
524
+ files.push({
525
+ path: "supabase/functions/genesis-studio/index.ts",
526
+ content: `// The Data Studio's server, as a Supabase Edge Function: every table, as the signed-in user.
527
+ // Generated by \`genesis studio init\`. It checks each user's token itself (verify_jwt is off, so the
528
+ // browser's CORS preflight can reach it).
529
+ import { supabaseStudio } from "npm:@marktiderman/genesis-studio-server@${SERVER_VERSION}";
530
+
531
+ const handler = supabaseStudio({
532
+ url: Deno.env.get("SUPABASE_URL")!,
533
+ database: Deno.env.get("STUDIO_DATABASE_URL")!,
534
+ // The app's origins, comma-separated, e.g. "https://app.example.com,http://localhost:8080".
535
+ allowedOrigins: (Deno.env.get("STUDIO_ALLOWED_ORIGINS") ?? "").split(",").map((o) => o.trim()).filter(Boolean),
536
+ // Server-side details of anything that goes wrong (the function's logs); users only see a plain message.
537
+ onError: (error) => console.error("[genesis-studio]", error),
538
+ // Who may open the studio. The default is any signed-in user, who sees exactly what row-level
539
+ // security already lets them see. Narrow it to staff with, e.g.:
540
+ // who: (claims) => (claims.app_metadata as { role?: string } | undefined)?.role === "admin",
541
+ });
542
+
543
+ Deno.serve((request) => handler(request));
544
+ `
545
+ });
546
+ if (facts.exists("supabase/config.toml")) {
547
+ const config = facts.read("supabase/config.toml") ?? "";
548
+ if (!/\[functions\.genesis-studio\]/.test(config)) {
549
+ files.push({ path: "supabase/config.toml", append: true, content: `
550
+ [functions.genesis-studio]
551
+ verify_jwt = false
552
+ ` });
553
+ }
554
+ } else {
555
+ steps.push("Deploy the function with JWT verification off (the studio verifies tokens itself): supabase functions deploy genesis-studio --no-verify-jwt");
556
+ }
557
+ const clientImport = lovable ? `import { supabase } from "@/integrations/supabase/client";` : `import { createClient } from "@supabase/supabase-js";`;
558
+ const clientSetup = lovable ? "" : `const supabase = createClient(import.meta.env.VITE_SUPABASE_URL, import.meta.env.VITE_SUPABASE_ANON_KEY);
559
+ `;
560
+ if (!lovable && !has(facts, "@supabase/supabase-js")) install.push("@supabase/supabase-js");
561
+ const componentDir = facts.exists("src/pages") ? "src/pages" : "src";
562
+ const routerPath = ["src/App.tsx", "src/app.tsx", "src/router.tsx", "src/routes.tsx", "src/main.tsx"].find(
563
+ (p) => /<Routes\b|<Route\b/.test(facts.read(p) ?? "")
564
+ );
565
+ const wired = routerPath ? wireStudioRoute(facts.read(routerPath), route, `./${componentDir.replace(/^src\/?/, "") ? `${componentDir.replace(/^src\//, "")}/` : ""}DataStudioPage`) : { skipped: `Add <Route path="${route}" element={<DataStudioPage />} /> to your router, inside the layout your other pages use.` };
566
+ const inShell = Boolean(wired.content);
567
+ files.push({
568
+ path: `${componentDir}/DataStudioPage.tsx`,
569
+ content: `// The Data Studio page. Generated by \`genesis studio init\`: add it to your router at ${route}.
570
+ import { useMemo } from "react";
571
+ import { DataStudio } from "@marktiderman/genesis-studio";
572
+ import { createSupabaseStudioProvider } from "@marktiderman/genesis-studio-server/client";
573
+ import "@marktiderman/genesis-studio/standalone.css";
574
+ ${clientImport}
575
+
576
+ ${clientSetup}const STUDIO_URL = \`\${import.meta.env.VITE_SUPABASE_URL}/functions/v1/genesis-studio\`;
577
+
578
+ export default function DataStudioPage() {
579
+ const provider = useMemo(() => createSupabaseStudioProvider(supabase, { url: STUDIO_URL }), []);
580
+ return <DataStudio provider={provider} title="Data"${inShell ? ` variant="plain"` : ""} />;
581
+ }
582
+ `
583
+ });
584
+ if (wired.content) {
585
+ files.push({
586
+ path: routerPath,
587
+ content: wired.content,
588
+ edit: `added ${route} inside your app's layout${wired.guard ? `, behind <${wired.guard}>` : ""}`
589
+ });
590
+ } else {
591
+ steps.push(wired.skipped);
592
+ }
593
+ steps.push(
594
+ `Set the login's password once, in the Supabase SQL editor (never in a migration): alter role ${role} with password '<a long random password>';`,
595
+ `Set the function's secrets: supabase secrets set STUDIO_DATABASE_URL='<session pooler string from Supabase \u2192 Connect, user ${role}.<project-ref>>' STUDIO_ALLOWED_ORIGINS='<your app's origins>'`,
596
+ `Apply ${migrationPath}, deploy the function (supabase functions deploy genesis-studio), then open ${route}.`
597
+ );
598
+ }
599
+ return { host, files, install, steps };
600
+ }
601
+ function planTanstackStart(facts, route, files, steps, role) {
602
+ files.push({
603
+ path: "src/routes/api/studio.ts",
604
+ content: `// The Data Studio's server: every table, as the signed-in user. Generated by \`genesis studio init\`.
605
+ import { createFileRoute } from "@tanstack/react-router";
606
+
607
+ // One handler for the server's life. On Cloudflare Workers it opens a database connection per
608
+ // request by itself, since a connection there can't outlive the request that opened it.
609
+ let studio: ((request: Request) => Promise<Response>) | undefined;
610
+
611
+ export const Route = createFileRoute("/api/studio")({
612
+ server: {
613
+ handlers: {
614
+ POST: async ({ request }) => {
615
+ // Loaded here, on the server only, so database code never reaches the browser bundle.
616
+ const { supabaseStudio } = await import("@marktiderman/genesis-studio-server");
617
+ studio ??= supabaseStudio({
618
+ url: process.env["SUPABASE_URL"] ?? process.env["VITE_SUPABASE_URL"]!,
619
+ database: process.env["STUDIO_DATABASE_URL"]!,
620
+ // Server-side details of anything that goes wrong; users only see a plain message.
621
+ onError: (error) => console.error("[genesis-studio]", error),
622
+ // Who may open the studio. The default is any signed-in user, who sees exactly what
623
+ // row-level security already lets them see. Narrow it to staff with, e.g.:
624
+ // who: (claims) => (claims.app_metadata as { role?: string } | undefined)?.role === "admin",
625
+ });
626
+ return studio(request);
627
+ },
628
+ },
629
+ },
630
+ });
631
+ `
632
+ });
633
+ const layouts = (facts.listDeep?.("src/routes") ?? []).filter((p) => p.endsWith("/route.tsx")).map((p) => ({ dir: p.slice(0, -"/route.tsx".length), text: facts.read(p) ?? "" })).filter((r) => /AppShell|Layout|Sidebar/.test(r.text) && !/\$/.test(r.dir));
634
+ const rank = (r) => (/AppShell/.test(r.text) ? 0 : 1) * 1e3 + r.dir.split("/").length;
635
+ const shellDirs = layouts.sort((a, b) => rank(a) - rank(b)).map((r) => r.dir);
636
+ const dir = shellDirs[0] ?? "src/routes";
637
+ const segments = route.replace(/^\//, "").split("/");
638
+ const named = segments.map((segment, i) => {
639
+ const prefix = segments.slice(0, i + 1).join(".");
640
+ const parent = i < segments.length - 1 && (facts.exists(`${dir}/${prefix}.tsx`) || facts.exists(`${dir}/${prefix}/route.tsx`));
641
+ return parent ? `${segment}_` : segment;
642
+ });
643
+ const id = `${dir.replace(/^src\/routes/, "")}/${named.join("/")}`.replace(/\/+/g, "/");
644
+ const file = `${dir}/${named.join(".")}.tsx`;
645
+ const lovable = facts.exists(LOVABLE_CLIENT);
646
+ const tailwind4 = /@import\s+["']tailwindcss/.test(facts.read("src/styles.css") ?? "");
647
+ files.push({
648
+ path: file,
649
+ content: `// The Data Studio page. Generated by \`genesis studio init\`. It sits inside the app's shell, so it
650
+ // gets the app's nav, header and theme.
651
+ import { useMemo } from "react";
652
+ import { createFileRoute } from "@tanstack/react-router";
653
+ import { DataStudio } from "@marktiderman/genesis-studio";
654
+ import { createSupabaseStudioProvider } from "@marktiderman/genesis-studio-server/client";
655
+ ${tailwind4 ? "" : 'import "@marktiderman/genesis-studio/standalone.css";\n'}${lovable ? 'import { supabase } from "@/integrations/supabase/client";' : 'import { createClient } from "@supabase/supabase-js";\n\nconst supabase = createClient(import.meta.env.VITE_SUPABASE_URL, import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY);'}
656
+
657
+ export const Route = createFileRoute("${id}")({
658
+ ssr: false,
659
+ component: DataStudioPage,
660
+ });
661
+
662
+ function DataStudioPage() {
663
+ const provider = useMemo(() => createSupabaseStudioProvider(supabase, { url: "/api/studio" }), []);
664
+ return <DataStudio provider={provider} title="Data" variant="plain" />;
665
+ }
666
+ `
667
+ });
668
+ if (tailwind4) {
669
+ const css = facts.read("src/styles.css");
670
+ if (!css.includes("genesis-studio/dist")) {
671
+ const line = '@source "../node_modules/@marktiderman/genesis-studio/dist";';
672
+ const ui = '@source "../node_modules/@marktiderman/genesis-ui/dist";';
673
+ const at = css.search(/@source[^\n]*genesis-ui[^\n]*\n/);
674
+ const next = at >= 0 ? css.replace(/(@source[^\n]*genesis-ui[^\n]*\n)/, `$1${line}
675
+ `) : css.replace(/(@import\s+["']tailwindcss[^\n]*\n)/, `$1${ui}
676
+ ${line}
677
+ `);
678
+ if (next !== css) {
679
+ files.push({ path: "src/styles.css", content: next, edit: "Tailwind now also scans the studio's classes" });
680
+ } else {
681
+ steps.push(`Add these to the stylesheet that imports Tailwind, so it builds the studio's classes:
682
+ ${ui}
683
+ ${line}`);
684
+ }
685
+ }
686
+ }
687
+ steps.push(
688
+ `Add a link to ${route} in your app's navigation (for staff only, if that's who should see it).`,
689
+ `Set the login's password once, in the Supabase SQL editor (never in a migration): alter role ${role} with password '<a long random password>';`,
690
+ `Add STUDIO_DATABASE_URL to the server's environment: the session pooler string from Supabase \u2192 Connect, with the user changed to ${role}.<project-ref> and that password.`,
691
+ `Apply the migration, then open ${route}.`
692
+ );
693
+ }
694
+ var SERVER_VERSION, PACKAGES, ROLE, LOVABLE_CLIENT;
695
+ var init_init = __esm({
696
+ "src/studio/init.ts"() {
697
+ init_wire_route();
698
+ SERVER_VERSION = createRequire(import.meta.url)("@marktiderman/genesis-studio-server/package.json").version;
699
+ PACKAGES = [
700
+ "@marktiderman/genesis-studio",
701
+ `@marktiderman/genesis-studio-server@${SERVER_VERSION}`,
702
+ "@marktiderman/genesis-ui",
703
+ "@marktiderman/genesis-core",
704
+ // Pinned to the ranges the studio supports: an unpinned "latest" can move
705
+ // past them (@hookform/resolvers 6 is a different major).
706
+ "@tanstack/react-query@^5",
707
+ "@tanstack/react-virtual@^3.14",
708
+ "react-hook-form@^7",
709
+ "zod@^4",
710
+ "@hookform/resolvers@^5.1.0"
711
+ ];
712
+ ROLE = /^[a-z_][a-z0-9_]{0,62}$/;
713
+ LOVABLE_CLIENT = "src/integrations/supabase/client.ts";
714
+ }
715
+ });
5
716
 
6
717
  // src/scaffolder.ts
7
718
  var VALID_NAME_PATTERN = /^[a-z][a-z0-9-]{1,30}$/;
@@ -387,6 +1098,117 @@ program.command("init").description("Scaffold a new Genesis consumer (brand pack
387
1098
  console.log(` 2. pnpm install`);
388
1099
  console.log(` 3. Read docs/prds/PRD-07-genesis-consumption-architecture/standards/usage-doctrine.md`);
389
1100
  });
1101
+ program.command("introspect").description("Write a checked-in contract (resources.genesis.ts) from the Postgres catalog or a PostgREST/Supabase OpenAPI spec").option("--database-env <name>", "Environment variable holding the Postgres URL", "DATABASE_URL").option("--openapi <file-or-url>", "Read a PostgREST OpenAPI document (a Supabase project's /rest/v1/) instead of Postgres").option("--header <header...>", "HTTP header for --openapi URLs, for values that aren't secret (repeatable)").option("--apikey-env <name>", "Environment variable holding the API key for --openapi URLs (sent as apikey and Bearer)").option("-s, --schema <schemas>", "Comma-separated schemas", "public").option("-o, --out <file>", "Where to write the contract", "resources.genesis.ts").option("--check", "Write nothing; exit 1 if the contract on disk is out of date (for CI)", false).action(async (opts) => {
1102
+ const schemas = opts.schema.split(",").map((s) => s.trim()).filter(Boolean);
1103
+ const { introspectOpenApi: introspectOpenApi2, introspectPostgres: introspectPostgres2, emitContracts: emitContracts2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
1104
+ let tables;
1105
+ let source;
1106
+ if (opts.openapi) {
1107
+ if (schemas.length !== 1) throw new Error("--openapi reads one schema at a time; pass a single --schema.");
1108
+ const headers = [...opts.header ?? []];
1109
+ if (opts.apikeyEnv) {
1110
+ const key = process.env[opts.apikeyEnv];
1111
+ if (!key) throw new Error(`Set ${opts.apikeyEnv} to the API key.`);
1112
+ headers.push(`apikey: ${key}`, `Authorization: Bearer ${key}`);
1113
+ }
1114
+ const doc = await readOpenApi(opts.openapi, headers);
1115
+ tables = introspectOpenApi2(doc, schemas[0]);
1116
+ source = `OpenAPI ${redactUrl(opts.openapi)}`;
1117
+ } else {
1118
+ const url = process.env[opts.databaseEnv];
1119
+ if (!url) throw new Error(`Set ${opts.databaseEnv} to the database URL, or pass --openapi.`);
1120
+ const { default: postgres } = await import('postgres');
1121
+ const sql = postgres(url, { max: 1, prepare: false, onnotice: () => {
1122
+ } });
1123
+ try {
1124
+ tables = await introspectPostgres2(sql, schemas);
1125
+ } finally {
1126
+ await sql.end();
1127
+ }
1128
+ source = `Postgres (${schemas.join(", ")})`;
1129
+ }
1130
+ const content = emitContracts2(tables, { source });
1131
+ const target = path.resolve(opts.out);
1132
+ if (opts.check) {
1133
+ const current = await fs.readFile(target, "utf-8").catch(() => null);
1134
+ if (current !== content) {
1135
+ console.error(`\u2717 ${opts.out} is out of date. Run \`genesis introspect\` and commit the result.`);
1136
+ process.exit(1);
1137
+ }
1138
+ console.log(`\u2714 ${opts.out} is up to date (${tables.length} tables).`);
1139
+ return;
1140
+ }
1141
+ await fs.writeFile(target, content, "utf-8");
1142
+ console.log(`\u2714 Wrote ${opts.out}: ${tables.length} tables.`);
1143
+ });
1144
+ var studio = program.command("studio").description("The Genesis Data Studio");
1145
+ studio.command("init").description("Turn the Data Studio on in this app: a server for every table, a page, and one migration to review").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--host <host>", "next, tanstack-start or supabase-function (default: detected)").option("--route <path>", "Where the page lives", "/admin/data").option("--login-role <name>", "The studio's database login", "genesis_studio_login").option("--force", "Overwrite files that already exist", false).action(async (opts) => {
1146
+ const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
1147
+ const root = path.resolve(opts.dir);
1148
+ const packageJson = JSON.parse(await fs.readFile(path.join(root, "package.json"), "utf-8").catch(() => "{}"));
1149
+ const existsSync = (await import('fs')).existsSync;
1150
+ const readSync = (await import('fs')).readFileSync;
1151
+ const readdirSync = (await import('fs')).readdirSync;
1152
+ if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
1153
+ throw new Error("--host must be next, tanstack-start or supabase-function.");
1154
+ }
1155
+ const plan = planStudioInit2(
1156
+ {
1157
+ packageJson,
1158
+ exists: (p) => existsSync(path.join(root, p)),
1159
+ read: (p) => existsSync(path.join(root, p)) ? readSync(path.join(root, p), "utf-8") : null,
1160
+ timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
1161
+ listDeep: (p) => {
1162
+ const out = [];
1163
+ const walk = (rel) => {
1164
+ for (const entry of readdirSync(path.join(root, rel), { withFileTypes: true })) {
1165
+ const child = `${rel}/${entry.name}`;
1166
+ if (entry.isDirectory()) walk(child);
1167
+ else out.push(child);
1168
+ }
1169
+ };
1170
+ try {
1171
+ walk(p);
1172
+ } catch {
1173
+ }
1174
+ return out;
1175
+ },
1176
+ list: (p) => {
1177
+ try {
1178
+ return readdirSync(path.join(root, p));
1179
+ } catch {
1180
+ return [];
1181
+ }
1182
+ }
1183
+ },
1184
+ { host: opts.host, route: opts.route, loginRole: opts.loginRole }
1185
+ );
1186
+ for (const file of plan.files) {
1187
+ const target = path.join(root, file.path);
1188
+ await fs.mkdir(path.dirname(target), { recursive: true });
1189
+ if (file.edit) {
1190
+ await fs.writeFile(target, file.content, "utf-8");
1191
+ console.log(`~ ${file.path} (${file.edit})`);
1192
+ continue;
1193
+ }
1194
+ if (file.append) {
1195
+ await fs.appendFile(target, file.content, "utf-8");
1196
+ console.log(`+ ${file.path} (appended)`);
1197
+ continue;
1198
+ }
1199
+ if (existsSync(target) && !opts.force) {
1200
+ console.log(`= ${file.path} exists; left as it is (--force to replace)`);
1201
+ continue;
1202
+ }
1203
+ await fs.writeFile(target, file.content, "utf-8");
1204
+ console.log(`+ ${file.path}`);
1205
+ }
1206
+ const pm = existsSync(path.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync(path.join(root, "yarn.lock")) ? "yarn add" : existsSync(path.join(root, "bun.lock")) || existsSync(path.join(root, "bun.lockb")) ? "bun add" : "npm install";
1207
+ console.log("");
1208
+ console.log(`\u2714 The Data Studio is set up for ${{ next: "Next.js", "tanstack-start": "TanStack Start", "supabase-function": "a Supabase Edge Function" }[plan.host]}. To finish:`);
1209
+ console.log(` 1. ${pm} ${plan.install.join(" ")}`);
1210
+ plan.steps.forEach((step, i) => console.log(` ${i + 2}. ${step}`));
1211
+ });
390
1212
  program.parseAsync(process.argv).catch((err) => {
391
1213
  const message = err instanceof Error ? err.message : String(err);
392
1214
  console.error(`\u2717 ${message}`);
@@ -415,5 +1237,27 @@ function createNodeFs() {
415
1237
  }
416
1238
  };
417
1239
  }
1240
+ async function readOpenApi(location, headers) {
1241
+ if (/^https?:\/\//.test(location)) {
1242
+ const init = {};
1243
+ for (const h of headers) {
1244
+ const at = h.indexOf(":");
1245
+ if (at < 1) throw new Error(`--header must be "Name: value".`);
1246
+ init[h.slice(0, at).trim()] = h.slice(at + 1).trim();
1247
+ }
1248
+ const response = await fetch(location, { headers: { accept: "application/openapi+json, application/json", ...init } });
1249
+ if (!response.ok) throw new Error(`Fetching the OpenAPI document failed: HTTP ${response.status}.`);
1250
+ return response.json();
1251
+ }
1252
+ return JSON.parse(await fs.readFile(location, "utf-8"));
1253
+ }
1254
+ function redactUrl(location) {
1255
+ try {
1256
+ const url = new URL(location);
1257
+ return `${url.origin}${url.pathname}`;
1258
+ } catch {
1259
+ return path.basename(location);
1260
+ }
1261
+ }
418
1262
  //# sourceMappingURL=cli.js.map
419
1263
  //# sourceMappingURL=cli.js.map