@prisma-next/family-sql 0.1.0-dev.10 → 0.1.0-dev.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,1389 @@
1
+ import {
2
+ collectSupportedCodecTypeIds,
3
+ readMarker
4
+ } from "./chunk-3HYKCN35.js";
5
+
6
+ // src/core/assembly.ts
7
+ import { createOperationRegistry } from "@prisma-next/operations";
8
+
9
+ // src/core/instance.ts
10
+ import { emit } from "@prisma-next/core-control-plane/emission";
11
+ import { sqlTargetFamilyHook } from "@prisma-next/sql-contract-emitter";
12
+ import { validateContract } from "@prisma-next/sql-contract-ts/contract";
13
+ import {
14
+ ensureSchemaStatement,
15
+ ensureTableStatement,
16
+ writeContractMarker
17
+ } from "@prisma-next/sql-runtime";
18
+ function convertOperationManifest(manifest) {
19
+ return {
20
+ forTypeId: manifest.for,
21
+ method: manifest.method,
22
+ args: manifest.args.map((arg) => {
23
+ if (arg.kind === "typeId") {
24
+ if (!arg.type) {
25
+ throw new Error("typeId arg must have type property");
26
+ }
27
+ return { kind: "typeId", type: arg.type };
28
+ }
29
+ if (arg.kind === "param") {
30
+ return { kind: "param" };
31
+ }
32
+ if (arg.kind === "literal") {
33
+ return { kind: "literal" };
34
+ }
35
+ throw new Error(`Invalid arg kind: ${arg.kind}`);
36
+ }),
37
+ returns: (() => {
38
+ if (manifest.returns.kind === "typeId") {
39
+ return { kind: "typeId", type: manifest.returns.type };
40
+ }
41
+ if (manifest.returns.kind === "builtin") {
42
+ return {
43
+ kind: "builtin",
44
+ type: manifest.returns.type
45
+ };
46
+ }
47
+ throw new Error(`Invalid return kind: ${manifest.returns.kind}`);
48
+ })(),
49
+ lowering: {
50
+ targetFamily: "sql",
51
+ strategy: manifest.lowering.strategy,
52
+ template: manifest.lowering.template
53
+ },
54
+ ...manifest.capabilities ? { capabilities: manifest.capabilities } : {}
55
+ };
56
+ }
57
+ function extractCodecTypeIdsFromContract(contract) {
58
+ const typeIds = /* @__PURE__ */ new Set();
59
+ if (typeof contract === "object" && contract !== null && "storage" in contract && typeof contract.storage === "object" && contract.storage !== null && "tables" in contract.storage) {
60
+ const storage = contract.storage;
61
+ if (storage.tables && typeof storage.tables === "object") {
62
+ for (const table of Object.values(storage.tables)) {
63
+ if (typeof table === "object" && table !== null && "columns" in table && typeof table.columns === "object" && table.columns !== null) {
64
+ const columns = table.columns;
65
+ for (const column of Object.values(columns)) {
66
+ if (column && typeof column === "object" && "codecId" in column && typeof column.codecId === "string") {
67
+ typeIds.add(column.codecId);
68
+ }
69
+ }
70
+ }
71
+ }
72
+ }
73
+ }
74
+ return Array.from(typeIds).sort();
75
+ }
76
+ function arraysEqual(a, b) {
77
+ if (a.length !== b.length) {
78
+ return false;
79
+ }
80
+ for (let i = 0; i < a.length; i++) {
81
+ if (a[i] !== b[i]) {
82
+ return false;
83
+ }
84
+ }
85
+ return true;
86
+ }
87
+ function comparePrimaryKey(contractPK, schemaPK, tableName, issues) {
88
+ if (!schemaPK) {
89
+ issues.push({
90
+ kind: "primary_key_mismatch",
91
+ table: tableName,
92
+ expected: contractPK.columns.join(", "),
93
+ message: `Table "${tableName}" is missing primary key`
94
+ });
95
+ return "fail";
96
+ }
97
+ if (!arraysEqual(contractPK.columns, schemaPK.columns)) {
98
+ issues.push({
99
+ kind: "primary_key_mismatch",
100
+ table: tableName,
101
+ expected: contractPK.columns.join(", "),
102
+ actual: schemaPK.columns.join(", "),
103
+ message: `Table "${tableName}" has primary key mismatch: expected columns [${contractPK.columns.join(", ")}], got [${schemaPK.columns.join(", ")}]`
104
+ });
105
+ return "fail";
106
+ }
107
+ if (contractPK.name && schemaPK.name && contractPK.name !== schemaPK.name) {
108
+ issues.push({
109
+ kind: "primary_key_mismatch",
110
+ table: tableName,
111
+ indexOrConstraint: contractPK.name,
112
+ expected: contractPK.name,
113
+ actual: schemaPK.name,
114
+ message: `Table "${tableName}" has primary key name mismatch: expected "${contractPK.name}", got "${schemaPK.name}"`
115
+ });
116
+ return "fail";
117
+ }
118
+ return "pass";
119
+ }
120
+ function compareForeignKeys(contractFKs, schemaFKs, tableName, tablePath, issues, strict) {
121
+ const nodes = [];
122
+ for (const contractFK of contractFKs) {
123
+ const fkPath = `${tablePath}.foreignKeys[${contractFK.columns.join(",")}]`;
124
+ const matchingFK = schemaFKs.find((fk) => {
125
+ return arraysEqual(fk.columns, contractFK.columns) && fk.referencedTable === contractFK.references.table && arraysEqual(fk.referencedColumns, contractFK.references.columns);
126
+ });
127
+ if (!matchingFK) {
128
+ issues.push({
129
+ kind: "foreign_key_mismatch",
130
+ table: tableName,
131
+ expected: `${contractFK.columns.join(", ")} -> ${contractFK.references.table}(${contractFK.references.columns.join(", ")})`,
132
+ message: `Table "${tableName}" is missing foreign key: ${contractFK.columns.join(", ")} -> ${contractFK.references.table}(${contractFK.references.columns.join(", ")})`
133
+ });
134
+ nodes.push({
135
+ status: "fail",
136
+ kind: "foreignKey",
137
+ name: `foreignKey(${contractFK.columns.join(", ")})`,
138
+ contractPath: fkPath,
139
+ code: "foreign_key_mismatch",
140
+ message: "Foreign key missing",
141
+ expected: contractFK,
142
+ actual: void 0,
143
+ children: []
144
+ });
145
+ } else {
146
+ if (contractFK.name && matchingFK.name && contractFK.name !== matchingFK.name) {
147
+ issues.push({
148
+ kind: "foreign_key_mismatch",
149
+ table: tableName,
150
+ indexOrConstraint: contractFK.name,
151
+ expected: contractFK.name,
152
+ actual: matchingFK.name,
153
+ message: `Table "${tableName}" has foreign key name mismatch: expected "${contractFK.name}", got "${matchingFK.name}"`
154
+ });
155
+ nodes.push({
156
+ status: "fail",
157
+ kind: "foreignKey",
158
+ name: `foreignKey(${contractFK.columns.join(", ")})`,
159
+ contractPath: fkPath,
160
+ code: "foreign_key_mismatch",
161
+ message: "Foreign key name mismatch",
162
+ expected: contractFK.name,
163
+ actual: matchingFK.name,
164
+ children: []
165
+ });
166
+ } else {
167
+ nodes.push({
168
+ status: "pass",
169
+ kind: "foreignKey",
170
+ name: `foreignKey(${contractFK.columns.join(", ")})`,
171
+ contractPath: fkPath,
172
+ code: "",
173
+ message: "",
174
+ expected: void 0,
175
+ actual: void 0,
176
+ children: []
177
+ });
178
+ }
179
+ }
180
+ }
181
+ if (strict) {
182
+ for (const schemaFK of schemaFKs) {
183
+ const matchingFK = contractFKs.find((fk) => {
184
+ return arraysEqual(fk.columns, schemaFK.columns) && fk.references.table === schemaFK.referencedTable && arraysEqual(fk.references.columns, schemaFK.referencedColumns);
185
+ });
186
+ if (!matchingFK) {
187
+ issues.push({
188
+ kind: "foreign_key_mismatch",
189
+ table: tableName,
190
+ message: `Extra foreign key found in database (not in contract): ${schemaFK.columns.join(", ")} -> ${schemaFK.referencedTable}(${schemaFK.referencedColumns.join(", ")})`
191
+ });
192
+ nodes.push({
193
+ status: "fail",
194
+ kind: "foreignKey",
195
+ name: `foreignKey(${schemaFK.columns.join(", ")})`,
196
+ contractPath: `${tablePath}.foreignKeys[${schemaFK.columns.join(",")}]`,
197
+ code: "extra_foreign_key",
198
+ message: "Extra foreign key found",
199
+ expected: void 0,
200
+ actual: schemaFK,
201
+ children: []
202
+ });
203
+ }
204
+ }
205
+ }
206
+ return nodes;
207
+ }
208
+ function compareUniqueConstraints(contractUniques, schemaUniques, tableName, tablePath, issues, strict) {
209
+ const nodes = [];
210
+ for (const contractUnique of contractUniques) {
211
+ const uniquePath = `${tablePath}.uniques[${contractUnique.columns.join(",")}]`;
212
+ const matchingUnique = schemaUniques.find(
213
+ (u) => arraysEqual(u.columns, contractUnique.columns)
214
+ );
215
+ if (!matchingUnique) {
216
+ issues.push({
217
+ kind: "unique_constraint_mismatch",
218
+ table: tableName,
219
+ expected: contractUnique.columns.join(", "),
220
+ message: `Table "${tableName}" is missing unique constraint: ${contractUnique.columns.join(", ")}`
221
+ });
222
+ nodes.push({
223
+ status: "fail",
224
+ kind: "unique",
225
+ name: `unique(${contractUnique.columns.join(", ")})`,
226
+ contractPath: uniquePath,
227
+ code: "unique_constraint_mismatch",
228
+ message: "Unique constraint missing",
229
+ expected: contractUnique,
230
+ actual: void 0,
231
+ children: []
232
+ });
233
+ } else {
234
+ if (contractUnique.name && matchingUnique.name && contractUnique.name !== matchingUnique.name) {
235
+ issues.push({
236
+ kind: "unique_constraint_mismatch",
237
+ table: tableName,
238
+ indexOrConstraint: contractUnique.name,
239
+ expected: contractUnique.name,
240
+ actual: matchingUnique.name,
241
+ message: `Table "${tableName}" has unique constraint name mismatch: expected "${contractUnique.name}", got "${matchingUnique.name}"`
242
+ });
243
+ nodes.push({
244
+ status: "fail",
245
+ kind: "unique",
246
+ name: `unique(${contractUnique.columns.join(", ")})`,
247
+ contractPath: uniquePath,
248
+ code: "unique_constraint_mismatch",
249
+ message: "Unique constraint name mismatch",
250
+ expected: contractUnique.name,
251
+ actual: matchingUnique.name,
252
+ children: []
253
+ });
254
+ } else {
255
+ nodes.push({
256
+ status: "pass",
257
+ kind: "unique",
258
+ name: `unique(${contractUnique.columns.join(", ")})`,
259
+ contractPath: uniquePath,
260
+ code: "",
261
+ message: "",
262
+ expected: void 0,
263
+ actual: void 0,
264
+ children: []
265
+ });
266
+ }
267
+ }
268
+ }
269
+ if (strict) {
270
+ for (const schemaUnique of schemaUniques) {
271
+ const matchingUnique = contractUniques.find(
272
+ (u) => arraysEqual(u.columns, schemaUnique.columns)
273
+ );
274
+ if (!matchingUnique) {
275
+ issues.push({
276
+ kind: "unique_constraint_mismatch",
277
+ table: tableName,
278
+ message: `Extra unique constraint found in database (not in contract): ${schemaUnique.columns.join(", ")}`
279
+ });
280
+ nodes.push({
281
+ status: "fail",
282
+ kind: "unique",
283
+ name: `unique(${schemaUnique.columns.join(", ")})`,
284
+ contractPath: `${tablePath}.uniques[${schemaUnique.columns.join(",")}]`,
285
+ code: "extra_unique_constraint",
286
+ message: "Extra unique constraint found",
287
+ expected: void 0,
288
+ actual: schemaUnique,
289
+ children: []
290
+ });
291
+ }
292
+ }
293
+ }
294
+ return nodes;
295
+ }
296
+ function compareIndexes(contractIndexes, schemaIndexes, tableName, tablePath, issues, strict) {
297
+ const nodes = [];
298
+ for (const contractIndex of contractIndexes) {
299
+ const indexPath = `${tablePath}.indexes[${contractIndex.columns.join(",")}]`;
300
+ const matchingIndex = schemaIndexes.find(
301
+ (idx) => arraysEqual(idx.columns, contractIndex.columns) && idx.unique === false
302
+ );
303
+ if (!matchingIndex) {
304
+ issues.push({
305
+ kind: "index_mismatch",
306
+ table: tableName,
307
+ expected: contractIndex.columns.join(", "),
308
+ message: `Table "${tableName}" is missing index: ${contractIndex.columns.join(", ")}`
309
+ });
310
+ nodes.push({
311
+ status: "fail",
312
+ kind: "index",
313
+ name: `index(${contractIndex.columns.join(", ")})`,
314
+ contractPath: indexPath,
315
+ code: "index_mismatch",
316
+ message: "Index missing",
317
+ expected: contractIndex,
318
+ actual: void 0,
319
+ children: []
320
+ });
321
+ } else {
322
+ if (contractIndex.name && matchingIndex.name && contractIndex.name !== matchingIndex.name) {
323
+ issues.push({
324
+ kind: "index_mismatch",
325
+ table: tableName,
326
+ indexOrConstraint: contractIndex.name,
327
+ expected: contractIndex.name,
328
+ actual: matchingIndex.name,
329
+ message: `Table "${tableName}" has index name mismatch: expected "${contractIndex.name}", got "${matchingIndex.name}"`
330
+ });
331
+ nodes.push({
332
+ status: "fail",
333
+ kind: "index",
334
+ name: `index(${contractIndex.columns.join(", ")})`,
335
+ contractPath: indexPath,
336
+ code: "index_mismatch",
337
+ message: "Index name mismatch",
338
+ expected: contractIndex.name,
339
+ actual: matchingIndex.name,
340
+ children: []
341
+ });
342
+ } else {
343
+ nodes.push({
344
+ status: "pass",
345
+ kind: "index",
346
+ name: `index(${contractIndex.columns.join(", ")})`,
347
+ contractPath: indexPath,
348
+ code: "",
349
+ message: "",
350
+ expected: void 0,
351
+ actual: void 0,
352
+ children: []
353
+ });
354
+ }
355
+ }
356
+ }
357
+ if (strict) {
358
+ for (const schemaIndex of schemaIndexes) {
359
+ if (schemaIndex.unique) {
360
+ continue;
361
+ }
362
+ const matchingIndex = contractIndexes.find(
363
+ (idx) => arraysEqual(idx.columns, schemaIndex.columns)
364
+ );
365
+ if (!matchingIndex) {
366
+ issues.push({
367
+ kind: "index_mismatch",
368
+ table: tableName,
369
+ message: `Extra index found in database (not in contract): ${schemaIndex.columns.join(", ")}`
370
+ });
371
+ nodes.push({
372
+ status: "fail",
373
+ kind: "index",
374
+ name: `index(${schemaIndex.columns.join(", ")})`,
375
+ contractPath: `${tablePath}.indexes[${schemaIndex.columns.join(",")}]`,
376
+ code: "extra_index",
377
+ message: "Extra index found",
378
+ expected: void 0,
379
+ actual: schemaIndex,
380
+ children: []
381
+ });
382
+ }
383
+ }
384
+ }
385
+ return nodes;
386
+ }
387
+ function compareExtensions(contractExtensions, schemaExtensions, contractTarget, issues, _strict) {
388
+ const nodes = [];
389
+ if (!contractExtensions) {
390
+ return nodes;
391
+ }
392
+ const contractExtensionNames = Object.keys(contractExtensions).filter(
393
+ (name) => name !== contractTarget
394
+ );
395
+ for (const extName of contractExtensionNames) {
396
+ const extPath = `extensions.${extName}`;
397
+ const normalizedExtName = extName.toLowerCase().replace(/^pg/, "");
398
+ const matchingExt = schemaExtensions.find((e) => {
399
+ const normalizedE = e.toLowerCase();
400
+ if (normalizedE === normalizedExtName || normalizedE === extName.toLowerCase()) {
401
+ return true;
402
+ }
403
+ if (normalizedE.includes(normalizedExtName) || normalizedExtName.includes(normalizedE)) {
404
+ return true;
405
+ }
406
+ return false;
407
+ });
408
+ const extensionLabels = {
409
+ pg: "database is postgres",
410
+ pgvector: "vector extension is enabled",
411
+ vector: "vector extension is enabled"
412
+ };
413
+ const extensionLabel = extensionLabels[extName] ?? `extension "${extName}" is enabled`;
414
+ if (!matchingExt) {
415
+ issues.push({
416
+ kind: "extension_missing",
417
+ table: "",
418
+ message: `Extension "${extName}" is missing from database`
419
+ });
420
+ nodes.push({
421
+ status: "fail",
422
+ kind: "extension",
423
+ name: extensionLabel,
424
+ contractPath: extPath,
425
+ code: "extension_missing",
426
+ message: `Extension "${extName}" is missing`,
427
+ expected: void 0,
428
+ actual: void 0,
429
+ children: []
430
+ });
431
+ } else {
432
+ nodes.push({
433
+ status: "pass",
434
+ kind: "extension",
435
+ name: extensionLabel,
436
+ contractPath: extPath,
437
+ code: "",
438
+ message: "",
439
+ expected: void 0,
440
+ actual: void 0,
441
+ children: []
442
+ });
443
+ }
444
+ }
445
+ return nodes;
446
+ }
447
+ function computeCounts(node) {
448
+ let pass = 0;
449
+ let warn = 0;
450
+ let fail = 0;
451
+ function traverse(n) {
452
+ if (n.status === "pass") {
453
+ pass++;
454
+ } else if (n.status === "warn") {
455
+ warn++;
456
+ } else if (n.status === "fail") {
457
+ fail++;
458
+ }
459
+ if (n.children) {
460
+ for (const child of n.children) {
461
+ traverse(child);
462
+ }
463
+ }
464
+ }
465
+ traverse(node);
466
+ return {
467
+ pass,
468
+ warn,
469
+ fail,
470
+ totalNodes: pass + warn + fail
471
+ };
472
+ }
473
+ function createVerifyResult(options) {
474
+ const contract = {
475
+ coreHash: options.contractCoreHash
476
+ };
477
+ if (options.contractProfileHash) {
478
+ contract.profileHash = options.contractProfileHash;
479
+ }
480
+ const target = {
481
+ expected: options.expectedTargetId
482
+ };
483
+ if (options.actualTargetId) {
484
+ target.actual = options.actualTargetId;
485
+ }
486
+ const meta = {
487
+ contractPath: options.contractPath
488
+ };
489
+ if (options.configPath) {
490
+ meta.configPath = options.configPath;
491
+ }
492
+ const result = {
493
+ ok: options.ok,
494
+ summary: options.summary,
495
+ contract,
496
+ target,
497
+ meta,
498
+ timings: {
499
+ total: options.totalTime
500
+ }
501
+ };
502
+ if (options.code) {
503
+ result.code = options.code;
504
+ }
505
+ if (options.marker) {
506
+ result.marker = {
507
+ coreHash: options.marker.coreHash,
508
+ profileHash: options.marker.profileHash
509
+ };
510
+ }
511
+ if (options.missingCodecs) {
512
+ result.missingCodecs = options.missingCodecs;
513
+ }
514
+ if (options.codecCoverageSkipped) {
515
+ result.codecCoverageSkipped = options.codecCoverageSkipped;
516
+ }
517
+ return result;
518
+ }
519
+ function buildSqlTypeMetadataRegistry(options) {
520
+ const { target, adapter, extensions } = options;
521
+ const registry = /* @__PURE__ */ new Map();
522
+ const targetId = adapter.targetId;
523
+ const descriptors = [target, adapter, ...extensions];
524
+ for (const descriptor of descriptors) {
525
+ const manifest = descriptor.manifest;
526
+ const storageTypes = manifest.types?.storage;
527
+ if (!storageTypes) {
528
+ continue;
529
+ }
530
+ for (const storageType of storageTypes) {
531
+ if (storageType.familyId === "sql" && storageType.targetId === targetId) {
532
+ registry.set(storageType.typeId, {
533
+ typeId: storageType.typeId,
534
+ familyId: "sql",
535
+ targetId: storageType.targetId,
536
+ ...storageType.nativeType !== void 0 ? { nativeType: storageType.nativeType } : {}
537
+ });
538
+ }
539
+ }
540
+ }
541
+ return registry;
542
+ }
543
+ function createSqlFamilyInstance(options) {
544
+ const { target, adapter, extensions } = options;
545
+ const descriptors = [target, adapter, ...extensions];
546
+ const operationRegistry = assembleOperationRegistry(descriptors, convertOperationManifest);
547
+ const codecTypeImports = extractCodecTypeImports(descriptors);
548
+ const operationTypeImports = extractOperationTypeImports(descriptors);
549
+ const extensionIds = extractExtensionIds(adapter, target, extensions);
550
+ const typeMetadataRegistry = buildSqlTypeMetadataRegistry({ target, adapter, extensions });
551
+ function stripMappings(contract) {
552
+ if (typeof contract === "object" && contract !== null && "mappings" in contract) {
553
+ const { mappings: _mappings, ...contractIR } = contract;
554
+ return contractIR;
555
+ }
556
+ return contract;
557
+ }
558
+ return {
559
+ familyId: "sql",
560
+ operationRegistry,
561
+ codecTypeImports,
562
+ operationTypeImports,
563
+ extensionIds,
564
+ typeMetadataRegistry,
565
+ validateContractIR(contractJson) {
566
+ const validated = validateContract(contractJson);
567
+ const { mappings: _mappings, ...contractIR } = validated;
568
+ return contractIR;
569
+ },
570
+ async verify(verifyOptions) {
571
+ const { driver, contractIR, expectedTargetId, contractPath, configPath } = verifyOptions;
572
+ const startTime = Date.now();
573
+ if (typeof contractIR !== "object" || contractIR === null || !("coreHash" in contractIR) || !("target" in contractIR) || typeof contractIR.coreHash !== "string" || typeof contractIR.target !== "string") {
574
+ throw new Error("Contract is missing required fields: coreHash or target");
575
+ }
576
+ const contractCoreHash = contractIR.coreHash;
577
+ const contractProfileHash = "profileHash" in contractIR && typeof contractIR.profileHash === "string" ? contractIR.profileHash : void 0;
578
+ const contractTarget = contractIR.target;
579
+ const marker = await readMarker(driver);
580
+ let missingCodecs;
581
+ let codecCoverageSkipped = false;
582
+ const supportedTypeIds = collectSupportedCodecTypeIds([
583
+ adapter,
584
+ target,
585
+ ...extensions
586
+ ]);
587
+ if (supportedTypeIds.length === 0) {
588
+ codecCoverageSkipped = true;
589
+ } else {
590
+ const supportedSet = new Set(supportedTypeIds);
591
+ const usedTypeIds = extractCodecTypeIdsFromContract(contractIR);
592
+ const missing = usedTypeIds.filter((id) => !supportedSet.has(id));
593
+ if (missing.length > 0) {
594
+ missingCodecs = missing;
595
+ }
596
+ }
597
+ if (!marker) {
598
+ const totalTime2 = Date.now() - startTime;
599
+ return createVerifyResult({
600
+ ok: false,
601
+ code: "PN-RTM-3001",
602
+ summary: "Marker missing",
603
+ contractCoreHash,
604
+ expectedTargetId,
605
+ contractPath,
606
+ totalTime: totalTime2,
607
+ ...contractProfileHash ? { contractProfileHash } : {},
608
+ ...missingCodecs ? { missingCodecs } : {},
609
+ ...codecCoverageSkipped ? { codecCoverageSkipped } : {},
610
+ ...configPath ? { configPath } : {}
611
+ });
612
+ }
613
+ if (contractTarget !== expectedTargetId) {
614
+ const totalTime2 = Date.now() - startTime;
615
+ return createVerifyResult({
616
+ ok: false,
617
+ code: "PN-RTM-3003",
618
+ summary: "Target mismatch",
619
+ contractCoreHash,
620
+ marker,
621
+ expectedTargetId,
622
+ actualTargetId: contractTarget,
623
+ contractPath,
624
+ totalTime: totalTime2,
625
+ ...contractProfileHash ? { contractProfileHash } : {},
626
+ ...missingCodecs ? { missingCodecs } : {},
627
+ ...codecCoverageSkipped ? { codecCoverageSkipped } : {},
628
+ ...configPath ? { configPath } : {}
629
+ });
630
+ }
631
+ if (marker.coreHash !== contractCoreHash) {
632
+ const totalTime2 = Date.now() - startTime;
633
+ return createVerifyResult({
634
+ ok: false,
635
+ code: "PN-RTM-3002",
636
+ summary: "Hash mismatch",
637
+ contractCoreHash,
638
+ marker,
639
+ expectedTargetId,
640
+ contractPath,
641
+ totalTime: totalTime2,
642
+ ...contractProfileHash ? { contractProfileHash } : {},
643
+ ...missingCodecs ? { missingCodecs } : {},
644
+ ...codecCoverageSkipped ? { codecCoverageSkipped } : {},
645
+ ...configPath ? { configPath } : {}
646
+ });
647
+ }
648
+ if (contractProfileHash && marker.profileHash !== contractProfileHash) {
649
+ const totalTime2 = Date.now() - startTime;
650
+ return createVerifyResult({
651
+ ok: false,
652
+ code: "PN-RTM-3002",
653
+ summary: "Hash mismatch",
654
+ contractCoreHash,
655
+ contractProfileHash,
656
+ marker,
657
+ expectedTargetId,
658
+ contractPath,
659
+ totalTime: totalTime2,
660
+ ...missingCodecs ? { missingCodecs } : {},
661
+ ...codecCoverageSkipped ? { codecCoverageSkipped } : {},
662
+ ...configPath ? { configPath } : {}
663
+ });
664
+ }
665
+ const totalTime = Date.now() - startTime;
666
+ return createVerifyResult({
667
+ ok: true,
668
+ summary: "Database matches contract",
669
+ contractCoreHash,
670
+ marker,
671
+ expectedTargetId,
672
+ contractPath,
673
+ totalTime,
674
+ ...contractProfileHash ? { contractProfileHash } : {},
675
+ ...missingCodecs ? { missingCodecs } : {},
676
+ ...codecCoverageSkipped ? { codecCoverageSkipped } : {},
677
+ ...configPath ? { configPath } : {}
678
+ });
679
+ },
680
+ async schemaVerify(options2) {
681
+ const { driver, contractIR, strict, contractPath, configPath } = options2;
682
+ const startTime = Date.now();
683
+ const contract = validateContract(contractIR);
684
+ const contractCoreHash = contract.coreHash;
685
+ const contractProfileHash = "profileHash" in contract && typeof contract.profileHash === "string" ? contract.profileHash : void 0;
686
+ const contractTarget = contract.target;
687
+ const controlAdapter = adapter.create();
688
+ const schemaIR = await controlAdapter.introspect(
689
+ driver,
690
+ contractIR
691
+ );
692
+ const issues = [];
693
+ const rootChildren = [];
694
+ const contractTables = contract.storage.tables;
695
+ const schemaTables = schemaIR.tables;
696
+ for (const [tableName, contractTable] of Object.entries(contractTables)) {
697
+ const schemaTable = schemaTables[tableName];
698
+ const tablePath = `storage.tables.${tableName}`;
699
+ if (!schemaTable) {
700
+ issues.push({
701
+ kind: "missing_table",
702
+ table: tableName,
703
+ message: `Table "${tableName}" is missing from database`
704
+ });
705
+ rootChildren.push({
706
+ status: "fail",
707
+ kind: "table",
708
+ name: `table ${tableName}`,
709
+ contractPath: tablePath,
710
+ code: "missing_table",
711
+ message: `Table "${tableName}" is missing`,
712
+ expected: void 0,
713
+ actual: void 0,
714
+ children: []
715
+ });
716
+ continue;
717
+ }
718
+ const tableChildren = [];
719
+ const columnNodes = [];
720
+ for (const [columnName, contractColumn] of Object.entries(contractTable.columns)) {
721
+ const schemaColumn = schemaTable.columns[columnName];
722
+ const columnPath = `${tablePath}.columns.${columnName}`;
723
+ if (!schemaColumn) {
724
+ issues.push({
725
+ kind: "missing_column",
726
+ table: tableName,
727
+ column: columnName,
728
+ message: `Column "${tableName}"."${columnName}" is missing from database`
729
+ });
730
+ columnNodes.push({
731
+ status: "fail",
732
+ kind: "column",
733
+ name: `${columnName}: missing`,
734
+ contractPath: columnPath,
735
+ code: "missing_column",
736
+ message: `Column "${columnName}" is missing`,
737
+ expected: void 0,
738
+ actual: void 0,
739
+ children: []
740
+ });
741
+ continue;
742
+ }
743
+ const columnChildren = [];
744
+ let columnStatus = "pass";
745
+ const contractNativeType = contractColumn.nativeType;
746
+ const schemaNativeType = schemaColumn.nativeType;
747
+ if (!contractNativeType) {
748
+ issues.push({
749
+ kind: "type_mismatch",
750
+ table: tableName,
751
+ column: columnName,
752
+ expected: "nativeType required",
753
+ actual: schemaNativeType || "unknown",
754
+ message: `Column "${tableName}"."${columnName}" is missing nativeType in contract`
755
+ });
756
+ columnChildren.push({
757
+ status: "fail",
758
+ kind: "type",
759
+ name: "type",
760
+ contractPath: `${columnPath}.nativeType`,
761
+ code: "type_mismatch",
762
+ message: "Contract column is missing nativeType",
763
+ expected: "nativeType required",
764
+ actual: schemaNativeType || "unknown",
765
+ children: []
766
+ });
767
+ columnStatus = "fail";
768
+ } else if (!schemaNativeType) {
769
+ issues.push({
770
+ kind: "type_mismatch",
771
+ table: tableName,
772
+ column: columnName,
773
+ expected: contractNativeType,
774
+ actual: "unknown",
775
+ message: `Column "${tableName}"."${columnName}" has type mismatch: schema column has no nativeType`
776
+ });
777
+ columnChildren.push({
778
+ status: "fail",
779
+ kind: "type",
780
+ name: "type",
781
+ contractPath: `${columnPath}.nativeType`,
782
+ code: "type_mismatch",
783
+ message: "Schema column has no nativeType",
784
+ expected: contractNativeType,
785
+ actual: "unknown",
786
+ children: []
787
+ });
788
+ columnStatus = "fail";
789
+ } else if (contractNativeType !== schemaNativeType) {
790
+ issues.push({
791
+ kind: "type_mismatch",
792
+ table: tableName,
793
+ column: columnName,
794
+ expected: contractNativeType,
795
+ actual: schemaNativeType,
796
+ message: `Column "${tableName}"."${columnName}" has type mismatch: expected "${contractNativeType}", got "${schemaNativeType}"`
797
+ });
798
+ columnChildren.push({
799
+ status: "fail",
800
+ kind: "type",
801
+ name: "type",
802
+ contractPath: `${columnPath}.nativeType`,
803
+ code: "type_mismatch",
804
+ message: `Type mismatch: expected ${contractNativeType}, got ${schemaNativeType}`,
805
+ expected: contractNativeType,
806
+ actual: schemaNativeType,
807
+ children: []
808
+ });
809
+ columnStatus = "fail";
810
+ }
811
+ if (contractColumn.codecId) {
812
+ const typeMetadata = typeMetadataRegistry.get(contractColumn.codecId);
813
+ if (!typeMetadata) {
814
+ columnChildren.push({
815
+ status: "warn",
816
+ kind: "type",
817
+ name: "type_metadata_missing",
818
+ contractPath: `${columnPath}.codecId`,
819
+ code: "type_metadata_missing",
820
+ message: `codecId "${contractColumn.codecId}" not found in type metadata registry`,
821
+ expected: contractColumn.codecId,
822
+ actual: void 0,
823
+ children: []
824
+ });
825
+ } else if (typeMetadata.nativeType && typeMetadata.nativeType !== contractNativeType) {
826
+ columnChildren.push({
827
+ status: "warn",
828
+ kind: "type",
829
+ name: "type_consistency",
830
+ contractPath: `${columnPath}.codecId`,
831
+ code: "type_consistency_warning",
832
+ message: `codecId "${contractColumn.codecId}" maps to nativeType "${typeMetadata.nativeType}" in registry, but contract has "${contractNativeType}"`,
833
+ expected: typeMetadata.nativeType,
834
+ actual: contractNativeType,
835
+ children: []
836
+ });
837
+ }
838
+ }
839
+ if (contractColumn.nullable !== schemaColumn.nullable) {
840
+ issues.push({
841
+ kind: "nullability_mismatch",
842
+ table: tableName,
843
+ column: columnName,
844
+ expected: String(contractColumn.nullable),
845
+ actual: String(schemaColumn.nullable),
846
+ message: `Column "${tableName}"."${columnName}" has nullability mismatch: expected ${contractColumn.nullable ? "nullable" : "not null"}, got ${schemaColumn.nullable ? "nullable" : "not null"}`
847
+ });
848
+ columnChildren.push({
849
+ status: "fail",
850
+ kind: "nullability",
851
+ name: "nullability",
852
+ contractPath: `${columnPath}.nullable`,
853
+ code: "nullability_mismatch",
854
+ message: `Nullability mismatch: expected ${contractColumn.nullable ? "nullable" : "not null"}, got ${schemaColumn.nullable ? "nullable" : "not null"}`,
855
+ expected: contractColumn.nullable,
856
+ actual: schemaColumn.nullable,
857
+ children: []
858
+ });
859
+ columnStatus = "fail";
860
+ }
861
+ const computedColumnStatus = columnChildren.some((c) => c.status === "fail") ? "fail" : columnChildren.some((c) => c.status === "warn") ? "warn" : "pass";
862
+ const finalColumnStatus = columnChildren.length > 0 ? computedColumnStatus : columnStatus;
863
+ const nullableText = contractColumn.nullable ? "nullable" : "not nullable";
864
+ const columnTypeDisplay = contractColumn.codecId ? `${contractNativeType} (${contractColumn.codecId})` : contractNativeType;
865
+ const failureMessages = columnChildren.filter((child) => child.status === "fail" && child.message).map((child) => child.message).filter((msg) => typeof msg === "string" && msg.length > 0);
866
+ const columnMessage = finalColumnStatus === "fail" && failureMessages.length > 0 ? failureMessages.join("; ") : "";
867
+ const columnCode = finalColumnStatus === "fail" && columnChildren.length > 0 && columnChildren[0] ? columnChildren[0].code : finalColumnStatus === "warn" && columnChildren.length > 0 && columnChildren[0] ? columnChildren[0].code : "";
868
+ columnNodes.push({
869
+ status: finalColumnStatus,
870
+ kind: "column",
871
+ name: `${columnName}: ${columnTypeDisplay} (${nullableText})`,
872
+ contractPath: columnPath,
873
+ code: columnCode,
874
+ message: columnMessage,
875
+ expected: void 0,
876
+ actual: void 0,
877
+ children: columnChildren
878
+ });
879
+ }
880
+ if (columnNodes.length > 0) {
881
+ const columnsStatus = columnNodes.some((c) => c.status === "fail") ? "fail" : columnNodes.some((c) => c.status === "warn") ? "warn" : "pass";
882
+ tableChildren.push({
883
+ status: columnsStatus,
884
+ kind: "columns",
885
+ name: "columns",
886
+ contractPath: `${tablePath}.columns`,
887
+ code: "",
888
+ message: "",
889
+ expected: void 0,
890
+ actual: void 0,
891
+ children: columnNodes
892
+ });
893
+ }
894
+ if (strict) {
895
+ for (const [columnName, schemaColumn] of Object.entries(schemaTable.columns)) {
896
+ if (!contractTable.columns[columnName]) {
897
+ issues.push({
898
+ kind: "missing_column",
899
+ table: tableName,
900
+ column: columnName,
901
+ message: `Extra column "${tableName}"."${columnName}" found in database (not in contract)`
902
+ });
903
+ columnNodes.push({
904
+ status: "fail",
905
+ kind: "column",
906
+ name: `${columnName}: extra`,
907
+ contractPath: `${tablePath}.columns.${columnName}`,
908
+ code: "extra_column",
909
+ message: `Extra column "${columnName}" found`,
910
+ expected: void 0,
911
+ actual: schemaColumn.nativeType,
912
+ children: []
913
+ });
914
+ }
915
+ }
916
+ }
917
+ if (contractTable.primaryKey) {
918
+ const pkStatus = comparePrimaryKey(
919
+ contractTable.primaryKey,
920
+ schemaTable.primaryKey,
921
+ tableName,
922
+ issues
923
+ );
924
+ if (pkStatus === "fail") {
925
+ tableChildren.push({
926
+ status: "fail",
927
+ kind: "primaryKey",
928
+ name: `primary key: ${contractTable.primaryKey.columns.join(", ")}`,
929
+ contractPath: `${tablePath}.primaryKey`,
930
+ code: "primary_key_mismatch",
931
+ message: "Primary key mismatch",
932
+ expected: contractTable.primaryKey,
933
+ actual: schemaTable.primaryKey,
934
+ children: []
935
+ });
936
+ } else {
937
+ tableChildren.push({
938
+ status: "pass",
939
+ kind: "primaryKey",
940
+ name: `primary key: ${contractTable.primaryKey.columns.join(", ")}`,
941
+ contractPath: `${tablePath}.primaryKey`,
942
+ code: "",
943
+ message: "",
944
+ expected: void 0,
945
+ actual: void 0,
946
+ children: []
947
+ });
948
+ }
949
+ } else if (schemaTable.primaryKey && strict) {
950
+ issues.push({
951
+ kind: "primary_key_mismatch",
952
+ table: tableName,
953
+ message: "Extra primary key found in database (not in contract)"
954
+ });
955
+ tableChildren.push({
956
+ status: "fail",
957
+ kind: "primaryKey",
958
+ name: `primary key: ${schemaTable.primaryKey.columns.join(", ")}`,
959
+ contractPath: `${tablePath}.primaryKey`,
960
+ code: "extra_primary_key",
961
+ message: "Extra primary key found",
962
+ expected: void 0,
963
+ actual: schemaTable.primaryKey,
964
+ children: []
965
+ });
966
+ }
967
+ const fkStatuses = compareForeignKeys(
968
+ contractTable.foreignKeys,
969
+ schemaTable.foreignKeys,
970
+ tableName,
971
+ tablePath,
972
+ issues,
973
+ strict
974
+ );
975
+ tableChildren.push(...fkStatuses);
976
+ const uniqueStatuses = compareUniqueConstraints(
977
+ contractTable.uniques,
978
+ schemaTable.uniques,
979
+ tableName,
980
+ tablePath,
981
+ issues,
982
+ strict
983
+ );
984
+ tableChildren.push(...uniqueStatuses);
985
+ const indexStatuses = compareIndexes(
986
+ contractTable.indexes,
987
+ schemaTable.indexes,
988
+ tableName,
989
+ tablePath,
990
+ issues,
991
+ strict
992
+ );
993
+ tableChildren.push(...indexStatuses);
994
+ const tableStatus = tableChildren.some((c) => c.status === "fail") ? "fail" : tableChildren.some((c) => c.status === "warn") ? "warn" : "pass";
995
+ const tableFailureMessages = tableChildren.filter((child) => child.status === "fail" && child.message).map((child) => child.message).filter((msg) => typeof msg === "string" && msg.length > 0);
996
+ const tableMessage = tableStatus === "fail" && tableFailureMessages.length > 0 ? `${tableFailureMessages.length} issue${tableFailureMessages.length === 1 ? "" : "s"}` : "";
997
+ const tableCode = tableStatus === "fail" && tableChildren.length > 0 && tableChildren[0] ? tableChildren[0].code : "";
998
+ rootChildren.push({
999
+ status: tableStatus,
1000
+ kind: "table",
1001
+ name: `table ${tableName}`,
1002
+ contractPath: tablePath,
1003
+ code: tableCode,
1004
+ message: tableMessage,
1005
+ expected: void 0,
1006
+ actual: void 0,
1007
+ children: tableChildren
1008
+ });
1009
+ }
1010
+ if (strict) {
1011
+ for (const tableName of Object.keys(schemaTables)) {
1012
+ if (!contractTables[tableName]) {
1013
+ issues.push({
1014
+ kind: "missing_table",
1015
+ table: tableName,
1016
+ message: `Extra table "${tableName}" found in database (not in contract)`
1017
+ });
1018
+ rootChildren.push({
1019
+ status: "fail",
1020
+ kind: "table",
1021
+ name: `table ${tableName}`,
1022
+ contractPath: `storage.tables.${tableName}`,
1023
+ code: "extra_table",
1024
+ message: `Extra table "${tableName}" found`,
1025
+ expected: void 0,
1026
+ actual: void 0,
1027
+ children: []
1028
+ });
1029
+ }
1030
+ }
1031
+ }
1032
+ const extensionStatuses = compareExtensions(
1033
+ contract.extensions,
1034
+ schemaIR.extensions,
1035
+ contractTarget,
1036
+ issues,
1037
+ strict
1038
+ );
1039
+ rootChildren.push(...extensionStatuses);
1040
+ const rootStatus = rootChildren.some((c) => c.status === "fail") ? "fail" : rootChildren.some((c) => c.status === "warn") ? "warn" : "pass";
1041
+ const root = {
1042
+ status: rootStatus,
1043
+ kind: "contract",
1044
+ name: "contract",
1045
+ contractPath: "",
1046
+ code: "",
1047
+ message: "",
1048
+ expected: void 0,
1049
+ actual: void 0,
1050
+ children: rootChildren
1051
+ };
1052
+ const counts = computeCounts(root);
1053
+ const ok = counts.fail === 0;
1054
+ const code = ok ? void 0 : "PN-SCHEMA-0001";
1055
+ const summary = ok ? "Database schema satisfies contract" : `Database schema does not satisfy contract (${counts.fail} failure${counts.fail === 1 ? "" : "s"})`;
1056
+ const totalTime = Date.now() - startTime;
1057
+ return {
1058
+ ok,
1059
+ ...code ? { code } : {},
1060
+ summary,
1061
+ contract: {
1062
+ coreHash: contractCoreHash,
1063
+ ...contractProfileHash ? { profileHash: contractProfileHash } : {}
1064
+ },
1065
+ target: {
1066
+ expected: contractTarget,
1067
+ actual: contractTarget
1068
+ },
1069
+ schema: {
1070
+ issues,
1071
+ root,
1072
+ counts
1073
+ },
1074
+ meta: {
1075
+ contractPath,
1076
+ strict,
1077
+ ...configPath ? { configPath } : {}
1078
+ },
1079
+ timings: {
1080
+ total: totalTime
1081
+ }
1082
+ };
1083
+ },
1084
+ async sign(options2) {
1085
+ const { driver, contractIR, contractPath, configPath } = options2;
1086
+ const startTime = Date.now();
1087
+ const contract = validateContract(contractIR);
1088
+ const contractCoreHash = contract.coreHash;
1089
+ const contractProfileHash = "profileHash" in contract && typeof contract.profileHash === "string" ? contract.profileHash : contractCoreHash;
1090
+ const contractTarget = contract.target;
1091
+ await driver.query(ensureSchemaStatement.sql, ensureSchemaStatement.params);
1092
+ await driver.query(ensureTableStatement.sql, ensureTableStatement.params);
1093
+ const existingMarker = await readMarker(driver);
1094
+ let markerCreated = false;
1095
+ let markerUpdated = false;
1096
+ let previousHashes;
1097
+ if (!existingMarker) {
1098
+ const write = writeContractMarker({
1099
+ coreHash: contractCoreHash,
1100
+ profileHash: contractProfileHash,
1101
+ contractJson: contractIR,
1102
+ canonicalVersion: 1
1103
+ });
1104
+ await driver.query(write.insert.sql, write.insert.params);
1105
+ markerCreated = true;
1106
+ } else {
1107
+ const existingCoreHash = existingMarker.coreHash;
1108
+ const existingProfileHash = existingMarker.profileHash;
1109
+ const coreHashMatches = existingCoreHash === contractCoreHash;
1110
+ const profileHashMatches = existingProfileHash === contractProfileHash;
1111
+ if (!coreHashMatches || !profileHashMatches) {
1112
+ previousHashes = {
1113
+ coreHash: existingCoreHash,
1114
+ profileHash: existingProfileHash
1115
+ };
1116
+ const write = writeContractMarker({
1117
+ coreHash: contractCoreHash,
1118
+ profileHash: contractProfileHash,
1119
+ contractJson: contractIR,
1120
+ canonicalVersion: existingMarker.canonicalVersion ?? 1
1121
+ });
1122
+ await driver.query(write.update.sql, write.update.params);
1123
+ markerUpdated = true;
1124
+ }
1125
+ }
1126
+ let summary;
1127
+ if (markerCreated) {
1128
+ summary = "Database signed (marker created)";
1129
+ } else if (markerUpdated) {
1130
+ summary = `Database signed (marker updated from ${previousHashes?.coreHash ?? "unknown"})`;
1131
+ } else {
1132
+ summary = "Database already signed with this contract";
1133
+ }
1134
+ const totalTime = Date.now() - startTime;
1135
+ return {
1136
+ ok: true,
1137
+ summary,
1138
+ contract: {
1139
+ coreHash: contractCoreHash,
1140
+ profileHash: contractProfileHash
1141
+ },
1142
+ target: {
1143
+ expected: contractTarget,
1144
+ actual: contractTarget
1145
+ },
1146
+ marker: {
1147
+ created: markerCreated,
1148
+ updated: markerUpdated,
1149
+ ...previousHashes ? { previous: previousHashes } : {}
1150
+ },
1151
+ meta: {
1152
+ contractPath,
1153
+ ...configPath ? { configPath } : {}
1154
+ },
1155
+ timings: {
1156
+ total: totalTime
1157
+ }
1158
+ };
1159
+ },
1160
+ async introspect(options2) {
1161
+ const { driver, contractIR } = options2;
1162
+ const controlAdapter = adapter.create();
1163
+ return controlAdapter.introspect(driver, contractIR);
1164
+ },
1165
+ toSchemaView(schema) {
1166
+ const rootLabel = "contract";
1167
+ const tableNodes = Object.entries(schema.tables).map(
1168
+ ([tableName, table]) => {
1169
+ const children = [];
1170
+ const columnNodes = [];
1171
+ for (const [columnName, column] of Object.entries(table.columns)) {
1172
+ const nullableText = column.nullable ? "(nullable)" : "(not nullable)";
1173
+ const typeDisplay = column.nativeType;
1174
+ const label = `${columnName}: ${typeDisplay} ${nullableText}`;
1175
+ columnNodes.push({
1176
+ kind: "field",
1177
+ id: `column-${tableName}-${columnName}`,
1178
+ label,
1179
+ meta: {
1180
+ nativeType: column.nativeType,
1181
+ nullable: column.nullable
1182
+ }
1183
+ });
1184
+ }
1185
+ if (columnNodes.length > 0) {
1186
+ children.push({
1187
+ kind: "collection",
1188
+ id: `columns-${tableName}`,
1189
+ label: "columns",
1190
+ children: columnNodes
1191
+ });
1192
+ }
1193
+ if (table.primaryKey) {
1194
+ const pkColumns = table.primaryKey.columns.join(", ");
1195
+ children.push({
1196
+ kind: "index",
1197
+ id: `primary-key-${tableName}`,
1198
+ label: `primary key: ${pkColumns}`,
1199
+ meta: {
1200
+ columns: table.primaryKey.columns,
1201
+ ...table.primaryKey.name ? { name: table.primaryKey.name } : {}
1202
+ }
1203
+ });
1204
+ }
1205
+ for (const unique of table.uniques) {
1206
+ const name = unique.name ?? `${tableName}_${unique.columns.join("_")}_unique`;
1207
+ const label = `unique ${name}`;
1208
+ children.push({
1209
+ kind: "index",
1210
+ id: `unique-${tableName}-${name}`,
1211
+ label,
1212
+ meta: {
1213
+ columns: unique.columns,
1214
+ unique: true
1215
+ }
1216
+ });
1217
+ }
1218
+ for (const index of table.indexes) {
1219
+ const name = index.name ?? `${tableName}_${index.columns.join("_")}_idx`;
1220
+ const label = index.unique ? `unique index ${name}` : `index ${name}`;
1221
+ children.push({
1222
+ kind: "index",
1223
+ id: `index-${tableName}-${name}`,
1224
+ label,
1225
+ meta: {
1226
+ columns: index.columns,
1227
+ unique: index.unique
1228
+ }
1229
+ });
1230
+ }
1231
+ const tableMeta = {};
1232
+ if (table.primaryKey) {
1233
+ tableMeta["primaryKey"] = table.primaryKey.columns;
1234
+ if (table.primaryKey.name) {
1235
+ tableMeta["primaryKeyName"] = table.primaryKey.name;
1236
+ }
1237
+ }
1238
+ if (table.foreignKeys.length > 0) {
1239
+ tableMeta["foreignKeys"] = table.foreignKeys.map((fk) => ({
1240
+ columns: fk.columns,
1241
+ referencedTable: fk.referencedTable,
1242
+ referencedColumns: fk.referencedColumns,
1243
+ ...fk.name ? { name: fk.name } : {}
1244
+ }));
1245
+ }
1246
+ const node = {
1247
+ kind: "entity",
1248
+ id: `table-${tableName}`,
1249
+ label: `table ${tableName}`,
1250
+ ...Object.keys(tableMeta).length > 0 ? { meta: tableMeta } : {},
1251
+ ...children.length > 0 ? { children } : {}
1252
+ };
1253
+ return node;
1254
+ }
1255
+ );
1256
+ const extensionNodes = schema.extensions.map((extName) => ({
1257
+ kind: "extension",
1258
+ id: `extension-${extName}`,
1259
+ label: `${extName} extension is enabled`
1260
+ }));
1261
+ const rootChildren = [...tableNodes, ...extensionNodes];
1262
+ const rootNode = {
1263
+ kind: "root",
1264
+ id: "sql-schema",
1265
+ label: rootLabel,
1266
+ ...rootChildren.length > 0 ? { children: rootChildren } : {}
1267
+ };
1268
+ return {
1269
+ root: rootNode
1270
+ };
1271
+ },
1272
+ async emitContract({ contractIR }) {
1273
+ const contractWithoutMappings = stripMappings(contractIR);
1274
+ const validatedIR = this.validateContractIR(contractWithoutMappings);
1275
+ const result = await emit(
1276
+ validatedIR,
1277
+ {
1278
+ outputDir: "",
1279
+ operationRegistry,
1280
+ codecTypeImports,
1281
+ operationTypeImports,
1282
+ extensionIds
1283
+ },
1284
+ sqlTargetFamilyHook
1285
+ );
1286
+ return {
1287
+ contractJson: result.contractJson,
1288
+ contractDts: result.contractDts,
1289
+ coreHash: result.coreHash,
1290
+ profileHash: result.profileHash
1291
+ };
1292
+ }
1293
+ };
1294
+ }
1295
+
1296
+ // src/core/assembly.ts
1297
+ function assembleOperationRegistry(descriptors, convertOperationManifest2) {
1298
+ const registry = createOperationRegistry();
1299
+ for (const descriptor of descriptors) {
1300
+ const operations = descriptor.manifest.operations ?? [];
1301
+ for (const operationManifest of operations) {
1302
+ const signature = convertOperationManifest2(operationManifest);
1303
+ registry.register(signature);
1304
+ }
1305
+ }
1306
+ return registry;
1307
+ }
1308
+ function extractCodecTypeImports(descriptors) {
1309
+ const imports = [];
1310
+ for (const descriptor of descriptors) {
1311
+ const codecTypes = descriptor.manifest.types?.codecTypes;
1312
+ if (codecTypes?.import) {
1313
+ imports.push(codecTypes.import);
1314
+ }
1315
+ }
1316
+ return imports;
1317
+ }
1318
+ function extractOperationTypeImports(descriptors) {
1319
+ const imports = [];
1320
+ for (const descriptor of descriptors) {
1321
+ const operationTypes = descriptor.manifest.types?.operationTypes;
1322
+ if (operationTypes?.import) {
1323
+ imports.push(operationTypes.import);
1324
+ }
1325
+ }
1326
+ return imports;
1327
+ }
1328
+ function extractExtensionIds(adapter, target, extensions) {
1329
+ const ids = [];
1330
+ const seen = /* @__PURE__ */ new Set();
1331
+ if (!seen.has(adapter.id)) {
1332
+ ids.push(adapter.id);
1333
+ seen.add(adapter.id);
1334
+ }
1335
+ if (!seen.has(target.id)) {
1336
+ ids.push(target.id);
1337
+ seen.add(target.id);
1338
+ }
1339
+ for (const ext of extensions) {
1340
+ if (!seen.has(ext.id)) {
1341
+ ids.push(ext.id);
1342
+ seen.add(ext.id);
1343
+ }
1344
+ }
1345
+ return ids;
1346
+ }
1347
+ function extractCodecTypeImportsFromPacks(packs) {
1348
+ const imports = [];
1349
+ for (const pack of packs) {
1350
+ const codecTypes = pack.manifest.types?.codecTypes;
1351
+ if (codecTypes?.import) {
1352
+ imports.push(codecTypes.import);
1353
+ }
1354
+ }
1355
+ return imports;
1356
+ }
1357
+ function extractOperationTypeImportsFromPacks(packs) {
1358
+ const imports = [];
1359
+ for (const pack of packs) {
1360
+ const operationTypes = pack.manifest.types?.operationTypes;
1361
+ if (operationTypes?.import) {
1362
+ imports.push(operationTypes.import);
1363
+ }
1364
+ }
1365
+ return imports;
1366
+ }
1367
+ function assembleOperationRegistryFromPacks(packs) {
1368
+ const registry = createOperationRegistry();
1369
+ for (const pack of packs) {
1370
+ const operations = pack.manifest.operations ?? [];
1371
+ for (const operationManifest of operations) {
1372
+ const signature = convertOperationManifest(operationManifest);
1373
+ registry.register(signature);
1374
+ }
1375
+ }
1376
+ return registry;
1377
+ }
1378
+ function extractExtensionIdsFromPacks(packs) {
1379
+ return packs.map((pack) => pack.manifest.id);
1380
+ }
1381
+
1382
+ export {
1383
+ extractCodecTypeImportsFromPacks,
1384
+ extractOperationTypeImportsFromPacks,
1385
+ assembleOperationRegistryFromPacks,
1386
+ extractExtensionIdsFromPacks,
1387
+ createSqlFamilyInstance
1388
+ };
1389
+ //# sourceMappingURL=chunk-LXRIZAYE.js.map