@atscript/typescript 0.1.99 → 0.1.101

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.
@@ -1,4 +1,4 @@
1
- import { l as defineAnnotatedType, t as buildJsonSchema } from "./json-schema-Cka8ETxe.mjs";
1
+ import { l as defineAnnotatedType, t as buildJsonSchema } from "./json-schema-BogNt-9w.mjs";
2
2
  import path from "path";
3
3
  import { DEFAULT_FORMAT, flattenInterfaceNode, getRelPath, hasNavPropAnnotation, isArray, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isInterface, isPrimitive, isProp, isQueryLogical, isRef, isStructure } from "@atscript/core";
4
4
 
@@ -658,6 +658,7 @@ const QUERY_OP_MAP = {
658
658
  "exists": "$exists",
659
659
  "not exists": "$exists"
660
660
  };
661
+ const SYNTH_IMPORTS_MARKER = "/*@@atscript-synth-imports@@*/";
661
662
  var JsRenderer = class extends BaseRenderer {
662
663
  /**
663
664
  * Relative imports get the configured `moduleExtension`; bare specifiers
@@ -715,32 +716,56 @@ var JsRenderer = class extends BaseRenderer {
715
716
  this._synthComputed = true;
716
717
  const refToOriginDoc = this.getExtendsRefs();
717
718
  if (refToOriginDoc.size === 0) return;
718
- const taken = new Set(this.doc.registry.definitions.keys());
719
- const allocated = /* @__PURE__ */ new Map();
720
- const synthPathCache = /* @__PURE__ */ new Map();
721
719
  for (const [refNode, originDoc] of refToOriginDoc) {
722
720
  const refId = refNode.id;
723
721
  if (!refId) continue;
724
722
  const ownerInfo = this.resolveOwner(originDoc, refId);
725
723
  if (!ownerInfo?.doc || ownerInfo.doc === this.doc) continue;
726
724
  if (ownerInfo.node && isPrimitive(ownerInfo.node)) continue;
727
- const ownerDoc = ownerInfo.doc;
728
- let synthPath;
729
- if (synthPathCache.has(ownerDoc)) synthPath = synthPathCache.get(ownerDoc);
730
- else {
731
- synthPath = this.computeSynthPath(ownerDoc);
732
- synthPathCache.set(ownerDoc, synthPath);
733
- }
734
- if (!synthPath) continue;
735
- const allocKey = `${synthPath}::${refId}`;
736
- let info = allocated.get(allocKey);
737
- if (!info) {
738
- info = this.allocateSynthInfo(refId, synthPath, ownerInfo, taken);
739
- allocated.set(allocKey, info);
740
- }
725
+ const info = this.synthBinding(refId, ownerInfo);
726
+ if (!info) continue;
741
727
  this._refSynthInfo.set(refNode, info);
742
728
  }
743
729
  }
730
+ getSynthTaken() {
731
+ if (!this._synthTaken) {
732
+ this._synthTaken = new Set(this.doc.registry.definitions.keys());
733
+ for (const name of this.doc.importedDefs.keys()) this._synthTaken.add(name);
734
+ }
735
+ return this._synthTaken;
736
+ }
737
+ getSynthPath(ownerDoc) {
738
+ if (!this._synthPathCache.has(ownerDoc)) this._synthPathCache.set(ownerDoc, this.computeSynthPath(ownerDoc));
739
+ return this._synthPathCache.get(ownerDoc);
740
+ }
741
+ synthBinding(name, ownerInfo) {
742
+ const synthPath = this.getSynthPath(ownerInfo.doc);
743
+ if (!synthPath) return;
744
+ const allocKey = `${synthPath}::${name}`;
745
+ let info = this._synthAllocated.get(allocKey);
746
+ if (!info) {
747
+ info = this.allocateSynthInfo(name, synthPath, ownerInfo, this.getSynthTaken());
748
+ this._synthAllocated.set(allocKey, info);
749
+ }
750
+ return info;
751
+ }
752
+ /**
753
+ * Binding for a type name used by an annotation argument (`ref` / qualified
754
+ * query field refs). An annotation inherited from another document (chain ref
755
+ * or `extends`) carries names that only that document imports, so when the
756
+ * name does not resolve here to the same declaration, a synthesized import is
757
+ * allocated (lazily, spliced into the header by `render()`).
758
+ */ annotationTypeName(typeName, origin) {
759
+ if (!origin || origin === this.doc) return typeName;
760
+ const theirs = this.resolveOwner(origin, typeName);
761
+ if (!theirs?.doc || !theirs.node || theirs.doc === this.doc || isPrimitive(theirs.node)) return typeName;
762
+ const mine = this.resolveOwner(this.doc, typeName);
763
+ if (mine?.doc === theirs.doc && mine.node === theirs.node) return typeName;
764
+ return this.synthBinding(typeName, {
765
+ doc: theirs.doc,
766
+ node: theirs.node
767
+ })?.alias ?? typeName;
768
+ }
744
769
  resolveOwner(fromDoc, refId) {
745
770
  const key = `${fromDoc.id}::${refId}`;
746
771
  let v = this._ownerCache.get(key);
@@ -814,10 +839,17 @@ var JsRenderer = class extends BaseRenderer {
814
839
  if (jsonSchemaMode === false) imports.push("throwFeatureDisabled as $d");
815
840
  this.writeln(`import { ${imports.join(", ")} } from "@atscript/typescript/utils"`);
816
841
  this.computeSynthesizedImports();
842
+ this.writeln(SYNTH_IMPORTS_MARKER);
843
+ }
844
+ render() {
845
+ const out = super.render();
846
+ const lines = [];
817
847
  for (const [synthPath, names] of this._synthImports) {
818
848
  const list = names.map((n) => n.alias === n.name ? n.name : `${n.name} as ${n.alias}`).join(", ");
819
- this.writeln(`import { ${list} } from "${this.transformFromPath(synthPath)}"`);
849
+ lines.push(`import { ${list} } from "${this.transformFromPath(synthPath)}"`);
820
850
  }
851
+ const marker = `${SYNTH_IMPORTS_MARKER}\n`;
852
+ return out.replace(marker, () => lines.length > 0 ? `${lines.join("\n")}\n` : "");
821
853
  }
822
854
  buildAdHocMap(annotateNodes) {
823
855
  const map = /* @__PURE__ */ new Map();
@@ -1289,53 +1321,53 @@ var JsRenderer = class extends BaseRenderer {
1289
1321
  if (multiple) this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value}, true)`);
1290
1322
  else this.writeln(`.annotate("${escapeQuotes(an.name)}", ${value})`);
1291
1323
  }
1292
- emitRefValue(text) {
1324
+ emitRefValue(text, origin) {
1293
1325
  const dotIdx = text.indexOf(".");
1294
- if (dotIdx === -1) return `() => ${text}`;
1295
- return `{ type: () => ${text.slice(0, dotIdx)}, field: "${escapeQuotes(text.slice(dotIdx + 1))}" }`;
1296
- }
1297
- emitArgValue(aSpec, argToken) {
1298
- if (aSpec.type === "ref") return this.emitRefValue(argToken.text);
1299
- if (aSpec.type === "query" && argToken.queryNode) return this.emitQueryTree(argToken.queryNode);
1300
- if (aSpec.type === "expr" && argToken.exprNode) return this.emitExprNode(argToken.exprNode.expression);
1301
- if (aSpec.type === "order" && argToken.orderNode) return `[${argToken.orderNode.items.map((item) => `{ ref: ${this.emitQueryFieldRef(item.ref)}${item.desc ? ", desc: true" : ""} }`).join(", ")}]`;
1326
+ if (dotIdx === -1) return `() => ${this.annotationTypeName(text, origin)}`;
1327
+ return `{ type: () => ${this.annotationTypeName(text.slice(0, dotIdx), origin)}, field: "${escapeQuotes(text.slice(dotIdx + 1))}" }`;
1328
+ }
1329
+ emitArgValue(aSpec, argToken, origin) {
1330
+ if (aSpec.type === "ref") return this.emitRefValue(argToken.text, origin);
1331
+ if (aSpec.type === "query" && argToken.queryNode) return this.emitQueryTree(argToken.queryNode, origin);
1332
+ if (aSpec.type === "expr" && argToken.exprNode) return this.emitExprNode(argToken.exprNode.expression, origin);
1333
+ if (aSpec.type === "order" && argToken.orderNode) return `[${argToken.orderNode.items.map((item) => `{ ref: ${this.emitQueryFieldRef(item.ref, origin)}${item.desc ? ", desc: true" : ""} }`).join(", ")}]`;
1302
1334
  return aSpec.type === "string" ? `"${escapeQuotes(argToken.text)}"` : argToken.text;
1303
1335
  }
1304
- emitExprNode(node) {
1336
+ emitExprNode(node, origin) {
1305
1337
  switch (node.entity) {
1306
1338
  case "query-expr-number": return String(node.value);
1307
1339
  case "query-expr-binary": {
1308
1340
  const { op, left, right } = node;
1309
- return `{ op: "${op}", args: [${this.emitExprNode(left)}, ${this.emitExprNode(right)}] }`;
1341
+ return `{ op: "${op}", args: [${this.emitExprNode(left, origin)}, ${this.emitExprNode(right, origin)}] }`;
1310
1342
  }
1311
1343
  case "query-expr-unary": {
1312
1344
  const { op, operand } = node;
1313
- return `{ op: "${op}", args: [${this.emitExprNode(operand)}] }`;
1345
+ return `{ op: "${op}", args: [${this.emitExprNode(operand, origin)}] }`;
1314
1346
  }
1315
1347
  case "query-expr-call": {
1316
1348
  const { fn, args } = node;
1317
- return `{ op: "${fn}", args: [${args.map((a) => this.emitExprNode(a)).join(", ")}] }`;
1349
+ return `{ op: "${fn}", args: [${args.map((a) => this.emitExprNode(a, origin)).join(", ")}] }`;
1318
1350
  }
1319
- default: return this.emitQueryFieldRef(node);
1351
+ default: return this.emitQueryFieldRef(node, origin);
1320
1352
  }
1321
1353
  }
1322
- emitQueryTree(queryNode) {
1323
- return this.emitQueryExpr(queryNode.expression);
1354
+ emitQueryTree(queryNode, origin) {
1355
+ return this.emitQueryExpr(queryNode.expression, origin);
1324
1356
  }
1325
- emitQueryExpr(node) {
1326
- if (isQueryLogical(node)) return this.emitQueryLogical(node);
1327
- return this.emitQueryComparison(node);
1357
+ emitQueryExpr(node, origin) {
1358
+ if (isQueryLogical(node)) return this.emitQueryLogical(node, origin);
1359
+ return this.emitQueryComparison(node, origin);
1328
1360
  }
1329
- emitQueryLogical(node) {
1330
- if (node.operator === "not") return `{ "$not": ${this.emitQueryExpr(node.operands[0])} }`;
1331
- return `{ "${node.operator === "and" ? "$and" : "$or"}": [${node.operands.map((op) => this.emitQueryExpr(op)).join(", ")}] }`;
1361
+ emitQueryLogical(node, origin) {
1362
+ if (node.operator === "not") return `{ "$not": ${this.emitQueryExpr(node.operands[0], origin)} }`;
1363
+ return `{ "${node.operator === "and" ? "$and" : "$or"}": [${node.operands.map((op) => this.emitQueryExpr(op, origin)).join(", ")}] }`;
1332
1364
  }
1333
- emitQueryComparison(node) {
1334
- const left = this.emitQueryFieldRef(node.left);
1365
+ emitQueryComparison(node, origin) {
1366
+ const left = this.emitQueryFieldRef(node.left, origin);
1335
1367
  const mappedOp = QUERY_OP_MAP[node.operator] || node.operator;
1336
1368
  const parts = [`left: ${left}`, `op: "${mappedOp}"`];
1337
1369
  if (node.right) {
1338
- if ("fieldRef" in node.right && node.right.fieldRef) parts.push(`right: ${this.emitQueryFieldRef(node.right)}`);
1370
+ if ("fieldRef" in node.right && node.right.fieldRef) parts.push(`right: ${this.emitQueryFieldRef(node.right, origin)}`);
1339
1371
  else if ("values" in node.right && node.right.values) {
1340
1372
  const values = node.right.values.map((v) => this.emitQueryLiteral(v)).join(", ");
1341
1373
  parts.push(`right: [${values}]`);
@@ -1344,9 +1376,9 @@ var JsRenderer = class extends BaseRenderer {
1344
1376
  else if (node.operator === "not exists") parts.push("right: false");
1345
1377
  return `{ ${parts.join(", ")} }`;
1346
1378
  }
1347
- emitQueryFieldRef(node) {
1379
+ emitQueryFieldRef(node, origin) {
1348
1380
  const parts = [];
1349
- if (node.typeRef) parts.push(`type: () => ${node.typeRef.text}`);
1381
+ if (node.typeRef) parts.push(`type: () => ${this.annotationTypeName(node.typeRef.text, origin)}`);
1350
1382
  parts.push(`field: "${escapeQuotes(node.fieldRef.text)}"`);
1351
1383
  return `{ ${parts.join(", ")} }`;
1352
1384
  }
@@ -1367,6 +1399,7 @@ var JsRenderer = class extends BaseRenderer {
1367
1399
  }
1368
1400
  }
1369
1401
  computeAnnotationValue(node, an) {
1402
+ const origin = this.doc.annotationOrigin(an);
1370
1403
  const spec = this.doc.resolveAnnotation(an.name);
1371
1404
  let targetValue = "true";
1372
1405
  let multiple = false;
@@ -1377,13 +1410,13 @@ var JsRenderer = class extends BaseRenderer {
1377
1410
  targetValue = "{ ";
1378
1411
  let i = 0;
1379
1412
  for (const aSpec of spec.arguments) {
1380
- if (an.args[i]) targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i])}${i === length - 1 ? "" : ", "} `;
1413
+ if (an.args[i]) targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i], origin)}${i === length - 1 ? "" : ", "} `;
1381
1414
  i++;
1382
1415
  }
1383
1416
  targetValue += "}";
1384
1417
  } else {
1385
1418
  const aSpec = spec.arguments[0];
1386
- targetValue = an.args[0] ? this.emitArgValue(aSpec, an.args[0]) : "true";
1419
+ targetValue = an.args[0] ? this.emitArgValue(aSpec, an.args[0], origin) : "true";
1387
1420
  }
1388
1421
  } else {
1389
1422
  multiple = node.countAnnotations(an.name) > 1 || an.args.length > 1;
@@ -1521,7 +1554,7 @@ var JsRenderer = class extends BaseRenderer {
1521
1554
  return [];
1522
1555
  }
1523
1556
  constructor(doc, opts) {
1524
- 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, "_ownerCache", 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._ownerCache = /* @__PURE__ */ new Map();
1557
+ 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), 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();
1525
1558
  }
1526
1559
  };
1527
1560
 
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_plugin = require('./plugin-BG_encHp.cjs');
2
+ const require_plugin = require('./plugin-Cu6Nez-H.cjs');
3
3
  let path = require("path");
4
4
  path = require_plugin.__toESM(path);
5
5
  let _atscript_core = require("@atscript/core");
@@ -1,4 +1,4 @@
1
- import { t as tsPlugin } from "./plugin-CVvPRB8q.mjs";
1
+ import { t as tsPlugin } from "./plugin-DG3jlbSN.mjs";
2
2
  import path from "path";
3
3
  import { build } from "@atscript/core";
4
4
  import { readFileSync, writeFileSync } from "fs";
package/dist/utils.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_json_schema = require('./json-schema-CZo482nY.cjs');
2
+ const require_json_schema = require('./json-schema-CtQ_rzJn.cjs');
3
3
 
4
4
  //#region packages/typescript/src/runtime/coerce.ts
5
5
  /**
@@ -406,6 +406,16 @@ function flattenAnnotatedType(type, options) {
406
406
 
407
407
  //#endregion
408
408
  //#region packages/typescript/src/runtime/serialize.ts
409
+ function _define_property(obj, key, value) {
410
+ if (key in obj) Object.defineProperty(obj, key, {
411
+ value,
412
+ enumerable: true,
413
+ configurable: true,
414
+ writable: true
415
+ });
416
+ else obj[key] = value;
417
+ return obj;
418
+ }
409
419
  /** Current serialization format version. Bumped on breaking changes to the serialized shape. */ const SERIALIZE_VERSION = 2;
410
420
  /**
411
421
  * Converts a runtime {@link TAtscriptAnnotatedType} into a plain JSON-safe object.
@@ -425,41 +435,135 @@ function flattenAnnotatedType(type, options) {
425
435
  * @param options - Optional filtering/transformation for annotations.
426
436
  * @returns A versioned, JSON-safe representation of the type.
427
437
  */ function serializeAnnotatedType(type, options) {
428
- const result = serializeNode(type, [], options, /* @__PURE__ */ new Set());
438
+ const result = serializeNode(type, [], options, new Visited());
429
439
  result.$v = SERIALIZE_VERSION;
430
440
  return result;
431
441
  }
432
- function serializeNode(def, path, options, visited) {
433
- if (def.id && visited.has(def.id)) return {
434
- type: {
435
- kind: "$ref",
436
- id: def.id
437
- },
438
- metadata: {},
439
- ...def.optional ? { optional: true } : {},
440
- id: def.id
441
- };
442
- if (def.id) visited.add(def.id);
443
- const result = {
444
- type: serializeTypeDef(def, path, options, visited),
445
- metadata: serializeMetadata(def.metadata, path, def.type.kind, options)
446
- };
447
- if (def.optional) result.optional = true;
448
- if (def.id) result.id = def.id;
442
+ /**
443
+ * Named types serialized so far. `own` keeps, per id, the first node serialized under it (and
444
+ * the `refDepth` it was serialized at); a later reference is compared against it, by a
445
+ * fingerprint of what it carries (metadata, `optional` and `ref`), to tell a reference that adds
446
+ * nothing from one whose prop annotations or FK target differ. The first node's key is computed
447
+ * only when a revisit needs it, and memoized.
448
+ */ let Visited = class Visited extends Set {
449
+ /** Whether `def` (revisiting its id at `refDepth`) carries something other than the first node. */ differsFromFirst(def, refDepth) {
450
+ const id = def.id;
451
+ let first = this.firstKeys.get(id);
452
+ if (first === void 0) {
453
+ const { def: firstDef, refDepth: firstDepth } = this.own.get(id);
454
+ first = ownKey(firstDef, this, firstDepth);
455
+ this.firstKeys.set(id, first);
456
+ }
457
+ return first !== ownKey(def, this, refDepth);
458
+ }
459
+ /** Stable per-run identity of a function / class instance (compared by reference). */ identity(value) {
460
+ let id = this.identities.get(value);
461
+ if (id === void 0) {
462
+ id = ++this.nextId;
463
+ this.identities.set(value, id);
464
+ }
465
+ return id;
466
+ }
467
+ constructor(...args) {
468
+ super(...args), _define_property(this, "own", /* @__PURE__ */ new Map()), _define_property(this, "firstKeys", /* @__PURE__ */ new Map()), _define_property(this, "identities", /* @__PURE__ */ new WeakMap()), _define_property(this, "nextId", 0);
469
+ }
470
+ };
471
+ /**
472
+ * A stable, cycle-safe, BigInt-tolerant comparison key of raw annotation values. Plain objects
473
+ * and arrays compare structurally; a type reference (a getter or an annotated type) by the type it
474
+ * resolves to, so equal targets collapse and different ones do not; other functions and objects by
475
+ * identity.
476
+ */ function fingerprint(value, visited, ancestors = /* @__PURE__ */ new Set()) {
477
+ switch (typeof value) {
478
+ case "bigint": return `${value}n`;
479
+ case "string": return JSON.stringify(value);
480
+ case "function": {
481
+ const target = resolveAnnotationTarget(value);
482
+ if (target) return targetKey(target, visited);
483
+ return `fn#${visited.identity(value)}`;
484
+ }
485
+ case "object": {
486
+ if (value === null) return "null";
487
+ const target = resolveAnnotationTarget(value);
488
+ if (target) return targetKey(target, visited);
489
+ if (!isPlainOrArray(value)) return `obj#${visited.identity(value)}`;
490
+ if (ancestors.has(value)) return "[circular]";
491
+ ancestors.add(value);
492
+ const body = Array.isArray(value) ? value.map((v) => fingerprint(v, visited, ancestors)).join(",") : Object.entries(value).map(([k, v]) => `${JSON.stringify(k)}:${fingerprint(v, visited, ancestors)}`).join(",");
493
+ ancestors.delete(value);
494
+ return `[${body}]`;
495
+ }
496
+ default: return String(value);
497
+ }
498
+ }
499
+ /** A plain object or an array (as opposed to a class instance), the shapes compared structurally. */ function isPlainOrArray(value) {
500
+ const proto = Object.getPrototypeOf(value);
501
+ return Array.isArray(value) || proto === Object.prototype || proto === null;
502
+ }
503
+ /** Comparison key of a resolved annotation target: its id, else its identity. */ function targetKey(target, visited) {
504
+ return target.id ? `ref#${target.id}` : `ref@${visited.identity(target)}`;
505
+ }
506
+ /** What a node carries of its own (metadata, optionality, FK target), as a comparison key. */ function ownKey(def, visited, refDepth) {
507
+ const entries = [...def.metadata.entries()].map(([k, v]) => `${JSON.stringify(k)}:${fingerprint(v, visited)}`);
508
+ const refTarget = refDepth > 0 ? def.ref?.type() : void 0;
509
+ const ref = def.ref && refTarget ? `${refTarget.id ?? ""}.${def.ref.field}` : "";
510
+ return `${entries.join(",")}|${def.optional ? 1 : 0}|${ref}`;
511
+ }
512
+ function serializeRef(def, options, visited) {
449
513
  const refDepth = options?.refDepth ?? 0;
450
514
  if (refDepth > 0 && def.ref) {
451
515
  const refTarget = def.ref.type();
452
- if (refTarget) result.ref = {
516
+ if (refTarget) return {
453
517
  field: def.ref.field,
454
- type: refDepth < 1 && isHalfStep(refDepth) ? {
455
- id: refTarget.id ?? "",
456
- metadata: serializeMetadata(refTarget.metadata, [], refTarget.type.kind, options)
457
- } : serializeNode(refTarget, [], {
518
+ type: refDepth < 1 && isHalfStep(refDepth) ? shallowTarget(refTarget, options, {
519
+ visited,
520
+ depth: 1
521
+ }, true) : serializeNode(refTarget, [], {
458
522
  ...options,
459
523
  refDepth: refDepth - 1
460
524
  }, visited)
461
525
  };
462
526
  }
527
+ }
528
+ function serializeNode(def, path, options, visited) {
529
+ const refDepth = options?.refDepth ?? 0;
530
+ const metadata = () => serializeMetadata(def, {
531
+ path,
532
+ kind: def.type.kind
533
+ }, options, {
534
+ visited,
535
+ depth: 0
536
+ });
537
+ if (def.id && visited.has(def.id)) {
538
+ const differs = visited.differsFromFirst(def, refDepth);
539
+ const ref = differs ? serializeRef(def, options, visited) : void 0;
540
+ return {
541
+ type: {
542
+ kind: "$ref",
543
+ id: def.id,
544
+ ...differs ? { own: true } : {}
545
+ },
546
+ metadata: differs ? metadata() : {},
547
+ ...def.optional ? { optional: true } : {},
548
+ id: def.id,
549
+ ...ref ? { ref } : {}
550
+ };
551
+ }
552
+ if (def.id) {
553
+ visited.add(def.id);
554
+ visited.own.set(def.id, {
555
+ def,
556
+ refDepth
557
+ });
558
+ }
559
+ const result = {
560
+ type: serializeTypeDef(def, path, options, visited),
561
+ metadata: metadata()
562
+ };
563
+ if (def.optional) result.optional = true;
564
+ if (def.id) result.id = def.id;
565
+ const ref = serializeRef(def, options, visited);
566
+ if (ref) result.ref = ref;
463
567
  return result;
464
568
  }
465
569
  function isHalfStep(refDepth) {
@@ -529,10 +633,72 @@ function serializeTypeDef(def, path, options, visited) {
529
633
  }
530
634
  });
531
635
  }
532
- function serializeMetadata(metadata, path, kind, options) {
636
+ /**
637
+ * Resolves a type reference held in an annotation value: an annotated type itself (same-file
638
+ * refs) or the getter generated for a cross-file ref. Generated getters are zero-arity, plain
639
+ * synchronous arrow functions (no `prototype`, `Function` constructor); that is the only shape
640
+ * invoked. Classes, `function` expressions, async/generator functions and any other function
641
+ * are never called, so serializing never runs user code.
642
+ */ function resolveAnnotationTarget(value) {
643
+ if (require_json_schema.isAnnotatedType(value)) return value;
644
+ if (typeof value === "function" && value.length === 0 && !Object.prototype.hasOwnProperty.call(value, "prototype") && value.constructor === Function) {
645
+ const fn = value;
646
+ try {
647
+ const target = fn();
648
+ return require_json_schema.isAnnotatedType(target) ? target : void 0;
649
+ } catch {
650
+ return;
651
+ }
652
+ }
653
+ }
654
+ /**
655
+ * `{ id }` for a referenced type, plus its metadata (serialized at the next depth, so every
656
+ * nested reference collapses to `{ id }`) when `withMetadata`.
657
+ */ function shallowTarget(target, options, state, withMetadata) {
658
+ return {
659
+ id: target.id ?? "",
660
+ ...withMetadata ? { metadata: serializeMetadata(target, {
661
+ path: [],
662
+ kind: target.type.kind
663
+ }, options, state) } : {}
664
+ };
665
+ }
666
+ /**
667
+ * Makes an annotation value JSON-safe: type references (a getter or a class, as emitted for `ref`
668
+ * arguments and qualified query field refs) become shallow targets `{ id, metadata }`
669
+ * (`refDepth > 0`) or `{ id }` (`refDepth` 0). Inside a shallow target's own metadata (`depth` >= 1)
670
+ * every reference is `{ id }`, so the output is bounded and cycle-free. Plain objects and arrays
671
+ * recurse; other values pass unchanged.
672
+ */ function serializeAnnotationValue(value, options, state) {
673
+ var _state;
674
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
675
+ const target = resolveAnnotationTarget(value);
676
+ if (target) return shallowTarget(target, options, {
677
+ visited: state.visited,
678
+ depth: state.depth + 1
679
+ }, state.depth === 0 && (options?.refDepth ?? 0) > 0);
680
+ if (typeof value === "function") return value;
681
+ if (!isPlainOrArray(value)) return value;
682
+ const ancestors = (_state = state).ancestors ?? (_state.ancestors = /* @__PURE__ */ new Set());
683
+ if (ancestors.has(value)) return "[Circular]";
684
+ ancestors.add(value);
685
+ const out = Array.isArray(value) ? value.map((item) => serializeAnnotationValue(item, options, state)) : Object.fromEntries(Object.entries(value).map(([k, v]) => [k, serializeAnnotationValue(v, options, state)]));
686
+ ancestors.delete(value);
687
+ return out;
688
+ }
689
+ function serializeMetadata(owner, site, options, state) {
690
+ const { path, kind } = site;
533
691
  const result = {};
534
692
  const ignoreSet = options?.ignoreAnnotations ? new Set(options.ignoreAnnotations) : void 0;
535
- for (const [key, value] of metadata.entries()) {
693
+ const overrides = options?.annotationOverrides?.(owner);
694
+ let entries = owner.metadata.entries();
695
+ if (overrides) {
696
+ const merged = new Map(entries);
697
+ for (const [key, value] of Object.entries(overrides)) if (value === void 0) merged.delete(key);
698
+ else merged.set(key, value);
699
+ entries = merged;
700
+ }
701
+ for (const [key, value] of entries) {
536
702
  if (ignoreSet?.has(key)) continue;
537
703
  if (options?.processAnnotation) {
538
704
  const processed = options.processAnnotation({
@@ -542,10 +708,10 @@ function serializeMetadata(metadata, path, kind, options) {
542
708
  kind
543
709
  });
544
710
  if (processed === void 0 || processed === null) continue;
545
- result[processed.key] = processed.value;
711
+ result[processed.key] = serializeAnnotationValue(processed.value, options, state);
546
712
  continue;
547
713
  }
548
- result[key] = value;
714
+ result[key] = serializeAnnotationValue(value, options, state);
549
715
  }
550
716
  return result;
551
717
  }
@@ -581,10 +747,41 @@ function emptyObjectTypeDef() {
581
747
  function toMetadataMap(record) {
582
748
  return new Map(Object.entries(record));
583
749
  }
750
+ function deserializeRef(data, resolved) {
751
+ if (!data.ref) return;
752
+ const refTargetData = data.ref.type;
753
+ if ("type" in refTargetData) {
754
+ const deserializedRefTarget = deserializeNode(refTargetData, resolved);
755
+ return {
756
+ type: () => deserializedRefTarget,
757
+ field: data.ref.field
758
+ };
759
+ }
760
+ const sentinel = require_json_schema.createAnnotatedTypeNode(emptyObjectTypeDef(), toMetadataMap(refTargetData.metadata), { id: refTargetData.id || void 0 });
761
+ return {
762
+ type: () => sentinel,
763
+ field: data.ref.field
764
+ };
765
+ }
584
766
  function deserializeNode(data, resolved) {
585
767
  if (data.type.kind === "$ref") {
586
- const refId = data.type.id;
587
- return resolved.get(refId) || require_json_schema.createAnnotatedTypeNode(emptyObjectTypeDef(), /* @__PURE__ */ new Map(), { id: refId });
768
+ const { id: refId, own } = data.type;
769
+ const target = resolved.get(refId);
770
+ if (!own) return target || require_json_schema.createAnnotatedTypeNode(emptyObjectTypeDef(), /* @__PURE__ */ new Map(), { id: refId });
771
+ const node = require_json_schema.createAnnotatedTypeNode(target?.type ?? emptyObjectTypeDef(), toMetadataMap(data.metadata), {
772
+ id: refId,
773
+ optional: data.optional || void 0,
774
+ ref: deserializeRef(data, resolved)
775
+ });
776
+ if (target) Object.defineProperty(node, "type", {
777
+ get: () => target.type,
778
+ set: (v) => {
779
+ target.type = v;
780
+ },
781
+ enumerable: true,
782
+ configurable: true
783
+ });
784
+ return node;
588
785
  }
589
786
  const metadata = toMetadataMap(data.metadata);
590
787
  let result;
@@ -598,23 +795,7 @@ function deserializeNode(data, resolved) {
598
795
  resolved.set(data.id, result);
599
796
  }
600
797
  const type = deserializeTypeDef(data.type, resolved);
601
- let ref;
602
- if (data.ref) {
603
- const refTargetData = data.ref.type;
604
- if ("type" in refTargetData) {
605
- const deserializedRefTarget = deserializeNode(refTargetData, resolved);
606
- ref = {
607
- type: () => deserializedRefTarget,
608
- field: data.ref.field
609
- };
610
- } else {
611
- const sentinel = require_json_schema.createAnnotatedTypeNode(emptyObjectTypeDef(), toMetadataMap(refTargetData.metadata), { id: refTargetData.id || void 0 });
612
- ref = {
613
- type: () => sentinel,
614
- field: data.ref.field
615
- };
616
- }
617
- }
798
+ const ref = deserializeRef(data, resolved);
618
799
  if (result) {
619
800
  result.type = type;
620
801
  if (ref) result.ref = ref;
package/dist/utils.d.ts CHANGED
@@ -590,6 +590,13 @@ interface TSerializedTypeComplex {
590
590
  interface TSerializedTypeRef {
591
591
  kind: '$ref';
592
592
  id: string;
593
+ /**
594
+ * The entry's `metadata` / `optional` belong to the referencing node (a prop's own
595
+ * annotations merged over the type's), not to the first node serialized under `id`.
596
+ * The deserializer then builds a node of its own over the shared type. The entry then also
597
+ * carries the use-site `ref` (FK target) when `refDepth` > 0 and the node has one.
598
+ */
599
+ own?: true;
593
600
  }
594
601
  type TSerializedTypeDef = TSerializedTypeFinal | TSerializedTypeObject | TSerializedTypeArray | TSerializedTypeComplex | TSerializedTypeRef;
595
602
  /** Context passed to {@link TSerializeOptions.processAnnotation} for each annotation entry. */
@@ -622,6 +629,17 @@ interface TSerializeOptions {
622
629
  * emits a shallow `{ id, metadata }` at the tail level instead of the full body.
623
630
  */
624
631
  refDepth?: number;
632
+ /**
633
+ * Per-node annotation overrides, applied over the node's own metadata BEFORE
634
+ * `ignoreAnnotations` / `processAnnotation` (which still filter them). Called with the owning
635
+ * annotated type node for every serialized metadata block (type nodes and shallow ref /
636
+ * annotation-value targets; never for collapsed `$ref` uses). Keys absent from the node are
637
+ * added, existing keys are replaced, and a key whose value is `undefined` is removed. Must be a
638
+ * pure function of the node: the repeated-type detector compares the nodes' own metadata, and a
639
+ * collapsed use restores to the first node's (overridden) metadata. Runtime metadata is never
640
+ * mutated.
641
+ */
642
+ annotationOverrides?: (type: TAtscriptAnnotatedType) => Readonly<Record<string, unknown>> | undefined;
625
643
  }
626
644
  /**
627
645
  * Converts a runtime {@link TAtscriptAnnotatedType} into a plain JSON-safe object.