@stardeck-customer-apps/data-store-sdk 0.5.0 → 0.6.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.
@@ -0,0 +1,729 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/cli/generate-types.ts
27
+ var import_fs2 = require("fs");
28
+ var import_path2 = require("path");
29
+ var import_util = require("util");
30
+ var import_serverless = require("@neondatabase/serverless");
31
+
32
+ // src/server/manifest.ts
33
+ var STARDECK_DATA_STORES_ENV = "STARDECK_DATA_STORES";
34
+ function readEnv(key) {
35
+ if (typeof process !== "undefined" && process.env?.[key]) {
36
+ return process.env[key];
37
+ }
38
+ return void 0;
39
+ }
40
+ function dataStoreSlug(name) {
41
+ const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
42
+ return slug || "store";
43
+ }
44
+ function readDataStoreManifest() {
45
+ const raw = readEnv(STARDECK_DATA_STORES_ENV);
46
+ if (!raw) return [];
47
+ try {
48
+ const parsed = JSON.parse(raw);
49
+ if (!Array.isArray(parsed)) return [];
50
+ return parsed.filter((e) => {
51
+ if (typeof e !== "object" || e === null) return false;
52
+ const entry = e;
53
+ if (typeof entry.id !== "string" || typeof entry.name !== "string" || typeof entry.slug !== "string") {
54
+ return false;
55
+ }
56
+ return entry.storeType === "storage" || typeof entry.url === "string";
57
+ });
58
+ } catch {
59
+ return [];
60
+ }
61
+ }
62
+ function resolveDataStore(ref) {
63
+ return resolveManifestEntry(readDataStoreManifest(), ref);
64
+ }
65
+ function resolveManifestEntry(entries, ref) {
66
+ if (ref.storeId) {
67
+ const byId = entries.find((e) => e.id === ref.storeId);
68
+ if (byId) return byId;
69
+ }
70
+ if (ref.storeName) {
71
+ const target = ref.storeName;
72
+ const byBindingKey = entries.find((e) => e.bindingKey === target);
73
+ if (byBindingKey) return byBindingKey;
74
+ const exact = entries.find((e) => e.slug === target || e.id === target || e.name === target);
75
+ if (exact) return exact;
76
+ const norm = dataStoreSlug(target);
77
+ const byBindingKeyNorm = entries.find((e) => e.bindingKey === norm);
78
+ if (byBindingKeyNorm) return byBindingKeyNorm;
79
+ return entries.find(
80
+ (e) => e.slug === norm || typeof e.name === "string" && dataStoreSlug(e.name) === norm
81
+ );
82
+ }
83
+ return void 0;
84
+ }
85
+
86
+ // src/cli/module-type-slices.ts
87
+ var import_fs = require("fs");
88
+ var import_path = require("path");
89
+ function toPascalCase(name) {
90
+ return name.split(/[_-]/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
91
+ }
92
+ function parseModuleManifestSlice(content, sourceLabel, warn) {
93
+ let parsed;
94
+ try {
95
+ parsed = JSON.parse(content);
96
+ } catch {
97
+ warn(`Skipping malformed module manifest at ${sourceLabel}`);
98
+ return null;
99
+ }
100
+ if (typeof parsed !== "object" || parsed === null) {
101
+ warn(`Skipping malformed module manifest at ${sourceLabel}`);
102
+ return null;
103
+ }
104
+ const record = parsed;
105
+ const name = record.name;
106
+ const tables = record.tables;
107
+ if (typeof name !== "string" || name.length === 0) {
108
+ warn(`Skipping module manifest at ${sourceLabel}: missing or invalid "name"`);
109
+ return null;
110
+ }
111
+ if (!Array.isArray(tables) || tables.length === 0) {
112
+ return null;
113
+ }
114
+ const tableNames = [];
115
+ for (const entry of tables) {
116
+ if (typeof entry !== "string" || entry.length === 0) {
117
+ warn(`Skipping module manifest at ${sourceLabel}: invalid "tables" entry`);
118
+ return null;
119
+ }
120
+ tableNames.push(entry);
121
+ }
122
+ return { name, tables: tableNames };
123
+ }
124
+ function discoverModuleManifests(modulesDir, warn) {
125
+ if (!(0, import_fs.existsSync)(modulesDir)) {
126
+ return [];
127
+ }
128
+ let entries;
129
+ try {
130
+ entries = (0, import_fs.readdirSync)(modulesDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
131
+ } catch {
132
+ warn(`Could not read modules directory: ${modulesDir}`);
133
+ return [];
134
+ }
135
+ const manifests = [];
136
+ for (const dirName of entries) {
137
+ const manifestPath = (0, import_path.join)(modulesDir, dirName, "module.json");
138
+ if (!(0, import_fs.existsSync)(manifestPath)) {
139
+ continue;
140
+ }
141
+ let content;
142
+ try {
143
+ content = (0, import_fs.readFileSync)(manifestPath, "utf-8");
144
+ } catch {
145
+ warn(`Skipping unreadable module manifest at ${manifestPath}`);
146
+ continue;
147
+ }
148
+ const slice = parseModuleManifestSlice(content, manifestPath, warn);
149
+ if (slice) {
150
+ manifests.push(slice);
151
+ }
152
+ }
153
+ return manifests.sort((a, b) => a.name.localeCompare(b.name));
154
+ }
155
+ function shouldLoadModuleManifests(noModules) {
156
+ return !noModules;
157
+ }
158
+ function emitModuleDbSlices(schemaTableNames, manifests, warn) {
159
+ const lines = [];
160
+ const moduleMapEntries = [];
161
+ for (const manifest of manifests) {
162
+ const presentTables = manifest.tables.filter((t) => schemaTableNames.has(t));
163
+ const absentTables = manifest.tables.filter((t) => !schemaTableNames.has(t));
164
+ if (absentTables.length > 0) {
165
+ warn(`Module "${manifest.name}": table(s) not in database: ${absentTables.join(", ")}`);
166
+ }
167
+ if (presentTables.length === 0) {
168
+ continue;
169
+ }
170
+ const interfaceName = `${toPascalCase(manifest.name)}ModuleDB`;
171
+ lines.push(`export interface ${interfaceName} {`);
172
+ for (const tableName of presentTables) {
173
+ const tableTypeName = `${toPascalCase(tableName)}Table`;
174
+ lines.push(` ${tableName}: ${tableTypeName};`);
175
+ }
176
+ lines.push("}");
177
+ lines.push("");
178
+ moduleMapEntries.push({ name: manifest.name, interfaceName });
179
+ }
180
+ if (moduleMapEntries.length === 0) {
181
+ return "";
182
+ }
183
+ lines.push("export interface ModuleDBs {");
184
+ for (const { name, interfaceName } of moduleMapEntries) {
185
+ lines.push(` "${name}": ${interfaceName};`);
186
+ }
187
+ lines.push("}");
188
+ lines.push("");
189
+ return lines.join("\n");
190
+ }
191
+
192
+ // src/cli/schema-ddl.ts
193
+ function quoteIdent(name) {
194
+ return `"${name.replace(/"/g, '""')}"`;
195
+ }
196
+ var TRACKED_EXTENSIONS = /* @__PURE__ */ new Set(["pgcrypto", "pg_trgm", "uuid-ossp", "citext"]);
197
+ function resolveSqlType(row) {
198
+ const dataType = row.data_type;
199
+ if (dataType === "ARRAY") {
200
+ return `${row.udt_name.replace(/^_/, "")}[]`;
201
+ }
202
+ if (dataType === "USER-DEFINED") {
203
+ return quoteIdent(row.udt_name);
204
+ }
205
+ if (dataType === "character varying") {
206
+ return row.character_maximum_length ? `varchar(${row.character_maximum_length})` : "varchar";
207
+ }
208
+ if (dataType === "character") {
209
+ return row.character_maximum_length ? `char(${row.character_maximum_length})` : "char";
210
+ }
211
+ if (dataType === "numeric") {
212
+ return row.numeric_precision !== null && row.numeric_scale !== null ? `numeric(${row.numeric_precision},${row.numeric_scale})` : "numeric";
213
+ }
214
+ if (dataType === "timestamp with time zone") return "timestamptz";
215
+ if (dataType === "timestamp without time zone") return "timestamp";
216
+ if (dataType === "time with time zone") return "timetz";
217
+ if (dataType === "time without time zone") return "time";
218
+ return dataType;
219
+ }
220
+ async function introspectSchemaSnapshot(executor) {
221
+ const [extensions, enums, columns, constraints, fks, checks, indexes] = await Promise.all([
222
+ executor.query(`SELECT extname FROM pg_extension ORDER BY extname`),
223
+ executor.query(
224
+ `SELECT t.typname AS name, e.enumlabel AS value
225
+ FROM pg_type t
226
+ JOIN pg_enum e ON e.enumtypid = t.oid
227
+ JOIN pg_namespace n ON n.oid = t.typnamespace
228
+ WHERE n.nspname = 'public'
229
+ ORDER BY t.typname, e.enumsortorder`
230
+ ),
231
+ executor.query(
232
+ `SELECT c.table_name, c.column_name, c.data_type, c.udt_name, c.is_nullable,
233
+ c.column_default, c.character_maximum_length, c.numeric_precision, c.numeric_scale,
234
+ c.is_generated, c.generation_expression
235
+ FROM information_schema.columns c
236
+ JOIN information_schema.tables t
237
+ ON c.table_name = t.table_name AND c.table_schema = t.table_schema
238
+ WHERE c.table_schema = 'public'
239
+ AND t.table_type = 'BASE TABLE'
240
+ AND t.table_name NOT LIKE '\\_deleted\\_%'
241
+ ORDER BY c.table_name, c.ordinal_position`
242
+ ),
243
+ executor.query(
244
+ `SELECT tc.table_name, tc.constraint_name, tc.constraint_type, ku.column_name
245
+ FROM information_schema.table_constraints tc
246
+ JOIN information_schema.key_column_usage ku
247
+ ON tc.constraint_name = ku.constraint_name AND tc.table_schema = ku.table_schema
248
+ WHERE tc.table_schema = 'public'
249
+ AND tc.constraint_type IN ('PRIMARY KEY', 'UNIQUE')
250
+ ORDER BY tc.table_name, tc.constraint_name, ku.ordinal_position`
251
+ ),
252
+ executor.query(
253
+ // Read column pairings from pg_catalog: information_schema's
254
+ // constraint_column_usage is uncorrelated with key_column_usage, so
255
+ // joining them for a composite FK produces a cross product. Unnesting
256
+ // conkey/confkey together WITH ORDINALITY keeps referencing↔referenced
257
+ // columns paired and ordered.
258
+ `SELECT con.conname AS constraint_name,
259
+ rel.relname AS table_name,
260
+ att.attname AS column_name,
261
+ frel.relname AS referenced_table,
262
+ fatt.attname AS referenced_column,
263
+ CASE con.confdeltype WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT'
264
+ WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END AS delete_rule,
265
+ CASE con.confupdtype WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT'
266
+ WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END AS update_rule
267
+ FROM pg_constraint con
268
+ JOIN pg_class rel ON rel.oid = con.conrelid
269
+ JOIN pg_namespace ns ON ns.oid = rel.relnamespace
270
+ JOIN pg_class frel ON frel.oid = con.confrelid
271
+ JOIN LATERAL unnest(con.conkey, con.confkey) WITH ORDINALITY AS cols(conkey, confkey, ord) ON true
272
+ JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attnum = cols.conkey
273
+ JOIN pg_attribute fatt ON fatt.attrelid = con.confrelid AND fatt.attnum = cols.confkey
274
+ WHERE ns.nspname = 'public' AND con.contype = 'f'
275
+ ORDER BY rel.relname, con.conname, cols.ord`
276
+ ),
277
+ executor.query(
278
+ `SELECT rel.relname AS table_name, con.conname AS name,
279
+ pg_get_constraintdef(con.oid) AS definition
280
+ FROM pg_constraint con
281
+ JOIN pg_class rel ON rel.oid = con.conrelid
282
+ JOIN pg_namespace ns ON ns.oid = rel.relnamespace
283
+ WHERE ns.nspname = 'public' AND con.contype = 'c'
284
+ AND rel.relname NOT LIKE '\\_deleted\\_%'
285
+ ORDER BY rel.relname, con.conname`
286
+ ),
287
+ executor.query(
288
+ `SELECT i.indexdef
289
+ FROM pg_indexes i
290
+ WHERE i.schemaname = 'public'
291
+ AND i.tablename NOT LIKE '\\_deleted\\_%'
292
+ AND NOT EXISTS (
293
+ SELECT 1 FROM pg_constraint c
294
+ JOIN pg_class cls ON cls.oid = c.conindid
295
+ WHERE cls.relname = i.indexname
296
+ )
297
+ ORDER BY i.indexname`
298
+ )
299
+ ]);
300
+ const enumMap = /* @__PURE__ */ new Map();
301
+ for (const row of enums.rows) {
302
+ const name = String(row.name);
303
+ if (!enumMap.has(name)) enumMap.set(name, []);
304
+ enumMap.get(name).push(String(row.value));
305
+ }
306
+ const tableMap = /* @__PURE__ */ new Map();
307
+ for (const row of columns.rows) {
308
+ const tableName = String(row.table_name);
309
+ if (!tableMap.has(tableName)) {
310
+ tableMap.set(tableName, { name: tableName, columns: [], primaryKey: [], uniques: [] });
311
+ }
312
+ const defaultExpr = row.column_default === null ? null : String(row.column_default);
313
+ const isSerial = defaultExpr !== null && /^nextval\(/.test(defaultExpr);
314
+ const isGenerated = row.is_generated === "ALWAYS";
315
+ tableMap.get(tableName).columns.push({
316
+ name: String(row.column_name),
317
+ sqlType: resolveSqlType({
318
+ data_type: String(row.data_type),
319
+ udt_name: String(row.udt_name),
320
+ character_maximum_length: row.character_maximum_length,
321
+ numeric_precision: row.numeric_precision,
322
+ numeric_scale: row.numeric_scale
323
+ }),
324
+ nullable: row.is_nullable === "YES",
325
+ defaultExpr: isGenerated ? null : defaultExpr,
326
+ isSerial: !isGenerated && isSerial,
327
+ generatedExpr: isGenerated ? String(row.generation_expression) : null
328
+ });
329
+ }
330
+ const constraintGroups = /* @__PURE__ */ new Map();
331
+ for (const row of constraints.rows) {
332
+ const key = String(row.constraint_name);
333
+ if (!constraintGroups.has(key)) {
334
+ constraintGroups.set(key, {
335
+ table: String(row.table_name),
336
+ type: String(row.constraint_type),
337
+ columns: []
338
+ });
339
+ }
340
+ constraintGroups.get(key).columns.push(String(row.column_name));
341
+ }
342
+ for (const group of constraintGroups.values()) {
343
+ const table = tableMap.get(group.table);
344
+ if (!table) continue;
345
+ if (group.type === "PRIMARY KEY") {
346
+ table.primaryKey = group.columns;
347
+ } else if (group.type === "UNIQUE") {
348
+ table.uniques.push(group.columns);
349
+ }
350
+ }
351
+ const fkGroups = /* @__PURE__ */ new Map();
352
+ for (const row of fks.rows) {
353
+ const key = String(row.constraint_name);
354
+ if (!fkGroups.has(key)) {
355
+ fkGroups.set(key, {
356
+ constraintName: key,
357
+ table: String(row.table_name),
358
+ columns: [],
359
+ referencedTable: String(row.referenced_table),
360
+ referencedColumns: [],
361
+ onDelete: String(row.delete_rule),
362
+ onUpdate: String(row.update_rule)
363
+ });
364
+ }
365
+ const fk = fkGroups.get(key);
366
+ fk.columns.push(String(row.column_name));
367
+ fk.referencedColumns.push(String(row.referenced_column));
368
+ }
369
+ return {
370
+ extensions: extensions.rows.map((r) => String(r.extname)).filter((name) => TRACKED_EXTENSIONS.has(name)),
371
+ enums: Array.from(enumMap, ([name, values]) => ({ name, values })),
372
+ tables: Array.from(tableMap.values()),
373
+ foreignKeys: Array.from(fkGroups.values()),
374
+ checks: checks.rows.map((r) => ({
375
+ table: String(r.table_name),
376
+ name: String(r.name),
377
+ definition: String(r.definition)
378
+ })),
379
+ indexes: indexes.rows.map((r) => ({ definition: String(r.indexdef) }))
380
+ };
381
+ }
382
+ function columnDdl(column, isSinglePk) {
383
+ let sqlType = column.sqlType;
384
+ if (column.isSerial) {
385
+ sqlType = sqlType === "bigint" ? "bigserial" : sqlType === "smallint" ? "smallserial" : "serial";
386
+ }
387
+ let ddl = `${quoteIdent(column.name)} ${sqlType}`;
388
+ if (isSinglePk) ddl += " PRIMARY KEY";
389
+ if (!column.nullable && !isSinglePk) ddl += " NOT NULL";
390
+ if (column.generatedExpr) {
391
+ ddl += ` GENERATED ALWAYS AS (${column.generatedExpr}) STORED`;
392
+ } else if (column.defaultExpr && !column.isSerial) {
393
+ ddl += ` DEFAULT ${column.defaultExpr}`;
394
+ }
395
+ return ddl;
396
+ }
397
+ function generateSchemaSql(snapshot) {
398
+ const lines = [
399
+ "-- Auto-generated by @stardeck-customer-apps/data-store-sdk",
400
+ "-- Schema snapshot of the live data store, applied to PGlite by the test harness.",
401
+ "-- Do not edit manually \u2014 regenerate with: npx stardeck-data-store generate-types",
402
+ ""
403
+ ];
404
+ for (const ext of snapshot.extensions) {
405
+ lines.push(`CREATE EXTENSION IF NOT EXISTS ${ext === "uuid-ossp" ? '"uuid-ossp"' : ext};`);
406
+ }
407
+ if (snapshot.extensions.length > 0) lines.push("");
408
+ for (const enumType of snapshot.enums) {
409
+ const values = enumType.values.map((v) => `'${v.replace(/'/g, "''")}'`).join(", ");
410
+ lines.push(`CREATE TYPE ${quoteIdent(enumType.name)} AS ENUM (${values});`);
411
+ }
412
+ if (snapshot.enums.length > 0) lines.push("");
413
+ for (const table of snapshot.tables) {
414
+ const singlePk = table.primaryKey.length === 1 ? table.primaryKey[0] : null;
415
+ const parts = table.columns.map((col) => " " + columnDdl(col, col.name === singlePk));
416
+ if (table.primaryKey.length > 1) {
417
+ parts.push(` PRIMARY KEY (${table.primaryKey.map(quoteIdent).join(", ")})`);
418
+ }
419
+ for (const unique of table.uniques) {
420
+ parts.push(` UNIQUE (${unique.map(quoteIdent).join(", ")})`);
421
+ }
422
+ lines.push(`CREATE TABLE ${quoteIdent(table.name)} (`);
423
+ lines.push(parts.join(",\n"));
424
+ lines.push(`);`);
425
+ lines.push("");
426
+ }
427
+ for (const check of snapshot.checks) {
428
+ lines.push(
429
+ `ALTER TABLE ${quoteIdent(check.table)} ADD CONSTRAINT ${quoteIdent(check.name)} ${check.definition};`
430
+ );
431
+ }
432
+ if (snapshot.checks.length > 0) lines.push("");
433
+ for (const fk of snapshot.foreignKeys) {
434
+ let stmt = `ALTER TABLE ${quoteIdent(fk.table)} ADD CONSTRAINT ${quoteIdent(fk.constraintName)} FOREIGN KEY (${fk.columns.map(quoteIdent).join(", ")}) REFERENCES ${quoteIdent(fk.referencedTable)} (${fk.referencedColumns.map(quoteIdent).join(", ")})`;
435
+ if (fk.onDelete !== "NO ACTION") stmt += ` ON DELETE ${fk.onDelete}`;
436
+ if (fk.onUpdate !== "NO ACTION") stmt += ` ON UPDATE ${fk.onUpdate}`;
437
+ lines.push(`${stmt};`);
438
+ }
439
+ if (snapshot.foreignKeys.length > 0) lines.push("");
440
+ for (const index of snapshot.indexes) {
441
+ lines.push(`${index.definition};`);
442
+ }
443
+ if (snapshot.indexes.length > 0) lines.push("");
444
+ return lines.join("\n");
445
+ }
446
+
447
+ // src/cli/generate-types.ts
448
+ var PG_TYPE_MAP = {
449
+ text: "string",
450
+ varchar: "string",
451
+ "character varying": "string",
452
+ char: "string",
453
+ character: "string",
454
+ uuid: "string",
455
+ integer: "number",
456
+ int: "number",
457
+ smallint: "number",
458
+ bigint: "string",
459
+ // bigint as string to avoid precision loss
460
+ numeric: "string",
461
+ decimal: "string",
462
+ real: "number",
463
+ "double precision": "number",
464
+ boolean: "boolean",
465
+ jsonb: "unknown",
466
+ json: "unknown",
467
+ "timestamp with time zone": "Date",
468
+ "timestamp without time zone": "Date",
469
+ timestamp: "Date",
470
+ date: "string",
471
+ time: "string",
472
+ "time with time zone": "string",
473
+ "time without time zone": "string",
474
+ bytea: "Buffer",
475
+ ARRAY: "unknown[]"
476
+ };
477
+ function pgTypeToTs(pgType) {
478
+ return PG_TYPE_MAP[pgType] ?? "unknown";
479
+ }
480
+ function parseCliArgs(argv, options = {}) {
481
+ const cwd = options.cwd ?? process.cwd();
482
+ const env = options.env ?? process.env;
483
+ let connectionString = env.DATA_STORE_URL;
484
+ let store;
485
+ let outputPath = "./src/generated/data-store-types.ts";
486
+ let schemaOutputPath;
487
+ let emitSchema = !(0, import_fs2.existsSync)((0, import_path2.resolve)(cwd, "datastore/ledger-order.json"));
488
+ let modulesDir = (0, import_path2.resolve)(cwd, "./src/modules");
489
+ let noModules = false;
490
+ let help = false;
491
+ for (let i = 0; i < argv.length; i++) {
492
+ if (argv[i] === "--connection-string" && argv[i + 1]) {
493
+ connectionString = argv[++i];
494
+ } else if (argv[i] === "--store" && argv[i + 1]) {
495
+ store = argv[++i];
496
+ } else if (argv[i] === "--output" && argv[i + 1]) {
497
+ outputPath = argv[++i];
498
+ } else if (argv[i] === "--schema-output" && argv[i + 1]) {
499
+ schemaOutputPath = argv[++i];
500
+ emitSchema = true;
501
+ } else if (argv[i] === "--no-schema") {
502
+ emitSchema = false;
503
+ } else if (argv[i] === "--modules-dir" && argv[i + 1]) {
504
+ modulesDir = (0, import_path2.resolve)(cwd, argv[++i]);
505
+ } else if (argv[i] === "--no-modules") {
506
+ noModules = true;
507
+ } else if (argv[i] === "--help") {
508
+ help = true;
509
+ }
510
+ }
511
+ return {
512
+ connectionString,
513
+ store,
514
+ outputPath,
515
+ schemaOutputPath,
516
+ emitSchema,
517
+ modulesDir,
518
+ noModules,
519
+ help
520
+ };
521
+ }
522
+ async function introspectSchema(connectionString) {
523
+ const pool = new import_serverless.Pool({ connectionString });
524
+ try {
525
+ const { rows } = await pool.query(`
526
+ SELECT
527
+ c.table_name,
528
+ c.column_name,
529
+ c.data_type,
530
+ c.is_nullable,
531
+ c.column_default
532
+ FROM information_schema.columns c
533
+ JOIN information_schema.tables t
534
+ ON c.table_name = t.table_name AND c.table_schema = t.table_schema
535
+ WHERE c.table_schema = 'public'
536
+ AND t.table_type = 'BASE TABLE'
537
+ AND t.table_name NOT LIKE '_deleted_%'
538
+ ORDER BY c.table_name, c.ordinal_position
539
+ `);
540
+ const tables = /* @__PURE__ */ new Map();
541
+ for (const row of rows) {
542
+ if (!tables.has(row.table_name)) {
543
+ tables.set(row.table_name, []);
544
+ }
545
+ tables.get(row.table_name).push(row);
546
+ }
547
+ return tables;
548
+ } finally {
549
+ await pool.end();
550
+ }
551
+ }
552
+ function generateTypeScript(tables, moduleSlices) {
553
+ const lines = [
554
+ "// AUTO-GENERATED by @stardeck-customer-apps/data-store-sdk \u2014 DO NOT EDIT.",
555
+ "// This file is overwritten in full on every run of:",
556
+ "// npx stardeck-data-store generate-types",
557
+ "// Anything you add here (hand-written or derived types) WILL BE LOST on the next",
558
+ "// regeneration. Put those in a separate file that imports from this one, e.g.",
559
+ "// src/lib/<domain>-types.ts importing the table types or DB from this file.",
560
+ "// When module manifests are discoverable, per-module DB slices and ModuleDBs are",
561
+ "// appended below the flat DB interface.",
562
+ "",
563
+ 'import type { Generated } from "kysely";',
564
+ ""
565
+ ];
566
+ for (const [tableName, columns] of tables) {
567
+ const interfaceName = toPascalCase(tableName) + "Table";
568
+ lines.push(`export interface ${interfaceName} {`);
569
+ for (const col of columns) {
570
+ const tsType = pgTypeToTs(col.data_type);
571
+ const isGenerated = col.column_default !== null;
572
+ const isNullable = col.is_nullable === "YES";
573
+ let type = tsType;
574
+ if (isNullable) {
575
+ type = `${tsType} | null`;
576
+ }
577
+ if (isGenerated) {
578
+ type = `Generated<${type}>`;
579
+ }
580
+ lines.push(` ${col.column_name}: ${type};`);
581
+ }
582
+ lines.push("}");
583
+ lines.push("");
584
+ }
585
+ lines.push("export interface DB {");
586
+ for (const tableName of tables.keys()) {
587
+ const interfaceName = toPascalCase(tableName) + "Table";
588
+ lines.push(` ${tableName}: ${interfaceName};`);
589
+ }
590
+ lines.push("}");
591
+ lines.push("");
592
+ if (moduleSlices) {
593
+ const trimmed = moduleSlices.trimEnd();
594
+ if (trimmed.length > 0) {
595
+ lines.push(trimmed);
596
+ lines.push("");
597
+ }
598
+ }
599
+ return lines.join("\n");
600
+ }
601
+ async function runGenerateTypes(options) {
602
+ const {
603
+ connectionString,
604
+ outputPath,
605
+ schemaOutputPath,
606
+ emitSchema = true,
607
+ modulesDir,
608
+ noModules,
609
+ introspect = introspectSchema,
610
+ warn = (message) => console.warn(message)
611
+ } = options;
612
+ console.log("Introspecting database schema...");
613
+ const tables = await introspect(connectionString);
614
+ if (tables.size === 0) {
615
+ console.log("No tables found in database.");
616
+ return;
617
+ }
618
+ console.log(`Found ${tables.size} table(s): ${Array.from(tables.keys()).join(", ")}`);
619
+ let moduleSlices = "";
620
+ if (shouldLoadModuleManifests(noModules)) {
621
+ const manifests = discoverModuleManifests(modulesDir, warn);
622
+ if (manifests.length > 0) {
623
+ moduleSlices = emitModuleDbSlices(new Set(tables.keys()), manifests, warn);
624
+ }
625
+ }
626
+ const typeScript = generateTypeScript(tables, moduleSlices || void 0);
627
+ const dir = outputPath.substring(0, outputPath.lastIndexOf("/"));
628
+ if (dir) {
629
+ const { mkdirSync } = await import("fs");
630
+ mkdirSync(dir, { recursive: true });
631
+ }
632
+ (0, import_fs2.writeFileSync)(outputPath, typeScript, "utf-8");
633
+ console.log(`Types written to ${outputPath}`);
634
+ if (emitSchema) {
635
+ const schemaPath = schemaOutputPath ?? `${dir ? `${dir}/` : ""}data-store-schema.sql`;
636
+ const pool = new import_serverless.Pool({ connectionString });
637
+ try {
638
+ const snapshot = await introspectSchemaSnapshot(pool);
639
+ (0, import_fs2.writeFileSync)(schemaPath, generateSchemaSql(snapshot), "utf-8");
640
+ console.log(`Schema snapshot written to ${schemaPath} (used by the test harness)`);
641
+ } finally {
642
+ await pool.end();
643
+ }
644
+ }
645
+ }
646
+ function connectionStringFromManifest(store) {
647
+ const databases = readDataStoreManifest().filter((entry) => entry.storeType !== "storage");
648
+ if (store) {
649
+ const match = resolveDataStore({ storeName: store });
650
+ if (!match?.url) {
651
+ return {
652
+ error: `No connected database store matches --store ${store}. Connected: ${listStores(databases)}.`
653
+ };
654
+ }
655
+ return { url: match.url };
656
+ }
657
+ if (databases.length === 1 && databases[0]?.url) return { url: databases[0].url };
658
+ if (databases.length === 0) {
659
+ return {
660
+ error: "No connected database store found. Run `npm run env:pull` in apps/web to write .env.local, or pass --connection-string."
661
+ };
662
+ }
663
+ return {
664
+ error: `${databases.length} database stores are connected; pass --store <bindingKey>. Connected: ${listStores(databases)}.`
665
+ };
666
+ }
667
+ function listStores(entries) {
668
+ return entries.length === 0 ? "none" : entries.map((entry) => entry.bindingKey ?? entry.slug).join(", ");
669
+ }
670
+ function loadEnvLocal(cwd) {
671
+ const path = (0, import_path2.resolve)(cwd, ".env.local");
672
+ let content;
673
+ try {
674
+ content = (0, import_fs2.readFileSync)(path, "utf8");
675
+ } catch (error) {
676
+ if (error.code !== "ENOENT") {
677
+ console.warn(`Warning: could not read ${path}: ${error.message}`);
678
+ }
679
+ return;
680
+ }
681
+ for (const [key, value] of Object.entries((0, import_util.parseEnv)(content))) {
682
+ if (value !== void 0 && process.env[key] === void 0) {
683
+ process.env[key] = value.replace(/\\\$/g, "$");
684
+ }
685
+ }
686
+ }
687
+ async function main(argv = process.argv.slice(2)) {
688
+ loadEnvLocal(process.cwd());
689
+ const parsed = parseCliArgs(argv);
690
+ if (parsed.help) {
691
+ console.log(`Usage: stardeck-data-store generate-types [options]
692
+
693
+ Options:
694
+ --connection-string <url> Postgres connection string (default: DATA_STORE_URL, else the
695
+ app's connected store from STARDECK_DATA_STORES / .env.local)
696
+ --store <bindingKey> Which connected store to read when the app has several
697
+ --output <path> Output file path (default: ./src/generated/data-store-types.ts)
698
+ --schema-output <path> DDL snapshot path (default: data-store-schema.sql next to --output)
699
+ --no-schema Skip the DDL snapshot used by the test harness (implied when
700
+ datastore/ledger-order.json exists: a Blueprint composes its own)
701
+ --modules-dir <path> Directory containing module folders (default: ./src/modules)
702
+ --no-modules Skip per-module DB slice generation
703
+ --help Show this help message`);
704
+ process.exit(0);
705
+ }
706
+ let connectionString = parsed.connectionString;
707
+ if (!connectionString) {
708
+ const resolved = connectionStringFromManifest(parsed.store);
709
+ if ("error" in resolved) {
710
+ console.error(`Error: ${resolved.error}`);
711
+ process.exit(1);
712
+ }
713
+ connectionString = resolved.url;
714
+ }
715
+ await runGenerateTypes({
716
+ connectionString,
717
+ outputPath: parsed.outputPath,
718
+ schemaOutputPath: parsed.schemaOutputPath,
719
+ emitSchema: parsed.emitSchema,
720
+ modulesDir: parsed.modulesDir,
721
+ noModules: parsed.noModules
722
+ });
723
+ }
724
+
725
+ // src/cli/bin.ts
726
+ main().catch((error) => {
727
+ console.error(error instanceof Error ? error.message : String(error));
728
+ process.exit(1);
729
+ });