@prisma-next/emitter 0.3.0-dev.14 → 0.3.0-dev.146

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.
Files changed (47) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +45 -35
  3. package/dist/domain-type-generation.d.mts +30 -0
  4. package/dist/domain-type-generation.d.mts.map +1 -0
  5. package/dist/domain-type-generation.mjs +213 -0
  6. package/dist/domain-type-generation.mjs.map +1 -0
  7. package/dist/exports/index.d.mts +39 -0
  8. package/dist/exports/index.d.mts.map +1 -0
  9. package/dist/exports/index.mjs +105 -0
  10. package/dist/exports/index.mjs.map +1 -0
  11. package/dist/test/utils.d.mts +21 -0
  12. package/dist/test/utils.d.mts.map +1 -0
  13. package/dist/test/utils.mjs +18 -0
  14. package/dist/test/utils.mjs.map +1 -0
  15. package/dist/type-expression-safety-7_1tfJXA.mjs +8 -0
  16. package/dist/type-expression-safety-7_1tfJXA.mjs.map +1 -0
  17. package/dist/type-expression-safety.d.mts +5 -0
  18. package/dist/type-expression-safety.d.mts.map +1 -0
  19. package/dist/type-expression-safety.mjs +3 -0
  20. package/package.json +29 -13
  21. package/src/domain-type-generation.ts +357 -0
  22. package/src/emit-types.ts +23 -0
  23. package/src/emit.ts +68 -0
  24. package/src/exports/index.ts +14 -9
  25. package/src/generate-contract-dts.ts +116 -0
  26. package/src/type-expression-safety.ts +3 -0
  27. package/test/canonicalization.test.ts +196 -19
  28. package/test/domain-type-generation.test.ts +790 -0
  29. package/test/emitter.integration.test.ts +132 -187
  30. package/test/emitter.roundtrip.test.ts +117 -191
  31. package/test/emitter.test.ts +124 -442
  32. package/test/hashing.test.ts +9 -34
  33. package/test/mock-spi.ts +18 -0
  34. package/test/type-expression-safety.test.ts +34 -0
  35. package/test/utils.ts +30 -165
  36. package/dist/exports/index.js +0 -6
  37. package/dist/exports/index.js.map +0 -1
  38. package/dist/src/exports/index.d.ts +0 -4
  39. package/dist/src/exports/index.d.ts.map +0 -1
  40. package/dist/src/target-family.d.ts +0 -2
  41. package/dist/src/target-family.d.ts.map +0 -1
  42. package/dist/test/utils.d.ts +0 -14
  43. package/dist/test/utils.d.ts.map +0 -1
  44. package/dist/test/utils.js +0 -78
  45. package/dist/test/utils.js.map +0 -1
  46. package/src/target-family.ts +0 -7
  47. package/test/factories.test.ts +0 -274
@@ -0,0 +1,790 @@
1
+ import type {
2
+ ContractField,
3
+ ContractModel,
4
+ ContractValueObject,
5
+ } from '@prisma-next/contract/types';
6
+ import type { Codec, CodecLookup } from '@prisma-next/framework-components/codec';
7
+ import type { TypesImportSpec } from '@prisma-next/framework-components/emission';
8
+ import { describe, expect, it, vi } from 'vitest';
9
+ import {
10
+ deduplicateImports,
11
+ generateCodecTypeIntersection,
12
+ generateContractFieldDescriptor,
13
+ generateFieldOutputTypesMap,
14
+ generateFieldResolvedType,
15
+ generateHashTypeAliases,
16
+ generateImportLines,
17
+ generateModelFieldsType,
18
+ generateModelRelationsType,
19
+ generateModelsType,
20
+ generateRootsType,
21
+ generateValueObjectsDescriptorType,
22
+ generateValueObjectType,
23
+ generateValueObjectTypeAliases,
24
+ serializeExecutionType,
25
+ serializeObjectKey,
26
+ serializeValue,
27
+ } from '../src/domain-type-generation';
28
+
29
+ describe('serializeValue', () => {
30
+ it('serializes null', () => {
31
+ expect(serializeValue(null)).toBe('null');
32
+ });
33
+
34
+ it('serializes undefined', () => {
35
+ expect(serializeValue(undefined)).toBe('undefined');
36
+ });
37
+
38
+ it('serializes strings with single quotes', () => {
39
+ expect(serializeValue('hello')).toBe("'hello'");
40
+ });
41
+
42
+ it('escapes backslashes and single quotes in strings', () => {
43
+ expect(serializeValue("it's")).toBe("'it\\'s'");
44
+ expect(serializeValue('back\\slash')).toBe("'back\\\\slash'");
45
+ });
46
+
47
+ it('serializes numbers', () => {
48
+ expect(serializeValue(42)).toBe('42');
49
+ expect(serializeValue(3.14)).toBe('3.14');
50
+ });
51
+
52
+ it('serializes booleans', () => {
53
+ expect(serializeValue(true)).toBe('true');
54
+ expect(serializeValue(false)).toBe('false');
55
+ });
56
+
57
+ it('serializes bigints', () => {
58
+ expect(serializeValue(BigInt(123))).toBe('123n');
59
+ });
60
+
61
+ it('serializes arrays as readonly tuples', () => {
62
+ expect(serializeValue(['a', 'b'])).toBe("readonly ['a', 'b']");
63
+ });
64
+
65
+ it('serializes objects with readonly properties', () => {
66
+ expect(serializeValue({ key: 'val' })).toBe("{ readonly key: 'val' }");
67
+ });
68
+
69
+ it('serializes nested objects', () => {
70
+ const result = serializeValue({ a: { b: 1 } });
71
+ expect(result).toBe('{ readonly a: { readonly b: 1 } }');
72
+ });
73
+
74
+ it('returns unknown for unsupported types', () => {
75
+ expect(serializeValue(Symbol('test'))).toBe('unknown');
76
+ });
77
+ });
78
+
79
+ describe('serializeObjectKey', () => {
80
+ it('passes through valid identifiers', () => {
81
+ expect(serializeObjectKey('foo')).toBe('foo');
82
+ expect(serializeObjectKey('_bar')).toBe('_bar');
83
+ expect(serializeObjectKey('$baz')).toBe('$baz');
84
+ expect(serializeObjectKey('camelCase')).toBe('camelCase');
85
+ });
86
+
87
+ it('quotes keys with special characters', () => {
88
+ expect(serializeObjectKey('has space')).toBe("'has space'");
89
+ expect(serializeObjectKey('has-dash')).toBe("'has-dash'");
90
+ expect(serializeObjectKey('ns/name@1')).toBe("'ns/name@1'");
91
+ });
92
+ });
93
+
94
+ describe('generateModelFieldsType', () => {
95
+ it('returns Record<string, never> for empty fields', () => {
96
+ expect(generateModelFieldsType({})).toBe('Record<string, never>');
97
+ });
98
+
99
+ it('generates field with type descriptor and nullable', () => {
100
+ const result = generateModelFieldsType({
101
+ name: { type: { kind: 'scalar', codecId: 'sql/text@1' }, nullable: false },
102
+ });
103
+ expect(result).toBe(
104
+ "{ readonly name: { readonly nullable: false; readonly type: { readonly kind: 'scalar'; readonly codecId: 'sql/text@1' } } }",
105
+ );
106
+ });
107
+
108
+ it('generates multiple fields', () => {
109
+ const result = generateModelFieldsType({
110
+ id: { type: { kind: 'scalar', codecId: 'sql/int4@1' }, nullable: false },
111
+ email: { type: { kind: 'scalar', codecId: 'sql/text@1' }, nullable: true },
112
+ });
113
+ expect(result).toContain(
114
+ "readonly id: { readonly nullable: false; readonly type: { readonly kind: 'scalar'; readonly codecId: 'sql/int4@1' } }",
115
+ );
116
+ expect(result).toContain(
117
+ "readonly email: { readonly nullable: true; readonly type: { readonly kind: 'scalar'; readonly codecId: 'sql/text@1' } }",
118
+ );
119
+ });
120
+
121
+ it('quotes keys with special characters', () => {
122
+ const result = generateModelFieldsType({
123
+ 'field-name': { type: { kind: 'scalar', codecId: 'sql/text@1' }, nullable: false },
124
+ });
125
+ expect(result).toContain("readonly 'field-name':");
126
+ });
127
+ });
128
+
129
+ describe('generateModelsType', () => {
130
+ const noopStorage = () => 'Record<string, never>';
131
+
132
+ function makeModel(overrides: Partial<ContractModel> = {}): ContractModel {
133
+ return {
134
+ fields: {},
135
+ relations: {},
136
+ storage: { storageHash: 'test' },
137
+ ...overrides,
138
+ };
139
+ }
140
+
141
+ it('returns Record<string, never> for empty models', () => {
142
+ expect(generateModelsType({}, noopStorage)).toBe('Record<string, never>');
143
+ });
144
+
145
+ it('generates model with fields, relations, and storage', () => {
146
+ const models: Record<string, ContractModel> = {
147
+ User: makeModel({
148
+ fields: { name: { type: { kind: 'scalar', codecId: 'sql/text@1' }, nullable: false } },
149
+ relations: { posts: { to: 'Post', cardinality: '1:N' } },
150
+ }),
151
+ };
152
+ const result = generateModelsType(models, () => "{ readonly table: 'users' }");
153
+ expect(result).toContain('readonly User:');
154
+ expect(result).toContain("readonly codecId: 'sql/text@1'");
155
+ expect(result).toContain("readonly to: 'Post'");
156
+ expect(result).toContain("readonly table: 'users'");
157
+ });
158
+
159
+ it('sorts models by name', () => {
160
+ const models: Record<string, ContractModel> = {
161
+ Zebra: makeModel(),
162
+ Alpha: makeModel(),
163
+ };
164
+ const result = generateModelsType(models, noopStorage);
165
+ const alphaIdx = result.indexOf('Alpha');
166
+ const zebraIdx = result.indexOf('Zebra');
167
+ expect(alphaIdx).toBeLessThan(zebraIdx);
168
+ });
169
+
170
+ it('passes modelName and model to the storage callback', () => {
171
+ const model = makeModel();
172
+ const models: Record<string, ContractModel> = { User: model };
173
+ const storageFn = vi.fn(() => 'Record<string, never>');
174
+ generateModelsType(models, storageFn);
175
+ expect(storageFn).toHaveBeenCalledWith('User', model);
176
+ });
177
+
178
+ it('includes owner when present', () => {
179
+ const models: Record<string, ContractModel> = {
180
+ Comment: makeModel({ owner: 'Post' }),
181
+ };
182
+ const result = generateModelsType(models, noopStorage);
183
+ expect(result).toContain("readonly owner: 'Post'");
184
+ });
185
+
186
+ it('includes discriminator when present', () => {
187
+ const models: Record<string, ContractModel> = {
188
+ Animal: makeModel({ discriminator: { field: 'type' } }),
189
+ };
190
+ const result = generateModelsType(models, noopStorage);
191
+ expect(result).toContain("readonly discriminator: { readonly field: 'type' }");
192
+ });
193
+
194
+ it('includes variants when present', () => {
195
+ const models: Record<string, ContractModel> = {
196
+ Animal: makeModel({ variants: { Dog: { value: 'dog' }, Cat: { value: 'cat' } } }),
197
+ };
198
+ const result = generateModelsType(models, noopStorage);
199
+ expect(result).toContain('readonly variants:');
200
+ expect(result).toContain('readonly Dog:');
201
+ expect(result).toContain('readonly Cat:');
202
+ });
203
+
204
+ it('includes base when present', () => {
205
+ const models: Record<string, ContractModel> = {
206
+ Dog: makeModel({ base: 'Animal' }),
207
+ };
208
+ const result = generateModelsType(models, noopStorage);
209
+ expect(result).toContain("readonly base: 'Animal'");
210
+ });
211
+ });
212
+
213
+ describe('generateRootsType', () => {
214
+ it('returns Record<string, string> for undefined roots', () => {
215
+ expect(generateRootsType(undefined)).toBe('Record<string, string>');
216
+ });
217
+
218
+ it('returns Record<string, string> for empty roots', () => {
219
+ expect(generateRootsType({})).toBe('Record<string, string>');
220
+ });
221
+
222
+ it('generates literal object type for roots', () => {
223
+ const result = generateRootsType({ users: 'User', posts: 'Post' });
224
+ expect(result).toContain("readonly users: 'User'");
225
+ expect(result).toContain("readonly posts: 'Post'");
226
+ });
227
+ });
228
+
229
+ describe('generateModelRelationsType', () => {
230
+ it('returns empty object for empty relations', () => {
231
+ expect(generateModelRelationsType({})).toBe('Record<string, never>');
232
+ });
233
+
234
+ it('generates relation with to and cardinality', () => {
235
+ const result = generateModelRelationsType({
236
+ posts: { to: 'Post', cardinality: '1:N' },
237
+ });
238
+ expect(result).toContain("readonly to: 'Post'");
239
+ expect(result).toContain("readonly cardinality: '1:N'");
240
+ });
241
+
242
+ it('generates relation with on (localFields/targetFields)', () => {
243
+ const result = generateModelRelationsType({
244
+ author: {
245
+ to: 'User',
246
+ cardinality: 'N:1',
247
+ on: { localFields: ['authorId'], targetFields: ['_id'] },
248
+ },
249
+ });
250
+ expect(result).toContain("readonly to: 'User'");
251
+ expect(result).toContain("readonly cardinality: 'N:1'");
252
+ expect(result).toContain("readonly localFields: readonly ['authorId']");
253
+ expect(result).toContain("readonly targetFields: readonly ['_id']");
254
+ });
255
+
256
+ it('skips non-object relations', () => {
257
+ const result = generateModelRelationsType({
258
+ bad: 'not an object' as unknown as Record<string, unknown>,
259
+ });
260
+ expect(result).toBe('Record<string, never>');
261
+ });
262
+
263
+ it('generates multiple relations', () => {
264
+ const result = generateModelRelationsType({
265
+ author: { to: 'User', cardinality: 'N:1' },
266
+ comments: { to: 'Comment', cardinality: '1:N' },
267
+ });
268
+ expect(result).toContain('readonly author:');
269
+ expect(result).toContain('readonly comments:');
270
+ });
271
+
272
+ it('omits to when missing from relation', () => {
273
+ const result = generateModelRelationsType({
274
+ rel: { cardinality: '1:N' },
275
+ });
276
+ expect(result).toContain("readonly cardinality: '1:N'");
277
+ expect(result).not.toContain('readonly to:');
278
+ });
279
+
280
+ it('omits cardinality when missing from relation', () => {
281
+ const result = generateModelRelationsType({
282
+ rel: { to: 'Post' },
283
+ });
284
+ expect(result).toContain("readonly to: 'Post'");
285
+ expect(result).not.toContain('readonly cardinality:');
286
+ });
287
+
288
+ it('skips relation object with no recognized properties', () => {
289
+ const result = generateModelRelationsType({
290
+ empty: { unknown: true },
291
+ });
292
+ expect(result).toBe('Record<string, never>');
293
+ });
294
+
295
+ it('throws when relation has on but missing localFields/targetFields', () => {
296
+ expect(() =>
297
+ generateModelRelationsType({
298
+ author: {
299
+ to: 'User',
300
+ cardinality: 'N:1',
301
+ on: { parentCols: ['userId'], childCols: ['id'] },
302
+ },
303
+ }),
304
+ ).toThrow('missing localFields or targetFields');
305
+ });
306
+ });
307
+
308
+ describe('deduplicateImports', () => {
309
+ it('returns empty array for empty input', () => {
310
+ expect(deduplicateImports([])).toEqual([]);
311
+ });
312
+
313
+ it('keeps unique imports', () => {
314
+ const imports: TypesImportSpec[] = [
315
+ { package: 'pkg-a', named: 'CodecTypes', alias: 'A' },
316
+ { package: 'pkg-b', named: 'CodecTypes', alias: 'B' },
317
+ ];
318
+ expect(deduplicateImports(imports)).toHaveLength(2);
319
+ });
320
+
321
+ it('deduplicates by package+named (first wins)', () => {
322
+ const imports: TypesImportSpec[] = [
323
+ { package: 'pkg-a', named: 'CodecTypes', alias: 'First' },
324
+ { package: 'pkg-a', named: 'CodecTypes', alias: 'Second' },
325
+ ];
326
+ const result = deduplicateImports(imports);
327
+ expect(result).toHaveLength(1);
328
+ expect(result[0]!.alias).toBe('First');
329
+ });
330
+
331
+ it('preserves insertion order', () => {
332
+ const imports: TypesImportSpec[] = [
333
+ { package: 'pkg-b', named: 'X', alias: 'X' },
334
+ { package: 'pkg-a', named: 'Y', alias: 'Y' },
335
+ ];
336
+ const result = deduplicateImports(imports);
337
+ expect(result[0]!.package).toBe('pkg-b');
338
+ expect(result[1]!.package).toBe('pkg-a');
339
+ });
340
+ });
341
+
342
+ describe('generateImportLines', () => {
343
+ it('generates import with alias', () => {
344
+ const imports: TypesImportSpec[] = [
345
+ { package: '@prisma-next/adapter', named: 'CodecTypes', alias: 'PgCodecTypes' },
346
+ ];
347
+ const lines = generateImportLines(imports);
348
+ expect(lines).toEqual([
349
+ "import type { CodecTypes as PgCodecTypes } from '@prisma-next/adapter';",
350
+ ]);
351
+ });
352
+
353
+ it('simplifies import when named === alias', () => {
354
+ const imports: TypesImportSpec[] = [
355
+ { package: '@prisma-next/adapter', named: 'Vector', alias: 'Vector' },
356
+ ];
357
+ const lines = generateImportLines(imports);
358
+ expect(lines).toEqual(["import type { Vector } from '@prisma-next/adapter';"]);
359
+ });
360
+ });
361
+
362
+ describe('generateCodecTypeIntersection', () => {
363
+ it('returns Record<string, never> when no matching imports', () => {
364
+ expect(generateCodecTypeIntersection([], 'CodecTypes')).toBe('Record<string, never>');
365
+ });
366
+
367
+ it('returns single alias when one match', () => {
368
+ const imports: TypesImportSpec[] = [
369
+ { package: 'pkg', named: 'CodecTypes', alias: 'PgCodecTypes' },
370
+ ];
371
+ expect(generateCodecTypeIntersection(imports, 'CodecTypes')).toBe('PgCodecTypes');
372
+ });
373
+
374
+ it('returns intersection when multiple matches', () => {
375
+ const imports: TypesImportSpec[] = [
376
+ { package: 'pkg-a', named: 'CodecTypes', alias: 'A' },
377
+ { package: 'pkg-b', named: 'CodecTypes', alias: 'B' },
378
+ ];
379
+ expect(generateCodecTypeIntersection(imports, 'CodecTypes')).toBe('A & B');
380
+ });
381
+
382
+ it('filters by named parameter', () => {
383
+ const imports: TypesImportSpec[] = [
384
+ { package: 'pkg', named: 'CodecTypes', alias: 'CT' },
385
+ { package: 'pkg', named: 'OperationTypes', alias: 'OT' },
386
+ ];
387
+ expect(generateCodecTypeIntersection(imports, 'OperationTypes')).toBe('OT');
388
+ });
389
+ });
390
+
391
+ describe('generateHashTypeAliases', () => {
392
+ it('generates storage and profile hash aliases', () => {
393
+ const result = generateHashTypeAliases({
394
+ storageHash: 'sha256:abc123',
395
+ profileHash: 'sha256:def456',
396
+ });
397
+ expect(result).toContain("StorageHashBase<'sha256:abc123'>");
398
+ expect(result).toContain("ProfileHashBase<'sha256:def456'>");
399
+ });
400
+
401
+ it('generates concrete execution hash when provided', () => {
402
+ const result = generateHashTypeAliases({
403
+ storageHash: 'sha256:abc',
404
+ executionHash: 'sha256:exec',
405
+ profileHash: 'sha256:prof',
406
+ });
407
+ expect(result).toContain("ExecutionHashBase<'sha256:exec'>");
408
+ });
409
+
410
+ it('generates generic execution hash when not provided', () => {
411
+ const result = generateHashTypeAliases({
412
+ storageHash: 'sha256:abc',
413
+ profileHash: 'sha256:prof',
414
+ });
415
+ expect(result).toContain('ExecutionHashBase<string>');
416
+ });
417
+ });
418
+
419
+ describe('serializeExecutionType', () => {
420
+ it('uses ExecutionHash alias instead of literal hash value', () => {
421
+ const result = serializeExecutionType({
422
+ executionHash: 'sha256:abc123',
423
+ mutations: { defaults: [] },
424
+ });
425
+ expect(result).toContain('readonly executionHash: ExecutionHash');
426
+ expect(result).not.toContain('sha256:abc123');
427
+ });
428
+
429
+ it('serializes non-hash fields normally', () => {
430
+ const result = serializeExecutionType({
431
+ executionHash: 'sha256:abc123',
432
+ mutations: { defaults: [{ kind: 'autoIncrement' }] },
433
+ });
434
+ expect(result).toContain('readonly mutations:');
435
+ expect(result).toContain("readonly kind: 'autoIncrement'");
436
+ });
437
+ });
438
+
439
+ describe('generateFieldResolvedType', () => {
440
+ it('generates CodecTypes lookup for scalar fields', () => {
441
+ const field: ContractField = {
442
+ nullable: false,
443
+ type: { kind: 'scalar', codecId: 'mongo/string@1' },
444
+ };
445
+ expect(generateFieldResolvedType(field)).toBe("CodecTypes['mongo/string@1']['output']");
446
+ });
447
+
448
+ it('generates named type reference for value object fields', () => {
449
+ const field: ContractField = {
450
+ nullable: false,
451
+ type: { kind: 'valueObject', name: 'Address' },
452
+ };
453
+ expect(generateFieldResolvedType(field)).toBe('Address');
454
+ });
455
+
456
+ it('wraps in ReadonlyArray for many: true', () => {
457
+ const field: ContractField = {
458
+ nullable: false,
459
+ type: { kind: 'valueObject', name: 'Address' },
460
+ many: true,
461
+ };
462
+ expect(generateFieldResolvedType(field)).toBe('ReadonlyArray<Address>');
463
+ });
464
+
465
+ it('wraps in Readonly<Record> for dict: true', () => {
466
+ const field: ContractField = {
467
+ nullable: false,
468
+ type: { kind: 'scalar', codecId: 'mongo/string@1' },
469
+ dict: true,
470
+ };
471
+ expect(generateFieldResolvedType(field)).toBe(
472
+ "Readonly<Record<string, CodecTypes['mongo/string@1']['output']>>",
473
+ );
474
+ });
475
+
476
+ it('appends | null for nullable: true', () => {
477
+ const field: ContractField = {
478
+ nullable: true,
479
+ type: { kind: 'valueObject', name: 'Address' },
480
+ };
481
+ expect(generateFieldResolvedType(field)).toBe('Address | null');
482
+ });
483
+
484
+ it('combines many and nullable', () => {
485
+ const field: ContractField = {
486
+ nullable: true,
487
+ type: { kind: 'valueObject', name: 'Address' },
488
+ many: true,
489
+ };
490
+ expect(generateFieldResolvedType(field)).toBe('ReadonlyArray<Address> | null');
491
+ });
492
+
493
+ it('handles union types', () => {
494
+ const field: ContractField = {
495
+ nullable: false,
496
+ type: {
497
+ kind: 'union',
498
+ members: [
499
+ { kind: 'scalar', codecId: 'mongo/string@1' },
500
+ { kind: 'valueObject', name: 'Address' },
501
+ ],
502
+ },
503
+ };
504
+ expect(generateFieldResolvedType(field)).toBe(
505
+ "CodecTypes['mongo/string@1']['output'] | Address",
506
+ );
507
+ });
508
+ });
509
+
510
+ describe('generateValueObjectType', () => {
511
+ const addressVo: ContractValueObject = {
512
+ fields: {
513
+ street: { nullable: false, type: { kind: 'scalar', codecId: 'mongo/string@1' } },
514
+ city: { nullable: false, type: { kind: 'scalar', codecId: 'mongo/string@1' } },
515
+ zip: { nullable: false, type: { kind: 'scalar', codecId: 'mongo/string@1' } },
516
+ },
517
+ };
518
+ const valueObjects: Record<string, ContractValueObject> = { Address: addressVo };
519
+
520
+ it('generates object type with all fields', () => {
521
+ const result = generateValueObjectType('Address', addressVo, valueObjects);
522
+ expect(result).toContain("readonly street: CodecTypes['mongo/string@1']['output']");
523
+ expect(result).toContain("readonly city: CodecTypes['mongo/string@1']['output']");
524
+ expect(result).toContain("readonly zip: CodecTypes['mongo/string@1']['output']");
525
+ });
526
+
527
+ it('handles value object field referencing another value object', () => {
528
+ const companyVo: ContractValueObject = {
529
+ fields: {
530
+ name: { nullable: false, type: { kind: 'scalar', codecId: 'mongo/string@1' } },
531
+ address: { nullable: false, type: { kind: 'valueObject', name: 'Address' } },
532
+ },
533
+ };
534
+ const vos = { ...valueObjects, Company: companyVo };
535
+ const result = generateValueObjectType('Company', companyVo, vos);
536
+ expect(result).toContain('readonly address: Address');
537
+ });
538
+
539
+ it('handles self-referencing value object (no infinite recursion)', () => {
540
+ const navItemVo: ContractValueObject = {
541
+ fields: {
542
+ label: { nullable: false, type: { kind: 'scalar', codecId: 'mongo/string@1' } },
543
+ children: {
544
+ nullable: false,
545
+ type: { kind: 'valueObject', name: 'NavItem' },
546
+ many: true,
547
+ },
548
+ },
549
+ };
550
+ const vos = { NavItem: navItemVo };
551
+ const result = generateValueObjectType('NavItem', navItemVo, vos);
552
+ expect(result).toContain('readonly children: ReadonlyArray<NavItem>');
553
+ });
554
+
555
+ it('returns Record<string, never> for empty value object', () => {
556
+ const emptyVo: ContractValueObject = { fields: {} };
557
+ expect(generateValueObjectType('Empty', emptyVo, {})).toBe('Record<string, never>');
558
+ });
559
+ });
560
+
561
+ describe('generateContractFieldDescriptor', () => {
562
+ it('generates scalar field descriptor', () => {
563
+ const field: ContractField = {
564
+ nullable: false,
565
+ type: { kind: 'scalar', codecId: 'pg/text@1' },
566
+ };
567
+ const result = generateContractFieldDescriptor('name', field);
568
+ expect(result).toBe(
569
+ "readonly name: { readonly nullable: false; readonly type: { readonly kind: 'scalar'; readonly codecId: 'pg/text@1' } }",
570
+ );
571
+ });
572
+
573
+ it('generates value object field descriptor', () => {
574
+ const field: ContractField = {
575
+ nullable: true,
576
+ type: { kind: 'valueObject', name: 'Address' },
577
+ };
578
+ const result = generateContractFieldDescriptor('homeAddress', field);
579
+ expect(result).toBe(
580
+ "readonly homeAddress: { readonly nullable: true; readonly type: { readonly kind: 'valueObject'; readonly name: 'Address' } }",
581
+ );
582
+ });
583
+
584
+ it('includes many modifier', () => {
585
+ const field: ContractField = {
586
+ nullable: false,
587
+ type: { kind: 'valueObject', name: 'Address' },
588
+ many: true,
589
+ };
590
+ const result = generateContractFieldDescriptor('addresses', field);
591
+ expect(result).toContain('; readonly many: true');
592
+ });
593
+
594
+ it('includes dict modifier', () => {
595
+ const field: ContractField = {
596
+ nullable: false,
597
+ type: { kind: 'scalar', codecId: 'mongo/string@1' },
598
+ dict: true,
599
+ };
600
+ const result = generateContractFieldDescriptor('labels', field);
601
+ expect(result).toContain('; readonly dict: true');
602
+ });
603
+
604
+ it('includes typeParams for scalar fields', () => {
605
+ const field: ContractField = {
606
+ nullable: false,
607
+ type: { kind: 'scalar', codecId: 'pg/vector@1', typeParams: { length: 1536 } },
608
+ };
609
+ const result = generateContractFieldDescriptor('embedding', field);
610
+ expect(result).toContain('readonly typeParams: { readonly length: 1536 }');
611
+ });
612
+ });
613
+
614
+ describe('generateValueObjectsDescriptorType', () => {
615
+ it('returns Record<string, never> for undefined', () => {
616
+ expect(generateValueObjectsDescriptorType(undefined)).toBe('Record<string, never>');
617
+ });
618
+
619
+ it('returns Record<string, never> for empty', () => {
620
+ expect(generateValueObjectsDescriptorType({})).toBe('Record<string, never>');
621
+ });
622
+
623
+ it('generates descriptor with fields for each value object', () => {
624
+ const valueObjects: Record<string, ContractValueObject> = {
625
+ Address: {
626
+ fields: {
627
+ street: { nullable: false, type: { kind: 'scalar', codecId: 'mongo/string@1' } },
628
+ },
629
+ },
630
+ };
631
+ const result = generateValueObjectsDescriptorType(valueObjects);
632
+ expect(result).toContain('readonly Address: { readonly fields:');
633
+ expect(result).toContain("readonly kind: 'scalar'");
634
+ expect(result).toContain("readonly codecId: 'mongo/string@1'");
635
+ });
636
+ });
637
+
638
+ describe('generateValueObjectTypeAliases', () => {
639
+ it('returns empty string for undefined', () => {
640
+ expect(generateValueObjectTypeAliases(undefined)).toBe('');
641
+ });
642
+
643
+ it('returns empty string for empty', () => {
644
+ expect(generateValueObjectTypeAliases({})).toBe('');
645
+ });
646
+
647
+ it('generates export type alias for each value object', () => {
648
+ const valueObjects: Record<string, ContractValueObject> = {
649
+ Address: {
650
+ fields: {
651
+ street: { nullable: false, type: { kind: 'scalar', codecId: 'mongo/string@1' } },
652
+ },
653
+ },
654
+ };
655
+ const result = generateValueObjectTypeAliases(valueObjects);
656
+ expect(result).toContain('export type Address =');
657
+ expect(result).toContain("readonly street: CodecTypes['mongo/string@1']['output']");
658
+ });
659
+
660
+ it('generates multiple type aliases', () => {
661
+ const valueObjects: Record<string, ContractValueObject> = {
662
+ Address: {
663
+ fields: {
664
+ street: { nullable: false, type: { kind: 'scalar', codecId: 'mongo/string@1' } },
665
+ },
666
+ },
667
+ GeoPoint: {
668
+ fields: {
669
+ lat: { nullable: false, type: { kind: 'scalar', codecId: 'mongo/double@1' } },
670
+ lng: { nullable: false, type: { kind: 'scalar', codecId: 'mongo/double@1' } },
671
+ },
672
+ },
673
+ };
674
+ const result = generateValueObjectTypeAliases(valueObjects);
675
+ expect(result).toContain('export type Address =');
676
+ expect(result).toContain('export type GeoPoint =');
677
+ });
678
+ });
679
+
680
+ function stubCodec(overrides: Partial<Codec> & { id: string }): Codec {
681
+ return {
682
+ targetTypes: [],
683
+ decode: (w: unknown) => w,
684
+ encodeJson: (v: unknown) => v,
685
+ decodeJson: (j: unknown) => j,
686
+ ...overrides,
687
+ } as unknown as Codec;
688
+ }
689
+
690
+ function stubCodecLookup(codecs: Record<string, Codec>): CodecLookup {
691
+ return { get: (id) => codecs[id] };
692
+ }
693
+
694
+ describe('generateFieldResolvedType', () => {
695
+ it('uses codec renderOutputType when typeParams are present', () => {
696
+ const lookup = stubCodecLookup({
697
+ 'pg/char@1': stubCodec({
698
+ id: 'pg/char@1',
699
+ renderOutputType: (p) => `Char<${p['length']}>`,
700
+ }),
701
+ });
702
+ const field: ContractField = {
703
+ nullable: false,
704
+ type: { kind: 'scalar', codecId: 'pg/char@1', typeParams: { length: 36 } },
705
+ };
706
+ expect(generateFieldResolvedType(field, lookup)).toBe('Char<36>');
707
+ });
708
+
709
+ it('falls back to CodecTypes lookup when no codecLookup provided', () => {
710
+ const field: ContractField = {
711
+ nullable: false,
712
+ type: { kind: 'scalar', codecId: 'pg/int4@1' },
713
+ };
714
+ expect(generateFieldResolvedType(field)).toBe("CodecTypes['pg/int4@1']['output']");
715
+ });
716
+
717
+ it('falls back to CodecTypes when renderOutputType returns unsafe expression', () => {
718
+ const lookup = stubCodecLookup({
719
+ 'test@1': stubCodec({
720
+ id: 'test@1',
721
+ renderOutputType: () => 'import("fs")',
722
+ }),
723
+ });
724
+ const field: ContractField = {
725
+ nullable: false,
726
+ type: { kind: 'scalar', codecId: 'test@1', typeParams: { x: 1 } },
727
+ };
728
+ expect(generateFieldResolvedType(field, lookup)).toBe("CodecTypes['test@1']['output']");
729
+ });
730
+
731
+ it('falls back to CodecTypes when codec has no renderOutputType', () => {
732
+ const lookup = stubCodecLookup({
733
+ 'pg/int4@1': stubCodec({ id: 'pg/int4@1' }),
734
+ });
735
+ const field: ContractField = {
736
+ nullable: false,
737
+ type: { kind: 'scalar', codecId: 'pg/int4@1', typeParams: { x: 1 } },
738
+ };
739
+ expect(generateFieldResolvedType(field, lookup)).toBe("CodecTypes['pg/int4@1']['output']");
740
+ });
741
+
742
+ it('falls back to CodecTypes when typeParams is empty', () => {
743
+ const lookup = stubCodecLookup({
744
+ 'pg/char@1': stubCodec({
745
+ id: 'pg/char@1',
746
+ renderOutputType: () => 'Char<36>',
747
+ }),
748
+ });
749
+ const field: ContractField = {
750
+ nullable: false,
751
+ type: { kind: 'scalar', codecId: 'pg/char@1', typeParams: {} },
752
+ };
753
+ expect(generateFieldResolvedType(field, lookup)).toBe("CodecTypes['pg/char@1']['output']");
754
+ });
755
+ });
756
+
757
+ describe('generateFieldOutputTypesMap', () => {
758
+ it('generates map entries with codec-dispatched rendering', () => {
759
+ const lookup = stubCodecLookup({
760
+ 'pg/char@1': stubCodec({
761
+ id: 'pg/char@1',
762
+ renderOutputType: (p) => `Char<${p['length']}>`,
763
+ }),
764
+ });
765
+ const models: Record<string, ContractModel> = {
766
+ User: {
767
+ fields: {
768
+ id: {
769
+ nullable: false,
770
+ type: { kind: 'scalar', codecId: 'pg/char@1', typeParams: { length: 36 } },
771
+ },
772
+ name: {
773
+ nullable: false,
774
+ type: { kind: 'scalar', codecId: 'pg/text@1' },
775
+ },
776
+ },
777
+ relations: {},
778
+ storage: { fields: {}, table: 'user' },
779
+ },
780
+ };
781
+ const result = generateFieldOutputTypesMap(models, lookup);
782
+ expect(result).toContain('Char<36>');
783
+ expect(result).toContain("CodecTypes['pg/text@1']['output']");
784
+ });
785
+
786
+ it('returns Record<string, never> for empty models', () => {
787
+ expect(generateFieldOutputTypesMap(undefined)).toBe('Record<string, never>');
788
+ expect(generateFieldOutputTypesMap({})).toBe('Record<string, never>');
789
+ });
790
+ });