@pol-studios/powersync 1.0.10 → 1.0.12

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,590 @@
1
+ // src/generator/config.ts
2
+ function defineConfig(config) {
3
+ return config;
4
+ }
5
+ var DEFAULT_SKIP_COLUMNS = [
6
+ "id",
7
+ // PowerSync handles id automatically
8
+ // Legacy numeric ID columns - typically not needed after UUID migration
9
+ "legacyId"
10
+ ];
11
+ var DEFAULT_DECIMAL_PATTERNS = ["hours", "watts", "voltage", "rate", "amount", "price", "cost", "total"];
12
+ var DEFAULT_INDEX_PATTERNS = [
13
+ "Id$",
14
+ // FK columns ending in Id (e.g., projectId, userId)
15
+ "^createdAt$",
16
+ "^updatedAt$",
17
+ "^status$",
18
+ "^type$"
19
+ ];
20
+
21
+ // src/generator/generator.ts
22
+ import * as fs from "fs";
23
+ import * as path from "path";
24
+
25
+ // src/generator/parser.ts
26
+ function parseRowType(tableContent, options) {
27
+ const columns = /* @__PURE__ */ new Map();
28
+ const rowMatch = tableContent.match(/Row:\s*\{([^}]+(?:\{[^}]*\}[^}]*)*)\}/s);
29
+ if (!rowMatch) return columns;
30
+ const rowContent = rowMatch[1];
31
+ const includePrimaryKey = options.syncPrimaryKey ?? options.includeId ?? false;
32
+ const columnRegex = /(\w+)\??:\s*([^,\n]+)/g;
33
+ let match;
34
+ while ((match = columnRegex.exec(rowContent)) !== null) {
35
+ const [, columnName, columnType] = match;
36
+ const shouldSkip = options.skipColumns.has(columnName) && !(includePrimaryKey && columnName === "id");
37
+ if (!shouldSkip) {
38
+ columns.set(columnName, columnType.trim());
39
+ }
40
+ }
41
+ return columns;
42
+ }
43
+ function extractTableDef(content, tableName, schema) {
44
+ const schemaRegex = new RegExp(`${schema}:\\s*\\{[\\s\\S]*?Tables:\\s*\\{`, "g");
45
+ const schemaMatch = schemaRegex.exec(content);
46
+ if (!schemaMatch) return null;
47
+ const startIndex = schemaMatch.index;
48
+ const tableRegex = new RegExp(`(?<![A-Za-z])${tableName}:\\s*\\{[\\s\\S]*?Row:\\s*\\{[\\s\\S]*?\\}[\\s\\S]*?Relationships:\\s*\\[[^\\]]*\\]\\s*\\}`, "g");
49
+ const searchContent = content.slice(startIndex);
50
+ const tableMatch = tableRegex.exec(searchContent);
51
+ return tableMatch ? tableMatch[0] : null;
52
+ }
53
+ function parseTypesFile(content, tables, skipColumns) {
54
+ const parsedTables = [];
55
+ for (const tableConfig of tables) {
56
+ const {
57
+ name,
58
+ schema = "public",
59
+ syncPrimaryKey,
60
+ includeId
61
+ } = tableConfig;
62
+ const tableDef = extractTableDef(content, name, schema);
63
+ if (!tableDef) {
64
+ continue;
65
+ }
66
+ const columns = parseRowType(tableDef, {
67
+ skipColumns,
68
+ syncPrimaryKey,
69
+ includeId
70
+ });
71
+ if (columns.size > 0) {
72
+ parsedTables.push({
73
+ name,
74
+ schema,
75
+ columns,
76
+ config: tableConfig
77
+ });
78
+ }
79
+ }
80
+ return parsedTables;
81
+ }
82
+ function getAvailableSchemas(content) {
83
+ const schemas = [];
84
+ const schemaRegex = /(\w+):\s*\{[\s\S]*?Tables:\s*\{/g;
85
+ let match;
86
+ while ((match = schemaRegex.exec(content)) !== null) {
87
+ schemas.push(match[1]);
88
+ }
89
+ return schemas;
90
+ }
91
+ function getTablesInSchema(content, schema) {
92
+ const tables = [];
93
+ const schemaRegex = new RegExp(`${schema}:\\s*\\{[\\s\\S]*?Tables:\\s*\\{([\\s\\S]*?)\\}\\s*Views:`, "g");
94
+ const schemaMatch = schemaRegex.exec(content);
95
+ if (!schemaMatch) return tables;
96
+ const tablesContent = schemaMatch[1];
97
+ const tableNameRegex = /^\s*(\w+):\s*\{/gm;
98
+ let match;
99
+ while ((match = tableNameRegex.exec(tablesContent)) !== null) {
100
+ tables.push(match[1]);
101
+ }
102
+ return tables;
103
+ }
104
+
105
+ // src/generator/templates.ts
106
+ function toSnakeCase(str) {
107
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
108
+ }
109
+ function generateIndexDefinitions(tableName, columns, indexPatterns, additionalColumns = []) {
110
+ const indexes = [];
111
+ const snakeTableName = toSnakeCase(tableName);
112
+ const columnsToIndex = /* @__PURE__ */ new Set();
113
+ for (const column of columns) {
114
+ if (column === "id") continue;
115
+ for (const pattern of indexPatterns) {
116
+ const regex = new RegExp(pattern);
117
+ if (regex.test(column)) {
118
+ columnsToIndex.add(column);
119
+ break;
120
+ }
121
+ }
122
+ }
123
+ for (const column of additionalColumns) {
124
+ if (columns.includes(column) && column !== "id") {
125
+ columnsToIndex.add(column);
126
+ }
127
+ }
128
+ for (const column of columnsToIndex) {
129
+ const snakeColumn = toSnakeCase(column);
130
+ indexes.push({
131
+ name: `idx_${snakeTableName}_${snakeColumn}`,
132
+ columns: [column]
133
+ });
134
+ }
135
+ indexes.sort((a, b) => a.name.localeCompare(b.name));
136
+ return indexes;
137
+ }
138
+ function generateHeader(typesPath) {
139
+ return `/**
140
+ * PowerSync Schema Definition
141
+ *
142
+ * AUTO-GENERATED from ${typesPath}
143
+ * Run: npx @pol-studios/powersync generate-schema
144
+ *
145
+ * DO NOT EDIT MANUALLY - changes will be overwritten
146
+ */
147
+
148
+ import { column, Schema, Table } from "@powersync/react-native";
149
+ `;
150
+ }
151
+ function formatIndexes(indexes) {
152
+ if (indexes.length === 0) return "";
153
+ const indexLines = indexes.map((idx) => {
154
+ const columnsStr = idx.columns.map((c) => `'${c}'`).join(", ");
155
+ return ` { name: '${idx.name}', columns: [${columnsStr}] },`;
156
+ });
157
+ return `indexes: [
158
+ ${indexLines.join("\n")}
159
+ ]`;
160
+ }
161
+ function generateTableDefinition(table, columnDefs, indexes = []) {
162
+ if (columnDefs.length === 0) {
163
+ return `// ${table.name} - no syncable columns found`;
164
+ }
165
+ const optionsParts = [];
166
+ if (table.config.trackMetadata) {
167
+ optionsParts.push("trackMetadata: true");
168
+ }
169
+ if (indexes.length > 0) {
170
+ optionsParts.push(formatIndexes(indexes));
171
+ }
172
+ const optionsStr = optionsParts.length > 0 ? `, {
173
+ ${optionsParts.join(",\n ")}
174
+ }` : "";
175
+ return `const ${table.name} = new Table({
176
+ ${columnDefs.join("\n")}
177
+ }${optionsStr});`;
178
+ }
179
+ function generateSchemaExport(tableNames) {
180
+ return `// ============================================================================
181
+ // SCHEMA EXPORT
182
+ // ============================================================================
183
+
184
+ // NOTE: photo_attachments is NOT included here.
185
+ // The AttachmentQueue from @powersync/attachments creates and manages
186
+ // its own internal SQLite table (not a view) during queue.init().
187
+ // This allows INSERT/UPDATE operations to work correctly.
188
+
189
+ export const AppSchema = new Schema({
190
+ ${tableNames.map((name) => ` ${name},`).join("\n")}
191
+ });
192
+
193
+ export type Database = (typeof AppSchema)["types"];`;
194
+ }
195
+ function generateSchemaMapping(tables, schemas) {
196
+ const schemaGroups = /* @__PURE__ */ new Map();
197
+ for (const schema of schemas) {
198
+ if (schema !== "public") {
199
+ schemaGroups.set(schema, []);
200
+ }
201
+ }
202
+ for (const table of tables) {
203
+ if (table.schema !== "public" && schemaGroups.has(table.schema)) {
204
+ schemaGroups.get(table.schema).push(table.name);
205
+ }
206
+ }
207
+ const sections = [`// ============================================================================
208
+ // SCHEMA MAPPING FOR CONNECTOR
209
+ // ============================================================================`];
210
+ for (const [schema, tableNames] of schemaGroups) {
211
+ if (tableNames.length > 0) {
212
+ const constName = `${schema.toUpperCase()}_SCHEMA_TABLES`;
213
+ sections.push(`
214
+ // Tables in the '${schema}' schema (need .schema('${schema}') in Supabase queries)
215
+ export const ${constName} = new Set([
216
+ ${tableNames.map((name) => ` "${name}",`).join("\n")}
217
+ ]);`);
218
+ }
219
+ }
220
+ const schemaChecks = Array.from(schemaGroups.entries()).filter(([, names]) => names.length > 0).map(([schema]) => {
221
+ const constName = `${schema.toUpperCase()}_SCHEMA_TABLES`;
222
+ return ` if (${constName}.has(tableName)) return "${schema}";`;
223
+ });
224
+ if (schemaChecks.length > 0) {
225
+ sections.push(`
226
+ /**
227
+ * Get the Supabase schema for a table
228
+ */
229
+ export function getTableSchema(tableName: string): ${schemas.map((s) => `"${s}"`).join(" | ")} {
230
+ ${schemaChecks.join("\n")}
231
+ return "public";
232
+ }`);
233
+ } else {
234
+ sections.push(`
235
+ /**
236
+ * Get the Supabase schema for a table
237
+ */
238
+ export function getTableSchema(tableName: string): "public" {
239
+ return "public";
240
+ }`);
241
+ }
242
+ return sections.join("\n");
243
+ }
244
+ function generateFKUtility() {
245
+ return `
246
+ // ============================================================================
247
+ // FOREIGN KEY UTILITIES
248
+ // ============================================================================
249
+
250
+ /**
251
+ * Check if a column name represents a foreign key reference
252
+ * Convention: columns ending in 'Id' are foreign keys (e.g., projectId -> Project table)
253
+ */
254
+ export function isForeignKeyColumn(columnName: string): boolean {
255
+ return columnName.endsWith('Id') && columnName !== 'id';
256
+ }
257
+
258
+ /**
259
+ * Get the referenced table name from a foreign key column
260
+ * e.g., 'projectId' -> 'Project', 'equipmentFixtureUnitId' -> 'EquipmentFixtureUnit'
261
+ */
262
+ export function getForeignKeyTable(columnName: string): string | null {
263
+ if (!isForeignKeyColumn(columnName)) return null;
264
+ // Remove 'Id' suffix and capitalize first letter
265
+ const baseName = columnName.slice(0, -2);
266
+ return baseName.charAt(0).toUpperCase() + baseName.slice(1);
267
+ }`;
268
+ }
269
+ function generateOutputFile(tables, tableDefs, schemas, typesPath) {
270
+ const tableNames = tables.map((t) => t.name);
271
+ return `${generateHeader(typesPath)}
272
+
273
+ // ============================================================================
274
+ // TABLE DEFINITIONS
275
+ // ============================================================================
276
+
277
+ ${tableDefs.join("\n\n")}
278
+
279
+ ${generateSchemaExport(tableNames)}
280
+
281
+ ${generateSchemaMapping(tables, ["public", ...schemas.filter((s) => s !== "public")])}
282
+ ${generateFKUtility()}
283
+ `;
284
+ }
285
+
286
+ // src/generator/fk-dependencies.ts
287
+ function fkColumnToTableName(columnName) {
288
+ if (!columnName.endsWith("Id") || columnName === "id") {
289
+ return null;
290
+ }
291
+ const baseName = columnName.slice(0, -2);
292
+ return baseName.charAt(0).toUpperCase() + baseName.slice(1);
293
+ }
294
+ function detectFKDependencies(tables) {
295
+ const tableNames = new Set(tables.map((t) => t.name));
296
+ const dependencies = /* @__PURE__ */ new Map();
297
+ const dependents = /* @__PURE__ */ new Map();
298
+ const fkRelationships = [];
299
+ for (const table of tables) {
300
+ dependencies.set(table.name, []);
301
+ dependents.set(table.name, []);
302
+ }
303
+ for (const table of tables) {
304
+ for (const [columnName] of table.columns) {
305
+ const referencedTable = fkColumnToTableName(columnName);
306
+ if (referencedTable && tableNames.has(referencedTable)) {
307
+ const tableDeps = dependencies.get(table.name) || [];
308
+ if (!tableDeps.includes(referencedTable)) {
309
+ tableDeps.push(referencedTable);
310
+ dependencies.set(table.name, tableDeps);
311
+ }
312
+ const refDeps = dependents.get(referencedTable) || [];
313
+ if (!refDeps.includes(table.name)) {
314
+ refDeps.push(table.name);
315
+ dependents.set(referencedTable, refDeps);
316
+ }
317
+ fkRelationships.push({
318
+ table: table.name,
319
+ column: columnName,
320
+ referencedTable
321
+ });
322
+ }
323
+ }
324
+ }
325
+ const uploadOrder = getUploadOrder({
326
+ dependencies
327
+ });
328
+ return {
329
+ dependencies,
330
+ dependents,
331
+ uploadOrder,
332
+ fkRelationships
333
+ };
334
+ }
335
+ function getUploadOrder(graph) {
336
+ const result = [];
337
+ const inDegree = /* @__PURE__ */ new Map();
338
+ const adjList = /* @__PURE__ */ new Map();
339
+ for (const [table, deps] of graph.dependencies) {
340
+ inDegree.set(table, deps.length);
341
+ adjList.set(table, []);
342
+ }
343
+ for (const [table, deps] of graph.dependencies) {
344
+ for (const dep of deps) {
345
+ const list = adjList.get(dep) || [];
346
+ list.push(table);
347
+ adjList.set(dep, list);
348
+ }
349
+ }
350
+ const queue = [];
351
+ for (const [table, degree] of inDegree) {
352
+ if (degree === 0) {
353
+ queue.push(table);
354
+ }
355
+ }
356
+ queue.sort();
357
+ while (queue.length > 0) {
358
+ const table = queue.shift();
359
+ result.push(table);
360
+ const dependentTables = adjList.get(table) || [];
361
+ for (const dependent of dependentTables) {
362
+ const newDegree = (inDegree.get(dependent) || 0) - 1;
363
+ inDegree.set(dependent, newDegree);
364
+ if (newDegree === 0) {
365
+ queue.push(dependent);
366
+ queue.sort();
367
+ }
368
+ }
369
+ }
370
+ if (result.length < graph.dependencies.size) {
371
+ const remaining = [...graph.dependencies.keys()].filter((t) => !result.includes(t)).sort();
372
+ result.push(...remaining);
373
+ }
374
+ return result;
375
+ }
376
+ function getRootTables(graph) {
377
+ const roots = [];
378
+ for (const [table, deps] of graph.dependencies) {
379
+ if (deps.length === 0) {
380
+ roots.push(table);
381
+ }
382
+ }
383
+ return roots.sort();
384
+ }
385
+ function getLeafTables(graph) {
386
+ const leaves = [];
387
+ for (const [table, deps] of graph.dependents) {
388
+ if (deps.length === 0) {
389
+ leaves.push(table);
390
+ }
391
+ }
392
+ return leaves.sort();
393
+ }
394
+ function formatDependencyGraph(graph) {
395
+ const lines = [];
396
+ lines.push("FK Dependencies:");
397
+ for (const fk of graph.fkRelationships) {
398
+ lines.push(` ${fk.table}.${fk.column} -> ${fk.referencedTable}`);
399
+ }
400
+ if (graph.fkRelationships.length === 0) {
401
+ lines.push(" (none detected)");
402
+ }
403
+ lines.push("");
404
+ lines.push("Upload Order (topological):");
405
+ graph.uploadOrder.forEach((table, i) => {
406
+ const deps = graph.dependencies.get(table) || [];
407
+ const depStr = deps.length > 0 ? ` (depends on: ${deps.join(", ")})` : " (root)";
408
+ lines.push(` ${i + 1}. ${table}${depStr}`);
409
+ });
410
+ return lines.join("\n");
411
+ }
412
+
413
+ // src/generator/generator.ts
414
+ function mapTypeToPowerSync(tsType, columnName, decimalPatterns) {
415
+ const cleanType = tsType.trim().replace(/\s*\|\s*null/g, "");
416
+ if (cleanType.includes("Json") || cleanType.includes("unknown") || cleanType.includes("{")) {
417
+ return null;
418
+ }
419
+ if (cleanType.includes("[]")) {
420
+ return null;
421
+ }
422
+ if (cleanType === "boolean") {
423
+ return {
424
+ type: "column.integer",
425
+ isBoolean: true
426
+ };
427
+ }
428
+ if (cleanType === "number") {
429
+ if (decimalPatterns.some((pattern) => columnName.toLowerCase().includes(pattern.toLowerCase()))) {
430
+ return {
431
+ type: "column.real"
432
+ };
433
+ }
434
+ return {
435
+ type: "column.integer"
436
+ };
437
+ }
438
+ if (cleanType === "string") {
439
+ return {
440
+ type: "column.text"
441
+ };
442
+ }
443
+ if (cleanType.includes("Database[") && cleanType.includes("Enums")) {
444
+ return {
445
+ type: "column.text",
446
+ isEnum: true
447
+ };
448
+ }
449
+ return {
450
+ type: "column.text"
451
+ };
452
+ }
453
+ function generateColumnDefs(table, decimalPatterns) {
454
+ const columnDefs = [];
455
+ for (const [columnName, tsType] of table.columns) {
456
+ const mapping = mapTypeToPowerSync(tsType, columnName, decimalPatterns);
457
+ if (mapping) {
458
+ let comment = "";
459
+ if (mapping.isBoolean) {
460
+ comment = " // boolean stored as 0/1";
461
+ } else if (mapping.isEnum) {
462
+ comment = " // enum stored as text";
463
+ }
464
+ columnDefs.push(` ${columnName}: ${mapping.type},${comment}`);
465
+ }
466
+ }
467
+ return columnDefs;
468
+ }
469
+ async function generateSchema(config, options) {
470
+ const cwd = options?.cwd ?? process.cwd();
471
+ const verbose = options?.verbose ?? false;
472
+ const dryRun = options?.dryRun ?? false;
473
+ const result = {
474
+ success: false,
475
+ tablesGenerated: 0,
476
+ outputPath: "",
477
+ errors: [],
478
+ warnings: []
479
+ };
480
+ const typesPath = path.isAbsolute(config.typesPath) ? config.typesPath : path.resolve(cwd, config.typesPath);
481
+ const outputPath = path.isAbsolute(config.outputPath) ? config.outputPath : path.resolve(cwd, config.outputPath);
482
+ result.outputPath = outputPath;
483
+ if (!fs.existsSync(typesPath)) {
484
+ result.errors.push(`Types file not found: ${typesPath}`);
485
+ return result;
486
+ }
487
+ if (verbose) {
488
+ console.log(`Reading types from: ${typesPath}`);
489
+ }
490
+ const typesContent = fs.readFileSync(typesPath, "utf-8");
491
+ const skipColumns = /* @__PURE__ */ new Set([...DEFAULT_SKIP_COLUMNS, ...config.skipColumns ?? []]);
492
+ const decimalPatterns = [...DEFAULT_DECIMAL_PATTERNS, ...config.decimalPatterns ?? []];
493
+ const parsedTables = parseTypesFile(typesContent, config.tables, skipColumns);
494
+ for (const tableConfig of config.tables) {
495
+ const found = parsedTables.some((t) => t.name === tableConfig.name);
496
+ if (!found) {
497
+ result.warnings.push(`Table '${tableConfig.name}' not found in schema '${tableConfig.schema ?? "public"}'`);
498
+ }
499
+ }
500
+ if (parsedTables.length === 0) {
501
+ result.errors.push("No tables were parsed successfully");
502
+ return result;
503
+ }
504
+ const autoIndexes = config.autoIndexes ?? true;
505
+ const indexPatterns = autoIndexes ? [...DEFAULT_INDEX_PATTERNS, ...config.indexPatterns ?? []] : config.indexPatterns ?? [];
506
+ const indexColumns = config.indexColumns ?? [];
507
+ const dependencyGraph = detectFKDependencies(parsedTables);
508
+ result.dependencyGraph = dependencyGraph;
509
+ if (verbose && dependencyGraph.fkRelationships.length > 0) {
510
+ console.log(`
511
+ FK Dependencies detected: ${dependencyGraph.fkRelationships.length}`);
512
+ for (const fk of dependencyGraph.fkRelationships) {
513
+ console.log(` ${fk.table}.${fk.column} -> ${fk.referencedTable}`);
514
+ }
515
+ console.log(`
516
+ Recommended upload order:`);
517
+ dependencyGraph.uploadOrder.forEach((table, i) => {
518
+ console.log(` ${i + 1}. ${table}`);
519
+ });
520
+ console.log("");
521
+ }
522
+ const tableDefs = [];
523
+ let totalIndexes = 0;
524
+ for (const table of parsedTables) {
525
+ if (verbose) {
526
+ const syncPK = table.config.syncPrimaryKey || table.config.includeId;
527
+ console.log(`Processing ${table.schema}.${table.name} (${table.columns.size} columns)${table.config.trackMetadata ? " [trackMetadata]" : ""}${syncPK ? " [syncPrimaryKey]" : ""}`);
528
+ }
529
+ const columnDefs = generateColumnDefs(table, decimalPatterns);
530
+ if (columnDefs.length === 0) {
531
+ result.warnings.push(`Table '${table.name}' has no syncable columns`);
532
+ continue;
533
+ }
534
+ const columnNames = [...table.columns.keys()];
535
+ const indexes = indexPatterns.length > 0 || indexColumns.length > 0 ? generateIndexDefinitions(table.name, columnNames, indexPatterns, indexColumns) : [];
536
+ totalIndexes += indexes.length;
537
+ if (verbose && indexes.length > 0) {
538
+ console.log(` Indexes: ${indexes.map((i) => i.name).join(", ")}`);
539
+ }
540
+ tableDefs.push(generateTableDefinition(table, columnDefs, indexes));
541
+ }
542
+ result.indexesGenerated = totalIndexes;
543
+ const schemas = [...new Set(config.tables.map((t) => t.schema ?? "public"))];
544
+ const relativePath = path.relative(cwd, typesPath);
545
+ const output = generateOutputFile(parsedTables.filter((t) => tableDefs.some((def) => def.includes(`const ${t.name} =`))), tableDefs, schemas, relativePath);
546
+ if (dryRun) {
547
+ result.success = true;
548
+ result.tablesGenerated = tableDefs.length;
549
+ result.output = output;
550
+ return result;
551
+ }
552
+ const outputDir = path.dirname(outputPath);
553
+ if (!fs.existsSync(outputDir)) {
554
+ fs.mkdirSync(outputDir, {
555
+ recursive: true
556
+ });
557
+ }
558
+ fs.writeFileSync(outputPath, output);
559
+ result.success = true;
560
+ result.tablesGenerated = tableDefs.length;
561
+ return result;
562
+ }
563
+ export {
564
+ DEFAULT_DECIMAL_PATTERNS,
565
+ DEFAULT_INDEX_PATTERNS,
566
+ DEFAULT_SKIP_COLUMNS,
567
+ defineConfig,
568
+ detectFKDependencies,
569
+ extractTableDef,
570
+ fkColumnToTableName,
571
+ formatDependencyGraph,
572
+ generateColumnDefs,
573
+ generateFKUtility,
574
+ generateHeader,
575
+ generateIndexDefinitions,
576
+ generateOutputFile,
577
+ generateSchema,
578
+ generateSchemaExport,
579
+ generateSchemaMapping,
580
+ generateTableDefinition,
581
+ getAvailableSchemas,
582
+ getLeafTables,
583
+ getRootTables,
584
+ getTablesInSchema,
585
+ getUploadOrder,
586
+ mapTypeToPowerSync,
587
+ parseRowType,
588
+ parseTypesFile
589
+ };
590
+ //# sourceMappingURL=index.js.map