@atscript/typescript 0.1.98 → 0.1.100

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/utils.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as forAnnotatedType, c as createAnnotatedTypeNode, d as isAnnotatedTypeOfPrimitive, f as isPhantomType, i as mergeJsonSchemas, l as defineAnnotatedType, m as ValidatorError, n as detectDiscriminator, o as annotate, p as Validator, r as fromJsonSchema, s as cloneRefProp, t as buildJsonSchema, u as isAnnotatedType } from "./json-schema-Cka8ETxe.mjs";
1
+ import { a as forAnnotatedType, c as createAnnotatedTypeNode, d as isAnnotatedTypeOfPrimitive, f as isPhantomType, i as mergeJsonSchemas, l as defineAnnotatedType, m as ValidatorError, n as detectDiscriminator, o as annotate, p as Validator, r as fromJsonSchema, s as cloneRefProp, t as buildJsonSchema, u as isAnnotatedType } from "./json-schema-BogNt-9w.mjs";
2
2
 
3
3
  //#region packages/typescript/src/runtime/coerce.ts
4
4
  /**
@@ -405,6 +405,16 @@ function flattenAnnotatedType(type, options) {
405
405
 
406
406
  //#endregion
407
407
  //#region packages/typescript/src/runtime/serialize.ts
408
+ function _define_property(obj, key, value) {
409
+ if (key in obj) Object.defineProperty(obj, key, {
410
+ value,
411
+ enumerable: true,
412
+ configurable: true,
413
+ writable: true
414
+ });
415
+ else obj[key] = value;
416
+ return obj;
417
+ }
408
418
  /** Current serialization format version. Bumped on breaking changes to the serialized shape. */ const SERIALIZE_VERSION = 2;
409
419
  /**
410
420
  * Converts a runtime {@link TAtscriptAnnotatedType} into a plain JSON-safe object.
@@ -424,41 +434,135 @@ function flattenAnnotatedType(type, options) {
424
434
  * @param options - Optional filtering/transformation for annotations.
425
435
  * @returns A versioned, JSON-safe representation of the type.
426
436
  */ function serializeAnnotatedType(type, options) {
427
- const result = serializeNode(type, [], options, /* @__PURE__ */ new Set());
437
+ const result = serializeNode(type, [], options, new Visited());
428
438
  result.$v = SERIALIZE_VERSION;
429
439
  return result;
430
440
  }
431
- function serializeNode(def, path, options, visited) {
432
- if (def.id && visited.has(def.id)) return {
433
- type: {
434
- kind: "$ref",
435
- id: def.id
436
- },
437
- metadata: {},
438
- ...def.optional ? { optional: true } : {},
439
- id: def.id
440
- };
441
- if (def.id) visited.add(def.id);
442
- const result = {
443
- type: serializeTypeDef(def, path, options, visited),
444
- metadata: serializeMetadata(def.metadata, path, def.type.kind, options)
445
- };
446
- if (def.optional) result.optional = true;
447
- if (def.id) result.id = def.id;
441
+ /**
442
+ * Named types serialized so far. `own` keeps, per id, the first node serialized under it (and
443
+ * the `refDepth` it was serialized at); a later reference is compared against it, by a
444
+ * fingerprint of what it carries (metadata, `optional` and `ref`), to tell a reference that adds
445
+ * nothing from one whose prop annotations or FK target differ. The first node's key is computed
446
+ * only when a revisit needs it, and memoized.
447
+ */ let Visited = class Visited extends Set {
448
+ /** Whether `def` (revisiting its id at `refDepth`) carries something other than the first node. */ differsFromFirst(def, refDepth) {
449
+ const id = def.id;
450
+ let first = this.firstKeys.get(id);
451
+ if (first === void 0) {
452
+ const { def: firstDef, refDepth: firstDepth } = this.own.get(id);
453
+ first = ownKey(firstDef, this, firstDepth);
454
+ this.firstKeys.set(id, first);
455
+ }
456
+ return first !== ownKey(def, this, refDepth);
457
+ }
458
+ /** Stable per-run identity of a function / class instance (compared by reference). */ identity(value) {
459
+ let id = this.identities.get(value);
460
+ if (id === void 0) {
461
+ id = ++this.nextId;
462
+ this.identities.set(value, id);
463
+ }
464
+ return id;
465
+ }
466
+ constructor(...args) {
467
+ 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);
468
+ }
469
+ };
470
+ /**
471
+ * A stable, cycle-safe, BigInt-tolerant comparison key of raw annotation values. Plain objects
472
+ * and arrays compare structurally; a type reference (a getter or an annotated type) by the type it
473
+ * resolves to, so equal targets collapse and different ones do not; other functions and objects by
474
+ * identity.
475
+ */ function fingerprint(value, visited, ancestors = /* @__PURE__ */ new Set()) {
476
+ switch (typeof value) {
477
+ case "bigint": return `${value}n`;
478
+ case "string": return JSON.stringify(value);
479
+ case "function": {
480
+ const target = resolveAnnotationTarget(value);
481
+ if (target) return targetKey(target, visited);
482
+ return `fn#${visited.identity(value)}`;
483
+ }
484
+ case "object": {
485
+ if (value === null) return "null";
486
+ const target = resolveAnnotationTarget(value);
487
+ if (target) return targetKey(target, visited);
488
+ if (!isPlainOrArray(value)) return `obj#${visited.identity(value)}`;
489
+ if (ancestors.has(value)) return "[circular]";
490
+ ancestors.add(value);
491
+ 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(",");
492
+ ancestors.delete(value);
493
+ return `[${body}]`;
494
+ }
495
+ default: return String(value);
496
+ }
497
+ }
498
+ /** A plain object or an array (as opposed to a class instance), the shapes compared structurally. */ function isPlainOrArray(value) {
499
+ const proto = Object.getPrototypeOf(value);
500
+ return Array.isArray(value) || proto === Object.prototype || proto === null;
501
+ }
502
+ /** Comparison key of a resolved annotation target: its id, else its identity. */ function targetKey(target, visited) {
503
+ return target.id ? `ref#${target.id}` : `ref@${visited.identity(target)}`;
504
+ }
505
+ /** What a node carries of its own (metadata, optionality, FK target), as a comparison key. */ function ownKey(def, visited, refDepth) {
506
+ const entries = [...def.metadata.entries()].map(([k, v]) => `${JSON.stringify(k)}:${fingerprint(v, visited)}`);
507
+ const refTarget = refDepth > 0 ? def.ref?.type() : void 0;
508
+ const ref = def.ref && refTarget ? `${refTarget.id ?? ""}.${def.ref.field}` : "";
509
+ return `${entries.join(",")}|${def.optional ? 1 : 0}|${ref}`;
510
+ }
511
+ function serializeRef(def, options, visited) {
448
512
  const refDepth = options?.refDepth ?? 0;
449
513
  if (refDepth > 0 && def.ref) {
450
514
  const refTarget = def.ref.type();
451
- if (refTarget) result.ref = {
515
+ if (refTarget) return {
452
516
  field: def.ref.field,
453
- type: refDepth < 1 && isHalfStep(refDepth) ? {
454
- id: refTarget.id ?? "",
455
- metadata: serializeMetadata(refTarget.metadata, [], refTarget.type.kind, options)
456
- } : serializeNode(refTarget, [], {
517
+ type: refDepth < 1 && isHalfStep(refDepth) ? shallowTarget(refTarget, options, {
518
+ visited,
519
+ depth: 1
520
+ }, true) : serializeNode(refTarget, [], {
457
521
  ...options,
458
522
  refDepth: refDepth - 1
459
523
  }, visited)
460
524
  };
461
525
  }
526
+ }
527
+ function serializeNode(def, path, options, visited) {
528
+ const refDepth = options?.refDepth ?? 0;
529
+ const metadata = () => serializeMetadata(def.metadata, {
530
+ path,
531
+ kind: def.type.kind
532
+ }, options, {
533
+ visited,
534
+ depth: 0
535
+ });
536
+ if (def.id && visited.has(def.id)) {
537
+ const differs = visited.differsFromFirst(def, refDepth);
538
+ const ref = differs ? serializeRef(def, options, visited) : void 0;
539
+ return {
540
+ type: {
541
+ kind: "$ref",
542
+ id: def.id,
543
+ ...differs ? { own: true } : {}
544
+ },
545
+ metadata: differs ? metadata() : {},
546
+ ...def.optional ? { optional: true } : {},
547
+ id: def.id,
548
+ ...ref ? { ref } : {}
549
+ };
550
+ }
551
+ if (def.id) {
552
+ visited.add(def.id);
553
+ visited.own.set(def.id, {
554
+ def,
555
+ refDepth
556
+ });
557
+ }
558
+ const result = {
559
+ type: serializeTypeDef(def, path, options, visited),
560
+ metadata: metadata()
561
+ };
562
+ if (def.optional) result.optional = true;
563
+ if (def.id) result.id = def.id;
564
+ const ref = serializeRef(def, options, visited);
565
+ if (ref) result.ref = ref;
462
566
  return result;
463
567
  }
464
568
  function isHalfStep(refDepth) {
@@ -528,7 +632,61 @@ function serializeTypeDef(def, path, options, visited) {
528
632
  }
529
633
  });
530
634
  }
531
- function serializeMetadata(metadata, path, kind, options) {
635
+ /**
636
+ * Resolves a type reference held in an annotation value: an annotated type itself (same-file
637
+ * refs) or the getter generated for a cross-file ref. Generated getters are zero-arity, plain
638
+ * synchronous arrow functions (no `prototype`, `Function` constructor); that is the only shape
639
+ * invoked. Classes, `function` expressions, async/generator functions and any other function
640
+ * are never called, so serializing never runs user code.
641
+ */ function resolveAnnotationTarget(value) {
642
+ if (isAnnotatedType(value)) return value;
643
+ if (typeof value === "function" && value.length === 0 && !Object.prototype.hasOwnProperty.call(value, "prototype") && value.constructor === Function) {
644
+ const fn = value;
645
+ try {
646
+ const target = fn();
647
+ return isAnnotatedType(target) ? target : void 0;
648
+ } catch {
649
+ return;
650
+ }
651
+ }
652
+ }
653
+ /**
654
+ * `{ id }` for a referenced type, plus its metadata (serialized at the next depth, so every
655
+ * nested reference collapses to `{ id }`) when `withMetadata`.
656
+ */ function shallowTarget(target, options, state, withMetadata) {
657
+ return {
658
+ id: target.id ?? "",
659
+ ...withMetadata ? { metadata: serializeMetadata(target.metadata, {
660
+ path: [],
661
+ kind: target.type.kind
662
+ }, options, state) } : {}
663
+ };
664
+ }
665
+ /**
666
+ * Makes an annotation value JSON-safe: type references (a getter or a class, as emitted for `ref`
667
+ * arguments and qualified query field refs) become shallow targets `{ id, metadata }`
668
+ * (`refDepth > 0`) or `{ id }` (`refDepth` 0). Inside a shallow target's own metadata (`depth` >= 1)
669
+ * every reference is `{ id }`, so the output is bounded and cycle-free. Plain objects and arrays
670
+ * recurse; other values pass unchanged.
671
+ */ function serializeAnnotationValue(value, options, state) {
672
+ var _state;
673
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
674
+ const target = resolveAnnotationTarget(value);
675
+ if (target) return shallowTarget(target, options, {
676
+ visited: state.visited,
677
+ depth: state.depth + 1
678
+ }, state.depth === 0 && (options?.refDepth ?? 0) > 0);
679
+ if (typeof value === "function") return value;
680
+ if (!isPlainOrArray(value)) return value;
681
+ const ancestors = (_state = state).ancestors ?? (_state.ancestors = /* @__PURE__ */ new Set());
682
+ if (ancestors.has(value)) return "[Circular]";
683
+ ancestors.add(value);
684
+ 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)]));
685
+ ancestors.delete(value);
686
+ return out;
687
+ }
688
+ function serializeMetadata(metadata, site, options, state) {
689
+ const { path, kind } = site;
532
690
  const result = {};
533
691
  const ignoreSet = options?.ignoreAnnotations ? new Set(options.ignoreAnnotations) : void 0;
534
692
  for (const [key, value] of metadata.entries()) {
@@ -541,10 +699,10 @@ function serializeMetadata(metadata, path, kind, options) {
541
699
  kind
542
700
  });
543
701
  if (processed === void 0 || processed === null) continue;
544
- result[processed.key] = processed.value;
702
+ result[processed.key] = serializeAnnotationValue(processed.value, options, state);
545
703
  continue;
546
704
  }
547
- result[key] = value;
705
+ result[key] = serializeAnnotationValue(value, options, state);
548
706
  }
549
707
  return result;
550
708
  }
@@ -580,10 +738,41 @@ function emptyObjectTypeDef() {
580
738
  function toMetadataMap(record) {
581
739
  return new Map(Object.entries(record));
582
740
  }
741
+ function deserializeRef(data, resolved) {
742
+ if (!data.ref) return;
743
+ const refTargetData = data.ref.type;
744
+ if ("type" in refTargetData) {
745
+ const deserializedRefTarget = deserializeNode(refTargetData, resolved);
746
+ return {
747
+ type: () => deserializedRefTarget,
748
+ field: data.ref.field
749
+ };
750
+ }
751
+ const sentinel = createAnnotatedTypeNode(emptyObjectTypeDef(), toMetadataMap(refTargetData.metadata), { id: refTargetData.id || void 0 });
752
+ return {
753
+ type: () => sentinel,
754
+ field: data.ref.field
755
+ };
756
+ }
583
757
  function deserializeNode(data, resolved) {
584
758
  if (data.type.kind === "$ref") {
585
- const refId = data.type.id;
586
- return resolved.get(refId) || createAnnotatedTypeNode(emptyObjectTypeDef(), /* @__PURE__ */ new Map(), { id: refId });
759
+ const { id: refId, own } = data.type;
760
+ const target = resolved.get(refId);
761
+ if (!own) return target || createAnnotatedTypeNode(emptyObjectTypeDef(), /* @__PURE__ */ new Map(), { id: refId });
762
+ const node = createAnnotatedTypeNode(target?.type ?? emptyObjectTypeDef(), toMetadataMap(data.metadata), {
763
+ id: refId,
764
+ optional: data.optional || void 0,
765
+ ref: deserializeRef(data, resolved)
766
+ });
767
+ if (target) Object.defineProperty(node, "type", {
768
+ get: () => target.type,
769
+ set: (v) => {
770
+ target.type = v;
771
+ },
772
+ enumerable: true,
773
+ configurable: true
774
+ });
775
+ return node;
587
776
  }
588
777
  const metadata = toMetadataMap(data.metadata);
589
778
  let result;
@@ -597,23 +786,7 @@ function deserializeNode(data, resolved) {
597
786
  resolved.set(data.id, result);
598
787
  }
599
788
  const type = deserializeTypeDef(data.type, resolved);
600
- let ref;
601
- if (data.ref) {
602
- const refTargetData = data.ref.type;
603
- if ("type" in refTargetData) {
604
- const deserializedRefTarget = deserializeNode(refTargetData, resolved);
605
- ref = {
606
- type: () => deserializedRefTarget,
607
- field: data.ref.field
608
- };
609
- } else {
610
- const sentinel = createAnnotatedTypeNode(emptyObjectTypeDef(), toMetadataMap(refTargetData.metadata), { id: refTargetData.id || void 0 });
611
- ref = {
612
- type: () => sentinel,
613
- field: data.ref.field
614
- };
615
- }
616
- }
789
+ const ref = deserializeRef(data, resolved);
617
790
  if (result) {
618
791
  result.type = type;
619
792
  if (ref) result.ref = ref;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/typescript",
3
- "version": "0.1.98",
3
+ "version": "0.1.100",
4
4
  "description": "Atscript: typescript-gen support.",
5
5
  "keywords": [
6
6
  "annotations",
@@ -73,7 +73,7 @@
73
73
  },
74
74
  "peerDependencies": {
75
75
  "@atscript/db": "^0.1.97",
76
- "@atscript/core": "^0.1.98"
76
+ "@atscript/core": "^0.1.100"
77
77
  },
78
78
  "peerDependenciesMeta": {
79
79
  "@atscript/db": {