@voxgig/struct 0.2.2 → 0.3.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/README.md CHANGED
@@ -610,7 +610,7 @@ transform(
610
610
  )
611
611
  // { x: { y: [ { q: 13, r: 13, p: 1 }, { q: 23, r: 23, p: 1 } ] } }
612
612
  ```
613
- <!-- => {"x": {"y": [{"q": 13, "r": 13, "p": 1}, {"q": 23, "r": 23, "p": 1}]}} -->
613
+ <!-- => {"x": {"y": [{"p": 1, "q": 13, "r": 13}, {"p": 1, "q": 23, "r": 23}]}} -->
614
614
 
615
615
  Putting a command in **key** position (or, for `$APPLY`, directly under a map)
616
616
  is an error — commands must be list values:
@@ -632,7 +632,7 @@ validate(
632
632
  // { name: 'Ada', age: 36 }
633
633
  ```
634
634
 
635
- <!-- => {"name": "Ada", "age": 36} -->
635
+ <!-- => {"age": 36, "name": "Ada"} -->
636
636
 
637
637
  <!-- example: select#query -->
638
638
  ```ts
@@ -644,7 +644,7 @@ select(
644
644
  // [{ name: 'Alice', age: 30, $KEY: 'a' }]
645
645
  ```
646
646
 
647
- <!-- => [{"name": "Alice", "age": 30, "$KEY": "a"}] -->
647
+ <!-- => [{"$KEY": "a", "age": 30, "name": "Alice"}] -->
648
648
 
649
649
  ### Builders
650
650
 
@@ -876,13 +876,33 @@ panel and per-port outcomes.
876
876
 
877
877
  ## Build and test
878
878
 
879
+ Building, linting and testing need nothing but this directory. The corpus
880
+ runner is [voxgig/omni](https://github.com/voxgig/omni), taken from npm as
881
+ `@voxgig/omni` — a **devDependency**, the way jest or vitest would be — so
882
+ there is no checkout to find and no `OMNI_HOME` to set. `npm run build` never
883
+ touches it, and `tools/omni-isolation.js` proves nothing shipped can reach it
884
+ (register 4.13).
885
+
886
+ This port is the first to take omni from a registry; the others still resolve
887
+ a checkout.
888
+
879
889
  ```bash
880
890
  cd typescript
881
- npm install
882
- npm run build # tsc -> dist/
883
- npm test # node --test on dist-test/
891
+ npm install # @voxgig/omni comes with it, as a devDependency
892
+ npm run build # tsc -> dist/ (no omni needed)
893
+ npm test # node --test on dist-test/ (omni from node_modules)
884
894
  ```
885
895
 
896
+ No clone, and no `$OMNI_HOME`. `npm ci` is NOT an option here: this repo
897
+ gitignores `package-lock.json` (`.gitignore` line 150) and commits none, so
898
+ there is nothing for it to install from — which is also why `@voxgig/omni` is
899
+ pinned to an exact `"0.1.0"` rather than a caret.
900
+
901
+ [`test/omni.ts`](./test/omni.ts) is the only file that names omni. It imports
902
+ `@voxgig/omni/compat/struct` and makes the corpus path absolute; that last part
903
+ is still needed, because this port's tests compile to two different depths and
904
+ omni's shim resolves a relative path against its caller.
905
+
886
906
  Tests live in [`test/`](./test/) and read fixtures from
887
907
  [`../build/test/`](../build/test/). The test runner consumes the
888
908
  shared JSONIC corpus shared by every language port.
@@ -125,9 +125,12 @@ declare function injectorArgs(argTypes: number[], args: any[]): any;
125
125
  declare function injectChild(child: any, store: any, inj: Injection): Injection;
126
126
  declare class StructUtility {
127
127
  clone: typeof clone;
128
+ condense: typeof condense;
129
+ condenseview: typeof condenseview;
128
130
  delprop: typeof delprop;
129
131
  escre: typeof escre;
130
132
  escurl: typeof escurl;
133
+ expand: typeof expand;
131
134
  filter: typeof filter;
132
135
  flatten: typeof flatten;
133
136
  getdef: typeof getdef;
@@ -137,6 +140,7 @@ declare class StructUtility {
137
140
  haskey: typeof haskey;
138
141
  inject: typeof inject;
139
142
  isempty: typeof isempty;
143
+ iscondensed: typeof iscondensed;
140
144
  isfunc: typeof isfunc;
141
145
  iskey: typeof iskey;
142
146
  islist: typeof islist;
@@ -161,6 +165,12 @@ declare class StructUtility {
161
165
  typename: typeof typename;
162
166
  validate: typeof validate;
163
167
  walk: typeof walk;
168
+ re_compile: typeof re_compile;
169
+ re_find: typeof re_find;
170
+ re_find_all: typeof re_find_all;
171
+ re_replace: typeof re_replace;
172
+ re_test: typeof re_test;
173
+ re_escape: typeof re_escape;
164
174
  SKIP: {
165
175
  '`$SKIP`': boolean;
166
176
  };
@@ -189,5 +199,19 @@ declare class StructUtility {
189
199
  injectorArgs: typeof injectorArgs;
190
200
  injectChild: typeof injectChild;
191
201
  }
192
- export { StructUtility, clone, delprop, escre, escurl, filter, flatten, getdef, getelem, getpath, getprop, haskey, inject, isempty, isfunc, iskey, islist, ismap, isnode, items, join, jsonify, keysof, merge, pad, pathify, select, setpath, setprop, size, slice, strkey, stringify, transform, typify, typename, validate, walk, re_compile, re_find, re_find_all, re_replace, re_test, re_escape, SKIP, DELETE, jm, jt, T_any, T_noval, T_boolean, T_decimal, T_integer, T_number, T_string, T_function, T_symbol, T_null, T_list, T_map, T_instance, T_scalar, T_node, M_KEYPRE, M_KEYPOST, M_VAL, MODENAME, checkPlacement, injectorArgs, injectChild, };
202
+ declare function iscondensed(val: any): boolean;
203
+ declare function condense(val: any): any;
204
+ declare function expand(cond: any): any;
205
+ type CondenseView = {
206
+ get: (path?: any) => any;
207
+ keys: (path?: any) => string[];
208
+ has: (path?: any) => boolean;
209
+ at: (path?: any) => CondenseView;
210
+ value: () => any;
211
+ size: () => number;
212
+ exists: () => boolean;
213
+ ref: () => any;
214
+ };
215
+ declare function condenseview(cond: any, idx?: number, memo?: any): CondenseView;
216
+ export { StructUtility, clone, condense, condenseview, expand, iscondensed, delprop, escre, escurl, filter, flatten, getdef, getelem, getpath, getprop, haskey, inject, isempty, isfunc, iskey, islist, ismap, isnode, items, join, jsonify, keysof, merge, pad, pathify, select, setpath, setprop, size, slice, strkey, stringify, transform, typify, typename, validate, walk, re_compile, re_find, re_find_all, re_replace, re_test, re_escape, SKIP, DELETE, jm, jt, T_any, T_noval, T_boolean, T_decimal, T_integer, T_number, T_string, T_function, T_symbol, T_null, T_list, T_map, T_instance, T_scalar, T_node, M_KEYPRE, M_KEYPOST, M_VAL, MODENAME, checkPlacement, injectorArgs, injectChild, };
193
217
  export type { Injection, Injector, WalkApply };
@@ -3,6 +3,10 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.MODENAME = exports.M_VAL = exports.M_KEYPOST = exports.M_KEYPRE = exports.T_node = exports.T_scalar = exports.T_instance = exports.T_map = exports.T_list = exports.T_null = exports.T_symbol = exports.T_function = exports.T_string = exports.T_number = exports.T_integer = exports.T_decimal = exports.T_boolean = exports.T_noval = exports.T_any = exports.DELETE = exports.SKIP = exports.StructUtility = void 0;
5
5
  exports.clone = clone;
6
+ exports.condense = condense;
7
+ exports.condenseview = condenseview;
8
+ exports.expand = expand;
9
+ exports.iscondensed = iscondensed;
6
10
  exports.delprop = delprop;
7
11
  exports.escre = escre;
8
12
  exports.escurl = escurl;
@@ -50,7 +54,7 @@ exports.jt = jt;
50
54
  exports.checkPlacement = checkPlacement;
51
55
  exports.injectorArgs = injectorArgs;
52
56
  exports.injectChild = injectChild;
53
- // VERSION: @voxgig/struct 0.2.2
57
+ // VERSION: @voxgig/struct 0.3.1
54
58
  /* Voxgig Struct
55
59
  * =============
56
60
  *
@@ -840,6 +844,18 @@ function delprop(parent, key) {
840
844
  if (!iskey(key)) {
841
845
  return parent;
842
846
  }
847
+ // A condensed structure is a DAG: one subtree can be reached by many
848
+ // references, so an in-place write would be visible through all of them.
849
+ // Raising is the decided contract (design Q1) - it can be relaxed to
850
+ // copy-on-write later without breaking any caller, where the reverse is not
851
+ // true. expand() gives an ordinary mutable copy.
852
+ //
853
+ // Checked AFTER the key validation: both helpers define an invalid key as
854
+ // ignored, so a call that cannot write must not start throwing merely
855
+ // because the store is condensed.
856
+ if (iscondensed(parent)) {
857
+ throw new Error('struct: condensed structures are immutable - ' + 'expand() first, then modify the copy');
858
+ }
843
859
  if (ismap(parent)) {
844
860
  key = strkey(key);
845
861
  delete parent[key];
@@ -871,6 +887,18 @@ function setprop(parent, key, val) {
871
887
  if (!iskey(key)) {
872
888
  return parent;
873
889
  }
890
+ // A condensed structure is a DAG: one subtree can be reached by many
891
+ // references, so an in-place write would be visible through all of them.
892
+ // Raising is the decided contract (design Q1) - it can be relaxed to
893
+ // copy-on-write later without breaking any caller, where the reverse is not
894
+ // true. expand() gives an ordinary mutable copy.
895
+ //
896
+ // Checked AFTER the key validation: both helpers define an invalid key as
897
+ // ignored, so a call that cannot write must not start throwing merely
898
+ // because the store is condensed.
899
+ if (iscondensed(parent)) {
900
+ throw new Error('struct: condensed structures are immutable - ' + 'expand() first, then modify the copy');
901
+ }
874
902
  if (ismap(parent)) {
875
903
  key = S_MT + key;
876
904
  const pany = parent;
@@ -1041,6 +1069,10 @@ function merge(val, maxdepth) {
1041
1069
  // Set a value using a path. Missing path parts are created.
1042
1070
  // String paths create only maps. Use a string list to create list parts.
1043
1071
  function setpath(store, path, val, injdef) {
1072
+ // Same contract as setprop/delprop: a condensed store is immutable.
1073
+ if (iscondensed(store)) {
1074
+ throw new Error('struct: condensed structures are immutable - ' + 'expand() first, then modify the copy');
1075
+ }
1044
1076
  const pathType = typify(path);
1045
1077
  const parts = 0 < (T_list & pathType)
1046
1078
  ? path
@@ -1084,6 +1116,25 @@ function getpath(store, path, injdef) {
1084
1116
  if (NONE === parts) {
1085
1117
  return NONE;
1086
1118
  }
1119
+ // TRANSPARENT CONDENSED READ. A condensed store answers the same path with
1120
+ // the same value as the ordinary node it was built from - the caller does
1121
+ // not need to know which it holds. Only the nodes ON the path are touched,
1122
+ // so this never materialises the whole structure.
1123
+ if (iscondensed(store)) {
1124
+ // The fast path applies only when there are no injection options to
1125
+ // honour. base/dparent/dpath/meta change what the walk below resolves
1126
+ // against, and silently ignoring them would make a condensed store
1127
+ // answer differently from the node it was built from - the opposite of
1128
+ // the transparent-read contract. Rare enough to be worth materialising.
1129
+ if (null == injdef || null == getprop(injdef, S_base)) {
1130
+ const found = condenseResolve(store, store[S_condroot], parts);
1131
+ const val = 0 > found ? undefined : condenseMaterialise(store, found);
1132
+ // Group A null-as-absent: an ordinary getpath observes a stored null
1133
+ // through getprop and reports it as absent, so this must too.
1134
+ return null == val ? undefined : val;
1135
+ }
1136
+ store = expand(store);
1137
+ }
1087
1138
  // let root = store
1088
1139
  let val = store;
1089
1140
  const base = getprop(injdef, S_base);
@@ -1773,14 +1824,23 @@ const validate_CHILD = (inj) => {
1773
1824
  inj.keyI = size(parent);
1774
1825
  return inj.dparent;
1775
1826
  }
1776
- // Clone children abd reset inj key index.
1827
+ // Clone children and reset inj key index.
1777
1828
  // The inject child loop will now iterate over the cloned children,
1778
- // validating them againt the current list values.
1829
+ // validating them against the current list values.
1779
1830
  items(inj.dparent, (n) => setprop(parent, n[0], clone(childtm)));
1780
1831
  slice(parent, 0, inj.dparent.length, true);
1781
- inj.keyI = 0;
1782
- const out = getprop(inj.dparent, 0);
1783
- return out;
1832
+ // NOTE: modifying inj! This extends the child value loop in inject
1833
+ // to cover every cloned child.
1834
+ for (let ckeyI = size(keys); ckeyI < size(parent); ckeyI++) {
1835
+ keys.push(strkey(ckeyI));
1836
+ }
1837
+ // Restart the child value loop at the first element (the loop
1838
+ // increments keyI on resume) so that the first element is also
1839
+ // validated against the child template.
1840
+ inj.keyI = -1;
1841
+ // SKIP leaves the cloned child template in place at the first
1842
+ // element so the resumed loop can validate it.
1843
+ return SKIP;
1784
1844
  }
1785
1845
  return NONE;
1786
1846
  };
@@ -2484,9 +2544,12 @@ function injectChild(child, store, inj) {
2484
2544
  class StructUtility {
2485
2545
  constructor() {
2486
2546
  this.clone = clone;
2547
+ this.condense = condense;
2548
+ this.condenseview = condenseview;
2487
2549
  this.delprop = delprop;
2488
2550
  this.escre = escre;
2489
2551
  this.escurl = escurl;
2552
+ this.expand = expand;
2490
2553
  this.filter = filter;
2491
2554
  this.flatten = flatten;
2492
2555
  this.getdef = getdef;
@@ -2496,6 +2559,7 @@ class StructUtility {
2496
2559
  this.haskey = haskey;
2497
2560
  this.inject = inject;
2498
2561
  this.isempty = isempty;
2562
+ this.iscondensed = iscondensed;
2499
2563
  this.isfunc = isfunc;
2500
2564
  this.iskey = iskey;
2501
2565
  this.islist = islist;
@@ -2520,6 +2584,12 @@ class StructUtility {
2520
2584
  this.typename = typename;
2521
2585
  this.validate = validate;
2522
2586
  this.walk = walk;
2587
+ this.re_compile = re_compile;
2588
+ this.re_find = re_find;
2589
+ this.re_find_all = re_find_all;
2590
+ this.re_replace = re_replace;
2591
+ this.re_test = re_test;
2592
+ this.re_escape = re_escape;
2523
2593
  this.SKIP = SKIP;
2524
2594
  this.DELETE = DELETE;
2525
2595
  this.jm = jm;
@@ -2546,4 +2616,423 @@ class StructUtility {
2546
2616
  }
2547
2617
  }
2548
2618
  exports.StructUtility = StructUtility;
2619
+ // ---------------------------------------------------------------------------
2620
+ // CONDENSED STRUCTURES
2621
+ //
2622
+ // A condensed structure holds the same information as a JSON-shaped node in a
2623
+ // fraction of the space, and can be read WITHOUT materialising it. Three
2624
+ // mechanisms, all in one format:
2625
+ //
2626
+ // intern a symbol table holds each distinct map key and string value once
2627
+ // share identical subtrees become ONE node with many references (a DAG)
2628
+ // lazy a reader resolves a path by walking integer indexes, touching
2629
+ // only the nodes on that path
2630
+ //
2631
+ // The shape:
2632
+ //
2633
+ // { "$condense": 1, format version
2634
+ // "sym": [ ... ], distinct strings, sorted (so lookup can bisect)
2635
+ // "node": [ ... ], integer-encoded nodes, children before parents
2636
+ // "root": 12 } index into node[]
2637
+ //
2638
+ // Each node is one of:
2639
+ //
2640
+ // map [0, k0, v0, k1, v1, ...] k ascending symbol ids, v node refs
2641
+ // list [1, v0, v1, ...] node refs
2642
+ // string [2, symId]
2643
+ // number [3, value]
2644
+ // true [4] false [5] null [6]
2645
+ //
2646
+ // Two properties are load-bearing rather than incidental:
2647
+ //
2648
+ // Map keys ascend, because keysof() sorts. That makes output byte-stable
2649
+ // (generators depend on it) and lets a key lookup bisect rather than scan.
2650
+ //
2651
+ // References are integer indexes into a post-order table, so every ref
2652
+ // points BACKWARDS. Sharing is therefore free — two identical subtrees
2653
+ // intern to one node and two refs, with no dedup pass at read time — and a
2654
+ // reader can never loop.
2655
+ //
2656
+ // The transport is JSON arrays of integers on purpose. The FORMAT is defined
2657
+ // here, but TOKENIZING is left to each language's own JSON parser: mature,
2658
+ // fast, memory-safe, already present, and nothing to keep in parity across
2659
+ // ports. A binary profile ($condense: 2) is a future option, deliberately
2660
+ // deferred - it is worth perhaps 2-3x and costs a hand-written decoder per
2661
+ // language.
2662
+ //
2663
+ // IMMUTABILITY. Sharing makes a condensed structure a DAG, so a mutation
2664
+ // through one reference would be visible through every other. Rather than
2665
+ // make that hazard the caller's problem, it is designed out: mutating
2666
+ // helpers RAISE on a condensed node, and expand()/value() always return an
2667
+ // independent copy. ref() is the one opt-in escape hatch and is named to be
2668
+ // alarming.
2669
+ const CONDENSE_VERSION = 1;
2670
+ const CONDENSE_MAP = 0;
2671
+ const CONDENSE_LIST = 1;
2672
+ const CONDENSE_STR = 2;
2673
+ const CONDENSE_NUM = 3;
2674
+ const CONDENSE_TRUE = 4;
2675
+ const CONDENSE_FALSE = 5;
2676
+ const CONDENSE_NULL = 6;
2677
+ const S_condense = '$condense';
2678
+ const S_condsym = 'sym';
2679
+ const S_condnode = 'node';
2680
+ const S_condroot = 'root';
2681
+ // Is this a condensed structure? Checked structurally rather than by a marker
2682
+ // alone, so an ordinary map that happens to carry a `$condense` key is not
2683
+ // mistaken for one.
2684
+ // Compare by UNICODE CODE POINT, not by UTF-16 code unit.
2685
+ //
2686
+ // JavaScript's default string sort compares UTF-16 code units, which orders
2687
+ // an astral character BEFORE a high-BMP one; Python, Go and Rust all compare
2688
+ // by code point (equivalently, by UTF-8 bytes). A symbol table sorted the
2689
+ // JavaScript way would make two conforming ports emit different bytes for the
2690
+ // same input, which is exactly the byte-stability the format promises. Code
2691
+ // point order is the portable choice, so it is specified rather than
2692
+ // inherited.
2693
+ function condenseCmp(a, b) {
2694
+ let i = 0;
2695
+ let j = 0;
2696
+ while (i < a.length && j < b.length) {
2697
+ const ca = a.codePointAt(i);
2698
+ const cb = b.codePointAt(j);
2699
+ if (ca !== cb) {
2700
+ return ca < cb ? -1 : 1;
2701
+ }
2702
+ i += 0xffff < ca ? 2 : 1;
2703
+ j += 0xffff < cb ? 2 : 1;
2704
+ }
2705
+ return a.length - i - (b.length - j);
2706
+ }
2707
+ // Assign a key that may be `__proto__`.
2708
+ //
2709
+ // Plain assignment to `__proto__` invokes the inherited setter instead of
2710
+ // creating an own property, so a model carrying that key or string value
2711
+ // would be silently corrupted - it is valid JSON and Seneca-adjacent data
2712
+ // really does use `$`-ish and `__`-ish names.
2713
+ function condenseSet(obj, key, val) {
2714
+ if ('__proto__' === key) {
2715
+ Object.defineProperty(obj, key, {
2716
+ value: val,
2717
+ enumerable: true,
2718
+ writable: true,
2719
+ configurable: true,
2720
+ });
2721
+ }
2722
+ else {
2723
+ obj[key] = val;
2724
+ }
2725
+ }
2726
+ function iscondensed(val) {
2727
+ // The version must MATCH, not merely be numeric: a future profile would
2728
+ // otherwise be decoded under this one's schema.
2729
+ return (ismap(val) &&
2730
+ CONDENSE_VERSION === val[S_condense] &&
2731
+ islist(val[S_condsym]) &&
2732
+ islist(val[S_condnode]) &&
2733
+ 'number' === typeof val[S_condroot]);
2734
+ }
2735
+ // Condense any JSON-shaped node. Pure: the same input always produces a
2736
+ // byte-identical result, on every port.
2737
+ function condense(val) {
2738
+ // Pass one: every distinct map key and string value, once, sorted.
2739
+ const symset = Object.create(null);
2740
+ const collect = (n) => {
2741
+ if (ismap(n)) {
2742
+ const keys = keysof(n);
2743
+ for (let i = 0; i < keys.length; i++) {
2744
+ symset[keys[i]] = true;
2745
+ collect(n[keys[i]]);
2746
+ }
2747
+ }
2748
+ else if (islist(n)) {
2749
+ for (let i = 0; i < n.length; i++) {
2750
+ collect(n[i]);
2751
+ }
2752
+ }
2753
+ else if ('string' === typeof n) {
2754
+ symset[n] = true;
2755
+ }
2756
+ };
2757
+ collect(val);
2758
+ const sym = Object.keys(symset).sort(condenseCmp);
2759
+ const symid = Object.create(null);
2760
+ for (let i = 0; i < sym.length; i++) {
2761
+ symid[sym[i]] = i;
2762
+ }
2763
+ // Pass two: build post-order, interning on the canonical encoding. Because
2764
+ // children are built first, identical subtrees have already been interned
2765
+ // by the time a parent references them, so sharing costs nothing extra.
2766
+ const node = [];
2767
+ const seen = Object.create(null);
2768
+ const intern = (enc) => {
2769
+ // The kind tag leads every encoding, so a string node and a number node
2770
+ // can never collide on the same joined key.
2771
+ const enckey = enc.join(',');
2772
+ const hit = seen[enckey];
2773
+ if (undefined !== hit) {
2774
+ return hit;
2775
+ }
2776
+ const idx = node.length;
2777
+ node.push(enc);
2778
+ seen[enckey] = idx;
2779
+ return idx;
2780
+ };
2781
+ const build = (n) => {
2782
+ if (ismap(n)) {
2783
+ const enc = [CONDENSE_MAP];
2784
+ // keysof sorts, so the key ids ascend and lookup can bisect.
2785
+ const keys = keysof(n);
2786
+ for (let i = 0; i < keys.length; i++) {
2787
+ enc.push(symid[keys[i]]);
2788
+ enc.push(build(n[keys[i]]));
2789
+ }
2790
+ return intern(enc);
2791
+ }
2792
+ if (islist(n)) {
2793
+ const enc = [CONDENSE_LIST];
2794
+ for (let i = 0; i < n.length; i++) {
2795
+ enc.push(build(n[i]));
2796
+ }
2797
+ return intern(enc);
2798
+ }
2799
+ if ('string' === typeof n) {
2800
+ return intern([CONDENSE_STR, symid[n]]);
2801
+ }
2802
+ if ('number' === typeof n) {
2803
+ return intern([CONDENSE_NUM, n]);
2804
+ }
2805
+ if (true === n) {
2806
+ return intern([CONDENSE_TRUE]);
2807
+ }
2808
+ if (false === n) {
2809
+ return intern([CONDENSE_FALSE]);
2810
+ }
2811
+ return intern([CONDENSE_NULL]);
2812
+ };
2813
+ const root = build(val);
2814
+ const out = {};
2815
+ out[S_condense] = CONDENSE_VERSION;
2816
+ out[S_condsym] = sym;
2817
+ out[S_condnode] = node;
2818
+ out[S_condroot] = root;
2819
+ return out;
2820
+ }
2821
+ // Resolve a symbol to its id by bisecting the sorted symbol table. -1 when
2822
+ // the string does not occur anywhere in the structure, which is itself a fast
2823
+ // negative answer for a key lookup.
2824
+ function condenseSymId(cond, key) {
2825
+ const sym = cond[S_condsym];
2826
+ let lo = 0;
2827
+ let hi = sym.length - 1;
2828
+ while (lo <= hi) {
2829
+ const mid = (lo + hi) >> 1;
2830
+ if (sym[mid] === key) {
2831
+ return mid;
2832
+ }
2833
+ if (0 > condenseCmp(sym[mid], key)) {
2834
+ lo = mid + 1;
2835
+ }
2836
+ else {
2837
+ hi = mid - 1;
2838
+ }
2839
+ }
2840
+ return -1;
2841
+ }
2842
+ // The node index of `key` inside node `idx`, or -1. Touches only this node.
2843
+ function condenseChild(cond, idx, key) {
2844
+ const enc = cond[S_condnode][idx];
2845
+ if (null == enc) {
2846
+ return -1;
2847
+ }
2848
+ if (CONDENSE_MAP === enc[0]) {
2849
+ const symid = condenseSymId(cond, S_MT + key);
2850
+ if (0 > symid) {
2851
+ return -1;
2852
+ }
2853
+ // Pairs live at [1,2], [3,4], ... with keys ascending: bisect the pairs.
2854
+ let lo = 0;
2855
+ let hi = (enc.length - 1) / 2 - 1;
2856
+ while (lo <= hi) {
2857
+ const mid = (lo + hi) >> 1;
2858
+ const k = enc[1 + mid * 2];
2859
+ if (k === symid) {
2860
+ return enc[2 + mid * 2];
2861
+ }
2862
+ if (k < symid) {
2863
+ lo = mid + 1;
2864
+ }
2865
+ else {
2866
+ hi = mid - 1;
2867
+ }
2868
+ }
2869
+ return -1;
2870
+ }
2871
+ if (CONDENSE_LIST === enc[0]) {
2872
+ // Canonical integer keys ONLY. Unary + would accept "01", "1e0", " 1"
2873
+ // and "+1", which an ordinary list lookup treats as plain (absent)
2874
+ // properties - condensing must not change which value a path selects.
2875
+ const k = S_MT + key;
2876
+ if (!/^(0|[1-9][0-9]*)$/.test(k)) {
2877
+ return -1;
2878
+ }
2879
+ const i = +k;
2880
+ if (i >= enc.length - 1) {
2881
+ return -1;
2882
+ }
2883
+ return enc[1 + i];
2884
+ }
2885
+ return -1;
2886
+ }
2887
+ // Walk a path from a starting node, returning the node index or -1.
2888
+ function condenseResolve(cond, idx, path) {
2889
+ const parts = islist(path)
2890
+ ? path
2891
+ : 'string' === typeof path
2892
+ ? '' === path
2893
+ ? []
2894
+ : path.split(S_DT)
2895
+ : null == path
2896
+ ? []
2897
+ : [S_MT + path];
2898
+ let at = idx;
2899
+ for (let i = 0; i < parts.length; i++) {
2900
+ if (0 > at) {
2901
+ return -1;
2902
+ }
2903
+ if (S_MT === parts[i]) {
2904
+ continue;
2905
+ }
2906
+ at = condenseChild(cond, at, parts[i]);
2907
+ }
2908
+ return at;
2909
+ }
2910
+ // Materialise node `idx` as an ordinary JSON-shaped value.
2911
+ //
2912
+ // Containers are rebuilt on every call and never memoised: sharing is an
2913
+ // implementation detail, and handing the same object out twice would let a
2914
+ // caller mutating one reference corrupt every other. The cost is that
2915
+ // expansion reproduces the original tree - which is exactly the size it was
2916
+ // before condensing, so it is bounded by the input.
2917
+ function condenseMaterialise(cond, idx) {
2918
+ const sym = cond[S_condsym];
2919
+ const node = cond[S_condnode];
2920
+ const rebuild = (i) => {
2921
+ const enc = node[i];
2922
+ if (null == enc) {
2923
+ return undefined;
2924
+ }
2925
+ const kind = enc[0];
2926
+ if (CONDENSE_MAP === kind) {
2927
+ const out = {};
2928
+ for (let j = 1; j < enc.length; j += 2) {
2929
+ condenseSet(out, sym[enc[j]], rebuild(enc[j + 1]));
2930
+ }
2931
+ return out;
2932
+ }
2933
+ if (CONDENSE_LIST === kind) {
2934
+ const out = [];
2935
+ for (let j = 1; j < enc.length; j++) {
2936
+ out.push(rebuild(enc[j]));
2937
+ }
2938
+ return out;
2939
+ }
2940
+ if (CONDENSE_STR === kind) {
2941
+ return sym[enc[1]];
2942
+ }
2943
+ if (CONDENSE_NUM === kind) {
2944
+ return enc[1];
2945
+ }
2946
+ if (CONDENSE_TRUE === kind) {
2947
+ return true;
2948
+ }
2949
+ if (CONDENSE_FALSE === kind) {
2950
+ return false;
2951
+ }
2952
+ return null;
2953
+ };
2954
+ return 0 > idx ? undefined : rebuild(idx);
2955
+ }
2956
+ // Fully materialise a condensed structure. The escape hatch: correct for any
2957
+ // caller, but it gives up every benefit of condensing, so prefer a view or a
2958
+ // path read.
2959
+ function expand(cond) {
2960
+ if (!iscondensed(cond)) {
2961
+ return cond;
2962
+ }
2963
+ return condenseMaterialise(cond, cond[S_condroot]);
2964
+ }
2965
+ // The keys of node `idx`, WITHOUT materialising any of its values. This is
2966
+ // the point of the whole exercise for enumeration: listing the names in a
2967
+ // large collection should cost a symbol-table read, not a full decode.
2968
+ function condenseKeys(cond, idx) {
2969
+ const enc = cond[S_condnode][idx];
2970
+ if (null == enc) {
2971
+ return [];
2972
+ }
2973
+ const sym = cond[S_condsym];
2974
+ const out = [];
2975
+ if (CONDENSE_MAP === enc[0]) {
2976
+ for (let j = 1; j < enc.length; j += 2) {
2977
+ out.push(sym[enc[j]]);
2978
+ }
2979
+ return out;
2980
+ }
2981
+ if (CONDENSE_LIST === enc[0]) {
2982
+ for (let j = 1; j < enc.length; j++) {
2983
+ out.push(S_MT + (j - 1));
2984
+ }
2985
+ return out;
2986
+ }
2987
+ return [];
2988
+ }
2989
+ function condenseview(cond, idx, memo) {
2990
+ const start = null == idx ? (iscondensed(cond) ? cond[S_condroot] : -1) : idx;
2991
+ // Shared materialisations, handed out ONLY by ref(). Threaded through at()
2992
+ // so every cursor into the same structure shares one memo - otherwise
2993
+ // ref() would hand out a different object per cursor and quietly stop
2994
+ // being the shared-reference escape hatch it claims to be.
2995
+ const refmemo = null == memo ? {} : memo;
2996
+ const view = {
2997
+ // The value at path, materialised. Scalars come back directly; a
2998
+ // container comes back as an independent copy.
2999
+ get: (path) => condenseMaterialise(cond, condenseResolve(cond, start, path)),
3000
+ // Key names at path, with no value decoding at all.
3001
+ keys: (path) => {
3002
+ const at = condenseResolve(cond, start, path);
3003
+ return 0 > at ? [] : condenseKeys(cond, at);
3004
+ },
3005
+ has: (path) => 0 <= condenseResolve(cond, start, path),
3006
+ // Chainable cursor. Cheap: no decoding happens here.
3007
+ at: (path) => condenseview(cond, condenseResolve(cond, start, path), refmemo),
3008
+ value: () => condenseMaterialise(cond, start),
3009
+ size: () => {
3010
+ const enc = 0 > start ? null : cond[S_condnode][start];
3011
+ if (null == enc) {
3012
+ return 0;
3013
+ }
3014
+ if (CONDENSE_MAP === enc[0]) {
3015
+ return (enc.length - 1) / 2;
3016
+ }
3017
+ if (CONDENSE_LIST === enc[0]) {
3018
+ return enc.length - 1;
3019
+ }
3020
+ return 0;
3021
+ },
3022
+ exists: () => 0 <= start,
3023
+ // DANGER, and named to say so. Returns a SHARED materialisation: the same
3024
+ // object for the same node, every time. Mutating it corrupts every other
3025
+ // reader of that node, including ones reached by a different path,
3026
+ // because the structure is a DAG. Use value() unless a profile says this
3027
+ // matters.
3028
+ ref: () => {
3029
+ const k = S_MT + start;
3030
+ if (undefined === refmemo[k]) {
3031
+ refmemo[k] = condenseMaterialise(cond, start);
3032
+ }
3033
+ return refmemo[k];
3034
+ },
3035
+ };
3036
+ return view;
3037
+ }
2549
3038
  //# sourceMappingURL=StructUtility.js.map