@atscript/typescript 0.1.110 → 0.2.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.
- package/dist/cli.cjs +3282 -3879
- package/dist/index.cjs +6 -4
- package/dist/index.d.ts +34 -14
- package/dist/index.mjs +3 -3
- package/dist/plugin-DhesoKce.mjs +3717 -0
- package/dist/plugin-oUSsb3Ri.cjs +3780 -0
- package/dist/realm-runtime.js +6328 -0
- package/dist/test-utils.cjs +77 -3
- package/dist/test-utils.d.ts +316 -4
- package/dist/test-utils.mjs +74 -3
- package/dist/{json-schema-BG1SEcjI.mjs → unique-name-hg1CyPIs.mjs} +1702 -713
- package/dist/{json-schema-B3iAqkGQ.cjs → unique-name-xWd9uO-k.cjs} +1779 -838
- package/dist/utils.cjs +1302 -237
- package/dist/utils.d.ts +323 -30
- package/dist/utils.mjs +1257 -209
- package/package.json +14 -4
- package/dist/plugin-DpzE8aJr.mjs +0 -2483
- package/dist/plugin-mzTvme4k.cjs +0 -2534
package/dist/plugin-mzTvme4k.cjs
DELETED
|
@@ -1,2534 +0,0 @@
|
|
|
1
|
-
//#region \0rolldown/runtime.js
|
|
2
|
-
var __create = Object.create;
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __copyProps = (to, from, except, desc) => {
|
|
9
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
10
|
-
for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
11
|
-
key = keys[i];
|
|
12
|
-
if (!__hasOwnProp.call(to, key) && key !== except) {
|
|
13
|
-
__defProp(to, key, {
|
|
14
|
-
get: ((k) => from[k]).bind(null, key),
|
|
15
|
-
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
return to;
|
|
21
|
-
};
|
|
22
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
23
|
-
value: mod,
|
|
24
|
-
enumerable: true
|
|
25
|
-
}) : target, mod));
|
|
26
|
-
|
|
27
|
-
//#endregion
|
|
28
|
-
const require_json_schema = require('./json-schema-B3iAqkGQ.cjs');
|
|
29
|
-
let path = require("path");
|
|
30
|
-
path = __toESM(path);
|
|
31
|
-
let _atscript_core = require("@atscript/core");
|
|
32
|
-
|
|
33
|
-
//#region packages/typescript/src/codegen/code-printer.ts
|
|
34
|
-
function _define_property$5(obj, key, value) {
|
|
35
|
-
if (key in obj) Object.defineProperty(obj, key, {
|
|
36
|
-
value,
|
|
37
|
-
enumerable: true,
|
|
38
|
-
configurable: true,
|
|
39
|
-
writable: true
|
|
40
|
-
});
|
|
41
|
-
else obj[key] = value;
|
|
42
|
-
return obj;
|
|
43
|
-
}
|
|
44
|
-
var CodePrinter = class {
|
|
45
|
-
/**
|
|
46
|
-
* Write text with NO automatic newline.
|
|
47
|
-
* If current line is empty, we prepend indentation.
|
|
48
|
-
*/ write(...text) {
|
|
49
|
-
if (!this.currentLine) this.currentLine = this.indentString();
|
|
50
|
-
this.currentLine += text.join("");
|
|
51
|
-
return this;
|
|
52
|
-
}
|
|
53
|
-
/**
|
|
54
|
-
* Write text and then finalize this line with a newline.
|
|
55
|
-
* Implemented by calling `write(...)` + push line + reset `currentLine`.
|
|
56
|
-
*/ writeln(...text) {
|
|
57
|
-
this.write(...text);
|
|
58
|
-
this.lines.push(this.currentLine);
|
|
59
|
-
this.currentLine = "";
|
|
60
|
-
return this;
|
|
61
|
-
}
|
|
62
|
-
/**
|
|
63
|
-
* Open a block with an opening/closing pair, e.g. "{}" or "()".
|
|
64
|
-
* By default, places the opening delimiter on the current line (no extra newline).
|
|
65
|
-
*/ block(pair) {
|
|
66
|
-
return this.doBlock(pair, false);
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* Same as `block()`, but adds a newline after writing the opening delimiter.
|
|
70
|
-
*/ blockln(pair) {
|
|
71
|
-
return this.doBlock(pair, true);
|
|
72
|
-
}
|
|
73
|
-
/**
|
|
74
|
-
* Close the most recent block. By default, closing delimiter goes on the current line.
|
|
75
|
-
*/ pop() {
|
|
76
|
-
return this.doPop(false);
|
|
77
|
-
}
|
|
78
|
-
/**
|
|
79
|
-
* Same as `pop()`, but puts the closing delimiter on a new line.
|
|
80
|
-
*/ popln() {
|
|
81
|
-
return this.doPop(true);
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* Increase indentation by one level.
|
|
85
|
-
*/ indent() {
|
|
86
|
-
this.indentLevel++;
|
|
87
|
-
return this;
|
|
88
|
-
}
|
|
89
|
-
/**
|
|
90
|
-
* Decrease indentation by one level (never below 0).
|
|
91
|
-
*/ unindent() {
|
|
92
|
-
this.indentLevel = Math.max(0, this.indentLevel - 1);
|
|
93
|
-
return this;
|
|
94
|
-
}
|
|
95
|
-
render() {
|
|
96
|
-
return this.toString();
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Return the entire code as a string. Removes any half-finished current line if empty.
|
|
100
|
-
*/ toString() {
|
|
101
|
-
if (this.currentLine.trim() !== "") this.lines.push(this.currentLine);
|
|
102
|
-
else if (this.currentLine.length > 0) this.lines.push(this.currentLine);
|
|
103
|
-
return this.lines.join("\n");
|
|
104
|
-
}
|
|
105
|
-
doBlock(pair, withNewLine) {
|
|
106
|
-
if (pair.length < 2) throw new Error(`Block pair must have at least 2 chars, e.g. "{}" or "()". Got "${pair}"`);
|
|
107
|
-
const opening = pair[0];
|
|
108
|
-
const closing = pair[pair.length - 1];
|
|
109
|
-
this.write(opening);
|
|
110
|
-
this.blockStack.push(closing);
|
|
111
|
-
if (withNewLine) this.writeln();
|
|
112
|
-
this.indent();
|
|
113
|
-
return this;
|
|
114
|
-
}
|
|
115
|
-
doPop(withNewLine) {
|
|
116
|
-
if (this.blockStack.length === 0) throw new Error("No block to pop (stack is empty).");
|
|
117
|
-
const closing = this.blockStack.pop();
|
|
118
|
-
this.unindent();
|
|
119
|
-
if (withNewLine) this.writeln(closing);
|
|
120
|
-
else this.write(closing);
|
|
121
|
-
return this;
|
|
122
|
-
}
|
|
123
|
-
indentString() {
|
|
124
|
-
return " ".repeat(this.indentLevel * this.indentSize);
|
|
125
|
-
}
|
|
126
|
-
constructor() {
|
|
127
|
-
_define_property$5(this, "lines", []);
|
|
128
|
-
_define_property$5(this, "currentLine", "");
|
|
129
|
-
_define_property$5(this, "indentLevel", 0);
|
|
130
|
-
_define_property$5(this, "indentSize", 2);
|
|
131
|
-
_define_property$5(this, "blockStack", []);
|
|
132
|
-
}
|
|
133
|
-
};
|
|
134
|
-
|
|
135
|
-
//#endregion
|
|
136
|
-
//#region packages/typescript/src/codegen/base-renderer.ts
|
|
137
|
-
function _define_property$4(obj, key, value) {
|
|
138
|
-
if (key in obj) Object.defineProperty(obj, key, {
|
|
139
|
-
value,
|
|
140
|
-
enumerable: true,
|
|
141
|
-
configurable: true,
|
|
142
|
-
writable: true
|
|
143
|
-
});
|
|
144
|
-
else obj[key] = value;
|
|
145
|
-
return obj;
|
|
146
|
-
}
|
|
147
|
-
var BaseRenderer = class extends CodePrinter {
|
|
148
|
-
get unused() {
|
|
149
|
-
return this._unused ?? (this._unused = new Set(this.doc.getUnusedTokens().map((t) => t.text)));
|
|
150
|
-
}
|
|
151
|
-
pre() {}
|
|
152
|
-
post() {}
|
|
153
|
-
render() {
|
|
154
|
-
this.pre();
|
|
155
|
-
for (const node of this.doc.nodes) this.renderNode(node);
|
|
156
|
-
this.post();
|
|
157
|
-
return this.toString();
|
|
158
|
-
}
|
|
159
|
-
renderInterface(node) {}
|
|
160
|
-
renderType(node) {}
|
|
161
|
-
renderAnnotate(node) {}
|
|
162
|
-
transformFromPath(path) {
|
|
163
|
-
return `${path}.as`;
|
|
164
|
-
}
|
|
165
|
-
renderImport(node) {
|
|
166
|
-
const def = node.getDefinition();
|
|
167
|
-
const refs = [];
|
|
168
|
-
const from = this.transformFromPath(node.token("path").text);
|
|
169
|
-
let isUnusedImport = true;
|
|
170
|
-
if ((0, _atscript_core.isGroup)(def)) {
|
|
171
|
-
for (const child of def.unwrap()) if ((0, _atscript_core.isRef)(child) && !this.unused.has(child.id)) {
|
|
172
|
-
const node = child;
|
|
173
|
-
refs.push(node.id);
|
|
174
|
-
isUnusedImport = false;
|
|
175
|
-
}
|
|
176
|
-
} else if ((0, _atscript_core.isRef)(def) && !this.unused.has(def.id)) {
|
|
177
|
-
refs.push(def.id);
|
|
178
|
-
isUnusedImport = false;
|
|
179
|
-
}
|
|
180
|
-
if (!isUnusedImport) this.writeln(`import { ${refs.join(", ")} } from "${from}"`);
|
|
181
|
-
}
|
|
182
|
-
renderNode(node) {
|
|
183
|
-
switch (node.entity) {
|
|
184
|
-
case "interface":
|
|
185
|
-
this.renderInterface(node);
|
|
186
|
-
break;
|
|
187
|
-
case "type":
|
|
188
|
-
this.renderType(node);
|
|
189
|
-
break;
|
|
190
|
-
case "import":
|
|
191
|
-
this.renderImport(node);
|
|
192
|
-
break;
|
|
193
|
-
case "annotate":
|
|
194
|
-
this.renderAnnotate(node);
|
|
195
|
-
break;
|
|
196
|
-
default: break;
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
constructor(doc) {
|
|
200
|
-
super(), _define_property$4(this, "doc", void 0), _define_property$4(this, "_unused", void 0), this.doc = doc;
|
|
201
|
-
}
|
|
202
|
-
};
|
|
203
|
-
|
|
204
|
-
//#endregion
|
|
205
|
-
//#region packages/typescript/src/codegen/utils.ts
|
|
206
|
-
const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
207
|
-
/**
|
|
208
|
-
* Wraps a property name in double quotes if it's not a valid identifier (contains special chars, etc.).
|
|
209
|
-
*
|
|
210
|
-
* Examples:
|
|
211
|
-
* - "validName" => "validName"
|
|
212
|
-
* - "some-prop" => "\"some-prop\""
|
|
213
|
-
*/ function wrapProp(name) {
|
|
214
|
-
if (!validIdentifier.test(name)) return `"${escapeQuotes(name)}"`;
|
|
215
|
-
return name;
|
|
216
|
-
}
|
|
217
|
-
function escapeQuotes(str) {
|
|
218
|
-
return str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
//#endregion
|
|
222
|
-
//#region packages/typescript/src/codegen/type-renderer.ts
|
|
223
|
-
function _define_property$3(obj, key, value) {
|
|
224
|
-
if (key in obj) Object.defineProperty(obj, key, {
|
|
225
|
-
value,
|
|
226
|
-
enumerable: true,
|
|
227
|
-
configurable: true,
|
|
228
|
-
writable: true
|
|
229
|
-
});
|
|
230
|
-
else obj[key] = value;
|
|
231
|
-
return obj;
|
|
232
|
-
}
|
|
233
|
-
var TypeRenderer = class TypeRenderer extends BaseRenderer {
|
|
234
|
-
pre() {
|
|
235
|
-
this.writeln("// prettier-ignore-start");
|
|
236
|
-
this.writeln("/* eslint-disable */");
|
|
237
|
-
this.writeln("/* oxlint-disable */");
|
|
238
|
-
this.writeln(`/// <reference path="./${this.doc.name}" />`);
|
|
239
|
-
this.writeln("/**");
|
|
240
|
-
this.writeln(" * 🪄 This file was generated by Atscript");
|
|
241
|
-
this.writeln(" * Do not edit this file!");
|
|
242
|
-
this.writeln(" */");
|
|
243
|
-
this.writeln();
|
|
244
|
-
this.writeln("import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TAtscriptAnnotatedType, TMetadataMap, Validator, TValidatorOptions } from \"@atscript/typescript/utils\"");
|
|
245
|
-
}
|
|
246
|
-
post() {
|
|
247
|
-
this.writeln("// prettier-ignore-end");
|
|
248
|
-
}
|
|
249
|
-
renderTypeDefString(def) {
|
|
250
|
-
const newThis = new TypeRenderer(this.doc, this.opts);
|
|
251
|
-
newThis.renderTypeDef(def);
|
|
252
|
-
return newThis.toString();
|
|
253
|
-
}
|
|
254
|
-
renderTypeDef(def) {
|
|
255
|
-
if (!def) {
|
|
256
|
-
this.write("unknown");
|
|
257
|
-
return;
|
|
258
|
-
}
|
|
259
|
-
if ((0, _atscript_core.isStructure)(def)) return this.renderStructure(def);
|
|
260
|
-
if ((0, _atscript_core.isGroup)(def)) {
|
|
261
|
-
const tuple = def.entity === "tuple";
|
|
262
|
-
const operator = tuple ? ", " : ` ${def.op} `;
|
|
263
|
-
const children = def.unwrap();
|
|
264
|
-
const hasSubgroup = !tuple && children.some((c) => c.entity === "group");
|
|
265
|
-
this.write(tuple ? "[" : hasSubgroup ? "(" : "");
|
|
266
|
-
this.renderTypeDef(def.first);
|
|
267
|
-
for (const child of children.slice(1)) {
|
|
268
|
-
this.write(operator);
|
|
269
|
-
this.renderTypeDef(child);
|
|
270
|
-
}
|
|
271
|
-
return this.write(tuple ? "]" : hasSubgroup ? ")" : "");
|
|
272
|
-
}
|
|
273
|
-
if ((0, _atscript_core.isConst)(def)) {
|
|
274
|
-
const name = def.token("identifier")?.type === "number" ? def.id : `"${escapeQuotes(def.id)}"`;
|
|
275
|
-
return this.write(name);
|
|
276
|
-
}
|
|
277
|
-
if ((0, _atscript_core.isRef)(def)) {
|
|
278
|
-
const node = def;
|
|
279
|
-
const unwound = this.doc.unwindType(node.id, node.chain);
|
|
280
|
-
if ((0, _atscript_core.isPrimitive)(unwound?.def)) {
|
|
281
|
-
this.write(renderPrimitiveTypeDef(unwound.def.config.type));
|
|
282
|
-
if (node.hasChain) this.write(` /* ${node.chain.map((c) => c.text).join(".")} */`);
|
|
283
|
-
return;
|
|
284
|
-
}
|
|
285
|
-
let name = node.id;
|
|
286
|
-
for (const c of node.chain) name += `["${escapeQuotes(c.text)}"]`;
|
|
287
|
-
return this.write(name);
|
|
288
|
-
}
|
|
289
|
-
if ((0, _atscript_core.isArray)(def)) {
|
|
290
|
-
const def2 = def.getDefinition();
|
|
291
|
-
const isGrp = def2?.entity === "group";
|
|
292
|
-
if (isGrp) this.write("(");
|
|
293
|
-
this.renderTypeDef(def2);
|
|
294
|
-
if (isGrp) this.write(")");
|
|
295
|
-
return this.write("[]");
|
|
296
|
-
}
|
|
297
|
-
if ((0, _atscript_core.isPrimitive)(def)) return this.write(renderPrimitiveTypeDef(def.config.type));
|
|
298
|
-
}
|
|
299
|
-
renderStructure(struct, asClass, interfaceNode, filterProps) {
|
|
300
|
-
this.blockln("{}");
|
|
301
|
-
const patterns = [];
|
|
302
|
-
const propsDefs = /* @__PURE__ */ new Set();
|
|
303
|
-
for (const prop of struct.props.values()) {
|
|
304
|
-
if (filterProps?.has(prop.id)) continue;
|
|
305
|
-
if (prop.token("identifier")?.pattern) {
|
|
306
|
-
if (!filterProps) patterns.push(prop);
|
|
307
|
-
continue;
|
|
308
|
-
}
|
|
309
|
-
const phantomType = this.phantomPropType(prop.getDefinition());
|
|
310
|
-
if (phantomType) {
|
|
311
|
-
this.writeln(`// ${prop.id}: ${phantomType}`);
|
|
312
|
-
continue;
|
|
313
|
-
}
|
|
314
|
-
const optional = !!prop.token("optional");
|
|
315
|
-
this.write(wrapProp(prop.id), optional ? "?" : "", ": ");
|
|
316
|
-
const renderedDef = this.renderTypeDefString(prop.getDefinition());
|
|
317
|
-
propsDefs.add(renderedDef);
|
|
318
|
-
renderedDef.split("\n").forEach((l) => this.writeln(l));
|
|
319
|
-
}
|
|
320
|
-
if (patterns.length > 0) {
|
|
321
|
-
this.write(`[key: string]: `);
|
|
322
|
-
for (const prop of patterns) propsDefs.add(this.renderTypeDefString(prop.getDefinition()));
|
|
323
|
-
const defs = Array.from(propsDefs);
|
|
324
|
-
if (defs.length > 1) {
|
|
325
|
-
this.indent();
|
|
326
|
-
for (const def of defs) {
|
|
327
|
-
this.writeln();
|
|
328
|
-
this.write("| ");
|
|
329
|
-
def.split("\n").forEach((l) => this.write(l.trim()));
|
|
330
|
-
}
|
|
331
|
-
this.unindent();
|
|
332
|
-
this.writeln();
|
|
333
|
-
} else defs[0].split("\n").forEach((l) => this.writeln(l));
|
|
334
|
-
}
|
|
335
|
-
if (asClass) this.renderStaticDeclarations(asClass, interfaceNode);
|
|
336
|
-
this.pop();
|
|
337
|
-
}
|
|
338
|
-
renderStaticDeclarations(asClass, interfaceNode) {
|
|
339
|
-
this.writeln("static __is_atscript_annotated_type: true");
|
|
340
|
-
this.writeln(`static type: TAtscriptTypeObject<keyof ${asClass}, ${asClass}>`);
|
|
341
|
-
this.writeln(`static metadata: TMetadataMap<AtscriptMetadata>`);
|
|
342
|
-
this.writeln(`static validator: (opts?: Partial<TValidatorOptions>) => Validator<typeof ${asClass}>`);
|
|
343
|
-
if (resolveJsonSchemaMode(this.opts) === false) this.writeln("/** @deprecated JSON Schema support is disabled. Calling this method will throw a runtime error. To enable, set `jsonSchema: 'lazy'` or `jsonSchema: 'bundle'` in tsPlugin options, or add `@emit.jsonSchema` annotation to individual interfaces. */");
|
|
344
|
-
this.writeln("static toJsonSchema: () => any");
|
|
345
|
-
if (!this.opts?.exampleData) this.writeln("/** @deprecated Example Data support is disabled. To enable, set `exampleData: true` in tsPlugin options. */");
|
|
346
|
-
this.writeln("static toExampleData?: () => any");
|
|
347
|
-
if (interfaceNode && (0, _atscript_core.isDbEntityNode)(interfaceNode)) {
|
|
348
|
-
this.renderFlat(interfaceNode);
|
|
349
|
-
this.renderOwnProps(interfaceNode);
|
|
350
|
-
this.renderNavProps(interfaceNode);
|
|
351
|
-
this.renderPk(interfaceNode);
|
|
352
|
-
this.renderDimMeasure(interfaceNode);
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
renderInterface(node) {
|
|
356
|
-
this.writeln();
|
|
357
|
-
const exported = node.token("export")?.text === "export";
|
|
358
|
-
this.renderJsDoc(node);
|
|
359
|
-
this.write(exported ? "export declare " : "declare ");
|
|
360
|
-
if (node.hasExtends) {
|
|
361
|
-
const firstParent = node.extendsTokens[0].text;
|
|
362
|
-
this.write(`class ${node.id} extends ${firstParent} `);
|
|
363
|
-
const resolved = this.doc.resolveInterfaceExtends(node);
|
|
364
|
-
if (resolved?.entity === "structure") {
|
|
365
|
-
const firstParentUnwound = this.doc.unwindType(firstParent);
|
|
366
|
-
let firstParentProps;
|
|
367
|
-
if (firstParentUnwound?.def) {
|
|
368
|
-
let fpDef = firstParentUnwound.def;
|
|
369
|
-
if ((0, _atscript_core.isInterface)(fpDef)) {
|
|
370
|
-
if (fpDef.hasExtends) {
|
|
371
|
-
const fpResolved = firstParentUnwound.doc.resolveInterfaceExtends(fpDef);
|
|
372
|
-
if (fpResolved && (0, _atscript_core.isStructure)(fpResolved)) firstParentProps = fpResolved.props;
|
|
373
|
-
}
|
|
374
|
-
if (!firstParentProps) fpDef = fpDef.getDefinition() || fpDef;
|
|
375
|
-
}
|
|
376
|
-
if (!firstParentProps && (0, _atscript_core.isStructure)(fpDef)) firstParentProps = fpDef.props;
|
|
377
|
-
}
|
|
378
|
-
this.renderStructure(resolved, node.id, node, firstParentProps);
|
|
379
|
-
} else this.writeln("{}");
|
|
380
|
-
} else {
|
|
381
|
-
this.write(`class ${node.id} `);
|
|
382
|
-
const struct = node.getDefinition();
|
|
383
|
-
if (struct?.entity === "structure") this.renderStructure(struct, node.id, node);
|
|
384
|
-
else this.writeln("{}");
|
|
385
|
-
}
|
|
386
|
-
this.writeln();
|
|
387
|
-
}
|
|
388
|
-
renderType(node) {
|
|
389
|
-
this.writeln();
|
|
390
|
-
const exported = node.token("export")?.text === "export";
|
|
391
|
-
this.renderJsDoc(node);
|
|
392
|
-
this.write(exported ? "export " : "declare ");
|
|
393
|
-
this.write(`type ${node.id} = `);
|
|
394
|
-
this.renderTypeDef(node.getDefinition());
|
|
395
|
-
this.writeln();
|
|
396
|
-
this.renderTypeNamespace(node);
|
|
397
|
-
}
|
|
398
|
-
renderAnnotate(node) {
|
|
399
|
-
if (node.isMutating) return;
|
|
400
|
-
const targetName = node.targetName;
|
|
401
|
-
this.writeln();
|
|
402
|
-
const exported = node.token("export")?.text === "export";
|
|
403
|
-
this.renderJsDoc(node);
|
|
404
|
-
if (this.isTypeTarget(targetName)) {
|
|
405
|
-
this.write(exported ? "export " : "declare ");
|
|
406
|
-
this.write(`type ${node.id} = ${targetName}`);
|
|
407
|
-
this.writeln();
|
|
408
|
-
const unwound = this.doc.unwindType(targetName);
|
|
409
|
-
this.renderTypeNamespaceFor(node.id, unwound?.def);
|
|
410
|
-
} else {
|
|
411
|
-
this.write(exported ? "export declare " : "declare ");
|
|
412
|
-
this.writeln(`class ${node.id} extends ${targetName} {}`);
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
renderTypeNamespace(node) {
|
|
416
|
-
this.renderTypeNamespaceFor(node.id, node.getDefinition());
|
|
417
|
-
}
|
|
418
|
-
renderTypeNamespaceFor(name, inputDef) {
|
|
419
|
-
this.write(`declare namespace ${name} `);
|
|
420
|
-
this.blockln("{}");
|
|
421
|
-
let typeDef = "TAtscriptTypeDef";
|
|
422
|
-
if (inputDef) {
|
|
423
|
-
let realDef = inputDef;
|
|
424
|
-
if ((0, _atscript_core.isRef)(inputDef)) realDef = this.doc.unwindType(inputDef.id, inputDef.chain)?.def || realDef;
|
|
425
|
-
realDef = this.doc.mergeIntersection(realDef);
|
|
426
|
-
if ((0, _atscript_core.isStructure)(realDef) || (0, _atscript_core.isInterface)(realDef)) typeDef = `TAtscriptTypeObject<keyof ${name}, ${name}>`;
|
|
427
|
-
else if ((0, _atscript_core.isGroup)(realDef)) typeDef = `TAtscriptTypeComplex<${name}>`;
|
|
428
|
-
else if ((0, _atscript_core.isArray)(realDef)) typeDef = `TAtscriptTypeArray<${name}>`;
|
|
429
|
-
else if ((0, _atscript_core.isPrimitive)(realDef)) typeDef = `TAtscriptTypeFinal<${name}>`;
|
|
430
|
-
}
|
|
431
|
-
this.writeln(`const __is_atscript_annotated_type: true`);
|
|
432
|
-
this.writeln(`const type: ${typeDef}`);
|
|
433
|
-
this.writeln(`const metadata: TMetadataMap<AtscriptMetadata>`);
|
|
434
|
-
this.writeln(`const validator: (opts?: Partial<TValidatorOptions>) => Validator<typeof ${name}>`);
|
|
435
|
-
if (resolveJsonSchemaMode(this.opts) === false) this.writeln("/** @deprecated JSON Schema support is disabled. Calling this method will throw a runtime error. To enable, set `jsonSchema: 'lazy'` or `jsonSchema: 'bundle'` in tsPlugin options, or add `@emit.jsonSchema` annotation to individual interfaces. */");
|
|
436
|
-
this.writeln("const toJsonSchema: () => any");
|
|
437
|
-
if (!this.opts?.exampleData) this.writeln("/** @deprecated Example Data support is disabled. To enable, set `exampleData: true` in tsPlugin options. */");
|
|
438
|
-
this.writeln("const toExampleData: (() => any) | undefined");
|
|
439
|
-
this.popln();
|
|
440
|
-
}
|
|
441
|
-
/**
|
|
442
|
-
* Renders the `static __flat` property — a map of all dot-notation paths
|
|
443
|
-
* to their TypeScript value types.
|
|
444
|
-
*
|
|
445
|
-
* This enables type-safe autocomplete for filter keys and `$select`/`$sort`
|
|
446
|
-
* paths when using `AtscriptDbTable`. The `FlatOf<T>` utility type extracts
|
|
447
|
-
* this map at the type level.
|
|
448
|
-
*
|
|
449
|
-
* Special rendering rules:
|
|
450
|
-
* - **Intermediate paths** (structures, arrays of structures) → `never`
|
|
451
|
-
* (prevents `$eq` comparisons, but allows `$select` and `$exists`)
|
|
452
|
-
* - **`@db.json` fields** → `string` (stored as serialized JSON in DB,
|
|
453
|
-
* not individually queryable)
|
|
454
|
-
* - **Leaf fields** → their original TypeScript type
|
|
455
|
-
*/ renderFlat(node) {
|
|
456
|
-
this.renderFlatMap("__flat", (0, _atscript_core.flattenInterfaceNode)(this.doc, node));
|
|
457
|
-
}
|
|
458
|
-
/**
|
|
459
|
-
* Renders the `static __ownProps` property — table-owned fields only (no nav props).
|
|
460
|
-
*/ renderOwnProps(node) {
|
|
461
|
-
this.renderFlatMap("__ownProps", (0, _atscript_core.flattenInterfaceNode)(this.doc, node, { skipNavProps: true }), {
|
|
462
|
-
leadingNewline: true,
|
|
463
|
-
trailingNewline: true
|
|
464
|
-
});
|
|
465
|
-
}
|
|
466
|
-
/**
|
|
467
|
-
* Shared renderer for flat-map static properties (`__flat`, `__ownProps`).
|
|
468
|
-
*
|
|
469
|
-
* Special rendering rules:
|
|
470
|
-
* - **Intermediate paths** (structures, arrays of structures) → `never`
|
|
471
|
-
* - **`@db.json` fields** → `string` (stored as serialized JSON in DB)
|
|
472
|
-
* - **Leaf fields** → their original TypeScript type
|
|
473
|
-
* - **Optional leaf / `@db.json` fields** → `<type> | null` — the DB layer treats
|
|
474
|
-
* optional as nullable in filters, so `null` must be assignable to the path's type
|
|
475
|
-
*/ renderFlatMap(propName, flatMap, opts) {
|
|
476
|
-
if (flatMap.size === 0) return;
|
|
477
|
-
if (opts?.leadingNewline) this.writeln();
|
|
478
|
-
this.write(`static ${propName}: `);
|
|
479
|
-
this.blockln("{}");
|
|
480
|
-
for (const [path, descriptor] of flatMap) {
|
|
481
|
-
this.write(`"${escapeQuotes(path)}"`);
|
|
482
|
-
if (descriptor.optional) this.write("?");
|
|
483
|
-
this.write(": ");
|
|
484
|
-
const nullable = descriptor.optional ? " | null" : "";
|
|
485
|
-
if (descriptor.intermediate) this.writeln("never");
|
|
486
|
-
else if (descriptor.dbJson) this.writeln(`string${nullable}`);
|
|
487
|
-
else {
|
|
488
|
-
const originalDef = descriptor.propNode?.getDefinition();
|
|
489
|
-
const defToRender = originalDef && !((0, _atscript_core.isGroup)(descriptor.def) && descriptor.def !== originalDef) ? originalDef : descriptor.def;
|
|
490
|
-
const lines = this.renderTypeDefString(defToRender).split("\n");
|
|
491
|
-
lines[lines.length - 1] += nullable;
|
|
492
|
-
lines.forEach((l) => this.writeln(l));
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
if (opts?.trailingNewline) this.popln();
|
|
496
|
-
else this.pop();
|
|
497
|
-
}
|
|
498
|
-
/**
|
|
499
|
-
* Renders the `static __navProps` property — a map of navigation property names
|
|
500
|
-
* to their declared TypeScript types.
|
|
501
|
-
*
|
|
502
|
-
* This enables type-safe `$with` in queries: `name` is constrained to known
|
|
503
|
-
* navigation property keys, and nested filter/controls are typed to the target entity.
|
|
504
|
-
*/ renderNavProps(node) {
|
|
505
|
-
let struct;
|
|
506
|
-
if (node.hasExtends) struct = this.doc.resolveInterfaceExtends(node);
|
|
507
|
-
if (!struct) struct = node.getDefinition();
|
|
508
|
-
if (!struct || !(0, _atscript_core.isStructure)(struct)) return;
|
|
509
|
-
const structNode = struct;
|
|
510
|
-
const navProps = [];
|
|
511
|
-
for (const [name, prop] of structNode.props) {
|
|
512
|
-
if (prop.token("identifier")?.pattern) continue;
|
|
513
|
-
if ((0, _atscript_core.hasNavPropAnnotation)(prop)) navProps.push({
|
|
514
|
-
name,
|
|
515
|
-
prop
|
|
516
|
-
});
|
|
517
|
-
}
|
|
518
|
-
if (navProps.length === 0) return;
|
|
519
|
-
this.writeln();
|
|
520
|
-
this.write("static __navProps: ");
|
|
521
|
-
this.blockln("{}");
|
|
522
|
-
for (const { name, prop } of navProps) {
|
|
523
|
-
this.write(`"${escapeQuotes(name)}"`);
|
|
524
|
-
if (prop.token("optional")) this.write("?");
|
|
525
|
-
this.write(": ");
|
|
526
|
-
const propDef = prop.getDefinition();
|
|
527
|
-
if (propDef) this.renderTypeDefString(propDef).split("\n").forEach((l) => this.writeln(l));
|
|
528
|
-
else this.writeln("unknown");
|
|
529
|
-
}
|
|
530
|
-
this.popln();
|
|
531
|
-
}
|
|
532
|
-
renderPk(node) {
|
|
533
|
-
const isMongoCollection = !!node.annotations?.some((a) => a.name === "db.mongo.collection");
|
|
534
|
-
let struct;
|
|
535
|
-
if (node.hasExtends) struct = this.doc.resolveInterfaceExtends(node);
|
|
536
|
-
if (!struct) struct = node.getDefinition();
|
|
537
|
-
if (!struct || !(0, _atscript_core.isStructure)(struct)) return;
|
|
538
|
-
const structNode = struct;
|
|
539
|
-
const pkProps = [];
|
|
540
|
-
const uniqueByIndex = /* @__PURE__ */ new Map();
|
|
541
|
-
for (const [name, prop] of structNode.props) {
|
|
542
|
-
if (prop.token("identifier")?.pattern) continue;
|
|
543
|
-
if (isMongoCollection && name === "_id") continue;
|
|
544
|
-
if (prop.countAnnotations("meta.id") > 0) pkProps.push({
|
|
545
|
-
name,
|
|
546
|
-
prop
|
|
547
|
-
});
|
|
548
|
-
if (prop.annotations) {
|
|
549
|
-
for (const ann of prop.annotations) if (ann.name === "db.index.unique") {
|
|
550
|
-
const indexName = ann.args[0]?.text ?? name;
|
|
551
|
-
let group = uniqueByIndex.get(indexName);
|
|
552
|
-
if (!group) {
|
|
553
|
-
group = [];
|
|
554
|
-
uniqueByIndex.set(indexName, group);
|
|
555
|
-
}
|
|
556
|
-
group.push({
|
|
557
|
-
name,
|
|
558
|
-
prop
|
|
559
|
-
});
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
const uniqueProps = [];
|
|
564
|
-
const pkNames = new Set(pkProps.map((p) => p.name));
|
|
565
|
-
for (const fields of uniqueByIndex.values()) if (fields.length === 1 && !pkNames.has(fields[0].name)) uniqueProps.push(fields[0]);
|
|
566
|
-
if (pkProps.length === 0 && uniqueProps.length === 0 && !isMongoCollection) return;
|
|
567
|
-
let mongoIdType;
|
|
568
|
-
if (isMongoCollection) {
|
|
569
|
-
const idProp = structNode.props.get("_id");
|
|
570
|
-
if (idProp) mongoIdType = this.renderTypeDefString(idProp.getDefinition()).trim();
|
|
571
|
-
mongoIdType ?? (mongoIdType = "string");
|
|
572
|
-
}
|
|
573
|
-
const uniqueTypes = [];
|
|
574
|
-
const seenTypes = /* @__PURE__ */ new Set();
|
|
575
|
-
for (const { prop } of uniqueProps) {
|
|
576
|
-
const rendered = this.renderTypeDefString(prop.getDefinition()).trim();
|
|
577
|
-
if (!seenTypes.has(rendered)) {
|
|
578
|
-
seenTypes.add(rendered);
|
|
579
|
-
uniqueTypes.push(rendered);
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
|
-
this.writeln();
|
|
583
|
-
const uniqueSuffix = uniqueTypes.length > 0 ? ` | ${uniqueTypes.join(" | ")}` : "";
|
|
584
|
-
if (pkProps.length === 0 && !isMongoCollection) this.writeln(`static __pk: ${uniqueTypes.join(" | ")}`);
|
|
585
|
-
else if (pkProps.length === 0) this.writeln(`static __pk: ${mongoIdType}${uniqueSuffix}`);
|
|
586
|
-
else if (pkProps.length === 1) {
|
|
587
|
-
this.write("static __pk: ");
|
|
588
|
-
if (isMongoCollection) this.write(`${mongoIdType} | `);
|
|
589
|
-
const renderedDef = this.renderTypeDefString(pkProps[0].prop.getDefinition()).trim();
|
|
590
|
-
this.writeln(`${renderedDef}${uniqueSuffix}`);
|
|
591
|
-
} else {
|
|
592
|
-
this.write("static __pk: ");
|
|
593
|
-
if (isMongoCollection) this.write(`${mongoIdType} | `);
|
|
594
|
-
this.blockln("{}");
|
|
595
|
-
for (const { name, prop } of pkProps) {
|
|
596
|
-
this.write(wrapProp(name), ": ");
|
|
597
|
-
this.renderTypeDefString(prop.getDefinition()).split("\n").forEach((l) => this.writeln(l));
|
|
598
|
-
}
|
|
599
|
-
this.pop();
|
|
600
|
-
this.writeln(uniqueSuffix);
|
|
601
|
-
}
|
|
602
|
-
}
|
|
603
|
-
renderDimMeasure(node) {
|
|
604
|
-
let struct;
|
|
605
|
-
if (node.hasExtends) struct = this.doc.resolveInterfaceExtends(node);
|
|
606
|
-
if (!struct) struct = node.getDefinition();
|
|
607
|
-
if (!struct || !(0, _atscript_core.isStructure)(struct)) return;
|
|
608
|
-
const structNode = struct;
|
|
609
|
-
const dims = [];
|
|
610
|
-
const measures = [];
|
|
611
|
-
for (const [name, prop] of structNode.props) {
|
|
612
|
-
if (prop.token("identifier")?.pattern) continue;
|
|
613
|
-
if (prop.countAnnotations("db.column.dimension") > 0) dims.push(name);
|
|
614
|
-
if (prop.countAnnotations("db.column.measure") > 0) measures.push(name);
|
|
615
|
-
}
|
|
616
|
-
if (dims.length === 0 && measures.length === 0) return;
|
|
617
|
-
this.writeln();
|
|
618
|
-
if (dims.length > 0) this.writeln(`static __dim: ${dims.map((d) => `"${escapeQuotes(d)}"`).join(" | ")}`);
|
|
619
|
-
if (measures.length > 0) this.writeln(`static __measure: ${measures.map((m) => `"${escapeQuotes(m)}"`).join(" | ")}`);
|
|
620
|
-
}
|
|
621
|
-
phantomPropType(def) {
|
|
622
|
-
if (!def) return;
|
|
623
|
-
if ((0, _atscript_core.isPrimitive)(def) && def.config.type === "phantom") return def.id;
|
|
624
|
-
if ((0, _atscript_core.isRef)(def)) {
|
|
625
|
-
const ref = def;
|
|
626
|
-
const unwound = this.doc.unwindType(ref.id, ref.chain)?.def;
|
|
627
|
-
if ((0, _atscript_core.isPrimitive)(unwound) && unwound.config.type === "phantom") return ref.hasChain ? `${ref.id}.${ref.chain.map((c) => c.text).join(".")}` : ref.id;
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
isTypeTarget(name, doc) {
|
|
631
|
-
const decl = (doc || this.doc).getDeclarationOwnerNode(name);
|
|
632
|
-
if (!decl?.node) return false;
|
|
633
|
-
if (decl.node.entity === "type") return true;
|
|
634
|
-
if (decl.node.entity === "interface") return false;
|
|
635
|
-
if (decl.node.entity === "annotate") return this.isTypeTarget(decl.node.targetName, decl.doc);
|
|
636
|
-
return false;
|
|
637
|
-
}
|
|
638
|
-
renderJsDoc(node) {
|
|
639
|
-
const range = node.token("identifier")?.range;
|
|
640
|
-
const rangeStr = range ? `:${range.start.line + 1}:${range.start.character + 1}` : "";
|
|
641
|
-
this.writeln(`/**`);
|
|
642
|
-
this.writeln(` * Atscript ${node.entity} **${node.id}**`);
|
|
643
|
-
this.writeln(` * @see {@link ./${this.doc.name}${rangeStr}}`);
|
|
644
|
-
this.writeln(` */`);
|
|
645
|
-
}
|
|
646
|
-
constructor(doc, opts) {
|
|
647
|
-
super(doc), _define_property$3(this, "opts", void 0), this.opts = opts;
|
|
648
|
-
}
|
|
649
|
-
};
|
|
650
|
-
function renderPrimitiveTypeDef(def) {
|
|
651
|
-
if (!def) return "unknown";
|
|
652
|
-
if (typeof def === "string") return def === "void" ? "undefined" : def;
|
|
653
|
-
switch (def.kind) {
|
|
654
|
-
case "final": return def.value === "void" ? "undefined" : def.value;
|
|
655
|
-
case "union": return def.items.map(renderPrimitiveTypeDef).join(" | ");
|
|
656
|
-
case "intersection": return def.items.map(renderPrimitiveTypeDef).join(" & ");
|
|
657
|
-
case "tuple": return `[${def.items.map(renderPrimitiveTypeDef).join(", ")}]`;
|
|
658
|
-
case "array": return `${renderPrimitiveTypeDef(def.of)}[]`;
|
|
659
|
-
case "object": return `{ ${Object.entries(def.props).map(([key, val]) => `${wrapProp(key)}${typeof val === "object" && val.optional ? "?" : ""}: ${renderPrimitiveTypeDef(val)}`).join("; ")} }`;
|
|
660
|
-
default: return "unknown";
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
//#endregion
|
|
665
|
-
//#region packages/typescript/src/runtime/compiled-check/build-layout.ts
|
|
666
|
-
/**
|
|
667
|
-
* Build-time layout derivation (renderer and tests; not part of the runtime bundle).
|
|
668
|
-
*/
|
|
669
|
-
/**
|
|
670
|
-
* Derives the layout of `root` (see layout.ts). Shared / recursive type defs are recorded
|
|
671
|
-
* once and referenced by index.
|
|
672
|
-
*/ function buildLayout(root, reader, classify) {
|
|
673
|
-
const defs = [];
|
|
674
|
-
const index = /* @__PURE__ */ new Map();
|
|
675
|
-
let slots = 0;
|
|
676
|
-
function describeDef(type) {
|
|
677
|
-
switch (type.kind) {
|
|
678
|
-
case "": return type.value === void 0 ? [require_json_schema.D_FINAL, type.designType] : [
|
|
679
|
-
require_json_schema.D_FINAL,
|
|
680
|
-
type.designType,
|
|
681
|
-
type.value
|
|
682
|
-
];
|
|
683
|
-
case "object": {
|
|
684
|
-
if (type.propsPatterns.length > 0) return [require_json_schema.D_OBJECT_PATTERNS];
|
|
685
|
-
const props = [...type.props];
|
|
686
|
-
return [
|
|
687
|
-
require_json_schema.D_OBJECT,
|
|
688
|
-
props.map(([key]) => key),
|
|
689
|
-
props.map(([, prop]) => site(prop))
|
|
690
|
-
];
|
|
691
|
-
}
|
|
692
|
-
case "array": return [require_json_schema.D_ARRAY, site(type.of)];
|
|
693
|
-
case "union":
|
|
694
|
-
case "intersection":
|
|
695
|
-
case "tuple": return [require_json_schema.ITEMS_KIND_CODES[type.kind], type.items.map(site)];
|
|
696
|
-
default: return [require_json_schema.D_UNKNOWN, String(type.kind)];
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
function site(node) {
|
|
700
|
-
const type = node.type;
|
|
701
|
-
const marker = classify?.(type);
|
|
702
|
-
const optional = !marker || marker === "ext" ? node.optional ? 1 : 0 : 0;
|
|
703
|
-
let d;
|
|
704
|
-
let keys = {
|
|
705
|
-
mask: 0,
|
|
706
|
-
shape: ""
|
|
707
|
-
};
|
|
708
|
-
if (marker === "interp") d = require_json_schema.INTERP;
|
|
709
|
-
else if (marker === "ext") {
|
|
710
|
-
d = require_json_schema.EXT;
|
|
711
|
-
keys = require_json_schema.readKeys(node.metadata, require_json_schema.siteBits(void 0, optional === 1), reader);
|
|
712
|
-
} else {
|
|
713
|
-
d = index.get(type) ?? -1;
|
|
714
|
-
if (d < 0) {
|
|
715
|
-
d = defs.length;
|
|
716
|
-
defs.push([]);
|
|
717
|
-
index.set(type, d);
|
|
718
|
-
defs[d] = describeDef(type);
|
|
719
|
-
}
|
|
720
|
-
keys = require_json_schema.readKeys(node.metadata, require_json_schema.siteBits(type, optional === 1), reader);
|
|
721
|
-
}
|
|
722
|
-
const result = [
|
|
723
|
-
optional,
|
|
724
|
-
keys.mask,
|
|
725
|
-
d,
|
|
726
|
-
keys.shape,
|
|
727
|
-
slots
|
|
728
|
-
];
|
|
729
|
-
slots += require_json_schema.siteSlotCount(result);
|
|
730
|
-
return result;
|
|
731
|
-
}
|
|
732
|
-
return [
|
|
733
|
-
defs,
|
|
734
|
-
site(root),
|
|
735
|
-
slots
|
|
736
|
-
];
|
|
737
|
-
}
|
|
738
|
-
/** JS source of a layout literal (plain arrays, strings and numbers incl. NaN / ±Infinity / -0). */ function layoutSource(value) {
|
|
739
|
-
if (Array.isArray(value)) return `[${value.map(layoutSource).join(",")}]`;
|
|
740
|
-
return literalSource(value);
|
|
741
|
-
}
|
|
742
|
-
/** JS source of a primitive literal. */ function literalSource(value) {
|
|
743
|
-
if (typeof value === "number") return Object.is(value, -0) ? "-0" : String(value);
|
|
744
|
-
if (typeof value === "string") return JSON.stringify(value).replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
|
|
745
|
-
if (value === void 0) return "undefined";
|
|
746
|
-
return JSON.stringify(value);
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
//#endregion
|
|
750
|
-
//#region packages/typescript/src/runtime/compiled-check/emit.ts
|
|
751
|
-
/**
|
|
752
|
-
* Emits the JS source of a compiled validator check factory from its layout.
|
|
753
|
-
*
|
|
754
|
-
* Build-time only (the renderer, and test code): the runtime never generates code. The
|
|
755
|
-
* emitted factory `(K, H) => check` mirrors the interpreted pre-check
|
|
756
|
-
* (validator-fast-check.ts) node for node — the same checks with the same PASS (1) /
|
|
757
|
-
* FAIL (0) / BAIL (2) contract — specialised to the layout: one function per object type
|
|
758
|
-
* def and per def that closes a reference cycle, everything else inlined.
|
|
759
|
-
*
|
|
760
|
-
* Generated code conventions:
|
|
761
|
-
* - Every function is `(v, f, o)`: the value, the flags (TOP, IN_UNION and option bits —
|
|
762
|
-
* see `optionFlags`) and the validator options (passed on to interpreted sub-checks).
|
|
763
|
-
* - A FAIL statement always leaves the current check: `return 0` outside unions; inside a
|
|
764
|
-
* union (where failures must visit everything the walk would) it records the failure and
|
|
765
|
-
* jumps past the failed node. `q` (`IN_UNION` unset) picks between the two when only the
|
|
766
|
-
* runtime flags tell. BAIL is always `return 2`.
|
|
767
|
-
* - Annotation values are closure constants `k<slot>` read from `K` once per bind.
|
|
768
|
-
*/ function _define_property$2(obj, key, value) {
|
|
769
|
-
if (key in obj) Object.defineProperty(obj, key, {
|
|
770
|
-
value,
|
|
771
|
-
enumerable: true,
|
|
772
|
-
configurable: true,
|
|
773
|
-
writable: true
|
|
774
|
-
});
|
|
775
|
-
else obj[key] = value;
|
|
776
|
-
return obj;
|
|
777
|
-
}
|
|
778
|
-
const ROOT_CTX = {
|
|
779
|
-
fail: "return 0",
|
|
780
|
-
inUnionFail: "return 0",
|
|
781
|
-
union: false,
|
|
782
|
-
clearTop: false
|
|
783
|
-
};
|
|
784
|
-
/** Factory-level helpers (see `TCompiledHelpers`), in declaration order. */ const HELPERS = [
|
|
785
|
-
["pk", /\bpk\./],
|
|
786
|
-
["ho", /\bho\.call\(/],
|
|
787
|
-
["dec", /\bdec\.test\(/],
|
|
788
|
-
["rn", /\brn\(/]
|
|
789
|
-
];
|
|
790
|
-
/** Source of the check factory `(K, H) => check` of `layout`. */ function emitCheckFactory(layout) {
|
|
791
|
-
return new CheckEmitter(layout).emit();
|
|
792
|
-
}
|
|
793
|
-
let CheckEmitter = class CheckEmitter {
|
|
794
|
-
emit() {
|
|
795
|
-
const body = [];
|
|
796
|
-
for (let d = 0; d < this.defs.length; d++) if (this.fn[d]) body.push(...this.defFunction(d));
|
|
797
|
-
const root = this.layout[1];
|
|
798
|
-
const rootDef = root[2] >= 0 ? this.defs[root[2]][0] : -1;
|
|
799
|
-
if (root[0] === 0 && this.fn[root[2]] && (rootDef === require_json_schema.D_OBJECT || rootDef === require_json_schema.D_OBJECT_PATTERNS || rootDef === require_json_schema.D_TUPLE || rootDef === require_json_schema.D_INTERSECTION)) body.push(`return d${root[2]}`);
|
|
800
|
-
else {
|
|
801
|
-
body.push(...this.fnLines("r", () => [...this.site(root, "v", ROOT_CTX), "return 1"]));
|
|
802
|
-
body.push("return r");
|
|
803
|
-
}
|
|
804
|
-
const code = body.join("\n");
|
|
805
|
-
const head = [];
|
|
806
|
-
const helpers = HELPERS.filter(([, use]) => use.test(code)).map(([h]) => `${h} = H.${h}`);
|
|
807
|
-
if (helpers.length > 0) head.push(`const ${helpers.join(", ")}`);
|
|
808
|
-
const slots = [...new Set(Array.from(code.matchAll(/\bk(\d+)\b/g), (m) => Number(m[1])))].filter((k) => k < this.layout[2]).sort((a, b) => a - b);
|
|
809
|
-
for (let i = 0; i < slots.length; i += 16) head.push(`const ${slots.slice(i, i + 16).map((k) => `k${k} = K[${k}]`).join(", ")}`);
|
|
810
|
-
return [
|
|
811
|
-
"(K, H) => {",
|
|
812
|
-
...indent([...head, ...body]),
|
|
813
|
-
"}"
|
|
814
|
-
].join("\n");
|
|
815
|
-
}
|
|
816
|
-
/**
|
|
817
|
-
* Object defs get a function each; so does every def a reference cycle passes through
|
|
818
|
-
* (each back-edge target of a DFS), which keeps inlining finite.
|
|
819
|
-
*/ functionDefs() {
|
|
820
|
-
const defs = this.defs;
|
|
821
|
-
const fn = defs.map((def) => def[0] === require_json_schema.D_OBJECT || def[0] === require_json_schema.D_OBJECT_PATTERNS);
|
|
822
|
-
const state = Array.from({ length: defs.length }).fill(0);
|
|
823
|
-
const dfs = (d) => {
|
|
824
|
-
state[d] = 1;
|
|
825
|
-
for (const site of require_json_schema.childSites(defs[d])) {
|
|
826
|
-
const c = site[2];
|
|
827
|
-
if (c < 0) continue;
|
|
828
|
-
if (state[c] === 1) fn[c] = true;
|
|
829
|
-
else if (state[c] === 0) dfs(c);
|
|
830
|
-
}
|
|
831
|
-
state[d] = 2;
|
|
832
|
-
};
|
|
833
|
-
for (let d = 0; d < defs.length; d++) if (state[d] === 0) dfs(d);
|
|
834
|
-
return fn;
|
|
835
|
-
}
|
|
836
|
-
next(prefix) {
|
|
837
|
-
return `${prefix}${this.uid++}`;
|
|
838
|
-
}
|
|
839
|
-
/** A check function `name(v, f, o)` declaring the `q` / `t` locals its body uses. */ fnLines(name, body) {
|
|
840
|
-
const lines = body();
|
|
841
|
-
const code = lines.join("\n");
|
|
842
|
-
const locals = [];
|
|
843
|
-
if (code.includes("if (q) return 0")) locals.push(`const q = (f & ${require_json_schema.F_IN_UNION}) === 0`);
|
|
844
|
-
if (/\bt = /.test(code)) locals.push("let t");
|
|
845
|
-
return [
|
|
846
|
-
`function ${name}(v, f, o) {`,
|
|
847
|
-
...indent([...locals, ...lines]),
|
|
848
|
-
"}"
|
|
849
|
-
];
|
|
850
|
-
}
|
|
851
|
-
defFunction(d) {
|
|
852
|
-
const def = this.defs[d];
|
|
853
|
-
return this.fnLines(`d${d}`, () => {
|
|
854
|
-
switch (def[0]) {
|
|
855
|
-
case require_json_schema.D_OBJECT: return this.objectBody(def);
|
|
856
|
-
case require_json_schema.D_OBJECT_PATTERNS: return [`if (${notObject("v")}) return 0`, "return 2"];
|
|
857
|
-
case require_json_schema.D_ARRAY: return [...this.items(def[1], "v", ROOT_CTX), "return 1"];
|
|
858
|
-
case require_json_schema.D_UNION: return [...this.unionBranches(def[1], "v", false, (item) => [`return ${choose(this.literalExpr(item), "3", "1")}`]), "return 0"];
|
|
859
|
-
case require_json_schema.D_TUPLE: return [...this.tuple(def[1], "v", ROOT_CTX), "return 1"];
|
|
860
|
-
case require_json_schema.D_INTERSECTION: return [...def[1].flatMap((item) => this.site(item, "v", ROOT_CTX)), "return 1"];
|
|
861
|
-
default: return ["return 2"];
|
|
862
|
-
}
|
|
863
|
-
});
|
|
864
|
-
}
|
|
865
|
-
/** Mirrors `fastCheckObject` (+ `pendStrips` / `hasUnknownKey`). */ objectBody(def) {
|
|
866
|
-
const sites = def[2];
|
|
867
|
-
const props = def[1].map((key, i) => ({
|
|
868
|
-
key,
|
|
869
|
-
site: sites[i]
|
|
870
|
-
})).filter((p) => !this.isPhantom(p.site));
|
|
871
|
-
const lines = [`if (${notObject("v")}) return 0`, "if (pk.length !== 0) return 2"];
|
|
872
|
-
if (props.some((p) => p.site[0] === 0 || p.site[2] === require_json_schema.INTERP)) {
|
|
873
|
-
const top = require_json_schema.F_PARTIAL_TOP | require_json_schema.F_TOP;
|
|
874
|
-
lines.push(`const sk = (f & ${require_json_schema.F_PARTIAL_DEEP}) !== 0 || (f & ${top}) === ${top}`);
|
|
875
|
-
}
|
|
876
|
-
if (props.length > 0) lines.push("let r = 1");
|
|
877
|
-
for (const { key, site } of props) {
|
|
878
|
-
const p = this.next("P");
|
|
879
|
-
const x = this.next("x");
|
|
880
|
-
const access = validIdentifier.test(key) ? `v.${key}` : `v[${literalSource(key)}]`;
|
|
881
|
-
lines.push(`${p}: {`, ` const ${x} = ${access}`);
|
|
882
|
-
if (site[0] === 0 || site[2] === require_json_schema.INTERP) lines.push(` if (${x} === undefined && sk) break ${p}`);
|
|
883
|
-
const ctx = recordingCtx(`r = 0; break ${p}`, false, true);
|
|
884
|
-
lines.push(...indent(this.site(site, x, ctx)), "}");
|
|
885
|
-
}
|
|
886
|
-
if (props.length > 0) lines.push("if (r === 0) return 0");
|
|
887
|
-
const known = props.map((p) => p.key);
|
|
888
|
-
const onUnknown = `{ if ((f & ${require_json_schema.F_ERROR}) !== 0) return 0; if ((f & ${require_json_schema.F_TOP}) === 0) return 2; pk.push(k) }`;
|
|
889
|
-
const scan = known.length === 0 ? [`for (const k in v) if (ho.call(v, k)) ${onUnknown}`] : [
|
|
890
|
-
"for (const k in v) {",
|
|
891
|
-
" switch (k) {",
|
|
892
|
-
...known.map((key) => ` case ${literalSource(key)}:`),
|
|
893
|
-
" break",
|
|
894
|
-
" default:",
|
|
895
|
-
` if (ho.call(v, k)) ${onUnknown}`,
|
|
896
|
-
" }",
|
|
897
|
-
"}"
|
|
898
|
-
];
|
|
899
|
-
lines.push(`if ((f & ${require_json_schema.F_ERROR | require_json_schema.F_STRIP}) !== 0) {`, ...indent(scan), "}", "return 1");
|
|
900
|
-
return lines;
|
|
901
|
-
}
|
|
902
|
-
isPhantom(site) {
|
|
903
|
-
const d = site[2];
|
|
904
|
-
return d >= 0 && this.defs[d][0] === require_json_schema.D_FINAL && this.defs[d][1] === "phantom";
|
|
905
|
-
}
|
|
906
|
-
isLiteralDef(d) {
|
|
907
|
-
return d >= 0 && this.defs[d][0] === require_json_schema.D_FINAL && this.defs[d].length > 2;
|
|
908
|
-
}
|
|
909
|
-
/** A required `never` union branch: it can never match (skipped). */ isNever(site) {
|
|
910
|
-
const d = site[2];
|
|
911
|
-
return site[0] === 0 && d >= 0 && this.defs[d][0] === require_json_schema.D_FINAL && this.defs[d][1] === "never" && !this.isLiteralDef(d);
|
|
912
|
-
}
|
|
913
|
-
/** Expression telling whether the site's type is a literal (`'true'` / `'false'` when known). */ literalExpr(site) {
|
|
914
|
-
const [, , d, , slot] = site;
|
|
915
|
-
if (d >= 0) return this.isLiteralDef(d) ? "true" : "false";
|
|
916
|
-
return `k${d === require_json_schema.INTERP ? slot + 1 : slot + (require_json_schema.hasRejectSlot(site) ? 1 : 0) + 1}`;
|
|
917
|
-
}
|
|
918
|
-
/** Mirrors `fastCheck` for one node holding `x`. */ site(site, x, ctx) {
|
|
919
|
-
const [optional, mask, d, shape, slot] = site;
|
|
920
|
-
if (d === require_json_schema.INTERP) return this.call(`k${slot}`, x, ctx);
|
|
921
|
-
let at = slot;
|
|
922
|
-
const rej = require_json_schema.hasRejectSlot(site) ? at++ : -1;
|
|
923
|
-
const body = d === require_json_schema.EXT ? this.call(`k${at}`, x, ctx) : this.def(d, mask, shape, at, x, ctx);
|
|
924
|
-
if (!optional) return body;
|
|
925
|
-
if (rej < 0) return body.length > 0 ? [
|
|
926
|
-
`if (${x} !== undefined && ${x} !== null) {`,
|
|
927
|
-
...indent(body),
|
|
928
|
-
"}"
|
|
929
|
-
] : [];
|
|
930
|
-
const lines = [`if (${x} === undefined || ${x} === null) {`, ` if (${x} === null && rn(k${rej})) ${ctx.fail}`];
|
|
931
|
-
if (body.length > 0) lines.push("} else {", ...indent(body));
|
|
932
|
-
lines.push("}");
|
|
933
|
-
return lines;
|
|
934
|
-
}
|
|
935
|
-
/** Calls a check function returning 0 / 1 / 2. */ call(fn, x, ctx) {
|
|
936
|
-
this.calls++;
|
|
937
|
-
return [`t = ${fn}(${x}, ${flags(ctx)}, o)`, `if (t !== 1) { if (t === 2) return 2; ${unblock(ctx.fail)} }`];
|
|
938
|
-
}
|
|
939
|
-
def(d, mask, shape, at, x, ctx) {
|
|
940
|
-
const def = this.defs[d];
|
|
941
|
-
const kind = def[0];
|
|
942
|
-
if (this.fn[d] && kind !== require_json_schema.D_ARRAY && kind !== require_json_schema.D_UNION) return this.call(`d${d}`, x, ctx);
|
|
943
|
-
switch (kind) {
|
|
944
|
-
case require_json_schema.D_FINAL: return this.final(def, mask, shape, at, x, ctx.fail);
|
|
945
|
-
case require_json_schema.D_ARRAY: return [
|
|
946
|
-
`if (!Array.isArray(${x})) ${ctx.fail}`,
|
|
947
|
-
...this.arrayConstraints(mask, require_json_schema.keySlots(mask, shape, at), x, ctx.fail),
|
|
948
|
-
...this.fn[d] ? this.call(`d${d}`, x, ctx) : this.items(def[1], x, ctx)
|
|
949
|
-
];
|
|
950
|
-
case require_json_schema.D_UNION: {
|
|
951
|
-
const constraints = this.unionConstraints(mask, shape, at, x, ctx.fail);
|
|
952
|
-
if (!this.fn[d]) return this.union(def[1], {
|
|
953
|
-
mask,
|
|
954
|
-
shape,
|
|
955
|
-
at
|
|
956
|
-
}, constraints, x, ctx);
|
|
957
|
-
this.calls++;
|
|
958
|
-
const lines = [
|
|
959
|
-
`t = d${d}(${x}, ${flags(ctx)}, o)`,
|
|
960
|
-
"if (t === 2) return 2",
|
|
961
|
-
`if (t === 0) ${ctx.fail}`
|
|
962
|
-
];
|
|
963
|
-
if (constraints.length > 0) lines.push("if (t === 1) {", ...indent(constraints), "}");
|
|
964
|
-
return lines;
|
|
965
|
-
}
|
|
966
|
-
case require_json_schema.D_INTERSECTION: return def[1].flatMap((item) => this.site(item, x, ctx));
|
|
967
|
-
case require_json_schema.D_TUPLE: return this.tuple(def[1], x, ctx);
|
|
968
|
-
default: return ["return 2"];
|
|
969
|
-
}
|
|
970
|
-
}
|
|
971
|
-
/** Mirrors `fastCheckFinal` + the string / number / boolean constraints. */ final(def, mask, shape, at, x, fail) {
|
|
972
|
-
const designType = def[1];
|
|
973
|
-
if (designType === "phantom") return [];
|
|
974
|
-
if (def.length > 2) return [`if (${x} !== ${literalSource(def[2])}) ${fail}`];
|
|
975
|
-
const ks = require_json_schema.keySlots(mask, shape, at);
|
|
976
|
-
switch (designType) {
|
|
977
|
-
case "string": return this.stringChecks(mask, shape, ks, x, fail, [`typeof ${x} !== "string"`]);
|
|
978
|
-
case "number": return this.numberChecks(mask, ks, x, fail, [`typeof ${x} !== "number"`, `!Number.isFinite(${x})`]);
|
|
979
|
-
case "boolean": {
|
|
980
|
-
const conds = [`typeof ${x} !== "boolean"`];
|
|
981
|
-
if (mask & require_json_schema.B_REQUIRED) conds.push(`${x} !== true`);
|
|
982
|
-
return [`if (${conds.join(" || ")}) ${fail}`];
|
|
983
|
-
}
|
|
984
|
-
case "any": return [];
|
|
985
|
-
case "never": return [fail];
|
|
986
|
-
case "undefined": return [`if (${x} !== undefined) ${fail}`];
|
|
987
|
-
case "null": return [`if (${x} !== null) ${fail}`];
|
|
988
|
-
case "decimal": return [`if (typeof ${x} !== "string" || !dec.test(${x})) ${fail}`];
|
|
989
|
-
default: return ["return 2"];
|
|
990
|
-
}
|
|
991
|
-
}
|
|
992
|
-
stringChecks(mask, shape, ks, x, fail, conds) {
|
|
993
|
-
if (mask & require_json_schema.B_REQUIRED) conds.push(`${x}.trim().length === 0`);
|
|
994
|
-
if (ks.minLength >= 0) conds.push(`${x}.length < k${ks.minLength}`);
|
|
995
|
-
if (ks.maxLength >= 0) conds.push(`${x}.length > k${ks.maxLength}`);
|
|
996
|
-
const lines = conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
|
|
997
|
-
let p = 0;
|
|
998
|
-
for (const c of shape) if (c === "n") lines.push(`if (!k${ks.patterns[p++]}.test(${x})) ${fail}`);
|
|
999
|
-
else if (c === "s") {
|
|
1000
|
-
lines.push("return 2");
|
|
1001
|
-
break;
|
|
1002
|
-
}
|
|
1003
|
-
return lines;
|
|
1004
|
-
}
|
|
1005
|
-
numberChecks(mask, ks, x, fail, conds) {
|
|
1006
|
-
if (mask & require_json_schema.B_INT) conds.push(`${x} % 1 !== 0`);
|
|
1007
|
-
if (ks.min >= 0) conds.push(`${x} < k${ks.min}`);
|
|
1008
|
-
if (ks.max >= 0) conds.push(`${x} > k${ks.max}`);
|
|
1009
|
-
if (ks.exMin >= 0) conds.push(`${x} <= k${ks.exMin}`);
|
|
1010
|
-
if (ks.exMax >= 0) conds.push(`${x} >= k${ks.exMax}`);
|
|
1011
|
-
return conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
|
|
1012
|
-
}
|
|
1013
|
-
/** Array length constraints; `uniqueItems` (duplicate detection) is left to the walk. */ arrayConstraints(mask, ks, x, fail) {
|
|
1014
|
-
const conds = [];
|
|
1015
|
-
if (ks.minLength >= 0) conds.push(`${x}.length < k${ks.minLength}`);
|
|
1016
|
-
if (ks.maxLength >= 0) conds.push(`${x}.length > k${ks.maxLength}`);
|
|
1017
|
-
const lines = conds.length > 0 ? [`if (${conds.join(" || ")}) ${fail}`] : [];
|
|
1018
|
-
if (mask & require_json_schema.B_UNIQUE) lines.push("return 2");
|
|
1019
|
-
return lines;
|
|
1020
|
-
}
|
|
1021
|
-
/** Mirrors `fastCheckUnionConstraints` (the caller skips literal branches). */ unionConstraints(mask, shape, at, x, fail) {
|
|
1022
|
-
const ks = require_json_schema.keySlots(mask, shape, at);
|
|
1023
|
-
const branches = [];
|
|
1024
|
-
if (mask & require_json_schema.STRING_BITS) branches.push([`typeof ${x} === "string"`, this.stringChecks(mask, shape, ks, x, fail, [])]);
|
|
1025
|
-
if (mask & require_json_schema.NUMBER_BITS) branches.push([`typeof ${x} === "number"`, this.numberChecks(mask, ks, x, fail, [])]);
|
|
1026
|
-
if (mask & require_json_schema.B_REQUIRED) branches.push([`typeof ${x} === "boolean"`, [`if (${x} !== true) ${fail}`]]);
|
|
1027
|
-
if (mask & require_json_schema.ARRAY_BITS) branches.push([`Array.isArray(${x})`, this.arrayConstraints(mask, ks, x, fail)]);
|
|
1028
|
-
const lines = [];
|
|
1029
|
-
branches.forEach(([cond, body], i) => {
|
|
1030
|
-
lines.push(`${i === 0 ? "if" : "} else if"} (${cond}) {`, ...indent(body));
|
|
1031
|
-
});
|
|
1032
|
-
if (lines.length > 0) lines.push("}");
|
|
1033
|
-
return lines;
|
|
1034
|
-
}
|
|
1035
|
-
/**
|
|
1036
|
-
* The union-level constraints after a non-literal branch passed. A required (non-optional)
|
|
1037
|
-
* branch of a known primitive / array type fixes `typeof`: only that part applies.
|
|
1038
|
-
*/ branchConstraints(item, { mask, shape, at }, constraints, x, fail) {
|
|
1039
|
-
const [optional, , d] = item;
|
|
1040
|
-
const def = this.defs[d];
|
|
1041
|
-
if (optional) return constraints;
|
|
1042
|
-
const ks = require_json_schema.keySlots(mask, shape, at);
|
|
1043
|
-
if (def[0] === require_json_schema.D_ARRAY) return this.arrayConstraints(mask, ks, x, fail);
|
|
1044
|
-
if (def[0] !== require_json_schema.D_FINAL) return constraints;
|
|
1045
|
-
switch (def[1]) {
|
|
1046
|
-
case "string": return this.stringChecks(mask, shape, ks, x, fail, []);
|
|
1047
|
-
case "number": return this.numberChecks(mask, ks, x, fail, []);
|
|
1048
|
-
case "boolean": return mask & require_json_schema.B_REQUIRED ? [`if (${x} !== true) ${fail}`] : [];
|
|
1049
|
-
case "null":
|
|
1050
|
-
case "undefined": return [];
|
|
1051
|
-
default: return constraints;
|
|
1052
|
-
}
|
|
1053
|
-
}
|
|
1054
|
-
/**
|
|
1055
|
-
* Mirrors the `fastCheck` union case: branches in declared order, each a labelled block a
|
|
1056
|
-
* FAIL breaks out of; `onMatch` ends a passing branch.
|
|
1057
|
-
*/ unionBranches(items, x, clearTop, onMatch) {
|
|
1058
|
-
const lines = [];
|
|
1059
|
-
for (const item of items) {
|
|
1060
|
-
if (this.isNever(item)) continue;
|
|
1061
|
-
const b = this.next("B");
|
|
1062
|
-
const calls = this.calls;
|
|
1063
|
-
const fail = `break ${b}`;
|
|
1064
|
-
const body = this.site(item, x, {
|
|
1065
|
-
fail,
|
|
1066
|
-
inUnionFail: fail,
|
|
1067
|
-
union: true,
|
|
1068
|
-
clearTop
|
|
1069
|
-
});
|
|
1070
|
-
lines.push(`${b}: {`, ...indent([...body, ...onMatch(item)]), "}");
|
|
1071
|
-
if (this.calls !== calls) lines.push("if (pk.length !== 0) return 2");
|
|
1072
|
-
}
|
|
1073
|
-
return lines;
|
|
1074
|
-
}
|
|
1075
|
-
/** An inline union: the first matching branch passes after the union-level constraints. */ union(items, keys, constraints, x, ctx) {
|
|
1076
|
-
const u = this.next("U");
|
|
1077
|
-
const branches = this.unionBranches(items, x, ctx.clearTop, (item) => {
|
|
1078
|
-
const lines = [];
|
|
1079
|
-
const literal = constraints.length > 0 ? this.literalExpr(item) : "true";
|
|
1080
|
-
if (literal === "false") lines.push(...this.branchConstraints(item, keys, constraints, x, ctx.fail));
|
|
1081
|
-
else if (literal !== "true") lines.push(`if (!${literal}) {`, ...indent(constraints), "}");
|
|
1082
|
-
lines.push(`break ${u}`);
|
|
1083
|
-
return lines;
|
|
1084
|
-
});
|
|
1085
|
-
return [
|
|
1086
|
-
`${u}: {`,
|
|
1087
|
-
...indent([...branches, ctx.fail]),
|
|
1088
|
-
"}"
|
|
1089
|
-
];
|
|
1090
|
-
}
|
|
1091
|
-
/** Mirrors `checkItems`: every item is visited inside a union (BAIL beats FAIL). */ items(of, x, ctx) {
|
|
1092
|
-
const y = this.next("y");
|
|
1093
|
-
const a = this.next("a");
|
|
1094
|
-
const body = this.site(of, y, recordingCtx(`${a} = 0; continue`, ctx.union, true));
|
|
1095
|
-
if (body.length === 0) return [`for (const ${y} of ${x}) {}`];
|
|
1096
|
-
return [
|
|
1097
|
-
`let ${a} = 1`,
|
|
1098
|
-
`for (const ${y} of ${x}) {`,
|
|
1099
|
-
...indent(body),
|
|
1100
|
-
"}",
|
|
1101
|
-
`if (${a} === 0) ${ctx.inUnionFail}`
|
|
1102
|
-
];
|
|
1103
|
-
}
|
|
1104
|
-
/** Mirrors the `fastCheck` tuple case: stops at the first non-passing item. */ tuple(items, x, ctx) {
|
|
1105
|
-
const lines = [`if (!Array.isArray(${x}) || ${x}.length !== ${items.length}) ${ctx.fail}`];
|
|
1106
|
-
items.forEach((item, i) => {
|
|
1107
|
-
const e = this.next("e");
|
|
1108
|
-
lines.push(`const ${e} = ${x}[${i}]`, ...this.site(item, e, {
|
|
1109
|
-
...ctx,
|
|
1110
|
-
clearTop: true
|
|
1111
|
-
}));
|
|
1112
|
-
});
|
|
1113
|
-
return lines;
|
|
1114
|
-
}
|
|
1115
|
-
constructor(layout) {
|
|
1116
|
-
_define_property$2(this, "layout", void 0);
|
|
1117
|
-
_define_property$2(this, "defs", void 0);
|
|
1118
|
-
/** Def index → emitted as its own function. */ _define_property$2(this, "fn", void 0);
|
|
1119
|
-
_define_property$2(this, "uid", void 0);
|
|
1120
|
-
/** Calls emitted so far (a union branch without calls cannot record strips). */ _define_property$2(this, "calls", void 0);
|
|
1121
|
-
this.layout = layout;
|
|
1122
|
-
this.uid = 0;
|
|
1123
|
-
this.calls = 0;
|
|
1124
|
-
this.defs = layout[0];
|
|
1125
|
-
this.fn = this.functionDefs();
|
|
1126
|
-
}
|
|
1127
|
-
};
|
|
1128
|
-
/**
|
|
1129
|
-
* Context of a node whose failure is recorded (`record`: e.g. `r = 0; break P1`) when
|
|
1130
|
-
* inside a union and leaves the check otherwise.
|
|
1131
|
-
*/ function recordingCtx(record, union, clearTop) {
|
|
1132
|
-
const inUnionFail = `{ ${record} }`;
|
|
1133
|
-
return {
|
|
1134
|
-
fail: union ? inUnionFail : `{ if (q) return 0; ${record} }`,
|
|
1135
|
-
inUnionFail,
|
|
1136
|
-
union,
|
|
1137
|
-
clearTop
|
|
1138
|
-
};
|
|
1139
|
-
}
|
|
1140
|
-
/** Flags passed to a callee. */ function flags(ctx) {
|
|
1141
|
-
if (ctx.clearTop) return ctx.union ? `(f & ${~require_json_schema.F_TOP}) | ${require_json_schema.F_IN_UNION}` : `f & ${~require_json_schema.F_TOP}`;
|
|
1142
|
-
return ctx.union ? `f | ${require_json_schema.F_IN_UNION}` : "f";
|
|
1143
|
-
}
|
|
1144
|
-
/** The statements of a `{ … }` block statement (other statements as they are). */ function unblock(statement) {
|
|
1145
|
-
return statement.startsWith("{ ") && statement.endsWith(" }") ? statement.slice(2, -2) : statement;
|
|
1146
|
-
}
|
|
1147
|
-
/** `cond ? a : b` folded when `cond` is a constant. */ function choose(cond, a, b) {
|
|
1148
|
-
return cond === "true" ? a : cond === "false" ? b : `${cond} ? ${a} : ${b}`;
|
|
1149
|
-
}
|
|
1150
|
-
function notObject(x) {
|
|
1151
|
-
return `typeof ${x} !== "object" || ${x} === null || Array.isArray(${x})`;
|
|
1152
|
-
}
|
|
1153
|
-
function indent(lines, n = 2) {
|
|
1154
|
-
const pad = " ".repeat(n);
|
|
1155
|
-
return lines.map((l) => pad + l);
|
|
1156
|
-
}
|
|
1157
|
-
|
|
1158
|
-
//#endregion
|
|
1159
|
-
//#region packages/typescript/src/codegen/validation-model.ts
|
|
1160
|
-
function _define_property$1(obj, key, value) {
|
|
1161
|
-
if (key in obj) Object.defineProperty(obj, key, {
|
|
1162
|
-
value,
|
|
1163
|
-
enumerable: true,
|
|
1164
|
-
configurable: true,
|
|
1165
|
-
writable: true
|
|
1166
|
-
});
|
|
1167
|
-
else obj[key] = value;
|
|
1168
|
-
return obj;
|
|
1169
|
-
}
|
|
1170
|
-
/** Kinds of the opaque types standing for another module's types (see {@link classifyType}). */ const EXT_KIND = "#ext";
|
|
1171
|
-
const INTERP_KIND = "#interp";
|
|
1172
|
-
/**
|
|
1173
|
-
* How the layout treats a model type: `'ext'` — another module's type referenced as a
|
|
1174
|
-
* whole (also an alias / prop clone of one: `cloneTypeDef` keeps the kind); `'interp'` — a
|
|
1175
|
-
* chained reference into another module's type, only known at runtime.
|
|
1176
|
-
*/ function classifyType(type) {
|
|
1177
|
-
const kind = type?.kind;
|
|
1178
|
-
return kind === EXT_KIND ? "ext" : kind === INTERP_KIND ? "interp" : void 0;
|
|
1179
|
-
}
|
|
1180
|
-
/**
|
|
1181
|
-
* Build-time model of the runtime type trees a generated `.as.js` module builds, used to
|
|
1182
|
-
* compile validator checks (`compileValidators`).
|
|
1183
|
-
*
|
|
1184
|
-
* The renderer drives it in lockstep with the builder chains it emits, through the real
|
|
1185
|
-
* runtime builder (`defineAnnotatedType`, `annotate`, `cloneRefProp`), so the model has
|
|
1186
|
-
* the same structure, the same type-def sharing (by identity) and the same validator
|
|
1187
|
-
* annotations as the module after its initialisation. Only the annotations the validator
|
|
1188
|
-
* pre-check reads are recorded. Types of other modules are opaque markers: a reference to
|
|
1189
|
-
* one (also an alias or a cloned prop of one) compiles to a cross-module site, bound at
|
|
1190
|
-
* runtime to the referenced class's own compiled check (see compiled-check/registry.ts).
|
|
1191
|
-
*
|
|
1192
|
-
* Anything the model cannot follow marks it broken; nothing is compiled then. A model that
|
|
1193
|
-
* nevertheless diverges from the runtime only costs speed: the runtime bind detects it and
|
|
1194
|
-
* the interpreted pre-check runs.
|
|
1195
|
-
*/ var ValidationModel = class {
|
|
1196
|
-
/** Runs a model step; a throw marks the model broken. */ run(step) {
|
|
1197
|
-
if (this.broken) return;
|
|
1198
|
-
try {
|
|
1199
|
-
return step();
|
|
1200
|
-
} catch {
|
|
1201
|
-
this.broken = true;
|
|
1202
|
-
return;
|
|
1203
|
-
}
|
|
1204
|
-
}
|
|
1205
|
-
/** Declares a generated class (`static type = {}; static metadata = new Map()`). */ declare(name) {
|
|
1206
|
-
this.classes.set(name, {
|
|
1207
|
-
__is_atscript_annotated_type: true,
|
|
1208
|
-
type: {},
|
|
1209
|
-
metadata: /* @__PURE__ */ new Map(),
|
|
1210
|
-
name
|
|
1211
|
-
});
|
|
1212
|
-
}
|
|
1213
|
-
/** The model of a class declared in this module (anything else: the emitted code throws). */ classBase(name) {
|
|
1214
|
-
const cls = this.classes.get(name);
|
|
1215
|
-
if (!cls) throw new Error(`${name} is not a class of this module`);
|
|
1216
|
-
return cls;
|
|
1217
|
-
}
|
|
1218
|
-
/** `$(kind, name?)`. */ handle(kind, name) {
|
|
1219
|
-
return this.run(() => require_json_schema.defineAnnotatedType(kind, name === void 0 ? void 0 : this.classBase(name)));
|
|
1220
|
-
}
|
|
1221
|
-
/** `.refTo(Local)` / `.refTo(() => Imported)` (with an optional chain). */ refTo(handle, name, imported, chain) {
|
|
1222
|
-
this.run(() => {
|
|
1223
|
-
if (!handle) throw new Error("no chain");
|
|
1224
|
-
if (imported) {
|
|
1225
|
-
const marker = this.marker(name, chain ? INTERP_KIND : EXT_KIND);
|
|
1226
|
-
handle.refTo(() => marker, chain);
|
|
1227
|
-
} else handle.refTo(this.classBase(name), chain);
|
|
1228
|
-
});
|
|
1229
|
-
}
|
|
1230
|
-
/** The opaque stand-in of another module's type `name`. */ marker(name, kind) {
|
|
1231
|
-
const key = `${name}${kind}`;
|
|
1232
|
-
let marker = this.markers.get(key);
|
|
1233
|
-
if (!marker) {
|
|
1234
|
-
marker = {
|
|
1235
|
-
__is_atscript_annotated_type: true,
|
|
1236
|
-
type: { kind },
|
|
1237
|
-
metadata: /* @__PURE__ */ new Map()
|
|
1238
|
-
};
|
|
1239
|
-
this.markers.set(key, marker);
|
|
1240
|
-
}
|
|
1241
|
-
return marker;
|
|
1242
|
-
}
|
|
1243
|
-
/** `.annotate(key, value, multiple)` on the current chain (validator keys only). */ annotate(key, value, multiple) {
|
|
1244
|
-
if (!require_json_schema.isValidatorKey(key)) return;
|
|
1245
|
-
this.run(() => {
|
|
1246
|
-
if (!this.current) throw new Error("no chain");
|
|
1247
|
-
this.current.annotate(key, value, multiple);
|
|
1248
|
-
});
|
|
1249
|
-
}
|
|
1250
|
-
/** The node a mutating-annotate accessor (`Name.type.props.get("a")?…`) points at. */ resolve(name, steps) {
|
|
1251
|
-
let cur = this.classes.get(name);
|
|
1252
|
-
for (const step of steps) {
|
|
1253
|
-
if (cur === void 0 || cur === null) return;
|
|
1254
|
-
if (step === "type") {
|
|
1255
|
-
cur = cur.type;
|
|
1256
|
-
if (classifyType(cur) !== void 0) return;
|
|
1257
|
-
} else if (step[0] === "props") cur = cur.props?.get(step[1]);
|
|
1258
|
-
else cur = cur.items?.[step[1]];
|
|
1259
|
-
}
|
|
1260
|
-
return cur;
|
|
1261
|
-
}
|
|
1262
|
-
/** `$c(<accessor>, "prop")`. */ cloneProp(name, steps, prop) {
|
|
1263
|
-
this.run(() => {
|
|
1264
|
-
const parent = this.resolve(name, steps);
|
|
1265
|
-
if (parent) require_json_schema.cloneRefProp(parent, prop);
|
|
1266
|
-
});
|
|
1267
|
-
}
|
|
1268
|
-
/** `<accessor>.metadata.delete(key)`. */ deleteAnnotation(name, steps, key) {
|
|
1269
|
-
this.run(() => {
|
|
1270
|
-
this.resolve(name, steps)?.metadata?.delete(key);
|
|
1271
|
-
});
|
|
1272
|
-
}
|
|
1273
|
-
/** `$a(<accessor>.metadata, key, value, multiple)`. */ mutateAnnotation(name, steps, key, value, multiple) {
|
|
1274
|
-
if (!require_json_schema.isValidatorKey(key)) return;
|
|
1275
|
-
this.run(() => {
|
|
1276
|
-
require_json_schema.annotate(this.resolve(name, steps)?.metadata, key, value, multiple);
|
|
1277
|
-
});
|
|
1278
|
-
}
|
|
1279
|
-
/**
|
|
1280
|
-
* `$cv(Name, version, layout, factory)` for class `name`, or `undefined` when it cannot be
|
|
1281
|
-
* compiled (its root type is only known at runtime, or the model is broken).
|
|
1282
|
-
*/ registration(name) {
|
|
1283
|
-
if (this.broken) return;
|
|
1284
|
-
const cls = this.classes.get(name);
|
|
1285
|
-
if (!cls) return;
|
|
1286
|
-
let layout;
|
|
1287
|
-
try {
|
|
1288
|
-
layout = buildLayout(cls, { regex: require_json_schema.getRegex }, classifyType);
|
|
1289
|
-
} catch {
|
|
1290
|
-
return;
|
|
1291
|
-
}
|
|
1292
|
-
const root = layout[1][2];
|
|
1293
|
-
if (root === require_json_schema.INTERP || root >= 0 && layout[0][root][0] === require_json_schema.D_UNKNOWN) return;
|
|
1294
|
-
return `$cv(${name}, ${require_json_schema.LAYOUT_VERSION}, ${layoutSource(layout)}, ${emitCheckFactory(layout)})`;
|
|
1295
|
-
}
|
|
1296
|
-
constructor() {
|
|
1297
|
-
/** The model could not follow the emitted code: compile nothing. */ _define_property$1(this, "broken", false);
|
|
1298
|
-
/** Handle of the chain being emitted (the target of `.annotate(…)` lines). */ _define_property$1(this, "current", void 0);
|
|
1299
|
-
_define_property$1(this, "classes", /* @__PURE__ */ new Map());
|
|
1300
|
-
_define_property$1(this, "markers", /* @__PURE__ */ new Map());
|
|
1301
|
-
}
|
|
1302
|
-
};
|
|
1303
|
-
/**
|
|
1304
|
-
* Runtime value of an annotation argument the emitted code writes as a raw expression
|
|
1305
|
-
* (`true`, `5`, `-1.5`, …). Anything else is opaque (truthy and not a number): the bind
|
|
1306
|
-
* compares only presence / truthiness and reads the real values at runtime.
|
|
1307
|
-
*/ function rawLiteralValue(text) {
|
|
1308
|
-
switch (text) {
|
|
1309
|
-
case "true": return true;
|
|
1310
|
-
case "false": return false;
|
|
1311
|
-
case "null": return null;
|
|
1312
|
-
case "undefined": return;
|
|
1313
|
-
default: {
|
|
1314
|
-
const n = Number(text);
|
|
1315
|
-
return text.trim() !== "" && !Number.isNaN(n) ? n : { opaque: text };
|
|
1316
|
-
}
|
|
1317
|
-
}
|
|
1318
|
-
}
|
|
1319
|
-
|
|
1320
|
-
//#endregion
|
|
1321
|
-
//#region packages/typescript/src/codegen/js-renderer.ts
|
|
1322
|
-
function _define_property(obj, key, value) {
|
|
1323
|
-
if (key in obj) Object.defineProperty(obj, key, {
|
|
1324
|
-
value,
|
|
1325
|
-
enumerable: true,
|
|
1326
|
-
configurable: true,
|
|
1327
|
-
writable: true
|
|
1328
|
-
});
|
|
1329
|
-
else obj[key] = value;
|
|
1330
|
-
return obj;
|
|
1331
|
-
}
|
|
1332
|
-
const QUERY_OP_MAP = {
|
|
1333
|
-
"=": "$eq",
|
|
1334
|
-
"!=": "$ne",
|
|
1335
|
-
">": "$gt",
|
|
1336
|
-
">=": "$gte",
|
|
1337
|
-
"<": "$lt",
|
|
1338
|
-
"<=": "$lte",
|
|
1339
|
-
"in": "$in",
|
|
1340
|
-
"not in": "$nin",
|
|
1341
|
-
"matches": "$regex",
|
|
1342
|
-
"exists": "$exists",
|
|
1343
|
-
"not exists": "$exists"
|
|
1344
|
-
};
|
|
1345
|
-
/** Value field of each number-bound annotation's object form. */ const NUMBER_BOUND_FIELDS = {
|
|
1346
|
-
"expect.min": "minValue",
|
|
1347
|
-
"expect.max": "maxValue",
|
|
1348
|
-
"expect.exclusiveMin": "exclusiveMinValue",
|
|
1349
|
-
"expect.exclusiveMax": "exclusiveMaxValue"
|
|
1350
|
-
};
|
|
1351
|
-
const SYNTH_IMPORTS_MARKER = "/*@@atscript-synth-imports@@*/";
|
|
1352
|
-
/** The runtime value of an annotation argument (see `JsRenderer.computeAnnotationValue`). */ function runtimeArg(type, token) {
|
|
1353
|
-
return type === "string" || type === void 0 && token.type === "text" ? token.text : rawLiteralValue(token.text);
|
|
1354
|
-
}
|
|
1355
|
-
/**
|
|
1356
|
-
* The runtime accessor of a mutating-annotate path: `Name` followed by the steps
|
|
1357
|
-
* (`.type`, `.props.get("a")?`, `.items[0]`).
|
|
1358
|
-
*/ function accessorPath(targetName, steps) {
|
|
1359
|
-
let path = targetName;
|
|
1360
|
-
for (const step of steps) path += step === "type" ? ".type" : step[0] === "props" ? `.props.get("${escapeQuotes(step[1])}")?` : `.items[${step[1]}]`;
|
|
1361
|
-
return path;
|
|
1362
|
-
}
|
|
1363
|
-
var JsRenderer = class extends BaseRenderer {
|
|
1364
|
-
/**
|
|
1365
|
-
* Relative imports get the configured `moduleExtension`; bare specifiers
|
|
1366
|
-
* always keep `.as` — they resolve through the package's `exports` map.
|
|
1367
|
-
*/ transformFromPath(path) {
|
|
1368
|
-
return (0, _atscript_core.isBareSpecifier)(path) ? `${path}.as` : `${path}${this.opts?.moduleExtension ?? ".as"}`;
|
|
1369
|
-
}
|
|
1370
|
-
/**
|
|
1371
|
-
* Override base `unused` to subtract symbols that the JS output references
|
|
1372
|
-
* transitively through `extends`-resolved parent prop trees. Without this,
|
|
1373
|
-
* cross-file `extends` strips the imports needed by inherited `.refTo()` calls.
|
|
1374
|
-
*/ get unused() {
|
|
1375
|
-
if (this._unusedJs) return this._unusedJs;
|
|
1376
|
-
const base = new Set(this.doc.getUnusedTokens().map((t) => t.text));
|
|
1377
|
-
for (const ref of this.getExtendsRefs().keys()) if (ref.id) base.delete(ref.id);
|
|
1378
|
-
return this._unusedJs = base;
|
|
1379
|
-
}
|
|
1380
|
-
getExtendsRefs() {
|
|
1381
|
-
if (this._extendsRefs) return this._extendsRefs;
|
|
1382
|
-
const out = /* @__PURE__ */ new Map();
|
|
1383
|
-
const visitedInterfaces = /* @__PURE__ */ new Set();
|
|
1384
|
-
for (const node of this.doc.nodes) if ((0, _atscript_core.isInterface)(node) && node.hasExtends) this.walkExtendsParents(node, this.doc, out, visitedInterfaces);
|
|
1385
|
-
return this._extendsRefs = out;
|
|
1386
|
-
}
|
|
1387
|
-
walkRefs(node, visited, visit) {
|
|
1388
|
-
if (!node || visited.has(node)) return;
|
|
1389
|
-
visited.add(node);
|
|
1390
|
-
if ((0, _atscript_core.isRef)(node)) {
|
|
1391
|
-
visit(node);
|
|
1392
|
-
return;
|
|
1393
|
-
}
|
|
1394
|
-
if ((0, _atscript_core.isGroup)(node)) {
|
|
1395
|
-
for (const item of node.unwrap()) this.walkRefs(item, visited, visit);
|
|
1396
|
-
return;
|
|
1397
|
-
}
|
|
1398
|
-
if ((0, _atscript_core.isArray)(node) || (0, _atscript_core.isProp)(node)) this.walkRefs(node.getDefinition(), visited, visit);
|
|
1399
|
-
}
|
|
1400
|
-
walkExtendsParents(iface, doc, out, visited) {
|
|
1401
|
-
if (visited.has(iface)) return;
|
|
1402
|
-
visited.add(iface);
|
|
1403
|
-
const visitedNodes = /* @__PURE__ */ new Set();
|
|
1404
|
-
for (const token of iface.extendsTokens) {
|
|
1405
|
-
const unwound = doc.unwindType(token.text);
|
|
1406
|
-
if (!unwound?.def || !(0, _atscript_core.isInterface)(unwound.def)) continue;
|
|
1407
|
-
const parentInterface = unwound.def;
|
|
1408
|
-
const parentDoc = unwound.doc;
|
|
1409
|
-
this.walkRefs(parentInterface.getDefinition(), visitedNodes, (ref) => {
|
|
1410
|
-
if (!out.has(ref)) out.set(ref, parentDoc);
|
|
1411
|
-
});
|
|
1412
|
-
if (parentInterface.hasExtends) this.walkExtendsParents(parentInterface, parentDoc, out, visited);
|
|
1413
|
-
}
|
|
1414
|
-
}
|
|
1415
|
-
computeSynthesizedImports() {
|
|
1416
|
-
if (this._synthComputed) return;
|
|
1417
|
-
this._synthComputed = true;
|
|
1418
|
-
const refToOriginDoc = this.getExtendsRefs();
|
|
1419
|
-
if (refToOriginDoc.size === 0) return;
|
|
1420
|
-
for (const [refNode, originDoc] of refToOriginDoc) {
|
|
1421
|
-
const refId = refNode.id;
|
|
1422
|
-
if (!refId) continue;
|
|
1423
|
-
const ownerInfo = this.resolveOwner(originDoc, refId);
|
|
1424
|
-
if (!ownerInfo?.doc || ownerInfo.doc === this.doc) continue;
|
|
1425
|
-
if (ownerInfo.node && (0, _atscript_core.isPrimitive)(ownerInfo.node)) continue;
|
|
1426
|
-
const info = this.synthBinding(refId, ownerInfo);
|
|
1427
|
-
if (!info) continue;
|
|
1428
|
-
this._refSynthInfo.set(refNode, info);
|
|
1429
|
-
}
|
|
1430
|
-
}
|
|
1431
|
-
getSynthTaken() {
|
|
1432
|
-
if (!this._synthTaken) {
|
|
1433
|
-
this._synthTaken = new Set(this.doc.registry.definitions.keys());
|
|
1434
|
-
for (const name of this.doc.importedDefs.keys()) this._synthTaken.add(name);
|
|
1435
|
-
}
|
|
1436
|
-
return this._synthTaken;
|
|
1437
|
-
}
|
|
1438
|
-
getSynthPath(ownerDoc) {
|
|
1439
|
-
if (!this._synthPathCache.has(ownerDoc)) this._synthPathCache.set(ownerDoc, this.computeSynthPath(ownerDoc));
|
|
1440
|
-
return this._synthPathCache.get(ownerDoc);
|
|
1441
|
-
}
|
|
1442
|
-
synthBinding(name, ownerInfo) {
|
|
1443
|
-
const synthPath = this.getSynthPath(ownerInfo.doc);
|
|
1444
|
-
if (!synthPath) return;
|
|
1445
|
-
const allocKey = `${synthPath}::${name}`;
|
|
1446
|
-
let info = this._synthAllocated.get(allocKey);
|
|
1447
|
-
if (!info) {
|
|
1448
|
-
info = this.allocateSynthInfo(name, synthPath, ownerInfo, this.getSynthTaken());
|
|
1449
|
-
this._synthAllocated.set(allocKey, info);
|
|
1450
|
-
}
|
|
1451
|
-
return info;
|
|
1452
|
-
}
|
|
1453
|
-
/**
|
|
1454
|
-
* Binding for a type name used by an annotation argument (`ref` / qualified
|
|
1455
|
-
* query field refs). An annotation inherited from another document (chain ref
|
|
1456
|
-
* or `extends`) carries names that only that document imports, so when the
|
|
1457
|
-
* name does not resolve here to the same declaration, a synthesized import is
|
|
1458
|
-
* allocated (lazily, spliced into the header by `render()`).
|
|
1459
|
-
*/ annotationTypeName(typeName, origin) {
|
|
1460
|
-
if (!origin || origin === this.doc) return typeName;
|
|
1461
|
-
const theirs = this.resolveOwner(origin, typeName);
|
|
1462
|
-
if (!theirs?.doc || !theirs.node || theirs.doc === this.doc || (0, _atscript_core.isPrimitive)(theirs.node)) return typeName;
|
|
1463
|
-
const mine = this.resolveOwner(this.doc, typeName);
|
|
1464
|
-
if (mine?.doc === theirs.doc && mine.node === theirs.node) return typeName;
|
|
1465
|
-
return this.synthBinding(typeName, {
|
|
1466
|
-
doc: theirs.doc,
|
|
1467
|
-
node: theirs.node
|
|
1468
|
-
})?.alias ?? typeName;
|
|
1469
|
-
}
|
|
1470
|
-
resolveOwner(fromDoc, refId) {
|
|
1471
|
-
const key = `${fromDoc.id}::${refId}`;
|
|
1472
|
-
let v = this._ownerCache.get(key);
|
|
1473
|
-
if (v === void 0 && !this._ownerCache.has(key)) {
|
|
1474
|
-
v = fromDoc.getDeclarationOwnerNode(refId);
|
|
1475
|
-
this._ownerCache.set(key, v);
|
|
1476
|
-
}
|
|
1477
|
-
return v;
|
|
1478
|
-
}
|
|
1479
|
-
allocateSynthInfo(refId, synthPath, ownerInfo, taken) {
|
|
1480
|
-
const ownerDoc = ownerInfo.doc;
|
|
1481
|
-
const ownerNode = ownerInfo.node;
|
|
1482
|
-
if (this.doc.importedDefs.get(refId)?.text === synthPath) return {
|
|
1483
|
-
alias: refId,
|
|
1484
|
-
ownerDoc,
|
|
1485
|
-
ownerNode
|
|
1486
|
-
};
|
|
1487
|
-
const alias = this.allocAlias(refId, taken);
|
|
1488
|
-
let group = this._synthImports.get(synthPath);
|
|
1489
|
-
if (!group) {
|
|
1490
|
-
group = [];
|
|
1491
|
-
this._synthImports.set(synthPath, group);
|
|
1492
|
-
}
|
|
1493
|
-
group.push({
|
|
1494
|
-
name: refId,
|
|
1495
|
-
alias
|
|
1496
|
-
});
|
|
1497
|
-
return {
|
|
1498
|
-
alias,
|
|
1499
|
-
ownerDoc,
|
|
1500
|
-
ownerNode
|
|
1501
|
-
};
|
|
1502
|
-
}
|
|
1503
|
-
allocAlias(name, taken) {
|
|
1504
|
-
if (!taken.has(name)) {
|
|
1505
|
-
taken.add(name);
|
|
1506
|
-
return name;
|
|
1507
|
-
}
|
|
1508
|
-
let n = 1;
|
|
1509
|
-
while (taken.has(`${name}_${n}`)) n++;
|
|
1510
|
-
const alias = `${name}_${n}`;
|
|
1511
|
-
taken.add(alias);
|
|
1512
|
-
return alias;
|
|
1513
|
-
}
|
|
1514
|
-
computeSynthPath(ownerDoc) {
|
|
1515
|
-
if ((0, _atscript_core.isBareId)(ownerDoc.id)) return ownerDoc.id.slice(5, -3);
|
|
1516
|
-
if (!ownerDoc.id.startsWith("file://")) return;
|
|
1517
|
-
return (0, _atscript_core.getRelPath)(this.doc.id, ownerDoc.id);
|
|
1518
|
-
}
|
|
1519
|
-
pre() {
|
|
1520
|
-
this.writeln("// prettier-ignore-start");
|
|
1521
|
-
this.writeln("/* eslint-disable */");
|
|
1522
|
-
this.writeln("/* oxlint-disable */");
|
|
1523
|
-
let hasMutatingAnnotate = false;
|
|
1524
|
-
const nodesByName = /* @__PURE__ */ new Map();
|
|
1525
|
-
for (const node of this.doc.nodes) {
|
|
1526
|
-
if (node.entity === "annotate" && node.isMutating) hasMutatingAnnotate = true;
|
|
1527
|
-
if (node.__typeId !== null && node.__typeId !== void 0 && node.id) {
|
|
1528
|
-
const name = node.id;
|
|
1529
|
-
if (!nodesByName.has(name)) nodesByName.set(name, []);
|
|
1530
|
-
nodesByName.get(name).push(node);
|
|
1531
|
-
}
|
|
1532
|
-
}
|
|
1533
|
-
for (const [name, nodes] of nodesByName) if (nodes.length === 1) this.typeIds.set(nodes[0], name);
|
|
1534
|
-
else for (let i = 0; i < nodes.length; i++) this.typeIds.set(nodes[i], `${name}__${i + 1}`);
|
|
1535
|
-
const imports = ["defineAnnotatedType as $", "annotate as $a"];
|
|
1536
|
-
if (hasMutatingAnnotate) imports.push("cloneRefProp as $c");
|
|
1537
|
-
const jsonSchemaMode = resolveJsonSchemaMode(this.opts);
|
|
1538
|
-
if (jsonSchemaMode === "lazy") imports.push("buildJsonSchema as $$");
|
|
1539
|
-
if (this.opts?.exampleData) imports.push("createDataFromAnnotatedType as $e");
|
|
1540
|
-
if (jsonSchemaMode === false) imports.push("throwFeatureDisabled as $d");
|
|
1541
|
-
if (this.model) imports.push("registerCompiledCheck as $cv");
|
|
1542
|
-
this.writeln(`import { ${imports.join(", ")} } from "@atscript/typescript/utils"`);
|
|
1543
|
-
this.computeSynthesizedImports();
|
|
1544
|
-
this.writeln(SYNTH_IMPORTS_MARKER);
|
|
1545
|
-
}
|
|
1546
|
-
render() {
|
|
1547
|
-
const out = super.render();
|
|
1548
|
-
const lines = [];
|
|
1549
|
-
for (const [synthPath, names] of this._synthImports) {
|
|
1550
|
-
const list = names.map((n) => n.alias === n.name ? n.name : `${n.name} as ${n.alias}`).join(", ");
|
|
1551
|
-
lines.push(`import { ${list} } from "${this.transformFromPath(synthPath)}"`);
|
|
1552
|
-
}
|
|
1553
|
-
const marker = `${SYNTH_IMPORTS_MARKER}\n`;
|
|
1554
|
-
return out.replace(marker, () => lines.length > 0 ? `${lines.join("\n")}\n` : "");
|
|
1555
|
-
}
|
|
1556
|
-
buildAdHocMap(annotateNodes) {
|
|
1557
|
-
const map = /* @__PURE__ */ new Map();
|
|
1558
|
-
for (const annotateNode of annotateNodes) for (const entry of annotateNode.entries) {
|
|
1559
|
-
const path = entry.hasChain ? [entry.id, ...entry.chain.map((c) => c.text)].join(".") : entry.id;
|
|
1560
|
-
const anns = entry.annotations || [];
|
|
1561
|
-
if (anns.length > 0) {
|
|
1562
|
-
const existing = map.get(path);
|
|
1563
|
-
if (existing) existing.push(...anns);
|
|
1564
|
-
else map.set(path, [...anns]);
|
|
1565
|
-
}
|
|
1566
|
-
}
|
|
1567
|
-
return map.size > 0 ? map : null;
|
|
1568
|
-
}
|
|
1569
|
-
/**
|
|
1570
|
-
* Checks if any ad-hoc annotation path extends beyond the current _propPath,
|
|
1571
|
-
* meaning annotations target properties inside a referenced type.
|
|
1572
|
-
*/ hasAdHocAnnotationsThroughRef() {
|
|
1573
|
-
if (!this._adHocAnnotations || this._propPath.length === 0) return false;
|
|
1574
|
-
const prefix = `${this._propPath.join(".")}.`;
|
|
1575
|
-
for (const key of this._adHocAnnotations.keys()) if (key.startsWith(prefix)) return true;
|
|
1576
|
-
return false;
|
|
1577
|
-
}
|
|
1578
|
-
post() {
|
|
1579
|
-
for (const node of this.postAnnotate) if (node.entity === "annotate") {
|
|
1580
|
-
const annotateNode = node;
|
|
1581
|
-
if (annotateNode.isMutating) this.renderMutatingAnnotateNode(annotateNode);
|
|
1582
|
-
else {
|
|
1583
|
-
const unwound = this.doc.unwindType(annotateNode.targetName);
|
|
1584
|
-
if (unwound?.def) {
|
|
1585
|
-
let def = this.doc.mergeIntersection(unwound.def);
|
|
1586
|
-
if ((0, _atscript_core.isInterface)(def)) if (def.hasExtends) def = unwound.doc.resolveInterfaceExtends(def) || def.getDefinition() || def;
|
|
1587
|
-
else def = def.getDefinition() || def;
|
|
1588
|
-
this._adHocAnnotations = this.buildAdHocMap([annotateNode]);
|
|
1589
|
-
this.modelClass(node.id, () => this.annotateType(def, node.id));
|
|
1590
|
-
this._adHocAnnotations = null;
|
|
1591
|
-
this.indent();
|
|
1592
|
-
this.defineMetadataForAnnotateAlias(annotateNode);
|
|
1593
|
-
this.unindent();
|
|
1594
|
-
this.writeln();
|
|
1595
|
-
}
|
|
1596
|
-
}
|
|
1597
|
-
} else {
|
|
1598
|
-
let def = node.getDefinition();
|
|
1599
|
-
if ((0, _atscript_core.isInterface)(node) && node.hasExtends) {
|
|
1600
|
-
const resolved = this.doc.resolveInterfaceExtends(node);
|
|
1601
|
-
if (resolved) def = resolved;
|
|
1602
|
-
}
|
|
1603
|
-
this.modelClass(node.id, () => this.annotateType(def, node.id));
|
|
1604
|
-
this.indent().defineMetadata(node).unindent();
|
|
1605
|
-
this.writeln();
|
|
1606
|
-
}
|
|
1607
|
-
this.renderCompiledChecks();
|
|
1608
|
-
this.writeln("// prettier-ignore-end");
|
|
1609
|
-
super.post();
|
|
1610
|
-
}
|
|
1611
|
-
/**
|
|
1612
|
-
* Emits class `name`'s chain; the validation model follows it (its handle stays the current
|
|
1613
|
-
* chain, the target of the class-level annotations emitted next).
|
|
1614
|
-
*/ modelClass(name, emit) {
|
|
1615
|
-
if (this.model) this.model.current = void 0;
|
|
1616
|
-
emit();
|
|
1617
|
-
if (this.model?.current) this.modelClasses.push(name);
|
|
1618
|
-
}
|
|
1619
|
-
/**
|
|
1620
|
-
* `compileValidators`: one `$cv(Class, …)` registration per class, after every chain and
|
|
1621
|
-
* mutating annotate of the module ran (the compiled check binds on first use).
|
|
1622
|
-
*/ renderCompiledChecks() {
|
|
1623
|
-
if (!this.model) return;
|
|
1624
|
-
const registrations = [];
|
|
1625
|
-
for (const name of this.modelClasses) {
|
|
1626
|
-
const registration = this.model.registration(name);
|
|
1627
|
-
if (registration) registrations.push(registration);
|
|
1628
|
-
}
|
|
1629
|
-
if (registrations.length > 0) {
|
|
1630
|
-
this.writeln("// Compiled validator checks");
|
|
1631
|
-
for (const registration of registrations) for (const line of registration.split("\n")) this.writeln(line);
|
|
1632
|
-
this.writeln();
|
|
1633
|
-
}
|
|
1634
|
-
}
|
|
1635
|
-
renderClassStatics(node) {
|
|
1636
|
-
this.writeln("static __is_atscript_annotated_type = true");
|
|
1637
|
-
this.writeln("static type = {}");
|
|
1638
|
-
this.writeln("static metadata = new Map()");
|
|
1639
|
-
const typeId = this.typeIds.get(node);
|
|
1640
|
-
if (typeId) this.writeln(`static id = "${typeId}"`);
|
|
1641
|
-
this.renderJsonSchemaMethod(node);
|
|
1642
|
-
this.renderExampleDataMethod(node);
|
|
1643
|
-
this.renderDimMeasure(node);
|
|
1644
|
-
}
|
|
1645
|
-
renderInterface(node) {
|
|
1646
|
-
this.renderDefinitionClass(node);
|
|
1647
|
-
}
|
|
1648
|
-
renderType(node) {
|
|
1649
|
-
this.renderDefinitionClass(node);
|
|
1650
|
-
}
|
|
1651
|
-
renderAnnotate(node) {
|
|
1652
|
-
if (node.isMutating) {
|
|
1653
|
-
this.postAnnotate.push(node);
|
|
1654
|
-
return;
|
|
1655
|
-
}
|
|
1656
|
-
if (!this.doc.unwindType(node.targetName)?.def) return;
|
|
1657
|
-
this.renderDefinitionClass(node);
|
|
1658
|
-
}
|
|
1659
|
-
renderDefinitionClass(node) {
|
|
1660
|
-
this.writeln();
|
|
1661
|
-
const exported = node.token("export")?.text === "export";
|
|
1662
|
-
this.write(exported ? "export " : "");
|
|
1663
|
-
this.write(`class ${node.id} `);
|
|
1664
|
-
this.blockln("{}");
|
|
1665
|
-
this.model?.declare(node.id);
|
|
1666
|
-
this.renderClassStatics(node);
|
|
1667
|
-
this.popln();
|
|
1668
|
-
this.postAnnotate.push(node);
|
|
1669
|
-
this.writeln();
|
|
1670
|
-
}
|
|
1671
|
-
renderJsonSchemaMethod(node) {
|
|
1672
|
-
const mode = resolveJsonSchemaMode(this.opts);
|
|
1673
|
-
if (node.countAnnotations("emit.jsonSchema") > 0 || mode === "bundle") {
|
|
1674
|
-
const schema = JSON.stringify(require_json_schema.buildJsonSchema(this.toAnnotatedType(node)));
|
|
1675
|
-
this.writeln("static toJsonSchema() {");
|
|
1676
|
-
this.indent().writeln(`return ${schema}`).unindent();
|
|
1677
|
-
this.writeln("}");
|
|
1678
|
-
} else if (mode === "lazy") {
|
|
1679
|
-
this.writeln("static toJsonSchema() {");
|
|
1680
|
-
this.indent().writeln("return this._jsonSchema ?? (this._jsonSchema = $$(this))").unindent();
|
|
1681
|
-
this.writeln("}");
|
|
1682
|
-
} else {
|
|
1683
|
-
this.writeln("static toJsonSchema() {");
|
|
1684
|
-
this.indent().writeln("$d(\"JSON Schema\", \"jsonSchema\", \"emit.jsonSchema\")").unindent();
|
|
1685
|
-
this.writeln("}");
|
|
1686
|
-
}
|
|
1687
|
-
}
|
|
1688
|
-
renderExampleDataMethod(_node) {
|
|
1689
|
-
if (this.opts?.exampleData) {
|
|
1690
|
-
this.writeln("static toExampleData() {");
|
|
1691
|
-
this.indent().writeln("return $e(this, { mode: \"example\" })").unindent();
|
|
1692
|
-
this.writeln("}");
|
|
1693
|
-
}
|
|
1694
|
-
}
|
|
1695
|
-
renderDimMeasure(node) {
|
|
1696
|
-
if (!(0, _atscript_core.isInterface)(node)) return;
|
|
1697
|
-
const interfaceNode = node;
|
|
1698
|
-
if (!(0, _atscript_core.isDbEntityNode)(interfaceNode)) return;
|
|
1699
|
-
let struct;
|
|
1700
|
-
if (interfaceNode.hasExtends) struct = this.doc.resolveInterfaceExtends(interfaceNode);
|
|
1701
|
-
if (!struct) struct = interfaceNode.getDefinition();
|
|
1702
|
-
if (!struct || !(0, _atscript_core.isStructure)(struct)) return;
|
|
1703
|
-
const structNode = struct;
|
|
1704
|
-
const dims = [];
|
|
1705
|
-
const measures = [];
|
|
1706
|
-
for (const [name, prop] of structNode.props) {
|
|
1707
|
-
if (prop.token("identifier")?.pattern) continue;
|
|
1708
|
-
if (prop.countAnnotations("db.column.dimension") > 0) dims.push(name);
|
|
1709
|
-
if (prop.countAnnotations("db.column.measure") > 0) measures.push(name);
|
|
1710
|
-
}
|
|
1711
|
-
if (dims.length > 0) this.writeln(`static dimensions = [${dims.map((d) => `'${escapeQuotes(d)}'`).join(", ")}]`);
|
|
1712
|
-
if (measures.length > 0) this.writeln(`static measures = [${measures.map((m) => `'${escapeQuotes(m)}'`).join(", ")}]`);
|
|
1713
|
-
}
|
|
1714
|
-
toAnnotatedType(node) {
|
|
1715
|
-
return node?.entity === "interface" || node?.entity === "type" ? this.declType(node) : this.toAnnotatedHandle(node).$type;
|
|
1716
|
-
}
|
|
1717
|
-
/**
|
|
1718
|
-
* The build-time runtime type of an interface / type declaration (see `_declTypes`);
|
|
1719
|
-
* `doc` is the document that declares it (where an alias's target name resolves).
|
|
1720
|
-
*/ declType(node, doc = this.doc) {
|
|
1721
|
-
const known = this._declTypes.get(node);
|
|
1722
|
-
if (known) return known;
|
|
1723
|
-
let def = node.getDefinition();
|
|
1724
|
-
if ((0, _atscript_core.isInterface)(node) && node.hasExtends) {
|
|
1725
|
-
const resolved = this.doc.resolveInterfaceExtends(node);
|
|
1726
|
-
if (resolved) def = resolved;
|
|
1727
|
-
}
|
|
1728
|
-
const typeId = this.typeIds.get(node) ?? (node.__typeId !== null && node.__typeId !== void 0 ? node.id : void 0);
|
|
1729
|
-
let handle;
|
|
1730
|
-
if (def && (0, _atscript_core.isRef)(def)) {
|
|
1731
|
-
const ref = def;
|
|
1732
|
-
const decl = doc.unwindType(ref.id, ref.chain)?.def;
|
|
1733
|
-
const target = this.refTarget(ref, decl, doc);
|
|
1734
|
-
handle = target ? require_json_schema.defineAnnotatedType().refTo(target) : this.toAnnotatedHandle(decl, true);
|
|
1735
|
-
} else {
|
|
1736
|
-
const base = {
|
|
1737
|
-
__is_atscript_annotated_type: true,
|
|
1738
|
-
type: {},
|
|
1739
|
-
metadata: /* @__PURE__ */ new Map(),
|
|
1740
|
-
id: typeId
|
|
1741
|
-
};
|
|
1742
|
-
this._declTypes.set(node, base);
|
|
1743
|
-
if (def) this._declTypes.set(def, base);
|
|
1744
|
-
handle = this.toAnnotatedHandle(def, true, base);
|
|
1745
|
-
}
|
|
1746
|
-
this._declTypes.set(node, handle.$type);
|
|
1747
|
-
if (typeId) handle.id(typeId);
|
|
1748
|
-
this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
|
|
1749
|
-
return handle.$type;
|
|
1750
|
-
}
|
|
1751
|
-
/**
|
|
1752
|
-
* The declaration type a reference points at (see `declType`), or `undefined` when it is
|
|
1753
|
-
* not a declaration (a chained reference into a prop, an unresolved name). A plain
|
|
1754
|
-
* reference to a type alias points at the alias itself (its own type and id, like the
|
|
1755
|
-
* runtime `$().refTo(Alias)`), not at what the alias unwinds to.
|
|
1756
|
-
*/ refTarget(ref, decl, doc = this.doc) {
|
|
1757
|
-
if (!decl) return;
|
|
1758
|
-
const owner = ref.hasChain ? void 0 : this.resolveOwner(doc, ref.id);
|
|
1759
|
-
if (owner?.node?.entity === "type" || owner?.node?.entity === "interface") return this.declType(owner.node, owner.doc);
|
|
1760
|
-
const known = this._declTypes.get(decl);
|
|
1761
|
-
if (known) return known;
|
|
1762
|
-
return (0, _atscript_core.isInterface)(decl) ? this.declType(decl) : void 0;
|
|
1763
|
-
}
|
|
1764
|
-
/**
|
|
1765
|
-
* The build-time runtime type of an expression node; with `base`, built into that object
|
|
1766
|
-
* (a declaration's type, see `declType`).
|
|
1767
|
-
*/ toAnnotatedHandle(node, skipAnnotations = false, base) {
|
|
1768
|
-
if (!node) return require_json_schema.defineAnnotatedType(void 0, base);
|
|
1769
|
-
switch (node.entity) {
|
|
1770
|
-
case "interface":
|
|
1771
|
-
case "type": return require_json_schema.defineAnnotatedType().refTo(this.declType(node));
|
|
1772
|
-
case "prop": {
|
|
1773
|
-
const prop = node;
|
|
1774
|
-
const def = prop.getDefinition();
|
|
1775
|
-
const handle = this.toAnnotatedHandle(def, true);
|
|
1776
|
-
if (!skipAnnotations) {
|
|
1777
|
-
this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(prop));
|
|
1778
|
-
if (prop.token("optional")) handle.optional();
|
|
1779
|
-
}
|
|
1780
|
-
return handle;
|
|
1781
|
-
}
|
|
1782
|
-
case "ref": {
|
|
1783
|
-
const ref = node;
|
|
1784
|
-
const decl = this.doc.unwindType(ref.id, ref.chain)?.def;
|
|
1785
|
-
const target = this.refTarget(ref, decl);
|
|
1786
|
-
const handle = target ? require_json_schema.defineAnnotatedType().refTo(target) : this.toAnnotatedHandle(decl, true);
|
|
1787
|
-
if (skipAnnotations) return handle;
|
|
1788
|
-
const own = this.doc.evalAnnotationsForNode(node);
|
|
1789
|
-
const referred = this.refTargetAnnotations(ref, decl);
|
|
1790
|
-
return this.applyExpectAnnotations(handle, referred ? this.doc.mergeNodesAnnotations(referred, own) : own);
|
|
1791
|
-
}
|
|
1792
|
-
case "primitive": {
|
|
1793
|
-
const prim = node;
|
|
1794
|
-
const handle = require_json_schema.defineAnnotatedType(void 0, base);
|
|
1795
|
-
handle.designType(prim.id === "never" ? "never" : prim.config.type);
|
|
1796
|
-
if (!skipAnnotations) this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
|
|
1797
|
-
return handle;
|
|
1798
|
-
}
|
|
1799
|
-
case "const": {
|
|
1800
|
-
const c = node;
|
|
1801
|
-
const handle = require_json_schema.defineAnnotatedType(void 0, base);
|
|
1802
|
-
const t = c.token("identifier")?.type;
|
|
1803
|
-
handle.designType(t === "number" ? "number" : "string");
|
|
1804
|
-
handle.value(t === "number" ? Number(c.id) : c.id);
|
|
1805
|
-
return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
|
|
1806
|
-
}
|
|
1807
|
-
case "structure": {
|
|
1808
|
-
const struct = node;
|
|
1809
|
-
const handle = require_json_schema.defineAnnotatedType("object", base);
|
|
1810
|
-
for (const prop of Array.from(struct.props.values())) {
|
|
1811
|
-
const propHandle = this.toAnnotatedHandle(prop);
|
|
1812
|
-
const pattern = prop.token("identifier")?.pattern;
|
|
1813
|
-
if (pattern) handle.propPattern(pattern, propHandle.$type);
|
|
1814
|
-
else handle.prop(prop.id, propHandle.$type);
|
|
1815
|
-
}
|
|
1816
|
-
return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
|
|
1817
|
-
}
|
|
1818
|
-
case "group": {
|
|
1819
|
-
const group = node;
|
|
1820
|
-
const handle = require_json_schema.defineAnnotatedType(group.op === "|" ? "union" : "intersection", base);
|
|
1821
|
-
for (const item of group.unwrap()) handle.item(this.toAnnotatedHandle(item).$type);
|
|
1822
|
-
return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
|
|
1823
|
-
}
|
|
1824
|
-
case "tuple": {
|
|
1825
|
-
const group = node;
|
|
1826
|
-
const handle = require_json_schema.defineAnnotatedType("tuple", base);
|
|
1827
|
-
for (const item of group.unwrap()) handle.item(this.toAnnotatedHandle(item).$type);
|
|
1828
|
-
return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
|
|
1829
|
-
}
|
|
1830
|
-
case "array": {
|
|
1831
|
-
const arr = node;
|
|
1832
|
-
const handle = require_json_schema.defineAnnotatedType("array", base);
|
|
1833
|
-
handle.of(this.toAnnotatedHandle(arr.getDefinition()).$type);
|
|
1834
|
-
return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
|
|
1835
|
-
}
|
|
1836
|
-
default: {
|
|
1837
|
-
const handle = require_json_schema.defineAnnotatedType(void 0, base);
|
|
1838
|
-
return skipAnnotations ? handle : this.applyExpectAnnotations(handle, this.doc.evalAnnotationsForNode(node));
|
|
1839
|
-
}
|
|
1840
|
-
}
|
|
1841
|
-
}
|
|
1842
|
-
applyExpectAnnotations(handle, annotations) {
|
|
1843
|
-
annotations?.forEach((a) => {
|
|
1844
|
-
switch (a.name) {
|
|
1845
|
-
case "expect.minLength":
|
|
1846
|
-
case "expect.maxLength":
|
|
1847
|
-
if (a.args[0]) handle.annotate(a.name, {
|
|
1848
|
-
length: Number(a.args[0].text),
|
|
1849
|
-
message: a.args[1]?.text
|
|
1850
|
-
});
|
|
1851
|
-
break;
|
|
1852
|
-
case "expect.min":
|
|
1853
|
-
case "expect.max":
|
|
1854
|
-
case "expect.exclusiveMin":
|
|
1855
|
-
case "expect.exclusiveMax":
|
|
1856
|
-
if (a.args[0]) handle.annotate(a.name, {
|
|
1857
|
-
[NUMBER_BOUND_FIELDS[a.name]]: Number(a.args[0].text),
|
|
1858
|
-
message: a.args[1]?.text
|
|
1859
|
-
});
|
|
1860
|
-
break;
|
|
1861
|
-
case "expect.pattern":
|
|
1862
|
-
handle.annotate(a.name, {
|
|
1863
|
-
pattern: a.args[0]?.text || "",
|
|
1864
|
-
flags: a.args[1]?.text,
|
|
1865
|
-
message: a.args[2]?.text
|
|
1866
|
-
}, true);
|
|
1867
|
-
break;
|
|
1868
|
-
case "expect.int":
|
|
1869
|
-
case "meta.required":
|
|
1870
|
-
handle.annotate(a.name, true);
|
|
1871
|
-
break;
|
|
1872
|
-
case "expect.array.uniqueItems":
|
|
1873
|
-
case "expect.array.key":
|
|
1874
|
-
handle.annotate(a.name, { message: a.args[0]?.text });
|
|
1875
|
-
break;
|
|
1876
|
-
default:
|
|
1877
|
-
}
|
|
1878
|
-
});
|
|
1879
|
-
return handle;
|
|
1880
|
-
}
|
|
1881
|
-
annotateType(_node, name) {
|
|
1882
|
-
if (!_node) return this;
|
|
1883
|
-
const node = this.doc.mergeIntersection(_node);
|
|
1884
|
-
let kind = node.entity;
|
|
1885
|
-
switch (node.entity) {
|
|
1886
|
-
case "ref": {
|
|
1887
|
-
const ref = node;
|
|
1888
|
-
const decl = this.doc.unwindType(ref.id, ref.chain)?.def;
|
|
1889
|
-
const primitive = this.inlinedPrimitive(ref, decl);
|
|
1890
|
-
if (primitive) {
|
|
1891
|
-
this.annotateType(primitive, name);
|
|
1892
|
-
return this;
|
|
1893
|
-
}
|
|
1894
|
-
if (this._adHocAnnotations && this.hasAdHocAnnotationsThroughRef()) {
|
|
1895
|
-
let resolved = decl ? this.doc.mergeIntersection(decl) : void 0;
|
|
1896
|
-
if (resolved && (0, _atscript_core.isInterface)(resolved)) resolved = resolved.getDefinition() || resolved;
|
|
1897
|
-
if (resolved) {
|
|
1898
|
-
this.annotateType(resolved, name);
|
|
1899
|
-
return this;
|
|
1900
|
-
}
|
|
1901
|
-
}
|
|
1902
|
-
const chain = ref.hasChain ? `, [${ref.chain.map((c) => `"${escapeQuotes(c.text)}"`).join(", ")}]` : "";
|
|
1903
|
-
const synth = this._refSynthInfo.get(ref);
|
|
1904
|
-
const ownerDecl = synth ? {
|
|
1905
|
-
doc: synth.ownerDoc,
|
|
1906
|
-
node: synth.ownerNode
|
|
1907
|
-
} : this.resolveOwner(this.doc, ref.id);
|
|
1908
|
-
const refName = synth?.alias ?? ref.id;
|
|
1909
|
-
const isImported = !!synth || (ownerDecl ? ownerDecl.doc !== this.doc : false);
|
|
1910
|
-
const refExpr = isImported ? `() => ${refName}` : refName;
|
|
1911
|
-
this.writeln(`$(${name ? `"", ${name}` : ""})`).indent().writeln(`.refTo(${refExpr}${chain})`);
|
|
1912
|
-
this.model?.refTo(this.modelHandle("", name), refName, isImported, ref.hasChain ? ref.chain.map((c) => c.text) : void 0);
|
|
1913
|
-
if (!ref.hasChain) {
|
|
1914
|
-
if (ownerDecl?.node) ownerDecl.doc.evalReferredAnnotations(ownerDecl.node)?.forEach((an) => {
|
|
1915
|
-
this.resolveAnnotationValue(ownerDecl.node, an);
|
|
1916
|
-
});
|
|
1917
|
-
}
|
|
1918
|
-
this.unindent();
|
|
1919
|
-
return this;
|
|
1920
|
-
}
|
|
1921
|
-
case "primitive":
|
|
1922
|
-
this.definePrimitive(node, name);
|
|
1923
|
-
return this;
|
|
1924
|
-
case "const":
|
|
1925
|
-
this.modelHandle("", name);
|
|
1926
|
-
this.writeln(`$(${name ? `"", ${name}` : ""})`).indent().defineConst(node).unindent();
|
|
1927
|
-
return this;
|
|
1928
|
-
case "structure":
|
|
1929
|
-
this.modelHandle("object", name);
|
|
1930
|
-
this.writeln(`$("object"${name ? `, ${name}` : ""})`).indent().defineObject(node).unindent();
|
|
1931
|
-
return this;
|
|
1932
|
-
case "group":
|
|
1933
|
-
kind = node.op === "|" ? "union" : "intersection";
|
|
1934
|
-
this.modelHandle(kind, name);
|
|
1935
|
-
this.writeln(`$("${kind}"${name ? `, ${name}` : ""})`).indent().defineGroup(node).unindent();
|
|
1936
|
-
return this;
|
|
1937
|
-
case "tuple":
|
|
1938
|
-
this.modelHandle("tuple", name);
|
|
1939
|
-
this.writeln(`$("tuple"${name ? `, ${name}` : ""})`).indent().defineGroup(node).unindent();
|
|
1940
|
-
return this;
|
|
1941
|
-
case "array":
|
|
1942
|
-
this.modelHandle("array", name);
|
|
1943
|
-
this.writeln(`$("array"${name ? `, ${name}` : ""})`).indent().defineArray(node).unindent();
|
|
1944
|
-
return this;
|
|
1945
|
-
default: return this;
|
|
1946
|
-
}
|
|
1947
|
-
}
|
|
1948
|
-
/** `$(kind, name?)` in the validation model; it becomes the current chain. */ modelHandle(kind, name) {
|
|
1949
|
-
if (!this.model) return;
|
|
1950
|
-
const h = this.model.handle(kind, name);
|
|
1951
|
-
this.model.current = h;
|
|
1952
|
-
return h;
|
|
1953
|
-
}
|
|
1954
|
-
/**
|
|
1955
|
-
* The model handle of a nested chain (`emit` writes it and its annotations): `current`
|
|
1956
|
-
* is cleared first so a chain that emits nothing breaks the model instead of leaving a
|
|
1957
|
-
* stale handle, and restored to the parent chain afterwards.
|
|
1958
|
-
*/ modelChild(emit) {
|
|
1959
|
-
if (!this.model) {
|
|
1960
|
-
emit();
|
|
1961
|
-
return;
|
|
1962
|
-
}
|
|
1963
|
-
const parent = this.model.current;
|
|
1964
|
-
this.model.current = void 0;
|
|
1965
|
-
emit();
|
|
1966
|
-
const child = this.model.current;
|
|
1967
|
-
this.model.current = parent;
|
|
1968
|
-
if (!child) this.model.broken = true;
|
|
1969
|
-
return child;
|
|
1970
|
-
}
|
|
1971
|
-
defineConst(node) {
|
|
1972
|
-
const t = node.token("identifier")?.type;
|
|
1973
|
-
const designType = t === "text" ? "string" : t === "number" ? "number" : "unknown";
|
|
1974
|
-
this.writeln(`.designType("${escapeQuotes(designType)}")`);
|
|
1975
|
-
this.writeln(`.value(${t === "text" ? `"${escapeQuotes(node.id)}"` : node.id})`);
|
|
1976
|
-
if (this.model) {
|
|
1977
|
-
const h = this.model.current;
|
|
1978
|
-
this.model.run(() => {
|
|
1979
|
-
h.designType(designType).value(t === "text" ? node.id : rawLiteralValue(node.id));
|
|
1980
|
-
});
|
|
1981
|
-
}
|
|
1982
|
-
return this;
|
|
1983
|
-
}
|
|
1984
|
-
definePrimitive(node, name) {
|
|
1985
|
-
this.renderPrimitiveDef(node.id === "never" ? "never" : node.config.type, name);
|
|
1986
|
-
this.writeln(` .tags(${Array.from(node.tags).map((f) => `"${escapeQuotes(f)}"`).join(", ")})`);
|
|
1987
|
-
return this;
|
|
1988
|
-
}
|
|
1989
|
-
/** Emits a primitive's builder chain (and follows it in the validation model). */ renderPrimitiveDef(def, name) {
|
|
1990
|
-
const d = (t) => [`"${t || ""}"`, name].filter(Boolean).join(", ").replace(/^""$/, "");
|
|
1991
|
-
const final = (designType) => {
|
|
1992
|
-
this.writeln(`$(${d()}).designType("${designType}")`);
|
|
1993
|
-
const h = this.modelHandle("", name);
|
|
1994
|
-
this.model?.run(() => h.designType(designType));
|
|
1995
|
-
};
|
|
1996
|
-
if (!def) return final("any");
|
|
1997
|
-
if (typeof def === "string") return final(def === "void" ? "undefined" : def);
|
|
1998
|
-
switch (def.kind) {
|
|
1999
|
-
case "final": return final(def.value === "void" ? "undefined" : def.value);
|
|
2000
|
-
case "union":
|
|
2001
|
-
case "intersection":
|
|
2002
|
-
case "tuple":
|
|
2003
|
-
this.writeln(`$(${d(def.kind)})`);
|
|
2004
|
-
this.modelHandle(def.kind, name);
|
|
2005
|
-
this.indent();
|
|
2006
|
-
for (const itemDef of def.items) {
|
|
2007
|
-
this.write(`.item(`);
|
|
2008
|
-
this.indent();
|
|
2009
|
-
const child = this.modelChild(() => this.renderPrimitiveDef(itemDef));
|
|
2010
|
-
this.writeln(".$type");
|
|
2011
|
-
this.unindent();
|
|
2012
|
-
this.write(`)`);
|
|
2013
|
-
this.model?.run(() => this.model.current.item(child.$type));
|
|
2014
|
-
}
|
|
2015
|
-
this.unindent();
|
|
2016
|
-
return;
|
|
2017
|
-
case "array": {
|
|
2018
|
-
this.writeln(`$(${d("array")})`);
|
|
2019
|
-
this.modelHandle("array", name);
|
|
2020
|
-
this.indent();
|
|
2021
|
-
this.write(".of(");
|
|
2022
|
-
this.indent();
|
|
2023
|
-
const child = this.modelChild(() => this.renderPrimitiveDef(def.of));
|
|
2024
|
-
this.writeln(`.$type`);
|
|
2025
|
-
this.unindent();
|
|
2026
|
-
this.writeln(`)`);
|
|
2027
|
-
this.unindent();
|
|
2028
|
-
this.model?.run(() => this.model.current.of(child.$type));
|
|
2029
|
-
return;
|
|
2030
|
-
}
|
|
2031
|
-
case "object": {
|
|
2032
|
-
this.writeln(`$(${d("object")})`);
|
|
2033
|
-
this.modelHandle("object", name);
|
|
2034
|
-
this.indent();
|
|
2035
|
-
const props = [...Object.entries(def.props).map(([k, p]) => [
|
|
2036
|
-
k,
|
|
2037
|
-
p,
|
|
2038
|
-
false
|
|
2039
|
-
]), ...Object.entries(def.propsPatterns).map(([k, p]) => [
|
|
2040
|
-
k,
|
|
2041
|
-
p,
|
|
2042
|
-
true
|
|
2043
|
-
])];
|
|
2044
|
-
for (const [key, propDef, isPattern] of props) {
|
|
2045
|
-
const optional = typeof propDef === "object" && propDef.optional;
|
|
2046
|
-
this.writeln(isPattern ? `.propPattern(` : `.prop(`);
|
|
2047
|
-
this.indent();
|
|
2048
|
-
this.writeln(isPattern ? `${key},` : `"${escapeQuotes(key)}",`);
|
|
2049
|
-
const child = this.modelChild(() => {
|
|
2050
|
-
this.renderPrimitiveDef(propDef);
|
|
2051
|
-
if (optional) {
|
|
2052
|
-
this.writeln(".optional()");
|
|
2053
|
-
this.model?.run(() => this.model.current.optional());
|
|
2054
|
-
}
|
|
2055
|
-
});
|
|
2056
|
-
this.writeln(".$type");
|
|
2057
|
-
this.unindent();
|
|
2058
|
-
this.write(`)`);
|
|
2059
|
-
this.model?.run(() => isPattern ? this.model.current.propPattern(/./, child.$type) : this.model.current.prop(key, child.$type));
|
|
2060
|
-
}
|
|
2061
|
-
this.unindent();
|
|
2062
|
-
return;
|
|
2063
|
-
}
|
|
2064
|
-
default: return final("any");
|
|
2065
|
-
}
|
|
2066
|
-
}
|
|
2067
|
-
defineObject(node) {
|
|
2068
|
-
const props = Array.from(node.props.values());
|
|
2069
|
-
for (const prop of props) {
|
|
2070
|
-
const pattern = prop.token("identifier")?.pattern;
|
|
2071
|
-
const optional = !!prop.token("optional");
|
|
2072
|
-
this._propPath.push(prop.id);
|
|
2073
|
-
if (pattern) {
|
|
2074
|
-
this.writeln(`.propPattern(`);
|
|
2075
|
-
this.indent();
|
|
2076
|
-
this.writeln(`/${pattern.source}/${pattern.flags},`);
|
|
2077
|
-
} else {
|
|
2078
|
-
this.writeln(`.prop(`);
|
|
2079
|
-
this.indent();
|
|
2080
|
-
this.writeln(`"${escapeQuotes(prop.id)}",`);
|
|
2081
|
-
}
|
|
2082
|
-
const child = this.modelChild(() => {
|
|
2083
|
-
this.annotateType(prop.getDefinition());
|
|
2084
|
-
this.indent().defineMetadata(prop).unindent();
|
|
2085
|
-
});
|
|
2086
|
-
if (optional) this.writeln(" .optional()");
|
|
2087
|
-
this.writeln(" .$type");
|
|
2088
|
-
this.unindent();
|
|
2089
|
-
this.write(`)`);
|
|
2090
|
-
this._propPath.pop();
|
|
2091
|
-
this.model?.run(() => {
|
|
2092
|
-
if (optional) child.optional();
|
|
2093
|
-
if (pattern) this.model.current.propPattern(pattern, child.$type);
|
|
2094
|
-
else this.model.current.prop(prop.id, child.$type);
|
|
2095
|
-
});
|
|
2096
|
-
}
|
|
2097
|
-
this.writeln();
|
|
2098
|
-
return this;
|
|
2099
|
-
}
|
|
2100
|
-
defineGroup(node) {
|
|
2101
|
-
for (const item of node.unwrap()) {
|
|
2102
|
-
this.write(".item(").indent();
|
|
2103
|
-
const child = this.modelChild(() => this.annotateType(item).defineInlinePrimitiveMetadata(item));
|
|
2104
|
-
this.write(" .$type").writeln(`)`).unindent();
|
|
2105
|
-
this.model?.run(() => this.model.current.item(child.$type));
|
|
2106
|
-
}
|
|
2107
|
-
return this;
|
|
2108
|
-
}
|
|
2109
|
-
defineArray(node) {
|
|
2110
|
-
const of = node.getDefinition();
|
|
2111
|
-
this.write(".of(").indent();
|
|
2112
|
-
const child = this.modelChild(() => this.annotateType(of).defineInlinePrimitiveMetadata(of));
|
|
2113
|
-
this.write(" .$type").writeln(`)`).unindent();
|
|
2114
|
-
this.model?.run(() => this.model.current.of(child.$type));
|
|
2115
|
-
return this;
|
|
2116
|
-
}
|
|
2117
|
-
/**
|
|
2118
|
-
* A built-in primitive extension used directly as a union / tuple member or array
|
|
2119
|
-
* element (`number.int | null`, `string.email[]`) is inlined by `annotateType` without
|
|
2120
|
-
* its built-in annotations (`expect.int`, the email pattern, …) — a prop gets them
|
|
2121
|
-
* through `defineMetadata`, a member has no prop to carry them, so emit them here.
|
|
2122
|
-
*/ defineInlinePrimitiveMetadata(node) {
|
|
2123
|
-
const primitive = node && this.inlinedPrimitive(node);
|
|
2124
|
-
if (primitive?.annotations?.length) {
|
|
2125
|
-
this.indent();
|
|
2126
|
-
for (const an of primitive.annotations) this.resolveAnnotationValue(primitive, an);
|
|
2127
|
-
this.unindent();
|
|
2128
|
-
}
|
|
2129
|
-
return this;
|
|
2130
|
-
}
|
|
2131
|
-
/**
|
|
2132
|
-
* The built-in primitive a ref is inlined as by `annotateType` — not a named alias that
|
|
2133
|
-
* resolves to one (`type MyString = string`), which is emitted as a `refTo`.
|
|
2134
|
-
*/ inlinedPrimitive(node, decl = (0, _atscript_core.isRef)(node) ? this.doc.unwindType(node.id, node.chain)?.def : void 0) {
|
|
2135
|
-
if (!(0, _atscript_core.isRef)(node) || !(0, _atscript_core.isPrimitive)(decl)) return;
|
|
2136
|
-
const ownerDecl = this.resolveOwner(this.doc, node.id);
|
|
2137
|
-
if (ownerDecl?.node && (ownerDecl.node.entity === "type" || ownerDecl.node.entity === "interface")) return;
|
|
2138
|
-
return decl;
|
|
2139
|
-
}
|
|
2140
|
-
/** Annotations a ref inherits from its target (see `annotateType`'s ref case). */ refTargetAnnotations(ref, decl) {
|
|
2141
|
-
const primitive = this.inlinedPrimitive(ref, decl);
|
|
2142
|
-
if (primitive) return primitive.annotations;
|
|
2143
|
-
if (ref.hasChain) return;
|
|
2144
|
-
const ownerDecl = this.resolveOwner(this.doc, ref.id);
|
|
2145
|
-
return ownerDecl?.node ? ownerDecl.doc.evalReferredAnnotations(ownerDecl.node) : void 0;
|
|
2146
|
-
}
|
|
2147
|
-
defineMetadata(node) {
|
|
2148
|
-
let annotations;
|
|
2149
|
-
const nodeDef = node.getDefinition?.();
|
|
2150
|
-
if (nodeDef && (0, _atscript_core.isRef)(nodeDef)) {
|
|
2151
|
-
const refNode = nodeDef;
|
|
2152
|
-
if (!refNode.hasChain) {
|
|
2153
|
-
const resolved = this.doc.unwindType(refNode.id, refNode.chain)?.def;
|
|
2154
|
-
if (resolved && !(0, _atscript_core.isPrimitive)(resolved)) annotations = node.annotations ?? [];
|
|
2155
|
-
else if (resolved && (0, _atscript_core.isPrimitive)(resolved)) {
|
|
2156
|
-
const ownerDecl = this.doc.getDeclarationOwnerNode(refNode.id);
|
|
2157
|
-
if (ownerDecl?.node && (ownerDecl.node.entity === "type" || ownerDecl.node.entity === "interface")) annotations = node.annotations ?? [];
|
|
2158
|
-
}
|
|
2159
|
-
}
|
|
2160
|
-
}
|
|
2161
|
-
if (annotations === void 0) annotations = this.doc.evalAnnotationsForNode(node);
|
|
2162
|
-
if (this._adHocAnnotations && this._propPath.length > 0) {
|
|
2163
|
-
const path = this._propPath.join(".");
|
|
2164
|
-
const adHoc = this._adHocAnnotations.get(path);
|
|
2165
|
-
if (adHoc) annotations = this.doc.mergeNodesAnnotations(annotations, adHoc);
|
|
2166
|
-
}
|
|
2167
|
-
annotations?.forEach((an) => {
|
|
2168
|
-
this.resolveAnnotationValue(node, an);
|
|
2169
|
-
});
|
|
2170
|
-
return this;
|
|
2171
|
-
}
|
|
2172
|
-
/**
|
|
2173
|
-
* For non-mutating annotate aliases: merge the target's type-level annotations
|
|
2174
|
-
* with the annotate block's own annotations (annotate's take priority).
|
|
2175
|
-
*/ defineMetadataForAnnotateAlias(annotateNode) {
|
|
2176
|
-
const annotateAnnotations = this.doc.evalAnnotationsForNode(annotateNode);
|
|
2177
|
-
const targetDecl = this.doc.getDeclarationOwnerNode(annotateNode.targetName);
|
|
2178
|
-
const targetAnnotations = targetDecl?.node ? targetDecl.doc.evalAnnotationsForNode(targetDecl.node) : void 0;
|
|
2179
|
-
this.doc.mergeNodesAnnotations(targetAnnotations, annotateAnnotations).forEach((an) => {
|
|
2180
|
-
this.resolveAnnotationValue(annotateNode, an);
|
|
2181
|
-
});
|
|
2182
|
-
return this;
|
|
2183
|
-
}
|
|
2184
|
-
resolveAnnotationValue(node, an) {
|
|
2185
|
-
const { value, multiple, runtime } = this.computeAnnotationValue(node, an);
|
|
2186
|
-
if (multiple) this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value}, true)`);
|
|
2187
|
-
else this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value})`);
|
|
2188
|
-
this.model?.annotate(an.name, runtime, multiple);
|
|
2189
|
-
}
|
|
2190
|
-
emitRefValue(text, origin) {
|
|
2191
|
-
const dotIdx = text.indexOf(".");
|
|
2192
|
-
if (dotIdx === -1) return `() => ${this.annotationTypeName(text, origin)}`;
|
|
2193
|
-
return `{ type: () => ${this.annotationTypeName(text.slice(0, dotIdx), origin)}, field: "${escapeQuotes(text.slice(dotIdx + 1))}" }`;
|
|
2194
|
-
}
|
|
2195
|
-
emitArgValue(aSpec, argToken, origin) {
|
|
2196
|
-
if (aSpec.type === "ref") return this.emitRefValue(argToken.text, origin);
|
|
2197
|
-
if (aSpec.type === "query" && argToken.queryNode) return this.emitQueryTree(argToken.queryNode, origin);
|
|
2198
|
-
if (aSpec.type === "expr" && argToken.exprNode) return this.emitExprNode(argToken.exprNode.expression, origin);
|
|
2199
|
-
if (aSpec.type === "order" && argToken.orderNode) return `[${argToken.orderNode.items.map((item) => `{ ref: ${this.emitQueryFieldRef(item.ref, origin)}${item.desc ? ", desc: true" : ""} }`).join(", ")}]`;
|
|
2200
|
-
return aSpec.type === "string" ? `"${escapeQuotes(argToken.text)}"` : argToken.text;
|
|
2201
|
-
}
|
|
2202
|
-
emitExprNode(node, origin) {
|
|
2203
|
-
switch (node.entity) {
|
|
2204
|
-
case "query-expr-number": return String(node.value);
|
|
2205
|
-
case "query-expr-binary": {
|
|
2206
|
-
const { op, left, right } = node;
|
|
2207
|
-
return `{ op: "${op}", args: [${this.emitExprNode(left, origin)}, ${this.emitExprNode(right, origin)}] }`;
|
|
2208
|
-
}
|
|
2209
|
-
case "query-expr-unary": {
|
|
2210
|
-
const { op, operand } = node;
|
|
2211
|
-
return `{ op: "${op}", args: [${this.emitExprNode(operand, origin)}] }`;
|
|
2212
|
-
}
|
|
2213
|
-
case "query-expr-call": {
|
|
2214
|
-
const { fn, args } = node;
|
|
2215
|
-
return `{ op: "${fn}", args: [${args.map((a) => this.emitExprNode(a, origin)).join(", ")}] }`;
|
|
2216
|
-
}
|
|
2217
|
-
default: return this.emitQueryFieldRef(node, origin);
|
|
2218
|
-
}
|
|
2219
|
-
}
|
|
2220
|
-
emitQueryTree(queryNode, origin) {
|
|
2221
|
-
return this.emitQueryExpr(queryNode.expression, origin);
|
|
2222
|
-
}
|
|
2223
|
-
emitQueryExpr(node, origin) {
|
|
2224
|
-
if ((0, _atscript_core.isQueryLogical)(node)) return this.emitQueryLogical(node, origin);
|
|
2225
|
-
return this.emitQueryComparison(node, origin);
|
|
2226
|
-
}
|
|
2227
|
-
emitQueryLogical(node, origin) {
|
|
2228
|
-
if (node.operator === "not") return `{ "$not": ${this.emitQueryExpr(node.operands[0], origin)} }`;
|
|
2229
|
-
return `{ "${node.operator === "and" ? "$and" : "$or"}": [${node.operands.map((op) => this.emitQueryExpr(op, origin)).join(", ")}] }`;
|
|
2230
|
-
}
|
|
2231
|
-
emitQueryComparison(node, origin) {
|
|
2232
|
-
const left = this.emitQueryFieldRef(node.left, origin);
|
|
2233
|
-
const mappedOp = QUERY_OP_MAP[node.operator] || node.operator;
|
|
2234
|
-
const parts = [`left: ${left}`, `op: "${mappedOp}"`];
|
|
2235
|
-
if (node.right) {
|
|
2236
|
-
if ("fieldRef" in node.right && node.right.fieldRef) parts.push(`right: ${this.emitQueryFieldRef(node.right, origin)}`);
|
|
2237
|
-
else if ("values" in node.right && node.right.values) {
|
|
2238
|
-
const values = node.right.values.map((v) => this.emitQueryLiteral(v)).join(", ");
|
|
2239
|
-
parts.push(`right: [${values}]`);
|
|
2240
|
-
} else if ("valueToken" in node.right) parts.push(`right: ${this.emitQueryLiteral(node.right)}`);
|
|
2241
|
-
} else if (node.operator === "exists") parts.push("right: true");
|
|
2242
|
-
else if (node.operator === "not exists") parts.push("right: false");
|
|
2243
|
-
return `{ ${parts.join(", ")} }`;
|
|
2244
|
-
}
|
|
2245
|
-
emitQueryFieldRef(node, origin) {
|
|
2246
|
-
const parts = [];
|
|
2247
|
-
if (node.typeRef) parts.push(`type: () => ${this.annotationTypeName(node.typeRef.text, origin)}`);
|
|
2248
|
-
parts.push(`field: "${escapeQuotes(node.fieldRef.text)}"`);
|
|
2249
|
-
return `{ ${parts.join(", ")} }`;
|
|
2250
|
-
}
|
|
2251
|
-
emitQueryLiteral(node) {
|
|
2252
|
-
const token = node.valueToken;
|
|
2253
|
-
switch (token.type) {
|
|
2254
|
-
case "text": return `"${escapeQuotes(token.text)}"`;
|
|
2255
|
-
case "number": return token.text;
|
|
2256
|
-
case "regexp": {
|
|
2257
|
-
const match = /^\/(.*)\/[a-z]*$/.exec(token.text);
|
|
2258
|
-
return `"${escapeQuotes(match ? match[1] : token.text)}"`;
|
|
2259
|
-
}
|
|
2260
|
-
case "identifier":
|
|
2261
|
-
if (token.text === "true" || token.text === "false") return token.text;
|
|
2262
|
-
if (token.text === "null" || token.text === "undefined") return "null";
|
|
2263
|
-
return token.text;
|
|
2264
|
-
default: return token.text;
|
|
2265
|
-
}
|
|
2266
|
-
}
|
|
2267
|
-
/**
|
|
2268
|
-
* The JS source of an annotation's value, and (for the validation model, which only reads
|
|
2269
|
-
* validator annotations: numbers, strings, flags) the runtime value it evaluates to;
|
|
2270
|
-
* other argument kinds are opaque there.
|
|
2271
|
-
*/ computeAnnotationValue(node, an) {
|
|
2272
|
-
const origin = this.doc.annotationOrigin(an);
|
|
2273
|
-
const spec = this.doc.resolveAnnotation(an.name);
|
|
2274
|
-
let targetValue = "true";
|
|
2275
|
-
let runtime = true;
|
|
2276
|
-
let multiple = false;
|
|
2277
|
-
if (spec) {
|
|
2278
|
-
multiple = spec.config.multiple;
|
|
2279
|
-
const length = spec.arguments.length;
|
|
2280
|
-
if (length !== 0) {
|
|
2281
|
-
if (Array.isArray(spec.config.argument)) {
|
|
2282
|
-
targetValue = "{ ";
|
|
2283
|
-
const fields = {};
|
|
2284
|
-
let i = 0;
|
|
2285
|
-
for (const aSpec of spec.arguments) {
|
|
2286
|
-
if (an.args[i]) {
|
|
2287
|
-
targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i], origin)}${i === length - 1 ? "" : ", "} `;
|
|
2288
|
-
fields[aSpec.name] = runtimeArg(aSpec.type, an.args[i]);
|
|
2289
|
-
}
|
|
2290
|
-
i++;
|
|
2291
|
-
}
|
|
2292
|
-
targetValue += "}";
|
|
2293
|
-
runtime = fields;
|
|
2294
|
-
} else if (an.args[0]) {
|
|
2295
|
-
const aSpec = spec.arguments[0];
|
|
2296
|
-
targetValue = this.emitArgValue(aSpec, an.args[0], origin);
|
|
2297
|
-
runtime = runtimeArg(aSpec.type, an.args[0]);
|
|
2298
|
-
}
|
|
2299
|
-
}
|
|
2300
|
-
} else {
|
|
2301
|
-
multiple = node.countAnnotations(an.name) > 1 || an.args.length > 1;
|
|
2302
|
-
if (an.args.length > 0) {
|
|
2303
|
-
targetValue = an.args[0].type === "text" ? `"${escapeQuotes(an.args[0].text)}"` : an.args[0].text;
|
|
2304
|
-
runtime = runtimeArg(void 0, an.args[0]);
|
|
2305
|
-
}
|
|
2306
|
-
}
|
|
2307
|
-
return {
|
|
2308
|
-
value: targetValue,
|
|
2309
|
-
multiple: !!multiple,
|
|
2310
|
-
runtime
|
|
2311
|
-
};
|
|
2312
|
-
}
|
|
2313
|
-
renderMutatingAnnotateNode(node) {
|
|
2314
|
-
const targetName = node.targetName;
|
|
2315
|
-
const targetDef = this.resolveTargetDef(targetName);
|
|
2316
|
-
this.writeln("// Ad-hoc annotations for ", targetName);
|
|
2317
|
-
const allClones = [];
|
|
2318
|
-
const entryAccessors = [];
|
|
2319
|
-
for (const entry of node.entries) {
|
|
2320
|
-
const anns = entry.annotations;
|
|
2321
|
-
if (!anns || anns.length === 0) continue;
|
|
2322
|
-
const parts = entry.hasChain ? [entry.id, ...entry.chain.map((c) => c.text)] : [entry.id];
|
|
2323
|
-
const { accessors, clones } = this.buildMutatingAccessors(targetDef, parts);
|
|
2324
|
-
allClones.push(...clones);
|
|
2325
|
-
entryAccessors.push({
|
|
2326
|
-
entry,
|
|
2327
|
-
accessors
|
|
2328
|
-
});
|
|
2329
|
-
}
|
|
2330
|
-
const cloneKeys = /* @__PURE__ */ new Set();
|
|
2331
|
-
for (const clone of allClones) {
|
|
2332
|
-
const parentPath = accessorPath(targetName, clone.parentSteps);
|
|
2333
|
-
const key = `${parentPath}|${clone.propName}`;
|
|
2334
|
-
if (!cloneKeys.has(key)) {
|
|
2335
|
-
cloneKeys.add(key);
|
|
2336
|
-
this.writeln(`$c(${parentPath}, "${escapeQuotes(clone.propName)}")`);
|
|
2337
|
-
this.model?.cloneProp(targetName, clone.parentSteps, clone.propName);
|
|
2338
|
-
}
|
|
2339
|
-
}
|
|
2340
|
-
for (const { entry, accessors } of entryAccessors) for (const accessor of accessors) this.emitMutatingAnnotations(entry, entry.annotations, accessor, targetName);
|
|
2341
|
-
const topAnnotations = node.annotations;
|
|
2342
|
-
if (topAnnotations && topAnnotations.length > 0) this.emitMutatingAnnotations(node, topAnnotations, [], targetName);
|
|
2343
|
-
this.writeln();
|
|
2344
|
-
}
|
|
2345
|
-
emitMutatingAnnotations(node, annotations, steps, targetName) {
|
|
2346
|
-
const accessor = accessorPath(targetName, steps);
|
|
2347
|
-
const cleared = /* @__PURE__ */ new Set();
|
|
2348
|
-
for (const an of annotations) {
|
|
2349
|
-
const { value, multiple, runtime } = this.computeAnnotationValue(node, an);
|
|
2350
|
-
if (multiple) {
|
|
2351
|
-
if (!cleared.has(an.name)) {
|
|
2352
|
-
const spec = this.doc.resolveAnnotation(an.name);
|
|
2353
|
-
if (!spec || spec.config.mergeStrategy !== "append") {
|
|
2354
|
-
this.writeln(`${accessor}.metadata.delete("${escapeQuotes(an.name)}")`);
|
|
2355
|
-
this.model?.deleteAnnotation(targetName, steps, an.name);
|
|
2356
|
-
}
|
|
2357
|
-
cleared.add(an.name);
|
|
2358
|
-
}
|
|
2359
|
-
this.writeln(`$a(${accessor}.metadata, "${escapeQuotes(an.name)}", ${value}, true)`);
|
|
2360
|
-
} else this.writeln(`$a(${accessor}.metadata, "${escapeQuotes(an.name)}", ${value})`);
|
|
2361
|
-
this.model?.mutateAnnotation(targetName, steps, an.name, runtime, multiple);
|
|
2362
|
-
}
|
|
2363
|
-
}
|
|
2364
|
-
resolveTargetDef(targetName) {
|
|
2365
|
-
const unwound = this.doc.unwindType(targetName);
|
|
2366
|
-
if (!unwound?.def) return;
|
|
2367
|
-
let def = unwound.def;
|
|
2368
|
-
if ((0, _atscript_core.isInterface)(def)) def = def.getDefinition() || def;
|
|
2369
|
-
return def;
|
|
2370
|
-
}
|
|
2371
|
-
/**
|
|
2372
|
-
* Builds the accessor paths (as steps, see `accessorPath`) for mutating annotate entries.
|
|
2373
|
-
* Computes exact paths at compile time by walking the AST,
|
|
2374
|
-
* so the generated JS accesses props directly without runtime search.
|
|
2375
|
-
* Returns multiple paths when a property appears in multiple union branches.
|
|
2376
|
-
*/ buildMutatingAccessors(targetDef, parts) {
|
|
2377
|
-
let accessors = [{
|
|
2378
|
-
steps: ["type"],
|
|
2379
|
-
def: targetDef
|
|
2380
|
-
}];
|
|
2381
|
-
const clones = [];
|
|
2382
|
-
for (let i = 0; i < parts.length; i++) {
|
|
2383
|
-
const last = i === parts.length - 1;
|
|
2384
|
-
const nextAccessors = [];
|
|
2385
|
-
for (const { steps, def } of accessors) {
|
|
2386
|
-
const results = this.buildPropPaths(def, parts[i]);
|
|
2387
|
-
const found = results.length > 0 ? results : [{
|
|
2388
|
-
steps: [["props", parts[i]]],
|
|
2389
|
-
propDef: void 0
|
|
2390
|
-
}];
|
|
2391
|
-
for (const result of found) {
|
|
2392
|
-
if (!last && result.propDef && (0, _atscript_core.isRef)(result.propDef)) clones.push({
|
|
2393
|
-
parentSteps: steps,
|
|
2394
|
-
propName: parts[i]
|
|
2395
|
-
});
|
|
2396
|
-
const next = [...steps, ...result.steps];
|
|
2397
|
-
if (!last) next.push("type");
|
|
2398
|
-
nextAccessors.push({
|
|
2399
|
-
steps: next,
|
|
2400
|
-
def: result.propDef
|
|
2401
|
-
});
|
|
2402
|
-
}
|
|
2403
|
-
}
|
|
2404
|
-
accessors = nextAccessors;
|
|
2405
|
-
}
|
|
2406
|
-
return {
|
|
2407
|
-
accessors: accessors.map((a) => a.steps),
|
|
2408
|
-
clones
|
|
2409
|
-
};
|
|
2410
|
-
}
|
|
2411
|
-
/**
|
|
2412
|
-
* Finds a property in a type tree at compile time, returning all
|
|
2413
|
-
* matching accessor steps and prop definitions for further chaining.
|
|
2414
|
-
* Returns multiple results when the same property appears in different union branches.
|
|
2415
|
-
*/ buildPropPaths(def, propName) {
|
|
2416
|
-
if (!def) return [];
|
|
2417
|
-
def = this.doc.mergeIntersection(def);
|
|
2418
|
-
if ((0, _atscript_core.isRef)(def)) {
|
|
2419
|
-
const ref = def;
|
|
2420
|
-
const unwound = this.doc.unwindType(ref.id, ref.chain)?.def;
|
|
2421
|
-
return this.buildPropPaths(unwound, propName);
|
|
2422
|
-
}
|
|
2423
|
-
if ((0, _atscript_core.isInterface)(def)) return this.buildPropPaths(def.getDefinition(), propName);
|
|
2424
|
-
if ((0, _atscript_core.isStructure)(def)) {
|
|
2425
|
-
const prop = def.props.get(propName);
|
|
2426
|
-
if (prop) return [{
|
|
2427
|
-
steps: [["props", propName]],
|
|
2428
|
-
propDef: prop.getDefinition()
|
|
2429
|
-
}];
|
|
2430
|
-
return [];
|
|
2431
|
-
}
|
|
2432
|
-
if ((0, _atscript_core.isGroup)(def)) {
|
|
2433
|
-
const items = def.unwrap();
|
|
2434
|
-
const results = [];
|
|
2435
|
-
for (let i = 0; i < items.length; i++) for (const result of this.buildPropPaths(items[i], propName)) results.push({
|
|
2436
|
-
steps: [
|
|
2437
|
-
["items", i],
|
|
2438
|
-
"type",
|
|
2439
|
-
...result.steps
|
|
2440
|
-
],
|
|
2441
|
-
propDef: result.propDef
|
|
2442
|
-
});
|
|
2443
|
-
return results;
|
|
2444
|
-
}
|
|
2445
|
-
return [];
|
|
2446
|
-
}
|
|
2447
|
-
constructor(doc, opts) {
|
|
2448
|
-
super(doc), _define_property(this, "opts", void 0), _define_property(this, "postAnnotate", void 0), _define_property(this, "_adHocAnnotations", void 0), _define_property(this, "_propPath", void 0), _define_property(this, "typeIds", void 0), _define_property(this, "_unusedJs", void 0), _define_property(this, "_extendsRefs", void 0), _define_property(this, "_refSynthInfo", void 0), _define_property(this, "_synthImports", void 0), _define_property(this, "_synthComputed", void 0), _define_property(this, "_synthTaken", void 0), _define_property(this, "_synthAllocated", void 0), _define_property(this, "_synthPathCache", void 0), _define_property(this, "_ownerCache", void 0), _define_property(this, "model", void 0), _define_property(this, "modelClasses", void 0), _define_property(this, "_declTypes", void 0), this.opts = opts, this.postAnnotate = [], this._adHocAnnotations = null, this._propPath = [], this.typeIds = /* @__PURE__ */ new Map(), this._refSynthInfo = /* @__PURE__ */ new Map(), this._synthImports = /* @__PURE__ */ new Map(), this._synthComputed = false, this._synthAllocated = /* @__PURE__ */ new Map(), this._synthPathCache = /* @__PURE__ */ new Map(), this._ownerCache = /* @__PURE__ */ new Map(), this.modelClasses = [], this._declTypes = /* @__PURE__ */ new Map();
|
|
2449
|
-
if (opts?.compileValidators) this.model = new ValidationModel();
|
|
2450
|
-
}
|
|
2451
|
-
};
|
|
2452
|
-
|
|
2453
|
-
//#endregion
|
|
2454
|
-
//#region packages/typescript/src/plugin.ts
|
|
2455
|
-
/**
|
|
2456
|
-
* Render formats of the JS output that override {@link TTsPluginOptions.compileValidators}
|
|
2457
|
-
* (used by `unplugin-atscript`'s `compileValidators` option).
|
|
2458
|
-
*/ const JS_COMPILED_FORMAT = "js:compiled";
|
|
2459
|
-
const JS_INTERPRETED_FORMAT = "js:interpreted";
|
|
2460
|
-
/**
|
|
2461
|
-
* Resolves the effective JSON schema mode from plugin options.
|
|
2462
|
-
*/ function resolveJsonSchemaMode(opts) {
|
|
2463
|
-
if (opts?.jsonSchema !== void 0) return opts.jsonSchema;
|
|
2464
|
-
return false;
|
|
2465
|
-
}
|
|
2466
|
-
const tsPlugin = (opts) => {
|
|
2467
|
-
return {
|
|
2468
|
-
name: "typescript",
|
|
2469
|
-
render(doc, format) {
|
|
2470
|
-
if (format === "dts" || format === _atscript_core.DEFAULT_FORMAT) return [{
|
|
2471
|
-
fileName: `${doc.name}.d.ts`,
|
|
2472
|
-
content: new TypeRenderer(doc, opts).render()
|
|
2473
|
-
}];
|
|
2474
|
-
if (format === "js" || format === JS_COMPILED_FORMAT || format === JS_INTERPRETED_FORMAT) {
|
|
2475
|
-
const jsOpts = format === "js" ? opts : {
|
|
2476
|
-
...opts,
|
|
2477
|
-
compileValidators: format === JS_COMPILED_FORMAT
|
|
2478
|
-
};
|
|
2479
|
-
return [{
|
|
2480
|
-
fileName: `${doc.name}.js`,
|
|
2481
|
-
content: new JsRenderer(doc, jsOpts).render()
|
|
2482
|
-
}];
|
|
2483
|
-
}
|
|
2484
|
-
},
|
|
2485
|
-
async buildEnd(output, format, repo) {
|
|
2486
|
-
if (format === "dts" || format === _atscript_core.DEFAULT_FORMAT) {
|
|
2487
|
-
const annotations = await repo.getUsedAnnotations();
|
|
2488
|
-
const tags = await repo.getPrimitivesTags() || /* @__PURE__ */ new Set();
|
|
2489
|
-
const rendered = [];
|
|
2490
|
-
for (const [key, val] of Object.entries(annotations)) {
|
|
2491
|
-
const multiple = val.multiple;
|
|
2492
|
-
const typeLine = Array.from(val.types).map((t) => {
|
|
2493
|
-
if (t.type === "object" && "props" in t) return `{ ${Object.entries(t.props).map(([k, v]) => `${wrapProp(k)}${v.optional ? "?" : ""}: ${v.type}`).join(", ")} }`;
|
|
2494
|
-
else return "optional" in t && t.optional ? `${t.type} | true` : t.type;
|
|
2495
|
-
}).join(" | ");
|
|
2496
|
-
rendered.push(`${wrapProp(key)}: ${multiple ? "(" : ""}${typeLine}${multiple ? ")[]" : ""}`);
|
|
2497
|
-
}
|
|
2498
|
-
const renderedTags = Array.from(tags).map((f) => `"${escapeQuotes(f)}"`).join(" | ");
|
|
2499
|
-
output.push({
|
|
2500
|
-
content: "// prettier-ignore-start\n/* eslint-disable */\n/* oxlint-disable */\n/**\n * 🪄 This file was generated by Atscript\n * It is generated based on annotations used in this project\n * Do not edit this file!\n *\n * Use `npx asc -f dts` command to re-generate this file\n */\nexport {}\n\ndeclare global {\n interface AtscriptMetadata {\n " + rendered.join("\n ") + "\n }\n type AtscriptPrimitiveTags = " + renderedTags + "\n}\n// prettier-ignore-end",
|
|
2501
|
-
fileName: "atscript.d.ts",
|
|
2502
|
-
source: "",
|
|
2503
|
-
target: path.default.join(repo.root, "atscript.d.ts")
|
|
2504
|
-
});
|
|
2505
|
-
}
|
|
2506
|
-
}
|
|
2507
|
-
};
|
|
2508
|
-
};
|
|
2509
|
-
|
|
2510
|
-
//#endregion
|
|
2511
|
-
Object.defineProperty(exports, 'JS_COMPILED_FORMAT', {
|
|
2512
|
-
enumerable: true,
|
|
2513
|
-
get: function () {
|
|
2514
|
-
return JS_COMPILED_FORMAT;
|
|
2515
|
-
}
|
|
2516
|
-
});
|
|
2517
|
-
Object.defineProperty(exports, 'JS_INTERPRETED_FORMAT', {
|
|
2518
|
-
enumerable: true,
|
|
2519
|
-
get: function () {
|
|
2520
|
-
return JS_INTERPRETED_FORMAT;
|
|
2521
|
-
}
|
|
2522
|
-
});
|
|
2523
|
-
Object.defineProperty(exports, '__toESM', {
|
|
2524
|
-
enumerable: true,
|
|
2525
|
-
get: function () {
|
|
2526
|
-
return __toESM;
|
|
2527
|
-
}
|
|
2528
|
-
});
|
|
2529
|
-
Object.defineProperty(exports, 'tsPlugin', {
|
|
2530
|
-
enumerable: true,
|
|
2531
|
-
get: function () {
|
|
2532
|
-
return tsPlugin;
|
|
2533
|
-
}
|
|
2534
|
-
});
|