@gramlot/gramlot 0.2.16 → 0.2.17

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/gramlot.js CHANGED
@@ -11378,25 +11378,6 @@ function registerType(cls, suffix, serializer, deserializer, jsonNative = false)
11378
11378
  CUSTOM_TYPES.push([cls, suffix, serializer, jsonNative]);
11379
11379
  SUFFIX_TO_TYPE[suffix] = [cls, deserializer];
11380
11380
  }
11381
- function registerClass(cls) {
11382
- if (!cls.tytxSuffix) {
11383
- throw new Error(`registerClass: ${cls.name} is missing a static tytxSuffix`);
11384
- }
11385
- if (typeof cls.prototype?.toTytx !== "function") {
11386
- throw new Error(`registerClass: ${cls.name} is missing a toTytx method`);
11387
- }
11388
- if (typeof cls.fromTytx !== "function") {
11389
- throw new Error(`registerClass: ${cls.name} is missing a static fromTytx method`);
11390
- }
11391
- registerType(
11392
- cls,
11393
- cls.tytxSuffix,
11394
- (obj) => obj.toTytx(),
11395
- (s) => cls.fromTytx(s),
11396
- cls.tytxJsonNative || false
11397
- );
11398
- return cls;
11399
- }
11400
11381
  function setSubtypeDict(suffix, subtypes) {
11401
11382
  SUBTYPE_DICTS.set(suffix, subtypes);
11402
11383
  }
@@ -11509,6 +11490,11 @@ var BagResolver = class _BagResolver {
11509
11490
  constructor(kwargs = {}) {
11510
11491
  const defaults = this.constructor.classKwargs;
11511
11492
  const merged = { ...defaults, ...kwargs };
11493
+ for (const option of ["interval", "reactive"]) {
11494
+ if (Object.hasOwn(merged, option)) {
11495
+ throw new TypeError(`Removed resolver option: ${option}. Schedule updates in the application; use reset() and read explicitly.`);
11496
+ }
11497
+ }
11512
11498
  this.cacheTime = merged.cacheTime;
11513
11499
  this._readOnly = merged.readOnly;
11514
11500
  this._asBag = merged.asBag;
@@ -11609,7 +11595,10 @@ var BagResolver = class _BagResolver {
11609
11595
  /**
11610
11596
  * Reset the cache, forcing next resolve to call load().
11611
11597
  */
11612
- reset() {
11598
+ reset(...args) {
11599
+ if (args.length) {
11600
+ throw new TypeError("reset() takes no arguments. It invalidates the cache for the next explicit read.");
11601
+ }
11613
11602
  this._lastUpdate = null;
11614
11603
  this._lastEffectiveFingerprint = null;
11615
11604
  }
@@ -11660,7 +11649,7 @@ var BagResolver = class _BagResolver {
11660
11649
  if (this._node && this._node.attr) {
11661
11650
  const internalParams = this.constructor.internalParams;
11662
11651
  for (const [key, value] of Object.entries(this._node.attr)) {
11663
- if (!internalParams.has(key) && !(key in kwargs)) {
11652
+ if (!internalParams.has(key)) {
11664
11653
  kwargs[key] = value;
11665
11654
  }
11666
11655
  }
@@ -11728,8 +11717,8 @@ var BagResolver = class _BagResolver {
11728
11717
  if (result.startsWith("<") && BagClass.fromXml) {
11729
11718
  return BagClass.fromXml(result);
11730
11719
  }
11731
- if ((result.startsWith("{") || result.startsWith("[")) && BagClass.fromJson) {
11732
- return BagClass.fromJson(result);
11720
+ if ((result.startsWith("{") || result.startsWith("[")) && BagClass.fromTytx) {
11721
+ return BagClass.fromTytx(result);
11733
11722
  }
11734
11723
  }
11735
11724
  return result;
@@ -12878,9 +12867,9 @@ function getClsMarker(cls, inherited) {
12878
12867
  }
12879
12868
 
12880
12869
  // node_modules/@genrojs/bag/src/bag.js
12881
- function* serializationNodes(bag, prefix = "") {
12870
+ function* serializationNodes(bag, prefix = []) {
12882
12871
  for (const node of bag) {
12883
- const path = prefix ? `${prefix}.${node.label}` : node.label;
12872
+ const path = [...prefix, node.label];
12884
12873
  yield [path, node];
12885
12874
  const value = node.getValue(true);
12886
12875
  if (!node.resolver && value instanceof Bag) yield* serializationNodes(value, path);
@@ -12895,14 +12884,33 @@ function xmlDateText(value) {
12895
12884
  if (isEpochDate && !isMidnight) return timestamp.slice(timestamp.indexOf("T") + 1);
12896
12885
  return timestamp;
12897
12886
  }
12887
+ function isDictionary(value) {
12888
+ if (value === null || typeof value !== "object") return false;
12889
+ const proto = Object.getPrototypeOf(value);
12890
+ return proto === Object.prototype || proto === null;
12891
+ }
12892
+ function wireValue(value) {
12893
+ if (typeof value === "string") return value.includes("::") ? `${value}::T` : value;
12894
+ if (Array.isArray(value)) return value.map(wireValue);
12895
+ if (isDictionary(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, wireValue(v)]));
12896
+ return value;
12897
+ }
12898
+ function ingestionOptions(options) {
12899
+ if (!isDictionary(options)) throw new TypeError("Bag options must be an object");
12900
+ const { recursive = true } = options;
12901
+ if (typeof recursive !== "boolean") throw new TypeError("recursive must be a boolean");
12902
+ return recursive;
12903
+ }
12904
+ var warnedFromJson = false;
12898
12905
  var Bag = class _Bag {
12899
12906
  static tytxSuffix = "X";
12900
12907
  /**
12901
12908
  * Create a new Bag.
12902
12909
  *
12903
- * @param {Object} [source=null] - Optional dict to initialize from.
12910
+ * @param {Object|Array|null} [source=null] - In-memory data with literal string labels.
12911
+ * @param {{recursive?: boolean}} [options={}] - Convert nested containers (default true).
12904
12912
  */
12905
- constructor(source = null) {
12913
+ constructor(source = null, options = {}) {
12906
12914
  this._nodes = new BagNodeContainer();
12907
12915
  this._backref = false;
12908
12916
  this._parent = null;
@@ -12911,8 +12919,9 @@ var Bag = class _Bag {
12911
12919
  this._updSubscribers = {};
12912
12920
  this._insSubscribers = {};
12913
12921
  this._delSubscribers = {};
12914
- if (source) {
12915
- this._loadSource(source);
12922
+ ingestionOptions(options);
12923
+ if (source !== null && source !== void 0) {
12924
+ this.fillFrom(source, options);
12916
12925
  }
12917
12926
  }
12918
12927
  // -------------------------------------------------------------------------
@@ -13508,7 +13517,11 @@ var Bag = class _Bag {
13508
13517
  * @param {Function} [options.delete] - Callback for delete events.
13509
13518
  * @param {Function} [options.any] - Callback for all events.
13510
13519
  */
13511
- subscribe(subscriberId, { update = null, insert = null, delete: del = null, any = null } = {}) {
13520
+ subscribe(subscriberId, options = {}) {
13521
+ if (Object.hasOwn(options, "timer") || Object.hasOwn(options, "interval")) {
13522
+ throw new TypeError("Timer subscriptions were removed. Schedule polling in the application.");
13523
+ }
13524
+ const { update = null, insert = null, delete: del = null, any = null } = options;
13512
13525
  if (!this.backref) {
13513
13526
  this.setBackref();
13514
13527
  }
@@ -13526,7 +13539,11 @@ var Bag = class _Bag {
13526
13539
  * @param {boolean} [options.delete=false] - Remove delete subscription.
13527
13540
  * @param {boolean} [options.any=false] - Remove all subscriptions.
13528
13541
  */
13529
- unsubscribe(subscriberId, { update = false, insert = false, delete: del = false, any = false } = {}) {
13542
+ unsubscribe(subscriberId, options = {}) {
13543
+ if (Object.hasOwn(options, "timer") || Object.hasOwn(options, "interval")) {
13544
+ throw new TypeError("Timer subscriptions were removed. Schedule polling in the application.");
13545
+ }
13546
+ const { update = false, insert = false, delete: del = false, any = false } = options;
13530
13547
  if (update || any) {
13531
13548
  delete this._updSubscribers[subscriberId];
13532
13549
  }
@@ -14375,54 +14392,50 @@ var Bag = class _Bag {
14375
14392
  * @param {Object} data - Object where keys become labels and values become node values.
14376
14393
  * @private
14377
14394
  */
14378
- _fillFromDict(data) {
14379
- this.clear();
14380
- for (const [key, value] of Object.entries(data)) {
14381
- if (value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof _Bag) && !(value instanceof BagNode)) {
14382
- this.setItem(key, this.createChildBag()._loadSource(value));
14383
- } else {
14384
- this.setItem(key, value);
14385
- }
14386
- }
14395
+ _appendLiteral(label, value, attr = null, resolver = null, nodeTag = null) {
14396
+ if (typeof label !== "string") throw new TypeError("Bag labels must be strings");
14397
+ const node = new this.nodeClass(this, label, null, attr, resolver, nodeTag, null, false);
14398
+ if (value instanceof BagResolver) node.resolver = value;
14399
+ else node._value = value;
14400
+ this._nodes._dict[label] = node;
14401
+ this._nodes._list.push(node);
14402
+ return node;
14387
14403
  }
14388
- /**
14389
- * Fill this Bag from a source (another Bag or plain object).
14390
- *
14391
- * Prepares replacement contents before changing this Bag:
14392
- * - If source is null/undefined: no-op
14393
- * - If source is a Bag: copies all nodes (deep copy for nested Bags)
14394
- * - If source is a plain object: keys become labels, values become node values.
14395
- * Nested objects are recursively converted to Bags.
14396
- *
14397
- * Preparation errors leave this Bag unchanged. Attached Bags emit one
14398
- * upd_value event after replacement, carrying the previous content.
14399
- * Listener exceptions propagate after the replacement has committed.
14400
- *
14401
- * @param {Bag|Object|null} source - Source to fill from.
14402
- * @returns {Bag} This Bag (for chaining).
14403
- *
14404
- * @example
14405
- * const bag = new Bag();
14406
- * bag.replace(new Bag({ a: 1, b: { c: 2 } }));
14407
- * // bag has 'a' = 1, 'b' = Bag with 'c' = 2
14408
- *
14409
- * const other = new Bag();
14410
- * other.setItem('x', 10);
14411
- * bag.replace(other);
14412
- * // bag now has only 'x' = 10
14413
- */
14414
- _loadSource(source) {
14415
- if (source == null) return this;
14416
- const prepared = this.createChildBag();
14417
- if (source instanceof _Bag) {
14418
- prepared._fillFromBag(source);
14419
- } else if (typeof source === "object" && !Array.isArray(source)) {
14420
- prepared._fillFromDict(source);
14421
- } else {
14422
- return this;
14404
+ /** Replace in-memory data atomically. None/null clears; leaves stay shared. */
14405
+ fillFrom(source = null, options = {}) {
14406
+ const recursive = ingestionOptions(options);
14407
+ if (source != null && !isDictionary(source) && !Array.isArray(source)) {
14408
+ throw new TypeError("Bag source must be a dictionary, array or null");
14423
14409
  }
14410
+ const prepared = this.createChildBag();
14411
+ const active = /* @__PURE__ */ new Set();
14412
+ const populate = (bag, data, path) => {
14413
+ if (active.has(data)) throw new TypeError(`Cyclic Bag source at ${path}`);
14414
+ active.add(data);
14415
+ try {
14416
+ const width = Array.isArray(data) ? String(data.length).length + 1 : 0;
14417
+ const entries = Array.isArray(data) ? Array.from(data, (value, i) => [`r_${String(i).padStart(width, "0")}`, value]) : Object.entries(data);
14418
+ if (!Array.isArray(data) && Object.getOwnPropertySymbols(data).some((key) => Object.prototype.propertyIsEnumerable.call(data, key))) {
14419
+ throw new TypeError(`Bag labels must be strings at ${path}`);
14420
+ }
14421
+ for (const [label, item] of entries) {
14422
+ let value = item;
14423
+ if (recursive && (isDictionary(value) || Array.isArray(value))) {
14424
+ value = this.createChildBag();
14425
+ populate(value, item, `${path}[${JSON.stringify(label)}]`);
14426
+ }
14427
+ bag._appendLiteral(label, value);
14428
+ }
14429
+ } finally {
14430
+ active.delete(data);
14431
+ }
14432
+ };
14433
+ if (source != null) populate(prepared, source, "$");
14424
14434
  return this._replacePrepared(prepared);
14425
14435
  }
14436
+ _loadSource(source, options = {}) {
14437
+ return this.fillFrom(source, options);
14438
+ }
14426
14439
  /** Replace all contents from a Bag, preserving identity. Returns this. */
14427
14440
  replace(other) {
14428
14441
  if (!(other instanceof _Bag)) throw new TypeError("Bag.replace expects a Bag");
@@ -14519,10 +14532,11 @@ var Bag = class _Bag {
14519
14532
  const compact = pathRegistry !== null;
14520
14533
  const pathToCode = compact ? /* @__PURE__ */ Object.create(null) : null;
14521
14534
  let codeCounter = 0;
14522
- const pathToClass = /* @__PURE__ */ new Map([["", this.constructor]]);
14535
+ const pathToClass = /* @__PURE__ */ new Map([["[]", this.constructor]]);
14523
14536
  for (const [path, node] of serializationNodes(this)) {
14524
- const lastDot = path.lastIndexOf(".");
14525
- const parentPath = lastDot >= 0 ? path.slice(0, lastDot) : "";
14537
+ const parentPath = path.slice(0, -1);
14538
+ const pathKey = JSON.stringify(path);
14539
+ const parentKey = JSON.stringify(parentPath);
14526
14540
  const nodeValue = node.getValue(true);
14527
14541
  let value;
14528
14542
  let branchCls = null;
@@ -14531,27 +14545,27 @@ var Bag = class _Bag {
14531
14545
  } else if (nodeValue instanceof _Bag) {
14532
14546
  const cls = nodeValue.constructor;
14533
14547
  const suffix = cls.tytxSuffix;
14534
- pathToClass.set(path, cls);
14535
- branchCls = getClsMarker(cls, getInheritedClass(pathToClass.get(parentPath), suffix));
14548
+ pathToClass.set(pathKey, cls);
14549
+ branchCls = getClsMarker(cls, getInheritedClass(pathToClass.get(parentKey), suffix));
14536
14550
  value = `::${suffix}`;
14537
14551
  } else if (nodeValue === null) {
14538
14552
  value = "::NN";
14539
14553
  } else {
14540
- value = nodeValue;
14554
+ value = wireValue(nodeValue);
14541
14555
  }
14542
14556
  if (node.attr && Object.hasOwn(node.attr, CLS_ATTRIBUTE)) {
14543
14557
  throw new BagSerializationError(
14544
14558
  `node '${path}': the attribute '${CLS_ATTRIBUTE}' is reserved for the Bag class name`
14545
14559
  );
14546
14560
  }
14547
- const attr = encodeAttrs(node.attr);
14561
+ const attr = encodeAttrs(wireValue(node.attr));
14548
14562
  if (branchCls !== null) attr[CLS_ATTRIBUTE] = branchCls;
14549
14563
  const tag2 = node.nodeTag;
14550
14564
  if (compact) {
14551
- const parentRef = parentPath ? pathToCode[parentPath] : null;
14565
+ const parentRef = parentPath.length ? pathToCode[parentKey] : null;
14552
14566
  yield [parentRef, node.label, tag2, value, attr];
14553
14567
  if (nodeValue instanceof _Bag) {
14554
- pathToCode[path] = codeCounter;
14568
+ pathToCode[pathKey] = codeCounter;
14555
14569
  pathRegistry[codeCounter] = path;
14556
14570
  codeCounter++;
14557
14571
  }
@@ -14571,6 +14585,15 @@ var Bag = class _Bag {
14571
14585
  * @returns {string|Uint8Array} Serialized data.
14572
14586
  */
14573
14587
  toTytx(transport = "json", compact = false) {
14588
+ const payload = this._toTytxPayload(compact);
14589
+ const suffix = this.constructor.tytxSuffix;
14590
+ if (transport === "json") return `${payload}::${suffix}`;
14591
+ if (transport === "msgpack") {
14592
+ return encode(new ExtData(4, new TextEncoder().encode(`${suffix}:${payload}`)));
14593
+ }
14594
+ throw new TypeError(`Unsupported transport: ${transport}`);
14595
+ }
14596
+ _toTytxPayload(compact = false) {
14574
14597
  let data;
14575
14598
  if (compact) {
14576
14599
  const paths = {};
@@ -14583,8 +14606,9 @@ var Bag = class _Bag {
14583
14606
  const rootClass = this.constructor;
14584
14607
  const rootCls = getClsMarker(rootClass, getInheritedClass(null, rootClass.tytxSuffix));
14585
14608
  if (rootCls !== null) data[CLS_ATTRIBUTE] = rootCls;
14586
- const tytxTransport = transport === "json" ? null : transport;
14587
- return toTytx(data, tytxTransport);
14609
+ data.rows = data.rows.map(([parent, label, tag2, value, attr]) => [wireValue(parent), wireValue(label), wireValue(tag2), value, attr]);
14610
+ if (data.paths) data.paths = wireValue(data.paths);
14611
+ return toTytx(data);
14588
14612
  }
14589
14613
  /**
14590
14614
  * Deserialize Bag from TyTx format.
@@ -14593,10 +14617,30 @@ var Bag = class _Bag {
14593
14617
  * @param {string} [transport='json'] - Input format: 'json' or 'msgpack'.
14594
14618
  * @returns {Bag} Reconstructed Bag.
14595
14619
  */
14596
- static fromTytx(data, transport = "json") {
14620
+ static fromTytx(data, transport = "json", options = {}) {
14621
+ if (isDictionary(transport)) {
14622
+ options = transport;
14623
+ transport = "json";
14624
+ }
14625
+ ingestionOptions(options);
14626
+ if (typeof data !== "string" && !(data instanceof Uint8Array)) {
14627
+ throw new TypeError("fromTytx requires serialized text or bytes");
14628
+ }
14629
+ if (transport !== "json" && transport !== "msgpack") {
14630
+ throw new TypeError(`Unsupported transport: ${transport}`);
14631
+ }
14632
+ if (transport === "json" && data instanceof Uint8Array) data = new TextDecoder().decode(data);
14633
+ const decoded = fromTytx(data, transport === "json" ? null : transport);
14634
+ if (decoded instanceof _Bag) return decoded;
14635
+ if (!isDictionary(decoded) && !Array.isArray(decoded)) {
14636
+ throw new TypeError("fromTytx requires a dictionary, array or typed Bag root");
14637
+ }
14638
+ return new this(decoded, options);
14639
+ }
14640
+ static _fromTytxPayload(data) {
14597
14641
  const suffix = this.tytxSuffix;
14598
14642
  if (data === "") return new (getInheritedClass(null, suffix))();
14599
- const parsed = fromTytx(data, transport === "json" ? null : transport);
14643
+ const parsed = fromTytx(data);
14600
14644
  if (!parsed || !Array.isArray(parsed.rows)) {
14601
14645
  throw new BagSerializationError("Invalid TYTX Bag: expected rows");
14602
14646
  }
@@ -14604,7 +14648,7 @@ var Bag = class _Bag {
14604
14648
  const compact = paths != null;
14605
14649
  const rootClass = Object.hasOwn(parsed, CLS_ATTRIBUTE) ? getSubtypeClass(suffix, parsed[CLS_ATTRIBUTE]) : getInheritedClass(null, suffix);
14606
14650
  const bag = new rootClass();
14607
- const pathToBag = /* @__PURE__ */ new Map([["", bag]]);
14651
+ const pathToBag = /* @__PURE__ */ new Map([["[]", bag]]);
14608
14652
  for (const row of parsed.rows) {
14609
14653
  if (!Array.isArray(row) || row.length !== 5) {
14610
14654
  throw new BagSerializationError("Invalid TYTX Bag row");
@@ -14617,16 +14661,15 @@ var Bag = class _Bag {
14617
14661
  }
14618
14662
  parentPath = parentRef === null ? "" : paths[parentRef];
14619
14663
  }
14620
- if (!pathToBag.has(parentPath)) {
14664
+ if (typeof parentPath === "string") parentPath = parentPath ? parentPath.split(".") : [];
14665
+ if (!Array.isArray(parentPath)) throw new BagSerializationError("Invalid TYTX parent path");
14666
+ const parentKey = JSON.stringify(parentPath);
14667
+ if (!pathToBag.has(parentKey)) {
14621
14668
  throw new BagSerializationError(`Missing or undecodable TYTX parent branch: ${parentPath}`);
14622
14669
  }
14623
- const parentBag = pathToBag.get(parentPath);
14624
- const fullPath = parentPath ? `${parentPath}.${label}` : label;
14670
+ const parentBag = pathToBag.get(parentKey);
14671
+ const fullPath = JSON.stringify([...parentPath, label]);
14625
14672
  let value = rawValue;
14626
- if (transport === "msgpack" && typeof value === "string" && value.startsWith("::")) {
14627
- const cls = getRegisteredType(value.slice(2));
14628
- if (cls === _Bag || cls?.prototype instanceof _Bag) value = fromTytx(value);
14629
- }
14630
14673
  const resolver = decodeResolver(value);
14631
14674
  const attr = decodeAttrs(rawAttr);
14632
14675
  const branchCls = Object.hasOwn(attr, CLS_ATTRIBUTE) ? attr[CLS_ATTRIBUTE] : null;
@@ -14640,10 +14683,8 @@ var Bag = class _Bag {
14640
14683
  throw new BagSerializationError(
14641
14684
  `node '${fullPath}': the attribute '${CLS_ATTRIBUTE}' is reserved for the Bag class name of a branch`
14642
14685
  );
14643
- } else if (value === "::NN") {
14644
- value = null;
14645
14686
  }
14646
- const node = parentBag.setItem(label, resolver || value, attr);
14687
+ const node = parentBag._appendLiteral(label, resolver ? null : value, attr, resolver);
14647
14688
  node.nodeTag = tag2 ?? null;
14648
14689
  }
14649
14690
  return bag;
@@ -14849,7 +14890,7 @@ ${" ".repeat(depth)}</${tag2}>`;
14849
14890
  const contentType = response.headers.get("content-type") || "";
14850
14891
  const text = await response.text();
14851
14892
  if (contentType.includes("json")) {
14852
- return _Bag.fromJson(text);
14893
+ return _Bag.fromTytx(text);
14853
14894
  }
14854
14895
  if (contentType.includes("xml")) {
14855
14896
  return _Bag.fromXml(text);
@@ -14859,7 +14900,7 @@ ${" ".repeat(depth)}</${tag2}>`;
14859
14900
  return _Bag.fromXml(text);
14860
14901
  }
14861
14902
  if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
14862
- return _Bag.fromJson(text);
14903
+ return _Bag.fromTytx(text);
14863
14904
  }
14864
14905
  throw new BagException(`Unsupported content-type: ${contentType}`);
14865
14906
  }
@@ -14904,67 +14945,17 @@ ${" ".repeat(depth)}</${tag2}>`;
14904
14945
  return result;
14905
14946
  }
14906
14947
  /**
14907
- * Deserialize JSON to Bag.
14908
- *
14909
- * Accepts JSON string, dict, or list. Recursively converts nested
14910
- * structures to Bag hierarchy.
14911
- *
14912
- * @param {string|Object|Array} source - JSON string, dict or list to parse.
14913
- * @param {string} [listJoiner=null] - If provided, join string arrays with this separator.
14914
- * @returns {Bag} Deserialized Bag.
14948
+ * Deprecated alias of fromTytx: serialized text only, no node heuristics.
14949
+ * @deprecated Use fromTytx, or new Bag(data) for native dictionaries/arrays.
14950
+ * @param {string|Uint8Array} source
14951
+ * @param {{recursive?: boolean}} [options={}]
14915
14952
  */
14916
- static fromJson(source, listJoiner = null) {
14917
- if (typeof source === "string") {
14918
- source = fromTytx(source);
14953
+ static fromJson(source, options = {}) {
14954
+ if (!warnedFromJson) {
14955
+ console.warn("Bag.fromJson is deprecated; use Bag.fromTytx");
14956
+ warnedFromJson = true;
14919
14957
  }
14920
- if (!Array.isArray(source) && typeof source !== "object") {
14921
- source = { value: source };
14922
- }
14923
- return _Bag._fromJsonRecursive(source, listJoiner);
14924
- }
14925
- /**
14926
- * Recursively convert JSON data to Bag (internal).
14927
- * @private
14928
- */
14929
- static _fromJsonRecursive(data, listJoiner = null) {
14930
- if (data instanceof _Bag) return data;
14931
- if (Array.isArray(data)) {
14932
- if (listJoiner !== null && data.every((item) => typeof item === "string")) {
14933
- return data.join(listJoiner);
14934
- }
14935
- if (data.length === 0) {
14936
- return new _Bag();
14937
- }
14938
- if (typeof data[0] === "object" && data[0] !== null && "label" in data[0]) {
14939
- const result2 = new _Bag();
14940
- for (const item of data) {
14941
- const label = item.label;
14942
- const value = _Bag._fromJsonRecursive(item.value, listJoiner);
14943
- const attr = decodeAttrs(item.attr);
14944
- const node = result2.setItem(label, value, attr);
14945
- node.nodeTag = item.tag ?? null;
14946
- const resolver = decodeResolver(item.resolver);
14947
- if (resolver) node.resolver = resolver;
14948
- }
14949
- return result2;
14950
- }
14951
- const result = new _Bag();
14952
- for (let n = 0; n < data.length; n++) {
14953
- result.setItem(`r_${n}`, _Bag._fromJsonRecursive(data[n], listJoiner));
14954
- }
14955
- return result;
14956
- }
14957
- if (typeof data === "object" && data !== null) {
14958
- if (Object.keys(data).length === 0) {
14959
- return new _Bag();
14960
- }
14961
- const result = new _Bag();
14962
- for (const [k, v] of Object.entries(data)) {
14963
- result.setItem(k, _Bag._fromJsonRecursive(v, listJoiner));
14964
- }
14965
- return result;
14966
- }
14967
- return data;
14958
+ return this.fromTytx(source, "json", options);
14968
14959
  }
14969
14960
  // -------------------------------------------------------------------------
14970
14961
  // String representation
@@ -15109,7 +15100,7 @@ var BagException = class extends Error {
15109
15100
  }
15110
15101
  };
15111
15102
  BagResolver.registerBagClass(Bag);
15112
- registerClass(Bag);
15103
+ registerType(Bag, "X", (bag) => bag._toTytxPayload(), (payload) => Bag._fromTytxPayload(payload));
15113
15104
  setSubtypeDict(Bag.tytxSuffix, { ...getSubtypeDict(Bag.tytxSuffix), Bag });
15114
15105
 
15115
15106
  // node_modules/@genrojs/builders/src/utils.js
@@ -15226,6 +15217,7 @@ var SourceBagNode = class extends BagNode {
15226
15217
  /** Reactive pointers carried by this node as [attrname, pointer].
15227
15218
  * attrname "" for a pointer in node.value. Only `^` (reactive). */
15228
15219
  pointers() {
15220
+ this.builder.validateCustomTypes(this);
15229
15221
  const result = [];
15230
15222
  for (const [attrname, v] of Object.entries(this.getAttr() || {})) {
15231
15223
  if (this.pointerType(v) === "^") {
@@ -15559,10 +15551,32 @@ function jsonValue(value, path) {
15559
15551
  if (plainObject(value)) return Object.entries(value).forEach(([k, v]) => jsonValue(v, `${path}.${k}`));
15560
15552
  fail(path, "must be lossless JSON data");
15561
15553
  }
15562
- function annotation(desc, path, nested = false) {
15554
+ function pythonRegexPattern(pattern, flags) {
15555
+ let result = "", inClass = false;
15556
+ for (let i = 0; i < pattern.length; i++) {
15557
+ const ch = pattern[i];
15558
+ if (ch === "\\") {
15559
+ result += ch + (pattern[++i] ?? "");
15560
+ continue;
15561
+ }
15562
+ if (ch === "[") inClass = true;
15563
+ if (!inClass && ch === "." && !(flags & 16)) result += "[^\\n]";
15564
+ else if (!inClass && ch === "^" && flags & 8) result += "(?:^|(?<=\\n))";
15565
+ else if (!inClass && ch === "$") result += flags & 8 ? "(?=\\n|(?![\\s\\S]))" : "(?=\\n?(?![\\s\\S]))";
15566
+ else result += ch;
15567
+ if (ch === "]") inClass = false;
15568
+ }
15569
+ return result;
15570
+ }
15571
+ function annotation(desc, path, nested = false, customTypes = null) {
15563
15572
  if (desc === null) return null;
15564
15573
  exactKeys(desc, ["kind", "module", "name", "origin", "arguments", "items", "values", "base", "metadata", "pattern", "flags", "ge", "le", "gt", "lt", "value"], ["kind"], path);
15565
15574
  switch (desc.kind) {
15575
+ case "custom": {
15576
+ exactKeys(desc, ["kind", "name"], ["kind", "name"], path);
15577
+ if (!customTypes) fail(path, "custom references require a catalog; nested catalog references are unsupported");
15578
+ return customTypes.resolve(desc.name, path);
15579
+ }
15566
15580
  case "any":
15567
15581
  return { ...desc, test: (_v) => true };
15568
15582
  case "type": {
@@ -15575,8 +15589,8 @@ function annotation(desc, path, nested = false) {
15575
15589
  }
15576
15590
  case "union": {
15577
15591
  if (!Array.isArray(desc.items) || !desc.items.length) fail(path, "union items must be non-empty");
15578
- const items = desc.items.map((v, i) => annotation(v, `${path}.items[${i}]`, true));
15579
- return { ...desc, items, test: (v) => items.some((x) => x.test && x.test(v)) };
15592
+ const items = desc.items.map((v, i) => annotation(v, `${path}.items[${i}]`, true, customTypes));
15593
+ return { ...desc, items, inputConstraint: items.some((x) => x.inputConstraint), test: (v) => items.some((x) => x.test && x.test(v)) };
15580
15594
  }
15581
15595
  case "literal":
15582
15596
  if (!Array.isArray(desc.values)) fail(path, "literal values must be an array");
@@ -15584,9 +15598,10 @@ function annotation(desc, path, nested = false) {
15584
15598
  return { ...desc, test: (v) => desc.values.some((x) => Object.is(x, v)) };
15585
15599
  case "annotated": {
15586
15600
  if (!Array.isArray(desc.metadata)) fail(path, "annotated metadata must be an array");
15587
- const base = annotation(desc.base, `${path}.base`, true);
15588
- const metadata = desc.metadata.map((v, i) => annotation(v, `${path}.metadata[${i}]`, true));
15589
- return { ...desc, base, metadata, test: (v) => base.test(v) && metadata.every((x) => !x.test || x.test(v)) };
15601
+ if (desc.metadata.some((v) => !["regex", "range", "value"].includes(v?.kind))) fail(path, "unsupported annotation metadata kind");
15602
+ const base = annotation(desc.base, `${path}.base`, true, customTypes);
15603
+ const metadata = desc.metadata.map((v, i) => annotation(v, `${path}.metadata[${i}]`, true, customTypes));
15604
+ return { ...desc, base, metadata, inputConstraint: base.inputConstraint, test: (v) => base.test(v) && metadata.every((x) => !x.test || x.test(v)) };
15590
15605
  }
15591
15606
  case "range": {
15592
15607
  for (const key of ["ge", "le", "gt", "lt"]) if (!Object.hasOwn(desc, key)) fail(path, `range missing '${key}'`);
@@ -15598,13 +15613,12 @@ function annotation(desc, path, nested = false) {
15598
15613
  const unsupported = desc.flags & ~(2 | 8 | 16 | 32);
15599
15614
  if (unsupported) fail(path, `unsupported Python regex flags ${unsupported}`);
15600
15615
  if (desc.flags & 2) fail(path, "IGNORECASE is not portable across Python and JavaScript Unicode rules");
15601
- if (/\\[AZwWdDsS]|\(\?P[<=!]|\(\?\(|\(\?>/.test(desc.pattern)) fail(path, "regex uses a non-portable construct or character class");
15616
+ if (/\\[AZzUwWdDsSabBN0-9]|\(\?P[<=!]|\(\?\(|\(\?>|\(\?#|\(\?[aiLmsux-]|[+*?}]\+|\{,/.test(desc.pattern.replaceAll(String.raw`[\s\S]`, "."))) fail(path, "regex uses a non-portable construct or character class");
15602
15617
  let flags = "uy";
15603
- if (desc.flags & 8) flags += "m";
15604
15618
  if (desc.flags & 16) flags += "s";
15605
15619
  let re;
15606
15620
  try {
15607
- re = new RegExp(`(?:${desc.pattern})(?![\\s\\S])`, flags);
15621
+ re = new RegExp(`(?:${pythonRegexPattern(desc.pattern, desc.flags)})(?![\\s\\S])`, flags);
15608
15622
  } catch (error) {
15609
15623
  fail(path, `invalid portable regex: ${error.message}`);
15610
15624
  }
@@ -15618,13 +15632,13 @@ function annotation(desc, path, nested = false) {
15618
15632
  jsonValue(desc.value, `${path}.value`);
15619
15633
  return { ...desc };
15620
15634
  case "generic": {
15621
- const origin = annotation(desc.origin, `${path}.origin`, true);
15635
+ const origin = annotation(desc.origin, `${path}.origin`, true, customTypes);
15622
15636
  if (desc.origin?.kind !== "type" || desc.origin.module !== "builtins" || !["list", "dict", "tuple", "set"].includes(desc.origin.name)) {
15623
15637
  fail(path, "only list, dict, tuple and set generic origins are supported");
15624
15638
  }
15625
15639
  if (!Array.isArray(desc.arguments)) fail(path, "generic arguments must be an array");
15626
- const args = desc.arguments.map((v, i) => annotation(v, `${path}.arguments[${i}]`, true));
15627
- return { ...desc, origin, arguments: args, test: (v) => origin.test(v) && genericItems(desc.origin, args, v) };
15640
+ const args = desc.arguments.map((v, i) => annotation(v, `${path}.arguments[${i}]`, true, customTypes));
15641
+ return { ...desc, origin, arguments: args, inputConstraint: args.some((x) => x.inputConstraint), test: (v) => origin.test(v) && genericItems(desc.origin, args, v) };
15628
15642
  }
15629
15643
  case "arguments":
15630
15644
  fail(path, "Callable argument-list descriptors are not supported by Python validation");
@@ -15683,7 +15697,7 @@ function parseParents(spec, path) {
15683
15697
  }
15684
15698
  return result;
15685
15699
  }
15686
- function parameters(value, path) {
15700
+ function parameters(value, path, customTypes) {
15687
15701
  if (value === null) return null;
15688
15702
  exactKeys(value, ["parameters", "accepts_var_keyword", "accepts_var_positional"], [], path);
15689
15703
  const params = value.parameters ?? [];
@@ -15708,14 +15722,14 @@ function parameters(value, path) {
15708
15722
  if (p.has_default) jsonValue(p.default, `${pp}.default`);
15709
15723
  foundVarKeyword ||= p.kind === "var_keyword";
15710
15724
  foundVarPositional ||= p.kind === "var_positional";
15711
- return { ...p, annotation: annotation(p.annotation, `${pp}.annotation`) };
15725
+ return { ...p, annotation: annotation(p.annotation, `${pp}.annotation`, false, customTypes) };
15712
15726
  });
15713
15727
  if (foundVarKeyword !== value.accepts_var_keyword || foundVarPositional !== value.accepts_var_positional) {
15714
15728
  fail(path, "variadic summary flags do not match parameters");
15715
15729
  }
15716
15730
  return { ...value, parameters: parsed };
15717
15731
  }
15718
- function declaration(value, path, isElement) {
15732
+ function declaration(value, path, isElement, customTypes) {
15719
15733
  const keys = ["doc", "sub_tags", "parent_tags", "inherits_from", "ns", "attributes", ...isElement ? ["node_label", "collection_key"] : [], "_meta"];
15720
15734
  exactKeys(value, keys, [], path);
15721
15735
  value = { ...Object.fromEntries(keys.map((k) => [k, null])), ...value };
@@ -15726,7 +15740,7 @@ function declaration(value, path, isElement) {
15726
15740
  }
15727
15741
  parseCardinality(value.sub_tags, `${path}.sub_tags`);
15728
15742
  parseParents(value.parent_tags, `${path}.parent_tags`);
15729
- return { ...value, attributes: parameters(value.attributes, `${path}.attributes`) };
15743
+ return { ...value, attributes: parameters(value.attributes, `${path}.attributes`, customTypes) };
15730
15744
  }
15731
15745
  function parents(value) {
15732
15746
  return value ? value.split(",").map((x) => x.trim()).filter(Boolean) : [];
@@ -15776,26 +15790,28 @@ function resolveGrammarDeclarations({ abstracts: rawAbstracts = {}, elements: ra
15776
15790
  return { abstracts, elements };
15777
15791
  }
15778
15792
  function parseGrammarDocument(doc) {
15779
- exactKeys(doc, ["document_format", "grammar", "abstracts", "elements"], ["document_format", "grammar", "abstracts", "elements"], "grammar document");
15793
+ exactKeys(doc, ["document_format", "grammar", "abstracts", "elements", "custom_types"], ["document_format", "grammar", "abstracts", "elements"], "grammar document");
15780
15794
  exactKeys(doc.document_format, ["name", "version"], ["name", "version"], "document_format");
15781
- if (doc.document_format.name !== "builder_grammar" || doc.document_format.version !== "1.1") fail("document_format", "expected builder_grammar version 1.1");
15795
+ if (doc.document_format.name !== "builder_grammar" || !["1.1", "1.2"].includes(doc.document_format.version)) fail("document_format", "expected builder_grammar version 1.1 or 1.2");
15782
15796
  exactKeys(doc.grammar, ["name", "version", "title", "description"], ["name", "version", "title", "description"], "grammar");
15783
15797
  if (typeof doc.grammar.name !== "string" || !doc.grammar.name) fail("grammar.name", "must be non-empty string");
15784
15798
  for (const key of ["version", "title", "description"]) if (doc.grammar[key] !== null && typeof doc.grammar[key] !== "string") fail(`grammar.${key}`, "must be string or null");
15785
15799
  if (!plainObject(doc.abstracts) || !plainObject(doc.elements)) fail("grammar document", "abstracts/elements must be objects");
15800
+ if (Object.hasOwn(doc, "custom_types") && doc.document_format.version !== "1.2") fail("custom_types", "requires version 1.2");
15801
+ const customTypes = CustomTypes.fromJSON(doc.custom_types ?? {});
15786
15802
  const rawAbstracts = {};
15787
15803
  for (const [name, value] of Object.entries(doc.abstracts)) {
15788
15804
  if (!name || name.startsWith("_")) {
15789
15805
  fail("abstracts", `invalid public name '${name}'`);
15790
15806
  }
15791
- rawAbstracts[name] = declaration(value, `abstracts.${name}`, false);
15807
+ rawAbstracts[name] = declaration(value, `abstracts.${name}`, false, customTypes);
15792
15808
  }
15793
15809
  const rawElements = {};
15794
15810
  for (const [name, value] of Object.entries(doc.elements)) {
15795
15811
  if (!name || name.startsWith("_")) {
15796
15812
  fail("elements", `invalid public name '${name}'`);
15797
15813
  }
15798
- rawElements[name] = declaration(value, `elements.${name}`, true);
15814
+ rawElements[name] = declaration(value, `elements.${name}`, true, customTypes);
15799
15815
  }
15800
15816
  return {
15801
15817
  grammar: structuredClone(doc.grammar),
@@ -15822,10 +15838,76 @@ function validateElementValues(tag2, spec, value, attrs) {
15822
15838
  if (present && p.annotation !== null && (!p.annotation.test || !p.annotation.test(supplied[p.name]))) fail(tag2, `invalid value for ${p.role} '${p.name}'`);
15823
15839
  }
15824
15840
  }
15841
+ var CustomTypes = class _CustomTypes {
15842
+ #definitions = /* @__PURE__ */ new Map();
15843
+ #compiled = /* @__PURE__ */ new Map();
15844
+ register(name, type, constraint) {
15845
+ const bases = /* @__PURE__ */ new Map([
15846
+ [String, "str"],
15847
+ [Number, "float"],
15848
+ ["string", "str"],
15849
+ ["integer", "int"],
15850
+ ["number", "float"]
15851
+ ]);
15852
+ const base = bases.has(type) ? { kind: "type", module: "builtins", name: bases.get(type) } : type;
15853
+ return this.#register(name, { kind: "annotated", base, metadata: [constraint] });
15854
+ }
15855
+ #register(name, definition) {
15856
+ if (typeof name !== "string" || !/^[A-Za-z][A-Za-z0-9_]*$/.test(name) || name in this || ["to_dict", "from_dict"].includes(name) || PYTHON_KEYWORDS2.has(name)) fail("custom_types", `invalid, reserved or duplicate name '${name}'`);
15857
+ exactKeys(definition, ["kind", "base", "metadata"], ["kind", "base", "metadata"], `custom_types.${name}`);
15858
+ if (definition.kind !== "annotated" || !Array.isArray(definition.metadata) || definition.metadata.length !== 1 || !["regex", "range"].includes(definition.metadata[0]?.kind)) {
15859
+ fail(`custom_types.${name}`, "requires an annotated base with one Regex or Range validator");
15860
+ }
15861
+ const expected = definition.metadata[0].kind === "regex" ? ["str"] : ["int", "float"];
15862
+ if (definition.base?.kind !== "type" || definition.base.module !== "builtins" || !expected.includes(definition.base.name)) {
15863
+ fail(`custom_types.${name}`, "portable Regex requires str; portable Range requires int or float");
15864
+ }
15865
+ jsonValue(definition, `custom_types.${name}`);
15866
+ const copy = structuredClone(definition);
15867
+ const compiled = annotation(copy, `custom_types.${name}`);
15868
+ const reference = Object.freeze({ kind: "custom", name });
15869
+ Object.defineProperty(this, name, { value: reference, enumerable: true });
15870
+ this.#definitions.set(name, copy);
15871
+ this.#compiled.set(name, { ...reference, inputConstraint: true, test: compiled.test });
15872
+ return reference;
15873
+ }
15874
+ resolve(name, path = "custom_types") {
15875
+ if (!this.#compiled.has(name)) fail(path, `unknown custom type '${name}'`);
15876
+ return { ...this.#compiled.get(name) };
15877
+ }
15878
+ validate(name, value) {
15879
+ if (!this.resolve(name).test(value)) fail(`custom_types.${name}`, "invalid input value");
15880
+ return true;
15881
+ }
15882
+ toJSON() {
15883
+ return structuredClone(Object.fromEntries(this.#definitions));
15884
+ }
15885
+ static fromJSON(catalog) {
15886
+ if (!plainObject(catalog)) fail("custom_types", "must be an object");
15887
+ const registry = new _CustomTypes();
15888
+ for (const [name, definition] of Object.entries(catalog)) registry.#register(name, definition);
15889
+ return registry;
15890
+ }
15891
+ };
15892
+ var PYTHON_KEYWORDS2 = new Set("False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield".split(" "));
15893
+ function validateCustomTypeValues(tag2, spec, value, attrs) {
15894
+ const signature = spec?.attributes;
15895
+ if (!signature) return;
15896
+ for (const p of signature.parameters) {
15897
+ if (!p.annotation?.inputConstraint || p.role === "framework" || ["var_keyword", "var_positional"].includes(p.kind)) continue;
15898
+ const supplied = p.role === "value" ? value : attrs[p.name];
15899
+ if (supplied === void 0) continue;
15900
+ if (!p.annotation.test(supplied)) fail(tag2, `invalid input for '${p.name}' (custom type)`);
15901
+ }
15902
+ }
15825
15903
 
15826
15904
  // node_modules/@genrojs/builders/src/collection.js
15827
15905
  function merge(current, incoming, path = []) {
15828
15906
  if (incoming === null) return structuredClone(current);
15907
+ if (path.length === 2 && path[0] === "custom_types" && current !== void 0) {
15908
+ if (!equalJson(current, incoming)) throw new TypeError(`conflicting custom type '${path[1]}'`);
15909
+ return structuredClone(current);
15910
+ }
15829
15911
  if (path.length === 2 && ["abstracts", "elements"].includes(path[0])) return structuredClone(incoming);
15830
15912
  if (record(current) && record(incoming)) {
15831
15913
  const result = structuredClone(current);
@@ -15841,6 +15923,12 @@ function merge(current, incoming, path = []) {
15841
15923
  }
15842
15924
  return structuredClone(incoming);
15843
15925
  }
15926
+ function equalJson(a, b) {
15927
+ if (Object.is(a, b)) return true;
15928
+ if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => equalJson(x, b[i]));
15929
+ if (record(a) && record(b)) return Object.keys(a).length === Object.keys(b).length && Object.keys(a).every((k) => Object.hasOwn(b, k) && equalJson(a[k], b[k]));
15930
+ return false;
15931
+ }
15844
15932
  function record(value) {
15845
15933
  return value !== null && typeof value === "object" && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
15846
15934
  }
@@ -15862,16 +15950,19 @@ var Collection = class _Collection {
15862
15950
  constructor(document) {
15863
15951
  json(document);
15864
15952
  const keys = ["document_format", "grammar", "abstracts", "elements"];
15865
- if (!record(document) || Object.keys(document).length !== keys.length || keys.some((k) => !Object.hasOwn(document, k))) {
15953
+ if (!record(document) || Object.keys(document).some((k) => ![...keys, "custom_types"].includes(k)) || keys.some((k) => !Object.hasOwn(document, k))) {
15866
15954
  throw new TypeError("collection requires document_format, grammar, abstracts and elements");
15867
15955
  }
15868
15956
  const format = document.document_format;
15869
- if (!record(format) || Object.keys(format).length !== 2 || format.name !== "builder_grammar" || format.version !== "1.1") {
15870
- throw new TypeError("expected builder_grammar version 1.1");
15957
+ if (!record(format) || Object.keys(format).length !== 2 || format.name !== "builder_grammar" || !["1.1", "1.2"].includes(format.version)) {
15958
+ throw new TypeError("expected builder_grammar version 1.1 or 1.2");
15871
15959
  }
15872
15960
  for (const section of ["grammar", "abstracts", "elements"]) {
15873
15961
  if (!record(document[section])) throw new TypeError(`${section} must be an object`);
15874
15962
  }
15963
+ if (Object.hasOwn(document, "custom_types") && (format.version !== "1.2" || !record(document.custom_types))) {
15964
+ throw new TypeError("custom_types requires an object catalog and version 1.2");
15965
+ }
15875
15966
  this.#document = structuredClone(document);
15876
15967
  }
15877
15968
  /** Compose a later document: an element or abstract it names replaces the
@@ -15879,7 +15970,9 @@ var Collection = class _Collection {
15879
15970
  * and a null metadata value preserves the earlier one. */
15880
15971
  update(document) {
15881
15972
  const incoming = new _Collection(document);
15882
- this.#document = merge(this.#document, incoming.#document);
15973
+ const merged = merge(this.#document, incoming.#document);
15974
+ if (this.#document.document_format.version === "1.2" || incoming.#document.document_format.version === "1.2") merged.document_format.version = "1.2";
15975
+ this.#document = merged;
15883
15976
  return this;
15884
15977
  }
15885
15978
  /** Export independent JSON data, not a second representation of the grammar. */
@@ -16530,6 +16623,11 @@ var BuilderBase = class _BuilderBase {
16530
16623
  return this;
16531
16624
  }
16532
16625
  /** Public value check used by renderers after removing framework attrs. */
16626
+ validateCustomTypes(node) {
16627
+ const host = node.parentBag?.parentNode?.builder || node.parentBag?._builder;
16628
+ const owner = host && host !== this && host.schema[node.nodeTag]?._meta?.subbuilder ? host : this;
16629
+ validateCustomTypeValues(node.nodeTag, owner.schema[node.nodeTag], node.value, node.getAttr() || {});
16630
+ }
16533
16631
  validateNodeValues(tag2, value, attrs = {}) {
16534
16632
  const actual = this.schemaTag(tag2);
16535
16633
  if (!actual) throw new Error(`unknown element '${tag2}'`);
@@ -16692,6 +16790,7 @@ var BuilderBase = class _BuilderBase {
16692
16790
  for (const node of bag.getNodes()) {
16693
16791
  const path = prefix ? `${prefix}.${node.label}` : node.label;
16694
16792
  const builder = node.builder;
16793
+ builder.validateCustomTypes(node);
16695
16794
  const info = builder.schema[node.nodeTag];
16696
16795
  if (info && !node._getMeta("data_element,subbuilder,component").some(Boolean)) {
16697
16796
  const children = node.value instanceof SourceBag ? node.value.getNodes().map((n) => n.nodeTag) : [];
@@ -16723,6 +16822,7 @@ var BuilderBase = class _BuilderBase {
16723
16822
  // --- data binding ------------------------------------------------
16724
16823
  /** Resolve the pointers/values a node carries → [runtimeValue, runtimeAttrs]. */
16725
16824
  runtimeValues(node) {
16825
+ node.builder.validateCustomTypes(node);
16726
16826
  const resolved2 = /* @__PURE__ */ new Map();
16727
16827
  const carried = {};
16728
16828
  const isDataElement = node._getMeta("data_element");
@@ -22133,6 +22233,15 @@ var URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src", "formaction", "xlin
22133
22233
  function withoutBindingAttributes(attrs) {
22134
22234
  return Object.fromEntries(Object.entries(attrs).filter(([name]) => !BINDING_ATTRIBUTES.has(name) && !BINDING_ATTRIBUTE_PREFIXES.some((prefix) => name.startsWith(prefix))));
22135
22235
  }
22236
+ function requireStyleClassAttributes(node, attrs, prefixes = []) {
22237
+ for (const [name, value] of Object.entries(attrs)) {
22238
+ const prefix = prefixes.find((candidate) => name.startsWith(candidate)) ?? "";
22239
+ const bare = name.slice(prefix.length);
22240
+ if (["style", "class", "_class"].includes(bare) && value != null && typeof value !== "string") {
22241
+ throw new TypeError(`${node.nodeTag} '${node.label}': '${name}' must be a string or null`);
22242
+ }
22243
+ }
22244
+ }
22136
22245
  function requireNoScriptAttributes(node, attrs, prefixes = []) {
22137
22246
  for (const [name, value] of Object.entries(withoutNullValues(withoutBindingAttributes(attrs)))) {
22138
22247
  const prefix = prefixes.find((candidate) => name.startsWith(candidate));
@@ -22281,6 +22390,7 @@ var GramlotSvgRenderer = class extends SvgRenderer {
22281
22390
  const evaluated = this.owner.evaluateExpressions(node, runtimeAttrs);
22282
22391
  requireNoScriptAttributes(node, evaluated);
22283
22392
  const [tag2, attrs] = super._handleMeta(node, evaluated);
22393
+ requireStyleClassAttributes(node, attrs);
22284
22394
  return node._getMeta("subbuilder") ? [tag2, svgAttributes(boundaryAttributes(attrs))] : [tag2, attrs];
22285
22395
  }
22286
22396
  /** `_meta`, binding attributes and null values out; Builder's `svgAttributes`; Gramlot names. */
@@ -22302,6 +22412,26 @@ var GramlotSvgRenderer = class extends SvgRenderer {
22302
22412
  }
22303
22413
  };
22304
22414
 
22415
+ // src/webcomponent.js
22416
+ var NAME2 = /^[a-z][.0-9_a-z\-\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}]*$/u;
22417
+ var RESERVED = /* @__PURE__ */ new Set([
22418
+ "annotation-xml",
22419
+ "color-profile",
22420
+ "font-face",
22421
+ "font-face-src",
22422
+ "font-face-uri",
22423
+ "font-face-format",
22424
+ "font-face-name",
22425
+ "missing-glyph"
22426
+ ]);
22427
+ function webcomponentCode(attrs) {
22428
+ const code = attrs.code;
22429
+ if (typeof code !== "string" || NAME2.exec(code)?.[0] !== code || !code.includes("-") || RESERVED.has(code)) {
22430
+ throw new TypeError("webcomponent: code must be a literal custom-element name");
22431
+ }
22432
+ return code;
22433
+ }
22434
+
22305
22435
  // src/renderer/gramlot-html-renderer.js
22306
22436
  var GramlotHtmlRenderer = class extends HtmlRenderer {
22307
22437
  // noConvertStyle attributes taken out in _handleMeta, put back after adaptAttrs.
@@ -22335,7 +22465,13 @@ var GramlotHtmlRenderer = class extends HtmlRenderer {
22335
22465
  const prefixes = this.builder.constructor.dialectPrefixes;
22336
22466
  const evaluated = this.evaluateExpressions(node, runtimeAttrs);
22337
22467
  requireNoScriptAttributes(node, evaluated, prefixes);
22338
- const [tag2, attrs] = super._handleMeta(node, withDataSrcdocSandbox(node, evaluated, prefixes));
22468
+ let [tag2, attrs] = super._handleMeta(node, withDataSrcdocSandbox(node, evaluated, prefixes));
22469
+ requireStyleClassAttributes(node, attrs, prefixes);
22470
+ if (node.nodeTag === "webcomponent") {
22471
+ tag2 = webcomponentCode(node.getAttr());
22472
+ const { code, ...rest2 } = attrs;
22473
+ attrs = rest2;
22474
+ }
22339
22475
  if (node._getMeta("subbuilder")) {
22340
22476
  const boundary = boundaryAttributes(attrs);
22341
22477
  if (node._getMeta("subbuilder") === "html") boundary.xmlns = SVG_NS;
@@ -22793,6 +22929,59 @@ var binding_default = {
22793
22929
  }
22794
22930
  };
22795
22931
 
22932
+ // src/builder/webcomponent.json
22933
+ var webcomponent_default = {
22934
+ document_format: {
22935
+ name: "builder_grammar",
22936
+ version: "1.1"
22937
+ },
22938
+ grammar: {
22939
+ name: "webcomponent",
22940
+ version: null,
22941
+ title: "Gramlot webcomponent",
22942
+ description: "An explicitly loaded autonomous custom element."
22943
+ },
22944
+ abstracts: {},
22945
+ elements: {
22946
+ webcomponent: {
22947
+ doc: "Create the custom-element tag named by literal code.",
22948
+ sub_tags: "*",
22949
+ parent_tags: null,
22950
+ inherits_from: null,
22951
+ ns: null,
22952
+ attributes: {
22953
+ parameters: [
22954
+ {
22955
+ name: "code",
22956
+ kind: "keyword_only",
22957
+ role: "attribute",
22958
+ annotation: {
22959
+ kind: "type",
22960
+ module: "builtins",
22961
+ name: "str"
22962
+ },
22963
+ has_default: false
22964
+ },
22965
+ {
22966
+ name: "attr",
22967
+ kind: "var_keyword",
22968
+ role: "attribute",
22969
+ annotation: {
22970
+ kind: "any"
22971
+ },
22972
+ has_default: false
22973
+ }
22974
+ ],
22975
+ accepts_var_keyword: true,
22976
+ accepts_var_positional: false
22977
+ },
22978
+ node_label: null,
22979
+ collection_key: null,
22980
+ _meta: null
22981
+ }
22982
+ }
22983
+ };
22984
+
22796
22985
  // src/builder/gramlot-builder.js
22797
22986
  var DATA_FORBIDDEN = "data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element";
22798
22987
  var EXCLUDED_ELEMENTS = /* @__PURE__ */ new Set();
@@ -22828,6 +23017,9 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
22828
23017
  static {
22829
23018
  this.defineGrammar(binding_default);
22830
23019
  }
23020
+ static {
23021
+ this.defineGrammar(webcomponent_default);
23022
+ }
22831
23023
  /** Tag prefixes of the parent dialects, from the `_name` of the classes above GramlotBuilder. */
22832
23024
  static get dialectPrefixes() {
22833
23025
  const prefixes = [];
@@ -22898,6 +23090,7 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
22898
23090
  }
22899
23091
  /** Builder's value check, plus the excluded attributes (authoring names the tag). */
22900
23092
  validateNodeValues(tag2, value, attrs = {}) {
23093
+ if (tag2 === "webcomponent") webcomponentCode(attrs);
22901
23094
  const excluded = excludedAttribute(attrs);
22902
23095
  if (excluded) throw new Error(`${tag2}: attribute '${excluded}' is excluded from Gramlot 0.2.0`);
22903
23096
  const error = dataElementError(tag2, attrs);
@@ -22906,12 +23099,17 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
22906
23099
  }
22907
23100
  /** Builder's node check, plus the excluded attributes (a Source node names tag and label). */
22908
23101
  validateNode(node, options = {}) {
23102
+ if (node.nodeTag === "webcomponent") webcomponentCode(options.attrs ?? node.getAttr());
22909
23103
  const excluded = excludedAttribute(options.attrs ?? node.getAttr());
22910
23104
  if (excluded) throw new Error(`${node.nodeTag} '${node.label}': attribute '${excluded}' is excluded from Gramlot 0.2.0`);
22911
23105
  const error = dataElementError(node.nodeTag, options.attrs ?? node.getAttr());
22912
23106
  if (error) throw new Error(`${node.nodeTag} '${node.label}': ${error}`);
22913
23107
  return super.validateNode(node, options);
22914
23108
  }
23109
+ /** Custom elements are outside the native HTML child catalogue, as components are. */
23110
+ _countsForGrammar(info) {
23111
+ return info !== this.schema.webcomponent && super._countsForGrammar(info);
23112
+ }
22915
23113
  /** Builder's child insertion; a plain object `value` of `dataSetter` becomes `new Bag(value)` (P25). */
22916
23114
  setChild(bag, tag2, value, attrs, parentOverride = null) {
22917
23115
  const plain = tag2 === "dataSetter" && attrs?.value !== null && typeof attrs?.value === "object" && Object.getPrototypeOf(attrs.value) === Object.prototype;
@@ -22952,7 +23150,10 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
22952
23150
  }
22953
23151
  let id = node.getAttr("__ref");
22954
23152
  if (id === null || id === void 0) {
22955
- id = crypto.randomUUID().replaceAll("-", "");
23153
+ id = Array.from(
23154
+ crypto.getRandomValues(new Uint8Array(16)),
23155
+ (byte) => byte.toString(16).padStart(2, "0")
23156
+ ).join("");
22956
23157
  node.setAttr({ __ref: id });
22957
23158
  }
22958
23159
  return { $gramlotRef: id, kind };
@@ -23430,7 +23631,7 @@ var HtmlElement = class {
23430
23631
  const builder = node.builder;
23431
23632
  const declaration3 = builder.schema[builder.schemaTag(node.nodeTag)];
23432
23633
  const meta = { ...declaration3._meta, ...node.getAttr("_meta") };
23433
- const tag2 = resolveRenderTag(node.nodeTag, {
23634
+ const tag2 = node.nodeTag === "webcomponent" ? webcomponentCode(node.getAttr()) : resolveRenderTag(node.nodeTag, {
23434
23635
  renderTag: meta.render_tag,
23435
23636
  ns: node.getAttr("ns"),
23436
23637
  dialectName: builder.constructor._name
@@ -24527,7 +24728,7 @@ var MACROS = [
24527
24728
  [/;FIRE/g, /(\W|^)FIRE (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)(;?)/g, "$1this.FIRE('$2')$3 "]
24528
24729
  ];
24529
24730
  var PUBLISH = /(\W|^)PUBLISH (?:\s*)(\^?[\w.#@$?-]+)/;
24530
- var RESERVED = /* @__PURE__ */ new Set([
24731
+ var RESERVED2 = /* @__PURE__ */ new Set([
24531
24732
  "arguments",
24532
24733
  "await",
24533
24734
  "break",
@@ -24688,7 +24889,7 @@ var InlineCompiler = class {
24688
24889
  }
24689
24890
  };
24690
24891
  function isIdentifier(name) {
24691
- return /^[A-Za-z_$][\w$]*$/.test(name) && !RESERVED.has(name);
24892
+ return /^[A-Za-z_$][\w$]*$/.test(name) && !RESERVED2.has(name);
24692
24893
  }
24693
24894
  function declaration2(node, attr) {
24694
24895
  return `${node.nodeTag} '${node.label}' ${attr ? `'${attr}'` : "node value"}`;
@@ -24711,7 +24912,8 @@ ${text}`, { cause: error });
24711
24912
  // src/binding/remote.js
24712
24913
  var RemoteBinding = class {
24713
24914
  #binding;
24714
- // The parameters of the last call, compared by `_cachedRemote`.
24915
+ // The name and TYTX parameters of the last mounted call, captured before sending it.
24916
+ #lastName = null;
24715
24917
  #lastParams = null;
24716
24918
  constructor(binding) {
24717
24919
  this.#binding = binding;
@@ -24728,8 +24930,9 @@ var RemoteBinding = class {
24728
24930
  /**
24729
24931
  * Request the fragment for the current parameters. Nothing happens before the node's `start` step,
24730
24932
  * on a closed node, without a name, or when `_if` or `_cachedRemote` stop the call; a false `_if`
24731
- * also cancels the request in flight, so its fragment is not mounted after `_else`. A failure of the
24732
- * request rejects with an error naming the node, its cause attached.
24933
+ * also cancels the request in flight, so its fragment is not mounted after `_else`. A cache hit
24934
+ * cancels a pending request too, keeping the mounted fragment. A failure of the request rejects
24935
+ * with an error naming the node, its cause attached.
24733
24936
  */
24734
24937
  async update() {
24735
24938
  if (this.closed || !this.binding.hasStamp("start")) return;
@@ -24748,14 +24951,22 @@ var RemoteBinding = class {
24748
24951
  if (otherwise) this.#inline("_else", otherwise, otherwise, params);
24749
24952
  return;
24750
24953
  }
24751
- if (attrs._cachedRemote && this.#lastParams && sameValue(params, this.#lastParams)) return;
24752
24954
  let mounted;
24955
+ let text;
24753
24956
  try {
24957
+ text = toTytx(params);
24958
+ if (attrs._cachedRemote && name === this.#lastName && text === this.#lastParams) {
24959
+ this.binding.runtime.gramlot.rpc.remoteRequests.get(node)?.controller.abort();
24960
+ return;
24961
+ }
24754
24962
  mounted = await this.binding.runtime.gramlot.src.remoteSource(node, name, params);
24755
24963
  } catch (error) {
24756
24964
  throw new Error(`${node.nodeTag} '${node.label}': remote '${name}' failed: ${error.message}`, { cause: error });
24757
24965
  }
24758
- if (mounted) this.#lastParams = params;
24966
+ if (mounted) {
24967
+ this.#lastName = name;
24968
+ this.#lastParams = text;
24969
+ }
24759
24970
  const onRemote = node.getAttr("_onRemote");
24760
24971
  if (mounted && onRemote) this.#inline("_onRemote", onRemote, onRemote, params);
24761
24972
  }
@@ -24763,17 +24974,6 @@ var RemoteBinding = class {
24763
24974
  return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, Object.keys(params), source)(params);
24764
24975
  }
24765
24976
  };
24766
- function sameValue(a, b) {
24767
- if (Object.is(a, b)) return true;
24768
- if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
24769
- if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((item, i) => sameValue(item, b[i]));
24770
- if (!isPlain(a) || !isPlain(b)) return false;
24771
- const keys = Object.keys(a);
24772
- return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && sameValue(a[key], b[key]));
24773
- }
24774
- function isPlain(value) {
24775
- return value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype;
24776
- }
24777
24977
 
24778
24978
  // src/binding/runtime.js
24779
24979
  var PROVIDERS = {
@@ -24790,7 +24990,10 @@ var BindingRuntime = class {
24790
24990
  #router;
24791
24991
  #installer;
24792
24992
  #inlineCompiler;
24793
- #subscription = `gramlot-data-${crypto.randomUUID()}`;
24993
+ #subscription = `gramlot-data-${Array.from(
24994
+ crypto.getRandomValues(new Uint8Array(16)),
24995
+ (byte) => byte.toString(16).padStart(2, "0")
24996
+ ).join("")}`;
24794
24997
  #disposed = false;
24795
24998
  constructor(gramlot) {
24796
24999
  this.#gramlot = gramlot;
@@ -25263,7 +25466,10 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
25263
25466
  this.building = false;
25264
25467
  this.disposed = false;
25265
25468
  this.elements = /* @__PURE__ */ new WeakMap();
25266
- this.instanceId = crypto.randomUUID();
25469
+ this.instanceId = Array.from(
25470
+ crypto.getRandomValues(new Uint8Array(16)),
25471
+ (byte) => byte.toString(16).padStart(2, "0")
25472
+ ).join("");
25267
25473
  this.radioGroups = new RadioGroups(this);
25268
25474
  this.subscription = `html-source-renderer-${this.instanceId}`;
25269
25475
  source.subscribe(this.subscription, { any: (event) => this.receive(event) });
@@ -26275,7 +26481,8 @@ var InOut = class {
26275
26481
  return new Promise((resolve, reject) => {
26276
26482
  input.addEventListener("change", async () => {
26277
26483
  try {
26278
- const bag = Bag.fromTytx(await input.files[0].text());
26484
+ const bag = fromTytx(await input.files[0].text());
26485
+ if (!(bag instanceof Bag)) throw new TypeError("the file must contain a typed Bag");
26279
26486
  this.gramlot.data.setItem(path, bag);
26280
26487
  resolve(bag);
26281
26488
  } catch (error) {
@@ -26462,7 +26669,7 @@ var PageBootstrap = class {
26462
26669
  }
26463
26670
  };
26464
26671
 
26465
- // src/server/page.js
26672
+ // src/server/page-base.js
26466
26673
  var SOURCE_METHOD = /* @__PURE__ */ Symbol("gramlot.source");
26467
26674
  var ENDPOINT_METHOD = /* @__PURE__ */ Symbol("gramlot.endpoint");
26468
26675
  var MARKERS = /* @__PURE__ */ new Map([[SOURCE_METHOD, "registerSource"], [ENDPOINT_METHOD, "registerEndpoint"]]);
@@ -26483,6 +26690,22 @@ function declare(PageClass, methodName, marker, auth) {
26483
26690
  }
26484
26691
  var Page = class {
26485
26692
  static title = "Gramlot";
26693
+ static installable = false;
26694
+ static appIcon = null;
26695
+ /** Default root manifest. appIcon is a 512px square PNG below the app root. */
26696
+ manifest({ baseUrl = "./" } = {}) {
26697
+ const { title, appIcon } = this.constructor;
26698
+ if (typeof appIcon !== "string" || !appIcon) throw new TypeError("An installable Page needs appIcon");
26699
+ return {
26700
+ id: baseUrl,
26701
+ name: title,
26702
+ short_name: title,
26703
+ start_url: baseUrl,
26704
+ scope: baseUrl,
26705
+ display: "standalone",
26706
+ icons: [{ src: baseUrl + appIcon.replace(/^\/+/, ""), sizes: "512x512", type: "image/png" }]
26707
+ };
26708
+ }
26486
26709
  static css = [];
26487
26710
  static css_requires = "";
26488
26711
  static js_requires = "";
@@ -26494,8 +26717,8 @@ var Page = class {
26494
26717
  * Mark the own method `methodName` of this page class as a remote Source method,
26495
26718
  * equivalent to Python `@source`; call it after the class.
26496
26719
  *
26497
- * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035); the
26498
- * declarative `remote` grammar attribute is not yet available.
26720
+ * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035);
26721
+ * the `remote` attribute requests it declaratively (GC-095 §105).
26499
26722
  */
26500
26723
  static registerSource(methodName, { auth = null } = {}) {
26501
26724
  declare(this, methodName, SOURCE_METHOD, auth);
@@ -26506,6 +26729,444 @@ var Page = class {
26506
26729
  declare(this, methodName, ENDPOINT_METHOD, auth);
26507
26730
  }
26508
26731
  };
26732
+
26733
+ // src/server/index-page.js
26734
+ var IndexPage = class extends Page {
26735
+ static title = "Application";
26736
+ static logoUrl = "";
26737
+ static shellId = "index";
26738
+ static navigation = [];
26739
+ static css = ["/themes/gramlot-base/theme.css", "/themes/gramlot-index/theme.css"];
26740
+ main(root) {
26741
+ const families = this.constructor.navigation;
26742
+ const shell = root.div({ class: "index-shell", id: this.constructor.shellId });
26743
+ const sidebar = shell.aside({ class: "index-sidebar", id: "index-sidebar" });
26744
+ const brand = sidebar.header();
26745
+ if (this.constructor.logoUrl) brand.img({ src: this.constructor.logoUrl, alt: this.constructor.title, class: "index-logo" });
26746
+ brand.h1(this.constructor.title);
26747
+ const navigation = sidebar.nav({ "aria-label": "Pages" }).ul({ class: "index-list" });
26748
+ for (const family of families) {
26749
+ const category = navigation.li().details({ open: family === families[0] });
26750
+ category.summary({ tabindex: -1 }).a(family.title, {
26751
+ id: `open-${family.key}`,
26752
+ href: `#panel-${family.key}`,
26753
+ class: "index-family",
26754
+ aria_current: null,
26755
+ tabindex: -1
26756
+ });
26757
+ const examplesList = category.ul({ class: "index-list" });
26758
+ for (const example of family.children) {
26759
+ examplesList.li().a(example.title, {
26760
+ id: `open-${example.key}`,
26761
+ href: example.url,
26762
+ aria_current: null,
26763
+ tabindex: -1
26764
+ });
26765
+ }
26766
+ }
26767
+ shell.div({
26768
+ class: "index-divider",
26769
+ id: "index-sidebar-divider",
26770
+ role: "separator",
26771
+ aria_orientation: "vertical",
26772
+ tabindex: 0,
26773
+ aria_label: "Resize sidebar",
26774
+ aria_controls: "index-sidebar",
26775
+ aria_valuemin: 120,
26776
+ aria_valuemax: 460,
26777
+ aria_valuenow: 240
26778
+ });
26779
+ const content = shell.main({ class: "index-main" });
26780
+ const tabs = content.div({ class: "index-tabs", role: "tablist", aria_label: "Open pages" });
26781
+ tabs.button("Introduction", {
26782
+ type: "button",
26783
+ role: "tab",
26784
+ id: "tab-intro",
26785
+ aria_controls: "panel-intro",
26786
+ aria_selected: "true",
26787
+ tabindex: -1,
26788
+ hidden: false
26789
+ });
26790
+ for (const family of families) {
26791
+ for (const { key, title } of [family, ...family.children]) {
26792
+ tabs.button(title, {
26793
+ type: "button",
26794
+ role: "tab",
26795
+ id: `tab-${key}`,
26796
+ aria_controls: `panel-${key}`,
26797
+ aria_selected: "false",
26798
+ tabindex: -1,
26799
+ hidden: true
26800
+ });
26801
+ }
26802
+ }
26803
+ const panels = content.div({ class: "index-panels" });
26804
+ const intro = panels.section({
26805
+ id: "panel-intro",
26806
+ class: "index-intro",
26807
+ role: "tabpanel",
26808
+ aria_labelledby: "tab-intro",
26809
+ hidden: false
26810
+ });
26811
+ this.introduction(intro);
26812
+ for (const family of families) {
26813
+ const categoryPanel = panels.section({
26814
+ id: `panel-${family.key}`,
26815
+ class: "index-category",
26816
+ role: "tabpanel",
26817
+ aria_labelledby: `tab-${family.key}`,
26818
+ hidden: true
26819
+ });
26820
+ this.groupPanel(categoryPanel, family);
26821
+ for (const example of family.children) this.panel(panels, example);
26822
+ }
26823
+ const footer = shell.footer({ class: "index-footer" });
26824
+ this.footer(footer);
26825
+ this.behavior(shell);
26826
+ }
26827
+ behavior(shell) {
26828
+ shell.dataController({ func: "indexMount", _onStart: true, shell_id: this.constructor.shellId });
26829
+ }
26830
+ introduction(pane) {
26831
+ pane.h2(this.constructor.title);
26832
+ pane.p("Choose a page from the navigation. Open pages remain available in tabs.");
26833
+ }
26834
+ groupPanel(pane, group) {
26835
+ pane.h2(group.title);
26836
+ }
26837
+ footer(footer) {
26838
+ const theme = footer.div({ class: "index-theme" });
26839
+ theme.html_label("Theme", { for: "index-appearance" });
26840
+ const appearance = theme.select({ id: "index-appearance", value: "compact" });
26841
+ appearance.option("Base", { value: "base", selected: false });
26842
+ appearance.option("Compact", { value: "compact", selected: true });
26843
+ const color = footer.div({ class: "index-theme" });
26844
+ color.html_label("Color mode", { for: "index-theme" });
26845
+ const choices = color.select({ id: "index-theme", value: "light" });
26846
+ choices.option("Light", { value: "light", selected: true });
26847
+ choices.option("Dark", { value: "dark", selected: false });
26848
+ const keyboard = footer.div({ class: "index-keyboard" });
26849
+ const label = keyboard.html_label({ for: "keyboard-navigation" });
26850
+ label.input({ type: "checkbox", id: "keyboard-navigation", checked: false });
26851
+ label.span("Keyboard navigation");
26852
+ if (this.constructor.installable) {
26853
+ const app = footer.details({ class: "index-install" });
26854
+ app.summary("Install app");
26855
+ app.button("Install", { type: "button", id: "index-install-button", hidden: true });
26856
+ app.p("", { id: "index-install-status", role: "status" });
26857
+ app.p("Chrome: use Install page as app in the browser menu. Safari on macOS Sonoma or later: File > Add to Dock.");
26858
+ app.p("Use HTTPS or localhost. For a static export, serve the directory; direct file opening is not installable. Keep the server running for hosted pages.");
26859
+ }
26860
+ }
26861
+ panel(parent, item) {
26862
+ const pane = parent.section({
26863
+ id: `panel-${item.key}`,
26864
+ class: "index-panel",
26865
+ role: "tabpanel",
26866
+ aria_labelledby: `tab-${item.key}`,
26867
+ hidden: true
26868
+ });
26869
+ pane.iframe({ id: `frame-${item.key}`, title: item.title, name: `page-${item.key}` });
26870
+ }
26871
+ };
26872
+
26873
+ // src/index-page-styles.js
26874
+ var compactStyle = '/* Gramlot Compact: load after gramlot-base/theme.css. Colors and behavior stay in Base. */\n@layer gramlot.tokens {\n :root {\n --gramlot-space-1: .2rem;\n --gramlot-space-2: .4rem;\n --gramlot-space-3: .5rem;\n --gramlot-space-4: .6rem;\n --gramlot-space-6: .9rem;\n --gramlot-space-8: 1.2rem;\n --gramlot-space-12: 1.8rem;\n --gramlot-radius-sm: .25rem;\n --gramlot-radius: .35rem;\n --gramlot-radius-lg: .4rem;\n }\n}\n\n@layer gramlot.base {\n html { font-size: 13px; }\n body { line-height: 1.35; }\n :where(h1, h2, h3, h4, h5, h6, p, ul, ol, dl, blockquote, pre, figure) { margin-block: 0 .5rem; }\n h1 { font-size: 1.35rem; }\n h2 { font-size: 1.15rem; }\n h3 { font-size: 1.05rem; }\n pre { padding: .5rem; }\n blockquote { padding-inline-start: .6rem; }\n hr { margin-block: 1rem; }\n}\n\n@layer gramlot.components {\n :where(button, input[type="button"], input[type="submit"], input[type="reset"], .button) {\n min-block-size: 28px;\n padding: .25rem .5rem;\n font-size: 1rem;\n line-height: 1.35;\n }\n :where(label) { font-size: .95rem; }\n :where(input:not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="checkbox"]):not([type="radio"]):not([type="range"]):not([type="color"]):not([type="file"]):not([type="hidden"]), select, textarea) {\n min-block-size: 28px;\n padding: .25rem .5rem;\n font-size: 1rem;\n line-height: 1.35;\n }\n :where(textarea) { min-block-size: 5rem; }\n :where(input[type="color"]) { min-block-size: 28px; }\n :where(input[type="file"])::file-selector-button { margin-inline-end: .5rem; padding: .25rem .5rem; }\n :where(fieldset) { margin-block-end: .6rem; padding: .5rem; }\n :where(table) { font-size: 1rem; }\n :where(th, td) { padding: .4rem .5rem; }\n :where(details) { padding: .4rem .5rem; }\n :where(details[open] > summary) { margin-block-end: .5rem; }\n :where(dialog) { padding: .75rem; }\n}\n\n@layer gramlot.utilities {\n .example-page { inline-size: min(100% - 1.2rem, var(--gramlot-page-width)); padding-block: .6rem; }\n .card { padding: .6rem; box-shadow: none; }\n}\n';
26875
+
26876
+ // src/index-theme.js
26877
+ var THEME_READY = "index:theme-ready";
26878
+ var THEME_SET = "index:theme-set";
26879
+ var THEMES = /* @__PURE__ */ new Set(["light", "dark"]);
26880
+ var APPEARANCES = /* @__PURE__ */ new Set(["base", "compact"]);
26881
+
26882
+ // src/index-page-runtime.js
26883
+ function mountIndexPage(renderer, root, onSelection = () => {
26884
+ }, prepareEntry = () => {
26885
+ }) {
26886
+ const shell = renderer.records.get(root).element;
26887
+ const document = shell.ownerDocument;
26888
+ const window2 = document.defaultView;
26889
+ const byId = (id) => document.getElementById(id);
26890
+ const node = (element) => renderer.elements.get(element).node;
26891
+ const set = (element, attrs) => node(element).setAttr(attrs);
26892
+ const keyboard = byId("keyboard-navigation");
26893
+ const theme = byId("index-theme");
26894
+ const appearance = byId("index-appearance");
26895
+ const sidebar = byId("index-sidebar");
26896
+ const sidebarHandle = byId("index-sidebar-divider");
26897
+ const preferencesKey = `gramlot.${shell.id}.preferences:${window2.location.pathname}`;
26898
+ let preferences = {};
26899
+ try {
26900
+ const saved = JSON.parse(window2.localStorage.getItem(preferencesKey));
26901
+ if (saved !== null && typeof saved === "object" && !Array.isArray(saved)) preferences = saved;
26902
+ } catch (error) {
26903
+ if (error.name !== "SyntaxError" && error.name !== "SecurityError") throw error;
26904
+ }
26905
+ const restoreChoice = (control, value, allowed) => {
26906
+ if (!control || !allowed.has(value)) return;
26907
+ set(control, { value });
26908
+ for (const option of control.options) set(option, { selected: option.value === value });
26909
+ };
26910
+ restoreChoice(theme, preferences.theme, THEMES);
26911
+ restoreChoice(appearance, preferences.appearance, APPEARANCES);
26912
+ const families = [...shell.querySelectorAll(".index-sidebar details")];
26913
+ const Bag2 = root.builder.data.constructor;
26914
+ const state = new Bag2();
26915
+ const opened = new Bag2();
26916
+ state.setItem("opened", opened);
26917
+ state.setItem("keyboard", keyboard?.checked ?? false);
26918
+ state.setItem("theme", theme?.value ?? "light");
26919
+ state.setItem("appearance", appearance?.value ?? "compact");
26920
+ const savePreferences = () => {
26921
+ try {
26922
+ window2.localStorage.setItem(preferencesKey, JSON.stringify({
26923
+ theme: state.getItem("theme"),
26924
+ appearance: state.getItem("appearance"),
26925
+ sidebarWidth: state.getItem("preferredSidebarWidth")
26926
+ }));
26927
+ } catch (error) {
26928
+ if (error.name !== "SecurityError" && error.name !== "QuotaExceededError") throw error;
26929
+ }
26930
+ };
26931
+ const entries = /* @__PURE__ */ new Map();
26932
+ const releases = [];
26933
+ const style = root.builder.wrapSource(root.value).style(compactStyle, { media: (appearance?.value ?? "compact") === "compact" ? "all" : "not all" });
26934
+ let drag = null;
26935
+ let disposed = false;
26936
+ let installPrompt = null;
26937
+ const previousTheme = document.documentElement.getAttribute("data-theme");
26938
+ const listen = (element, type, handler) => {
26939
+ if (!element) return;
26940
+ element.addEventListener(type, handler);
26941
+ releases.push(() => element.removeEventListener(type, handler));
26942
+ };
26943
+ const stopDrag = () => {
26944
+ if (!drag) return;
26945
+ const { handle, pointerId } = drag;
26946
+ drag = null;
26947
+ if (!disposed) set(shell, { data_resizing: null });
26948
+ if (handle.hasPointerCapture(pointerId)) handle.releasePointerCapture(pointerId);
26949
+ };
26950
+ const dispose = () => {
26951
+ if (disposed) return;
26952
+ disposed = true;
26953
+ installPrompt = null;
26954
+ stopDrag();
26955
+ for (const release of releases.reverse()) release();
26956
+ if (style.parentBag) style.parentBag.popNode(style.label);
26957
+ if (previousTheme == null) document.documentElement.removeAttribute("data-theme");
26958
+ else document.documentElement.setAttribute("data-theme", previousTheme);
26959
+ };
26960
+ const send = (frame) => frame.contentWindow.postMessage({ type: THEME_SET, theme: state.getItem("theme"), appearance: state.getItem("appearance") }, "*");
26961
+ const applyTheme = () => {
26962
+ document.documentElement.setAttribute("data-theme", state.getItem("theme"));
26963
+ style.setAttr({ media: state.getItem("appearance") === "compact" ? "all" : "not all" });
26964
+ for (const { frame } of entries.values()) if (frame) send(frame);
26965
+ };
26966
+ const updateInspector = () => onSelection(entries, state.getItem("active"));
26967
+ function select(key) {
26968
+ const entry = entries.get(key);
26969
+ if (!opened.getItem(key)) {
26970
+ opened.setItem(key, true);
26971
+ set(entry.tab, { hidden: false });
26972
+ if (entry.frame) set(entry.frame, { src: entry.open.getAttribute("href") });
26973
+ }
26974
+ if (entry.family) set(entry.family, { open: true });
26975
+ for (const [current, item] of entries) {
26976
+ const active = current === key;
26977
+ set(item.tab, { aria_selected: String(active), tabindex: active && state.getItem("keyboard") ? 0 : -1 });
26978
+ set(item.panel, { hidden: !active });
26979
+ if (item.open) set(item.open, { aria_current: active ? "page" : null });
26980
+ }
26981
+ state.setItem("active", key);
26982
+ updateInspector();
26983
+ }
26984
+ function setRatio(entry, value) {
26985
+ const ratio = Math.max(20, Math.min(80, value));
26986
+ state.setItem(`ratio.${entry.key}`, ratio);
26987
+ set(entry.split, { style: `--split-position: ${ratio}%` });
26988
+ set(entry.handle, { aria_valuenow: ratio });
26989
+ }
26990
+ const sidebarMaximum = () => Math.max(120, Math.min(460, Math.floor(window2.innerWidth * 0.6)));
26991
+ const setSidebarWidth = (value, remember = false) => {
26992
+ const maximum = sidebarMaximum();
26993
+ const width = Math.max(120, Math.min(maximum, value));
26994
+ state.setItem("sidebarWidth", width);
26995
+ set(shell, { style: `--sidebar-width: ${width}px` });
26996
+ set(sidebarHandle, { aria_valuenow: width, aria_valuemax: maximum });
26997
+ if (remember) {
26998
+ state.setItem("preferredSidebarWidth", width);
26999
+ savePreferences();
27000
+ }
27001
+ };
27002
+ const beginDrag = (handle, event, move) => {
27003
+ if (event.button !== 0) return;
27004
+ stopDrag();
27005
+ handle.setPointerCapture(event.pointerId);
27006
+ drag = { handle, pointerId: event.pointerId, move };
27007
+ set(shell, { data_resizing: "true" });
27008
+ event.preventDefault();
27009
+ };
27010
+ try {
27011
+ const install = byId("index-install-button");
27012
+ if (install) {
27013
+ listen(window2, "beforeinstallprompt", (event) => {
27014
+ event.preventDefault();
27015
+ installPrompt = event;
27016
+ set(install, { hidden: false, disabled: false });
27017
+ });
27018
+ listen(window2, "appinstalled", () => {
27019
+ installPrompt = null;
27020
+ set(install, { hidden: true });
27021
+ node(byId("index-install-status")).setValue("App installed.");
27022
+ });
27023
+ listen(install, "click", async () => {
27024
+ if (!installPrompt) return;
27025
+ const prompt = installPrompt;
27026
+ installPrompt = null;
27027
+ set(install, { disabled: true });
27028
+ try {
27029
+ await prompt.prompt();
27030
+ const { outcome } = await prompt.userChoice;
27031
+ if (!disposed) node(byId("index-install-status")).setValue(
27032
+ outcome === "accepted" ? "Installation accepted." : "Installation cancelled. You can also use the browser menu."
27033
+ );
27034
+ } catch (error) {
27035
+ if (!disposed) node(byId("index-install-status")).setValue(`Installation failed: ${error.message}`);
27036
+ } finally {
27037
+ if (!disposed) set(install, { hidden: true });
27038
+ }
27039
+ });
27040
+ }
27041
+ set(shell, { data_resizing: null });
27042
+ const savedWidth = preferences.sidebarWidth;
27043
+ const width = typeof savedWidth === "number" && Number.isFinite(savedWidth) && savedWidth >= 120 && savedWidth <= 460 ? savedWidth : sidebar.getBoundingClientRect().width || Number(sidebarHandle.getAttribute("aria-valuenow"));
27044
+ state.setItem("preferredSidebarWidth", width);
27045
+ setSidebarWidth(width);
27046
+ listen(sidebarHandle, "keydown", (event) => {
27047
+ const current = state.getItem("sidebarWidth");
27048
+ const value = event.key === "ArrowLeft" ? current - 10 : event.key === "ArrowRight" ? current + 10 : event.key === "Home" ? 120 : event.key === "End" ? sidebarMaximum() : null;
27049
+ if (value == null) return;
27050
+ event.preventDefault();
27051
+ setSidebarWidth(value, true);
27052
+ });
27053
+ listen(sidebarHandle, "pointerdown", (event) => beginDrag(
27054
+ sidebarHandle,
27055
+ event,
27056
+ (x) => setSidebarWidth(Math.round(x - shell.getBoundingClientRect().left), true)
27057
+ ));
27058
+ listen(sidebarHandle, "lostpointercapture", () => {
27059
+ if (drag?.handle === sidebarHandle) stopDrag();
27060
+ });
27061
+ listen(window2, "resize", () => setSidebarWidth(state.getItem("preferredSidebarWidth")));
27062
+ for (const tab of shell.querySelectorAll(".index-tabs button")) {
27063
+ const key = tab.id.slice("tab-".length);
27064
+ const entry = {
27065
+ key,
27066
+ tab,
27067
+ panel: byId(`panel-${key}`),
27068
+ open: key === "intro" ? null : byId(`open-${key}`)
27069
+ };
27070
+ entries.set(key, entry);
27071
+ if (!tab.hidden) opened.setItem(key, true);
27072
+ if (tab.getAttribute("aria-selected") === "true") state.setItem("active", key);
27073
+ listen(tab, "click", () => select(key));
27074
+ if (entry.open) listen(entry.open, "click", (event) => {
27075
+ event.preventDefault();
27076
+ select(key);
27077
+ });
27078
+ listen(tab, "keydown", (event) => {
27079
+ if (!state.getItem("keyboard") || !["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
27080
+ const keys = [...entries.keys()].filter((key2) => opened.getItem(key2));
27081
+ const index = keys.indexOf(key);
27082
+ const next = event.key === "Home" ? 0 : event.key === "End" ? keys.length - 1 : (index + (event.key === "ArrowRight" ? 1 : -1) + keys.length) % keys.length;
27083
+ event.preventDefault();
27084
+ select(keys[next]);
27085
+ entries.get(keys[next]).tab.focus();
27086
+ });
27087
+ if (key === "intro") continue;
27088
+ entry.family = entry.open.closest("details");
27089
+ prepareEntry(entry, { byId, node, set, listen });
27090
+ if (entry.panel.classList.contains("index-category")) continue;
27091
+ entry.frame = byId(`frame-${key}`);
27092
+ entry.split = byId(`split-${key}`);
27093
+ entry.handle = byId(`divider-${key}`);
27094
+ if (entry.handle) state.setItem(`ratio.${key}`, Number(entry.handle.getAttribute("aria-valuenow")));
27095
+ listen(entry.frame, "load", () => send(entry.frame));
27096
+ if (!entry.handle) continue;
27097
+ listen(entry.handle, "keydown", (event) => {
27098
+ const current = state.getItem(`ratio.${key}`);
27099
+ const value = event.key === "ArrowLeft" ? current - 5 : event.key === "ArrowRight" ? current + 5 : event.key === "Home" ? 20 : event.key === "End" ? 80 : null;
27100
+ if (value == null) return;
27101
+ event.preventDefault();
27102
+ setRatio(entry, value);
27103
+ });
27104
+ listen(entry.handle, "pointerdown", (event) => beginDrag(entry.handle, event, (x) => {
27105
+ const bounds = entry.split.getBoundingClientRect();
27106
+ if (bounds.width > 0) setRatio(entry, Math.round((x - bounds.left) * 100 / bounds.width));
27107
+ }));
27108
+ listen(entry.handle, "lostpointercapture", () => {
27109
+ if (drag?.handle === entry.handle) stopDrag();
27110
+ });
27111
+ }
27112
+ listen(document, "pointermove", (event) => {
27113
+ if (!drag || event.pointerId !== drag.pointerId) return;
27114
+ drag.move(event.clientX);
27115
+ });
27116
+ for (const type of ["pointerup", "pointercancel"]) listen(document, type, (event) => {
27117
+ if (drag && event.pointerId === drag.pointerId) stopDrag();
27118
+ });
27119
+ for (const family of families) listen(family, "toggle", () => set(family, { open: family.open }));
27120
+ listen(keyboard, "change", () => {
27121
+ state.setItem("keyboard", keyboard?.checked ?? false);
27122
+ set(keyboard, { checked: keyboard?.checked ?? false });
27123
+ for (const [key, entry] of entries) {
27124
+ if (entry.open) set(entry.open, { tabindex: keyboard?.checked ?? false ? 0 : -1 });
27125
+ set(entry.tab, { tabindex: (keyboard?.checked ?? false) && key === state.getItem("active") ? 0 : -1 });
27126
+ }
27127
+ });
27128
+ listen(appearance, "change", () => {
27129
+ if (!APPEARANCES.has(appearance?.value ?? "compact")) throw new Error("Index appearance must be base or compact");
27130
+ state.setItem("appearance", appearance?.value ?? "compact");
27131
+ set(appearance, { value: appearance?.value ?? "compact" });
27132
+ for (const option of appearance.options) set(option, { selected: option.value === (appearance?.value ?? "compact") });
27133
+ applyTheme();
27134
+ savePreferences();
27135
+ });
27136
+ listen(theme, "change", () => {
27137
+ if (!THEMES.has(theme?.value ?? "light")) throw new Error("Index theme must be light or dark");
27138
+ state.setItem("theme", theme?.value ?? "light");
27139
+ set(theme, { value: theme?.value ?? "light" });
27140
+ for (const option of theme.options) set(option, { selected: option.value === (theme?.value ?? "light") });
27141
+ applyTheme();
27142
+ savePreferences();
27143
+ });
27144
+ listen(window2, "message", (event) => {
27145
+ if (event.data?.type !== THEME_READY) return;
27146
+ for (const { frame } of entries.values()) {
27147
+ if (frame && frame.contentWindow === event.source) {
27148
+ send(frame);
27149
+ updateInspector();
27150
+ break;
27151
+ }
27152
+ }
27153
+ });
27154
+ applyTheme();
27155
+ updateInspector();
27156
+ renderer.onDispose(root, dispose);
27157
+ } catch (error) {
27158
+ dispose();
27159
+ throw error;
27160
+ }
27161
+ return { dispose };
27162
+ }
27163
+ var IndexLogic = class {
27164
+ indexMount(node, { shell_id }) {
27165
+ const renderer = this.page.src.renderer;
27166
+ const element = renderer.destination.ownerDocument.getElementById(shell_id);
27167
+ this.index = mountIndexPage(renderer, renderer.elements.get(element).node);
27168
+ }
27169
+ };
26509
27170
  export {
26510
27171
  Bag,
26511
27172
  BagNode,
@@ -26518,11 +27179,14 @@ export {
26518
27179
  Handler,
26519
27180
  HttpTransport,
26520
27181
  InOut,
27182
+ IndexLogic,
27183
+ IndexPage,
26521
27184
  Page,
26522
27185
  PageBootstrap,
26523
27186
  References,
26524
27187
  RpcError,
26525
27188
  RpcHandler,
26526
27189
  SourceHandler,
26527
- UtilitiesHandler
27190
+ UtilitiesHandler,
27191
+ mountIndexPage
26528
27192
  };