-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathast-to-print-document.ts
More file actions
325 lines (286 loc) · 10.5 KB
/
Copy pathast-to-print-document.ts
File metadata and controls
325 lines (286 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import type {
PslAttribute,
PslAttributeArgument,
PslDocumentAst,
PslField,
PslModel,
PslNamedTypeDeclaration,
PslTypeConstructorCall,
} from '@prisma-next/framework-components/psl-ast';
import {
flatPslModels,
namespacePslExtensionBlocks,
UNSPECIFIED_PSL_NAMESPACE_ID,
} from '@prisma-next/framework-components/psl-ast';
import type { PrintDocument, PrintNamespaceSection } from './print-document';
import { escapePslString } from './serialize-print-document';
import type { PrinterField, PrinterModel, PrinterNamedType } from './types';
// `contract infer` produces a starting-point PSL contract from a live database
// schema; the user is expected to edit it (rename models/fields, tighten types,
// add `@id` where introspection couldn't infer one, etc.) and then run
// `contract emit` to produce the canonical artifacts. The header invites that
// workflow rather than warning against it.
const DEFAULT_AST_PRINT_HEADER =
'// use prisma-next\n// Contract inferred from the live database schema. Edit as needed, then run `prisma-next contract emit`.';
export function astDocumentToPrintDocument(ast: PslDocumentAst): PrintDocument {
// FK dependencies are resolved across the whole document — a model in one
// namespace can reference a model in another, and the topo-sort needs to
// see every model to produce a stable order. After sorting, we re-bucket by
// namespace so each block prints with its own models in topo order.
const allModels = flatPslModels(ast);
const modelNames = new Set(allModels.map((m) => m.name));
const deps = buildModelFkDeps(allModels, modelNames);
const sortedModels = topologicalSortModels(allModels, deps);
const modelNamespaceIndex = new Map<string, string>();
for (const namespace of ast.namespaces) {
for (const model of namespace.models) {
modelNamespaceIndex.set(model.name, namespace.name);
}
}
const namedTypes: PrinterNamedType[] = ast.types
? ast.types.declarations.map(namedTypeDeclarationToPrinterNamedType)
: [];
const namespaceSections: PrintNamespaceSection[] = ast.namespaces.map((namespace) => {
const namespaceModels = sortedModels.filter(
(model) => modelNamespaceIndex.get(model.name) === namespace.name,
);
const printerModels = namespaceModels.map((m) => modelToPrinterModel(m));
return {
name: namespace.name,
models: printerModels,
extensionBlocks: namespacePslExtensionBlocks(namespace),
};
});
// Ensure the synthesised `__unspecified__` bucket sorts first so top-level
// declarations print before any `namespace { … }` blocks — matches what a
// user would write by hand.
namespaceSections.sort((a, b) => {
if (a.name === b.name) return 0;
if (a.name === UNSPECIFIED_PSL_NAMESPACE_ID) return -1;
if (b.name === UNSPECIFIED_PSL_NAMESPACE_ID) return 1;
return a.name.localeCompare(b.name);
});
return {
headerComment: DEFAULT_AST_PRINT_HEADER,
namedTypes,
namespaces: namespaceSections,
};
}
export function renderPslAttribute(attr: PslAttribute): string {
const prefix = attr.target === 'model' || attr.target === 'enum' ? '@@' : '@';
if (attr.args.length === 0) {
return `${prefix}${attr.name}`;
}
const inner = attr.args.map(renderAttributeArgument).join(', ');
return `${prefix}${attr.name}(${inner})`;
}
function renderAttributeArgument(arg: PslAttributeArgument): string {
if (arg.kind === 'positional') {
return arg.value;
}
return `${arg.name}: ${arg.value}`;
}
function namedTypeDeclarationToPrinterNamedType(decl: PslNamedTypeDeclaration): PrinterNamedType {
const base =
decl.baseType ??
(decl.typeConstructor !== undefined ? formatTypeConstructor(decl.typeConstructor) : '');
const attributes = decl.attributes.map(renderPslAttribute);
return {
name: decl.name,
baseType: base,
attributes,
};
}
function formatTypeConstructor(tc: PslTypeConstructorCall): string {
const path = tc.path.join('.');
if (tc.args.length === 0) {
return path;
}
return `${path}(${tc.args.map(renderAttributeArgument).join(', ')})`;
}
function getPositionalStringArg(attr: PslAttribute, index: number): string | undefined {
const positional = attr.args.filter((a) => a.kind === 'positional');
const raw = positional[index]?.value.trim();
if (!raw) return undefined;
const m = raw.match(/^(['"])(.*)\1$/);
if (!m) return undefined;
return unescapePslString(m[2] as string);
}
/**
* Inverse of `escapePslString`. The parser stores quoted-literal arguments with
* their PSL escape sequences (`\\`, `\"`, `\n`, `\r`) intact; when we round-trip
* a value through `getPositionalStringArg` and re-render via `escapePslString`,
* we must decode it once on extraction to avoid double-escaping the same
* sequences on output.
*/
function unescapePslString(value: string): string {
let result = '';
for (let i = 0; i < value.length; i++) {
const ch = value.charCodeAt(i);
if (ch !== 0x5c /* '\\' */ || i + 1 >= value.length) {
result += value[i];
continue;
}
const next = value[i + 1];
if (next === '\\' || next === '"' || next === "'") {
result += next;
} else if (next === 'n') {
result += '\n';
} else if (next === 'r') {
result += '\r';
} else {
result += '\\';
result += next;
}
i++;
}
return result;
}
function modelToPrinterModel(model: PslModel): PrinterModel {
let mapName: string | undefined;
const modelAttrStrings: string[] = [];
for (const a of model.attributes) {
if (a.name === 'map' && a.target === 'model') {
mapName = getPositionalStringArg(a, 0) ?? mapName;
continue;
}
modelAttrStrings.push(renderPslAttribute(a));
}
if (mapName !== undefined) {
modelAttrStrings.push(`@@map("${escapePslString(mapName)}")`);
}
const printerFields = model.fields.map((f) => fieldToPrinterField(f));
return {
name: model.name,
mapName,
fields: printerFields,
modelAttributes: modelAttrStrings,
comment: model.comment,
};
}
/**
* Assembles the qualified type name string for a field type reference.
*
* Handles all four forms:
* - `space:ns.Name` — typeContractSpaceId + typeNamespaceId + typeName
* - `space:Name` — typeContractSpaceId + typeName (no namespace)
* - `ns.Name` — typeNamespaceId + typeName (no space); fixes TML-2459 printer gap
* - `Name` — typeName only (no qualifier)
*/
function assembleQualifiedTypeName(field: PslField): string {
const { typeName, typeNamespaceId, typeContractSpaceId } = field;
const dotted = typeNamespaceId !== undefined ? `${typeNamespaceId}.${typeName}` : typeName;
return typeContractSpaceId !== undefined ? `${typeContractSpaceId}:${dotted}` : dotted;
}
function fieldToPrinterField(field: PslField): PrinterField {
// Assemble the qualified type identifier: `space:ns.Name` / `space:Name` / `ns.Name` / `Name`.
// When a typeConstructor is present it takes precedence and carries no qualifier.
// Line-wrap policy (pinned): keep the identifier on one line until the existing column limit —
// no special wrap logic at `:` or `.` (project-spec open question; simplest readable default).
const typeName =
field.typeConstructor !== undefined
? formatTypeConstructor(field.typeConstructor)
: assembleQualifiedTypeName(field);
let mapName: string | undefined;
const attrStrings: string[] = [];
for (const a of field.attributes) {
if (a.name === 'map' && a.target === 'field') {
mapName = getPositionalStringArg(a, 0) ?? mapName;
continue;
}
attrStrings.push(renderPslAttribute(a));
}
if (mapName !== undefined) {
attrStrings.push(`@map("${escapePslString(mapName)}")`);
}
const isRelation = field.attributes.some((a) => a.name === 'relation' && a.target === 'field');
const isUnsupported = typeName.startsWith('Unsupported(');
const isId = field.attributes.some((a) => a.name === 'id' && a.target === 'field');
return {
name: field.name,
typeName,
optional: field.optional,
list: field.list,
attributes: attrStrings,
mapName,
isId,
isRelation,
isUnsupported,
comment: undefined,
};
}
function buildModelFkDeps(
models: readonly PslModel[],
modelNames: ReadonlySet<string>,
): Map<string, Set<string>> {
const deps = new Map<string, Set<string>>();
for (const m of models) {
deps.set(m.name, new Set());
}
for (const m of models) {
for (const field of m.fields) {
const refModel = relationReferencedModel(field, modelNames);
if (!refModel || refModel === m.name) continue;
if (!hasFullRelation(field)) continue;
(deps.get(m.name) as Set<string>).add(refModel);
}
}
return deps;
}
function hasFullRelation(field: PslField): boolean {
const rel = field.attributes.find((a) => a.name === 'relation' && a.target === 'field');
if (!rel) return false;
const named = Object.fromEntries(
rel.args
.filter(
(a): a is import('@prisma-next/framework-components/psl-ast').PslAttributeNamedArgument =>
a.kind === 'named',
)
.map((a) => [a.name, a.value.trim()]),
);
// Canonical `from:`/`to:` declare the FK dependency edge; legacy
// `fields:`/`references:` are accepted as an input alias for the same edge.
const hasFrom = named['from'] !== undefined || named['fields'] !== undefined;
const hasTo = named['to'] !== undefined || named['references'] !== undefined;
return hasFrom && hasTo;
}
function relationReferencedModel(
field: PslField,
modelNames: ReadonlySet<string>,
): string | undefined {
const head = field.typeConstructor?.path[0];
const raw = head ?? field.typeName.replace(/\?$/, '').replace(/\[\]$/, '');
if (raw.length === 0) {
return undefined;
}
return modelNames.has(raw) ? raw : undefined;
}
function topologicalSortModels(
models: readonly PslModel[],
deps: ReadonlyMap<string, Set<string>>,
): PslModel[] {
const byName = new Map(models.map((m) => [m.name, m]));
const result: PslModel[] = [];
const visited = new Set<string>();
const visiting = new Set<string>();
const sortedNames = [...deps.keys()].sort();
function visit(name: string): void {
if (visited.has(name)) return;
if (visiting.has(name)) return;
visiting.add(name);
const sortedDeps = [...(deps.get(name) ?? new Set())].sort();
for (const dep of sortedDeps) {
visit(dep);
}
visiting.delete(name);
visited.add(name);
const model = byName.get(name);
if (model) {
result.push(model);
}
}
for (const name of sortedNames) {
visit(name);
}
return result;
}