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