@opensaas/stack-cli 0.42.3 → 0.44.0-alpha.1

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 (134) hide show
  1. package/README.md +116 -135
  2. package/dist/.build-hash +1 -0
  3. package/dist/commands/db.d.ts +23 -0
  4. package/dist/commands/db.d.ts.map +1 -0
  5. package/dist/commands/db.js +43 -0
  6. package/dist/commands/db.js.map +1 -0
  7. package/dist/commands/dev.d.ts +12 -1
  8. package/dist/commands/dev.d.ts.map +1 -1
  9. package/dist/commands/dev.js +519 -22
  10. package/dist/commands/dev.js.map +1 -1
  11. package/dist/commands/fk-renames.d.ts +14 -0
  12. package/dist/commands/fk-renames.d.ts.map +1 -0
  13. package/dist/commands/fk-renames.js +90 -0
  14. package/dist/commands/fk-renames.js.map +1 -0
  15. package/dist/commands/generate.d.ts +61 -4
  16. package/dist/commands/generate.d.ts.map +1 -1
  17. package/dist/commands/generate.js +225 -138
  18. package/dist/commands/generate.js.map +1 -1
  19. package/dist/commands/init.d.ts +6 -0
  20. package/dist/commands/init.d.ts.map +1 -1
  21. package/dist/commands/init.js +13 -2
  22. package/dist/commands/init.js.map +1 -1
  23. package/dist/commands/junction-ids.d.ts +11 -0
  24. package/dist/commands/junction-ids.d.ts.map +1 -0
  25. package/dist/commands/junction-ids.js +81 -0
  26. package/dist/commands/junction-ids.js.map +1 -0
  27. package/dist/commands/migrate.d.ts +2 -0
  28. package/dist/commands/migrate.d.ts.map +1 -1
  29. package/dist/commands/migrate.js +47 -25
  30. package/dist/commands/migrate.js.map +1 -1
  31. package/dist/dev/app-runner.d.ts +70 -0
  32. package/dist/dev/app-runner.d.ts.map +1 -0
  33. package/dist/dev/app-runner.js +116 -0
  34. package/dist/dev/app-runner.js.map +1 -0
  35. package/dist/dev/control.d.ts +73 -0
  36. package/dist/dev/control.d.ts.map +1 -0
  37. package/dist/dev/control.js +251 -0
  38. package/dist/dev/control.js.map +1 -0
  39. package/dist/dev/staged-reconcile.d.ts +126 -0
  40. package/dist/dev/staged-reconcile.d.ts.map +1 -0
  41. package/dist/dev/staged-reconcile.js +289 -0
  42. package/dist/dev/staged-reconcile.js.map +1 -0
  43. package/dist/generator/config-load.d.ts +34 -0
  44. package/dist/generator/config-load.d.ts.map +1 -0
  45. package/dist/generator/config-load.js +64 -0
  46. package/dist/generator/config-load.js.map +1 -0
  47. package/dist/generator/context.d.ts +39 -3
  48. package/dist/generator/context.d.ts.map +1 -1
  49. package/dist/generator/context.js +245 -107
  50. package/dist/generator/context.js.map +1 -1
  51. package/dist/generator/contract-emit.d.ts +24 -0
  52. package/dist/generator/contract-emit.d.ts.map +1 -0
  53. package/dist/generator/contract-emit.js +34 -0
  54. package/dist/generator/contract-emit.js.map +1 -0
  55. package/dist/generator/contract-module.d.ts +39 -0
  56. package/dist/generator/contract-module.d.ts.map +1 -0
  57. package/dist/generator/contract-module.js +440 -0
  58. package/dist/generator/contract-module.js.map +1 -0
  59. package/dist/generator/extension-spaces.d.ts +142 -0
  60. package/dist/generator/extension-spaces.d.ts.map +1 -0
  61. package/dist/generator/extension-spaces.js +358 -0
  62. package/dist/generator/extension-spaces.js.map +1 -0
  63. package/dist/generator/index.d.ts +12 -4
  64. package/dist/generator/index.d.ts.map +1 -1
  65. package/dist/generator/index.js +7 -3
  66. package/dist/generator/index.js.map +1 -1
  67. package/dist/generator/lists.d.ts +6 -7
  68. package/dist/generator/lists.d.ts.map +1 -1
  69. package/dist/generator/lists.js +33 -13
  70. package/dist/generator/lists.js.map +1 -1
  71. package/dist/generator/output-paths.d.ts +62 -19
  72. package/dist/generator/output-paths.d.ts.map +1 -1
  73. package/dist/generator/output-paths.js +68 -30
  74. package/dist/generator/output-paths.js.map +1 -1
  75. package/dist/generator/prisma-cli.d.ts +61 -0
  76. package/dist/generator/prisma-cli.d.ts.map +1 -0
  77. package/dist/generator/prisma-cli.js +92 -0
  78. package/dist/generator/prisma-cli.js.map +1 -0
  79. package/dist/generator/prisma-config.d.ts +50 -31
  80. package/dist/generator/prisma-config.d.ts.map +1 -1
  81. package/dist/generator/prisma-config.js +72 -65
  82. package/dist/generator/prisma-config.js.map +1 -1
  83. package/dist/generator/source-text.d.ts +16 -0
  84. package/dist/generator/source-text.d.ts.map +1 -0
  85. package/dist/generator/source-text.js +35 -0
  86. package/dist/generator/source-text.js.map +1 -0
  87. package/dist/generator/tables.d.ts +5 -0
  88. package/dist/generator/tables.d.ts.map +1 -0
  89. package/dist/generator/tables.js +84 -0
  90. package/dist/generator/tables.js.map +1 -0
  91. package/dist/generator/types.d.ts +23 -3
  92. package/dist/generator/types.d.ts.map +1 -1
  93. package/dist/generator/types.js +291 -1171
  94. package/dist/generator/types.js.map +1 -1
  95. package/dist/index.js +20 -7
  96. package/dist/index.js.map +1 -1
  97. package/dist/mcp/lib/documentation-provider.d.ts.map +1 -1
  98. package/dist/mcp/lib/documentation-provider.js +44 -42
  99. package/dist/mcp/lib/documentation-provider.js.map +1 -1
  100. package/dist/mcp/lib/generators/feature-generator.d.ts.map +1 -1
  101. package/dist/mcp/lib/generators/feature-generator.js +124 -73
  102. package/dist/mcp/lib/generators/feature-generator.js.map +1 -1
  103. package/dist/mcp/lib/wizards/migration-wizard.js +6 -6
  104. package/dist/mcp/lib/wizards/migration-wizard.js.map +1 -1
  105. package/dist/mcp/lib/wizards/wizard-engine.d.ts.map +1 -1
  106. package/dist/mcp/lib/wizards/wizard-engine.js +3 -2
  107. package/dist/mcp/lib/wizards/wizard-engine.js.map +1 -1
  108. package/dist/mcp/server/stack-mcp-server.js +1 -1
  109. package/dist/migration/fk-renames.d.ts +39 -0
  110. package/dist/migration/fk-renames.d.ts.map +1 -0
  111. package/dist/migration/fk-renames.js +79 -0
  112. package/dist/migration/fk-renames.js.map +1 -0
  113. package/dist/migration/generators/migration-generator.d.ts +11 -0
  114. package/dist/migration/generators/migration-generator.d.ts.map +1 -1
  115. package/dist/migration/generators/migration-generator.js +83 -150
  116. package/dist/migration/generators/migration-generator.js.map +1 -1
  117. package/dist/migration/introspectors/prisma-introspector.d.ts.map +1 -1
  118. package/dist/migration/introspectors/prisma-introspector.js +1 -0
  119. package/dist/migration/introspectors/prisma-introspector.js.map +1 -1
  120. package/dist/migration/junction-ids.d.ts +15 -0
  121. package/dist/migration/junction-ids.d.ts.map +1 -0
  122. package/dist/migration/junction-ids.js +58 -0
  123. package/dist/migration/junction-ids.js.map +1 -0
  124. package/dist/migration/types.d.ts +2 -0
  125. package/dist/migration/types.d.ts.map +1 -1
  126. package/package.json +27 -15
  127. package/dist/generator/node-build.d.ts +0 -53
  128. package/dist/generator/node-build.d.ts.map +0 -1
  129. package/dist/generator/node-build.js +0 -280
  130. package/dist/generator/node-build.js.map +0 -1
  131. package/dist/generator/prisma.d.ts +0 -30
  132. package/dist/generator/prisma.d.ts.map +0 -1
  133. package/dist/generator/prisma.js +0 -422
  134. package/dist/generator/prisma.js.map +0 -1
@@ -1,1237 +1,357 @@
1
+ import { isComputedField, typeDescriptorToTypeString } from '@opensaas/stack-core/extend';
1
2
  import * as fs from 'fs';
2
3
  import * as path from 'path';
3
- import { resolveListTimestamps } from './prisma.js';
4
- function mapFieldTypeToTypeScript(field) {
5
- if (field.type === 'relationship') {
6
- return null;
7
- }
8
- if (field.getTypeScriptType) {
9
- const result = field.getTypeScriptType();
10
- return result.type;
11
- }
12
- throw new Error(`Field type "${field.type}" does not implement getTypeScriptType method`);
13
- }
14
- function isFieldOptional(field) {
15
- // Relationships are always nullable
16
- if (field.type === 'relationship') {
17
- return true;
18
- }
19
- if (field.getTypeScriptType) {
20
- const result = field.getTypeScriptType();
21
- return result.optional;
22
- }
23
- return true;
24
- }
25
- function getVirtualFieldNames(fields) {
26
- return Object.entries(fields)
27
- .filter(([_, config]) => config.type === 'virtual')
28
- .map(([name, _]) => name);
29
- }
4
+ import { assertFieldKeysAreIdentifiers, quote } from './source-text.js';
30
5
  /**
31
- * Intersected with Prisma's GetPayload to add virtual fields to query results.
6
+ * The empty member of a `Remainder` entry. `Record<never, never>` rather than
7
+ * an index-signature type: `keyof` it is `never`, so an empty `output` map
8
+ * cannot accidentally `Omit` every column off the row.
32
9
  */
33
- function generateVirtualFieldsType(listName, fields) {
34
- const lines = [];
35
- const virtualFields = Object.entries(fields).filter(([_, config]) => config.type === 'virtual');
36
- lines.push(`/**`);
37
- lines.push(` * Virtual fields for ${listName} - computed fields not in database`);
38
- lines.push(` * These are added to query results via resolveOutput hooks`);
39
- lines.push(` */`);
40
- lines.push(`export type ${listName}VirtualFields = {`);
41
- for (const [fieldName, fieldConfig] of virtualFields) {
42
- const tsType = mapFieldTypeToTypeScript(fieldConfig);
43
- if (!tsType)
44
- continue;
45
- const optional = isFieldOptional(fieldConfig);
46
- const nullability = optional ? ' | null' : '';
47
- lines.push(` ${fieldName}: ${tsType}${nullability}`);
48
- }
49
- if (virtualFields.length === 0) {
50
- lines.push(' // No virtual fields defined');
51
- }
52
- lines.push('}');
53
- return lines.join('\n');
54
- }
10
+ const EMPTY = 'Record<never, never>';
55
11
  /**
56
- * Replaces Prisma's base types with transformed types (e.g., string -> HashedPassword).
12
+ * Resolve the TypeScript type a field reads as, when it differs from its
13
+ * column's codec type. A virtual field's `outputType` is already a resolved
14
+ * string; a stored field's may be a descriptor.
57
15
  */
58
- function generateTransformedFieldsType(listName, fields) {
59
- const lines = [];
60
- const transformedFields = Object.entries(fields).filter(([_, config]) => config.resultExtension);
61
- lines.push(`/**`);
62
- lines.push(` * Transformed fields for ${listName} - fields with resultExtension transformations`);
63
- lines.push(` * These override Prisma's base types with transformed types via result extensions`);
64
- lines.push(` */`);
65
- lines.push(`export type ${listName}TransformedFields = {`);
66
- for (const [fieldName, fieldConfig] of transformedFields) {
67
- if (fieldConfig.resultExtension) {
68
- const optional = isFieldOptional(fieldConfig);
69
- const nullability = optional ? ' | undefined' : '';
70
- lines.push(` ${fieldName}: ${fieldConfig.resultExtension.outputType}${nullability}`);
71
- }
72
- }
73
- if (transformedFields.length === 0) {
74
- lines.push(' // No transformed fields defined');
75
- }
76
- lines.push('}');
77
- return lines.join('\n');
16
+ function readOutputType(field) {
17
+ const declared = field.outputType;
18
+ return declared === undefined ? null : typeDescriptorToTypeString(declared);
19
+ }
20
+ function readInputType(field) {
21
+ const declared = field.inputType;
22
+ return declared === undefined ? null : typeDescriptorToTypeString(declared);
78
23
  }
79
24
  /**
80
- * Kept for backwards compatibility — `CustomDB` itself uses Prisma's
81
- * GetPayload + VirtualFields instead.
25
+ * A field's contract descriptor, read once so its `kind` and (for a
26
+ * multi-column field) its `columns` are never fetched by separate calls into
27
+ * the same — possibly throwing — `getContractField()` (mirrors `derive.ts`'s
28
+ * single call). `undefined` when the field declares none or throws
29
+ * describing itself; a throw is swallowed here for the same reason
30
+ * `validateFieldConfig`'s own reader swallows it: this renderer only runs
31
+ * after `validateConfigFields` has already gated the config, so a field
32
+ * reaching here that still throws fails at the step designed to name it, not
33
+ * with an opaque stack trace out of this one.
82
34
  */
83
- function generateModelOutputType(listName,
84
- // ListConfig is generic over per-list TypeInfo; we only read `db`/`fields`, which are
85
- // invariant across that generic, so the permissive default arg is intentional.
86
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
87
- listConfig, dbConfig, isSingleton) {
88
- const fields = listConfig.fields;
89
- const lines = [];
90
- lines.push(`export type ${listName}Output = {`);
91
- // Singleton lists use an Int id (bare `id Int @id`, see ADR-0004) matching
92
- // Keystone 6, so the TypeScript id type is `number` rather than `string`.
93
- lines.push(isSingleton ? ' id: number' : ' id: string');
94
- for (const [fieldName, fieldConfig] of Object.entries(fields)) {
95
- if (fieldConfig.type === 'virtual')
96
- continue;
97
- if (fieldConfig.type === 'relationship') {
98
- const relField = fieldConfig;
99
- const [targetList] = relField.ref.split('.');
100
- if (relField.many) {
101
- lines.push(` ${fieldName}?: ${targetList}Output[]`); // Optional since only present with include
102
- }
103
- else {
104
- lines.push(` ${fieldName}Id: string | null`);
105
- lines.push(` ${fieldName}?: ${targetList}Output | null`); // Optional since only present with include
106
- }
107
- }
108
- else {
109
- const tsType = mapFieldTypeToTypeScript(fieldConfig);
110
- if (!tsType)
111
- continue;
112
- const optional = isFieldOptional(fieldConfig);
113
- const nullability = optional ? ' | null' : '';
114
- lines.push(` ${fieldName}: ${tsType}${nullability}`);
115
- }
35
+ function readDescriptor(field, fieldKey, listKey, config) {
36
+ try {
37
+ return field.getContractField?.(fieldKey, listKey, config);
116
38
  }
117
- // Auto-timestamp columns mirror the Prisma schema: only emitted when timestamps are
118
- // enabled (off by default — ADR-0004) and not already declared as a field above.
119
- const timestamps = resolveListTimestamps(listConfig, dbConfig);
120
- if (timestamps.createdAt) {
121
- lines.push(' createdAt: Date');
39
+ catch {
40
+ return undefined;
122
41
  }
123
- if (timestamps.updatedAt) {
124
- lines.push(' updatedAt: Date');
125
- }
126
- lines.push('} & ' + listName + 'VirtualFields');
127
- return lines.join('\n');
128
- }
129
- function generateModelTypeAlias(listName) {
130
- return `export type ${listName} = ${listName}Output`;
131
42
  }
132
43
  /**
133
- * Render a single scalar create/update input member line — the SINGLE source of
134
- * truth for a scalar field's member shape (name, `?` optionality, TypeScript
135
- * type, and `| null` nullability).
136
- *
137
- * Both the standalone `{List}CreateInput`/`{List}UpdateInput` exports and the
138
- * call-site write-`data` override (`buildScalarOverrideMembers`) render their
139
- * scalar members through this helper so the two cannot drift on how a nullable
140
- * scalar is represented (#608).
141
- *
142
- * Nullability: a nullable scalar (`getTypeScriptType().optional`) gets `| null`,
143
- * matching Prisma's nullable-column input. A required scalar gets neither `?`
144
- * nor `| null`.
145
- *
146
- * Optionality:
147
- * - create: optional (`?`) when nullable OR it has a default value. The
148
- * `defaultValue === undefined` check is explicit (not truthiness) so a
149
- * falsy-but-present default such as `checkbox({ defaultValue: false })` is
150
- * still treated as having a default. See #599.
151
- * - update: always optional (partial update).
152
- *
153
- * Returns `null` for fields whose `getTypeScriptType()` yields no type, so
154
- * callers can skip them.
155
- *
156
- * @param indent - Leading whitespace for the emitted line (call sites differ:
157
- * standalone inputs use 2 spaces, the `data` override uses 4).
44
+ * Render `{ a: T; b: U }`, or the empty marker when there is nothing to say.
158
45
  */
159
- function renderScalarInputMember(fieldName, fieldConfig, forCreate, indent) {
160
- const tsType = mapFieldTypeToTypeScript(fieldConfig);
161
- if (!tsType)
162
- return null;
163
- const nullable = isFieldOptional(fieldConfig);
164
- const nullability = nullable ? ' | null' : '';
165
- let optional;
166
- if (forCreate) {
167
- const required = !nullable && fieldConfig.defaultValue === undefined;
168
- optional = required ? '' : '?';
169
- }
170
- else {
171
- optional = '?';
172
- }
173
- return `${indent}${fieldName}${optional}: ${tsType}${nullability}`;
46
+ function renderMembers(members, indent) {
47
+ if (members.length === 0)
48
+ return EMPTY;
49
+ return `{\n${members.map((m) => `${indent} ${m}`).join('\n')}\n${indent}}`;
174
50
  }
175
- function generateCreateInputType(listName, fields) {
176
- const lines = [];
177
- lines.push(`export type ${listName}CreateInput = {`);
178
- for (const [fieldName, fieldConfig] of Object.entries(fields)) {
179
- // Virtual fields with resolveInput hooks can handle side effects but don't store data.
180
- if (fieldConfig.virtual) {
181
- continue;
182
- }
183
- if (fieldConfig.type === 'relationship') {
184
- const relField = fieldConfig;
185
- if (relField.many) {
186
- lines.push(` ${fieldName}?: { connect: Array<{ id: string }> }`);
187
- }
188
- else {
189
- lines.push(` ${fieldName}?: { connect: { id: string } }`);
51
+ /**
52
+ * One list's contract remainder: the facts the emitted Contract artifacts
53
+ * cannot carry (ADR-0052). Everything else about the list — scalar types,
54
+ * nullability, relation arity, foreign-key ownership, column defaults — is
55
+ * read from the contract by core's generics and is never written here.
56
+ */
57
+ function generateRemainderEntry(listName, fields, dependencies, isSingleton, config) {
58
+ const computed = [];
59
+ const output = [];
60
+ const input = [];
61
+ const columns = [];
62
+ for (const [fieldName, field] of Object.entries(fields)) {
63
+ const outputType = readOutputType(field);
64
+ const descriptor = readDescriptor(field, fieldName, listName, config);
65
+ // A field that stores nothing lands in `computed` by its descriptor's
66
+ // `kind`, not by the `virtual` flag alone: a third-party field can
67
+ // declare `kind: 'computed'` without also setting the flag, and the
68
+ // descriptor is the source of truth (mirrors `validateFieldConfig`,
69
+ // `filterReadableFields`'s virtual-field pass, and `needsEntries` below —
70
+ // `isComputedField` is the one predicate all four share, issue #1531).
71
+ if (isComputedField(field, fieldName, listName, config, { kind: descriptor?.kind })) {
72
+ // A computed field has no column, so the contract has no type for it. An
73
+ // `unknown` here would compile for every consumer and guard none of them,
74
+ // so the missing declaration is reported instead.
75
+ if (outputType === null) {
76
+ throw new Error(`List "${listName}", field "${fieldName}": a virtual field must declare an ` +
77
+ '`outputType` — there is no column for the contract to type it from.');
190
78
  }
79
+ computed.push(`${fieldName}: ${outputType}`);
80
+ continue;
191
81
  }
192
- else {
193
- // Shared source of truth with the write-`data` override (#608): same
194
- // optionality + `| null` nullability for nullable scalars.
195
- const member = renderScalarInputMember(fieldName, fieldConfig, true, ' ');
196
- if (!member)
197
- continue;
198
- lines.push(member);
82
+ if (outputType !== null)
83
+ output.push(`${fieldName}: ${outputType}`);
84
+ const inputType = readInputType(field);
85
+ if (inputType !== null)
86
+ input.push(`${fieldName}: ${inputType}`);
87
+ if (descriptor?.kind === 'columns') {
88
+ const names = descriptor.columns.map((column) => quote(column.name));
89
+ columns.push(`${fieldName}: ${names.length === 0 ? 'never' : names.join(' | ')}`);
199
90
  }
200
91
  }
201
- lines.push('}');
92
+ const needs = needsEntries(listName, fields, dependencies, config).map(([fieldName, keys]) => `${fieldName}: ${keys}`);
93
+ const lines = [
94
+ ` ${listName}: {`,
95
+ ` computed: ${renderMembers(computed, ' ')}`,
96
+ ` output: ${renderMembers(output, ' ')}`,
97
+ ` input: ${renderMembers(input, ' ')}`,
98
+ ` columns: ${renderMembers(columns, ' ')}`,
99
+ ` needs: ${renderMembers(needs, ' ')}`,
100
+ ];
101
+ if (isSingleton)
102
+ lines.push(' singleton: true');
103
+ lines.push(' }');
202
104
  return lines.join('\n');
203
105
  }
204
106
  /**
205
- * Decide whether a scalar field should have its write-path `data` type narrowed
206
- * to the OpenSaaS `getTypeScriptType()` type, or left as Prisma's input type.
107
+ * Each computed field's declared dependency set, read off the one table
108
+ * `deriveDependencyTable` produced (ADR-0051). The runtime widens a read from
109
+ * that table and the `Remainder` renders the same rows as types, so the two
110
+ * cannot disagree about which columns a hook is handed — including the
111
+ * foreign-key column a declared relation implies on the owning side.
207
112
  *
208
- * Most scalar fields are narrowed so that field-level narrowing (e.g.
209
- * `calendarDay` -> `string`) is a genuine compile error to violate at the
210
- * `context.db.<list>.create()/update()` call site (#599). Three field shapes are
211
- * deliberately left on Prisma's input type to avoid regressing valid writes:
113
+ * Only a COMPUTED field's row becomes a type — by `isComputedField`, the same
114
+ * flag-or-descriptor rule `generateRemainderEntry` sorts a field into
115
+ * `computed` by (issue #1531). `field-visibility.ts` builds the narrowed
116
+ * `computedFieldItem` for a computed field's `resolveOutput` and hands a
117
+ * stored field's the whole `workingItem`, which carries the field's own
118
+ * column — a column `NeedsRow`'s `Pick` does not name. So a `NeedsItem` for a
119
+ * stored field would reject a read that always succeeds. The table keeps those
120
+ * rows because the widening still pays for their declarations.
212
121
  *
213
- * - `decimal`: OpenSaaS narrows to `Decimal`, but Prisma accepts
214
- * `Decimal | number | string`. A strict override would wrongly reject valid
215
- * `number`/`string` decimal writes.
216
- * - `bigInt`: OpenSaaS narrows to `bigint` (issue #907), but Prisma accepts
217
- * `bigint | number`. A strict override would wrongly reject a valid `number`
218
- * write, the same failure mode as `decimal` above. (`bigInt()`'s own
219
- * `getZodSchema` additionally accepts a numeric `string`, coerced to
220
- * `bigint` at the access-control boundary — wider than this narrowly-typed
221
- * `context.db` call site, which is fine: the boundary is TypeScript's, not
222
- * the field's.)
223
- * - `json`: OpenSaaS narrows to `unknown`, but Prisma's input type carries the
224
- * `JsonNull`/`DbNull` sentinels. Overriding to `unknown` would drop them.
225
- *
226
- * Multi-column / `resultExtension` storage fields (`getColumnNames`) are also
227
- * left to Prisma: they back several raw columns rather than a single scalar
228
- * column, so there is no single OpenSaaS scalar to narrow to. Their raw backing
229
- * columns are still stripped from the override (see `getScalarOverrideOmitKeys`)
230
- * so no dangling Prisma keys are left behind — mirroring `generateGetPayload`.
231
- */
232
- function shouldNarrowScalarWrite(fieldConfig) {
233
- if (fieldConfig.type === 'relationship')
234
- return false;
235
- if (fieldConfig.virtual)
236
- return false;
237
- if (!fieldConfig.getTypeScriptType)
238
- return false;
239
- // Keep Prisma's input type for decimal/bigInt/json (see doc comment above).
240
- if (fieldConfig.type === 'decimal' ||
241
- fieldConfig.type === 'bigInt' ||
242
- fieldConfig.type === 'json')
243
- return false;
244
- // Multi-column / storage fields back raw columns, not a single scalar.
245
- if (typeof fieldConfig.getColumnNames === 'function')
246
- return false;
247
- return true;
248
- }
249
- /**
250
- * The Prisma `data` keys to omit before re-adding narrowed scalar members.
251
- * Includes each narrowed scalar field name plus any raw backing columns of
252
- * multi-column fields (so no dangling Prisma keys remain after the Omit).
253
- */
254
- function getScalarOverrideOmitKeys(fields) {
255
- const keys = [];
256
- for (const [fieldName, fieldConfig] of Object.entries(fields)) {
257
- if (shouldNarrowScalarWrite(fieldConfig)) {
258
- keys.push(fieldName);
259
- }
260
- // Strip raw backing columns of multi-column fields regardless of narrowing:
261
- // they are assembled from a logical field and must not leak Prisma keys.
262
- if (typeof fieldConfig.getColumnNames === 'function') {
263
- keys.push(...fieldConfig.getColumnNames(fieldName));
264
- }
265
- }
266
- return keys;
122
+ * `never` for a field whose hook declares nothing: `NeedsRow` still adds the
123
+ * list's system fields, which is exactly what such a hook receives.
124
+ */
125
+ export function needsEntries(listName, fields, dependencies, config) {
126
+ const rows = dependencies[listName]?.fields ?? {};
127
+ return Object.keys(rows)
128
+ .sort()
129
+ .filter((fieldName) => {
130
+ const field = fields[fieldName];
131
+ return field !== undefined && isComputedField(field, fieldName, listName, config);
132
+ })
133
+ .map((fieldName) => {
134
+ const { columns, relations } = rows[fieldName];
135
+ const keys = [...columns, ...relations];
136
+ return [fieldName, keys.length === 0 ? 'never' : keys.map((k) => quote(k)).join(' | ')];
137
+ });
267
138
  }
268
139
  /**
269
- * Build the narrowed scalar member lines for a write `data` override.
270
- * Each narrowed scalar field uses its OpenSaaS `getTypeScriptType()` type with
271
- * correct optionality/nullability.
140
+ * The bindings the module imports, each renamed into a namespace of its own.
272
141
  *
273
- * @param forCreate - create uses required/optional + default semantics; update
274
- * makes every field optional (partial update).
275
- */
276
- function buildScalarOverrideMembers(fields, forCreate) {
277
- const members = [];
278
- for (const [fieldName, fieldConfig] of Object.entries(fields)) {
279
- if (!shouldNarrowScalarWrite(fieldConfig))
280
- continue;
281
- // Shared source of truth with generateCreateInputType / generateUpdateInputType
282
- // (#608): identical optionality + `| null` nullability rendering. The override
283
- // uses 4-space indentation since it is nested inside the `data: ... & { ... }`.
284
- const member = renderScalarInputMember(fieldName, fieldConfig, forCreate, ' ');
285
- if (!member)
286
- continue;
287
- members.push(member);
288
- }
289
- return members;
290
- }
142
+ * A list name is a config value under no naming rules beyond PascalCase, so a
143
+ * list called `Row` or `Contract` would otherwise shadow the very generic its
144
+ * own interface is declared from, and the emitted file would not compile with
145
+ * nothing on the generator side to say why. `$` is not a legal character in a
146
+ * list name, so no list can reach these — the same injective-prefix discipline
147
+ * the Contract module applies to its model and enum bindings.
148
+ */
149
+ function imported(name) {
150
+ return `Stack$${name}`;
151
+ }
152
+ /** Every name the module declares that is not derived from a list name. */
153
+ const MODULE_NAMES = [
154
+ 'Remainder',
155
+ 'DB',
156
+ 'TxDB',
157
+ 'BaseContext',
158
+ 'Context',
159
+ 'TransactionContext',
160
+ ];
291
161
  /**
292
- * Build the write `data` type for a single-record create/update Args type.
293
- * Scalars are narrowed to OpenSaaS types while relationship nested writes,
294
- * unchecked FK fields, and decimal/json keep Prisma's input shape.
295
- *
296
- * Shape: `Omit<Prisma.{List}{Create|Update}Args['data'], <omitKeys>> & { <narrowed scalars> }`
297
- *
298
- * When there are no narrowable scalars and no backing columns to strip, the
299
- * Prisma `data` type is used unchanged.
162
+ * The suffixes a list name is decorated with. Two distinct list names can still
163
+ * land on one binding — `Post` and `PostList` both want `PostList` — which is
164
+ * what {@link claimNames} refuses.
300
165
  */
301
- function buildWriteDataType(listName, fields, forCreate) {
302
- const argsType = forCreate ? `${listName}CreateArgs` : `${listName}UpdateArgs`;
303
- const prismaData = `Prisma.${argsType}['data']`;
304
- const omitKeys = getScalarOverrideOmitKeys(fields);
305
- const members = buildScalarOverrideMembers(fields, forCreate);
306
- if (omitKeys.length === 0 && members.length === 0) {
307
- return prismaData;
308
- }
309
- const omitUnion = omitKeys.map((k) => `'${k}'`).join(' | ');
310
- const base = omitKeys.length > 0 ? `Omit<${prismaData}, ${omitUnion}>` : prismaData;
311
- if (members.length === 0) {
312
- return base;
313
- }
314
- return `${base} & {\n${members.join('\n')}\n }`;
315
- }
166
+ const LIST_SUFFIXES = ['', 'StoredRow', 'CreateInput', 'UpdateInput', 'List', 'TxList'];
316
167
  /**
317
- * Build a narrowed write input type over an arbitrary Prisma base input type
318
- * expression (e.g. `Prisma.{List}CreateInput`). Used by the createMany /
319
- * updateMany variants whose `data` is built from the scalar `*Input` types
320
- * rather than the single-record `*Args['data']`.
321
- */
322
- function buildWriteInputOverride(prismaBase, fields, forCreate) {
323
- const omitKeys = getScalarOverrideOmitKeys(fields);
324
- const members = buildScalarOverrideMembers(fields, forCreate);
325
- if (omitKeys.length === 0 && members.length === 0) {
326
- return prismaBase;
327
- }
328
- const omitUnion = omitKeys.map((k) => `'${k}'`).join(' | ');
329
- const base = omitKeys.length > 0 ? `Omit<${prismaBase}, ${omitUnion}>` : prismaBase;
330
- if (members.length === 0) {
331
- return base;
332
- }
333
- return `${base} & {\n${members.join('\n')}\n }`;
334
- }
335
- function generateUpdateInputType(listName, fields) {
336
- const lines = [];
337
- lines.push(`export type ${listName}UpdateInput = {`);
338
- for (const [fieldName, fieldConfig] of Object.entries(fields)) {
339
- // Virtual fields with resolveInput hooks can accept input for side effects
340
- // but we still skip them in the input type since they don't store data
341
- if (fieldConfig.virtual) {
342
- continue;
168
+ * Refuse a config whose lists and computed fields would have the module declare
169
+ * one name twice, naming both origins. The alternative is an emitted file that
170
+ * does not compile, with no generator-side error to explain it.
171
+ */
172
+ function claimNames(config, needsFields) {
173
+ const claimed = new Map();
174
+ const claim = (name, origin) => {
175
+ const existing = claimed.get(name);
176
+ if (existing !== undefined) {
177
+ throw new Error(`The generated types would declare "${name}" twice: ${existing}, and ${origin}. ` +
178
+ 'Rename one of them.');
343
179
  }
344
- if (fieldConfig.type === 'relationship') {
345
- const relField = fieldConfig;
346
- if (relField.many) {
347
- lines.push(` ${fieldName}?: { connect: Array<{ id: string }>, disconnect: Array<{ id: string }> }`);
348
- }
349
- else {
350
- lines.push(` ${fieldName}?: { connect: { id: string } } | { disconnect: true }`);
351
- }
352
- }
353
- else {
354
- // Shared source of truth with the write-`data` override (#608): partial
355
- // update (always optional) with `| null` nullability for nullable scalars.
356
- const member = renderScalarInputMember(fieldName, fieldConfig, false, ' ');
357
- if (!member)
358
- continue;
359
- lines.push(member);
180
+ claimed.set(name, origin);
181
+ };
182
+ for (const name of MODULE_NAMES)
183
+ claim(name, `the bundle's own \`${name}\``);
184
+ for (const listName of Object.keys(config.lists)) {
185
+ for (const suffix of LIST_SUFFIXES) {
186
+ claim(`${listName}${suffix}`, `list "${listName}"`);
360
187
  }
361
188
  }
362
- lines.push('}');
363
- return lines.join('\n');
364
- }
365
- function generateWhereInputType(listName, _fields) {
366
- return `export type ${listName}WhereInput = Prisma.${listName}WhereInput`;
367
- }
368
- function generateHookTypes(listName) {
369
- const lines = [];
370
- lines.push(`/**`);
371
- lines.push(` * Hook types for ${listName} list`);
372
- lines.push(` * Properly typed to use Prisma's generated input types`);
373
- lines.push(` */`);
374
- lines.push(`export type ${listName}Hooks = {`);
375
- lines.push(` resolveInput?: (args:`);
376
- lines.push(` | {`);
377
- lines.push(` operation: 'create'`);
378
- lines.push(` resolvedData: Prisma.${listName}CreateInput`);
379
- lines.push(` item: undefined`);
380
- lines.push(` context: BaseContext`);
381
- lines.push(` }`);
382
- lines.push(` | {`);
383
- lines.push(` operation: 'update'`);
384
- lines.push(` resolvedData: Prisma.${listName}UpdateInput`);
385
- lines.push(` item: ${listName}`);
386
- lines.push(` context: BaseContext`);
387
- lines.push(` }`);
388
- lines.push(` ) => Promise<Prisma.${listName}CreateInput | Prisma.${listName}UpdateInput>`);
389
- lines.push(` validateInput?: (args: {`);
390
- lines.push(` operation: 'create' | 'update'`);
391
- lines.push(` resolvedData: Prisma.${listName}CreateInput | Prisma.${listName}UpdateInput`);
392
- lines.push(` item?: ${listName}`);
393
- lines.push(` context: BaseContext`);
394
- lines.push(` addValidationError: (msg: string) => void`);
395
- lines.push(` }) => Promise<void>`);
396
- lines.push(` beforeOperation?: (args: {`);
397
- lines.push(` operation: 'create' | 'update' | 'delete'`);
398
- lines.push(` resolvedData?: Prisma.${listName}CreateInput | Prisma.${listName}UpdateInput`);
399
- lines.push(` item?: ${listName}`);
400
- lines.push(` context: BaseContext`);
401
- lines.push(` }) => Promise<void>`);
402
- lines.push(` afterOperation?: (args: {`);
403
- lines.push(` operation: 'create' | 'update' | 'delete'`);
404
- lines.push(` resolvedData?: Prisma.${listName}CreateInput | Prisma.${listName}UpdateInput`);
405
- lines.push(` item?: ${listName}`);
406
- lines.push(` context: BaseContext`);
407
- lines.push(` }) => Promise<void>`);
408
- lines.push(`}`);
409
- return lines.join('\n');
410
- }
411
- function generateSelectType(listName, fields) {
412
- const virtualFields = getVirtualFieldNames(fields);
413
- const relationshipFields = Object.entries(fields)
414
- .filter(([_, config]) => config.type === 'relationship')
415
- .map(([name, config]) => ({
416
- name,
417
- targetList: config.ref.split('.')[0],
418
- }));
419
- if (virtualFields.length === 0 && relationshipFields.length === 0) {
420
- return `/**
421
- * Select type for ${listName}
422
- * No virtual fields defined, uses Prisma's Select type directly
423
- */
424
- export type ${listName}Select = Prisma.${listName}Select`;
425
- }
426
- const lines = [];
427
- if (virtualFields.length > 0) {
428
- virtualFields.forEach((name) => {
429
- lines.push(` ${name}?: boolean`);
430
- });
431
- }
432
- if (relationshipFields.length > 0) {
433
- relationshipFields.forEach(({ name, targetList }) => {
434
- lines.push(` ${name}?: boolean | ${targetList}DefaultArgs`);
435
- });
436
- }
437
- if (lines.length === 0) {
438
- return `/**
439
- * Select type for ${listName}
440
- * Uses Prisma's Select type directly
441
- */
442
- export type ${listName}Select = Prisma.${listName}Select`;
443
- }
444
- const exampleLines = [];
445
- if (virtualFields.length > 0) {
446
- exampleLines.push(...virtualFields.map((name) => ` * ${name}: true, // Virtual field`));
189
+ for (const [listName, fieldName] of needsFields) {
190
+ claim(`${listName}${capitalize(fieldName)}NeedsItem`, `list "${listName}"'s computed field "${fieldName}"`);
447
191
  }
448
- return `/**
449
- * Select type for ${listName} with virtual field support
450
- * Extends Prisma's Select type to include virtual fields
451
- * and supports custom Select types in nested relationships
452
- * Use this type when selecting fields to enable virtual field selection
453
- *
454
- * @example
455
- * const select = {
456
- * id: true,
457
- * name: true,
458
- ${exampleLines.join('\n')}
459
- * } satisfies ${listName}Select
460
- */
461
- export type ${listName}Select = Prisma.${listName}Select & {
462
- ${lines.join('\n')}
463
- }`;
464
192
  }
465
193
  /**
466
- * Only generates an Include type if the list has relationship fields — Prisma
467
- * itself only generates Include types for models with relations.
468
- */
469
- function generateIncludeType(listName, fields) {
470
- const relationshipFields = Object.entries(fields)
471
- .filter(([_, config]) => config.type === 'relationship')
472
- .map(([name, config]) => ({
473
- name,
474
- targetList: config.ref.split('.')[0],
475
- }));
476
- if (relationshipFields.length === 0) {
477
- return null;
478
- }
479
- const virtualFields = getVirtualFieldNames(fields);
194
+ * The named interfaces one list contributes. Each is a `interface X extends
195
+ * Generic<Contract, Remainder, 'X'> {}` line, so TypeScript resolves it as its
196
+ * own lazily-checked symbol (ADR-0032).
197
+ */
198
+ function generateListInterfaces(listName) {
199
+ const key = `<${imported('Contract')}, Remainder, '${listName}'>`;
200
+ return [
201
+ `export interface ${listName} extends ${imported('Row')}${key} {}`,
202
+ `export interface ${listName}StoredRow extends ${imported('StoredRow')}${key} {}`,
203
+ `export interface ${listName}CreateInput extends ${imported('CreateInput')}${key} {}`,
204
+ `export interface ${listName}UpdateInput extends ${imported('UpdateInput')}${key} {}`,
205
+ `export interface ${listName}List extends ${imported('SecuredList')}${key} {}`,
206
+ // The transaction-bound face of the same list: `forUpdate()` and nothing
207
+ // else (ADR-0047).
208
+ `export interface ${listName}TxList extends ${imported('SecuredList')}<${imported('Contract')}, Remainder, '${listName}', true> {}`,
209
+ ].join('\n');
210
+ }
211
+ function generateDbType(config) {
212
+ const listNames = Object.keys(config.lists);
480
213
  const lines = [];
481
- if (virtualFields.length > 0) {
482
- virtualFields.forEach((name) => {
483
- lines.push(` ${name}?: boolean`);
484
- });
485
- }
486
- relationshipFields.forEach(({ name, targetList }) => {
487
- lines.push(` ${name}?: boolean | ${targetList}DefaultArgs`);
488
- });
489
- if (lines.length === 0) {
490
- return `/**
491
- * Include type for ${listName}
492
- * No virtual fields defined, uses Prisma's Include type directly
493
- */
494
- export type ${listName}Include = Prisma.${listName}Include`;
495
- }
496
- const exampleLines = [];
497
- if (virtualFields.length > 0) {
498
- exampleLines.push(...virtualFields.map((name) => ` * ${name}: true, // Virtual field`));
499
- }
500
- return `/**
501
- * Include type for ${listName} with virtual field support
502
- * Extends Prisma's Include type to include virtual fields
503
- * and supports custom Include types in nested relationships
504
- * Use this type when including relationships to enable virtual field selection
505
- *
506
- * @example
507
- * const include = {
508
- * author: true,
509
- ${exampleLines.join('\n')}
510
- * } satisfies ${listName}Include
511
- */
512
- export type ${listName}Include = Prisma.${listName}Include & {
513
- ${lines.join('\n')}
514
- }`;
515
- }
516
- /**
517
- * Always generated, even for lists without virtual fields — CustomDB type
518
- * signatures stay consistent, and lists without their own virtual fields
519
- * still need this to support nested relations that have them.
520
- */
521
- function generateGetPayloadType(listName, fields) {
522
- const virtualFields = getVirtualFieldNames(fields);
523
- const transformedFieldNames = Object.entries(fields)
524
- .filter(([_, config]) => config.resultExtension)
525
- .map(([name, _]) => name);
526
- // Multi-column fields (e.g. storage image()/file() in Keystone-parity mode)
527
- // back several raw Prisma columns that must be stripped from the public
528
- // payload: only the assembled logical field (added back via TransformedFields)
529
- // is exposed. Collect those raw column names for omission. See ADR-0006.
530
- const multiColumnRawNames = Object.entries(fields).flatMap(([name, config]) => config.getColumnNames ? config.getColumnNames(name) : []);
531
- const relationshipFields = Object.entries(fields)
532
- .filter(([_, config]) => config.type === 'relationship')
533
- .map(([name, config]) => ({
534
- name,
535
- targetList: config.ref.split('.')[0],
536
- many: !!config.many,
537
- }));
538
- const lines = [];
539
- lines.push(`/**`);
540
- if (virtualFields.length > 0 || transformedFieldNames.length > 0) {
541
- lines.push(` * GetPayload type for ${listName} with virtual and transformed field support`);
542
- lines.push(` * Extends Prisma's GetPayload to include virtual and transformed fields`);
543
- }
544
- else {
545
- lines.push(` * GetPayload type for ${listName}`);
546
- lines.push(` * Wraps Prisma's GetPayload to ensure nested relations support virtual fields`);
547
- }
548
- lines.push(` * Use this type to get properly typed results with virtual fields`);
549
- lines.push(` *`);
550
- lines.push(` * @example`);
551
- lines.push(` * const select = {`);
552
- lines.push(` * id: true,`);
553
- if (virtualFields.length > 0) {
554
- virtualFields.forEach((fieldName) => {
555
- lines.push(` * ${fieldName}: true, // Virtual field`);
556
- });
557
- }
558
- else {
559
- lines.push(` * // Relations can include virtual fields from related lists`);
560
- }
561
- lines.push(` * } satisfies ${listName}Select`);
562
- lines.push(` *`);
563
- lines.push(` * type Result = ${listName}GetPayload<{ select: typeof select }>`);
564
- lines.push(` */`);
565
- lines.push(`export type ${listName}GetPayload<T extends { select?: any; include?: any } = {}> =`);
566
- // Build the base type (Prisma's GetPayload minus relationship and transformed fields)
567
- // When virtual fields exist, strip them from T before passing to Prisma so Prisma never
568
- // tries to resolve a virtual field name (which would produce `never` in its payload type).
569
- const fieldsToOmit = [
570
- ...transformedFieldNames,
571
- ...relationshipFields.map((r) => r.name),
572
- ...multiColumnRawNames,
573
- ];
574
- const prismaT = virtualFields.length > 0 ? `StripVirtualFromArgs<T, keyof ${listName}VirtualFields>` : 'T';
575
- if (fieldsToOmit.length > 0) {
576
- lines.push(` Omit<Prisma.${listName}GetPayload<${prismaT}>, ${fieldsToOmit.map((n) => `'${n}'`).join(' | ')}> &`);
577
- }
578
- else {
579
- lines.push(` Prisma.${listName}GetPayload<${prismaT}> &`);
580
- }
581
- if (transformedFieldNames.length > 0) {
582
- lines.push(` ${listName}TransformedFields &`);
583
- }
584
- if (relationshipFields.length > 0) {
585
- lines.push(` {`);
586
- for (const rel of relationshipFields) {
587
- lines.push(` ${rel.name}?:`);
588
- lines.push(` T extends { select: any }`);
589
- lines.push(` ? '${rel.name}' extends keyof T['select']`);
590
- lines.push(` ? T['select']['${rel.name}'] extends true`);
591
- lines.push(` ? ${rel.targetList}${rel.many ? '[]' : ''}`);
592
- lines.push(` : T['select']['${rel.name}'] extends { select: any }`);
593
- lines.push(` ? ${rel.targetList}GetPayload<{ select: T['select']['${rel.name}']['select'] }>${rel.many ? '[]' : ''}`);
594
- lines.push(` : T['select']['${rel.name}'] extends { include: any }`);
595
- lines.push(` ? ${rel.targetList}GetPayload<{ include: T['select']['${rel.name}']['include'] }>${rel.many ? '[]' : ''}`);
596
- lines.push(` : ${rel.targetList}${rel.many ? '[]' : ''}`);
597
- lines.push(` : never`);
598
- lines.push(` : T extends { include: any }`);
599
- lines.push(` ? T['include'] extends true`);
600
- lines.push(` ? ${rel.targetList}${rel.many ? '[]' : ''}`);
601
- lines.push(` : '${rel.name}' extends keyof T['include']`);
602
- lines.push(` ? T['include']['${rel.name}'] extends true`);
603
- lines.push(` ? ${rel.targetList}${rel.many ? '[]' : ''}`);
604
- lines.push(` : T['include']['${rel.name}'] extends { select: any }`);
605
- lines.push(` ? ${rel.targetList}GetPayload<{ select: T['include']['${rel.name}']['select'] }>${rel.many ? '[]' : ''}`);
606
- lines.push(` : T['include']['${rel.name}'] extends { include: any }`);
607
- lines.push(` ? ${rel.targetList}GetPayload<{ include: T['include']['${rel.name}']['include'] }>${rel.many ? '[]' : ''}`);
608
- lines.push(` : ${rel.targetList}${rel.many ? '[]' : ''}`);
609
- lines.push(` : never`);
610
- lines.push(` : ${rel.targetList}${rel.many ? '[]' : ''}`);
611
- }
612
- lines.push(` } &`);
613
- }
614
- if (virtualFields.length > 0) {
615
- lines.push(` (`);
616
- lines.push(` T extends { select: any }`);
617
- lines.push(` ? T['select'] extends true`);
618
- lines.push(` ? ${listName}VirtualFields`);
619
- lines.push(` : {`);
620
- lines.push(` [K in keyof ${listName}VirtualFields as K extends keyof T['select']`);
621
- lines.push(` ? T['select'][K] extends true`);
622
- lines.push(` ? K`);
623
- lines.push(` : never`);
624
- lines.push(` : never]: ${listName}VirtualFields[K]`);
625
- lines.push(` }`);
626
- lines.push(` : T extends { include: any }`);
627
- lines.push(` ? T['include'] extends true`);
628
- lines.push(` ? ${listName}VirtualFields`);
629
- lines.push(` : {`);
630
- lines.push(` [K in keyof ${listName}VirtualFields as K extends keyof T['include']`);
631
- lines.push(` ? T['include'][K] extends true`);
632
- lines.push(` ? K`);
633
- lines.push(` : never`);
634
- lines.push(` : never]: ${listName}VirtualFields[K]`);
635
- lines.push(` }`);
636
- lines.push(` : ${listName}VirtualFields`);
637
- lines.push(` )`);
214
+ lines.push('/**');
215
+ lines.push(' * The access-controlled `db` surface, one member per list.');
216
+ lines.push(' */');
217
+ lines.push('export interface DB {');
218
+ for (const listName of listNames) {
219
+ lines.push(` ${listName}: ${listName}List`);
638
220
  }
639
- else {
640
- lines.push(` {}`);
221
+ lines.push('}');
222
+ lines.push('');
223
+ lines.push('/**');
224
+ lines.push(' * The same surface inside `context.transaction()`, where a read can take a');
225
+ lines.push(' * row lock. `forUpdate()` is the only difference between the two.');
226
+ lines.push(' */');
227
+ lines.push('export interface TxDB {');
228
+ for (const listName of listNames) {
229
+ lines.push(` ${listName}: ${listName}TxList`);
641
230
  }
231
+ lines.push('}');
642
232
  return lines.join('\n');
643
233
  }
644
- function generateDefaultArgsType(listName, fields) {
645
- const hasRelationships = Object.values(fields).some((field) => field.type === 'relationship');
646
- if (hasRelationships) {
647
- return `/**
648
- * Default args type for ${listName} with custom Select/Include support
649
- * Used in nested relationship selections to support virtual fields
650
- */
651
- export type ${listName}DefaultArgs = {
652
- select?: ${listName}Select | null
653
- include?: ${listName}Include | null
654
- }`;
655
- }
656
- else {
657
- return `/**
658
- * Default args type for ${listName} with custom Select support
659
- * Used in nested relationship selections to support virtual fields
660
- */
661
- export type ${listName}DefaultArgs = {
662
- select?: ${listName}Select | null
663
- }`;
664
- }
665
- }
666
- function generateFindUniqueArgsType(listName, fields) {
667
- const hasRelationships = Object.values(fields).some((field) => field.type === 'relationship');
668
- if (hasRelationships) {
669
- return `/**
670
- * Custom FindUniqueArgs for ${listName} with virtual field support in nested relationships
671
- */
672
- export type ${listName}FindUniqueArgs = Omit<Prisma.${listName}FindUniqueArgs, 'select' | 'include'> & {
673
- select?: ${listName}Select | null
674
- include?: ${listName}Include | null
675
- query?: Fragment<${listName}Output, FieldSelection<${listName}Output>>
676
- }`;
677
- }
678
- else {
679
- return `/**
680
- * Custom FindUniqueArgs for ${listName} with virtual field support
681
- */
682
- export type ${listName}FindUniqueArgs = Omit<Prisma.${listName}FindUniqueArgs, 'select'> & {
683
- select?: ${listName}Select | null
684
- query?: Fragment<${listName}Output, FieldSelection<${listName}Output>>
685
- }`;
686
- }
687
- }
688
- function generateFindManyArgsType(listName, fields) {
689
- const hasRelationships = Object.values(fields).some((field) => field.type === 'relationship');
690
- if (hasRelationships) {
691
- return `/**
692
- * Custom FindManyArgs for ${listName} with virtual field support in nested relationships
693
- */
694
- export type ${listName}FindManyArgs = Omit<Prisma.${listName}FindManyArgs, 'select' | 'include'> & {
695
- select?: ${listName}Select | null
696
- include?: ${listName}Include | null
697
- query?: Fragment<${listName}Output, FieldSelection<${listName}Output>>
698
- }`;
699
- }
700
- else {
701
- return `/**
702
- * Custom FindManyArgs for ${listName} with virtual field support
703
- */
704
- export type ${listName}FindManyArgs = Omit<Prisma.${listName}FindManyArgs, 'select'> & {
705
- select?: ${listName}Select | null
706
- query?: Fragment<${listName}Output, FieldSelection<${listName}Output>>
707
- }`;
708
- }
709
- }
710
- function generateFindFirstArgsType(listName, fields) {
711
- const hasRelationships = Object.values(fields).some((field) => field.type === 'relationship');
712
- if (hasRelationships) {
713
- return `/**
714
- * Custom FindFirstArgs for ${listName} with virtual field support in nested relationships
715
- */
716
- export type ${listName}FindFirstArgs = Omit<Prisma.${listName}FindFirstArgs, 'select' | 'include'> & {
717
- select?: ${listName}Select | null
718
- include?: ${listName}Include | null
719
- query?: Fragment<${listName}Output, FieldSelection<${listName}Output>>
720
- }`;
721
- }
722
- else {
723
- return `/**
724
- * Custom FindFirstArgs for ${listName} with virtual field support
234
+ function generateContextTypes() {
235
+ const session = imported('Session');
236
+ const services = imported('PluginServices');
237
+ // The app's own Prisma 8 client, keyed to its emitted contract — naming it
238
+ // here is what keeps `context.unsafe.sql`/`.raw` typed as Prisma's own
239
+ // builder and raw tag rather than degrading to `object` at the generic
240
+ // default (ADR-0052).
241
+ const client = `${imported('PostgresClient')}<${imported('Contract')}>`;
242
+ return `/**
243
+ * The context a hook, an access rule and a plugin service see: the secured
244
+ * \`db\`, the session and the ambient plumbing, with nothing that can start a
245
+ * transaction or change who is asking.
725
246
  */
726
- export type ${listName}FindFirstArgs = Omit<Prisma.${listName}FindFirstArgs, 'select'> & {
727
- select?: ${listName}Select | null
728
- query?: Fragment<${listName}Output, FieldSelection<${listName}Output>>
729
- }`;
730
- }
731
- }
247
+ export interface BaseContext<TSession extends ${session} = ${session}>
248
+ extends ${imported('StackBaseContext')}<DB, TSession, ${services}, ${client}> {}
249
+
732
250
  /**
733
- * The same include/query narrowing as FindUniqueArgs, minus `where` (a
734
- * singleton has no unique selector; there is exactly one row).
251
+ * The full context a server action or page component holds — everything
252
+ * \`BaseContext\` carries plus \`sudo()\`, \`withSession()\` and \`transaction()\`.
735
253
  */
736
- function generateGetArgsType(listName, fields) {
737
- const hasRelationships = Object.values(fields).some((field) => field.type === 'relationship');
738
- if (hasRelationships) {
739
- return `/**
740
- * Custom Args for ${listName}.get() with virtual field support in nested relationships
741
- */
742
- export type ${listName}GetArgs = {
743
- select?: ${listName}Select | null
744
- include?: ${listName}Include | null
745
- query?: Fragment<${listName}Output, FieldSelection<${listName}Output>>
746
- }`;
747
- }
748
- else {
749
- return `/**
750
- * Custom Args for ${listName}.get() with virtual field support
751
- */
752
- export type ${listName}GetArgs = {
753
- select?: ${listName}Select | null
754
- query?: Fragment<${listName}Output, FieldSelection<${listName}Output>>
755
- }`;
756
- }
757
- }
758
- function generateCreateArgsType(listName, fields) {
759
- const hasRelationships = Object.values(fields).some((field) => field.type === 'relationship');
760
- // Narrow scalar `data` members to OpenSaaS types so field-level narrowing
761
- // (e.g. calendarDay -> string) is a compile error at the call site (#599),
762
- // while relationship nested writes / decimal / json keep Prisma's shape.
763
- const dataType = buildWriteDataType(listName, fields, true);
764
- if (hasRelationships) {
765
- return `/**
766
- * Custom CreateArgs for ${listName} with virtual field support in nested relationships
767
- * The \`data\` member narrows scalar fields to their OpenSaaS types (#599).
768
- */
769
- export type ${listName}CreateArgs = Omit<Prisma.${listName}CreateArgs, 'select' | 'include' | 'data'> & {
770
- select?: ${listName}Select | null
771
- include?: ${listName}Include | null
772
- data: ${dataType}
773
- }`;
774
- }
775
- else {
776
- return `/**
777
- * Custom CreateArgs for ${listName} with virtual field support
778
- * The \`data\` member narrows scalar fields to their OpenSaaS types (#599).
779
- */
780
- export type ${listName}CreateArgs = Omit<Prisma.${listName}CreateArgs, 'select' | 'data'> & {
781
- select?: ${listName}Select | null
782
- data: ${dataType}
783
- }`;
784
- }
785
- }
786
- function generateUpdateArgsType(listName, fields) {
787
- const hasRelationships = Object.values(fields).some((field) => field.type === 'relationship');
788
- // See generateCreateArgsType: narrow scalar `data` members (#599).
789
- const dataType = buildWriteDataType(listName, fields, false);
790
- if (hasRelationships) {
791
- return `/**
792
- * Custom UpdateArgs for ${listName} with virtual field support in nested relationships
793
- * The \`data\` member narrows scalar fields to their OpenSaaS types (#599).
794
- */
795
- export type ${listName}UpdateArgs = Omit<Prisma.${listName}UpdateArgs, 'select' | 'include' | 'data'> & {
796
- select?: ${listName}Select | null
797
- include?: ${listName}Include | null
798
- data: ${dataType}
799
- }`;
800
- }
801
- else {
802
- return `/**
803
- * Custom UpdateArgs for ${listName} with virtual field support
804
- * The \`data\` member narrows scalar fields to their OpenSaaS types (#599).
805
- */
806
- export type ${listName}UpdateArgs = Omit<Prisma.${listName}UpdateArgs, 'select' | 'data'> & {
807
- select?: ${listName}Select | null
808
- data: ${dataType}
809
- }`;
810
- }
811
- }
812
- function generateDeleteArgsType(listName, fields) {
813
- const hasRelationships = Object.values(fields).some((field) => field.type === 'relationship');
814
- if (hasRelationships) {
815
- return `/**
816
- * Custom DeleteArgs for ${listName} with virtual field support in nested relationships
817
- */
818
- export type ${listName}DeleteArgs = Omit<Prisma.${listName}DeleteArgs, 'select' | 'include'> & {
819
- select?: ${listName}Select | null
820
- include?: ${listName}Include | null
821
- }`;
822
- }
823
- else {
824
- return `/**
825
- * Custom DeleteArgs for ${listName} with virtual field support
826
- */
827
- export type ${listName}DeleteArgs = Omit<Prisma.${listName}DeleteArgs, 'select'> & {
828
- select?: ${listName}Select | null
829
- }`;
830
- }
831
- }
832
- function generateCreateManyArgsType(listName, fields) {
833
- const hasRelationships = Object.values(fields).some((field) => field.type === 'relationship');
834
- // createMany `data` is an array of scalar inputs; narrow each element (#599).
835
- const dataElement = buildWriteInputOverride(`Prisma.${listName}CreateInput`, fields, true);
836
- if (hasRelationships) {
837
- return `/**
838
- * Custom CreateManyArgs for ${listName} with virtual field support in nested relationships
839
- * Each \`data\` element narrows scalar fields to their OpenSaaS types (#599).
840
- */
841
- export type ${listName}CreateManyArgs = {
842
- data: Array<${dataElement}>
843
- select?: ${listName}Select | null
844
- include?: ${listName}Include | null
845
- }`;
846
- }
847
- else {
848
- return `/**
849
- * Custom CreateManyArgs for ${listName} with virtual field support
850
- * Each \`data\` element narrows scalar fields to their OpenSaaS types (#599).
851
- */
852
- export type ${listName}CreateManyArgs = {
853
- data: Array<${dataElement}>
854
- select?: ${listName}Select | null
855
- }`;
856
- }
857
- }
858
- function generateUpdateManyArgsType(listName, fields) {
859
- const hasRelationships = Object.values(fields).some((field) => field.type === 'relationship');
860
- // updateMany `data` is a single partial scalar input; narrow it (#599).
861
- const dataType = buildWriteInputOverride(`Prisma.${listName}UpdateInput`, fields, false);
862
- if (hasRelationships) {
863
- return `/**
864
- * Custom UpdateManyArgs for ${listName} with virtual field support in nested relationships
865
- * The \`data\` member narrows scalar fields to their OpenSaaS types (#599).
866
- */
867
- export type ${listName}UpdateManyArgs = {
868
- where?: ${listName}WhereInput
869
- data: ${dataType}
870
- select?: ${listName}Select | null
871
- include?: ${listName}Include | null
872
- }`;
873
- }
874
- else {
875
- return `/**
876
- * Custom UpdateManyArgs for ${listName} with virtual field support
877
- * The \`data\` member narrows scalar fields to their OpenSaaS types (#599).
878
- */
879
- export type ${listName}UpdateManyArgs = {
880
- where?: ${listName}WhereInput
881
- data: ${dataType}
882
- select?: ${listName}Select | null
883
- }`;
884
- }
885
- }
254
+ export interface Context<TSession extends ${session} = ${session}>
255
+ extends ${imported('StackContext')}<DB, TSession, ${services}, TxDB, ${client}> {}
256
+
886
257
  /**
887
- * Generate the named CRUD interface for a single list — extracted out of
888
- * `CustomDB` (rather than inlined as an anonymous object-literal member) so
889
- * TypeScript resolves it as its own lazily-checked symbol. See #952 / ADR-0032:
890
- * an anonymous per-list block inlined directly into one large `CustomDB`
891
- * intersection, combined with the self-referential `Context.sudo(): Context`
892
- * return type, hit `TS2589: Type instantiation is excessively deep` once a
893
- * schema grew past ~7-8 lists.
894
- *
895
- * Every method below is generic over its own `*Args` type, to preserve
896
- * Prisma's conditional return type together with the virtual-field-aware
897
- * `GetPayload` — `count` is the only exception, since it returns a plain number.
898
- *
899
- * `findUnique`/`findFirst`/`findMany` each carry a second, fragment-`query`
900
- * overload matching core's `AugmentedFindUnique`/`AugmentedFindFirst`/
901
- * `AugmentedFindMany` (`AccessControlledDB`'s own read methods) — see #1233:
902
- * before this, a fragment `query` read through the generated `CustomDB`
903
- * silently degraded to the unnarrowed list payload instead of
904
- * `ResultOf<fragment>`, because only the generic `*Args`-based overload was
905
- * generated here. The two overload shapes are hand-written to match core's
906
- * rather than wrapped through core's generics via
907
- * `Parameters<TOriginal>`/`ReturnType<TOriginal>` indirection — that
908
- * indirection reintroduces #952's eager-expansion failure one level deeper
909
- * (`TS2321: Excessive stack depth comparing types`) against a schema whose
910
- * `GetPayload`s cross-reference each other, even though the resulting type
911
- * is structurally identical either way.
912
- *
913
- * A third, trailing, NON-generic member closes each of those three methods
914
- * (plus singleton `get`) — see #1287: a two-member overload set (fragment,
915
- * then the generic `SelectSubset`-based member) is not assignable to a plain
916
- * structural seam (`{ findUnique(args: { where: {...} }): Promise<...> }`,
917
- * the pattern #1214 itself recommends for keeping app code off the generated
918
- * types) once `SelectSubset` carries Prisma's real conditional-intersection
919
- * shape — TypeScript rejects the whole overloaded member against the
920
- * seam's single signature. The same two-member shape also breaks
921
- * `Parameters<typeof db.<list>.findMany>`, which resolves against an
922
- * overloaded type's LAST member only: with the generic member last, the
923
- * unresolved `T` collapses to `never`. Verified empirically (not from the
924
- * TS spec, which does not document either behaviour): adding this third,
925
- * concrete member fixes both, and its position among the three doesn't
926
- * matter for assignability. It sits last because overload resolution tries
927
- * members in declaration order and this one must never win a real call:
928
- * kept last, a normal call (bare, or with `select`/`include`) still matches
929
- * the generic member first and keeps its `T`-narrowed `{List}GetPayload<T>`
930
- * return.
931
- *
932
- * The third member's parameter type deliberately OMITS `select`/`include`/
933
- * `query` (`Pick<..., 'where'>` for `findUnique`, `Omit<..., 'select' |
934
- * 'include' | 'query'>` elsewhere) rather than reusing the full
935
- * `{List}FindXArgs` as-is. `{List}FindXArgs` declares `select`/`include` as
936
- * independently optional, with none of `Prisma.SelectSubset`'s
937
- * `SelectAndInclude`/`SelectAndOmit` exclusivity check the generic member
938
- * enforces — an unrestricted third member would give overload resolution a
939
- * fallback that silently accepts `{ select, include }` together (a
940
- * combination Prisma itself forbids) the moment the generic member's guard
941
- * rejects it. Stripping those keys here closes that hole: a literal call
942
- * providing `select`/`include`/`query` no longer structurally matches this
943
- * member at all (an excess property on a call to a member that doesn't
944
- * declare it), so it can only ever be reached by the two things it exists
945
- * for — the seam-assignability and `Parameters<>` checks above — never by a
946
- * real call.
258
+ * The context inside \`context.transaction()\`: the same surface over \`TxDB\`,
259
+ * whose reads carry \`forUpdate()\`, plus \`advisoryLock()\`.
947
260
  */
948
- function generateListCrudInterface(listName, isSingleton) {
949
- const lines = [];
950
- lines.push(`/**`);
951
- lines.push(` * Access-controlled CRUD methods for ${listName}, with virtual field support.`);
952
- lines.push(` */`);
953
- lines.push(`export interface ${listName}Crud {`);
954
- // Fragment-`query` overload matching core's `AugmentedFindUnique` — see
955
- // the file-level comment above for why this is hand-written rather than
956
- // wrapped through core's generic.
957
- lines.push(` findUnique: {`);
958
- lines.push(` <TItem, TFields extends FieldSelection<TItem>>(args: {`);
959
- lines.push(` where: Record<string, unknown>`);
960
- lines.push(` query: Fragment<TItem, TFields>`);
961
- lines.push(` }): Promise<ResultOf<Fragment<TItem, TFields>> | null>`);
962
- lines.push(` <T extends ${listName}FindUniqueArgs>(`);
963
- lines.push(` args: Prisma.SelectSubset<T, ${listName}FindUniqueArgs>`);
964
- lines.push(` ): Promise<${listName}GetPayload<T> | null>`);
965
- lines.push(` (args: Pick<${listName}FindUniqueArgs, 'where'>): Promise<${listName}GetPayload<${listName}FindUniqueArgs> | null>`);
966
- lines.push(` }`);
967
- lines.push(` findFirst: {`);
968
- lines.push(` <TItem, TFields extends FieldSelection<TItem>>(args: {`);
969
- lines.push(` where?: Record<string, unknown>`);
970
- lines.push(` orderBy?: Record<string, 'asc' | 'desc'> | Array<Record<string, 'asc' | 'desc'>>`);
971
- lines.push(` skip?: number`);
972
- lines.push(` query: Fragment<TItem, TFields>`);
973
- lines.push(` }): Promise<ResultOf<Fragment<TItem, TFields>> | null>`);
974
- lines.push(` <T extends ${listName}FindFirstArgs>(`);
975
- lines.push(` args?: Prisma.SelectSubset<T, ${listName}FindFirstArgs>`);
976
- lines.push(` ): Promise<${listName}GetPayload<T> | null>`);
977
- lines.push(` (args?: Omit<${listName}FindFirstArgs, 'select' | 'include' | 'query'>): Promise<${listName}GetPayload<${listName}FindFirstArgs> | null>`);
978
- lines.push(` }`);
979
- lines.push(` findMany: {`);
980
- lines.push(` <TItem, TFields extends FieldSelection<TItem>>(args: {`);
981
- lines.push(` where?: Record<string, unknown>`);
982
- lines.push(` orderBy?: Record<string, 'asc' | 'desc'> | Array<Record<string, 'asc' | 'desc'>>`);
983
- lines.push(` take?: number`);
984
- lines.push(` skip?: number`);
985
- lines.push(` query: Fragment<TItem, TFields>`);
986
- lines.push(` }): Promise<ResultOf<Fragment<TItem, TFields>>[]>`);
987
- lines.push(` <T extends ${listName}FindManyArgs>(`);
988
- lines.push(` args?: Prisma.SelectSubset<T, ${listName}FindManyArgs>`);
989
- lines.push(` ): Promise<Array<${listName}GetPayload<T>>>`);
990
- lines.push(` (args?: Omit<${listName}FindManyArgs, 'select' | 'include' | 'query'>): Promise<Array<${listName}GetPayload<${listName}FindManyArgs>>>`);
991
- lines.push(` }`);
992
- lines.push(` create: <T extends ${listName}CreateArgs>(`);
993
- lines.push(` args: Prisma.SelectSubset<T, ${listName}CreateArgs>`);
994
- lines.push(` ) => Promise<${listName}GetPayload<T>>`);
995
- lines.push(` update: <T extends ${listName}UpdateArgs>(`);
996
- lines.push(` args: Prisma.SelectSubset<T, ${listName}UpdateArgs>`);
997
- lines.push(` ) => Promise<${listName}GetPayload<T> | null>`);
998
- lines.push(` delete: <T extends ${listName}DeleteArgs>(`);
999
- lines.push(` args: Prisma.SelectSubset<T, ${listName}DeleteArgs>`);
1000
- lines.push(` ) => Promise<${listName}GetPayload<T> | null>`);
1001
- lines.push(` count: (args?: Prisma.${listName}CountArgs) => Promise<number>`);
1002
- lines.push(` createMany: <T extends ${listName}CreateManyArgs>(`);
1003
- lines.push(` args: Prisma.SelectSubset<T, ${listName}CreateManyArgs>`);
1004
- lines.push(` ) => Promise<Array<${listName}GetPayload<T>>>`);
1005
- lines.push(` updateMany: <T extends ${listName}UpdateManyArgs>(`);
1006
- lines.push(` args: Prisma.SelectSubset<T, ${listName}UpdateManyArgs>`);
1007
- lines.push(` ) => Promise<Array<${listName}GetPayload<T>>>`);
1008
- // get - only for singleton lists; accepts the same include/query narrowing
1009
- // as findUnique (minus `where` — a singleton has exactly one row). No core
1010
- // `AccessControlledDB` counterpart exists for `get` (singletons are an
1011
- // OpenSaaS-level concept core's Prisma-shaped delegate map can't see), so
1012
- // the fragment overload is hand-written here rather than reused from core.
1013
- if (isSingleton) {
1014
- lines.push(` get: {`);
1015
- lines.push(` <TFields extends FieldSelection<${listName}Output>>(args: {`);
1016
- lines.push(` query: Fragment<${listName}Output, TFields>`);
1017
- lines.push(` }): Promise<ResultOf<Fragment<${listName}Output, TFields>> | null>`);
1018
- lines.push(` <T extends ${listName}GetArgs>(`);
1019
- lines.push(` args?: Prisma.SelectSubset<T, ${listName}GetArgs>`);
1020
- lines.push(` ): Promise<${listName}GetPayload<T> | null>`);
1021
- lines.push(` (args?: Omit<${listName}GetArgs, 'select' | 'include' | 'query'>): Promise<${listName}GetPayload<${listName}GetArgs> | null>`);
1022
- lines.push(` }`);
1023
- }
1024
- lines.push(`}`);
1025
- return lines.join('\n');
261
+ export interface TransactionContext<TSession extends ${session} = ${session}>
262
+ extends ${imported('StackTransactionContext')}<TxDB, TSession, ${services}, TxDB, ${client}> {}`;
1026
263
  }
1027
264
  /**
1028
- * Generate the custom DB interface that uses Prisma's conditional types with
1029
- * virtual and transformed fields. This leverages Prisma's GetPayload utility
1030
- * to get correct types based on select/include.
265
+ * The relative specifier of the emitted `contract.d.ts` from `.opensaas/`.
1031
266
  *
1032
- * `CustomDB` is declared as an `interface` referencing each list's own named
1033
- * `{List}Crud` interface (see `generateListCrudInterface`) rather than as a
1034
- * `type` alias with N per-list object literals hand-unrolled into one
1035
- * intersection — see #952 / ADR-0032.
1036
- */
1037
- function generateCustomDBType(config) {
1038
- const lines = [];
1039
- // db keys to omit from AccessControlledDB before re-adding each list's own {List}Crud.
1040
- const dbKeys = Object.keys(config.lists).map((listName) => {
1041
- const dbKey = listName.charAt(0).toLowerCase() + listName.slice(1);
1042
- return `'${dbKey}'`;
1043
- });
1044
- for (const listName of Object.keys(config.lists)) {
1045
- const isSingleton = !!config.lists[listName]?.isSingleton;
1046
- lines.push(generateListCrudInterface(listName, isSingleton));
1047
- lines.push('');
1048
- }
1049
- lines.push('/**');
1050
- lines.push(" * Custom DB type that uses Prisma's conditional types with virtual and transformed field support");
1051
- lines.push(' * Types change based on select/include - relationships only present when explicitly included');
1052
- lines.push(' * Virtual fields and transformed fields are added to the base model type');
1053
- lines.push(' */');
1054
- lines.push('export interface CustomDB extends Omit<AccessControlledDB<PrismaClient>, ');
1055
- lines.push(` ${dbKeys.join(' | ')}`);
1056
- lines.push('> {');
1057
- for (const listName of Object.keys(config.lists)) {
1058
- const dbKey = listName.charAt(0).toLowerCase() + listName.slice(1); // camelCase
1059
- lines.push(` ${dbKey}: ${listName}Crud`);
1060
- }
1061
- lines.push('}');
1062
- return lines.join('\n');
1063
- }
1064
- /**
1065
- * Generate BaseContext and Context types derived from core's `StackContext`
1066
- * — the interface `getContext()` actually returns (#1261) — rather than
1067
- * re-declaring its extra members (`serverAction`, `transaction`, `sudo`,
1068
- * `withSession`) by hand. `BaseContext` omits `db`/`session` (replaced with
1069
- * the generated `CustomDB`/`TSession`) plus those four, matching its
1070
- * existing "database and session only" contract; `Context` re-adds them so
1071
- * any newly added `StackContext` member reaches `Context` through plain
1072
- * inheritance with no generator change, while the four whose return type is
1073
- * self-referential are re-declared here so they resolve to the generated
1074
- * `Context`, not core's `StackContext`.
1075
- *
1076
- * Both are declared as `interface`s rather than `type` aliases. `Context`'s
1077
- * `sudo(): Context` return type is self-referential, and a self-referential
1078
- * `type` alias is eagerly expanded wherever it's checked — the same pattern
1079
- * already found (and removed) on the core `AccessContext` interface for
1080
- * breaking TypeScript's structural checking of unrelated generated Prisma
1081
- * types (see `packages/core/CLAUDE.md`). An `interface` is resolved lazily by
1082
- * TypeScript instead, so the self-reference no longer forces eager expansion
1083
- * of the (already large) `CustomDB` it embeds. See #952 / ADR-0032.
1084
- */
1085
- function generateContextType(_config) {
1086
- const lines = [];
1087
- lines.push('/**');
1088
- lines.push(' * Base context type for services that only need database and session access');
1089
- lines.push(' * Compatible with both AccessContext (from hooks) and Context (from server actions)');
1090
- lines.push(' * Use this type for services that should work in both contexts');
1091
- lines.push(' */');
1092
- lines.push("export interface BaseContext<TSession extends OpensaasSession = OpensaasSession> extends Omit<StackContext<PrismaClient>, 'db' | 'session' | 'serverAction' | 'transaction' | 'sudo' | 'withSession'> {");
1093
- lines.push(' db: CustomDB');
1094
- lines.push(' session: TSession');
1095
- lines.push('}');
1096
- lines.push('');
1097
- lines.push('/**');
1098
- lines.push(' * Full context type with server action capabilities and virtual field typing');
1099
- lines.push(' * Extends BaseContext and adds serverAction, transaction, sudo, and withSession methods');
1100
- lines.push(' * Use this type in server actions and components that need full context capabilities');
1101
- lines.push(' */');
1102
- lines.push('export interface Context<TSession extends OpensaasSession = OpensaasSession> extends BaseContext<TSession> {');
1103
- lines.push(' serverAction: (props: ServerActionProps) => Promise<unknown>');
1104
- lines.push(' transaction: <T>(');
1105
- lines.push(' fn: (txContext: Context<TSession>) => Promise<T>,');
1106
- lines.push(' options?: TransactionOptions,');
1107
- lines.push(' ) => Promise<T>');
1108
- lines.push(' sudo: () => Context<TSession>');
1109
- lines.push(' withSession: (session: TSession | null) => Context<TSession>');
1110
- lines.push('}');
1111
- return lines.join('\n');
1112
- }
1113
- function collectFieldImports(config) {
1114
- const importsMap = new Map();
1115
- for (const listConfig of Object.values(config.lists)) {
1116
- for (const fieldConfig of Object.values(listConfig.fields)) {
1117
- if (fieldConfig.getTypeScriptImports) {
1118
- const imports = fieldConfig.getTypeScriptImports();
1119
- for (const imp of imports) {
1120
- const existing = importsMap.get(imp.from);
1121
- if (existing) {
1122
- imp.names.forEach((name) => existing.names.add(name));
1123
- if (imp.typeOnly === false) {
1124
- existing.typeOnly = false;
1125
- }
1126
- }
1127
- else {
1128
- importsMap.set(imp.from, {
1129
- names: new Set(imp.names),
1130
- typeOnly: imp.typeOnly ?? true,
1131
- });
1132
- }
1133
- }
1134
- }
1135
- }
1136
- }
1137
- return Array.from(importsMap.entries()).map(([from, { names, typeOnly }]) => ({
1138
- names: Array.from(names).sort(),
1139
- from,
1140
- typeOnly,
1141
- }));
1142
- }
1143
- export function generateTypes(config) {
267
+ * Spelled `.d.js`, not `.d.ts`: the Contract module (`prisma/contract.ts`)
268
+ * sits in the same directory, and TypeScript resolves `./contract.d.ts` to
269
+ * THAT file, so the import lands on the builder module and `Contract` is not
270
+ * among its exports. `./contract.d.js` takes the standard `.js` -> `.d.ts`
271
+ * mapping and reaches the emitted declarations. The import is type-only and
272
+ * erased, so no loader ever sees the specifier — ADR-0054's `.ts` rule is
273
+ * about value imports.
274
+ */
275
+ const CONTRACT_IMPORT = '../prisma/contract.d.js';
276
+ export function generateTypes(config, dependencies) {
277
+ assertFieldKeysAreIdentifiers(config);
278
+ const listNames = Object.keys(config.lists);
279
+ const needsFields = Object.entries(config.lists).flatMap(([listName, listConfig]) => needsEntries(listName, listConfig.fields, dependencies, config).map(([fieldName]) => [listName, fieldName]));
280
+ claimNames(config, needsFields);
1144
281
  const lines = [];
1145
282
  lines.push('/**');
1146
283
  lines.push(' * Generated types from OpenSaas configuration');
1147
284
  lines.push(' * DO NOT EDIT - This file is automatically generated');
285
+ lines.push(' *');
286
+ lines.push(' * This file declares the CONTRACT REMAINDER — the per-list facts the');
287
+ lines.push(' * emitted Contract artifacts cannot carry — and instantiates the generics');
288
+ lines.push(' * `@opensaas/stack-core` exports, keyed by the emitted `Contract`. Scalar');
289
+ lines.push(' * types, nullability, relation arity and column defaults are read from the');
290
+ lines.push(' * contract and are never written here. See ADR-0052.');
1148
291
  lines.push(' */');
1149
292
  lines.push('');
1150
- // Use alias for Session to avoid conflicts if user has a list named "Session".
1151
- // Session, StackContext and TransactionOptions stay on the public root entry
1152
- // point (Session is the module-augmentation target; StackContext is what
1153
- // BaseContext/Context derive from, #1261); the rest are unstable runtime
1154
- // plumbing on /internal.
1155
- lines.push("import type { Session as OpensaasSession, StackContext, TransactionOptions } from '@opensaas/stack-core'");
1156
- lines.push("import type { StorageUtils, ServerActionProps, AccessControlledDB, Fragment, FieldSelection, ResultOf } from '@opensaas/stack-core/internal'");
1157
- // Relative imports carry an explicit `.ts` extension (see ./extension.ts) so
1158
- // the bundle resolves under a host bundler / plain Node without an
1159
- // `extensionAlias`. See ADR-0008.
1160
- lines.push("import type { PrismaClient, Prisma } from './prisma-client/client.ts'");
1161
- lines.push("import type { PluginServices } from './plugin-types.ts'");
1162
- const fieldImports = collectFieldImports(config);
1163
- for (const imp of fieldImports) {
1164
- const typePrefix = imp.typeOnly ? 'type ' : '';
1165
- const names = imp.names.join(', ');
1166
- lines.push(`import ${typePrefix}{ ${names} } from '${imp.from}'`);
1167
- }
293
+ // Only what is used is imported: a project compiling `.opensaas/` under
294
+ // `noUnusedLocals` cannot edit generated code to silence it.
295
+ const coreImports = ['Session', 'StackBaseContext', 'StackContext', 'StackTransactionContext'];
296
+ if (listNames.length > 0) {
297
+ coreImports.push('CreateInput', 'Row', 'SecuredList', 'StoredRow', 'UpdateInput');
298
+ }
299
+ if (needsFields.length > 0)
300
+ coreImports.push('NeedsRow');
301
+ // Named unconditionally: Context/BaseContext/TransactionContext key the
302
+ // Unsafe surface to it (PostgresClient<Contract>) whether or not the config
303
+ // declares any list.
304
+ lines.push(`import type { Contract as ${imported('Contract')} } from '${CONTRACT_IMPORT}'`);
305
+ lines.push(`import type { PostgresClient as ${imported('PostgresClient')} } from '@prisma/orm-postgres/runtime'`);
306
+ lines.push('import type {');
307
+ for (const name of coreImports.sort()) {
308
+ lines.push(` ${name} as ${imported(name)},`);
309
+ }
310
+ lines.push("} from '@opensaas/stack-core'");
311
+ lines.push(`import type { PluginServices as ${imported('PluginServices')} } from './plugin-types.ts'`);
1168
312
  lines.push('');
1169
- lines.push('// Utility: strips virtual field keys from select/include so Prisma GetPayload never sees them');
1170
- lines.push('type StripVirtualFromArgs<T, VirtualKeys extends string> =');
1171
- lines.push(' T extends { select: infer S extends object }');
1172
- lines.push(" ? Omit<T, 'select'> & { select: Omit<S, VirtualKeys> }");
1173
- lines.push(' : T extends { include: infer I extends object }');
1174
- lines.push(" ? Omit<T, 'include'> & { include: Omit<I, VirtualKeys> }");
1175
- lines.push(' : T');
313
+ lines.push('/**');
314
+ lines.push(' * The contract remainder, one entry per list:');
315
+ lines.push(' *');
316
+ lines.push(' * - `computed` — a virtual field, which has no column to type it from');
317
+ lines.push(' * - `output` / `input` — a stored field whose TypeScript face differs');
318
+ lines.push(' * from its codec (`password` reads as `HashedPassword`)');
319
+ lines.push(' * - `columns` — a multi-column field’s physical column names, hidden');
320
+ lines.push(' * behind its assembled logical key');
321
+ lines.push(' * - `needs` — each computed field’s declared dependency set');
322
+ lines.push(' * - `singleton` — a config fact the contract cannot see');
323
+ lines.push(' */');
324
+ lines.push('export type Remainder = {');
325
+ const remainderEntries = Object.entries(config.lists).map(([listName, listConfig]) => generateRemainderEntry(listName, listConfig.fields, dependencies, !!listConfig.isSingleton, config));
326
+ lines.push(remainderEntries.join('\n'));
327
+ lines.push('}');
1176
328
  lines.push('');
1177
- for (const [listName, listConfig] of Object.entries(config.lists)) {
1178
- // VirtualFields first — needed by the Output type and CustomDB.
1179
- lines.push(generateVirtualFieldsType(listName, listConfig.fields));
1180
- lines.push('');
1181
- // TransformedFields — needed by CustomDB.
1182
- lines.push(generateTransformedFieldsType(listName, listConfig.fields));
1183
- lines.push('');
1184
- lines.push(generateModelOutputType(listName, listConfig, config.db, !!listConfig.isSingleton));
1185
- lines.push('');
1186
- lines.push(generateModelTypeAlias(listName));
1187
- lines.push('');
1188
- lines.push(generateCreateInputType(listName, listConfig.fields));
1189
- lines.push('');
1190
- lines.push(generateUpdateInputType(listName, listConfig.fields));
1191
- lines.push('');
1192
- lines.push(generateWhereInputType(listName, listConfig.fields));
1193
- lines.push('');
1194
- lines.push(generateHookTypes(listName));
329
+ for (const listName of listNames) {
330
+ lines.push(generateListInterfaces(listName));
1195
331
  lines.push('');
1196
- lines.push(generateSelectType(listName, listConfig.fields));
1197
- lines.push('');
1198
- const includeType = generateIncludeType(listName, listConfig.fields);
1199
- if (includeType) {
1200
- lines.push(includeType);
1201
- lines.push('');
1202
- }
1203
- lines.push(generateGetPayloadType(listName, listConfig.fields));
1204
- lines.push('');
1205
- lines.push(generateDefaultArgsType(listName, listConfig.fields));
1206
- lines.push('');
1207
- lines.push(generateFindUniqueArgsType(listName, listConfig.fields));
1208
- lines.push('');
1209
- lines.push(generateFindManyArgsType(listName, listConfig.fields));
1210
- lines.push('');
1211
- lines.push(generateFindFirstArgsType(listName, listConfig.fields));
1212
- lines.push('');
1213
- if (listConfig.isSingleton) {
1214
- lines.push(generateGetArgsType(listName, listConfig.fields));
1215
- lines.push('');
1216
- }
1217
- lines.push(generateCreateArgsType(listName, listConfig.fields));
1218
- lines.push('');
1219
- lines.push(generateUpdateArgsType(listName, listConfig.fields));
1220
- lines.push('');
1221
- lines.push(generateDeleteArgsType(listName, listConfig.fields));
1222
- lines.push('');
1223
- lines.push(generateCreateManyArgsType(listName, listConfig.fields));
1224
- lines.push('');
1225
- lines.push(generateUpdateManyArgsType(listName, listConfig.fields));
332
+ }
333
+ // The declared-dependency item types `lists.ts` hands each hook. Named here
334
+ // rather than inlined so `lists.ts` stays a namespace of references.
335
+ const needsInterfaces = needsFields.map(([listName, fieldName]) => `export interface ${listName}${capitalize(fieldName)}NeedsItem` +
336
+ ` extends ${imported('NeedsRow')}<${imported('Contract')}, Remainder, '${listName}', Remainder['${listName}']['needs']['${fieldName}']> {}`);
337
+ if (needsInterfaces.length > 0) {
338
+ lines.push('/**');
339
+ lines.push(' * What each computed field’s `resolveOutput` hook is handed: its declared');
340
+ lines.push(' * dependency set plus the list’s system fields, and nothing else.');
341
+ lines.push(' */');
342
+ lines.push(needsInterfaces.join('\n'));
1226
343
  lines.push('');
1227
344
  }
1228
- lines.push(generateCustomDBType(config));
345
+ lines.push(generateDbType(config));
1229
346
  lines.push('');
1230
- lines.push(generateContextType(config));
347
+ lines.push(generateContextTypes());
1231
348
  return lines.join('\n');
1232
349
  }
1233
- export function writeTypes(config, outputPath) {
1234
- const types = generateTypes(config);
350
+ function capitalize(value) {
351
+ return value.charAt(0).toUpperCase() + value.slice(1);
352
+ }
353
+ export function writeTypes(config, outputPath, dependencies) {
354
+ const types = generateTypes(config, dependencies);
1235
355
  const dir = path.dirname(outputPath);
1236
356
  if (!fs.existsSync(dir)) {
1237
357
  fs.mkdirSync(dir, { recursive: true });