@gramlot/gramlot 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/gramlot.js CHANGED
@@ -64,13 +64,13 @@ var require_conventions = __commonJS({
64
64
  function hasOwn(object, key) {
65
65
  return Object.prototype.hasOwnProperty.call(object, key);
66
66
  }
67
- function assign(target, source) {
67
+ function assign(target, source2) {
68
68
  if (target === null || typeof target !== "object") {
69
69
  throw new TypeError("target is not an object");
70
70
  }
71
- for (var key in source) {
72
- if (hasOwn(source, key)) {
73
- target[key] = source[key];
71
+ for (var key in source2) {
72
+ if (hasOwn(source2, key)) {
73
+ target[key] = source2[key];
74
74
  }
75
75
  }
76
76
  return target;
@@ -5442,18 +5442,18 @@ var require_sax = __commonJS({
5442
5442
  function XMLReader() {
5443
5443
  }
5444
5444
  XMLReader.prototype = {
5445
- parse: function(source, defaultNSMap, entityMap) {
5445
+ parse: function(source2, defaultNSMap, entityMap) {
5446
5446
  var domBuilder = this.domBuilder;
5447
5447
  domBuilder.startDocument();
5448
5448
  _copy(defaultNSMap, defaultNSMap = /* @__PURE__ */ Object.create(null));
5449
- parse2(source, defaultNSMap, entityMap, domBuilder, this.errorHandler);
5449
+ parse2(source2, defaultNSMap, entityMap, domBuilder, this.errorHandler);
5450
5450
  domBuilder.endDocument();
5451
5451
  }
5452
5452
  };
5453
5453
  var ENTITY_REG = /&#?\w+;?/g;
5454
- function parse2(source, defaultNSMapCopy, entityMap, domBuilder, errorHandler) {
5454
+ function parse2(source2, defaultNSMapCopy, entityMap, domBuilder, errorHandler) {
5455
5455
  var isHTML = isHTMLMimeType(domBuilder.mimeType);
5456
- if (source.indexOf(g.UNICODE_REPLACEMENT_CHARACTER) >= 0) {
5456
+ if (source2.indexOf(g.UNICODE_REPLACEMENT_CHARACTER) >= 0) {
5457
5457
  errorHandler.warning("Unicode replacement character detected, source encoding issues?");
5458
5458
  }
5459
5459
  function fixedFromCharCode(code) {
@@ -5488,7 +5488,7 @@ var require_sax = __commonJS({
5488
5488
  }
5489
5489
  function appendText(end2) {
5490
5490
  if (end2 > start) {
5491
- var xt = source.substring(start, end2).replace(ENTITY_REG, entityReplacer);
5491
+ var xt = source2.substring(start, end2).replace(ENTITY_REG, entityReplacer);
5492
5492
  locator && position(start);
5493
5493
  domBuilder.characters(xt, 0, end2 - start);
5494
5494
  start = end2;
@@ -5499,7 +5499,7 @@ var require_sax = __commonJS({
5499
5499
  var linePattern = /\r\n?|\n|$/g;
5500
5500
  var locator = domBuilder.locator;
5501
5501
  function position(p, m) {
5502
- while (p >= lineEnd && (m = linePattern.exec(source))) {
5502
+ while (p >= lineEnd && (m = linePattern.exec(source2))) {
5503
5503
  lineStart = lineEnd;
5504
5504
  lineEnd = m.index + m[0].length;
5505
5505
  locator.lineNumber++;
@@ -5511,14 +5511,14 @@ var require_sax = __commonJS({
5511
5511
  var start = 0;
5512
5512
  while (true) {
5513
5513
  try {
5514
- var tagStart = source.indexOf("<", start);
5514
+ var tagStart = source2.indexOf("<", start);
5515
5515
  if (tagStart < 0) {
5516
5516
  if (!isHTML && unclosedTags.length > 0) {
5517
5517
  return errorHandler.fatalError("unclosed xml tag(s): " + unclosedTags.join(", "));
5518
5518
  }
5519
- if (!source.substring(start).match(/^\s*$/)) {
5519
+ if (!source2.substring(start).match(/^\s*$/)) {
5520
5520
  var doc = domBuilder.doc;
5521
- var text = doc.createTextNode(source.substring(start));
5521
+ var text = doc.createTextNode(source2.substring(start));
5522
5522
  if (doc.documentElement) {
5523
5523
  return errorHandler.error("Extra content at the end of the document");
5524
5524
  }
@@ -5528,17 +5528,17 @@ var require_sax = __commonJS({
5528
5528
  return;
5529
5529
  }
5530
5530
  if (tagStart > start) {
5531
- var fromSource = source.substring(start, tagStart);
5531
+ var fromSource = source2.substring(start, tagStart);
5532
5532
  if (!isHTML && unclosedTags.length === 0) {
5533
5533
  fromSource = fromSource.replace(new RegExp(g.S_OPT.source, "g"), "");
5534
5534
  fromSource && errorHandler.error("Unexpected content outside root element: '" + fromSource + "'");
5535
5535
  }
5536
5536
  appendText(tagStart);
5537
5537
  }
5538
- switch (source.charAt(tagStart + 1)) {
5538
+ switch (source2.charAt(tagStart + 1)) {
5539
5539
  case "/":
5540
- var end = source.indexOf(">", tagStart + 2);
5541
- var tagNameRaw = source.substring(tagStart + 2, end > 0 ? end : void 0);
5540
+ var end = source2.indexOf(">", tagStart + 2);
5541
+ var tagNameRaw = source2.substring(tagStart + 2, end > 0 ? end : void 0);
5542
5542
  if (!tagNameRaw) {
5543
5543
  return errorHandler.fatalError("end tag name missing");
5544
5544
  }
@@ -5589,17 +5589,17 @@ var require_sax = __commonJS({
5589
5589
  // end element
5590
5590
  case "?":
5591
5591
  locator && position(tagStart);
5592
- end = parseProcessingInstruction(source, tagStart, domBuilder, errorHandler);
5592
+ end = parseProcessingInstruction(source2, tagStart, domBuilder, errorHandler);
5593
5593
  break;
5594
5594
  case "!":
5595
5595
  locator && position(tagStart);
5596
- end = parseDoctypeCommentOrCData(source, tagStart, domBuilder, errorHandler, isHTML);
5596
+ end = parseDoctypeCommentOrCData(source2, tagStart, domBuilder, errorHandler, isHTML);
5597
5597
  break;
5598
5598
  default:
5599
5599
  locator && position(tagStart);
5600
5600
  var el = new ElementAttributes();
5601
5601
  var currentNSMap = parseStack[parseStack.length - 1].currentNSMap;
5602
- var end = parseElementStartPart(source, tagStart, el, currentNSMap, entityReplacer, errorHandler, isHTML);
5602
+ var end = parseElementStartPart(source2, tagStart, el, currentNSMap, entityReplacer, errorHandler, isHTML);
5603
5603
  var len = el.length;
5604
5604
  if (!el.closed) {
5605
5605
  if (isHTML && conventions.isHTMLVoidElement(el.tagName)) {
@@ -5626,7 +5626,7 @@ var require_sax = __commonJS({
5626
5626
  }
5627
5627
  }
5628
5628
  if (isHTML && !el.closed) {
5629
- end = parseHtmlSpecialContent(source, end, el.tagName, entityReplacer, domBuilder);
5629
+ end = parseHtmlSpecialContent(source2, end, el.tagName, entityReplacer, domBuilder);
5630
5630
  } else {
5631
5631
  end++;
5632
5632
  }
@@ -5652,7 +5652,7 @@ var require_sax = __commonJS({
5652
5652
  t.columnNumber = f.columnNumber;
5653
5653
  return t;
5654
5654
  }
5655
- function parseElementStartPart(source, start, el, currentNSMap, entityReplacer, errorHandler, isHTML) {
5655
+ function parseElementStartPart(source2, start, el, currentNSMap, entityReplacer, errorHandler, isHTML) {
5656
5656
  function addAttribute(qname, value2, startIndex) {
5657
5657
  if (hasOwn(el.attributeNames, qname)) {
5658
5658
  return errorHandler.fatalError("Attribute " + qname + " redefined");
@@ -5675,14 +5675,14 @@ var require_sax = __commonJS({
5675
5675
  var p = ++start;
5676
5676
  var s = S_TAG;
5677
5677
  while (true) {
5678
- var c = source.charAt(p);
5678
+ var c = source2.charAt(p);
5679
5679
  if (s === S_TAG && c === "<") {
5680
- throw new Error("unexpected < in tag name: " + source.slice(start, p));
5680
+ throw new Error("unexpected < in tag name: " + source2.slice(start, p));
5681
5681
  }
5682
5682
  switch (c) {
5683
5683
  case "=":
5684
5684
  if (s === S_ATTR) {
5685
- attrName = source.slice(start, p);
5685
+ attrName = source2.slice(start, p);
5686
5686
  s = S_EQ;
5687
5687
  } else if (s === S_ATTR_SPACE) {
5688
5688
  s = S_EQ;
@@ -5695,19 +5695,19 @@ var require_sax = __commonJS({
5695
5695
  if (s === S_EQ || s === S_ATTR) {
5696
5696
  if (s === S_ATTR) {
5697
5697
  errorHandler.warning('attribute value must after "="');
5698
- attrName = source.slice(start, p);
5698
+ attrName = source2.slice(start, p);
5699
5699
  }
5700
5700
  start = p + 1;
5701
- p = source.indexOf(c, start);
5701
+ p = source2.indexOf(c, start);
5702
5702
  if (p > 0) {
5703
- value = source.slice(start, p);
5703
+ value = source2.slice(start, p);
5704
5704
  addAttribute(attrName, value, start - 1);
5705
5705
  s = S_ATTR_END;
5706
5706
  } else {
5707
5707
  throw new Error("attribute value no end '" + c + "' match");
5708
5708
  }
5709
5709
  } else if (s == S_ATTR_NOQUOT_VALUE) {
5710
- value = source.slice(start, p);
5710
+ value = source2.slice(start, p);
5711
5711
  addAttribute(attrName, value, start);
5712
5712
  errorHandler.warning('attribute "' + attrName + '" missed start quot(' + c + ")!!");
5713
5713
  start = p + 1;
@@ -5719,7 +5719,7 @@ var require_sax = __commonJS({
5719
5719
  case "/":
5720
5720
  switch (s) {
5721
5721
  case S_TAG:
5722
- el.setTagName(source.slice(start, p));
5722
+ el.setTagName(source2.slice(start, p));
5723
5723
  case S_ATTR_END:
5724
5724
  case S_TAG_SPACE:
5725
5725
  case S_TAG_CLOSE:
@@ -5739,13 +5739,13 @@ var require_sax = __commonJS({
5739
5739
  case "":
5740
5740
  errorHandler.error("unexpected end of input");
5741
5741
  if (s == S_TAG) {
5742
- el.setTagName(source.slice(start, p));
5742
+ el.setTagName(source2.slice(start, p));
5743
5743
  }
5744
5744
  return p;
5745
5745
  case ">":
5746
5746
  switch (s) {
5747
5747
  case S_TAG:
5748
- el.setTagName(source.slice(start, p));
5748
+ el.setTagName(source2.slice(start, p));
5749
5749
  case S_ATTR_END:
5750
5750
  case S_TAG_SPACE:
5751
5751
  case S_TAG_CLOSE:
@@ -5754,7 +5754,7 @@ var require_sax = __commonJS({
5754
5754
  case S_ATTR_NOQUOT_VALUE:
5755
5755
  //Compatible state
5756
5756
  case S_ATTR:
5757
- value = source.slice(start, p);
5757
+ value = source2.slice(start, p);
5758
5758
  if (value.slice(-1) === "/") {
5759
5759
  el.closed = true;
5760
5760
  value = value.slice(0, -1);
@@ -5786,15 +5786,15 @@ var require_sax = __commonJS({
5786
5786
  if (c <= " ") {
5787
5787
  switch (s) {
5788
5788
  case S_TAG:
5789
- el.setTagName(source.slice(start, p));
5789
+ el.setTagName(source2.slice(start, p));
5790
5790
  s = S_TAG_SPACE;
5791
5791
  break;
5792
5792
  case S_ATTR:
5793
- attrName = source.slice(start, p);
5793
+ attrName = source2.slice(start, p);
5794
5794
  s = S_ATTR_SPACE;
5795
5795
  break;
5796
5796
  case S_ATTR_NOQUOT_VALUE:
5797
- var value = source.slice(start, p);
5797
+ var value = source2.slice(start, p);
5798
5798
  errorHandler.warning('attribute "' + value + '" missed quot(")!!');
5799
5799
  addAttribute(attrName, value, start);
5800
5800
  case S_ATTR_END:
@@ -5898,17 +5898,17 @@ var require_sax = __commonJS({
5898
5898
  return true;
5899
5899
  }
5900
5900
  }
5901
- function parseHtmlSpecialContent(source, elStartEnd, tagName, entityReplacer, domBuilder) {
5901
+ function parseHtmlSpecialContent(source2, elStartEnd, tagName, entityReplacer, domBuilder) {
5902
5902
  var isEscapableRaw = isHTMLEscapableRawTextElement(tagName);
5903
5903
  if (isEscapableRaw || isHTMLRawTextElement(tagName)) {
5904
5904
  var closeTag = new RegExp("</" + tagName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ">", "ig");
5905
5905
  closeTag.lastIndex = elStartEnd;
5906
- var match = closeTag.exec(source);
5906
+ var match = closeTag.exec(source2);
5907
5907
  var elEndStart = match ? match.index : -1;
5908
5908
  if (elEndStart < 0) {
5909
5909
  return elStartEnd + 1;
5910
5910
  }
5911
- var text = source.substring(elStartEnd + 1, elEndStart);
5911
+ var text = source2.substring(elStartEnd + 1, elEndStart);
5912
5912
  if (isEscapableRaw) {
5913
5913
  text = text.replace(ENTITY_REG, entityReplacer);
5914
5914
  }
@@ -5917,18 +5917,18 @@ var require_sax = __commonJS({
5917
5917
  }
5918
5918
  return elStartEnd + 1;
5919
5919
  }
5920
- function _copy(source, target) {
5921
- for (var n in source) {
5922
- if (hasOwn(source, n)) {
5923
- target[n] = source[n];
5920
+ function _copy(source2, target) {
5921
+ for (var n in source2) {
5922
+ if (hasOwn(source2, n)) {
5923
+ target[n] = source2[n];
5924
5924
  }
5925
5925
  }
5926
5926
  }
5927
- function parseUtils(source, start) {
5927
+ function parseUtils(source2, start) {
5928
5928
  var index = start;
5929
5929
  function char(n) {
5930
5930
  n = n || 0;
5931
- return source.charAt(index + n);
5931
+ return source2.charAt(index + n);
5932
5932
  }
5933
5933
  function skip(n) {
5934
5934
  n = n || 1;
@@ -5936,7 +5936,7 @@ var require_sax = __commonJS({
5936
5936
  }
5937
5937
  function skipBlanks() {
5938
5938
  var blanks = 0;
5939
- while (index < source.length) {
5939
+ while (index < source2.length) {
5940
5940
  var c = char();
5941
5941
  if (c !== " " && c !== "\n" && c !== " " && c !== "\r") {
5942
5942
  return blanks;
@@ -5947,13 +5947,13 @@ var require_sax = __commonJS({
5947
5947
  return -1;
5948
5948
  }
5949
5949
  function substringFromIndex() {
5950
- return source.substring(index);
5950
+ return source2.substring(index);
5951
5951
  }
5952
5952
  function substringStartsWith(text) {
5953
- return source.substring(index, index + text.length) === text;
5953
+ return source2.substring(index, index + text.length) === text;
5954
5954
  }
5955
5955
  function substringStartsWithCaseInsensitive(text) {
5956
- return source.substring(index, index + text.length).toUpperCase() === text.toUpperCase();
5956
+ return source2.substring(index, index + text.length).toUpperCase() === text.toUpperCase();
5957
5957
  }
5958
5958
  function getMatch(args) {
5959
5959
  var expr = g.reg("^", args);
@@ -5971,7 +5971,7 @@ var require_sax = __commonJS({
5971
5971
  },
5972
5972
  getMatch,
5973
5973
  getSource: function() {
5974
- return source;
5974
+ return source2;
5975
5975
  },
5976
5976
  skip,
5977
5977
  skipBlanks,
@@ -5994,14 +5994,14 @@ var require_sax = __commonJS({
5994
5994
  p2.skip(match[0].length);
5995
5995
  return match[0];
5996
5996
  }
5997
- var source = p.getSource();
5997
+ var source2 = p.getSource();
5998
5998
  if (p.char() === "[") {
5999
5999
  p.skip(1);
6000
6000
  var intSubsetStart = p.getIndex();
6001
- while (p.getIndex() < source.length) {
6001
+ while (p.getIndex() < source2.length) {
6002
6002
  p.skipBlanks();
6003
6003
  if (p.char() === "]") {
6004
- var internalSubset = source.substring(intSubsetStart, p.getIndex());
6004
+ var internalSubset = source2.substring(intSubsetStart, p.getIndex());
6005
6005
  p.skip(1);
6006
6006
  return internalSubset;
6007
6007
  }
@@ -6039,8 +6039,8 @@ var require_sax = __commonJS({
6039
6039
  return errorHandler.fatalError("doctype internal subset is not well-formed, missing ]");
6040
6040
  }
6041
6041
  }
6042
- function parseDoctypeCommentOrCData(source, start, domBuilder, errorHandler, isHTML) {
6043
- var p = parseUtils(source, start);
6042
+ function parseDoctypeCommentOrCData(source2, start, domBuilder, errorHandler, isHTML) {
6043
+ var p = parseUtils(source2, start);
6044
6044
  switch (isHTML ? p.char(2).toUpperCase() : p.char(2)) {
6045
6045
  case "-":
6046
6046
  var comment = p.getMatch(g.Comment);
@@ -6131,8 +6131,8 @@ var require_sax = __commonJS({
6131
6131
  return errorHandler.fatalError('Not well-formed XML starting with "<!" at position ' + start);
6132
6132
  }
6133
6133
  }
6134
- function parseProcessingInstruction(source, start, domBuilder, errorHandler) {
6135
- var match = source.substring(start).match(g.PI);
6134
+ function parseProcessingInstruction(source2, start, domBuilder, errorHandler) {
6135
+ var match = source2.substring(start).match(g.PI);
6136
6136
  if (!match) {
6137
6137
  return errorHandler.fatalError("Invalid processing instruction starting at position " + start);
6138
6138
  }
@@ -6142,7 +6142,7 @@ var require_sax = __commonJS({
6142
6142
  "processing instruction at position " + start + " is an xml declaration which is only at the start of the document"
6143
6143
  );
6144
6144
  }
6145
- if (!g.XMLDecl.test(source.substring(start))) {
6145
+ if (!g.XMLDecl.test(source2.substring(start))) {
6146
6146
  return errorHandler.fatalError("xml declaration is not well-formed");
6147
6147
  }
6148
6148
  }
@@ -6236,7 +6236,7 @@ var require_dom_parser = __commonJS({
6236
6236
  this.locator = !!options.locator;
6237
6237
  this.xmlns = this.assign(/* @__PURE__ */ Object.create(null), options.xmlns);
6238
6238
  }
6239
- DOMParser4.prototype.parseFromString = function(source, mimeType) {
6239
+ DOMParser4.prototype.parseFromString = function(source2, mimeType) {
6240
6240
  if (!isValidMimeType(mimeType)) {
6241
6241
  throw new TypeError('DOMParser.parseFromString: the provided mimeType "' + mimeType + '" is not valid.');
6242
6242
  }
@@ -6264,10 +6264,10 @@ var require_dom_parser = __commonJS({
6264
6264
  sax2.errorHandler = domBuilder;
6265
6265
  sax2.domBuilder = domBuilder;
6266
6266
  var isXml = !conventions.isHTMLMimeType(mimeType);
6267
- if (isXml && typeof source !== "string") {
6267
+ if (isXml && typeof source2 !== "string") {
6268
6268
  sax2.errorHandler.fatalError("source is not a string");
6269
6269
  }
6270
- sax2.parse(this.normalizeLineEndings(String(source)), defaultNSMap, entityMap);
6270
+ sax2.parse(this.normalizeLineEndings(String(source2)), defaultNSMap, entityMap);
6271
6271
  if (!domBuilder.doc.documentElement) {
6272
6272
  sax2.errorHandler.fatalError("missing root element");
6273
6273
  }
@@ -12839,7 +12839,7 @@ var Bag = class _Bag {
12839
12839
  *
12840
12840
  * @param {Object} [source=null] - Optional dict to initialize from.
12841
12841
  */
12842
- constructor(source = null) {
12842
+ constructor(source2 = null) {
12843
12843
  this._nodes = new BagNodeContainer();
12844
12844
  this._backref = false;
12845
12845
  this._parent = null;
@@ -12848,8 +12848,8 @@ var Bag = class _Bag {
12848
12848
  this._updSubscribers = {};
12849
12849
  this._insSubscribers = {};
12850
12850
  this._delSubscribers = {};
12851
- if (source) {
12852
- this._loadSource(source);
12851
+ if (source2) {
12852
+ this._loadSource(source2);
12853
12853
  }
12854
12854
  }
12855
12855
  // -------------------------------------------------------------------------
@@ -14206,10 +14206,10 @@ var Bag = class _Bag {
14206
14206
  * @param {boolean} [ignoreNone=false] - Optional extension: preserve existing
14207
14207
  * values when the incoming value is null. It is not the mode argument.
14208
14208
  */
14209
- update(source, mode = null, reason = null, ignoreNone = false) {
14210
- if (!(source instanceof _Bag)) {
14211
- for (const label in source) {
14212
- const value = source[label];
14209
+ update(source2, mode = null, reason = null, ignoreNone = false) {
14210
+ if (!(source2 instanceof _Bag)) {
14211
+ for (const label in source2) {
14212
+ const value = source2[label];
14213
14213
  if (!ignoreNone || value !== null || !this._nodes.has(label)) {
14214
14214
  this.setItem(
14215
14215
  label,
@@ -14226,7 +14226,7 @@ var Bag = class _Bag {
14226
14226
  }
14227
14227
  return;
14228
14228
  }
14229
- for (const incoming of [...source]) {
14229
+ for (const incoming of [...source2]) {
14230
14230
  const label = incoming.label;
14231
14231
  const resolver = mode === "static" ? incoming.resolver : null;
14232
14232
  const value = resolver ? null : incoming.getValue();
@@ -14348,13 +14348,13 @@ var Bag = class _Bag {
14348
14348
  * bag.replace(other);
14349
14349
  * // bag now has only 'x' = 10
14350
14350
  */
14351
- _loadSource(source) {
14352
- if (source == null) return this;
14351
+ _loadSource(source2) {
14352
+ if (source2 == null) return this;
14353
14353
  const prepared = this.createChildBag();
14354
- if (source instanceof _Bag) {
14355
- prepared._fillFromBag(source);
14356
- } else if (typeof source === "object" && !Array.isArray(source)) {
14357
- prepared._fillFromDict(source);
14354
+ if (source2 instanceof _Bag) {
14355
+ prepared._fillFromBag(source2);
14356
+ } else if (typeof source2 === "object" && !Array.isArray(source2)) {
14357
+ prepared._fillFromDict(source2);
14358
14358
  } else {
14359
14359
  return this;
14360
14360
  }
@@ -14702,19 +14702,19 @@ ${" ".repeat(depth)}</${tag2}>`;
14702
14702
  * @param {string} [options.tagAttribute=null] - If set, save XML tag name as this attribute on each node.
14703
14703
  * @returns {Bag} Reconstructed Bag hierarchy.
14704
14704
  */
14705
- static fromXml(source, options = {}) {
14705
+ static fromXml(source2, options = {}) {
14706
14706
  const { tagAttribute = null } = options;
14707
14707
  let doc;
14708
14708
  if (typeof DOMParser !== "undefined") {
14709
14709
  const parser = new DOMParser();
14710
- doc = parser.parseFromString(source, "application/xml");
14710
+ doc = parser.parseFromString(source2, "application/xml");
14711
14711
  const parseError = doc.querySelector("parsererror");
14712
14712
  if (parseError) {
14713
14713
  throw new Error(`XML parse error: ${parseError.textContent}`);
14714
14714
  }
14715
14715
  } else {
14716
14716
  const parser = new import_xmldom2.DOMParser();
14717
- doc = parser.parseFromString(source, "application/xml");
14717
+ doc = parser.parseFromString(source2, "application/xml");
14718
14718
  }
14719
14719
  return this._xmlElementToBag(doc.documentElement, tagAttribute);
14720
14720
  }
@@ -14848,14 +14848,14 @@ ${" ".repeat(depth)}</${tag2}>`;
14848
14848
  * @param {string} [listJoiner=null] - If provided, join string arrays with this separator.
14849
14849
  * @returns {Bag} Deserialized Bag.
14850
14850
  */
14851
- static fromJson(source, listJoiner = null) {
14852
- if (typeof source === "string") {
14853
- source = fromTytx(source);
14851
+ static fromJson(source2, listJoiner = null) {
14852
+ if (typeof source2 === "string") {
14853
+ source2 = fromTytx(source2);
14854
14854
  }
14855
- if (!Array.isArray(source) && typeof source !== "object") {
14856
- source = { value: source };
14855
+ if (!Array.isArray(source2) && typeof source2 !== "object") {
14856
+ source2 = { value: source2 };
14857
14857
  }
14858
- return _Bag._fromJsonRecursive(source, listJoiner);
14858
+ return _Bag._fromJsonRecursive(source2, listJoiner);
14859
14859
  }
14860
14860
  /**
14861
14861
  * Recursively convert JSON data to Bag (internal).
@@ -15317,8 +15317,8 @@ var SourceBagNode = class extends BagNode {
15317
15317
  }
15318
15318
  };
15319
15319
  var SourceBag = class _SourceBag extends Bag {
15320
- constructor(source = null, builder = null) {
15321
- super(source);
15320
+ constructor(source2 = null, builder = null) {
15321
+ super(source2);
15322
15322
  this._builder = builder;
15323
15323
  this._insertingBuilder = null;
15324
15324
  }
@@ -15453,11 +15453,11 @@ function elementCall(builder, target, tag2, onBag) {
15453
15453
  };
15454
15454
  }
15455
15455
  function sourceBagFromTytx(payload, builder, { transport = "json" } = {}) {
15456
- const source = fromTytx(payload, transport === "json" ? null : transport);
15457
- if (!(source instanceof SourceBag)) {
15456
+ const source2 = fromTytx(payload, transport === "json" ? null : transport);
15457
+ if (!(source2 instanceof SourceBag)) {
15458
15458
  throw new TypeError("TYTX payload did not decode to SourceBag");
15459
15459
  }
15460
- return source.bindBuilder(builder);
15460
+ return source2.bindBuilder(builder);
15461
15461
  }
15462
15462
 
15463
15463
  // node_modules/@genrojs/builders/src/grammar-loader.js
@@ -15968,8 +15968,8 @@ var RendererBase = class {
15968
15968
  return this.render(roots[0], expansionOpts);
15969
15969
  }
15970
15970
  /** Normalize the source before the top-level walk. Identity by default. */
15971
- preprocess(source) {
15972
- return source;
15971
+ preprocess(source2) {
15972
+ return source2;
15973
15973
  }
15974
15974
  /** Dialect-specific fragment for `node`. Concrete renderers override. */
15975
15975
  renderedItem(_node, _item, _runtimeAttrs, _opts) {
@@ -16727,8 +16727,8 @@ var BuilderBase = class _BuilderBase {
16727
16727
  if (typeof func !== "string") {
16728
16728
  throw new Error("data-element func must be a name or a function");
16729
16729
  }
16730
- for (const source of this.dataLogic) {
16731
- const holder = typeof source === "function" ? source : source.constructor;
16730
+ for (const source2 of this.dataLogic) {
16731
+ const holder = typeof source2 === "function" ? source2 : source2.constructor;
16732
16732
  const fn = holder[func];
16733
16733
  if (typeof fn === "function") {
16734
16734
  return fn;
@@ -22005,6 +22005,26 @@ function requireNoScriptAttributes(node, attrs, prefixes = []) {
22005
22005
  function isJavascriptUrl(value) {
22006
22006
  return typeof value === "string" && /^javascript:/i.test(value.replace(/[\t\n\r]/g, "").replace(/^[\u0000-\u0020]+/, ""));
22007
22007
  }
22008
+ function withDataSrcdocSandbox(node, attrs, prefixes = []) {
22009
+ if (node.nodeTag !== "iframe") return attrs;
22010
+ const bare = (name) => {
22011
+ const prefix = prefixes.find((candidate) => name.startsWith(candidate)) ?? "";
22012
+ return [prefix, name.slice(prefix.length).toLowerCase()];
22013
+ };
22014
+ const declared = Object.fromEntries(sourceAttributeItems(node.getAttr()));
22015
+ const srcdoc = [...Object.keys(declared), ...Object.keys(attrs)].find((name) => bare(name)[1] === "srcdoc");
22016
+ if (srcdoc === void 0 || Object.keys(declared).some((name) => bare(name)[1] === "sandbox")) return attrs;
22017
+ const fromData = (name, seen) => {
22018
+ const raw = declared[name];
22019
+ seen.add(name);
22020
+ return node.pointerType(raw) !== null || isExpression2(raw) || templateParameters(raw).some((param) => Object.hasOwn(declared, param) && !seen.has(param) && fromData(param, seen));
22021
+ };
22022
+ if (node.pointerType(node.value) === null && !(Object.hasOwn(declared, srcdoc) && fromData(srcdoc, /* @__PURE__ */ new Set()))) {
22023
+ return attrs;
22024
+ }
22025
+ const rest = Object.fromEntries(Object.entries(attrs).filter(([name]) => bare(name)[1] !== "sandbox"));
22026
+ return { [`${bare(srcdoc)[0]}sandbox`]: "", ...rest };
22027
+ }
22008
22028
  function withoutNullValues(attrs) {
22009
22029
  return Object.fromEntries(Object.entries(attrs).filter(([, value]) => value != null));
22010
22030
  }
@@ -22166,12 +22186,13 @@ var GramlotHtmlRenderer = class extends HtmlRenderer {
22166
22186
  * Builder's meta; then the noConvertStyle attributes of the tag are set aside, because adaptAttrs
22167
22187
  * has no tag. A sub-builder boundary node keeps its attributes literal, with the Gramlot filters and
22168
22188
  * names; the `html` boundary inside SVG is a `foreignObject` in the SVG namespace. No attribute
22169
- * makes the browser run a text: no `on<event>`, no `javascript:` URL.
22189
+ * makes the browser run a text: no `on<event>`, no `javascript:` URL, no `srcdoc` from Data without `sandbox`.
22170
22190
  */
22171
22191
  _handleMeta(node, runtimeAttrs) {
22192
+ const prefixes = this.builder.constructor.dialectPrefixes;
22172
22193
  const evaluated = this.evaluateExpressions(node, runtimeAttrs);
22173
- requireNoScriptAttributes(node, evaluated, this.builder.constructor.dialectPrefixes);
22174
- const [tag2, attrs] = super._handleMeta(node, evaluated);
22194
+ requireNoScriptAttributes(node, evaluated, prefixes);
22195
+ const [tag2, attrs] = super._handleMeta(node, withDataSrcdocSandbox(node, evaluated, prefixes));
22175
22196
  if (node._getMeta("subbuilder")) {
22176
22197
  const boundary = boundaryAttributes(attrs);
22177
22198
  if (node._getMeta("subbuilder") === "html") boundary.xmlns = SVG_NS;
@@ -23148,7 +23169,9 @@ var HtmlElement = class {
23148
23169
  if (textValue2 === DEFAULT_TEXT) textValue2 = this.text(node);
23149
23170
  const nextText = textValue2 == null ? "" : String(textValue2);
23150
23171
  if (text.data !== nextText) text.data = nextText;
23151
- for (const key of /* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(attrs)])) {
23172
+ const keys = [.../* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(attrs)])];
23173
+ keys.sort((a, b) => (b === "sandbox") - (a === "sandbox"));
23174
+ for (const key of keys) {
23152
23175
  if (this.metadataAttributes.has(key) || controlled && key === "value") continue;
23153
23176
  const value = attrs[key];
23154
23177
  const attrName = key;
@@ -23924,14 +23947,14 @@ var Provider = class {
23924
23947
  * `_triggerpars`, `_reason`, the click arguments (undefined for any other trigger), then the author
23925
23948
  * attributes; a body (`formula`, `script`, or `_else` in their place) has `_kwargs` first, `_if` has not.
23926
23949
  */
23927
- #inline(attr, code, source, kwargs, body) {
23950
+ #inline(attr, code, source2, kwargs, body) {
23928
23951
  const names = [
23929
23952
  ...body ? ["_kwargs"] : [],
23930
23953
  ...TRIGGER_FIELDS,
23931
23954
  ...CLICK_FIELDS,
23932
23955
  ...Object.keys(authorArguments(kwargs))
23933
23956
  ];
23934
- return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, names, source)({ ...kwargs, _kwargs: kwargs });
23957
+ return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, names, source2)({ ...kwargs, _kwargs: kwargs });
23935
23958
  }
23936
23959
  #closeRegistrations() {
23937
23960
  for (const registration of this.#registrations.splice(0)) registration.close();
@@ -24045,8 +24068,8 @@ var InlineCompiler = class {
24045
24068
  * The legacy macros of `source` translated to the node methods, `$n` to `arguments[n-1]`, as in
24046
24069
  * `gnrlang.js`. A translated declaration gets one deprecation warning; `PUBLISH` is an error.
24047
24070
  */
24048
- preprocess(node, attr, source) {
24049
- const text = source.trim();
24071
+ preprocess(node, attr, source2) {
24072
+ const text = source2.trim();
24050
24073
  if (PUBLISH.test(text)) throw new Error(`${declaration2(node, attr)}: the PUBLISH macro is excluded from Gramlot 0.2.0`);
24051
24074
  let result = text.replace(/\$(\d+)/g, (_token, n) => `arguments[${parseInt(n, 10) - 1}]`);
24052
24075
  for (const [separator, macro, target] of MACROS) {
@@ -24068,7 +24091,7 @@ var InlineCompiler = class {
24068
24091
  * compile again; the entry is released when its attribute changes or is removed, and when the
24069
24092
  * node's NodeBinding closes.
24070
24093
  */
24071
- compile(node, attr, code, argNames, source = code) {
24094
+ compile(node, attr, code, argNames, source2 = code) {
24072
24095
  if (node.activatedCode(attr) !== code) {
24073
24096
  throw new Error(`${declaration2(node, attr)}: inline code runs only as received with the Source (main or a remote Source); a text written later is not run: use named logic`);
24074
24097
  }
@@ -24079,8 +24102,8 @@ var InlineCompiler = class {
24079
24102
  this.runtime.bindingFor(node).track(() => this.release(node));
24080
24103
  }
24081
24104
  let entry = entries.get(attr);
24082
- if (entry?.source !== source) {
24083
- entry = { source, text: this.preprocess(node, attr, source), key: null, run: null };
24105
+ if (entry?.source !== source2) {
24106
+ entry = { source: source2, text: this.preprocess(node, attr, source2), key: null, run: null };
24084
24107
  entries.set(attr, entry);
24085
24108
  }
24086
24109
  const params = argNames.filter(isIdentifier);
@@ -24151,7 +24174,7 @@ function create(node, attr, text, params) {
24151
24174
  `);
24152
24175
  } catch (error) {
24153
24176
  if (error instanceof EvalError) {
24154
- throw new EvalError(`${declaration2(node, attr)}: inline code blocked by the Content Security Policy of the page (no 'unsafe-eval'); move the code to named logic (a method of the page companion _aux.js) or serve the page with the permissive CSP profile, which allows 'unsafe-eval'`, { cause: error });
24177
+ throw new EvalError(`${declaration2(node, attr)}: inline code blocked by the Content Security Policy of the page (no 'unsafe-eval'); move the code to named logic (a method of the page's class Logic) or serve the page with the permissive CSP profile, which allows 'unsafe-eval'`, { cause: error });
24155
24178
  }
24156
24179
  throw new SyntaxError(`${declaration2(node, attr)}: ${error.message} in the inline code:
24157
24180
  ${text}`, { cause: error });
@@ -24602,19 +24625,19 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
24602
24625
  // The resolved projection that `project` hands to the rebuild of a control whose shape changed.
24603
24626
  #rebuildAttributes = /* @__PURE__ */ new WeakMap();
24604
24627
  /** The live renderer of one Gramlot page: `binding` is the page's BindingRuntime (§4.3). */
24605
- constructor(builder, source, destination, { binding } = {}) {
24628
+ constructor(builder, source2, destination, { binding } = {}) {
24606
24629
  super(builder);
24607
- if (!(builder instanceof BuilderBase) || !(source instanceof GramlotBuilderBag) || destination?.nodeType !== 1) {
24630
+ if (!(builder instanceof BuilderBase) || !(source2 instanceof GramlotBuilderBag) || destination?.nodeType !== 1) {
24608
24631
  throw new TypeError("GramlotRenderer requires a BuilderBase, GramlotBuilderBag and HTML destination");
24609
24632
  }
24610
24633
  if (!(binding instanceof BindingRuntime)) throw new TypeError("GramlotRenderer requires a BindingRuntime");
24611
- if (!(source._builder instanceof BuilderBase)) throw new TypeError("SourceBag requires builder ownership");
24634
+ if (!(source2._builder instanceof BuilderBase)) throw new TypeError("SourceBag requires builder ownership");
24612
24635
  this._binding = binding;
24613
- this.source = source;
24636
+ this.source = source2;
24614
24637
  this.destination = destination;
24615
24638
  this.html = new HtmlElement({ metadataAttributes: ["__ref"] });
24616
24639
  this.records = /* @__PURE__ */ new Map();
24617
- this.references = new References(source);
24640
+ this.references = new References(source2);
24618
24641
  this.pending = [];
24619
24642
  this.building = false;
24620
24643
  this.disposed = false;
@@ -24622,7 +24645,7 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
24622
24645
  this.instanceId = crypto.randomUUID();
24623
24646
  this.radioGroups = new RadioGroups(this);
24624
24647
  this.subscription = `html-source-renderer-${this.instanceId}`;
24625
- source.subscribe(this.subscription, { any: (event) => this.receive(event) });
24648
+ source2.subscribe(this.subscription, { any: (event) => this.receive(event) });
24626
24649
  }
24627
24650
  get binding() {
24628
24651
  return this._binding;
@@ -25226,10 +25249,10 @@ function regexStarts(previous) {
25226
25249
  if (/^[\w$]/.test(previous)) return REGEX_AFTER_WORDS.has(previous);
25227
25250
  return previous !== ")" && previous !== "]";
25228
25251
  }
25229
- function regexEnd(source, start) {
25252
+ function regexEnd(source2, start) {
25230
25253
  let inClass = false;
25231
- for (let index = start + 1; index < source.length; index++) {
25232
- const char = source[index];
25254
+ for (let index = start + 1; index < source2.length; index++) {
25255
+ const char = source2[index];
25233
25256
  if (char === "\n") return -1;
25234
25257
  if (char === "\\") {
25235
25258
  index++;
@@ -25241,26 +25264,26 @@ function regexEnd(source, start) {
25241
25264
  }
25242
25265
  return -1;
25243
25266
  }
25244
- function declaresConstructor(source) {
25267
+ function declaresConstructor(source2) {
25245
25268
  let depth = 0;
25246
25269
  let members = "";
25247
25270
  let previous = "";
25248
- for (let index = source.indexOf("{"); index < source.length; index++) {
25249
- const char = source[index];
25250
- if (char === "/" && source[index + 1] === "/") {
25251
- index = source.indexOf("\n", index);
25271
+ for (let index = source2.indexOf("{"); index < source2.length; index++) {
25272
+ const char = source2[index];
25273
+ if (char === "/" && source2[index + 1] === "/") {
25274
+ index = source2.indexOf("\n", index);
25252
25275
  if (index < 0) break;
25253
25276
  continue;
25254
25277
  }
25255
- if (char === "/" && source[index + 1] === "*") {
25256
- const close = source.indexOf("*/", index + 2);
25278
+ if (char === "/" && source2[index + 1] === "*") {
25279
+ const close = source2.indexOf("*/", index + 2);
25257
25280
  if (close >= 0) {
25258
25281
  index = close + 1;
25259
25282
  continue;
25260
25283
  }
25261
25284
  }
25262
25285
  if (char === "/" && regexStarts(previous)) {
25263
- const close = regexEnd(source, index);
25286
+ const close = regexEnd(source2, index);
25264
25287
  if (close >= 0) {
25265
25288
  index = close;
25266
25289
  previous = ")";
@@ -25269,17 +25292,17 @@ function declaresConstructor(source) {
25269
25292
  }
25270
25293
  if (char === '"' || char === "'" || char === "`") {
25271
25294
  let end = index + 1;
25272
- while (end < source.length && source[end] !== char) end += source[end] === "\\" ? 2 : 1;
25273
- if (depth === 1) members += source.slice(index + 1, end) === "constructor" ? " constructor" : ' ""';
25295
+ while (end < source2.length && source2[end] !== char) end += source2[end] === "\\" ? 2 : 1;
25296
+ if (depth === 1) members += source2.slice(index + 1, end) === "constructor" ? " constructor" : ' ""';
25274
25297
  index = end;
25275
25298
  previous = ")";
25276
25299
  continue;
25277
25300
  }
25278
25301
  if (/[\w$]/.test(char)) {
25279
25302
  let end = index + 1;
25280
- while (end < source.length && /[\w$]/.test(source[end])) end++;
25281
- if (depth === 1) members += source.slice(index, end);
25282
- previous = source.slice(index, end);
25303
+ while (end < source2.length && /[\w$]/.test(source2[end])) end++;
25304
+ if (depth === 1) members += source2.slice(index, end);
25305
+ previous = source2.slice(index, end);
25283
25306
  index = end - 1;
25284
25307
  continue;
25285
25308
  }
@@ -25368,7 +25391,7 @@ var LogicRegistry = class {
25368
25391
  }
25369
25392
  /**
25370
25393
  * Copy the methods of `logicClass` into the group `group` (a `js_requires` name, `a/b` nested,
25371
- * or null for the page companion), creating the groups on the way. On an equal method name in
25394
+ * or null for the page logic), creating the groups on the way. On an equal method name in
25372
25395
  * the same group the last registration wins.
25373
25396
  */
25374
25397
  register(logicClass, { group = null, resource }) {
@@ -25469,6 +25492,120 @@ var MainTransport = class {
25469
25492
  }
25470
25493
  };
25471
25494
 
25495
+ // src/inout.js
25496
+ var MAILTO_LIMIT = 2e3;
25497
+ function leafText(value) {
25498
+ if (!(value instanceof Date)) return String(value ?? "");
25499
+ const text = value.toISOString();
25500
+ return text.endsWith("T00:00:00.000Z") ? text.slice(0, 10) : text;
25501
+ }
25502
+ var InOut = class {
25503
+ constructor(gramlot, document) {
25504
+ this.gramlot = gramlot;
25505
+ this.document = document;
25506
+ }
25507
+ /** The Bag at path in the Data. */
25508
+ branch(path) {
25509
+ const value = this.gramlot.data.getItem(path);
25510
+ if (!(value instanceof Bag)) throw new Error(`gramlot.inout: no data Bag at '${path}'`);
25511
+ return value;
25512
+ }
25513
+ /** One `relative.path: value` line per leaf of the branch at path. */
25514
+ mailText(path) {
25515
+ const lines = [];
25516
+ const walk2 = (bag, prefix) => {
25517
+ for (const node of bag.getNodes()) {
25518
+ const label = prefix + node.label;
25519
+ if (node.value instanceof Bag) walk2(node.value, `${label}.`);
25520
+ else lines.push(`${label}: ${leafText(node.value)}`);
25521
+ }
25522
+ };
25523
+ walk2(this.branch(path), "");
25524
+ return lines.join("\n");
25525
+ }
25526
+ /** The mailto: URL of sendMail; longer than MAILTO_LIMIT raises an Error. */
25527
+ mailtoUrl(path, email) {
25528
+ const url = `mailto:${encodeURIComponent(email)}?subject=${encodeURIComponent(this.document.title)}&body=${encodeURIComponent(this.mailText(path))}`;
25529
+ if (url.length > MAILTO_LIMIT) {
25530
+ throw new Error(`gramlot.inout.sendMail: the email of '${path}' is ${url.length} characters long, over the mailto: limit of ${MAILTO_LIMIT}; send it with sendHttp or save it as a file`);
25531
+ }
25532
+ return url;
25533
+ }
25534
+ /** Prepare an email to email in the mail program of the user, with the data at path as text lines. */
25535
+ sendMail(path, email) {
25536
+ this.open(this.mailtoUrl(path, email));
25537
+ }
25538
+ /** POST the data at path as a JSON object to url; resolves with the Response, rejects on a status out of 2xx. */
25539
+ async sendHttp(path, url) {
25540
+ const body = JSON.stringify(this.branch(path).asDict(false, false, true));
25541
+ const response = await this.document.defaultView.fetch(url, {
25542
+ method: "POST",
25543
+ headers: { "Content-Type": "application/json" },
25544
+ body
25545
+ });
25546
+ if (!response.ok) throw new Error(`gramlot.inout.sendHttp: ${url} answered ${response.status}`);
25547
+ return response;
25548
+ }
25549
+ /** Save the data at path as a TYTX file, which restore reads back with its exact types. */
25550
+ save(path, filename) {
25551
+ this.saveText(this.branch(path).toTytx(), filename, "application/json");
25552
+ }
25553
+ /** Read a TYTX file chosen by the user into path; resolves with the restored Bag. Needs a user gesture. */
25554
+ restore(path) {
25555
+ const input = this.document.createElement("input");
25556
+ input.type = "file";
25557
+ input.accept = ".json,application/json";
25558
+ return new Promise((resolve, reject) => {
25559
+ input.addEventListener("change", async () => {
25560
+ try {
25561
+ const bag = Bag.fromTytx(await input.files[0].text());
25562
+ this.gramlot.data.setItem(path, bag);
25563
+ resolve(bag);
25564
+ } catch (error) {
25565
+ reject(new Error(
25566
+ `gramlot.inout.restore: the file is not a saved Gramlot branch: ${error.message}`,
25567
+ { cause: error }
25568
+ ));
25569
+ }
25570
+ }, { once: true });
25571
+ input.click();
25572
+ });
25573
+ }
25574
+ /** Export the data at path as 'json' (Bag.toJson) or 'xml' (Bag.toXml, inside one root element named
25575
+ * after the last segment of path); types become text. */
25576
+ download(path, filename, format) {
25577
+ if (!["json", "xml"].includes(format)) {
25578
+ throw new Error(`gramlot.inout.download: format '${format}' is not 'json' or 'xml'`);
25579
+ }
25580
+ const bag = this.branch(path);
25581
+ if (format === "json") {
25582
+ this.saveText(bag.toJson(false), filename, "application/json");
25583
+ } else {
25584
+ const root = path.split(".").at(-1);
25585
+ this.saveText(
25586
+ `<?xml version='1.0' encoding='UTF-8'?>
25587
+ <${root}>${bag.toXml()}</${root}>`,
25588
+ filename,
25589
+ "application/xml"
25590
+ );
25591
+ }
25592
+ }
25593
+ /** Hand text to the browser as a file named filename. */
25594
+ saveText(text, filename, type) {
25595
+ const window2 = this.document.defaultView;
25596
+ const url = window2.URL.createObjectURL(new window2.Blob([text], { type }));
25597
+ this.open(url, filename);
25598
+ window2.setTimeout(() => window2.URL.revokeObjectURL(url), 1e3);
25599
+ }
25600
+ /** Follow url through a link, as a download when filename is given. */
25601
+ open(url, filename = null) {
25602
+ const link = this.document.createElement("a");
25603
+ link.href = url;
25604
+ if (filename !== null) link.download = filename;
25605
+ link.click();
25606
+ }
25607
+ };
25608
+
25472
25609
  // src/gramlot.js
25473
25610
  var Gramlot = class {
25474
25611
  constructor({
@@ -25488,6 +25625,7 @@ var Gramlot = class {
25488
25625
  this.binding = new BindingRuntime(this);
25489
25626
  this.builder.binding = this.binding;
25490
25627
  this.data = this.builder.data;
25628
+ this.inout = new InOut(this, document);
25491
25629
  this.binding.attach();
25492
25630
  this.source = this.builder.source;
25493
25631
  const destination = element ?? document.getElementById(rootId);
@@ -25544,10 +25682,10 @@ var Gramlot = class {
25544
25682
  * NodeBindings (P12, no rollback).
25545
25683
  */
25546
25684
  mountMainSource(wire) {
25547
- const source = this.prepareSource(wire);
25548
- this.renderer.validateCandidate(source);
25685
+ const source2 = this.prepareSource(wire);
25686
+ this.renderer.validateCandidate(source2);
25549
25687
  try {
25550
- this.source.setItem("main", source);
25688
+ this.source.setItem("main", source2);
25551
25689
  } catch (error) {
25552
25690
  if (!this.binding.bindingFor(this.source.getNode("main"))) this.source.popNode("main");
25553
25691
  throw error;
@@ -25566,9 +25704,9 @@ var Gramlot = class {
25566
25704
  if (!(wire instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25567
25705
  return wire.bindBuilder(builder).activateCode();
25568
25706
  }
25569
- const source = sourceBagFromTytx(wire, builder);
25570
- if (!(source instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25571
- return source.activateCode();
25707
+ const source2 = sourceBagFromTytx(wire, builder);
25708
+ if (!(source2 instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25709
+ return source2.activateCode();
25572
25710
  }
25573
25711
  /**
25574
25712
  * Replace one Source node's children only after incoming Source validation.
@@ -25693,6 +25831,24 @@ var PageBootstrap = class {
25693
25831
  new MainTransport(mainUrl, void 0, sourceUrl, closeUrl, this.document.defaultView.navigator).close(pageId, { beacon: true });
25694
25832
  }
25695
25833
  };
25834
+
25835
+ // src/adapters/page.js
25836
+ var SOURCE_METHOD = /* @__PURE__ */ Symbol("gramlot.source");
25837
+ function source(method) {
25838
+ if (typeof method !== "function") throw new TypeError("source requires a method");
25839
+ method[SOURCE_METHOD] = true;
25840
+ return method;
25841
+ }
25842
+ var Page = class {
25843
+ static title = "Gramlot";
25844
+ static css = [];
25845
+ static css_requires = "";
25846
+ static js_requires = "";
25847
+ static sourceBuilder = GramlotBuilder;
25848
+ main(root) {
25849
+ throw new Error("Page.main(root) must be implemented");
25850
+ }
25851
+ };
25696
25852
  export {
25697
25853
  Bag,
25698
25854
  BagNode,
@@ -25701,7 +25857,10 @@ export {
25701
25857
  GramlotHtmlRenderer,
25702
25858
  GramlotRenderer,
25703
25859
  GramlotSvgRenderer,
25860
+ InOut,
25704
25861
  MainTransport,
25862
+ Page,
25705
25863
  PageBootstrap,
25706
- References
25864
+ References,
25865
+ source
25707
25866
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gramlot/gramlot",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "description": "Declarative HTML/SVG interfaces with live data binding, authored in JavaScript or Python.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -27,8 +27,11 @@ async function realFile(filename) {
27
27
  /** Minimal reference Host on one pages folder, with APIs shared by Node.js and Bun.
28
28
  * The Python counterpart is src/gramlot/server/file_host.py. Page path foo: the
29
29
  * file page foo.js first, then the folder page foo/foo.js; the file wins when both
30
- * exist. Beside the page file: foo.css (CSS), foo_aux.js (JS module exporting
31
- * Logic, group null) and foo.md (README). The _aux suffix is reserved. There are
30
+ * exist. Beside the page file: foo.css (CSS) and foo.md (README). The page logic
31
+ * (group null) is the Logic export of the page module itself, else foo_aux.js
32
+ * (JS module exporting Logic); both at once raise an Error. The page module then
33
+ * reaches the browser, so its imports must resolve there too. The _aux suffix is
34
+ * reserved. There are
32
35
  * no resource levels: a name in css_requires/js_requires raises
33
36
  * InvalidResourceName. Modules are trusted ESM application files; runtime module
34
37
  * caching applies.
@@ -67,7 +70,7 @@ export class FileHost extends Host {
67
70
  return (await import(pathToFileURL(await this.locatePage(path)).href)).Page;
68
71
  }
69
72
 
70
- /** Page.css URLs as written, then the companions foo.css and foo_aux.js. */
73
+ /** Page.css URLs as written, then the companion foo.css and the page logic. */
71
74
  async resolveResources(path, PageClass) {
72
75
  if (parseRequires(PageClass.css_requires).length || parseRequires(PageClass.js_requires).length) {
73
76
  throw new InvalidResourceName('requires need a Host with a resource system');
@@ -76,7 +79,12 @@ export class FileHost extends Host {
76
79
  const stem = join(dirname(pageFile), basename(pageFile, extname(pageFile)));
77
80
  const css = [...PageClass.css], js = [];
78
81
  if (await realFile(`${stem}.css`)) css.push(await this.url(`${stem}.css`));
79
- if (await realFile(`${stem}_aux.js`)) js.push({url: await this.url(`${stem}_aux.js`), group: null});
82
+ const logic = [];
83
+ // The module is already in the runtime cache: resolvePage imported it.
84
+ if ('Logic' in await import(pathToFileURL(pageFile).href)) logic.push(await this.url(pageFile));
85
+ if (await realFile(`${stem}_aux.js`)) logic.push(await this.url(`${stem}_aux.js`));
86
+ if (logic.length === 2) throw new Error(`Two logic modules for one page: ${logic.join(' and ')}`);
87
+ if (logic.length) js.push({url: logic[0], group: null});
80
88
  return {css, js};
81
89
  }
82
90
 
@@ -81,6 +81,9 @@ export class Host {
81
81
  const head = root.head();
82
82
  head.meta({charset: 'utf-8'});
83
83
  head.title(title);
84
+ // A page module served for its Logic imports the core from the runtime already loaded.
85
+ head.script(scriptJson({imports: {'@gramlot/gramlot/page': prefixed(prefix, this.runtimeUrl)}}),
86
+ {type: 'importmap', nonce});
84
87
  const body = root.body();
85
88
  body.div({id: this.rootId});
86
89
  body.script(`import {PageBootstrap} from ${scriptJson(prefixed(prefix, this.runtimeUrl))};` +
@@ -176,7 +176,7 @@ function create(node, attr, text, params) {
176
176
  } catch (error) {
177
177
  if (error instanceof EvalError) {
178
178
  throw new EvalError(`${declaration(node, attr)}: inline code blocked by the Content Security Policy of the page `
179
- + `(no 'unsafe-eval'); move the code to named logic (a method of the page companion _aux.js) `
179
+ + `(no 'unsafe-eval'); move the code to named logic (a method of the page's class Logic) `
180
180
  + `or serve the page with the permissive CSP profile, which allows 'unsafe-eval'`, {cause: error});
181
181
  }
182
182
  throw new SyntaxError(`${declaration(node, attr)}: ${error.message} in the inline code:\n${text}`, {cause: error});
@@ -2,7 +2,7 @@
2
2
  * Named logic of one Gramlot page (source plan §4.9, decision P21).
3
3
  *
4
4
  * Every logic file exports `class Logic`; its prototype methods are copied into a
5
- * `LogicGroup`: the root group for the page companion (group null), a child group
5
+ * `LogicGroup`: the root group for the page logic (group null), a child group
6
6
  * for each name of `js_requires` (`a/b` is the group `b` inside the group `a`).
7
7
  * The constructor of `Logic` never runs.
8
8
  */
@@ -178,7 +178,7 @@ export class LogicRegistry {
178
178
 
179
179
  /**
180
180
  * Copy the methods of `logicClass` into the group `group` (a `js_requires` name, `a/b` nested,
181
- * or null for the page companion), creating the groups on the way. On an equal method name in
181
+ * or null for the page logic), creating the groups on the way. On an equal method name in
182
182
  * the same group the last registration wins.
183
183
  */
184
184
  register(logicClass, {group = null, resource}) {
package/src/gramlot.js CHANGED
@@ -5,6 +5,7 @@ import {GramlotRenderer} from './renderer/gramlot-renderer.js';
5
5
  import {BindingRuntime} from './binding/runtime.js';
6
6
  import {LogicRegistry} from './binding/logic.js';
7
7
  import {MainTransport} from './transport.js';
8
+ import {InOut} from './inout.js';
8
9
 
9
10
  /**
10
11
  * One Gramlot page. The construction order is the one of source plan §4.3: the Data
@@ -20,6 +21,7 @@ export class Gramlot {
20
21
  this.binding = new BindingRuntime(this);
21
22
  this.builder.binding = this.binding;
22
23
  this.data = this.builder.data;
24
+ this.inout = new InOut(this, document);
23
25
  this.binding.attach();
24
26
  this.source = this.builder.source;
25
27
  const destination = element ?? document.getElementById(rootId);
package/src/index.js CHANGED
@@ -1,5 +1,7 @@
1
1
  export {Gramlot} from './gramlot.js';
2
2
  export {PageBootstrap} from './bootstrap.js';
3
+ // A page module served for its Logic imports @gramlot/gramlot/page; the bootstrap import map points it here.
4
+ export {Page, source} from './adapters/page.js';
3
5
  export {GramlotBuilder} from './builder/gramlot-builder.js';
4
6
  export {GramlotRenderer} from './renderer/gramlot-renderer.js';
5
7
  export {GramlotHtmlRenderer} from './renderer/gramlot-html-renderer.js';
@@ -7,3 +9,4 @@ export {GramlotSvgRenderer} from './renderer/gramlot-svg-renderer.js';
7
9
  export {Bag, BagNode} from '@genrojs/bag';
8
10
  export {References} from './references.js';
9
11
  export {MainTransport} from './transport.js';
12
+ export {InOut} from './inout.js';
package/src/inout.js ADDED
@@ -0,0 +1,129 @@
1
+ import {Bag} from '@genrojs/bag';
2
+
3
+ /** The practical length limit of a mailto: URL in mail programs and browsers. */
4
+ export const MAILTO_LIMIT = 2000;
5
+
6
+ /** A leaf value as text: a Date at UTC midnight is a date (TYTX `D`), any other Date a datetime. */
7
+ function leafText(value) {
8
+ if (!(value instanceof Date)) return String(value ?? '');
9
+ const text = value.toISOString();
10
+ return text.endsWith('T00:00:00.000Z') ? text.slice(0, 10) : text;
11
+ }
12
+
13
+ /**
14
+ * What the page sends, receives, saves and downloads: `gramlot.inout` (decisions of 2026-10-03).
15
+ * Every function takes the Data path of a Bag branch; a missing path or a value that is not a Bag
16
+ * raises an Error. Part of the browser runtime, so Python and JavaScript pages use it alike, from
17
+ * inline code or from their Logic.
18
+ */
19
+ export class InOut {
20
+ constructor(gramlot, document) {
21
+ this.gramlot = gramlot;
22
+ this.document = document;
23
+ }
24
+
25
+ /** The Bag at path in the Data. */
26
+ branch(path) {
27
+ const value = this.gramlot.data.getItem(path);
28
+ if (!(value instanceof Bag)) throw new Error(`gramlot.inout: no data Bag at '${path}'`);
29
+ return value;
30
+ }
31
+
32
+ /** One `relative.path: value` line per leaf of the branch at path. */
33
+ mailText(path) {
34
+ const lines = [];
35
+ const walk = (bag, prefix) => {
36
+ for (const node of bag.getNodes()) {
37
+ const label = prefix + node.label;
38
+ if (node.value instanceof Bag) walk(node.value, `${label}.`);
39
+ else lines.push(`${label}: ${leafText(node.value)}`);
40
+ }
41
+ };
42
+ walk(this.branch(path), '');
43
+ return lines.join('\n');
44
+ }
45
+
46
+ /** The mailto: URL of sendMail; longer than MAILTO_LIMIT raises an Error. */
47
+ mailtoUrl(path, email) {
48
+ const url = `mailto:${encodeURIComponent(email)}?subject=${encodeURIComponent(this.document.title)}` +
49
+ `&body=${encodeURIComponent(this.mailText(path))}`;
50
+ if (url.length > MAILTO_LIMIT) {
51
+ throw new Error(`gramlot.inout.sendMail: the email of '${path}' is ${url.length} characters long, ` +
52
+ `over the mailto: limit of ${MAILTO_LIMIT}; send it with sendHttp or save it as a file`);
53
+ }
54
+ return url;
55
+ }
56
+
57
+ /** Prepare an email to email in the mail program of the user, with the data at path as text lines. */
58
+ sendMail(path, email) {
59
+ this.open(this.mailtoUrl(path, email));
60
+ }
61
+
62
+ /** POST the data at path as a JSON object to url; resolves with the Response, rejects on a status out of 2xx. */
63
+ async sendHttp(path, url) {
64
+ const body = JSON.stringify(this.branch(path).asDict(false, false, true));
65
+ const response = await this.document.defaultView.fetch(url, {
66
+ method: 'POST', headers: {'Content-Type': 'application/json'}, body,
67
+ });
68
+ if (!response.ok) throw new Error(`gramlot.inout.sendHttp: ${url} answered ${response.status}`);
69
+ return response;
70
+ }
71
+
72
+ /** Save the data at path as a TYTX file, which restore reads back with its exact types. */
73
+ save(path, filename) {
74
+ this.saveText(this.branch(path).toTytx(), filename, 'application/json');
75
+ }
76
+
77
+ /** Read a TYTX file chosen by the user into path; resolves with the restored Bag. Needs a user gesture. */
78
+ restore(path) {
79
+ const input = this.document.createElement('input');
80
+ input.type = 'file';
81
+ input.accept = '.json,application/json';
82
+ return new Promise((resolve, reject) => {
83
+ input.addEventListener('change', async () => {
84
+ try {
85
+ const bag = Bag.fromTytx(await input.files[0].text());
86
+ this.gramlot.data.setItem(path, bag);
87
+ resolve(bag);
88
+ } catch (error) {
89
+ reject(new Error(`gramlot.inout.restore: the file is not a saved Gramlot branch: ${error.message}`,
90
+ {cause: error}));
91
+ }
92
+ }, {once: true});
93
+ input.click();
94
+ });
95
+ }
96
+
97
+ /** Export the data at path as 'json' (Bag.toJson) or 'xml' (Bag.toXml, inside one root element named
98
+ * after the last segment of path); types become text. */
99
+ download(path, filename, format) {
100
+ if (!['json', 'xml'].includes(format)) {
101
+ throw new Error(`gramlot.inout.download: format '${format}' is not 'json' or 'xml'`);
102
+ }
103
+ const bag = this.branch(path);
104
+ if (format === 'json') {
105
+ this.saveText(bag.toJson(false), filename, 'application/json');
106
+ } else {
107
+ const root = path.split('.').at(-1);
108
+ this.saveText(`<?xml version='1.0' encoding='UTF-8'?>\n<${root}>${bag.toXml()}</${root}>`, filename,
109
+ 'application/xml');
110
+ }
111
+ }
112
+
113
+ /** Hand text to the browser as a file named filename. */
114
+ saveText(text, filename, type) {
115
+ const window = this.document.defaultView;
116
+ const url = window.URL.createObjectURL(new window.Blob([text], {type}));
117
+ this.open(url, filename);
118
+ // The download reads the Blob after the click returns.
119
+ window.setTimeout(() => window.URL.revokeObjectURL(url), 1000);
120
+ }
121
+
122
+ /** Follow url through a link, as a download when filename is given. */
123
+ open(url, filename = null) {
124
+ const link = this.document.createElement('a');
125
+ link.href = url;
126
+ if (filename !== null) link.download = filename;
127
+ link.click();
128
+ }
129
+ }
@@ -64,6 +64,36 @@ function isJavascriptUrl(value) {
64
64
  return typeof value === 'string' && /^javascript:/i.test(value.replace(/[\t\n\r]/g, '').replace(/^[\u0000-\u0020]+/, ''));
65
65
  }
66
66
 
67
+ /**
68
+ * `attrs` of an `iframe` whose `srcdoc` comes from Data, with an empty `sandbox` first: the browser shows
69
+ * the HTML of a datum and runs nothing of it. `srcdoc` comes from Data when it is a `^`/`=` pointer, a `==`
70
+ * expression or a `${…}` template reading one, or when the node value is a pointer, whose datum can carry
71
+ * `srcdoc` in its `_wdg`. The declaration decides, so the iframe has `sandbox` while `srcdoc` is still null.
72
+ * A `sandbox` declared in the Source stays as declared; a literal `srcdoc` gets none. The names are read
73
+ * without the dialect `prefixes` (`html_`); `sandbox` takes the prefix of `srcdoc`.
74
+ */
75
+ export function withDataSrcdocSandbox(node, attrs, prefixes = []) {
76
+ if (node.nodeTag !== 'iframe') return attrs;
77
+ const bare = name => {
78
+ const prefix = prefixes.find(candidate => name.startsWith(candidate)) ?? '';
79
+ return [prefix, name.slice(prefix.length).toLowerCase()];
80
+ };
81
+ const declared = Object.fromEntries(sourceAttributeItems(node.getAttr()));
82
+ const srcdoc = [...Object.keys(declared), ...Object.keys(attrs)].find(name => bare(name)[1] === 'srcdoc');
83
+ if (srcdoc === undefined || Object.keys(declared).some(name => bare(name)[1] === 'sandbox')) return attrs;
84
+ const fromData = (name, seen) => {
85
+ const raw = declared[name];
86
+ seen.add(name);
87
+ return node.pointerType(raw) !== null || isExpression(raw) || templateParameters(raw)
88
+ .some(param => Object.hasOwn(declared, param) && !seen.has(param) && fromData(param, seen));
89
+ };
90
+ if (node.pointerType(node.value) === null && !(Object.hasOwn(declared, srcdoc) && fromData(srcdoc, new Set()))) {
91
+ return attrs;
92
+ }
93
+ const rest = Object.fromEntries(Object.entries(attrs).filter(([name]) => bare(name)[1] !== 'sandbox'));
94
+ return {[`${bare(srcdoc)[0]}sandbox`]: '', ...rest};
95
+ }
96
+
67
97
  /** The attributes of `attrs` whose value is neither null nor undefined. */
68
98
  export function withoutNullValues(attrs) {
69
99
  return Object.fromEntries(Object.entries(attrs).filter(([, value]) => value != null));
@@ -2,7 +2,8 @@ import {HtmlBuilder, HtmlRenderer, SvgBuilder, sourceAttributeItems} from '@genr
2
2
  import {GramlotSvgRenderer} from './gramlot-svg-renderer.js';
3
3
  import {
4
4
  SVG_NS, XHTML_NS, boundaryAttributes, displayItem, domNames, isExpression, requireNoExpressionTemplate,
5
- requireNoScriptAttributes, splitNativeAttributes, textValue, withoutBindingAttributes, withoutNullValues,
5
+ requireNoScriptAttributes, splitNativeAttributes, textValue, withDataSrcdocSandbox, withoutBindingAttributes,
6
+ withoutNullValues,
6
7
  } from './attributes.js';
7
8
 
8
9
  /**
@@ -39,12 +40,13 @@ export class GramlotHtmlRenderer extends HtmlRenderer {
39
40
  * Builder's meta; then the noConvertStyle attributes of the tag are set aside, because adaptAttrs
40
41
  * has no tag. A sub-builder boundary node keeps its attributes literal, with the Gramlot filters and
41
42
  * names; the `html` boundary inside SVG is a `foreignObject` in the SVG namespace. No attribute
42
- * makes the browser run a text: no `on<event>`, no `javascript:` URL.
43
+ * makes the browser run a text: no `on<event>`, no `javascript:` URL, no `srcdoc` from Data without `sandbox`.
43
44
  */
44
45
  _handleMeta(node, runtimeAttrs) {
46
+ const prefixes = this.builder.constructor.dialectPrefixes;
45
47
  const evaluated = this.evaluateExpressions(node, runtimeAttrs);
46
- requireNoScriptAttributes(node, evaluated, this.builder.constructor.dialectPrefixes);
47
- const [tag, attrs] = super._handleMeta(node, evaluated);
48
+ requireNoScriptAttributes(node, evaluated, prefixes);
49
+ const [tag, attrs] = super._handleMeta(node, withDataSrcdocSandbox(node, evaluated, prefixes));
48
50
  if (node._getMeta('subbuilder')) {
49
51
  const boundary = boundaryAttributes(attrs);
50
52
  if (node._getMeta('subbuilder') === 'html') boundary.xmlns = SVG_NS;
package/src/view/html.js CHANGED
@@ -112,7 +112,10 @@ export class HtmlElement {
112
112
  if (textValue === DEFAULT_TEXT) textValue = this.text(node);
113
113
  const nextText = textValue == null ? '' : String(textValue);
114
114
  if (text.data !== nextText) text.data = nextText;
115
- for (const key of new Set([...Object.keys(previous), ...Object.keys(attrs)])) {
115
+ const keys = [...new Set([...Object.keys(previous), ...Object.keys(attrs)])];
116
+ // The browser reads `sandbox` when `src` or `srcdoc` starts a navigation: `sandbox` is written first.
117
+ keys.sort((a, b) => (b === 'sandbox') - (a === 'sandbox'));
118
+ for (const key of keys) {
116
119
  if (this.metadataAttributes.has(key) || (controlled && key === 'value')) continue;
117
120
  const value = attrs[key];
118
121
  const attrName = key;