@gramlot/gramlot 0.2.16 → 0.2.18

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.
Files changed (47) hide show
  1. package/assets/branding/app-icon.png +0 -0
  2. package/dist/gramlot.js +1413 -235
  3. package/dist/gramlot.min.js +74 -17
  4. package/package.json +9 -5
  5. package/src/binding/ask-dialog.js +108 -0
  6. package/src/binding/providers.js +41 -6
  7. package/src/binding/remote.js +19 -20
  8. package/src/binding/runtime.js +38 -2
  9. package/src/builder/gramlot-builder.js +21 -3
  10. package/src/builder/source.js +18 -5
  11. package/src/builder/webcomponent.json +51 -0
  12. package/src/frame-messages.js +177 -0
  13. package/src/gramlot.d.ts +14 -0
  14. package/src/gramlot.js +9 -1
  15. package/src/handlers/rpc-handler.js +2 -0
  16. package/src/handlers/source-handler.js +1 -0
  17. package/src/handlers/subscriptions-handler.js +103 -0
  18. package/src/index-page-runtime.d.ts +11 -0
  19. package/src/index-page-runtime.js +287 -0
  20. package/src/index-page-styles.js +2 -0
  21. package/src/index-theme.js +5 -0
  22. package/src/index.d.ts +4 -1
  23. package/src/index.js +3 -0
  24. package/src/inout.js +3 -1
  25. package/src/references.d.ts +5 -0
  26. package/src/references.js +23 -1
  27. package/src/renderer/attributes.js +14 -3
  28. package/src/renderer/gramlot-html-renderer.js +9 -2
  29. package/src/renderer/gramlot-renderer.js +5 -1
  30. package/src/renderer/gramlot-svg-renderer.js +2 -1
  31. package/src/server/conformance.js +22 -2
  32. package/src/server/gramlot-server.d.ts +1 -0
  33. package/src/server/gramlot-server.js +12 -0
  34. package/src/server/index-page.d.ts +14 -0
  35. package/src/server/index-page.js +102 -0
  36. package/src/server/page-base.js +88 -0
  37. package/src/server/page.d.ts +8 -2
  38. package/src/server/page.js +3 -76
  39. package/src/view/button.js +17 -3
  40. package/src/view/html.js +4 -3
  41. package/src/webcomponent.js +13 -0
  42. package/themes/gramlot-base/README.md +8 -0
  43. package/themes/gramlot-compact/README.md +49 -0
  44. package/themes/gramlot-compact/theme.css +57 -0
  45. package/themes/gramlot-index/theme.css +51 -0
  46. package/tools/gramlot-tools-inspector.js +1733 -0
  47. package/tools/inspector-agent.js +252 -0
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);
14919
- }
14920
- if (!Array.isArray(source) && typeof source !== "object") {
14921
- source = { value: source };
14953
+ static fromJson(source, options = {}) {
14954
+ if (!warnedFromJson) {
14955
+ console.warn("Bag.fromJson is deprecated; use Bag.fromTytx");
14956
+ warnedFromJson = true;
14922
14957
  }
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");
@@ -21780,11 +21880,11 @@ var Handler = class {
21780
21880
 
21781
21881
  // src/builder/source.js
21782
21882
  var CODE_ATTRIBUTES = {
21783
- dataFormula: ["formula", "_if", "_else"],
21784
- dataController: ["script", "_if", "_else"],
21785
- dataRpc: ["_if", "_else", "_onCalling", "_onResult", "_onError"],
21883
+ dataFormula: ["formula", "_if", "_else", "_ask_if", "_ask_onCancel"],
21884
+ dataController: ["script", "_if", "_else", "_ask_if", "_ask_onCancel"],
21885
+ dataRpc: ["_ask_if", "_ask_onCancel", "_if", "_else", "_onCalling", "_onResult", "_onError"],
21786
21886
  dataRemote: ["_if", "_else"],
21787
- button: ["action"]
21887
+ button: ["action", "_ask_if"]
21788
21888
  };
21789
21889
  var REMOTE_CONTROLS = ["_cachedRemote", "_if", "_else", "_onRemote"];
21790
21890
  var REMOTE_CODE_ATTRIBUTES = ["_if", "_else", "_onRemote"];
@@ -21811,7 +21911,15 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21811
21911
  ];
21812
21912
  const items = [];
21813
21913
  for (const [name, value] of Object.entries(this.getAttr() ?? {})) {
21814
- if (typeof value === "string" && (own.includes(name) || name.startsWith("connect_on"))) items.push([name, value]);
21914
+ if (typeof value === "string" && (own.includes(name) || name.startsWith("connect_on") || name.startsWith("subscribe_") || name.startsWith("selfsubscribe_"))) items.push([name, value]);
21915
+ }
21916
+ for (const attribute of ["ask", "_ask"]) {
21917
+ const spec = this.getAttr(attribute);
21918
+ if (spec && typeof spec === "object") {
21919
+ for (const key of ["_if", "askIf"]) {
21920
+ if (typeof spec[key] === "string") items.push([`${attribute}.${key}`, spec[key]]);
21921
+ }
21922
+ }
21815
21923
  }
21816
21924
  for (const [name, value] of sourceAttributeItems(this.getAttr())) {
21817
21925
  if (isExpression(value)) items.push([name, value]);
@@ -21860,6 +21968,10 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21860
21968
  this.setAttr(attributes);
21861
21969
  return wrapSource(this);
21862
21970
  }
21971
+ /** Publish to this node's selfsubscribe topics, as in the legacy Source API. */
21972
+ publish(topic, payload = {}) {
21973
+ return this.builder.binding.gramlot._subscriptions.publishNode(this, topic, payload);
21974
+ }
21863
21975
  /** Builder's pointerType, except that a string starting with `==` is not a pointer. */
21864
21976
  pointerType(v) {
21865
21977
  if (typeof v === "string" && v.startsWith("==")) return null;
@@ -22107,6 +22219,11 @@ var BINDING_ATTRIBUTES = /* @__PURE__ */ new Set([
22107
22219
  "visible",
22108
22220
  "action",
22109
22221
  "fire",
22222
+ "ask",
22223
+ "_ask",
22224
+ "_ask_if",
22225
+ "_ask_title",
22226
+ "_ask_onCancel",
22110
22227
  "if",
22111
22228
  "else",
22112
22229
  "_init",
@@ -22119,7 +22236,7 @@ var BINDING_ATTRIBUTES = /* @__PURE__ */ new Set([
22119
22236
  "_cachedRemote",
22120
22237
  "_onRemote"
22121
22238
  ]);
22122
- var BINDING_ATTRIBUTE_PREFIXES = ["default_", "attr_", "fire_", "connect_on", "remote_"];
22239
+ var BINDING_ATTRIBUTE_PREFIXES = ["default_", "attr_", "fire_", "connect_on", "subscribe_", "selfsubscribe_", "formsubscribe_", "remote_"];
22123
22240
  var NATIVE_ATTRIBUTES = {
22124
22241
  table: ["width", "border"],
22125
22242
  editor: ["height"],
@@ -22131,7 +22248,16 @@ var TEMPLATE_REFERENCE = /(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
22131
22248
  var DISPLAY_ATTRIBUTES = ["format", "mask", "locale", "places", "dtype"];
22132
22249
  var URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src", "formaction", "xlink:href", "xlink_href"]);
22133
22250
  function withoutBindingAttributes(attrs) {
22134
- return Object.fromEntries(Object.entries(attrs).filter(([name]) => !BINDING_ATTRIBUTES.has(name) && !BINDING_ATTRIBUTE_PREFIXES.some((prefix) => name.startsWith(prefix))));
22251
+ return Object.fromEntries(Object.entries(attrs).filter(([name, value]) => !(value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef")) && !BINDING_ATTRIBUTES.has(name) && !BINDING_ATTRIBUTE_PREFIXES.some((prefix) => name.startsWith(prefix))));
22252
+ }
22253
+ function requireStyleClassAttributes(node, attrs, prefixes = []) {
22254
+ for (const [name, value] of Object.entries(attrs)) {
22255
+ const prefix = prefixes.find((candidate) => name.startsWith(candidate)) ?? "";
22256
+ const bare = name.slice(prefix.length);
22257
+ if (["style", "class", "_class"].includes(bare) && value != null && typeof value !== "string") {
22258
+ throw new TypeError(`${node.nodeTag} '${node.label}': '${name}' must be a string or null`);
22259
+ }
22260
+ }
22135
22261
  }
22136
22262
  function requireNoScriptAttributes(node, attrs, prefixes = []) {
22137
22263
  for (const [name, value] of Object.entries(withoutNullValues(withoutBindingAttributes(attrs)))) {
@@ -22281,6 +22407,7 @@ var GramlotSvgRenderer = class extends SvgRenderer {
22281
22407
  const evaluated = this.owner.evaluateExpressions(node, runtimeAttrs);
22282
22408
  requireNoScriptAttributes(node, evaluated);
22283
22409
  const [tag2, attrs] = super._handleMeta(node, evaluated);
22410
+ requireStyleClassAttributes(node, attrs);
22284
22411
  return node._getMeta("subbuilder") ? [tag2, svgAttributes(boundaryAttributes(attrs))] : [tag2, attrs];
22285
22412
  }
22286
22413
  /** `_meta`, binding attributes and null values out; Builder's `svgAttributes`; Gramlot names. */
@@ -22302,6 +22429,26 @@ var GramlotSvgRenderer = class extends SvgRenderer {
22302
22429
  }
22303
22430
  };
22304
22431
 
22432
+ // src/webcomponent.js
22433
+ 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;
22434
+ var RESERVED = /* @__PURE__ */ new Set([
22435
+ "annotation-xml",
22436
+ "color-profile",
22437
+ "font-face",
22438
+ "font-face-src",
22439
+ "font-face-uri",
22440
+ "font-face-format",
22441
+ "font-face-name",
22442
+ "missing-glyph"
22443
+ ]);
22444
+ function webcomponentCode(attrs) {
22445
+ const code = attrs.code;
22446
+ if (typeof code !== "string" || NAME2.exec(code)?.[0] !== code || !code.includes("-") || RESERVED.has(code)) {
22447
+ throw new TypeError("webcomponent: code must be a literal custom-element name");
22448
+ }
22449
+ return code;
22450
+ }
22451
+
22305
22452
  // src/renderer/gramlot-html-renderer.js
22306
22453
  var GramlotHtmlRenderer = class extends HtmlRenderer {
22307
22454
  // noConvertStyle attributes taken out in _handleMeta, put back after adaptAttrs.
@@ -22335,7 +22482,13 @@ var GramlotHtmlRenderer = class extends HtmlRenderer {
22335
22482
  const prefixes = this.builder.constructor.dialectPrefixes;
22336
22483
  const evaluated = this.evaluateExpressions(node, runtimeAttrs);
22337
22484
  requireNoScriptAttributes(node, evaluated, prefixes);
22338
- const [tag2, attrs] = super._handleMeta(node, withDataSrcdocSandbox(node, evaluated, prefixes));
22485
+ let [tag2, attrs] = super._handleMeta(node, withDataSrcdocSandbox(node, evaluated, prefixes));
22486
+ requireStyleClassAttributes(node, attrs, prefixes);
22487
+ if (node.nodeTag === "webcomponent") {
22488
+ tag2 = webcomponentCode(node.getAttr());
22489
+ const { code, ...rest2 } = attrs;
22490
+ attrs = rest2;
22491
+ }
22339
22492
  if (node._getMeta("subbuilder")) {
22340
22493
  const boundary = boundaryAttributes(attrs);
22341
22494
  if (node._getMeta("subbuilder") === "html") boundary.xmlns = SVG_NS;
@@ -22793,11 +22946,64 @@ var binding_default = {
22793
22946
  }
22794
22947
  };
22795
22948
 
22949
+ // src/builder/webcomponent.json
22950
+ var webcomponent_default = {
22951
+ document_format: {
22952
+ name: "builder_grammar",
22953
+ version: "1.1"
22954
+ },
22955
+ grammar: {
22956
+ name: "webcomponent",
22957
+ version: null,
22958
+ title: "Gramlot webcomponent",
22959
+ description: "An explicitly loaded autonomous custom element."
22960
+ },
22961
+ abstracts: {},
22962
+ elements: {
22963
+ webcomponent: {
22964
+ doc: "Create the custom-element tag named by literal code.",
22965
+ sub_tags: "*",
22966
+ parent_tags: null,
22967
+ inherits_from: null,
22968
+ ns: null,
22969
+ attributes: {
22970
+ parameters: [
22971
+ {
22972
+ name: "code",
22973
+ kind: "keyword_only",
22974
+ role: "attribute",
22975
+ annotation: {
22976
+ kind: "type",
22977
+ module: "builtins",
22978
+ name: "str"
22979
+ },
22980
+ has_default: false
22981
+ },
22982
+ {
22983
+ name: "attr",
22984
+ kind: "var_keyword",
22985
+ role: "attribute",
22986
+ annotation: {
22987
+ kind: "any"
22988
+ },
22989
+ has_default: false
22990
+ }
22991
+ ],
22992
+ accepts_var_keyword: true,
22993
+ accepts_var_positional: false
22994
+ },
22995
+ node_label: null,
22996
+ collection_key: null,
22997
+ _meta: null
22998
+ }
22999
+ }
23000
+ };
23001
+
22796
23002
  // src/builder/gramlot-builder.js
22797
23003
  var DATA_FORBIDDEN = "data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element";
22798
23004
  var EXCLUDED_ELEMENTS = /* @__PURE__ */ new Set();
22799
- var EXCLUDED_ATTRIBUTES = /* @__PURE__ */ new Set(["serverpath", "dbenv", "shared_id", "_ask", "ask"]);
22800
- var EXCLUDED_ATTRIBUTE_PREFIXES = ["subscribe_", "selfsubscribe_", "formsubscribe_"];
23005
+ var EXCLUDED_ATTRIBUTES = /* @__PURE__ */ new Set(["serverpath", "dbenv", "shared_id"]);
23006
+ var EXCLUDED_ATTRIBUTE_PREFIXES = ["formsubscribe_"];
22801
23007
  var DATA_PATH_ATTRIBUTES = {
22802
23008
  dataSetter: "destination_path",
22803
23009
  dataFormula: "result_path",
@@ -22806,6 +23012,11 @@ var DATA_PATH_ATTRIBUTES = {
22806
23012
  };
22807
23013
  var DATA_INLINE_ATTRIBUTES = { dataFormula: "formula", dataController: "script" };
22808
23014
  function dataElementError(tag2, attrs) {
23015
+ if (Object.hasOwn(attrs, "ask") && tag2 !== "button") return "'ask' is supported on buttons";
23016
+ if (Object.hasOwn(attrs, "_ask") && !["dataController", "dataFormula", "dataRpc"].includes(tag2)) return "'_ask' requires a controller, formula or RPC";
23017
+ if (["dataSetter", "dataRemote"].includes(tag2) && Object.keys(attrs).some((name) => name.startsWith("subscribe_") || name.startsWith("selfsubscribe_"))) {
23018
+ return "topic subscriptions are supported on controllers, formulas, RPCs and rendered elements";
23019
+ }
22809
23020
  const pathName = DATA_PATH_ATTRIBUTES[tag2];
22810
23021
  if (pathName && String(attrs[pathName] ?? "").includes("?")) {
22811
23022
  return `'${pathName}' does not accept '?attr': '${attrs[pathName]}'`;
@@ -22828,6 +23039,9 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
22828
23039
  static {
22829
23040
  this.defineGrammar(binding_default);
22830
23041
  }
23042
+ static {
23043
+ this.defineGrammar(webcomponent_default);
23044
+ }
22831
23045
  /** Tag prefixes of the parent dialects, from the `_name` of the classes above GramlotBuilder. */
22832
23046
  static get dialectPrefixes() {
22833
23047
  const prefixes = [];
@@ -22898,6 +23112,7 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
22898
23112
  }
22899
23113
  /** Builder's value check, plus the excluded attributes (authoring names the tag). */
22900
23114
  validateNodeValues(tag2, value, attrs = {}) {
23115
+ if (tag2 === "webcomponent") webcomponentCode(attrs);
22901
23116
  const excluded = excludedAttribute(attrs);
22902
23117
  if (excluded) throw new Error(`${tag2}: attribute '${excluded}' is excluded from Gramlot 0.2.0`);
22903
23118
  const error = dataElementError(tag2, attrs);
@@ -22906,14 +23121,20 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
22906
23121
  }
22907
23122
  /** Builder's node check, plus the excluded attributes (a Source node names tag and label). */
22908
23123
  validateNode(node, options = {}) {
23124
+ if (node.nodeTag === "webcomponent") webcomponentCode(options.attrs ?? node.getAttr());
22909
23125
  const excluded = excludedAttribute(options.attrs ?? node.getAttr());
22910
23126
  if (excluded) throw new Error(`${node.nodeTag} '${node.label}': attribute '${excluded}' is excluded from Gramlot 0.2.0`);
22911
23127
  const error = dataElementError(node.nodeTag, options.attrs ?? node.getAttr());
22912
23128
  if (error) throw new Error(`${node.nodeTag} '${node.label}': ${error}`);
22913
23129
  return super.validateNode(node, options);
22914
23130
  }
23131
+ /** Custom elements are outside the native HTML child catalogue, as components are. */
23132
+ _countsForGrammar(info) {
23133
+ return info !== this.schema.webcomponent && super._countsForGrammar(info);
23134
+ }
22915
23135
  /** Builder's child insertion; a plain object `value` of `dataSetter` becomes `new Bag(value)` (P25). */
22916
23136
  setChild(bag, tag2, value, attrs, parentOverride = null) {
23137
+ attrs = Object.fromEntries(Object.entries(attrs ?? {}).map(([key, value2]) => [key, sourceTarget(value2) instanceof SourceBagNode ? this.reference(value2) : value2]));
22917
23138
  const plain = tag2 === "dataSetter" && attrs?.value !== null && typeof attrs?.value === "object" && Object.getPrototypeOf(attrs.value) === Object.prototype;
22918
23139
  const actual = plain ? { ...attrs, value: new Bag(attrs.value) } : attrs;
22919
23140
  return super.setChild(bag, tag2, value, actual, parentOverride);
@@ -22952,7 +23173,10 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
22952
23173
  }
22953
23174
  let id = node.getAttr("__ref");
22954
23175
  if (id === null || id === void 0) {
22955
- id = crypto.randomUUID().replaceAll("-", "");
23176
+ id = Array.from(
23177
+ crypto.getRandomValues(new Uint8Array(16)),
23178
+ (byte) => byte.toString(16).padStart(2, "0")
23179
+ ).join("");
22956
23180
  node.setAttr({ __ref: id });
22957
23181
  }
22958
23182
  return { $gramlotRef: id, kind };
@@ -23430,7 +23654,7 @@ var HtmlElement = class {
23430
23654
  const builder = node.builder;
23431
23655
  const declaration3 = builder.schema[builder.schemaTag(node.nodeTag)];
23432
23656
  const meta = { ...declaration3._meta, ...node.getAttr("_meta") };
23433
- const tag2 = resolveRenderTag(node.nodeTag, {
23657
+ const tag2 = node.nodeTag === "webcomponent" ? webcomponentCode(node.getAttr()) : resolveRenderTag(node.nodeTag, {
23434
23658
  renderTag: meta.render_tag,
23435
23659
  ns: node.getAttr("ns"),
23436
23660
  dialectName: builder.constructor._name
@@ -23445,7 +23669,7 @@ var HtmlElement = class {
23445
23669
  throw new TypeError("HTML text must be scalar");
23446
23670
  }
23447
23671
  for (const [key, value] of Object.entries(node.attr)) {
23448
- if (this.metadataAttributes.has(key)) continue;
23672
+ if (this.metadataAttributes.has(key) || ["ask", "_ask"].includes(key) || value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef")) continue;
23449
23673
  if (value != null && !["string", "number", "boolean"].includes(typeof value)) {
23450
23674
  throw new TypeError(`HTML attribute ${key} must be scalar`);
23451
23675
  }
@@ -23491,7 +23715,7 @@ var HtmlElement = class {
23491
23715
  const keys = [.../* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(attrs)])];
23492
23716
  keys.sort((a, b) => (b === "sandbox") - (a === "sandbox"));
23493
23717
  for (const key of keys) {
23494
- if (this.metadataAttributes.has(key) || controlled && key === "value") continue;
23718
+ if (this.metadataAttributes.has(key) || ["ask", "_ask"].includes(key) || controlled && key === "value") continue;
23495
23719
  const value = attrs[key];
23496
23720
  const attrName = key;
23497
23721
  const propertyName = domPropertyName(attrName);
@@ -23527,6 +23751,129 @@ var HtmlElement = class {
23527
23751
  }
23528
23752
  };
23529
23753
 
23754
+ // src/binding/ask-dialog.js
23755
+ var pages = /* @__PURE__ */ new WeakMap();
23756
+ var SPEC_KEYS = /* @__PURE__ */ new Set(["title", "msg", "fields", "_if", "askIf"]);
23757
+ var FIELD_KEYS = /* @__PURE__ */ new Set(["name", "lbl", "tag", "type", "default_value", "required", "min", "max", "step", "placeholder"]);
23758
+ var AskDialog = class {
23759
+ static required(binding, specification, parameters2, attribute) {
23760
+ const evaluate = (name, code) => typeof code === "boolean" ? code : binding.runtime.inlineCompiler.compile(
23761
+ binding.node,
23762
+ name,
23763
+ code,
23764
+ Object.keys(parameters2),
23765
+ `return (${code});`
23766
+ )(parameters2);
23767
+ if (typeof specification === "string") {
23768
+ const condition = binding.node.getAttr("_ask_if");
23769
+ return !condition || Boolean(evaluate("_ask_if", condition));
23770
+ }
23771
+ if (specification?.askIf) evaluate(`${attribute}.askIf`, specification.askIf);
23772
+ return !specification?._if || Boolean(evaluate(`${attribute}._if`, specification._if));
23773
+ }
23774
+ static show(binding, specification, parameters2, title = "Parameters") {
23775
+ const spec = typeof specification === "string" ? { msg: specification, title } : specification;
23776
+ if (!spec || typeof spec !== "object" || Array.isArray(spec)) throw new TypeError("ask requires text or a parameter description");
23777
+ for (const key of Object.keys(spec)) {
23778
+ if (!SPEC_KEYS.has(key)) throw new Error(`Unsupported ask option: ${key}`);
23779
+ }
23780
+ const fields = spec.fields ?? [];
23781
+ if (!Array.isArray(fields)) throw new TypeError("ask fields must be an array");
23782
+ const names = /* @__PURE__ */ new Set();
23783
+ for (const field of fields) {
23784
+ if (!field || !/^[A-Za-z_]\w*$/.test(field.name) || names.has(field.name)) throw new Error("ask fields require distinct simple names");
23785
+ names.add(field.name);
23786
+ for (const key of Object.keys(field)) {
23787
+ if (!FIELD_KEYS.has(key)) throw new Error(`Unsupported ask field option: ${key}`);
23788
+ }
23789
+ if (field.tag && !["input", "textarea"].includes(field.tag)) throw new Error(`Unsupported ask widget: ${field.tag}`);
23790
+ if (field.type && !["text", "number", "date", "checkbox", "email", "password", "url", "tel"].includes(field.type)) {
23791
+ throw new Error(`Unsupported ask input type: ${field.type}`);
23792
+ }
23793
+ }
23794
+ const app = binding.runtime.gramlot;
23795
+ let page = pages.get(app);
23796
+ if (!page) {
23797
+ const group = `ask_${Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
23798
+ const requests = /* @__PURE__ */ new Map();
23799
+ class Logic {
23800
+ confirm(node, event) {
23801
+ event.preventDefault();
23802
+ requests.get(node.getAttr("request"))?.finish(true);
23803
+ }
23804
+ cancel(node, event) {
23805
+ event.preventDefault();
23806
+ requests.get(node.getAttr("request"))?.finish(false);
23807
+ }
23808
+ }
23809
+ app.src.logicRegistry.register(Logic, { group, resource: "gramlot:ask" });
23810
+ page = { group, requests };
23811
+ pages.set(app, page);
23812
+ }
23813
+ return new Promise((resolve, reject) => {
23814
+ const id = `ask_${Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
23815
+ let finished = false;
23816
+ let release = () => {
23817
+ };
23818
+ const finish = (confirmed, failure = null) => {
23819
+ if (finished) return;
23820
+ finished = true;
23821
+ const result = confirmed ? Object.fromEntries(fields.map((field) => [field.name, app.data.getItem(`${id}.${field.name}`)])) : null;
23822
+ page.requests.delete(id);
23823
+ release();
23824
+ try {
23825
+ app.src.source.popNode(id);
23826
+ if (app.data.getNode(id)) app.data.popNode(id);
23827
+ if (failure) reject(failure);
23828
+ else resolve(result);
23829
+ } catch (error) {
23830
+ reject(error);
23831
+ }
23832
+ };
23833
+ page.requests.set(id, { finish });
23834
+ release = binding.track(() => finish(false));
23835
+ try {
23836
+ const builder = new GramlotBuilder();
23837
+ const dialog = builder.root.dialog({
23838
+ node_id: id,
23839
+ datapath: id,
23840
+ request: id,
23841
+ connect_oncancel: `${page.group}.cancel`,
23842
+ connect_onclose: `${page.group}.cancel`,
23843
+ class: "gramlot-ask",
23844
+ "aria-labelledby": `${id}_title`,
23845
+ style: "border:1px solid #aab4c2;border-radius:8px;padding:16px;max-width:32rem;width:calc(100% - 48px);font:inherit;"
23846
+ });
23847
+ dialog.h2(spec.title ?? title, { id: `${id}_title`, style: "font-size:1.1em;margin:0 0 12px;" });
23848
+ if (spec.msg) dialog.p(spec.msg);
23849
+ const form = dialog.form({ request: id, connect_onsubmit: `${page.group}.confirm` });
23850
+ for (const field of fields) {
23851
+ form.dataSetter({
23852
+ destination_path: `.${field.name}`,
23853
+ value: Object.hasOwn(parameters2, field.name) ? parameters2[field.name] : field.default_value ?? (field.type === "checkbox" ? false : "")
23854
+ });
23855
+ const row = form.div({ style: "margin:8px 0;" });
23856
+ row.html_label(field.lbl ?? field.name, { for: `${id}_${field.name}`, style: "display:block;margin-bottom:4px;" });
23857
+ const attrs = { id: `${id}_${field.name}`, value: `^.${field.name}`, live: true };
23858
+ for (const key of ["required", "min", "max", "step", "placeholder"]) {
23859
+ if (field[key] !== void 0) attrs[key] = field[key];
23860
+ }
23861
+ if (field.tag === "textarea") row.textarea(attrs);
23862
+ else row.input({ ...attrs, type: field.type ?? "text" });
23863
+ }
23864
+ const buttons = form.div({ style: "display:flex;justify-content:flex-end;gap:8px;margin-top:16px;" });
23865
+ buttons.button("Cancel", { type: "button", request: id, connect_onclick: `${page.group}.cancel` });
23866
+ buttons.button("Confirm", { type: "submit", autofocus: fields.length === 0 });
23867
+ app.src.source.setItem(id, app.src.prepareSource(builder.source));
23868
+ const node = app.src.binding.nodeIds.get(id);
23869
+ app.dom.getDomNode(node).showModal();
23870
+ } catch (error) {
23871
+ finish(false, error);
23872
+ }
23873
+ });
23874
+ }
23875
+ };
23876
+
23530
23877
  // src/view/button.js
23531
23878
  var ButtonBinding = class _ButtonBinding {
23532
23879
  #binding;
@@ -23615,9 +23962,22 @@ var ButtonBinding = class _ButtonBinding {
23615
23962
  const provider = this.binding.runtime.bindingFor(this.controllers[0])?.providers[0];
23616
23963
  provider?.invoke({ kind: "click", event, counter });
23617
23964
  } else if (mechanism === "action") {
23618
- const [, attrs] = node.builder.runtimeValues(node);
23619
- const values = { ...attrs, event, _counter: counter, modifiers };
23620
- this.binding.runtime.inlineCompiler.compile(node, "action", node.getAttr("action"), Object.keys(values))(values);
23965
+ const read = () => {
23966
+ const [, attrs] = node.builder.runtimeValues(node);
23967
+ const authored = Object.fromEntries(Object.entries(attrs).filter(([name]) => name !== "ask"));
23968
+ return { ...this.binding.runtime.renderer.references.resolveArguments(authored), event, _counter: counter, modifiers };
23969
+ };
23970
+ const execute = (result) => {
23971
+ if (this.binding.closed || result === null) return;
23972
+ const values = { ...read(), ...result };
23973
+ if (result) values._askResult = result;
23974
+ this.binding.runtime.inlineCompiler.compile(node, "action", node.getAttr("action"), Object.keys(values))(values);
23975
+ };
23976
+ const ask = node.getAttr("ask");
23977
+ if (ask && AskDialog.required(this.binding, ask, read(), "ask")) {
23978
+ return AskDialog.show(this.binding, ask, read()).then(execute);
23979
+ }
23980
+ execute(void 0);
23621
23981
  } else {
23622
23982
  const attributes = { modifier: modifiers, _counter: counter };
23623
23983
  const fire = node.getAttr("fire");
@@ -23699,6 +24059,18 @@ var NativeEventBinding = class {
23699
24059
  };
23700
24060
 
23701
24061
  // src/references.js
24062
+ function assertTransportData(value, ancestors = /* @__PURE__ */ new Set()) {
24063
+ if (!value || typeof value !== "object") return;
24064
+ const nodeClass = value.ownerDocument?.defaultView?.Node ?? value.defaultView?.Node;
24065
+ if (sourceTarget(value) instanceof SourceBagNode || nodeClass && value instanceof nodeClass) {
24066
+ throw new TypeError("Live Source/DOM references cannot cross a transport boundary");
24067
+ }
24068
+ if (ancestors.has(value)) throw new TypeError("Transport data cannot contain circular references");
24069
+ ancestors.add(value);
24070
+ const children = value instanceof Bag ? value.getNodes().flatMap((node) => [node.staticValue, node.getAttr()]) : Object.values(value);
24071
+ for (const child of children) assertTransportData(child, ancestors);
24072
+ ancestors.delete(value);
24073
+ }
23702
24074
  var References = class {
23703
24075
  constructor(sourceRoot = null) {
23704
24076
  this.entries = /* @__PURE__ */ new Map();
@@ -23733,6 +24105,13 @@ var References = class {
23733
24105
  if (entry.node === node) this.entries.delete(id);
23734
24106
  }
23735
24107
  }
24108
+ /** Resolve only directly authored descriptors; message payloads are not expressions. */
24109
+ resolveArguments(attrs) {
24110
+ return Object.fromEntries(Object.entries(attrs).map(([name, value]) => [
24111
+ name,
24112
+ value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef") ? this.resolve(value) : value
24113
+ ]));
24114
+ }
23736
24115
  resolve(reference) {
23737
24116
  if (!reference || !["node", "dom"].includes(reference.kind)) {
23738
24117
  throw new TypeError("Expected a node or DOM reference");
@@ -24183,6 +24562,10 @@ var CONTROL_ATTRIBUTES = /* @__PURE__ */ new Set([
24183
24562
  "_delay",
24184
24563
  "_timing",
24185
24564
  "_userChanges",
24565
+ "_ask",
24566
+ "_ask_if",
24567
+ "_ask_title",
24568
+ "_ask_onCancel",
24186
24569
  "method",
24187
24570
  "timeout",
24188
24571
  "_onCalling",
@@ -24243,6 +24626,20 @@ var Provider = class {
24243
24626
  this.#registrations.push(registration);
24244
24627
  if (name === "_timing") this.#timingRegistration = registration;
24245
24628
  }
24629
+ const subscriptions = this.binding.runtime.gramlot._subscriptions;
24630
+ for (const name of Object.keys(node.getAttr())) {
24631
+ const prefix = name.startsWith("selfsubscribe_") ? "selfsubscribe_" : name.startsWith("subscribe_") ? "subscribe_" : null;
24632
+ if (!prefix) continue;
24633
+ const topic = prefix === "selfsubscribe_" ? subscriptions.topicFor(node, name.slice(prefix.length)) : name.slice(prefix.length);
24634
+ const handle = subscriptions.subscribe(topic, (payload) => {
24635
+ const trigger = { kind: "subscription", topic, payload };
24636
+ if (this.#resolved("_userChanges") && topic !== "node") return;
24637
+ const delay = this.#resolved("_delay");
24638
+ if (delay > 0) this.#debounce(trigger, delay);
24639
+ else this.invoke(trigger);
24640
+ });
24641
+ this.#registrations.push({ close: () => subscriptions.unsubscribe(handle) });
24642
+ }
24246
24643
  this.#startTiming();
24247
24644
  if (this.kind === "remote") this.invoke({ kind: "install", change: null });
24248
24645
  }
@@ -24281,6 +24678,22 @@ var Provider = class {
24281
24678
  const rpc = this.kind === "rpc";
24282
24679
  const remote = this.kind === "remote";
24283
24680
  const kwargs = this.readArguments(trigger);
24681
+ if (trigger.askResult) {
24682
+ Object.assign(kwargs, trigger.askResult);
24683
+ kwargs._askResult = trigger.askResult;
24684
+ }
24685
+ const ask = node.getAttr("_ask");
24686
+ if (ask && !trigger.askDone && AskDialog.required(this.binding, ask, kwargs, "_ask")) {
24687
+ return AskDialog.show(this.binding, ask, kwargs, node.getAttr("_ask_title") ?? "Warning").then((result2) => {
24688
+ if (this.binding.closed) return;
24689
+ if (result2 === null) {
24690
+ const cancel = node.getAttr("_ask_onCancel");
24691
+ if (cancel) this.#inline("_ask_onCancel", cancel, cancel, kwargs, true);
24692
+ return;
24693
+ }
24694
+ return this.invoke({ ...trigger, askDone: true, askResult: result2 });
24695
+ });
24696
+ }
24284
24697
  let [attr, body] = [formula ? "formula" : "script", node.getAttr(formula ? "formula" : "script")];
24285
24698
  const condition = node.getAttr("_if");
24286
24699
  if (condition && !this.#inline("_if", condition, `return (${condition})`, kwargs, false)) {
@@ -24316,12 +24729,14 @@ var Provider = class {
24316
24729
  readArguments(trigger) {
24317
24730
  const node = this.node;
24318
24731
  const [, attrs] = node.builder.runtimeValues(node);
24319
- const kwargs = {};
24320
- for (const [name, value] of Object.entries(attrs)) {
24321
- if (!CONTROL_ATTRIBUTES.has(name)) kwargs[name] = value;
24322
- }
24732
+ const authored = Object.fromEntries(Object.entries(attrs).filter(([name]) => !CONTROL_ATTRIBUTES.has(name) && !name.startsWith("subscribe_") && !name.startsWith("selfsubscribe_")));
24733
+ const kwargs = {
24734
+ ...trigger.kind === "subscription" ? trigger.payload : {},
24735
+ ...this.binding.runtime.renderer.references.resolveArguments(authored)
24736
+ };
24737
+ if (trigger.kind === "subscription") kwargs._subscription_kwargs = trigger.payload;
24323
24738
  const change = trigger.change ?? null;
24324
- const reason = change ? change.level : trigger.kind;
24739
+ const reason = change ? change.level : trigger.kind === "subscription" ? trigger.topic : trigger.kind;
24325
24740
  kwargs._node = change ? change.node : null;
24326
24741
  kwargs._triggerpars = { kw: change, trigger_reason: reason };
24327
24742
  kwargs._reason = reason;
@@ -24498,7 +24913,7 @@ var RemoteProvider = class extends Provider {
24498
24913
  return "remote";
24499
24914
  }
24500
24915
  };
24501
- var TRIGGER_FIELDS = ["_node", "_triggerpars", "_reason"];
24916
+ var TRIGGER_FIELDS = ["_node", "_triggerpars", "_reason", "_subscription_kwargs", "_askResult"];
24502
24917
  var CLICK_FIELDS = ["_evt", "button_counter", "button_shift", "button_ctrl", "button_alt", "button_meta"];
24503
24918
  function authorArguments(kwargs) {
24504
24919
  const author = { ...kwargs };
@@ -24527,7 +24942,7 @@ var MACROS = [
24527
24942
  [/;FIRE/g, /(\W|^)FIRE (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)(;?)/g, "$1this.FIRE('$2')$3 "]
24528
24943
  ];
24529
24944
  var PUBLISH = /(\W|^)PUBLISH (?:\s*)(\^?[\w.#@$?-]+)/;
24530
- var RESERVED = /* @__PURE__ */ new Set([
24945
+ var RESERVED2 = /* @__PURE__ */ new Set([
24531
24946
  "arguments",
24532
24947
  "await",
24533
24948
  "break",
@@ -24688,7 +25103,7 @@ var InlineCompiler = class {
24688
25103
  }
24689
25104
  };
24690
25105
  function isIdentifier(name) {
24691
- return /^[A-Za-z_$][\w$]*$/.test(name) && !RESERVED.has(name);
25106
+ return /^[A-Za-z_$][\w$]*$/.test(name) && !RESERVED2.has(name);
24692
25107
  }
24693
25108
  function declaration2(node, attr) {
24694
25109
  return `${node.nodeTag} '${node.label}' ${attr ? `'${attr}'` : "node value"}`;
@@ -24711,7 +25126,8 @@ ${text}`, { cause: error });
24711
25126
  // src/binding/remote.js
24712
25127
  var RemoteBinding = class {
24713
25128
  #binding;
24714
- // The parameters of the last call, compared by `_cachedRemote`.
25129
+ // The name and TYTX parameters of the last mounted call, captured before sending it.
25130
+ #lastName = null;
24715
25131
  #lastParams = null;
24716
25132
  constructor(binding) {
24717
25133
  this.#binding = binding;
@@ -24728,8 +25144,9 @@ var RemoteBinding = class {
24728
25144
  /**
24729
25145
  * Request the fragment for the current parameters. Nothing happens before the node's `start` step,
24730
25146
  * 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.
25147
+ * also cancels the request in flight, so its fragment is not mounted after `_else`. A cache hit
25148
+ * cancels a pending request too, keeping the mounted fragment. A failure of the request rejects
25149
+ * with an error naming the node, its cause attached.
24733
25150
  */
24734
25151
  async update() {
24735
25152
  if (this.closed || !this.binding.hasStamp("start")) return;
@@ -24748,14 +25165,22 @@ var RemoteBinding = class {
24748
25165
  if (otherwise) this.#inline("_else", otherwise, otherwise, params);
24749
25166
  return;
24750
25167
  }
24751
- if (attrs._cachedRemote && this.#lastParams && sameValue(params, this.#lastParams)) return;
24752
25168
  let mounted;
25169
+ let text;
24753
25170
  try {
25171
+ text = toTytx(params);
25172
+ if (attrs._cachedRemote && name === this.#lastName && text === this.#lastParams) {
25173
+ this.binding.runtime.gramlot.rpc.remoteRequests.get(node)?.controller.abort();
25174
+ return;
25175
+ }
24754
25176
  mounted = await this.binding.runtime.gramlot.src.remoteSource(node, name, params);
24755
25177
  } catch (error) {
24756
25178
  throw new Error(`${node.nodeTag} '${node.label}': remote '${name}' failed: ${error.message}`, { cause: error });
24757
25179
  }
24758
- if (mounted) this.#lastParams = params;
25180
+ if (mounted) {
25181
+ this.#lastName = name;
25182
+ this.#lastParams = text;
25183
+ }
24759
25184
  const onRemote = node.getAttr("_onRemote");
24760
25185
  if (mounted && onRemote) this.#inline("_onRemote", onRemote, onRemote, params);
24761
25186
  }
@@ -24763,17 +25188,6 @@ var RemoteBinding = class {
24763
25188
  return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, Object.keys(params), source)(params);
24764
25189
  }
24765
25190
  };
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
25191
 
24778
25192
  // src/binding/runtime.js
24779
25193
  var PROVIDERS = {
@@ -24790,7 +25204,10 @@ var BindingRuntime = class {
24790
25204
  #router;
24791
25205
  #installer;
24792
25206
  #inlineCompiler;
24793
- #subscription = `gramlot-data-${crypto.randomUUID()}`;
25207
+ #subscription = `gramlot-data-${Array.from(
25208
+ crypto.getRandomValues(new Uint8Array(16)),
25209
+ (byte) => byte.toString(16).padStart(2, "0")
25210
+ ).join("")}`;
24794
25211
  #disposed = false;
24795
25212
  constructor(gramlot) {
24796
25213
  this.#gramlot = gramlot;
@@ -25169,6 +25586,10 @@ var NodeBinding = class {
25169
25586
  * A node whose `remote` is a string gets its RemoteBinding, created once.
25170
25587
  */
25171
25588
  registerPointers() {
25589
+ if (this.node._getMeta("data_element")) {
25590
+ this.runtime.renderer.references.remove(this.node);
25591
+ this.runtime.renderer.references.register(this.node, null);
25592
+ }
25172
25593
  const node = this.node;
25173
25594
  const dataElement = node._getMeta("data_element");
25174
25595
  if (dataElement && !PROVIDERS[node.nodeTag]) return;
@@ -25184,10 +25605,36 @@ var NodeBinding = class {
25184
25605
  if (name === "datapath") this.#datapathRegistration = registration;
25185
25606
  if (this.remote && (name === "remote" || name.startsWith("remote_"))) this.#remoteRegistrations.add(registration);
25186
25607
  }
25187
- if (!dataElement) return;
25608
+ if (!dataElement) {
25609
+ this.#registerTopics();
25610
+ return;
25611
+ }
25188
25612
  this.#provider ??= new PROVIDERS[node.nodeTag](this);
25189
25613
  this.#provider.register();
25190
25614
  }
25615
+ /** Rendered node topic handlers share semantic lifetime, not DOM lifetime. */
25616
+ #registerTopics() {
25617
+ const node = this.node;
25618
+ const subscriptions = this.runtime.gramlot._subscriptions;
25619
+ for (const [name, handler] of Object.entries(node.getAttr())) {
25620
+ const prefix = name.startsWith("selfsubscribe_") ? "selfsubscribe_" : name.startsWith("subscribe_") ? "subscribe_" : null;
25621
+ if (!prefix) continue;
25622
+ if (typeof handler !== "string" || !handler) throw new TypeError(`${name} requires a handler`);
25623
+ const topic = prefix === "selfsubscribe_" ? subscriptions.topicFor(node, name.slice(prefix.length)) : name.slice(prefix.length);
25624
+ const handle = subscriptions.subscribe(topic, (payload) => {
25625
+ if (this.closed) return;
25626
+ if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(handler)) {
25627
+ const { group, method } = this.runtime.logicRegistry.resolve(handler, node);
25628
+ return method.call(group, node, payload);
25629
+ }
25630
+ const [, attrs] = node.builder.runtimeValues(node);
25631
+ const authored = Object.fromEntries(Object.entries(attrs).filter(([key]) => !key.startsWith("subscribe_") && !key.startsWith("selfsubscribe_")));
25632
+ const values = { ...this.runtime.renderer.references.resolveArguments(authored), p_0: payload };
25633
+ return this.runtime.inlineCompiler.compile(node, name, handler, Object.keys(values))(values);
25634
+ });
25635
+ this.#registrations.push({ close: () => subscriptions.unsubscribe(handle) });
25636
+ }
25637
+ }
25191
25638
  /** Close the registrations and make them again from the current pointers, the provider's included (D1). */
25192
25639
  rebind() {
25193
25640
  this.#closeRegistrations();
@@ -25218,6 +25665,7 @@ var NodeBinding = class {
25218
25665
  close() {
25219
25666
  if (this.closed) return;
25220
25667
  this.#closed = true;
25668
+ if (this.node._getMeta("data_element")) this.runtime.renderer.references.remove(this.node);
25221
25669
  this.#closeRegistrations();
25222
25670
  const errors = [];
25223
25671
  for (const disposer of this.#disposers.splice(0).reverse()) {
@@ -25263,7 +25711,10 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
25263
25711
  this.building = false;
25264
25712
  this.disposed = false;
25265
25713
  this.elements = /* @__PURE__ */ new WeakMap();
25266
- this.instanceId = crypto.randomUUID();
25714
+ this.instanceId = Array.from(
25715
+ crypto.getRandomValues(new Uint8Array(16)),
25716
+ (byte) => byte.toString(16).padStart(2, "0")
25717
+ ).join("");
25267
25718
  this.radioGroups = new RadioGroups(this);
25268
25719
  this.subscription = `html-source-renderer-${this.instanceId}`;
25269
25720
  source.subscribe(this.subscription, { any: (event) => this.receive(event) });
@@ -25395,10 +25846,13 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
25395
25846
  if (!(block instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25396
25847
  const excluded = /* @__PURE__ */ new Set();
25397
25848
  const exclude = (node) => {
25849
+ if (excluded.has(node)) return;
25398
25850
  excluded.add(node);
25399
25851
  for (const child of this.records.get(node)?.children ?? []) exclude(child);
25852
+ if (node.value instanceof SourceBag) for (const child of node.value.getNodes()) exclude(child);
25400
25853
  };
25401
25854
  for (const child of this.records.get(replacingNode)?.children ?? []) exclude(child);
25855
+ if (replacingNode?.value instanceof SourceBag) for (const child of replacingNode.value.getNodes()) exclude(child);
25402
25856
  this.#validateBlock(block, replacingNode ? replacingNode.nodeTag : null);
25403
25857
  requireInstallable(block);
25404
25858
  this.references?.validate(block, excluded);
@@ -26106,6 +26560,7 @@ var SourceHandler = class extends Handler {
26106
26560
  }
26107
26561
  this.gramlot.state = "started";
26108
26562
  this.binding.pageStarted();
26563
+ this.gramlot._subscriptions.ready();
26109
26564
  return this.gramlot;
26110
26565
  }
26111
26566
  /**
@@ -26185,6 +26640,7 @@ var RpcHandler = class extends Handler {
26185
26640
  /** Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an RpcError. */
26186
26641
  async call(contentType, name, params = {}, { signal } = {}) {
26187
26642
  if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
26643
+ assertTransportData(params);
26188
26644
  const id = requestId();
26189
26645
  const text = toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params });
26190
26646
  const response = fromTytx(await this.transport.call(text, signal));
@@ -26209,6 +26665,258 @@ var DomHandler = class extends Handler {
26209
26665
  }
26210
26666
  };
26211
26667
 
26668
+ // src/frame-messages.js
26669
+ var TYPE = "gramlot:publish";
26670
+ var FrameMessages = class {
26671
+ #app;
26672
+ #window;
26673
+ #document;
26674
+ #session = Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
26675
+ #peers = /* @__PURE__ */ new Map();
26676
+ #closed = false;
26677
+ #listener;
26678
+ #load;
26679
+ #hide;
26680
+ #show;
26681
+ constructor(app, document) {
26682
+ this.#app = app;
26683
+ this.#document = document;
26684
+ this.#window = document.defaultView;
26685
+ this.#listener = (event) => this.#receive(event);
26686
+ this.#load = (event) => {
26687
+ if (event.target?.localName !== "iframe") return;
26688
+ const peer = this.#child(event.target);
26689
+ if (!peer) return;
26690
+ this.#forget(peer.window);
26691
+ this.#send(peer, { kind: "hello" });
26692
+ };
26693
+ this.#window.addEventListener("message", this.#listener);
26694
+ this.#hide = () => this.#disconnect();
26695
+ this.#show = () => this.ready();
26696
+ this.#window.addEventListener("pagehide", this.#hide);
26697
+ this.#window.addEventListener("pageshow", this.#show);
26698
+ document.addEventListener("load", this.#load, true);
26699
+ const parent = this.#parent();
26700
+ if (parent) this.#send(parent, { kind: "hello" });
26701
+ }
26702
+ ready() {
26703
+ if (this.#closed || this.#app.state !== "started") return;
26704
+ const parent = this.#parent();
26705
+ if (parent) this.#send(parent, { kind: "ready" });
26706
+ for (const frame of this.#document.getElementsByTagName("iframe")) {
26707
+ const child = this.#child(frame);
26708
+ if (child) this.#send(child, { kind: "hello" });
26709
+ }
26710
+ }
26711
+ /** Preflight before local dispatch: no queue or silent fallback for an unavailable page. */
26712
+ prepare(descriptor, payload) {
26713
+ const peers = [];
26714
+ if (descriptor.parent) {
26715
+ const parent = this.#parent();
26716
+ if (!parent) throw new Error("This page has no parent frame");
26717
+ peers.push(parent);
26718
+ }
26719
+ if (descriptor.iframe !== void 0) {
26720
+ const target = descriptor.iframe;
26721
+ const node = sourceTarget(target);
26722
+ const frame = typeof target === "string" ? this.#document.getElementById(target) : node instanceof SourceBagNode ? this.#app.dom.getDomNode(node) : null;
26723
+ const child = this.#child(frame);
26724
+ if (!child) throw new Error("iframe destination must be an active Gramlot iframe ID or Source reference");
26725
+ peers.push(child);
26726
+ }
26727
+ const destinations = peers.map((peer) => {
26728
+ const connection = this.#peers.get(peer.window);
26729
+ if (!connection || connection.origin !== peer.origin) throw new Error("Destination page is not ready");
26730
+ return { ...peer, session: connection.session };
26731
+ });
26732
+ assertTransportData(payload);
26733
+ const wire = toTytx(payload);
26734
+ return () => {
26735
+ if (this.#closed) return;
26736
+ for (const peer of destinations) {
26737
+ const current = this.#peer(peer.window);
26738
+ if (!current || current.origin !== peer.origin || this.#peers.get(peer.window)?.session !== peer.session) {
26739
+ throw new Error("Destination page disconnected before publication");
26740
+ }
26741
+ this.#send(peer, { kind: "publish", recipient: peer.session, topic: descriptor.topic, wire });
26742
+ }
26743
+ };
26744
+ }
26745
+ dispose() {
26746
+ if (this.#closed) return;
26747
+ this.#disconnect();
26748
+ this.#closed = true;
26749
+ this.#window.removeEventListener("message", this.#listener);
26750
+ this.#window.removeEventListener("pagehide", this.#hide);
26751
+ this.#window.removeEventListener("pageshow", this.#show);
26752
+ this.#document.removeEventListener("load", this.#load, true);
26753
+ }
26754
+ #disconnect() {
26755
+ for (const [window2, peer] of this.#peers) this.#send({ window: window2, origin: peer.origin }, { kind: "close" });
26756
+ for (const window2 of this.#peers.keys()) this.#forget(window2);
26757
+ }
26758
+ #forget(window2) {
26759
+ this.#peers.get(window2)?.release?.();
26760
+ this.#peers.delete(window2);
26761
+ }
26762
+ #remember(peer, session) {
26763
+ this.#forget(peer.window);
26764
+ const connection = { session, origin: peer.origin };
26765
+ if (peer.node) connection.release = this.#app.src.binding.bindingFor(peer.node).track(() => {
26766
+ this.#send(peer, { kind: "close" });
26767
+ this.#forget(peer.window);
26768
+ });
26769
+ this.#peers.set(peer.window, connection);
26770
+ }
26771
+ #receive(event) {
26772
+ if (this.#closed || event.data?.type !== TYPE) return;
26773
+ const peer = this.#peer(event.source);
26774
+ if (!peer || event.origin !== peer.origin) return;
26775
+ const message = event.data;
26776
+ if (typeof message.session !== "string" || !message.session) return;
26777
+ if (message.kind === "hello") {
26778
+ this.#forget(peer.window);
26779
+ if (message.ready === true) this.#remember(peer, message.session);
26780
+ if (this.#app.state === "started") this.#send(peer, { kind: "ready" });
26781
+ } else if (message.kind === "ready") {
26782
+ const changed = this.#peers.get(peer.window)?.session !== message.session;
26783
+ this.#remember(peer, message.session);
26784
+ if (changed && this.#app.state === "started") this.#send(peer, { kind: "ready" });
26785
+ } else if (message.kind === "close") {
26786
+ if (this.#peers.get(peer.window)?.session === message.session) this.#forget(peer.window);
26787
+ } else if (message.kind === "publish") {
26788
+ if (this.#app.state !== "started" || message.recipient !== this.#session || this.#peers.get(peer.window)?.session !== message.session) return;
26789
+ if (typeof message.topic !== "string" || !message.topic || typeof message.wire !== "string") return;
26790
+ this.#app.publish(message.topic, fromTytx(message.wire));
26791
+ }
26792
+ }
26793
+ #send(peer, message) {
26794
+ peer.window.postMessage({ type: TYPE, session: this.#session, ready: this.#app.state === "started", ...message }, peer.origin === "null" ? "*" : peer.origin);
26795
+ }
26796
+ #parent() {
26797
+ const parent = this.#window.parent;
26798
+ if (parent === this.#window) return null;
26799
+ return { window: parent, origin: this.#origin(this.#document.referrer || this.#document.baseURI) };
26800
+ }
26801
+ #child(frame) {
26802
+ if (frame?.localName !== "iframe" || !frame.isConnected || !frame.contentWindow) return null;
26803
+ const node = this.#app.dom.getBaseSourceNode(frame);
26804
+ if (!node || !this.#app.src.binding.bindingFor(node) || this.#app.dom.getDomNode(node) !== frame) return null;
26805
+ const sandbox = frame.getAttribute("sandbox");
26806
+ const opaque = sandbox !== null && !sandbox.split(/\s+/).includes("allow-same-origin");
26807
+ const origin = opaque ? "null" : this.#origin(frame.hasAttribute("srcdoc") ? this.#document.baseURI : frame.getAttribute("src") || this.#document.baseURI);
26808
+ return { window: frame.contentWindow, origin, node };
26809
+ }
26810
+ #origin(address) {
26811
+ const url = new URL(address, this.#document.baseURI);
26812
+ return url.protocol === "file:" ? "null" : url.origin;
26813
+ }
26814
+ #peer(window2) {
26815
+ const parent = this.#parent();
26816
+ if (parent?.window === window2) return parent;
26817
+ for (const frame of this.#document.getElementsByTagName("iframe")) {
26818
+ const child = this.#child(frame);
26819
+ if (child?.window === window2) return child;
26820
+ }
26821
+ return null;
26822
+ }
26823
+ };
26824
+
26825
+ // src/handlers/subscriptions-handler.js
26826
+ var SubscriptionsHandler = class extends Handler {
26827
+ #topics = /* @__PURE__ */ new Map();
26828
+ #handles = /* @__PURE__ */ new WeakSet();
26829
+ #nodeIds = /* @__PURE__ */ new WeakMap();
26830
+ #sequence = 0;
26831
+ #closed = false;
26832
+ #frames;
26833
+ attach(document) {
26834
+ this.#frames = new FrameMessages(this.gramlot, document);
26835
+ }
26836
+ ready() {
26837
+ this.#frames.ready();
26838
+ }
26839
+ subscribe(topic, callback) {
26840
+ this.#requireOpen();
26841
+ this.#requireTopic(topic);
26842
+ if (typeof callback !== "function") throw new TypeError("subscribe requires a callback");
26843
+ const handle = Object.freeze({});
26844
+ this.#handles.add(handle);
26845
+ if (!this.#topics.has(topic)) this.#topics.set(topic, /* @__PURE__ */ new Map());
26846
+ this.#topics.get(topic).set(handle, callback);
26847
+ return handle;
26848
+ }
26849
+ unsubscribe(handle) {
26850
+ if (!this.#handles.has(handle)) throw new TypeError("Unknown subscription registration");
26851
+ for (const [topic, callbacks] of this.#topics) {
26852
+ if (callbacks.delete(handle) && !callbacks.size) this.#topics.delete(topic);
26853
+ }
26854
+ }
26855
+ publish(topic, payload = {}) {
26856
+ this.#requireOpen();
26857
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
26858
+ throw new TypeError("publish requires one object of named data");
26859
+ }
26860
+ if (typeof topic === "string") return this.#deliver(topic, payload);
26861
+ if (!topic || typeof topic !== "object" || Array.isArray(topic)) {
26862
+ throw new TypeError("publish requires a topic string or descriptor");
26863
+ }
26864
+ const keys = Object.keys(topic);
26865
+ if (keys.some((key) => !["topic", "nodeId", "parent", "iframe"].includes(key))) {
26866
+ throw new Error("This publication route is not implemented yet");
26867
+ }
26868
+ this.#requireTopic(topic.topic);
26869
+ if (topic.parent !== void 0 && typeof topic.parent !== "boolean") throw new TypeError("parent must be boolean");
26870
+ if (topic.iframe === "*") throw new Error("Recursive iframe broadcast is not implemented yet");
26871
+ if ((topic.parent || topic.iframe !== void 0) && Object.hasOwn(topic, "nodeId")) {
26872
+ throw new Error("Interframe node addressing is not implemented yet");
26873
+ }
26874
+ const forward = topic.parent || topic.iframe !== void 0 ? this.#frames.prepare(topic, payload) : null;
26875
+ if (Object.hasOwn(topic, "nodeId")) {
26876
+ const node = this.gramlot.src.binding.nodeIds.get(topic.nodeId);
26877
+ if (!node) throw new Error(`node_id not found: ${topic.nodeId}`);
26878
+ return this.publishNode(node, topic.topic, payload);
26879
+ }
26880
+ this.#deliver(topic.topic, payload);
26881
+ forward?.();
26882
+ }
26883
+ topicFor(node, topic) {
26884
+ this.#requireTopic(topic);
26885
+ node = sourceTarget(node);
26886
+ const binding = this.gramlot.src.binding.bindingFor(node);
26887
+ if (!binding || binding.closed) throw new Error("Topic target is not an active Source node of this page");
26888
+ let id = node.getAttr("node_id");
26889
+ if (id == null) {
26890
+ if (!this.#nodeIds.has(node)) this.#nodeIds.set(node, `gramlot-self-${++this.#sequence}`);
26891
+ id = this.#nodeIds.get(node);
26892
+ }
26893
+ return `${id}_${topic}`;
26894
+ }
26895
+ publishNode(node, topic, payload = {}) {
26896
+ return this.publish(this.topicFor(node, topic), payload);
26897
+ }
26898
+ dispose() {
26899
+ this.#closed = true;
26900
+ this.#frames.dispose();
26901
+ this.#topics.clear();
26902
+ }
26903
+ #deliver(topic, payload) {
26904
+ this.#requireTopic(topic);
26905
+ const callbacks = this.#topics.get(topic);
26906
+ if (!callbacks) return;
26907
+ for (const [handle, callback] of [...callbacks]) {
26908
+ if (this.#closed) break;
26909
+ if (callbacks.has(handle)) callback(payload);
26910
+ }
26911
+ }
26912
+ #requireTopic(topic) {
26913
+ if (typeof topic !== "string" || !topic) throw new TypeError("A topic must be a nonempty string");
26914
+ }
26915
+ #requireOpen() {
26916
+ if (this.#closed) throw new Error("Gramlot subscriptions are disposed");
26917
+ }
26918
+ };
26919
+
26212
26920
  // src/inout.js
26213
26921
  var MAILTO_LIMIT = 2e3;
26214
26922
  function leafText(value) {
@@ -26275,7 +26983,8 @@ var InOut = class {
26275
26983
  return new Promise((resolve, reject) => {
26276
26984
  input.addEventListener("change", async () => {
26277
26985
  try {
26278
- const bag = Bag.fromTytx(await input.files[0].text());
26986
+ const bag = fromTytx(await input.files[0].text());
26987
+ if (!(bag instanceof Bag)) throw new TypeError("the file must contain a typed Bag");
26279
26988
  this.gramlot.data.setItem(path, bag);
26280
26989
  resolve(bag);
26281
26990
  } catch (error) {
@@ -26340,11 +27049,12 @@ var Gramlot = class {
26340
27049
  rootId = "gramlot-root",
26341
27050
  capabilities = [],
26342
27051
  element = null,
26343
- document = globalThis.document,
27052
+ document = element?.ownerDocument ?? globalThis.document,
26344
27053
  transport = null,
26345
27054
  collections = []
26346
27055
  } = {}) {
26347
27056
  this.pageId = pageId;
27057
+ Object.defineProperty(this, "_subscriptions", { value: new SubscriptionsHandler(this) });
26348
27058
  this.capabilities = Object.freeze([...capabilities]);
26349
27059
  this.src = new SourceHandler(this, { collections, destination: element ?? document.getElementById(rootId) });
26350
27060
  this.data = this.src.builder.data;
@@ -26352,6 +27062,7 @@ var Gramlot = class {
26352
27062
  this.dom = new DomHandler(this);
26353
27063
  this.utl = new UtilitiesHandler(this, document);
26354
27064
  this.state = "ready";
27065
+ this._subscriptions.attach(document);
26355
27066
  this.abort = new AbortController();
26356
27067
  if (this.rpc.transport instanceof HttpTransport) {
26357
27068
  this.pagehide = (event) => {
@@ -26361,6 +27072,15 @@ var Gramlot = class {
26361
27072
  this.window = document.defaultView;
26362
27073
  }
26363
27074
  }
27075
+ publish(topic, payload = {}) {
27076
+ return this._subscriptions.publish(topic, payload);
27077
+ }
27078
+ subscribe(topic, callback) {
27079
+ return this._subscriptions.subscribe(topic, callback);
27080
+ }
27081
+ unsubscribe(registration) {
27082
+ this._subscriptions.unsubscribe(registration);
27083
+ }
26364
27084
  start() {
26365
27085
  if (this.state === "disposed") return Promise.reject(new Error("Gramlot is disposed"));
26366
27086
  if (!this.rpc.transport) return Promise.reject(new Error("This Gramlot instance has no server transport"));
@@ -26385,6 +27105,7 @@ var Gramlot = class {
26385
27105
  dispose({ beacon = false } = {}) {
26386
27106
  if (this.state === "disposed") return;
26387
27107
  this.state = "disposed";
27108
+ this._subscriptions.dispose();
26388
27109
  if (this.pagehide) this.window.removeEventListener("pagehide", this.pagehide);
26389
27110
  this.abort.abort();
26390
27111
  for (const request of this.rpc.remoteRequests.values()) request.controller.abort();
@@ -26462,7 +27183,7 @@ var PageBootstrap = class {
26462
27183
  }
26463
27184
  };
26464
27185
 
26465
- // src/server/page.js
27186
+ // src/server/page-base.js
26466
27187
  var SOURCE_METHOD = /* @__PURE__ */ Symbol("gramlot.source");
26467
27188
  var ENDPOINT_METHOD = /* @__PURE__ */ Symbol("gramlot.endpoint");
26468
27189
  var MARKERS = /* @__PURE__ */ new Map([[SOURCE_METHOD, "registerSource"], [ENDPOINT_METHOD, "registerEndpoint"]]);
@@ -26483,6 +27204,22 @@ function declare(PageClass, methodName, marker, auth) {
26483
27204
  }
26484
27205
  var Page = class {
26485
27206
  static title = "Gramlot";
27207
+ static installable = false;
27208
+ static appIcon = null;
27209
+ /** Default root manifest. appIcon is a 512px square PNG below the app root. */
27210
+ manifest({ baseUrl = "./" } = {}) {
27211
+ const { title, appIcon } = this.constructor;
27212
+ if (typeof appIcon !== "string" || !appIcon) throw new TypeError("An installable Page needs appIcon");
27213
+ return {
27214
+ id: baseUrl,
27215
+ name: title,
27216
+ short_name: title,
27217
+ start_url: baseUrl,
27218
+ scope: baseUrl,
27219
+ display: "standalone",
27220
+ icons: [{ src: baseUrl + appIcon.replace(/^\/+/, ""), sizes: "512x512", type: "image/png" }]
27221
+ };
27222
+ }
26486
27223
  static css = [];
26487
27224
  static css_requires = "";
26488
27225
  static js_requires = "";
@@ -26494,8 +27231,8 @@ var Page = class {
26494
27231
  * Mark the own method `methodName` of this page class as a remote Source method,
26495
27232
  * equivalent to Python `@source`; call it after the class.
26496
27233
  *
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.
27234
+ * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035);
27235
+ * the `remote` attribute requests it declaratively (GC-095 §105).
26499
27236
  */
26500
27237
  static registerSource(methodName, { auth = null } = {}) {
26501
27238
  declare(this, methodName, SOURCE_METHOD, auth);
@@ -26506,6 +27243,444 @@ var Page = class {
26506
27243
  declare(this, methodName, ENDPOINT_METHOD, auth);
26507
27244
  }
26508
27245
  };
27246
+
27247
+ // src/server/index-page.js
27248
+ var IndexPage = class extends Page {
27249
+ static title = "Application";
27250
+ static logoUrl = "";
27251
+ static shellId = "index";
27252
+ static navigation = [];
27253
+ static css = ["/themes/gramlot-base/theme.css", "/themes/gramlot-index/theme.css"];
27254
+ main(root) {
27255
+ const families = this.constructor.navigation;
27256
+ const shell = root.div({ class: "index-shell", id: this.constructor.shellId });
27257
+ const sidebar = shell.aside({ class: "index-sidebar", id: "index-sidebar" });
27258
+ const brand = sidebar.header();
27259
+ if (this.constructor.logoUrl) brand.img({ src: this.constructor.logoUrl, alt: this.constructor.title, class: "index-logo" });
27260
+ brand.h1(this.constructor.title);
27261
+ const navigation = sidebar.nav({ "aria-label": "Pages" }).ul({ class: "index-list" });
27262
+ for (const family of families) {
27263
+ const category = navigation.li().details({ open: family === families[0] });
27264
+ category.summary({ tabindex: -1 }).a(family.title, {
27265
+ id: `open-${family.key}`,
27266
+ href: `#panel-${family.key}`,
27267
+ class: "index-family",
27268
+ aria_current: null,
27269
+ tabindex: -1
27270
+ });
27271
+ const examplesList = category.ul({ class: "index-list" });
27272
+ for (const example of family.children) {
27273
+ examplesList.li().a(example.title, {
27274
+ id: `open-${example.key}`,
27275
+ href: example.url,
27276
+ aria_current: null,
27277
+ tabindex: -1
27278
+ });
27279
+ }
27280
+ }
27281
+ shell.div({
27282
+ class: "index-divider",
27283
+ id: "index-sidebar-divider",
27284
+ role: "separator",
27285
+ aria_orientation: "vertical",
27286
+ tabindex: 0,
27287
+ aria_label: "Resize sidebar",
27288
+ aria_controls: "index-sidebar",
27289
+ aria_valuemin: 120,
27290
+ aria_valuemax: 460,
27291
+ aria_valuenow: 240
27292
+ });
27293
+ const content = shell.main({ class: "index-main" });
27294
+ const tabs = content.div({ class: "index-tabs", role: "tablist", aria_label: "Open pages" });
27295
+ tabs.button("Introduction", {
27296
+ type: "button",
27297
+ role: "tab",
27298
+ id: "tab-intro",
27299
+ aria_controls: "panel-intro",
27300
+ aria_selected: "true",
27301
+ tabindex: -1,
27302
+ hidden: false
27303
+ });
27304
+ for (const family of families) {
27305
+ for (const { key, title } of [family, ...family.children]) {
27306
+ tabs.button(title, {
27307
+ type: "button",
27308
+ role: "tab",
27309
+ id: `tab-${key}`,
27310
+ aria_controls: `panel-${key}`,
27311
+ aria_selected: "false",
27312
+ tabindex: -1,
27313
+ hidden: true
27314
+ });
27315
+ }
27316
+ }
27317
+ const panels = content.div({ class: "index-panels" });
27318
+ const intro = panels.section({
27319
+ id: "panel-intro",
27320
+ class: "index-intro",
27321
+ role: "tabpanel",
27322
+ aria_labelledby: "tab-intro",
27323
+ hidden: false
27324
+ });
27325
+ this.introduction(intro);
27326
+ for (const family of families) {
27327
+ const categoryPanel = panels.section({
27328
+ id: `panel-${family.key}`,
27329
+ class: "index-category",
27330
+ role: "tabpanel",
27331
+ aria_labelledby: `tab-${family.key}`,
27332
+ hidden: true
27333
+ });
27334
+ this.groupPanel(categoryPanel, family);
27335
+ for (const example of family.children) this.panel(panels, example);
27336
+ }
27337
+ const footer = shell.footer({ class: "index-footer" });
27338
+ this.footer(footer);
27339
+ this.behavior(shell);
27340
+ }
27341
+ behavior(shell) {
27342
+ shell.dataController({ func: "indexMount", _onStart: true, shell_id: this.constructor.shellId });
27343
+ }
27344
+ introduction(pane) {
27345
+ pane.h2(this.constructor.title);
27346
+ pane.p("Choose a page from the navigation. Open pages remain available in tabs.");
27347
+ }
27348
+ groupPanel(pane, group) {
27349
+ pane.h2(group.title);
27350
+ }
27351
+ footer(footer) {
27352
+ const theme = footer.div({ class: "index-theme" });
27353
+ theme.html_label("Theme", { for: "index-appearance" });
27354
+ const appearance = theme.select({ id: "index-appearance", value: "compact" });
27355
+ appearance.option("Base", { value: "base", selected: false });
27356
+ appearance.option("Compact", { value: "compact", selected: true });
27357
+ const color = footer.div({ class: "index-theme" });
27358
+ color.html_label("Color mode", { for: "index-theme" });
27359
+ const choices = color.select({ id: "index-theme", value: "light" });
27360
+ choices.option("Light", { value: "light", selected: true });
27361
+ choices.option("Dark", { value: "dark", selected: false });
27362
+ const keyboard = footer.div({ class: "index-keyboard" });
27363
+ const label = keyboard.html_label({ for: "keyboard-navigation" });
27364
+ label.input({ type: "checkbox", id: "keyboard-navigation", checked: false });
27365
+ label.span("Keyboard navigation");
27366
+ if (this.constructor.installable) {
27367
+ const app = footer.details({ class: "index-install" });
27368
+ app.summary("Install app");
27369
+ app.button("Install", { type: "button", id: "index-install-button", hidden: true });
27370
+ app.p("", { id: "index-install-status", role: "status" });
27371
+ app.p("Chrome: use Install page as app in the browser menu. Safari on macOS Sonoma or later: File > Add to Dock.");
27372
+ 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.");
27373
+ }
27374
+ }
27375
+ panel(parent, item) {
27376
+ const pane = parent.section({
27377
+ id: `panel-${item.key}`,
27378
+ class: "index-panel",
27379
+ role: "tabpanel",
27380
+ aria_labelledby: `tab-${item.key}`,
27381
+ hidden: true
27382
+ });
27383
+ pane.iframe({ id: `frame-${item.key}`, title: item.title, name: `page-${item.key}` });
27384
+ }
27385
+ };
27386
+
27387
+ // src/index-page-styles.js
27388
+ 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';
27389
+
27390
+ // src/index-theme.js
27391
+ var THEME_READY = "index:theme-ready";
27392
+ var THEME_SET = "index:theme-set";
27393
+ var THEMES = /* @__PURE__ */ new Set(["light", "dark"]);
27394
+ var APPEARANCES = /* @__PURE__ */ new Set(["base", "compact"]);
27395
+
27396
+ // src/index-page-runtime.js
27397
+ function mountIndexPage(renderer, root, onSelection = () => {
27398
+ }, prepareEntry = () => {
27399
+ }) {
27400
+ const shell = renderer.records.get(root).element;
27401
+ const document = shell.ownerDocument;
27402
+ const window2 = document.defaultView;
27403
+ const byId = (id) => document.getElementById(id);
27404
+ const node = (element) => renderer.elements.get(element).node;
27405
+ const set = (element, attrs) => node(element).setAttr(attrs);
27406
+ const keyboard = byId("keyboard-navigation");
27407
+ const theme = byId("index-theme");
27408
+ const appearance = byId("index-appearance");
27409
+ const sidebar = byId("index-sidebar");
27410
+ const sidebarHandle = byId("index-sidebar-divider");
27411
+ const preferencesKey = `gramlot.${shell.id}.preferences:${window2.location.pathname}`;
27412
+ let preferences = {};
27413
+ try {
27414
+ const saved = JSON.parse(window2.localStorage.getItem(preferencesKey));
27415
+ if (saved !== null && typeof saved === "object" && !Array.isArray(saved)) preferences = saved;
27416
+ } catch (error) {
27417
+ if (error.name !== "SyntaxError" && error.name !== "SecurityError") throw error;
27418
+ }
27419
+ const restoreChoice = (control, value, allowed) => {
27420
+ if (!control || !allowed.has(value)) return;
27421
+ set(control, { value });
27422
+ for (const option of control.options) set(option, { selected: option.value === value });
27423
+ };
27424
+ restoreChoice(theme, preferences.theme, THEMES);
27425
+ restoreChoice(appearance, preferences.appearance, APPEARANCES);
27426
+ const families = [...shell.querySelectorAll(".index-sidebar details")];
27427
+ const Bag2 = root.builder.data.constructor;
27428
+ const state = new Bag2();
27429
+ const opened = new Bag2();
27430
+ state.setItem("opened", opened);
27431
+ state.setItem("keyboard", keyboard?.checked ?? false);
27432
+ state.setItem("theme", theme?.value ?? "light");
27433
+ state.setItem("appearance", appearance?.value ?? "compact");
27434
+ const savePreferences = () => {
27435
+ try {
27436
+ window2.localStorage.setItem(preferencesKey, JSON.stringify({
27437
+ theme: state.getItem("theme"),
27438
+ appearance: state.getItem("appearance"),
27439
+ sidebarWidth: state.getItem("preferredSidebarWidth")
27440
+ }));
27441
+ } catch (error) {
27442
+ if (error.name !== "SecurityError" && error.name !== "QuotaExceededError") throw error;
27443
+ }
27444
+ };
27445
+ const entries = /* @__PURE__ */ new Map();
27446
+ const releases = [];
27447
+ const style = root.builder.wrapSource(root.value).style(compactStyle, { media: (appearance?.value ?? "compact") === "compact" ? "all" : "not all" });
27448
+ let drag = null;
27449
+ let disposed = false;
27450
+ let installPrompt = null;
27451
+ const previousTheme = document.documentElement.getAttribute("data-theme");
27452
+ const listen = (element, type, handler) => {
27453
+ if (!element) return;
27454
+ element.addEventListener(type, handler);
27455
+ releases.push(() => element.removeEventListener(type, handler));
27456
+ };
27457
+ const stopDrag = () => {
27458
+ if (!drag) return;
27459
+ const { handle, pointerId } = drag;
27460
+ drag = null;
27461
+ if (!disposed) set(shell, { data_resizing: null });
27462
+ if (handle.hasPointerCapture(pointerId)) handle.releasePointerCapture(pointerId);
27463
+ };
27464
+ const dispose = () => {
27465
+ if (disposed) return;
27466
+ disposed = true;
27467
+ installPrompt = null;
27468
+ stopDrag();
27469
+ for (const release of releases.reverse()) release();
27470
+ if (style.parentBag) style.parentBag.popNode(style.label);
27471
+ if (previousTheme == null) document.documentElement.removeAttribute("data-theme");
27472
+ else document.documentElement.setAttribute("data-theme", previousTheme);
27473
+ };
27474
+ const send = (frame) => frame.contentWindow.postMessage({ type: THEME_SET, theme: state.getItem("theme"), appearance: state.getItem("appearance") }, "*");
27475
+ const applyTheme = () => {
27476
+ document.documentElement.setAttribute("data-theme", state.getItem("theme"));
27477
+ style.setAttr({ media: state.getItem("appearance") === "compact" ? "all" : "not all" });
27478
+ for (const { frame } of entries.values()) if (frame) send(frame);
27479
+ };
27480
+ const updateInspector = () => onSelection(entries, state.getItem("active"));
27481
+ function select(key) {
27482
+ const entry = entries.get(key);
27483
+ if (!opened.getItem(key)) {
27484
+ opened.setItem(key, true);
27485
+ set(entry.tab, { hidden: false });
27486
+ if (entry.frame) set(entry.frame, { src: entry.open.getAttribute("href") });
27487
+ }
27488
+ if (entry.family) set(entry.family, { open: true });
27489
+ for (const [current, item] of entries) {
27490
+ const active = current === key;
27491
+ set(item.tab, { aria_selected: String(active), tabindex: active && state.getItem("keyboard") ? 0 : -1 });
27492
+ set(item.panel, { hidden: !active });
27493
+ if (item.open) set(item.open, { aria_current: active ? "page" : null });
27494
+ }
27495
+ state.setItem("active", key);
27496
+ updateInspector();
27497
+ }
27498
+ function setRatio(entry, value) {
27499
+ const ratio = Math.max(20, Math.min(80, value));
27500
+ state.setItem(`ratio.${entry.key}`, ratio);
27501
+ set(entry.split, { style: `--split-position: ${ratio}%` });
27502
+ set(entry.handle, { aria_valuenow: ratio });
27503
+ }
27504
+ const sidebarMaximum = () => Math.max(120, Math.min(460, Math.floor(window2.innerWidth * 0.6)));
27505
+ const setSidebarWidth = (value, remember = false) => {
27506
+ const maximum = sidebarMaximum();
27507
+ const width = Math.max(120, Math.min(maximum, value));
27508
+ state.setItem("sidebarWidth", width);
27509
+ set(shell, { style: `--sidebar-width: ${width}px` });
27510
+ set(sidebarHandle, { aria_valuenow: width, aria_valuemax: maximum });
27511
+ if (remember) {
27512
+ state.setItem("preferredSidebarWidth", width);
27513
+ savePreferences();
27514
+ }
27515
+ };
27516
+ const beginDrag = (handle, event, move) => {
27517
+ if (event.button !== 0) return;
27518
+ stopDrag();
27519
+ handle.setPointerCapture(event.pointerId);
27520
+ drag = { handle, pointerId: event.pointerId, move };
27521
+ set(shell, { data_resizing: "true" });
27522
+ event.preventDefault();
27523
+ };
27524
+ try {
27525
+ const install = byId("index-install-button");
27526
+ if (install) {
27527
+ listen(window2, "beforeinstallprompt", (event) => {
27528
+ event.preventDefault();
27529
+ installPrompt = event;
27530
+ set(install, { hidden: false, disabled: false });
27531
+ });
27532
+ listen(window2, "appinstalled", () => {
27533
+ installPrompt = null;
27534
+ set(install, { hidden: true });
27535
+ node(byId("index-install-status")).setValue("App installed.");
27536
+ });
27537
+ listen(install, "click", async () => {
27538
+ if (!installPrompt) return;
27539
+ const prompt = installPrompt;
27540
+ installPrompt = null;
27541
+ set(install, { disabled: true });
27542
+ try {
27543
+ await prompt.prompt();
27544
+ const { outcome } = await prompt.userChoice;
27545
+ if (!disposed) node(byId("index-install-status")).setValue(
27546
+ outcome === "accepted" ? "Installation accepted." : "Installation cancelled. You can also use the browser menu."
27547
+ );
27548
+ } catch (error) {
27549
+ if (!disposed) node(byId("index-install-status")).setValue(`Installation failed: ${error.message}`);
27550
+ } finally {
27551
+ if (!disposed) set(install, { hidden: true });
27552
+ }
27553
+ });
27554
+ }
27555
+ set(shell, { data_resizing: null });
27556
+ const savedWidth = preferences.sidebarWidth;
27557
+ const width = typeof savedWidth === "number" && Number.isFinite(savedWidth) && savedWidth >= 120 && savedWidth <= 460 ? savedWidth : sidebar.getBoundingClientRect().width || Number(sidebarHandle.getAttribute("aria-valuenow"));
27558
+ state.setItem("preferredSidebarWidth", width);
27559
+ setSidebarWidth(width);
27560
+ listen(sidebarHandle, "keydown", (event) => {
27561
+ const current = state.getItem("sidebarWidth");
27562
+ const value = event.key === "ArrowLeft" ? current - 10 : event.key === "ArrowRight" ? current + 10 : event.key === "Home" ? 120 : event.key === "End" ? sidebarMaximum() : null;
27563
+ if (value == null) return;
27564
+ event.preventDefault();
27565
+ setSidebarWidth(value, true);
27566
+ });
27567
+ listen(sidebarHandle, "pointerdown", (event) => beginDrag(
27568
+ sidebarHandle,
27569
+ event,
27570
+ (x) => setSidebarWidth(Math.round(x - shell.getBoundingClientRect().left), true)
27571
+ ));
27572
+ listen(sidebarHandle, "lostpointercapture", () => {
27573
+ if (drag?.handle === sidebarHandle) stopDrag();
27574
+ });
27575
+ listen(window2, "resize", () => setSidebarWidth(state.getItem("preferredSidebarWidth")));
27576
+ for (const tab of shell.querySelectorAll(".index-tabs button")) {
27577
+ const key = tab.id.slice("tab-".length);
27578
+ const entry = {
27579
+ key,
27580
+ tab,
27581
+ panel: byId(`panel-${key}`),
27582
+ open: key === "intro" ? null : byId(`open-${key}`)
27583
+ };
27584
+ entries.set(key, entry);
27585
+ if (!tab.hidden) opened.setItem(key, true);
27586
+ if (tab.getAttribute("aria-selected") === "true") state.setItem("active", key);
27587
+ listen(tab, "click", () => select(key));
27588
+ if (entry.open) listen(entry.open, "click", (event) => {
27589
+ event.preventDefault();
27590
+ select(key);
27591
+ });
27592
+ listen(tab, "keydown", (event) => {
27593
+ if (!state.getItem("keyboard") || !["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
27594
+ const keys = [...entries.keys()].filter((key2) => opened.getItem(key2));
27595
+ const index = keys.indexOf(key);
27596
+ const next = event.key === "Home" ? 0 : event.key === "End" ? keys.length - 1 : (index + (event.key === "ArrowRight" ? 1 : -1) + keys.length) % keys.length;
27597
+ event.preventDefault();
27598
+ select(keys[next]);
27599
+ entries.get(keys[next]).tab.focus();
27600
+ });
27601
+ if (key === "intro") continue;
27602
+ entry.family = entry.open.closest("details");
27603
+ prepareEntry(entry, { byId, node, set, listen });
27604
+ if (entry.panel.classList.contains("index-category")) continue;
27605
+ entry.frame = byId(`frame-${key}`);
27606
+ entry.split = byId(`split-${key}`);
27607
+ entry.handle = byId(`divider-${key}`);
27608
+ if (entry.handle) state.setItem(`ratio.${key}`, Number(entry.handle.getAttribute("aria-valuenow")));
27609
+ listen(entry.frame, "load", () => send(entry.frame));
27610
+ if (!entry.handle) continue;
27611
+ listen(entry.handle, "keydown", (event) => {
27612
+ const current = state.getItem(`ratio.${key}`);
27613
+ const value = event.key === "ArrowLeft" ? current - 5 : event.key === "ArrowRight" ? current + 5 : event.key === "Home" ? 20 : event.key === "End" ? 80 : null;
27614
+ if (value == null) return;
27615
+ event.preventDefault();
27616
+ setRatio(entry, value);
27617
+ });
27618
+ listen(entry.handle, "pointerdown", (event) => beginDrag(entry.handle, event, (x) => {
27619
+ const bounds = entry.split.getBoundingClientRect();
27620
+ if (bounds.width > 0) setRatio(entry, Math.round((x - bounds.left) * 100 / bounds.width));
27621
+ }));
27622
+ listen(entry.handle, "lostpointercapture", () => {
27623
+ if (drag?.handle === entry.handle) stopDrag();
27624
+ });
27625
+ }
27626
+ listen(document, "pointermove", (event) => {
27627
+ if (!drag || event.pointerId !== drag.pointerId) return;
27628
+ drag.move(event.clientX);
27629
+ });
27630
+ for (const type of ["pointerup", "pointercancel"]) listen(document, type, (event) => {
27631
+ if (drag && event.pointerId === drag.pointerId) stopDrag();
27632
+ });
27633
+ for (const family of families) listen(family, "toggle", () => set(family, { open: family.open }));
27634
+ listen(keyboard, "change", () => {
27635
+ state.setItem("keyboard", keyboard?.checked ?? false);
27636
+ set(keyboard, { checked: keyboard?.checked ?? false });
27637
+ for (const [key, entry] of entries) {
27638
+ if (entry.open) set(entry.open, { tabindex: keyboard?.checked ?? false ? 0 : -1 });
27639
+ set(entry.tab, { tabindex: (keyboard?.checked ?? false) && key === state.getItem("active") ? 0 : -1 });
27640
+ }
27641
+ });
27642
+ listen(appearance, "change", () => {
27643
+ if (!APPEARANCES.has(appearance?.value ?? "compact")) throw new Error("Index appearance must be base or compact");
27644
+ state.setItem("appearance", appearance?.value ?? "compact");
27645
+ set(appearance, { value: appearance?.value ?? "compact" });
27646
+ for (const option of appearance.options) set(option, { selected: option.value === (appearance?.value ?? "compact") });
27647
+ applyTheme();
27648
+ savePreferences();
27649
+ });
27650
+ listen(theme, "change", () => {
27651
+ if (!THEMES.has(theme?.value ?? "light")) throw new Error("Index theme must be light or dark");
27652
+ state.setItem("theme", theme?.value ?? "light");
27653
+ set(theme, { value: theme?.value ?? "light" });
27654
+ for (const option of theme.options) set(option, { selected: option.value === (theme?.value ?? "light") });
27655
+ applyTheme();
27656
+ savePreferences();
27657
+ });
27658
+ listen(window2, "message", (event) => {
27659
+ if (event.data?.type !== THEME_READY) return;
27660
+ for (const { frame } of entries.values()) {
27661
+ if (frame && frame.contentWindow === event.source) {
27662
+ send(frame);
27663
+ updateInspector();
27664
+ break;
27665
+ }
27666
+ }
27667
+ });
27668
+ applyTheme();
27669
+ updateInspector();
27670
+ renderer.onDispose(root, dispose);
27671
+ } catch (error) {
27672
+ dispose();
27673
+ throw error;
27674
+ }
27675
+ return { dispose };
27676
+ }
27677
+ var IndexLogic = class {
27678
+ indexMount(node, { shell_id }) {
27679
+ const renderer = this.page.src.renderer;
27680
+ const element = renderer.destination.ownerDocument.getElementById(shell_id);
27681
+ this.index = mountIndexPage(renderer, renderer.elements.get(element).node);
27682
+ }
27683
+ };
26509
27684
  export {
26510
27685
  Bag,
26511
27686
  BagNode,
@@ -26518,11 +27693,14 @@ export {
26518
27693
  Handler,
26519
27694
  HttpTransport,
26520
27695
  InOut,
27696
+ IndexLogic,
27697
+ IndexPage,
26521
27698
  Page,
26522
27699
  PageBootstrap,
26523
27700
  References,
26524
27701
  RpcError,
26525
27702
  RpcHandler,
26526
27703
  SourceHandler,
26527
- UtilitiesHandler
27704
+ UtilitiesHandler,
27705
+ mountIndexPage
26528
27706
  };