trigger_system 1.0.0

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 (136) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +127 -0
  3. package/dist/browser/index.browser.js +48 -0
  4. package/dist/browser/index.browser.js.map +122 -0
  5. package/dist/cli/lsp-server.d.ts +3 -0
  6. package/dist/cli/lsp-server.d.ts.map +1 -0
  7. package/dist/cli/validate.d.ts +2 -0
  8. package/dist/cli/validate.d.ts.map +1 -0
  9. package/dist/core/action-registry.d.ts +12 -0
  10. package/dist/core/action-registry.d.ts.map +1 -0
  11. package/dist/core/context-adapter.d.ts +23 -0
  12. package/dist/core/context-adapter.d.ts.map +1 -0
  13. package/dist/core/dependency-graph.d.ts +18 -0
  14. package/dist/core/dependency-graph.d.ts.map +1 -0
  15. package/dist/core/engine.d.ts +24 -0
  16. package/dist/core/engine.d.ts.map +1 -0
  17. package/dist/core/event-queue.d.ts +25 -0
  18. package/dist/core/event-queue.d.ts.map +1 -0
  19. package/dist/core/expression-engine.d.ts +31 -0
  20. package/dist/core/expression-engine.d.ts.map +1 -0
  21. package/dist/core/index.d.ts +10 -0
  22. package/dist/core/index.d.ts.map +1 -0
  23. package/dist/core/persistence-browser.d.ts +20 -0
  24. package/dist/core/persistence-browser.d.ts.map +1 -0
  25. package/dist/core/persistence.d.ts +34 -0
  26. package/dist/core/persistence.d.ts.map +1 -0
  27. package/dist/core/persistence.node.d.ts +18 -0
  28. package/dist/core/persistence.node.d.ts.map +1 -0
  29. package/dist/core/plugin-manager.d.ts +15 -0
  30. package/dist/core/plugin-manager.d.ts.map +1 -0
  31. package/dist/core/rule-engine.d.ts +39 -0
  32. package/dist/core/rule-engine.d.ts.map +1 -0
  33. package/dist/core/state-manager.d.ts +41 -0
  34. package/dist/core/state-manager.d.ts.map +1 -0
  35. package/dist/domain/index.d.ts +2 -0
  36. package/dist/domain/index.d.ts.map +1 -0
  37. package/dist/domain/validator.d.ts +2433 -0
  38. package/dist/domain/validator.d.ts.map +1 -0
  39. package/dist/index.browser.d.ts +6 -0
  40. package/dist/index.browser.d.ts.map +1 -0
  41. package/dist/index.d.ts +7 -0
  42. package/dist/index.d.ts.map +1 -0
  43. package/dist/io/index.d.ts +2 -0
  44. package/dist/io/index.d.ts.map +1 -0
  45. package/dist/io/loader.node.d.ts +14 -0
  46. package/dist/io/loader.node.d.ts.map +1 -0
  47. package/dist/lsp/completions.d.ts +6 -0
  48. package/dist/lsp/completions.d.ts.map +1 -0
  49. package/dist/lsp/completions.js +624 -0
  50. package/dist/lsp/completions.js.map +1 -0
  51. package/dist/lsp/data-context.d.ts +60 -0
  52. package/dist/lsp/data-context.d.ts.map +1 -0
  53. package/dist/lsp/data-context.js +172 -0
  54. package/dist/lsp/data-context.js.map +1 -0
  55. package/dist/lsp/diagnostics.d.ts +7 -0
  56. package/dist/lsp/diagnostics.d.ts.map +1 -0
  57. package/dist/lsp/diagnostics.js +373 -0
  58. package/dist/lsp/diagnostics.js.map +1 -0
  59. package/dist/lsp/directives.d.ts +44 -0
  60. package/dist/lsp/directives.d.ts.map +1 -0
  61. package/dist/lsp/directives.js +232 -0
  62. package/dist/lsp/directives.js.map +1 -0
  63. package/dist/lsp/domain/index.d.ts +2 -0
  64. package/dist/lsp/domain/index.d.ts.map +1 -0
  65. package/dist/lsp/domain/index.js +18 -0
  66. package/dist/lsp/domain/index.js.map +1 -0
  67. package/dist/lsp/domain/validator.d.ts +2433 -0
  68. package/dist/lsp/domain/validator.d.ts.map +1 -0
  69. package/dist/lsp/domain/validator.js +225 -0
  70. package/dist/lsp/domain/validator.js.map +1 -0
  71. package/dist/lsp/hover.d.ts +7 -0
  72. package/dist/lsp/hover.d.ts.map +1 -0
  73. package/dist/lsp/hover.js +462 -0
  74. package/dist/lsp/hover.js.map +1 -0
  75. package/dist/lsp/lsp/completions.d.ts +6 -0
  76. package/dist/lsp/lsp/completions.d.ts.map +1 -0
  77. package/dist/lsp/lsp/completions.js +624 -0
  78. package/dist/lsp/lsp/completions.js.map +1 -0
  79. package/dist/lsp/lsp/data-context.d.ts +60 -0
  80. package/dist/lsp/lsp/data-context.d.ts.map +1 -0
  81. package/dist/lsp/lsp/data-context.js +172 -0
  82. package/dist/lsp/lsp/data-context.js.map +1 -0
  83. package/dist/lsp/lsp/diagnostics.d.ts +7 -0
  84. package/dist/lsp/lsp/diagnostics.d.ts.map +1 -0
  85. package/dist/lsp/lsp/diagnostics.js +373 -0
  86. package/dist/lsp/lsp/diagnostics.js.map +1 -0
  87. package/dist/lsp/lsp/directives.d.ts +44 -0
  88. package/dist/lsp/lsp/directives.d.ts.map +1 -0
  89. package/dist/lsp/lsp/directives.js +232 -0
  90. package/dist/lsp/lsp/directives.js.map +1 -0
  91. package/dist/lsp/lsp/hover.d.ts +7 -0
  92. package/dist/lsp/lsp/hover.d.ts.map +1 -0
  93. package/dist/lsp/lsp/hover.js +462 -0
  94. package/dist/lsp/lsp/hover.js.map +1 -0
  95. package/dist/lsp/lsp/semantic_tokens.d.ts +4 -0
  96. package/dist/lsp/lsp/semantic_tokens.d.ts.map +1 -0
  97. package/dist/lsp/lsp/semantic_tokens.js +158 -0
  98. package/dist/lsp/lsp/semantic_tokens.js.map +1 -0
  99. package/dist/lsp/lsp/server.d.ts +2 -0
  100. package/dist/lsp/lsp/server.d.ts.map +1 -0
  101. package/dist/lsp/lsp/server.js +216 -0
  102. package/dist/lsp/lsp/server.js.map +1 -0
  103. package/dist/lsp/semantic_tokens.d.ts +4 -0
  104. package/dist/lsp/semantic_tokens.d.ts.map +1 -0
  105. package/dist/lsp/semantic_tokens.js +158 -0
  106. package/dist/lsp/semantic_tokens.js.map +1 -0
  107. package/dist/lsp/server.bundle.d.ts +2 -0
  108. package/dist/lsp/server.bundle.d.ts.map +1 -0
  109. package/dist/lsp/server.bundle.js +256 -0
  110. package/dist/lsp/server.d.ts +2 -0
  111. package/dist/lsp/server.d.ts.map +1 -0
  112. package/dist/lsp/server.js +216 -0
  113. package/dist/lsp/server.js.map +1 -0
  114. package/dist/lsp/types.d.ts +71 -0
  115. package/dist/lsp/types.d.ts.map +1 -0
  116. package/dist/lsp/types.js +4 -0
  117. package/dist/lsp/types.js.map +1 -0
  118. package/dist/node/index.js +186 -0
  119. package/dist/node/index.js.map +196 -0
  120. package/dist/node/node.js +187 -0
  121. package/dist/node/node.js.map +198 -0
  122. package/dist/node.d.ts +4 -0
  123. package/dist/node.d.ts.map +1 -0
  124. package/dist/sdk/builder.d.ts +39 -0
  125. package/dist/sdk/builder.d.ts.map +1 -0
  126. package/dist/sdk/exporter.d.ts +13 -0
  127. package/dist/sdk/exporter.d.ts.map +1 -0
  128. package/dist/sdk/index.d.ts +3 -0
  129. package/dist/sdk/index.d.ts.map +1 -0
  130. package/dist/types.d.ts +71 -0
  131. package/dist/types.d.ts.map +1 -0
  132. package/dist/utils/emitter.d.ts +25 -0
  133. package/dist/utils/emitter.d.ts.map +1 -0
  134. package/dist/utils/utils.d.ts +18 -0
  135. package/dist/utils/utils.d.ts.map +1 -0
  136. package/package.json +91 -0
@@ -0,0 +1,198 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["..\\..\\node_modules\\yaml\\dist\\nodes\\identity.js", "..\\..\\node_modules\\yaml\\dist\\visit.js", "..\\..\\node_modules\\yaml\\dist\\doc\\directives.js", "..\\..\\node_modules\\yaml\\dist\\doc\\anchors.js", "..\\..\\node_modules\\yaml\\dist\\doc\\applyReviver.js", "..\\..\\node_modules\\yaml\\dist\\nodes\\toJS.js", "..\\..\\node_modules\\yaml\\dist\\nodes\\Node.js", "..\\..\\node_modules\\yaml\\dist\\nodes\\Alias.js", "..\\..\\node_modules\\yaml\\dist\\nodes\\Scalar.js", "..\\..\\node_modules\\yaml\\dist\\doc\\createNode.js", "..\\..\\node_modules\\yaml\\dist\\nodes\\Collection.js", "..\\..\\node_modules\\yaml\\dist\\stringify\\stringifyComment.js", "..\\..\\node_modules\\yaml\\dist\\stringify\\foldFlowLines.js", "..\\..\\node_modules\\yaml\\dist\\stringify\\stringifyString.js", "..\\..\\node_modules\\yaml\\dist\\stringify\\stringify.js", "..\\..\\node_modules\\yaml\\dist\\stringify\\stringifyPair.js", "..\\..\\node_modules\\yaml\\dist\\log.js", "..\\..\\node_modules\\yaml\\dist\\schema\\yaml-1.1\\merge.js", "..\\..\\node_modules\\yaml\\dist\\nodes\\addPairToJSMap.js", "..\\..\\node_modules\\yaml\\dist\\nodes\\Pair.js", "..\\..\\node_modules\\yaml\\dist\\stringify\\stringifyCollection.js", "..\\..\\node_modules\\yaml\\dist\\nodes\\YAMLMap.js", "..\\..\\node_modules\\yaml\\dist\\schema\\common\\map.js", "..\\..\\node_modules\\yaml\\dist\\nodes\\YAMLSeq.js", "..\\..\\node_modules\\yaml\\dist\\schema\\common\\seq.js", "..\\..\\node_modules\\yaml\\dist\\schema\\common\\string.js", "..\\..\\node_modules\\yaml\\dist\\schema\\common\\null.js", "..\\..\\node_modules\\yaml\\dist\\schema\\core\\bool.js", "..\\..\\node_modules\\yaml\\dist\\stringify\\stringifyNumber.js", "..\\..\\node_modules\\yaml\\dist\\schema\\core\\float.js", "..\\..\\node_modules\\yaml\\dist\\schema\\core\\int.js", "..\\..\\node_modules\\yaml\\dist\\schema\\core\\schema.js", "..\\..\\node_modules\\yaml\\dist\\schema\\json\\schema.js", "..\\..\\node_modules\\yaml\\dist\\schema\\yaml-1.1\\binary.js", "..\\..\\node_modules\\yaml\\dist\\schema\\yaml-1.1\\pairs.js", "..\\..\\node_modules\\yaml\\dist\\schema\\yaml-1.1\\omap.js", "..\\..\\node_modules\\yaml\\dist\\schema\\yaml-1.1\\bool.js", "..\\..\\node_modules\\yaml\\dist\\schema\\yaml-1.1\\float.js", "..\\..\\node_modules\\yaml\\dist\\schema\\yaml-1.1\\int.js", "..\\..\\node_modules\\yaml\\dist\\schema\\yaml-1.1\\set.js", "..\\..\\node_modules\\yaml\\dist\\schema\\yaml-1.1\\timestamp.js", "..\\..\\node_modules\\yaml\\dist\\schema\\yaml-1.1\\schema.js", "..\\..\\node_modules\\yaml\\dist\\schema\\tags.js", "..\\..\\node_modules\\yaml\\dist\\schema\\Schema.js", "..\\..\\node_modules\\yaml\\dist\\stringify\\stringifyDocument.js", "..\\..\\node_modules\\yaml\\dist\\doc\\Document.js", "..\\..\\node_modules\\yaml\\dist\\errors.js", "..\\..\\node_modules\\yaml\\dist\\compose\\resolve-props.js", "..\\..\\node_modules\\yaml\\dist\\compose\\util-contains-newline.js", "..\\..\\node_modules\\yaml\\dist\\compose\\util-flow-indent-check.js", "..\\..\\node_modules\\yaml\\dist\\compose\\util-map-includes.js", "..\\..\\node_modules\\yaml\\dist\\compose\\resolve-block-map.js", "..\\..\\node_modules\\yaml\\dist\\compose\\resolve-block-seq.js", "..\\..\\node_modules\\yaml\\dist\\compose\\resolve-end.js", "..\\..\\node_modules\\yaml\\dist\\compose\\resolve-flow-collection.js", "..\\..\\node_modules\\yaml\\dist\\compose\\compose-collection.js", "..\\..\\node_modules\\yaml\\dist\\compose\\resolve-block-scalar.js", "..\\..\\node_modules\\yaml\\dist\\compose\\resolve-flow-scalar.js", "..\\..\\node_modules\\yaml\\dist\\compose\\compose-scalar.js", "..\\..\\node_modules\\yaml\\dist\\compose\\util-empty-scalar-position.js", "..\\..\\node_modules\\yaml\\dist\\compose\\compose-node.js", "..\\..\\node_modules\\yaml\\dist\\compose\\compose-doc.js", "..\\..\\node_modules\\yaml\\dist\\compose\\composer.js", "..\\..\\node_modules\\yaml\\dist\\parse\\cst-scalar.js", "..\\..\\node_modules\\yaml\\dist\\parse\\cst-stringify.js", "..\\..\\node_modules\\yaml\\dist\\parse\\cst-visit.js", "..\\..\\node_modules\\yaml\\dist\\parse\\cst.js", "..\\..\\node_modules\\yaml\\dist\\parse\\lexer.js", "..\\..\\node_modules\\yaml\\dist\\parse\\line-counter.js", "..\\..\\node_modules\\yaml\\dist\\parse\\parser.js", "..\\..\\node_modules\\yaml\\dist\\public-api.js", "..\\..\\node_modules\\yaml\\dist\\index.js", "..\\..\\src\\core\\expression-engine.ts", "..\\..\\src\\core\\event-queue.ts", "..\\..\\src\\core\\persistence.ts", "..\\..\\src\\core\\persistence-browser.ts", "..\\..\\src\\core\\state-manager.ts", "..\\..\\src\\core\\action-registry.ts", "..\\..\\src\\core\\context-adapter.ts", "..\\..\\src\\utils\\emitter.ts", "..\\..\\src\\core\\rule-engine.ts", "..\\..\\src\\utils\\utils.ts", "..\\..\\src\\core\\engine.ts", "..\\..\\node_modules\\@ark\\util\\out\\arrays.js", "..\\..\\node_modules\\@ark\\util\\out\\domain.js", "..\\..\\node_modules\\@ark\\util\\out\\errors.js", "..\\..\\node_modules\\@ark\\util\\out\\flatMorph.js", "..\\..\\node_modules\\@ark\\util\\out\\records.js", "..\\..\\node_modules\\@ark\\util\\out\\objectKinds.js", "..\\..\\node_modules\\@ark\\util\\out\\clone.js", "..\\..\\node_modules\\@ark\\util\\out\\functions.js", "..\\..\\node_modules\\@ark\\util\\out\\generics.js", "..\\..\\node_modules\\@ark\\util\\out\\hkt.js", "..\\..\\node_modules\\@ark\\util\\out\\isomorphic.js", "..\\..\\node_modules\\@ark\\util\\out\\strings.js", "..\\..\\node_modules\\@ark\\util\\out\\numbers.js", "..\\..\\node_modules\\@ark\\util\\out\\registry.js", "..\\..\\node_modules\\@ark\\util\\out\\primitive.js", "..\\..\\node_modules\\@ark\\util\\out\\serialize.js", "..\\..\\node_modules\\@ark\\util\\out\\path.js", "..\\..\\node_modules\\@ark\\util\\out\\scanner.js", "..\\..\\node_modules\\@ark\\util\\out\\traits.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\registry.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\compile.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\utils.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\implement.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\toJsonSchema.js", "..\\..\\node_modules\\@ark\\schema\\out\\config.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\errors.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\traversal.js", "..\\..\\node_modules\\@ark\\schema\\out\\node.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\disjoint.js", "..\\..\\node_modules\\@ark\\schema\\out\\shared\\intersections.js", "..\\..\\node_modules\\@ark\\schema\\out\\constraint.js", "..\\..\\node_modules\\@ark\\schema\\out\\generic.js", "..\\..\\node_modules\\@ark\\schema\\out\\predicate.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\divisor.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\range.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\after.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\before.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\exactLength.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\max.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\maxLength.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\min.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\minLength.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\kinds.js", "..\\..\\node_modules\\@ark\\schema\\out\\refinements\\pattern.js", "..\\..\\node_modules\\@ark\\schema\\out\\parse.js", "..\\..\\node_modules\\@ark\\schema\\out\\structure\\prop.js", "..\\..\\node_modules\\@ark\\schema\\out\\structure\\optional.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\root.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\utils.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\alias.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\basis.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\domain.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\intersection.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\morph.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\proto.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\union.js", "..\\..\\node_modules\\@ark\\schema\\out\\roots\\unit.js", "..\\..\\node_modules\\@ark\\schema\\out\\structure\\index.js", "..\\..\\node_modules\\@ark\\schema\\out\\structure\\required.js", "..\\..\\node_modules\\@ark\\schema\\out\\structure\\sequence.js", "..\\..\\node_modules\\@ark\\schema\\out\\structure\\structure.js", "..\\..\\node_modules\\@ark\\schema\\out\\kinds.js", "..\\..\\node_modules\\@ark\\schema\\out\\module.js", "..\\..\\node_modules\\@ark\\schema\\out\\scope.js", "..\\..\\node_modules\\@ark\\schema\\out\\structure\\shared.js", "..\\..\\node_modules\\@ark\\schema\\out\\intrinsic.js", "..\\..\\node_modules\\arkregex\\out\\regex.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operand\\date.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operand\\enclosed.js", "..\\..\\node_modules\\arktype\\out\\parser\\ast\\validate.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\tokens.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operand\\genericArgs.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operand\\unenclosed.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operand\\operand.js", "..\\..\\node_modules\\arktype\\out\\parser\\reduce\\shared.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operator\\bounds.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operator\\brand.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operator\\divisor.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operator\\operator.js", "..\\..\\node_modules\\arktype\\out\\parser\\shift\\operator\\default.js", "..\\..\\node_modules\\arktype\\out\\parser\\string.js", "..\\..\\node_modules\\arktype\\out\\parser\\reduce\\dynamic.js", "..\\..\\node_modules\\arktype\\out\\generic.js", "..\\..\\node_modules\\arktype\\out\\fn.js", "..\\..\\node_modules\\arktype\\out\\match.js", "..\\..\\node_modules\\arktype\\out\\parser\\property.js", "..\\..\\node_modules\\arktype\\out\\parser\\objectLiteral.js", "..\\..\\node_modules\\arktype\\out\\parser\\tupleExpressions.js", "..\\..\\node_modules\\arktype\\out\\parser\\tupleLiteral.js", "..\\..\\node_modules\\arktype\\out\\parser\\definition.js", "..\\..\\node_modules\\arktype\\out\\type.js", "..\\..\\node_modules\\arktype\\out\\scope.js", "..\\..\\node_modules\\arktype\\out\\keywords\\builtins.js", "..\\..\\node_modules\\arktype\\out\\keywords\\Array.js", "..\\..\\node_modules\\arktype\\out\\keywords\\FormData.js", "..\\..\\node_modules\\arktype\\out\\keywords\\TypedArray.js", "..\\..\\node_modules\\arktype\\out\\keywords\\constructors.js", "..\\..\\node_modules\\arktype\\out\\keywords\\number.js", "..\\..\\node_modules\\arktype\\out\\keywords\\string.js", "..\\..\\node_modules\\arktype\\out\\keywords\\ts.js", "..\\..\\node_modules\\arktype\\out\\keywords\\keywords.js", "..\\..\\src\\domain\\validator.ts", "..\\..\\src\\sdk\\builder.ts", "..\\..\\src\\sdk\\exporter.ts", "..\\..\\src\\core\\persistence.node.ts", "..\\..\\src\\io\\loader.node.ts"],
4
+ "sourcesContent": [
5
+ "'use strict';\n\nconst ALIAS = Symbol.for('yaml.alias');\nconst DOC = Symbol.for('yaml.document');\nconst MAP = Symbol.for('yaml.map');\nconst PAIR = Symbol.for('yaml.pair');\nconst SCALAR = Symbol.for('yaml.scalar');\nconst SEQ = Symbol.for('yaml.seq');\nconst NODE_TYPE = Symbol.for('yaml.node.type');\nconst isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;\nconst isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;\nconst isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;\nconst isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;\nconst isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;\nconst isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;\nfunction isCollection(node) {\n if (node && typeof node === 'object')\n switch (node[NODE_TYPE]) {\n case MAP:\n case SEQ:\n return true;\n }\n return false;\n}\nfunction isNode(node) {\n if (node && typeof node === 'object')\n switch (node[NODE_TYPE]) {\n case ALIAS:\n case MAP:\n case SCALAR:\n case SEQ:\n return true;\n }\n return false;\n}\nconst hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;\n\nexports.ALIAS = ALIAS;\nexports.DOC = DOC;\nexports.MAP = MAP;\nexports.NODE_TYPE = NODE_TYPE;\nexports.PAIR = PAIR;\nexports.SCALAR = SCALAR;\nexports.SEQ = SEQ;\nexports.hasAnchor = hasAnchor;\nexports.isAlias = isAlias;\nexports.isCollection = isCollection;\nexports.isDocument = isDocument;\nexports.isMap = isMap;\nexports.isNode = isNode;\nexports.isPair = isPair;\nexports.isScalar = isScalar;\nexports.isSeq = isSeq;\n",
6
+ "'use strict';\n\nvar identity = require('./nodes/identity.js');\n\nconst BREAK = Symbol('break visit');\nconst SKIP = Symbol('skip children');\nconst REMOVE = Symbol('remove node');\n/**\n * Apply a visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n * - `key`: For sequence values and map `Pair`, the node's index in the\n * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n * `null` for the root node.\n * - `node`: The current node.\n * - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n * - `undefined` (default): Do nothing and continue\n * - `visit.SKIP`: Do not visit the children of this node, continue with next\n * sibling\n * - `visit.BREAK`: Terminate traversal completely\n * - `visit.REMOVE`: Remove the current node, then continue with the next one\n * - `Node`: Replace the current node, then continue by visiting it\n * - `number`: While iterating the items of a sequence or map, set the index\n * of the next step. This is useful especially if the index of the current\n * node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nfunction visit(node, visitor) {\n const visitor_ = initVisitor(visitor);\n if (identity.isDocument(node)) {\n const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));\n if (cd === REMOVE)\n node.contents = null;\n }\n else\n visit_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisit.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisit.SKIP = SKIP;\n/** Remove the current node */\nvisit.REMOVE = REMOVE;\nfunction visit_(key, node, visitor, path) {\n const ctrl = callVisitor(key, node, visitor, path);\n if (identity.isNode(ctrl) || identity.isPair(ctrl)) {\n replaceNode(key, path, ctrl);\n return visit_(key, ctrl, visitor, path);\n }\n if (typeof ctrl !== 'symbol') {\n if (identity.isCollection(node)) {\n path = Object.freeze(path.concat(node));\n for (let i = 0; i < node.items.length; ++i) {\n const ci = visit_(i, node.items[i], visitor, path);\n if (typeof ci === 'number')\n i = ci - 1;\n else if (ci === BREAK)\n return BREAK;\n else if (ci === REMOVE) {\n node.items.splice(i, 1);\n i -= 1;\n }\n }\n }\n else if (identity.isPair(node)) {\n path = Object.freeze(path.concat(node));\n const ck = visit_('key', node.key, visitor, path);\n if (ck === BREAK)\n return BREAK;\n else if (ck === REMOVE)\n node.key = null;\n const cv = visit_('value', node.value, visitor, path);\n if (cv === BREAK)\n return BREAK;\n else if (cv === REMOVE)\n node.value = null;\n }\n }\n return ctrl;\n}\n/**\n * Apply an async visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n * - `key`: For sequence values and map `Pair`, the node's index in the\n * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n * `null` for the root node.\n * - `node`: The current node.\n * - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n * - `Promise`: Must resolve to one of the following values\n * - `undefined` (default): Do nothing and continue\n * - `visit.SKIP`: Do not visit the children of this node, continue with next\n * sibling\n * - `visit.BREAK`: Terminate traversal completely\n * - `visit.REMOVE`: Remove the current node, then continue with the next one\n * - `Node`: Replace the current node, then continue by visiting it\n * - `number`: While iterating the items of a sequence or map, set the index\n * of the next step. This is useful especially if the index of the current\n * node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nasync function visitAsync(node, visitor) {\n const visitor_ = initVisitor(visitor);\n if (identity.isDocument(node)) {\n const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));\n if (cd === REMOVE)\n node.contents = null;\n }\n else\n await visitAsync_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisitAsync.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisitAsync.SKIP = SKIP;\n/** Remove the current node */\nvisitAsync.REMOVE = REMOVE;\nasync function visitAsync_(key, node, visitor, path) {\n const ctrl = await callVisitor(key, node, visitor, path);\n if (identity.isNode(ctrl) || identity.isPair(ctrl)) {\n replaceNode(key, path, ctrl);\n return visitAsync_(key, ctrl, visitor, path);\n }\n if (typeof ctrl !== 'symbol') {\n if (identity.isCollection(node)) {\n path = Object.freeze(path.concat(node));\n for (let i = 0; i < node.items.length; ++i) {\n const ci = await visitAsync_(i, node.items[i], visitor, path);\n if (typeof ci === 'number')\n i = ci - 1;\n else if (ci === BREAK)\n return BREAK;\n else if (ci === REMOVE) {\n node.items.splice(i, 1);\n i -= 1;\n }\n }\n }\n else if (identity.isPair(node)) {\n path = Object.freeze(path.concat(node));\n const ck = await visitAsync_('key', node.key, visitor, path);\n if (ck === BREAK)\n return BREAK;\n else if (ck === REMOVE)\n node.key = null;\n const cv = await visitAsync_('value', node.value, visitor, path);\n if (cv === BREAK)\n return BREAK;\n else if (cv === REMOVE)\n node.value = null;\n }\n }\n return ctrl;\n}\nfunction initVisitor(visitor) {\n if (typeof visitor === 'object' &&\n (visitor.Collection || visitor.Node || visitor.Value)) {\n return Object.assign({\n Alias: visitor.Node,\n Map: visitor.Node,\n Scalar: visitor.Node,\n Seq: visitor.Node\n }, visitor.Value && {\n Map: visitor.Value,\n Scalar: visitor.Value,\n Seq: visitor.Value\n }, visitor.Collection && {\n Map: visitor.Collection,\n Seq: visitor.Collection\n }, visitor);\n }\n return visitor;\n}\nfunction callVisitor(key, node, visitor, path) {\n if (typeof visitor === 'function')\n return visitor(key, node, path);\n if (identity.isMap(node))\n return visitor.Map?.(key, node, path);\n if (identity.isSeq(node))\n return visitor.Seq?.(key, node, path);\n if (identity.isPair(node))\n return visitor.Pair?.(key, node, path);\n if (identity.isScalar(node))\n return visitor.Scalar?.(key, node, path);\n if (identity.isAlias(node))\n return visitor.Alias?.(key, node, path);\n return undefined;\n}\nfunction replaceNode(key, path, node) {\n const parent = path[path.length - 1];\n if (identity.isCollection(parent)) {\n parent.items[key] = node;\n }\n else if (identity.isPair(parent)) {\n if (key === 'key')\n parent.key = node;\n else\n parent.value = node;\n }\n else if (identity.isDocument(parent)) {\n parent.contents = node;\n }\n else {\n const pt = identity.isAlias(parent) ? 'alias' : 'scalar';\n throw new Error(`Cannot replace node with ${pt} parent`);\n }\n}\n\nexports.visit = visit;\nexports.visitAsync = visitAsync;\n",
7
+ "'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar visit = require('../visit.js');\n\nconst escapeChars = {\n '!': '%21',\n ',': '%2C',\n '[': '%5B',\n ']': '%5D',\n '{': '%7B',\n '}': '%7D'\n};\nconst escapeTagName = (tn) => tn.replace(/[!,[\\]{}]/g, ch => escapeChars[ch]);\nclass Directives {\n constructor(yaml, tags) {\n /**\n * The directives-end/doc-start marker `---`. If `null`, a marker may still be\n * included in the document's stringified representation.\n */\n this.docStart = null;\n /** The doc-end marker `...`. */\n this.docEnd = false;\n this.yaml = Object.assign({}, Directives.defaultYaml, yaml);\n this.tags = Object.assign({}, Directives.defaultTags, tags);\n }\n clone() {\n const copy = new Directives(this.yaml, this.tags);\n copy.docStart = this.docStart;\n return copy;\n }\n /**\n * During parsing, get a Directives instance for the current document and\n * update the stream state according to the current version's spec.\n */\n atDocument() {\n const res = new Directives(this.yaml, this.tags);\n switch (this.yaml.version) {\n case '1.1':\n this.atNextDocument = true;\n break;\n case '1.2':\n this.atNextDocument = false;\n this.yaml = {\n explicit: Directives.defaultYaml.explicit,\n version: '1.2'\n };\n this.tags = Object.assign({}, Directives.defaultTags);\n break;\n }\n return res;\n }\n /**\n * @param onError - May be called even if the action was successful\n * @returns `true` on success\n */\n add(line, onError) {\n if (this.atNextDocument) {\n this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' };\n this.tags = Object.assign({}, Directives.defaultTags);\n this.atNextDocument = false;\n }\n const parts = line.trim().split(/[ \\t]+/);\n const name = parts.shift();\n switch (name) {\n case '%TAG': {\n if (parts.length !== 2) {\n onError(0, '%TAG directive should contain exactly two parts');\n if (parts.length < 2)\n return false;\n }\n const [handle, prefix] = parts;\n this.tags[handle] = prefix;\n return true;\n }\n case '%YAML': {\n this.yaml.explicit = true;\n if (parts.length !== 1) {\n onError(0, '%YAML directive should contain exactly one part');\n return false;\n }\n const [version] = parts;\n if (version === '1.1' || version === '1.2') {\n this.yaml.version = version;\n return true;\n }\n else {\n const isValid = /^\\d+\\.\\d+$/.test(version);\n onError(6, `Unsupported YAML version ${version}`, isValid);\n return false;\n }\n }\n default:\n onError(0, `Unknown directive ${name}`, true);\n return false;\n }\n }\n /**\n * Resolves a tag, matching handles to those defined in %TAG directives.\n *\n * @returns Resolved tag, which may also be the non-specific tag `'!'` or a\n * `'!local'` tag, or `null` if unresolvable.\n */\n tagName(source, onError) {\n if (source === '!')\n return '!'; // non-specific tag\n if (source[0] !== '!') {\n onError(`Not a valid tag: ${source}`);\n return null;\n }\n if (source[1] === '<') {\n const verbatim = source.slice(2, -1);\n if (verbatim === '!' || verbatim === '!!') {\n onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);\n return null;\n }\n if (source[source.length - 1] !== '>')\n onError('Verbatim tags must end with a >');\n return verbatim;\n }\n const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);\n if (!suffix)\n onError(`The ${source} tag has no suffix`);\n const prefix = this.tags[handle];\n if (prefix) {\n try {\n return prefix + decodeURIComponent(suffix);\n }\n catch (error) {\n onError(String(error));\n return null;\n }\n }\n if (handle === '!')\n return source; // local tag\n onError(`Could not resolve tag: ${source}`);\n return null;\n }\n /**\n * Given a fully resolved tag, returns its printable string form,\n * taking into account current tag prefixes and defaults.\n */\n tagString(tag) {\n for (const [handle, prefix] of Object.entries(this.tags)) {\n if (tag.startsWith(prefix))\n return handle + escapeTagName(tag.substring(prefix.length));\n }\n return tag[0] === '!' ? tag : `!<${tag}>`;\n }\n toString(doc) {\n const lines = this.yaml.explicit\n ? [`%YAML ${this.yaml.version || '1.2'}`]\n : [];\n const tagEntries = Object.entries(this.tags);\n let tagNames;\n if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) {\n const tags = {};\n visit.visit(doc.contents, (_key, node) => {\n if (identity.isNode(node) && node.tag)\n tags[node.tag] = true;\n });\n tagNames = Object.keys(tags);\n }\n else\n tagNames = [];\n for (const [handle, prefix] of tagEntries) {\n if (handle === '!!' && prefix === 'tag:yaml.org,2002:')\n continue;\n if (!doc || tagNames.some(tn => tn.startsWith(prefix)))\n lines.push(`%TAG ${handle} ${prefix}`);\n }\n return lines.join('\\n');\n }\n}\nDirectives.defaultYaml = { explicit: false, version: '1.2' };\nDirectives.defaultTags = { '!!': 'tag:yaml.org,2002:' };\n\nexports.Directives = Directives;\n",
8
+ "'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar visit = require('../visit.js');\n\n/**\n * Verify that the input string is a valid anchor.\n *\n * Will throw on errors.\n */\nfunction anchorIsValid(anchor) {\n if (/[\\x00-\\x19\\s,[\\]{}]/.test(anchor)) {\n const sa = JSON.stringify(anchor);\n const msg = `Anchor must not contain whitespace or control characters: ${sa}`;\n throw new Error(msg);\n }\n return true;\n}\nfunction anchorNames(root) {\n const anchors = new Set();\n visit.visit(root, {\n Value(_key, node) {\n if (node.anchor)\n anchors.add(node.anchor);\n }\n });\n return anchors;\n}\n/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */\nfunction findNewAnchor(prefix, exclude) {\n for (let i = 1; true; ++i) {\n const name = `${prefix}${i}`;\n if (!exclude.has(name))\n return name;\n }\n}\nfunction createNodeAnchors(doc, prefix) {\n const aliasObjects = [];\n const sourceObjects = new Map();\n let prevAnchors = null;\n return {\n onAnchor: (source) => {\n aliasObjects.push(source);\n prevAnchors ?? (prevAnchors = anchorNames(doc));\n const anchor = findNewAnchor(prefix, prevAnchors);\n prevAnchors.add(anchor);\n return anchor;\n },\n /**\n * With circular references, the source node is only resolved after all\n * of its child nodes are. This is why anchors are set only after all of\n * the nodes have been created.\n */\n setAnchors: () => {\n for (const source of aliasObjects) {\n const ref = sourceObjects.get(source);\n if (typeof ref === 'object' &&\n ref.anchor &&\n (identity.isScalar(ref.node) || identity.isCollection(ref.node))) {\n ref.node.anchor = ref.anchor;\n }\n else {\n const error = new Error('Failed to resolve repeated object (this should not happen)');\n error.source = source;\n throw error;\n }\n }\n },\n sourceObjects\n };\n}\n\nexports.anchorIsValid = anchorIsValid;\nexports.anchorNames = anchorNames;\nexports.createNodeAnchors = createNodeAnchors;\nexports.findNewAnchor = findNewAnchor;\n",
9
+ "'use strict';\n\n/**\n * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,\n * in section 24.5.1.1 \"Runtime Semantics: InternalizeJSONProperty\" of the\n * 2021 edition: https://tc39.es/ecma262/#sec-json.parse\n *\n * Includes extensions for handling Map and Set objects.\n */\nfunction applyReviver(reviver, obj, key, val) {\n if (val && typeof val === 'object') {\n if (Array.isArray(val)) {\n for (let i = 0, len = val.length; i < len; ++i) {\n const v0 = val[i];\n const v1 = applyReviver(reviver, val, String(i), v0);\n // eslint-disable-next-line @typescript-eslint/no-array-delete\n if (v1 === undefined)\n delete val[i];\n else if (v1 !== v0)\n val[i] = v1;\n }\n }\n else if (val instanceof Map) {\n for (const k of Array.from(val.keys())) {\n const v0 = val.get(k);\n const v1 = applyReviver(reviver, val, k, v0);\n if (v1 === undefined)\n val.delete(k);\n else if (v1 !== v0)\n val.set(k, v1);\n }\n }\n else if (val instanceof Set) {\n for (const v0 of Array.from(val)) {\n const v1 = applyReviver(reviver, val, v0, v0);\n if (v1 === undefined)\n val.delete(v0);\n else if (v1 !== v0) {\n val.delete(v0);\n val.add(v1);\n }\n }\n }\n else {\n for (const [k, v0] of Object.entries(val)) {\n const v1 = applyReviver(reviver, val, k, v0);\n if (v1 === undefined)\n delete val[k];\n else if (v1 !== v0)\n val[k] = v1;\n }\n }\n }\n return reviver.call(obj, key, val);\n}\n\nexports.applyReviver = applyReviver;\n",
10
+ "'use strict';\n\nvar identity = require('./identity.js');\n\n/**\n * Recursively convert any node or its contents to native JavaScript\n *\n * @param value - The input value\n * @param arg - If `value` defines a `toJSON()` method, use this\n * as its first argument\n * @param ctx - Conversion context, originally set in Document#toJS(). If\n * `{ keep: true }` is not set, output should be suitable for JSON\n * stringification.\n */\nfunction toJS(value, arg, ctx) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n if (Array.isArray(value))\n return value.map((v, i) => toJS(v, String(i), ctx));\n if (value && typeof value.toJSON === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n if (!ctx || !identity.hasAnchor(value))\n return value.toJSON(arg, ctx);\n const data = { aliasCount: 0, count: 1, res: undefined };\n ctx.anchors.set(value, data);\n ctx.onCreate = res => {\n data.res = res;\n delete ctx.onCreate;\n };\n const res = value.toJSON(arg, ctx);\n if (ctx.onCreate)\n ctx.onCreate(res);\n return res;\n }\n if (typeof value === 'bigint' && !ctx?.keep)\n return Number(value);\n return value;\n}\n\nexports.toJS = toJS;\n",
11
+ "'use strict';\n\nvar applyReviver = require('../doc/applyReviver.js');\nvar identity = require('./identity.js');\nvar toJS = require('./toJS.js');\n\nclass NodeBase {\n constructor(type) {\n Object.defineProperty(this, identity.NODE_TYPE, { value: type });\n }\n /** Create a copy of this node. */\n clone() {\n const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n if (this.range)\n copy.range = this.range.slice();\n return copy;\n }\n /** A plain JavaScript representation of this node. */\n toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n if (!identity.isDocument(doc))\n throw new TypeError('A document argument is required');\n const ctx = {\n anchors: new Map(),\n doc,\n keep: true,\n mapAsMap: mapAsMap === true,\n mapKeyWarned: false,\n maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n };\n const res = toJS.toJS(this, '', ctx);\n if (typeof onAnchor === 'function')\n for (const { count, res } of ctx.anchors.values())\n onAnchor(res, count);\n return typeof reviver === 'function'\n ? applyReviver.applyReviver(reviver, { '': res }, '', res)\n : res;\n }\n}\n\nexports.NodeBase = NodeBase;\n",
12
+ "'use strict';\n\nvar anchors = require('../doc/anchors.js');\nvar visit = require('../visit.js');\nvar identity = require('./identity.js');\nvar Node = require('./Node.js');\nvar toJS = require('./toJS.js');\n\nclass Alias extends Node.NodeBase {\n constructor(source) {\n super(identity.ALIAS);\n this.source = source;\n Object.defineProperty(this, 'tag', {\n set() {\n throw new Error('Alias nodes cannot have tags');\n }\n });\n }\n /**\n * Resolve the value of this alias within `doc`, finding the last\n * instance of the `source` anchor before this node.\n */\n resolve(doc, ctx) {\n let nodes;\n if (ctx?.aliasResolveCache) {\n nodes = ctx.aliasResolveCache;\n }\n else {\n nodes = [];\n visit.visit(doc, {\n Node: (_key, node) => {\n if (identity.isAlias(node) || identity.hasAnchor(node))\n nodes.push(node);\n }\n });\n if (ctx)\n ctx.aliasResolveCache = nodes;\n }\n let found = undefined;\n for (const node of nodes) {\n if (node === this)\n break;\n if (node.anchor === this.source)\n found = node;\n }\n return found;\n }\n toJSON(_arg, ctx) {\n if (!ctx)\n return { source: this.source };\n const { anchors, doc, maxAliasCount } = ctx;\n const source = this.resolve(doc, ctx);\n if (!source) {\n const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n throw new ReferenceError(msg);\n }\n let data = anchors.get(source);\n if (!data) {\n // Resolve anchors for Node.prototype.toJS()\n toJS.toJS(source, null, ctx);\n data = anchors.get(source);\n }\n /* istanbul ignore if */\n if (data?.res === undefined) {\n const msg = 'This should not happen: Alias anchor was not resolved?';\n throw new ReferenceError(msg);\n }\n if (maxAliasCount >= 0) {\n data.count += 1;\n if (data.aliasCount === 0)\n data.aliasCount = getAliasCount(doc, source, anchors);\n if (data.count * data.aliasCount > maxAliasCount) {\n const msg = 'Excessive alias count indicates a resource exhaustion attack';\n throw new ReferenceError(msg);\n }\n }\n return data.res;\n }\n toString(ctx, _onComment, _onChompKeep) {\n const src = `*${this.source}`;\n if (ctx) {\n anchors.anchorIsValid(this.source);\n if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {\n const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n throw new Error(msg);\n }\n if (ctx.implicitKey)\n return `${src} `;\n }\n return src;\n }\n}\nfunction getAliasCount(doc, node, anchors) {\n if (identity.isAlias(node)) {\n const source = node.resolve(doc);\n const anchor = anchors && source && anchors.get(source);\n return anchor ? anchor.count * anchor.aliasCount : 0;\n }\n else if (identity.isCollection(node)) {\n let count = 0;\n for (const item of node.items) {\n const c = getAliasCount(doc, item, anchors);\n if (c > count)\n count = c;\n }\n return count;\n }\n else if (identity.isPair(node)) {\n const kc = getAliasCount(doc, node.key, anchors);\n const vc = getAliasCount(doc, node.value, anchors);\n return Math.max(kc, vc);\n }\n return 1;\n}\n\nexports.Alias = Alias;\n",
13
+ "'use strict';\n\nvar identity = require('./identity.js');\nvar Node = require('./Node.js');\nvar toJS = require('./toJS.js');\n\nconst isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');\nclass Scalar extends Node.NodeBase {\n constructor(value) {\n super(identity.SCALAR);\n this.value = value;\n }\n toJSON(arg, ctx) {\n return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);\n }\n toString() {\n return String(this.value);\n }\n}\nScalar.BLOCK_FOLDED = 'BLOCK_FOLDED';\nScalar.BLOCK_LITERAL = 'BLOCK_LITERAL';\nScalar.PLAIN = 'PLAIN';\nScalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE';\nScalar.QUOTE_SINGLE = 'QUOTE_SINGLE';\n\nexports.Scalar = Scalar;\nexports.isScalarValue = isScalarValue;\n",
14
+ "'use strict';\n\nvar Alias = require('../nodes/Alias.js');\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\n\nconst defaultTagPrefix = 'tag:yaml.org,2002:';\nfunction findTagObject(value, tagName, tags) {\n if (tagName) {\n const match = tags.filter(t => t.tag === tagName);\n const tagObj = match.find(t => !t.format) ?? match[0];\n if (!tagObj)\n throw new Error(`Tag ${tagName} not found`);\n return tagObj;\n }\n return tags.find(t => t.identify?.(value) && !t.format);\n}\nfunction createNode(value, tagName, ctx) {\n if (identity.isDocument(value))\n value = value.contents;\n if (identity.isNode(value))\n return value;\n if (identity.isPair(value)) {\n const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx);\n map.items.push(value);\n return map;\n }\n if (value instanceof String ||\n value instanceof Number ||\n value instanceof Boolean ||\n (typeof BigInt !== 'undefined' && value instanceof BigInt) // not supported everywhere\n ) {\n // https://tc39.es/ecma262/#sec-serializejsonproperty\n value = value.valueOf();\n }\n const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;\n // Detect duplicate references to the same object & use Alias nodes for all\n // after first. The `ref` wrapper allows for circular references to resolve.\n let ref = undefined;\n if (aliasDuplicateObjects && value && typeof value === 'object') {\n ref = sourceObjects.get(value);\n if (ref) {\n ref.anchor ?? (ref.anchor = onAnchor(value));\n return new Alias.Alias(ref.anchor);\n }\n else {\n ref = { anchor: null, node: null };\n sourceObjects.set(value, ref);\n }\n }\n if (tagName?.startsWith('!!'))\n tagName = defaultTagPrefix + tagName.slice(2);\n let tagObj = findTagObject(value, tagName, schema.tags);\n if (!tagObj) {\n if (value && typeof value.toJSON === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n value = value.toJSON();\n }\n if (!value || typeof value !== 'object') {\n const node = new Scalar.Scalar(value);\n if (ref)\n ref.node = node;\n return node;\n }\n tagObj =\n value instanceof Map\n ? schema[identity.MAP]\n : Symbol.iterator in Object(value)\n ? schema[identity.SEQ]\n : schema[identity.MAP];\n }\n if (onTagObj) {\n onTagObj(tagObj);\n delete ctx.onTagObj;\n }\n const node = tagObj?.createNode\n ? tagObj.createNode(ctx.schema, value, ctx)\n : typeof tagObj?.nodeClass?.from === 'function'\n ? tagObj.nodeClass.from(ctx.schema, value, ctx)\n : new Scalar.Scalar(value);\n if (tagName)\n node.tag = tagName;\n else if (!tagObj.default)\n node.tag = tagObj.tag;\n if (ref)\n ref.node = node;\n return node;\n}\n\nexports.createNode = createNode;\n",
15
+ "'use strict';\n\nvar createNode = require('../doc/createNode.js');\nvar identity = require('./identity.js');\nvar Node = require('./Node.js');\n\nfunction collectionFromPath(schema, path, value) {\n let v = value;\n for (let i = path.length - 1; i >= 0; --i) {\n const k = path[i];\n if (typeof k === 'number' && Number.isInteger(k) && k >= 0) {\n const a = [];\n a[k] = v;\n v = a;\n }\n else {\n v = new Map([[k, v]]);\n }\n }\n return createNode.createNode(v, undefined, {\n aliasDuplicateObjects: false,\n keepUndefined: false,\n onAnchor: () => {\n throw new Error('This should not happen, please report a bug.');\n },\n schema,\n sourceObjects: new Map()\n });\n}\n// Type guard is intentionally a little wrong so as to be more useful,\n// as it does not cover untypable empty non-string iterables (e.g. []).\nconst isEmptyPath = (path) => path == null ||\n (typeof path === 'object' && !!path[Symbol.iterator]().next().done);\nclass Collection extends Node.NodeBase {\n constructor(type, schema) {\n super(type);\n Object.defineProperty(this, 'schema', {\n value: schema,\n configurable: true,\n enumerable: false,\n writable: true\n });\n }\n /**\n * Create a copy of this collection.\n *\n * @param schema - If defined, overwrites the original's schema\n */\n clone(schema) {\n const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n if (schema)\n copy.schema = schema;\n copy.items = copy.items.map(it => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it);\n if (this.range)\n copy.range = this.range.slice();\n return copy;\n }\n /**\n * Adds a value to the collection. For `!!map` and `!!omap` the value must\n * be a Pair instance or a `{ key, value }` object, which may not have a key\n * that already exists in the map.\n */\n addIn(path, value) {\n if (isEmptyPath(path))\n this.add(value);\n else {\n const [key, ...rest] = path;\n const node = this.get(key, true);\n if (identity.isCollection(node))\n node.addIn(rest, value);\n else if (node === undefined && this.schema)\n this.set(key, collectionFromPath(this.schema, rest, value));\n else\n throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n }\n }\n /**\n * Removes a value from the collection.\n * @returns `true` if the item was found and removed.\n */\n deleteIn(path) {\n const [key, ...rest] = path;\n if (rest.length === 0)\n return this.delete(key);\n const node = this.get(key, true);\n if (identity.isCollection(node))\n return node.deleteIn(rest);\n else\n throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n }\n /**\n * Returns item at `key`, or `undefined` if not found. By default unwraps\n * scalar values from their surrounding node; to disable set `keepScalar` to\n * `true` (collections are always returned intact).\n */\n getIn(path, keepScalar) {\n const [key, ...rest] = path;\n const node = this.get(key, true);\n if (rest.length === 0)\n return !keepScalar && identity.isScalar(node) ? node.value : node;\n else\n return identity.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;\n }\n hasAllNullValues(allowScalar) {\n return this.items.every(node => {\n if (!identity.isPair(node))\n return false;\n const n = node.value;\n return (n == null ||\n (allowScalar &&\n identity.isScalar(n) &&\n n.value == null &&\n !n.commentBefore &&\n !n.comment &&\n !n.tag));\n });\n }\n /**\n * Checks if the collection includes a value with the key `key`.\n */\n hasIn(path) {\n const [key, ...rest] = path;\n if (rest.length === 0)\n return this.has(key);\n const node = this.get(key, true);\n return identity.isCollection(node) ? node.hasIn(rest) : false;\n }\n /**\n * Sets a value in this collection. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n */\n setIn(path, value) {\n const [key, ...rest] = path;\n if (rest.length === 0) {\n this.set(key, value);\n }\n else {\n const node = this.get(key, true);\n if (identity.isCollection(node))\n node.setIn(rest, value);\n else if (node === undefined && this.schema)\n this.set(key, collectionFromPath(this.schema, rest, value));\n else\n throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n }\n }\n}\n\nexports.Collection = Collection;\nexports.collectionFromPath = collectionFromPath;\nexports.isEmptyPath = isEmptyPath;\n",
16
+ "'use strict';\n\n/**\n * Stringifies a comment.\n *\n * Empty comment lines are left empty,\n * lines consisting of a single space are replaced by `#`,\n * and all other lines are prefixed with a `#`.\n */\nconst stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#');\nfunction indentComment(comment, indent) {\n if (/^\\n+$/.test(comment))\n return comment.substring(1);\n return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;\n}\nconst lineComment = (str, indent, comment) => str.endsWith('\\n')\n ? indentComment(comment, indent)\n : comment.includes('\\n')\n ? '\\n' + indentComment(comment, indent)\n : (str.endsWith(' ') ? '' : ' ') + comment;\n\nexports.indentComment = indentComment;\nexports.lineComment = lineComment;\nexports.stringifyComment = stringifyComment;\n",
17
+ "'use strict';\n\nconst FOLD_FLOW = 'flow';\nconst FOLD_BLOCK = 'block';\nconst FOLD_QUOTED = 'quoted';\n/**\n * Tries to keep input at up to `lineWidth` characters, splitting only on spaces\n * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are\n * terminated with `\\n` and started with `indent`.\n */\nfunction foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {\n if (!lineWidth || lineWidth < 0)\n return text;\n if (lineWidth < minContentWidth)\n minContentWidth = 0;\n const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);\n if (text.length <= endStep)\n return text;\n const folds = [];\n const escapedFolds = {};\n let end = lineWidth - indent.length;\n if (typeof indentAtStart === 'number') {\n if (indentAtStart > lineWidth - Math.max(2, minContentWidth))\n folds.push(0);\n else\n end = lineWidth - indentAtStart;\n }\n let split = undefined;\n let prev = undefined;\n let overflow = false;\n let i = -1;\n let escStart = -1;\n let escEnd = -1;\n if (mode === FOLD_BLOCK) {\n i = consumeMoreIndentedLines(text, i, indent.length);\n if (i !== -1)\n end = i + endStep;\n }\n for (let ch; (ch = text[(i += 1)]);) {\n if (mode === FOLD_QUOTED && ch === '\\\\') {\n escStart = i;\n switch (text[i + 1]) {\n case 'x':\n i += 3;\n break;\n case 'u':\n i += 5;\n break;\n case 'U':\n i += 9;\n break;\n default:\n i += 1;\n }\n escEnd = i;\n }\n if (ch === '\\n') {\n if (mode === FOLD_BLOCK)\n i = consumeMoreIndentedLines(text, i, indent.length);\n end = i + indent.length + endStep;\n split = undefined;\n }\n else {\n if (ch === ' ' &&\n prev &&\n prev !== ' ' &&\n prev !== '\\n' &&\n prev !== '\\t') {\n // space surrounded by non-space can be replaced with newline + indent\n const next = text[i + 1];\n if (next && next !== ' ' && next !== '\\n' && next !== '\\t')\n split = i;\n }\n if (i >= end) {\n if (split) {\n folds.push(split);\n end = split + endStep;\n split = undefined;\n }\n else if (mode === FOLD_QUOTED) {\n // white-space collected at end may stretch past lineWidth\n while (prev === ' ' || prev === '\\t') {\n prev = ch;\n ch = text[(i += 1)];\n overflow = true;\n }\n // Account for newline escape, but don't break preceding escape\n const j = i > escEnd + 1 ? i - 2 : escStart - 1;\n // Bail out if lineWidth & minContentWidth are shorter than an escape string\n if (escapedFolds[j])\n return text;\n folds.push(j);\n escapedFolds[j] = true;\n end = j + endStep;\n split = undefined;\n }\n else {\n overflow = true;\n }\n }\n }\n prev = ch;\n }\n if (overflow && onOverflow)\n onOverflow();\n if (folds.length === 0)\n return text;\n if (onFold)\n onFold();\n let res = text.slice(0, folds[0]);\n for (let i = 0; i < folds.length; ++i) {\n const fold = folds[i];\n const end = folds[i + 1] || text.length;\n if (fold === 0)\n res = `\\n${indent}${text.slice(0, end)}`;\n else {\n if (mode === FOLD_QUOTED && escapedFolds[fold])\n res += `${text[fold]}\\\\`;\n res += `\\n${indent}${text.slice(fold + 1, end)}`;\n }\n }\n return res;\n}\n/**\n * Presumes `i + 1` is at the start of a line\n * @returns index of last newline in more-indented block\n */\nfunction consumeMoreIndentedLines(text, i, indent) {\n let end = i;\n let start = i + 1;\n let ch = text[start];\n while (ch === ' ' || ch === '\\t') {\n if (i < start + indent) {\n ch = text[++i];\n }\n else {\n do {\n ch = text[++i];\n } while (ch && ch !== '\\n');\n end = i;\n start = i + 1;\n ch = text[start];\n }\n }\n return end;\n}\n\nexports.FOLD_BLOCK = FOLD_BLOCK;\nexports.FOLD_FLOW = FOLD_FLOW;\nexports.FOLD_QUOTED = FOLD_QUOTED;\nexports.foldFlowLines = foldFlowLines;\n",
18
+ "'use strict';\n\nvar Scalar = require('../nodes/Scalar.js');\nvar foldFlowLines = require('./foldFlowLines.js');\n\nconst getFoldOptions = (ctx, isBlock) => ({\n indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,\n lineWidth: ctx.options.lineWidth,\n minContentWidth: ctx.options.minContentWidth\n});\n// Also checks for lines starting with %, as parsing the output as YAML 1.1 will\n// presume that's starting a new document.\nconst containsDocumentMarker = (str) => /^(%|---|\\.\\.\\.)/m.test(str);\nfunction lineLengthOverLimit(str, lineWidth, indentLength) {\n if (!lineWidth || lineWidth < 0)\n return false;\n const limit = lineWidth - indentLength;\n const strLen = str.length;\n if (strLen <= limit)\n return false;\n for (let i = 0, start = 0; i < strLen; ++i) {\n if (str[i] === '\\n') {\n if (i - start > limit)\n return true;\n start = i + 1;\n if (strLen - start <= limit)\n return false;\n }\n }\n return true;\n}\nfunction doubleQuotedString(value, ctx) {\n const json = JSON.stringify(value);\n if (ctx.options.doubleQuotedAsJSON)\n return json;\n const { implicitKey } = ctx;\n const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;\n const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');\n let str = '';\n let start = 0;\n for (let i = 0, ch = json[i]; ch; ch = json[++i]) {\n if (ch === ' ' && json[i + 1] === '\\\\' && json[i + 2] === 'n') {\n // space before newline needs to be escaped to not be folded\n str += json.slice(start, i) + '\\\\ ';\n i += 1;\n start = i;\n ch = '\\\\';\n }\n if (ch === '\\\\')\n switch (json[i + 1]) {\n case 'u':\n {\n str += json.slice(start, i);\n const code = json.substr(i + 2, 4);\n switch (code) {\n case '0000':\n str += '\\\\0';\n break;\n case '0007':\n str += '\\\\a';\n break;\n case '000b':\n str += '\\\\v';\n break;\n case '001b':\n str += '\\\\e';\n break;\n case '0085':\n str += '\\\\N';\n break;\n case '00a0':\n str += '\\\\_';\n break;\n case '2028':\n str += '\\\\L';\n break;\n case '2029':\n str += '\\\\P';\n break;\n default:\n if (code.substr(0, 2) === '00')\n str += '\\\\x' + code.substr(2);\n else\n str += json.substr(i, 6);\n }\n i += 5;\n start = i + 1;\n }\n break;\n case 'n':\n if (implicitKey ||\n json[i + 2] === '\"' ||\n json.length < minMultiLineLength) {\n i += 1;\n }\n else {\n // folding will eat first newline\n str += json.slice(start, i) + '\\n\\n';\n while (json[i + 2] === '\\\\' &&\n json[i + 3] === 'n' &&\n json[i + 4] !== '\"') {\n str += '\\n';\n i += 2;\n }\n str += indent;\n // space after newline needs to be escaped to not be folded\n if (json[i + 2] === ' ')\n str += '\\\\';\n i += 1;\n start = i + 1;\n }\n break;\n default:\n i += 1;\n }\n }\n str = start ? str + json.slice(start) : json;\n return implicitKey\n ? str\n : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));\n}\nfunction singleQuotedString(value, ctx) {\n if (ctx.options.singleQuote === false ||\n (ctx.implicitKey && value.includes('\\n')) ||\n /[ \\t]\\n|\\n[ \\t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline\n )\n return doubleQuotedString(value, ctx);\n const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');\n const res = \"'\" + value.replace(/'/g, \"''\").replace(/\\n+/g, `$&\\n${indent}`) + \"'\";\n return ctx.implicitKey\n ? res\n : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction quotedString(value, ctx) {\n const { singleQuote } = ctx.options;\n let qs;\n if (singleQuote === false)\n qs = doubleQuotedString;\n else {\n const hasDouble = value.includes('\"');\n const hasSingle = value.includes(\"'\");\n if (hasDouble && !hasSingle)\n qs = singleQuotedString;\n else if (hasSingle && !hasDouble)\n qs = doubleQuotedString;\n else\n qs = singleQuote ? singleQuotedString : doubleQuotedString;\n }\n return qs(value, ctx);\n}\n// The negative lookbehind avoids a polynomial search,\n// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind\nlet blockEndNewlines;\ntry {\n blockEndNewlines = new RegExp('(^|(?<!\\n))\\n+(?!\\n|$)', 'g');\n}\ncatch {\n blockEndNewlines = /\\n+(?!\\n|$)/g;\n}\nfunction blockString({ comment, type, value }, ctx, onComment, onChompKeep) {\n const { blockQuote, commentString, lineWidth } = ctx.options;\n // 1. Block can't end in whitespace unless the last line is non-empty.\n // 2. Strings consisting of only whitespace are best rendered explicitly.\n if (!blockQuote || /\\n[\\t ]+$/.test(value)) {\n return quotedString(value, ctx);\n }\n const indent = ctx.indent ||\n (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : '');\n const literal = blockQuote === 'literal'\n ? true\n : blockQuote === 'folded' || type === Scalar.Scalar.BLOCK_FOLDED\n ? false\n : type === Scalar.Scalar.BLOCK_LITERAL\n ? true\n : !lineLengthOverLimit(value, lineWidth, indent.length);\n if (!value)\n return literal ? '|\\n' : '>\\n';\n // determine chomping from whitespace at value end\n let chomp;\n let endStart;\n for (endStart = value.length; endStart > 0; --endStart) {\n const ch = value[endStart - 1];\n if (ch !== '\\n' && ch !== '\\t' && ch !== ' ')\n break;\n }\n let end = value.substring(endStart);\n const endNlPos = end.indexOf('\\n');\n if (endNlPos === -1) {\n chomp = '-'; // strip\n }\n else if (value === end || endNlPos !== end.length - 1) {\n chomp = '+'; // keep\n if (onChompKeep)\n onChompKeep();\n }\n else {\n chomp = ''; // clip\n }\n if (end) {\n value = value.slice(0, -end.length);\n if (end[end.length - 1] === '\\n')\n end = end.slice(0, -1);\n end = end.replace(blockEndNewlines, `$&${indent}`);\n }\n // determine indent indicator from whitespace at value start\n let startWithSpace = false;\n let startEnd;\n let startNlPos = -1;\n for (startEnd = 0; startEnd < value.length; ++startEnd) {\n const ch = value[startEnd];\n if (ch === ' ')\n startWithSpace = true;\n else if (ch === '\\n')\n startNlPos = startEnd;\n else\n break;\n }\n let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);\n if (start) {\n value = value.substring(start.length);\n start = start.replace(/\\n+/g, `$&${indent}`);\n }\n const indentSize = indent ? '2' : '1'; // root is at -1\n // Leading | or > is added later\n let header = (startWithSpace ? indentSize : '') + chomp;\n if (comment) {\n header += ' ' + commentString(comment.replace(/ ?[\\r\\n]+/g, ' '));\n if (onComment)\n onComment();\n }\n if (!literal) {\n const foldedValue = value\n .replace(/\\n+/g, '\\n$&')\n .replace(/(?:^|\\n)([\\t ].*)(?:([\\n\\t ]*)\\n(?![\\n\\t ]))?/g, '$1$2') // more-indented lines aren't folded\n // ^ more-ind. ^ empty ^ capture next empty lines only at end of indent\n .replace(/\\n+/g, `$&${indent}`);\n let literalFallback = false;\n const foldOptions = getFoldOptions(ctx, true);\n if (blockQuote !== 'folded' && type !== Scalar.Scalar.BLOCK_FOLDED) {\n foldOptions.onOverflow = () => {\n literalFallback = true;\n };\n }\n const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);\n if (!literalFallback)\n return `>${header}\\n${indent}${body}`;\n }\n value = value.replace(/\\n+/g, `$&${indent}`);\n return `|${header}\\n${indent}${start}${value}${end}`;\n}\nfunction plainString(item, ctx, onComment, onChompKeep) {\n const { type, value } = item;\n const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;\n if ((implicitKey && value.includes('\\n')) ||\n (inFlow && /[[\\]{},]/.test(value))) {\n return quotedString(value, ctx);\n }\n if (/^[\\n\\t ,[\\]{}#&*!|>'\"%@`]|^[?-]$|^[?-][ \\t]|[\\n:][ \\t]|[ \\t]\\n|[\\n\\t ]#|[\\n\\t :]$/.test(value)) {\n // not allowed:\n // - '-' or '?'\n // - start with an indicator character (except [?:-]) or /[?-] /\n // - '\\n ', ': ' or ' \\n' anywhere\n // - '#' not preceded by a non-space char\n // - end with ' ' or ':'\n return implicitKey || inFlow || !value.includes('\\n')\n ? quotedString(value, ctx)\n : blockString(item, ctx, onComment, onChompKeep);\n }\n if (!implicitKey &&\n !inFlow &&\n type !== Scalar.Scalar.PLAIN &&\n value.includes('\\n')) {\n // Where allowed & type not set explicitly, prefer block style for multiline strings\n return blockString(item, ctx, onComment, onChompKeep);\n }\n if (containsDocumentMarker(value)) {\n if (indent === '') {\n ctx.forceBlockIndent = true;\n return blockString(item, ctx, onComment, onChompKeep);\n }\n else if (implicitKey && indent === indentStep) {\n return quotedString(value, ctx);\n }\n }\n const str = value.replace(/\\n+/g, `$&\\n${indent}`);\n // Verify that output will be parsed as a string, as e.g. plain numbers and\n // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),\n // and others in v1.1.\n if (actualString) {\n const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str);\n const { compat, tags } = ctx.doc.schema;\n if (tags.some(test) || compat?.some(test))\n return quotedString(value, ctx);\n }\n return implicitKey\n ? str\n : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction stringifyString(item, ctx, onComment, onChompKeep) {\n const { implicitKey, inFlow } = ctx;\n const ss = typeof item.value === 'string'\n ? item\n : Object.assign({}, item, { value: String(item.value) });\n let { type } = item;\n if (type !== Scalar.Scalar.QUOTE_DOUBLE) {\n // force double quotes on control characters & unpaired surrogates\n if (/[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x9f\\u{D800}-\\u{DFFF}]/u.test(ss.value))\n type = Scalar.Scalar.QUOTE_DOUBLE;\n }\n const _stringify = (_type) => {\n switch (_type) {\n case Scalar.Scalar.BLOCK_FOLDED:\n case Scalar.Scalar.BLOCK_LITERAL:\n return implicitKey || inFlow\n ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers\n : blockString(ss, ctx, onComment, onChompKeep);\n case Scalar.Scalar.QUOTE_DOUBLE:\n return doubleQuotedString(ss.value, ctx);\n case Scalar.Scalar.QUOTE_SINGLE:\n return singleQuotedString(ss.value, ctx);\n case Scalar.Scalar.PLAIN:\n return plainString(ss, ctx, onComment, onChompKeep);\n default:\n return null;\n }\n };\n let res = _stringify(type);\n if (res === null) {\n const { defaultKeyType, defaultStringType } = ctx.options;\n const t = (implicitKey && defaultKeyType) || defaultStringType;\n res = _stringify(t);\n if (res === null)\n throw new Error(`Unsupported default string type ${t}`);\n }\n return res;\n}\n\nexports.stringifyString = stringifyString;\n",
19
+ "'use strict';\n\nvar anchors = require('../doc/anchors.js');\nvar identity = require('../nodes/identity.js');\nvar stringifyComment = require('./stringifyComment.js');\nvar stringifyString = require('./stringifyString.js');\n\nfunction createStringifyContext(doc, options) {\n const opt = Object.assign({\n blockQuote: true,\n commentString: stringifyComment.stringifyComment,\n defaultKeyType: null,\n defaultStringType: 'PLAIN',\n directives: null,\n doubleQuotedAsJSON: false,\n doubleQuotedMinMultiLineLength: 40,\n falseStr: 'false',\n flowCollectionPadding: true,\n indentSeq: true,\n lineWidth: 80,\n minContentWidth: 20,\n nullStr: 'null',\n simpleKeys: false,\n singleQuote: null,\n trueStr: 'true',\n verifyAliasOrder: true\n }, doc.schema.toStringOptions, options);\n let inFlow;\n switch (opt.collectionStyle) {\n case 'block':\n inFlow = false;\n break;\n case 'flow':\n inFlow = true;\n break;\n default:\n inFlow = null;\n }\n return {\n anchors: new Set(),\n doc,\n flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '',\n indent: '',\n indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ',\n inFlow,\n options: opt\n };\n}\nfunction getTagObject(tags, item) {\n if (item.tag) {\n const match = tags.filter(t => t.tag === item.tag);\n if (match.length > 0)\n return match.find(t => t.format === item.format) ?? match[0];\n }\n let tagObj = undefined;\n let obj;\n if (identity.isScalar(item)) {\n obj = item.value;\n let match = tags.filter(t => t.identify?.(obj));\n if (match.length > 1) {\n const testMatch = match.filter(t => t.test);\n if (testMatch.length > 0)\n match = testMatch;\n }\n tagObj =\n match.find(t => t.format === item.format) ?? match.find(t => !t.format);\n }\n else {\n obj = item;\n tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);\n }\n if (!tagObj) {\n const name = obj?.constructor?.name ?? (obj === null ? 'null' : typeof obj);\n throw new Error(`Tag not resolved for ${name} value`);\n }\n return tagObj;\n}\n// needs to be called before value stringifier to allow for circular anchor refs\nfunction stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {\n if (!doc.directives)\n return '';\n const props = [];\n const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor;\n if (anchor && anchors.anchorIsValid(anchor)) {\n anchors$1.add(anchor);\n props.push(`&${anchor}`);\n }\n const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);\n if (tag)\n props.push(doc.directives.tagString(tag));\n return props.join(' ');\n}\nfunction stringify(item, ctx, onComment, onChompKeep) {\n if (identity.isPair(item))\n return item.toString(ctx, onComment, onChompKeep);\n if (identity.isAlias(item)) {\n if (ctx.doc.directives)\n return item.toString(ctx);\n if (ctx.resolvedAliases?.has(item)) {\n throw new TypeError(`Cannot stringify circular structure without alias nodes`);\n }\n else {\n if (ctx.resolvedAliases)\n ctx.resolvedAliases.add(item);\n else\n ctx.resolvedAliases = new Set([item]);\n item = item.resolve(ctx.doc);\n }\n }\n let tagObj = undefined;\n const node = identity.isNode(item)\n ? item\n : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });\n tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));\n const props = stringifyProps(node, tagObj, ctx);\n if (props.length > 0)\n ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;\n const str = typeof tagObj.stringify === 'function'\n ? tagObj.stringify(node, ctx, onComment, onChompKeep)\n : identity.isScalar(node)\n ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep)\n : node.toString(ctx, onComment, onChompKeep);\n if (!props)\n return str;\n return identity.isScalar(node) || str[0] === '{' || str[0] === '['\n ? `${props} ${str}`\n : `${props}\\n${ctx.indent}${str}`;\n}\n\nexports.createStringifyContext = createStringifyContext;\nexports.stringify = stringify;\n",
20
+ "'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\nvar stringify = require('./stringify.js');\nvar stringifyComment = require('./stringifyComment.js');\n\nfunction stringifyPair({ key, value }, ctx, onComment, onChompKeep) {\n const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;\n let keyComment = (identity.isNode(key) && key.comment) || null;\n if (simpleKeys) {\n if (keyComment) {\n throw new Error('With simple keys, key nodes cannot have comments');\n }\n if (identity.isCollection(key) || (!identity.isNode(key) && typeof key === 'object')) {\n const msg = 'With simple keys, collection cannot be used as a key value';\n throw new Error(msg);\n }\n }\n let explicitKey = !simpleKeys &&\n (!key ||\n (keyComment && value == null && !ctx.inFlow) ||\n identity.isCollection(key) ||\n (identity.isScalar(key)\n ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL\n : typeof key === 'object'));\n ctx = Object.assign({}, ctx, {\n allNullValues: false,\n implicitKey: !explicitKey && (simpleKeys || !allNullValues),\n indent: indent + indentStep\n });\n let keyCommentDone = false;\n let chompKeep = false;\n let str = stringify.stringify(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true));\n if (!explicitKey && !ctx.inFlow && str.length > 1024) {\n if (simpleKeys)\n throw new Error('With simple keys, single line scalar must not span more than 1024 characters');\n explicitKey = true;\n }\n if (ctx.inFlow) {\n if (allNullValues || value == null) {\n if (keyCommentDone && onComment)\n onComment();\n return str === '' ? '?' : explicitKey ? `? ${str}` : str;\n }\n }\n else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) {\n str = `? ${str}`;\n if (keyComment && !keyCommentDone) {\n str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));\n }\n else if (chompKeep && onChompKeep)\n onChompKeep();\n return str;\n }\n if (keyCommentDone)\n keyComment = null;\n if (explicitKey) {\n if (keyComment)\n str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));\n str = `? ${str}\\n${indent}:`;\n }\n else {\n str = `${str}:`;\n if (keyComment)\n str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));\n }\n let vsb, vcb, valueComment;\n if (identity.isNode(value)) {\n vsb = !!value.spaceBefore;\n vcb = value.commentBefore;\n valueComment = value.comment;\n }\n else {\n vsb = false;\n vcb = null;\n valueComment = null;\n if (value && typeof value === 'object')\n value = doc.createNode(value);\n }\n ctx.implicitKey = false;\n if (!explicitKey && !keyComment && identity.isScalar(value))\n ctx.indentAtStart = str.length + 1;\n chompKeep = false;\n if (!indentSeq &&\n indentStep.length >= 2 &&\n !ctx.inFlow &&\n !explicitKey &&\n identity.isSeq(value) &&\n !value.flow &&\n !value.tag &&\n !value.anchor) {\n // If indentSeq === false, consider '- ' as part of indentation where possible\n ctx.indent = ctx.indent.substring(2);\n }\n let valueCommentDone = false;\n const valueStr = stringify.stringify(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));\n let ws = ' ';\n if (keyComment || vsb || vcb) {\n ws = vsb ? '\\n' : '';\n if (vcb) {\n const cs = commentString(vcb);\n ws += `\\n${stringifyComment.indentComment(cs, ctx.indent)}`;\n }\n if (valueStr === '' && !ctx.inFlow) {\n if (ws === '\\n' && valueComment)\n ws = '\\n\\n';\n }\n else {\n ws += `\\n${ctx.indent}`;\n }\n }\n else if (!explicitKey && identity.isCollection(value)) {\n const vs0 = valueStr[0];\n const nl0 = valueStr.indexOf('\\n');\n const hasNewline = nl0 !== -1;\n const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;\n if (hasNewline || !flow) {\n let hasPropsLine = false;\n if (hasNewline && (vs0 === '&' || vs0 === '!')) {\n let sp0 = valueStr.indexOf(' ');\n if (vs0 === '&' &&\n sp0 !== -1 &&\n sp0 < nl0 &&\n valueStr[sp0 + 1] === '!') {\n sp0 = valueStr.indexOf(' ', sp0 + 1);\n }\n if (sp0 === -1 || nl0 < sp0)\n hasPropsLine = true;\n }\n if (!hasPropsLine)\n ws = `\\n${ctx.indent}`;\n }\n }\n else if (valueStr === '' || valueStr[0] === '\\n') {\n ws = '';\n }\n str += ws + valueStr;\n if (ctx.inFlow) {\n if (valueCommentDone && onComment)\n onComment();\n }\n else if (valueComment && !valueCommentDone) {\n str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment));\n }\n else if (chompKeep && onChompKeep) {\n onChompKeep();\n }\n return str;\n}\n\nexports.stringifyPair = stringifyPair;\n",
21
+ "'use strict';\n\nvar node_process = require('process');\n\nfunction debug(logLevel, ...messages) {\n if (logLevel === 'debug')\n console.log(...messages);\n}\nfunction warn(logLevel, warning) {\n if (logLevel === 'debug' || logLevel === 'warn') {\n if (typeof node_process.emitWarning === 'function')\n node_process.emitWarning(warning);\n else\n console.warn(warning);\n }\n}\n\nexports.debug = debug;\nexports.warn = warn;\n",
22
+ "'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar Scalar = require('../../nodes/Scalar.js');\n\n// If the value associated with a merge key is a single mapping node, each of\n// its key/value pairs is inserted into the current mapping, unless the key\n// already exists in it. If the value associated with the merge key is a\n// sequence, then this sequence is expected to contain mapping nodes and each\n// of these nodes is merged in turn according to its order in the sequence.\n// Keys in mapping nodes earlier in the sequence override keys specified in\n// later mapping nodes. -- http://yaml.org/type/merge.html\nconst MERGE_KEY = '<<';\nconst merge = {\n identify: value => value === MERGE_KEY ||\n (typeof value === 'symbol' && value.description === MERGE_KEY),\n default: 'key',\n tag: 'tag:yaml.org,2002:merge',\n test: /^<<$/,\n resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), {\n addToJSMap: addMergeToJSMap\n }),\n stringify: () => MERGE_KEY\n};\nconst isMergeKey = (ctx, key) => (merge.identify(key) ||\n (identity.isScalar(key) &&\n (!key.type || key.type === Scalar.Scalar.PLAIN) &&\n merge.identify(key.value))) &&\n ctx?.doc.schema.tags.some(tag => tag.tag === merge.tag && tag.default);\nfunction addMergeToJSMap(ctx, map, value) {\n value = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value;\n if (identity.isSeq(value))\n for (const it of value.items)\n mergeValue(ctx, map, it);\n else if (Array.isArray(value))\n for (const it of value)\n mergeValue(ctx, map, it);\n else\n mergeValue(ctx, map, value);\n}\nfunction mergeValue(ctx, map, value) {\n const source = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value;\n if (!identity.isMap(source))\n throw new Error('Merge sources must be maps or map aliases');\n const srcMap = source.toJSON(null, ctx, Map);\n for (const [key, value] of srcMap) {\n if (map instanceof Map) {\n if (!map.has(key))\n map.set(key, value);\n }\n else if (map instanceof Set) {\n map.add(key);\n }\n else if (!Object.prototype.hasOwnProperty.call(map, key)) {\n Object.defineProperty(map, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n }\n }\n return map;\n}\n\nexports.addMergeToJSMap = addMergeToJSMap;\nexports.isMergeKey = isMergeKey;\nexports.merge = merge;\n",
23
+ "'use strict';\n\nvar log = require('../log.js');\nvar merge = require('../schema/yaml-1.1/merge.js');\nvar stringify = require('../stringify/stringify.js');\nvar identity = require('./identity.js');\nvar toJS = require('./toJS.js');\n\nfunction addPairToJSMap(ctx, map, { key, value }) {\n if (identity.isNode(key) && key.addToJSMap)\n key.addToJSMap(ctx, map, value);\n // TODO: Should drop this special case for bare << handling\n else if (merge.isMergeKey(ctx, key))\n merge.addMergeToJSMap(ctx, map, value);\n else {\n const jsKey = toJS.toJS(key, '', ctx);\n if (map instanceof Map) {\n map.set(jsKey, toJS.toJS(value, jsKey, ctx));\n }\n else if (map instanceof Set) {\n map.add(jsKey);\n }\n else {\n const stringKey = stringifyKey(key, jsKey, ctx);\n const jsValue = toJS.toJS(value, stringKey, ctx);\n if (stringKey in map)\n Object.defineProperty(map, stringKey, {\n value: jsValue,\n writable: true,\n enumerable: true,\n configurable: true\n });\n else\n map[stringKey] = jsValue;\n }\n }\n return map;\n}\nfunction stringifyKey(key, jsKey, ctx) {\n if (jsKey === null)\n return '';\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n if (typeof jsKey !== 'object')\n return String(jsKey);\n if (identity.isNode(key) && ctx?.doc) {\n const strCtx = stringify.createStringifyContext(ctx.doc, {});\n strCtx.anchors = new Set();\n for (const node of ctx.anchors.keys())\n strCtx.anchors.add(node.anchor);\n strCtx.inFlow = true;\n strCtx.inStringifyKey = true;\n const strKey = key.toString(strCtx);\n if (!ctx.mapKeyWarned) {\n let jsonStr = JSON.stringify(strKey);\n if (jsonStr.length > 40)\n jsonStr = jsonStr.substring(0, 36) + '...\"';\n log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);\n ctx.mapKeyWarned = true;\n }\n return strKey;\n }\n return JSON.stringify(jsKey);\n}\n\nexports.addPairToJSMap = addPairToJSMap;\n",
24
+ "'use strict';\n\nvar createNode = require('../doc/createNode.js');\nvar stringifyPair = require('../stringify/stringifyPair.js');\nvar addPairToJSMap = require('./addPairToJSMap.js');\nvar identity = require('./identity.js');\n\nfunction createPair(key, value, ctx) {\n const k = createNode.createNode(key, undefined, ctx);\n const v = createNode.createNode(value, undefined, ctx);\n return new Pair(k, v);\n}\nclass Pair {\n constructor(key, value = null) {\n Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR });\n this.key = key;\n this.value = value;\n }\n clone(schema) {\n let { key, value } = this;\n if (identity.isNode(key))\n key = key.clone(schema);\n if (identity.isNode(value))\n value = value.clone(schema);\n return new Pair(key, value);\n }\n toJSON(_, ctx) {\n const pair = ctx?.mapAsMap ? new Map() : {};\n return addPairToJSMap.addPairToJSMap(ctx, pair, this);\n }\n toString(ctx, onComment, onChompKeep) {\n return ctx?.doc\n ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep)\n : JSON.stringify(this);\n }\n}\n\nexports.Pair = Pair;\nexports.createPair = createPair;\n",
25
+ "'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar stringify = require('./stringify.js');\nvar stringifyComment = require('./stringifyComment.js');\n\nfunction stringifyCollection(collection, ctx, options) {\n const flow = ctx.inFlow ?? collection.flow;\n const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;\n return stringify(collection, ctx, options);\n}\nfunction stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {\n const { indent, options: { commentString } } = ctx;\n const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });\n let chompKeep = false; // flag for the preceding node's status\n const lines = [];\n for (let i = 0; i < items.length; ++i) {\n const item = items[i];\n let comment = null;\n if (identity.isNode(item)) {\n if (!chompKeep && item.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, item.commentBefore, chompKeep);\n if (item.comment)\n comment = item.comment;\n }\n else if (identity.isPair(item)) {\n const ik = identity.isNode(item.key) ? item.key : null;\n if (ik) {\n if (!chompKeep && ik.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);\n }\n }\n chompKeep = false;\n let str = stringify.stringify(item, itemCtx, () => (comment = null), () => (chompKeep = true));\n if (comment)\n str += stringifyComment.lineComment(str, itemIndent, commentString(comment));\n if (chompKeep && comment)\n chompKeep = false;\n lines.push(blockItemPrefix + str);\n }\n let str;\n if (lines.length === 0) {\n str = flowChars.start + flowChars.end;\n }\n else {\n str = lines[0];\n for (let i = 1; i < lines.length; ++i) {\n const line = lines[i];\n str += line ? `\\n${indent}${line}` : '\\n';\n }\n }\n if (comment) {\n str += '\\n' + stringifyComment.indentComment(commentString(comment), indent);\n if (onComment)\n onComment();\n }\n else if (chompKeep && onChompKeep)\n onChompKeep();\n return str;\n}\nfunction stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {\n const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;\n itemIndent += indentStep;\n const itemCtx = Object.assign({}, ctx, {\n indent: itemIndent,\n inFlow: true,\n type: null\n });\n let reqNewline = false;\n let linesAtValue = 0;\n const lines = [];\n for (let i = 0; i < items.length; ++i) {\n const item = items[i];\n let comment = null;\n if (identity.isNode(item)) {\n if (item.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, item.commentBefore, false);\n if (item.comment)\n comment = item.comment;\n }\n else if (identity.isPair(item)) {\n const ik = identity.isNode(item.key) ? item.key : null;\n if (ik) {\n if (ik.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, ik.commentBefore, false);\n if (ik.comment)\n reqNewline = true;\n }\n const iv = identity.isNode(item.value) ? item.value : null;\n if (iv) {\n if (iv.comment)\n comment = iv.comment;\n if (iv.commentBefore)\n reqNewline = true;\n }\n else if (item.value == null && ik?.comment) {\n comment = ik.comment;\n }\n }\n if (comment)\n reqNewline = true;\n let str = stringify.stringify(item, itemCtx, () => (comment = null));\n if (i < items.length - 1)\n str += ',';\n if (comment)\n str += stringifyComment.lineComment(str, itemIndent, commentString(comment));\n if (!reqNewline && (lines.length > linesAtValue || str.includes('\\n')))\n reqNewline = true;\n lines.push(str);\n linesAtValue = lines.length;\n }\n const { start, end } = flowChars;\n if (lines.length === 0) {\n return start + end;\n }\n else {\n if (!reqNewline) {\n const len = lines.reduce((sum, line) => sum + line.length + 2, 2);\n reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;\n }\n if (reqNewline) {\n let str = start;\n for (const line of lines)\n str += line ? `\\n${indentStep}${indent}${line}` : '\\n';\n return `${str}\\n${indent}${end}`;\n }\n else {\n return `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`;\n }\n }\n}\nfunction addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {\n if (comment && chompKeep)\n comment = comment.replace(/^\\n+/, '');\n if (comment) {\n const ic = stringifyComment.indentComment(commentString(comment), indent);\n lines.push(ic.trimStart()); // Avoid double indent on first line\n }\n}\n\nexports.stringifyCollection = stringifyCollection;\n",
26
+ "'use strict';\n\nvar stringifyCollection = require('../stringify/stringifyCollection.js');\nvar addPairToJSMap = require('./addPairToJSMap.js');\nvar Collection = require('./Collection.js');\nvar identity = require('./identity.js');\nvar Pair = require('./Pair.js');\nvar Scalar = require('./Scalar.js');\n\nfunction findPair(items, key) {\n const k = identity.isScalar(key) ? key.value : key;\n for (const it of items) {\n if (identity.isPair(it)) {\n if (it.key === key || it.key === k)\n return it;\n if (identity.isScalar(it.key) && it.key.value === k)\n return it;\n }\n }\n return undefined;\n}\nclass YAMLMap extends Collection.Collection {\n static get tagName() {\n return 'tag:yaml.org,2002:map';\n }\n constructor(schema) {\n super(identity.MAP, schema);\n this.items = [];\n }\n /**\n * A generic collection parsing method that can be extended\n * to other node classes that inherit from YAMLMap\n */\n static from(schema, obj, ctx) {\n const { keepUndefined, replacer } = ctx;\n const map = new this(schema);\n const add = (key, value) => {\n if (typeof replacer === 'function')\n value = replacer.call(obj, key, value);\n else if (Array.isArray(replacer) && !replacer.includes(key))\n return;\n if (value !== undefined || keepUndefined)\n map.items.push(Pair.createPair(key, value, ctx));\n };\n if (obj instanceof Map) {\n for (const [key, value] of obj)\n add(key, value);\n }\n else if (obj && typeof obj === 'object') {\n for (const key of Object.keys(obj))\n add(key, obj[key]);\n }\n if (typeof schema.sortMapEntries === 'function') {\n map.items.sort(schema.sortMapEntries);\n }\n return map;\n }\n /**\n * Adds a value to the collection.\n *\n * @param overwrite - If not set `true`, using a key that is already in the\n * collection will throw. Otherwise, overwrites the previous value.\n */\n add(pair, overwrite) {\n let _pair;\n if (identity.isPair(pair))\n _pair = pair;\n else if (!pair || typeof pair !== 'object' || !('key' in pair)) {\n // In TypeScript, this never happens.\n _pair = new Pair.Pair(pair, pair?.value);\n }\n else\n _pair = new Pair.Pair(pair.key, pair.value);\n const prev = findPair(this.items, _pair.key);\n const sortEntries = this.schema?.sortMapEntries;\n if (prev) {\n if (!overwrite)\n throw new Error(`Key ${_pair.key} already set`);\n // For scalars, keep the old node & its comments and anchors\n if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))\n prev.value.value = _pair.value;\n else\n prev.value = _pair.value;\n }\n else if (sortEntries) {\n const i = this.items.findIndex(item => sortEntries(_pair, item) < 0);\n if (i === -1)\n this.items.push(_pair);\n else\n this.items.splice(i, 0, _pair);\n }\n else {\n this.items.push(_pair);\n }\n }\n delete(key) {\n const it = findPair(this.items, key);\n if (!it)\n return false;\n const del = this.items.splice(this.items.indexOf(it), 1);\n return del.length > 0;\n }\n get(key, keepScalar) {\n const it = findPair(this.items, key);\n const node = it?.value;\n return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? undefined;\n }\n has(key) {\n return !!findPair(this.items, key);\n }\n set(key, value) {\n this.add(new Pair.Pair(key, value), true);\n }\n /**\n * @param ctx - Conversion context, originally set in Document#toJS()\n * @param {Class} Type - If set, forces the returned collection type\n * @returns Instance of Type, Map, or Object\n */\n toJSON(_, ctx, Type) {\n const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {};\n if (ctx?.onCreate)\n ctx.onCreate(map);\n for (const item of this.items)\n addPairToJSMap.addPairToJSMap(ctx, map, item);\n return map;\n }\n toString(ctx, onComment, onChompKeep) {\n if (!ctx)\n return JSON.stringify(this);\n for (const item of this.items) {\n if (!identity.isPair(item))\n throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);\n }\n if (!ctx.allNullValues && this.hasAllNullValues(false))\n ctx = Object.assign({}, ctx, { allNullValues: true });\n return stringifyCollection.stringifyCollection(this, ctx, {\n blockItemPrefix: '',\n flowChars: { start: '{', end: '}' },\n itemIndent: ctx.indent || '',\n onChompKeep,\n onComment\n });\n }\n}\n\nexports.YAMLMap = YAMLMap;\nexports.findPair = findPair;\n",
27
+ "'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar YAMLMap = require('../../nodes/YAMLMap.js');\n\nconst map = {\n collection: 'map',\n default: true,\n nodeClass: YAMLMap.YAMLMap,\n tag: 'tag:yaml.org,2002:map',\n resolve(map, onError) {\n if (!identity.isMap(map))\n onError('Expected a mapping for this tag');\n return map;\n },\n createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)\n};\n\nexports.map = map;\n",
28
+ "'use strict';\n\nvar createNode = require('../doc/createNode.js');\nvar stringifyCollection = require('../stringify/stringifyCollection.js');\nvar Collection = require('./Collection.js');\nvar identity = require('./identity.js');\nvar Scalar = require('./Scalar.js');\nvar toJS = require('./toJS.js');\n\nclass YAMLSeq extends Collection.Collection {\n static get tagName() {\n return 'tag:yaml.org,2002:seq';\n }\n constructor(schema) {\n super(identity.SEQ, schema);\n this.items = [];\n }\n add(value) {\n this.items.push(value);\n }\n /**\n * Removes a value from the collection.\n *\n * `key` must contain a representation of an integer for this to succeed.\n * It may be wrapped in a `Scalar`.\n *\n * @returns `true` if the item was found and removed.\n */\n delete(key) {\n const idx = asItemIndex(key);\n if (typeof idx !== 'number')\n return false;\n const del = this.items.splice(idx, 1);\n return del.length > 0;\n }\n get(key, keepScalar) {\n const idx = asItemIndex(key);\n if (typeof idx !== 'number')\n return undefined;\n const it = this.items[idx];\n return !keepScalar && identity.isScalar(it) ? it.value : it;\n }\n /**\n * Checks if the collection includes a value with the key `key`.\n *\n * `key` must contain a representation of an integer for this to succeed.\n * It may be wrapped in a `Scalar`.\n */\n has(key) {\n const idx = asItemIndex(key);\n return typeof idx === 'number' && idx < this.items.length;\n }\n /**\n * Sets a value in this collection. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n *\n * If `key` does not contain a representation of an integer, this will throw.\n * It may be wrapped in a `Scalar`.\n */\n set(key, value) {\n const idx = asItemIndex(key);\n if (typeof idx !== 'number')\n throw new Error(`Expected a valid index, not ${key}.`);\n const prev = this.items[idx];\n if (identity.isScalar(prev) && Scalar.isScalarValue(value))\n prev.value = value;\n else\n this.items[idx] = value;\n }\n toJSON(_, ctx) {\n const seq = [];\n if (ctx?.onCreate)\n ctx.onCreate(seq);\n let i = 0;\n for (const item of this.items)\n seq.push(toJS.toJS(item, String(i++), ctx));\n return seq;\n }\n toString(ctx, onComment, onChompKeep) {\n if (!ctx)\n return JSON.stringify(this);\n return stringifyCollection.stringifyCollection(this, ctx, {\n blockItemPrefix: '- ',\n flowChars: { start: '[', end: ']' },\n itemIndent: (ctx.indent || '') + ' ',\n onChompKeep,\n onComment\n });\n }\n static from(schema, obj, ctx) {\n const { replacer } = ctx;\n const seq = new this(schema);\n if (obj && Symbol.iterator in Object(obj)) {\n let i = 0;\n for (let it of obj) {\n if (typeof replacer === 'function') {\n const key = obj instanceof Set ? it : String(i++);\n it = replacer.call(obj, key, it);\n }\n seq.items.push(createNode.createNode(it, undefined, ctx));\n }\n }\n return seq;\n }\n}\nfunction asItemIndex(key) {\n let idx = identity.isScalar(key) ? key.value : key;\n if (idx && typeof idx === 'string')\n idx = Number(idx);\n return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0\n ? idx\n : null;\n}\n\nexports.YAMLSeq = YAMLSeq;\n",
29
+ "'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar YAMLSeq = require('../../nodes/YAMLSeq.js');\n\nconst seq = {\n collection: 'seq',\n default: true,\n nodeClass: YAMLSeq.YAMLSeq,\n tag: 'tag:yaml.org,2002:seq',\n resolve(seq, onError) {\n if (!identity.isSeq(seq))\n onError('Expected a sequence for this tag');\n return seq;\n },\n createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)\n};\n\nexports.seq = seq;\n",
30
+ "'use strict';\n\nvar stringifyString = require('../../stringify/stringifyString.js');\n\nconst string = {\n identify: value => typeof value === 'string',\n default: true,\n tag: 'tag:yaml.org,2002:str',\n resolve: str => str,\n stringify(item, ctx, onComment, onChompKeep) {\n ctx = Object.assign({ actualString: true }, ctx);\n return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);\n }\n};\n\nexports.string = string;\n",
31
+ "'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\n\nconst nullTag = {\n identify: value => value == null,\n createNode: () => new Scalar.Scalar(null),\n default: true,\n tag: 'tag:yaml.org,2002:null',\n test: /^(?:~|[Nn]ull|NULL)?$/,\n resolve: () => new Scalar.Scalar(null),\n stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)\n ? source\n : ctx.options.nullStr\n};\n\nexports.nullTag = nullTag;\n",
32
+ "'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\n\nconst boolTag = {\n identify: value => typeof value === 'boolean',\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,\n resolve: str => new Scalar.Scalar(str[0] === 't' || str[0] === 'T'),\n stringify({ source, value }, ctx) {\n if (source && boolTag.test.test(source)) {\n const sv = source[0] === 't' || source[0] === 'T';\n if (value === sv)\n return source;\n }\n return value ? ctx.options.trueStr : ctx.options.falseStr;\n }\n};\n\nexports.boolTag = boolTag;\n",
33
+ "'use strict';\n\nfunction stringifyNumber({ format, minFractionDigits, tag, value }) {\n if (typeof value === 'bigint')\n return String(value);\n const num = typeof value === 'number' ? value : Number(value);\n if (!isFinite(num))\n return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';\n let n = Object.is(value, -0) ? '-0' : JSON.stringify(value);\n if (!format &&\n minFractionDigits &&\n (!tag || tag === 'tag:yaml.org,2002:float') &&\n /^\\d/.test(n)) {\n let i = n.indexOf('.');\n if (i < 0) {\n i = n.length;\n n += '.';\n }\n let d = minFractionDigits - (n.length - i - 1);\n while (d-- > 0)\n n += '0';\n }\n return n;\n}\n\nexports.stringifyNumber = stringifyNumber;\n",
34
+ "'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst floatNaN = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n resolve: str => str.slice(-3).toLowerCase() === 'nan'\n ? NaN\n : str[0] === '-'\n ? Number.NEGATIVE_INFINITY\n : Number.POSITIVE_INFINITY,\n stringify: stringifyNumber.stringifyNumber\n};\nconst floatExp = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n format: 'EXP',\n test: /^[-+]?(?:\\.[0-9]+|[0-9]+(?:\\.[0-9]*)?)[eE][-+]?[0-9]+$/,\n resolve: str => parseFloat(str),\n stringify(node) {\n const num = Number(node.value);\n return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);\n }\n};\nconst float = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^[-+]?(?:\\.[0-9]+|[0-9]+\\.[0-9]*)$/,\n resolve(str) {\n const node = new Scalar.Scalar(parseFloat(str));\n const dot = str.indexOf('.');\n if (dot !== -1 && str[str.length - 1] === '0')\n node.minFractionDigits = str.length - dot - 1;\n return node;\n },\n stringify: stringifyNumber.stringifyNumber\n};\n\nexports.float = float;\nexports.floatExp = floatExp;\nexports.floatNaN = floatNaN;\n",
35
+ "'use strict';\n\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nconst intResolve = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));\nfunction intStringify(node, radix, prefix) {\n const { value } = node;\n if (intIdentify(value) && value >= 0)\n return prefix + value.toString(radix);\n return stringifyNumber.stringifyNumber(node);\n}\nconst intOct = {\n identify: value => intIdentify(value) && value >= 0,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'OCT',\n test: /^0o[0-7]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),\n stringify: node => intStringify(node, 8, '0o')\n};\nconst int = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n test: /^[-+]?[0-9]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n stringify: stringifyNumber.stringifyNumber\n};\nconst intHex = {\n identify: value => intIdentify(value) && value >= 0,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'HEX',\n test: /^0x[0-9a-fA-F]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n stringify: node => intStringify(node, 16, '0x')\n};\n\nexports.int = int;\nexports.intHex = intHex;\nexports.intOct = intOct;\n",
36
+ "'use strict';\n\nvar map = require('../common/map.js');\nvar _null = require('../common/null.js');\nvar seq = require('../common/seq.js');\nvar string = require('../common/string.js');\nvar bool = require('./bool.js');\nvar float = require('./float.js');\nvar int = require('./int.js');\n\nconst schema = [\n map.map,\n seq.seq,\n string.string,\n _null.nullTag,\n bool.boolTag,\n int.intOct,\n int.int,\n int.intHex,\n float.floatNaN,\n float.floatExp,\n float.float\n];\n\nexports.schema = schema;\n",
37
+ "'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\nvar map = require('../common/map.js');\nvar seq = require('../common/seq.js');\n\nfunction intIdentify(value) {\n return typeof value === 'bigint' || Number.isInteger(value);\n}\nconst stringifyJSON = ({ value }) => JSON.stringify(value);\nconst jsonScalars = [\n {\n identify: value => typeof value === 'string',\n default: true,\n tag: 'tag:yaml.org,2002:str',\n resolve: str => str,\n stringify: stringifyJSON\n },\n {\n identify: value => value == null,\n createNode: () => new Scalar.Scalar(null),\n default: true,\n tag: 'tag:yaml.org,2002:null',\n test: /^null$/,\n resolve: () => null,\n stringify: stringifyJSON\n },\n {\n identify: value => typeof value === 'boolean',\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^true$|^false$/,\n resolve: str => str === 'true',\n stringify: stringifyJSON\n },\n {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n test: /^-?(?:0|[1-9][0-9]*)$/,\n resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),\n stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)\n },\n {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,\n resolve: str => parseFloat(str),\n stringify: stringifyJSON\n }\n];\nconst jsonError = {\n default: true,\n tag: '',\n test: /^/,\n resolve(str, onError) {\n onError(`Unresolved plain scalar ${JSON.stringify(str)}`);\n return str;\n }\n};\nconst schema = [map.map, seq.seq].concat(jsonScalars, jsonError);\n\nexports.schema = schema;\n",
38
+ "'use strict';\n\nvar node_buffer = require('buffer');\nvar Scalar = require('../../nodes/Scalar.js');\nvar stringifyString = require('../../stringify/stringifyString.js');\n\nconst binary = {\n identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array\n default: false,\n tag: 'tag:yaml.org,2002:binary',\n /**\n * Returns a Buffer in node and an Uint8Array in browsers\n *\n * To use the resulting buffer as an image, you'll want to do something like:\n *\n * const blob = new Blob([buffer], { type: 'image/jpeg' })\n * document.querySelector('#photo').src = URL.createObjectURL(blob)\n */\n resolve(src, onError) {\n if (typeof node_buffer.Buffer === 'function') {\n return node_buffer.Buffer.from(src, 'base64');\n }\n else if (typeof atob === 'function') {\n // On IE 11, atob() can't handle newlines\n const str = atob(src.replace(/[\\n\\r]/g, ''));\n const buffer = new Uint8Array(str.length);\n for (let i = 0; i < str.length; ++i)\n buffer[i] = str.charCodeAt(i);\n return buffer;\n }\n else {\n onError('This environment does not support reading binary tags; either Buffer or atob is required');\n return src;\n }\n },\n stringify({ comment, type, value }, ctx, onComment, onChompKeep) {\n if (!value)\n return '';\n const buf = value; // checked earlier by binary.identify()\n let str;\n if (typeof node_buffer.Buffer === 'function') {\n str =\n buf instanceof node_buffer.Buffer\n ? buf.toString('base64')\n : node_buffer.Buffer.from(buf.buffer).toString('base64');\n }\n else if (typeof btoa === 'function') {\n let s = '';\n for (let i = 0; i < buf.length; ++i)\n s += String.fromCharCode(buf[i]);\n str = btoa(s);\n }\n else {\n throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');\n }\n type ?? (type = Scalar.Scalar.BLOCK_LITERAL);\n if (type !== Scalar.Scalar.QUOTE_DOUBLE) {\n const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);\n const n = Math.ceil(str.length / lineWidth);\n const lines = new Array(n);\n for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {\n lines[i] = str.substr(o, lineWidth);\n }\n str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? '\\n' : ' ');\n }\n return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);\n }\n};\n\nexports.binary = binary;\n",
39
+ "'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar Pair = require('../../nodes/Pair.js');\nvar Scalar = require('../../nodes/Scalar.js');\nvar YAMLSeq = require('../../nodes/YAMLSeq.js');\n\nfunction resolvePairs(seq, onError) {\n if (identity.isSeq(seq)) {\n for (let i = 0; i < seq.items.length; ++i) {\n let item = seq.items[i];\n if (identity.isPair(item))\n continue;\n else if (identity.isMap(item)) {\n if (item.items.length > 1)\n onError('Each pair must have its own sequence indicator');\n const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));\n if (item.commentBefore)\n pair.key.commentBefore = pair.key.commentBefore\n ? `${item.commentBefore}\\n${pair.key.commentBefore}`\n : item.commentBefore;\n if (item.comment) {\n const cn = pair.value ?? pair.key;\n cn.comment = cn.comment\n ? `${item.comment}\\n${cn.comment}`\n : item.comment;\n }\n item = pair;\n }\n seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item);\n }\n }\n else\n onError('Expected a sequence for this tag');\n return seq;\n}\nfunction createPairs(schema, iterable, ctx) {\n const { replacer } = ctx;\n const pairs = new YAMLSeq.YAMLSeq(schema);\n pairs.tag = 'tag:yaml.org,2002:pairs';\n let i = 0;\n if (iterable && Symbol.iterator in Object(iterable))\n for (let it of iterable) {\n if (typeof replacer === 'function')\n it = replacer.call(iterable, String(i++), it);\n let key, value;\n if (Array.isArray(it)) {\n if (it.length === 2) {\n key = it[0];\n value = it[1];\n }\n else\n throw new TypeError(`Expected [key, value] tuple: ${it}`);\n }\n else if (it && it instanceof Object) {\n const keys = Object.keys(it);\n if (keys.length === 1) {\n key = keys[0];\n value = it[key];\n }\n else {\n throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);\n }\n }\n else {\n key = it;\n }\n pairs.items.push(Pair.createPair(key, value, ctx));\n }\n return pairs;\n}\nconst pairs = {\n collection: 'seq',\n default: false,\n tag: 'tag:yaml.org,2002:pairs',\n resolve: resolvePairs,\n createNode: createPairs\n};\n\nexports.createPairs = createPairs;\nexports.pairs = pairs;\nexports.resolvePairs = resolvePairs;\n",
40
+ "'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar toJS = require('../../nodes/toJS.js');\nvar YAMLMap = require('../../nodes/YAMLMap.js');\nvar YAMLSeq = require('../../nodes/YAMLSeq.js');\nvar pairs = require('./pairs.js');\n\nclass YAMLOMap extends YAMLSeq.YAMLSeq {\n constructor() {\n super();\n this.add = YAMLMap.YAMLMap.prototype.add.bind(this);\n this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);\n this.get = YAMLMap.YAMLMap.prototype.get.bind(this);\n this.has = YAMLMap.YAMLMap.prototype.has.bind(this);\n this.set = YAMLMap.YAMLMap.prototype.set.bind(this);\n this.tag = YAMLOMap.tag;\n }\n /**\n * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,\n * but TypeScript won't allow widening the signature of a child method.\n */\n toJSON(_, ctx) {\n if (!ctx)\n return super.toJSON(_);\n const map = new Map();\n if (ctx?.onCreate)\n ctx.onCreate(map);\n for (const pair of this.items) {\n let key, value;\n if (identity.isPair(pair)) {\n key = toJS.toJS(pair.key, '', ctx);\n value = toJS.toJS(pair.value, key, ctx);\n }\n else {\n key = toJS.toJS(pair, '', ctx);\n }\n if (map.has(key))\n throw new Error('Ordered maps must not include duplicate keys');\n map.set(key, value);\n }\n return map;\n }\n static from(schema, iterable, ctx) {\n const pairs$1 = pairs.createPairs(schema, iterable, ctx);\n const omap = new this();\n omap.items = pairs$1.items;\n return omap;\n }\n}\nYAMLOMap.tag = 'tag:yaml.org,2002:omap';\nconst omap = {\n collection: 'seq',\n identify: value => value instanceof Map,\n nodeClass: YAMLOMap,\n default: false,\n tag: 'tag:yaml.org,2002:omap',\n resolve(seq, onError) {\n const pairs$1 = pairs.resolvePairs(seq, onError);\n const seenKeys = [];\n for (const { key } of pairs$1.items) {\n if (identity.isScalar(key)) {\n if (seenKeys.includes(key.value)) {\n onError(`Ordered maps must not include duplicate keys: ${key.value}`);\n }\n else {\n seenKeys.push(key.value);\n }\n }\n }\n return Object.assign(new YAMLOMap(), pairs$1);\n },\n createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)\n};\n\nexports.YAMLOMap = YAMLOMap;\nexports.omap = omap;\n",
41
+ "'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\n\nfunction boolStringify({ value, source }, ctx) {\n const boolObj = value ? trueTag : falseTag;\n if (source && boolObj.test.test(source))\n return source;\n return value ? ctx.options.trueStr : ctx.options.falseStr;\n}\nconst trueTag = {\n identify: value => value === true,\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,\n resolve: () => new Scalar.Scalar(true),\n stringify: boolStringify\n};\nconst falseTag = {\n identify: value => value === false,\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,\n resolve: () => new Scalar.Scalar(false),\n stringify: boolStringify\n};\n\nexports.falseTag = falseTag;\nexports.trueTag = trueTag;\n",
42
+ "'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst floatNaN = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n resolve: (str) => str.slice(-3).toLowerCase() === 'nan'\n ? NaN\n : str[0] === '-'\n ? Number.NEGATIVE_INFINITY\n : Number.POSITIVE_INFINITY,\n stringify: stringifyNumber.stringifyNumber\n};\nconst floatExp = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n format: 'EXP',\n test: /^[-+]?(?:[0-9][0-9_]*)?(?:\\.[0-9_]*)?[eE][-+]?[0-9]+$/,\n resolve: (str) => parseFloat(str.replace(/_/g, '')),\n stringify(node) {\n const num = Number(node.value);\n return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);\n }\n};\nconst float = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^[-+]?(?:[0-9][0-9_]*)?\\.[0-9_]*$/,\n resolve(str) {\n const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, '')));\n const dot = str.indexOf('.');\n if (dot !== -1) {\n const f = str.substring(dot + 1).replace(/_/g, '');\n if (f[f.length - 1] === '0')\n node.minFractionDigits = f.length;\n }\n return node;\n },\n stringify: stringifyNumber.stringifyNumber\n};\n\nexports.float = float;\nexports.floatExp = floatExp;\nexports.floatNaN = floatNaN;\n",
43
+ "'use strict';\n\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nfunction intResolve(str, offset, radix, { intAsBigInt }) {\n const sign = str[0];\n if (sign === '-' || sign === '+')\n offset += 1;\n str = str.substring(offset).replace(/_/g, '');\n if (intAsBigInt) {\n switch (radix) {\n case 2:\n str = `0b${str}`;\n break;\n case 8:\n str = `0o${str}`;\n break;\n case 16:\n str = `0x${str}`;\n break;\n }\n const n = BigInt(str);\n return sign === '-' ? BigInt(-1) * n : n;\n }\n const n = parseInt(str, radix);\n return sign === '-' ? -1 * n : n;\n}\nfunction intStringify(node, radix, prefix) {\n const { value } = node;\n if (intIdentify(value)) {\n const str = value.toString(radix);\n return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;\n }\n return stringifyNumber.stringifyNumber(node);\n}\nconst intBin = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'BIN',\n test: /^[-+]?0b[0-1_]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),\n stringify: node => intStringify(node, 2, '0b')\n};\nconst intOct = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'OCT',\n test: /^[-+]?0[0-7_]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),\n stringify: node => intStringify(node, 8, '0')\n};\nconst int = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n test: /^[-+]?[0-9][0-9_]*$/,\n resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n stringify: stringifyNumber.stringifyNumber\n};\nconst intHex = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'HEX',\n test: /^[-+]?0x[0-9a-fA-F_]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n stringify: node => intStringify(node, 16, '0x')\n};\n\nexports.int = int;\nexports.intBin = intBin;\nexports.intHex = intHex;\nexports.intOct = intOct;\n",
44
+ "'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar Pair = require('../../nodes/Pair.js');\nvar YAMLMap = require('../../nodes/YAMLMap.js');\n\nclass YAMLSet extends YAMLMap.YAMLMap {\n constructor(schema) {\n super(schema);\n this.tag = YAMLSet.tag;\n }\n add(key) {\n let pair;\n if (identity.isPair(key))\n pair = key;\n else if (key &&\n typeof key === 'object' &&\n 'key' in key &&\n 'value' in key &&\n key.value === null)\n pair = new Pair.Pair(key.key, null);\n else\n pair = new Pair.Pair(key, null);\n const prev = YAMLMap.findPair(this.items, pair.key);\n if (!prev)\n this.items.push(pair);\n }\n /**\n * If `keepPair` is `true`, returns the Pair matching `key`.\n * Otherwise, returns the value of that Pair's key.\n */\n get(key, keepPair) {\n const pair = YAMLMap.findPair(this.items, key);\n return !keepPair && identity.isPair(pair)\n ? identity.isScalar(pair.key)\n ? pair.key.value\n : pair.key\n : pair;\n }\n set(key, value) {\n if (typeof value !== 'boolean')\n throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);\n const prev = YAMLMap.findPair(this.items, key);\n if (prev && !value) {\n this.items.splice(this.items.indexOf(prev), 1);\n }\n else if (!prev && value) {\n this.items.push(new Pair.Pair(key));\n }\n }\n toJSON(_, ctx) {\n return super.toJSON(_, ctx, Set);\n }\n toString(ctx, onComment, onChompKeep) {\n if (!ctx)\n return JSON.stringify(this);\n if (this.hasAllNullValues(true))\n return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);\n else\n throw new Error('Set items must all have null values');\n }\n static from(schema, iterable, ctx) {\n const { replacer } = ctx;\n const set = new this(schema);\n if (iterable && Symbol.iterator in Object(iterable))\n for (let value of iterable) {\n if (typeof replacer === 'function')\n value = replacer.call(iterable, value, value);\n set.items.push(Pair.createPair(value, null, ctx));\n }\n return set;\n }\n}\nYAMLSet.tag = 'tag:yaml.org,2002:set';\nconst set = {\n collection: 'map',\n identify: value => value instanceof Set,\n nodeClass: YAMLSet,\n default: false,\n tag: 'tag:yaml.org,2002:set',\n createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),\n resolve(map, onError) {\n if (identity.isMap(map)) {\n if (map.hasAllNullValues(true))\n return Object.assign(new YAMLSet(), map);\n else\n onError('Set items must all have null values');\n }\n else\n onError('Expected a mapping for this tag');\n return map;\n }\n};\n\nexports.YAMLSet = YAMLSet;\nexports.set = set;\n",
45
+ "'use strict';\n\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\n/** Internal types handle bigint as number, because TS can't figure it out. */\nfunction parseSexagesimal(str, asBigInt) {\n const sign = str[0];\n const parts = sign === '-' || sign === '+' ? str.substring(1) : str;\n const num = (n) => asBigInt ? BigInt(n) : Number(n);\n const res = parts\n .replace(/_/g, '')\n .split(':')\n .reduce((res, p) => res * num(60) + num(p), num(0));\n return (sign === '-' ? num(-1) * res : res);\n}\n/**\n * hhhh:mm:ss.sss\n *\n * Internal types handle bigint as number, because TS can't figure it out.\n */\nfunction stringifySexagesimal(node) {\n let { value } = node;\n let num = (n) => n;\n if (typeof value === 'bigint')\n num = n => BigInt(n);\n else if (isNaN(value) || !isFinite(value))\n return stringifyNumber.stringifyNumber(node);\n let sign = '';\n if (value < 0) {\n sign = '-';\n value *= num(-1);\n }\n const _60 = num(60);\n const parts = [value % _60]; // seconds, including ms\n if (value < 60) {\n parts.unshift(0); // at least one : is required\n }\n else {\n value = (value - parts[0]) / _60;\n parts.unshift(value % _60); // minutes\n if (value >= 60) {\n value = (value - parts[0]) / _60;\n parts.unshift(value); // hours\n }\n }\n return (sign +\n parts\n .map(n => String(n).padStart(2, '0'))\n .join(':')\n .replace(/000000\\d*$/, '') // % 60 may introduce error\n );\n}\nconst intTime = {\n identify: value => typeof value === 'bigint' || Number.isInteger(value),\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'TIME',\n test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,\n resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),\n stringify: stringifySexagesimal\n};\nconst floatTime = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n format: 'TIME',\n test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*$/,\n resolve: str => parseSexagesimal(str, false),\n stringify: stringifySexagesimal\n};\nconst timestamp = {\n identify: value => value instanceof Date,\n default: true,\n tag: 'tag:yaml.org,2002:timestamp',\n // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part\n // may be omitted altogether, resulting in a date format. In such a case, the time part is\n // assumed to be 00:00:00Z (start of day, UTC).\n test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd\n '(?:' + // time is optional\n '(?:t|T|[ \\\\t]+)' + // t | T | whitespace\n '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?\n '(?:[ \\\\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30\n ')?$'),\n resolve(str) {\n const match = str.match(timestamp.test);\n if (!match)\n throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd');\n const [, year, month, day, hour, minute, second] = match.map(Number);\n const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0;\n let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);\n const tz = match[8];\n if (tz && tz !== 'Z') {\n let d = parseSexagesimal(tz, false);\n if (Math.abs(d) < 30)\n d *= 60;\n date -= 60000 * d;\n }\n return new Date(date);\n },\n stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\\.000Z$/, '') ?? ''\n};\n\nexports.floatTime = floatTime;\nexports.intTime = intTime;\nexports.timestamp = timestamp;\n",
46
+ "'use strict';\n\nvar map = require('../common/map.js');\nvar _null = require('../common/null.js');\nvar seq = require('../common/seq.js');\nvar string = require('../common/string.js');\nvar binary = require('./binary.js');\nvar bool = require('./bool.js');\nvar float = require('./float.js');\nvar int = require('./int.js');\nvar merge = require('./merge.js');\nvar omap = require('./omap.js');\nvar pairs = require('./pairs.js');\nvar set = require('./set.js');\nvar timestamp = require('./timestamp.js');\n\nconst schema = [\n map.map,\n seq.seq,\n string.string,\n _null.nullTag,\n bool.trueTag,\n bool.falseTag,\n int.intBin,\n int.intOct,\n int.int,\n int.intHex,\n float.floatNaN,\n float.floatExp,\n float.float,\n binary.binary,\n merge.merge,\n omap.omap,\n pairs.pairs,\n set.set,\n timestamp.intTime,\n timestamp.floatTime,\n timestamp.timestamp\n];\n\nexports.schema = schema;\n",
47
+ "'use strict';\n\nvar map = require('./common/map.js');\nvar _null = require('./common/null.js');\nvar seq = require('./common/seq.js');\nvar string = require('./common/string.js');\nvar bool = require('./core/bool.js');\nvar float = require('./core/float.js');\nvar int = require('./core/int.js');\nvar schema = require('./core/schema.js');\nvar schema$1 = require('./json/schema.js');\nvar binary = require('./yaml-1.1/binary.js');\nvar merge = require('./yaml-1.1/merge.js');\nvar omap = require('./yaml-1.1/omap.js');\nvar pairs = require('./yaml-1.1/pairs.js');\nvar schema$2 = require('./yaml-1.1/schema.js');\nvar set = require('./yaml-1.1/set.js');\nvar timestamp = require('./yaml-1.1/timestamp.js');\n\nconst schemas = new Map([\n ['core', schema.schema],\n ['failsafe', [map.map, seq.seq, string.string]],\n ['json', schema$1.schema],\n ['yaml11', schema$2.schema],\n ['yaml-1.1', schema$2.schema]\n]);\nconst tagsByName = {\n binary: binary.binary,\n bool: bool.boolTag,\n float: float.float,\n floatExp: float.floatExp,\n floatNaN: float.floatNaN,\n floatTime: timestamp.floatTime,\n int: int.int,\n intHex: int.intHex,\n intOct: int.intOct,\n intTime: timestamp.intTime,\n map: map.map,\n merge: merge.merge,\n null: _null.nullTag,\n omap: omap.omap,\n pairs: pairs.pairs,\n seq: seq.seq,\n set: set.set,\n timestamp: timestamp.timestamp\n};\nconst coreKnownTags = {\n 'tag:yaml.org,2002:binary': binary.binary,\n 'tag:yaml.org,2002:merge': merge.merge,\n 'tag:yaml.org,2002:omap': omap.omap,\n 'tag:yaml.org,2002:pairs': pairs.pairs,\n 'tag:yaml.org,2002:set': set.set,\n 'tag:yaml.org,2002:timestamp': timestamp.timestamp\n};\nfunction getTags(customTags, schemaName, addMergeTag) {\n const schemaTags = schemas.get(schemaName);\n if (schemaTags && !customTags) {\n return addMergeTag && !schemaTags.includes(merge.merge)\n ? schemaTags.concat(merge.merge)\n : schemaTags.slice();\n }\n let tags = schemaTags;\n if (!tags) {\n if (Array.isArray(customTags))\n tags = [];\n else {\n const keys = Array.from(schemas.keys())\n .filter(key => key !== 'yaml11')\n .map(key => JSON.stringify(key))\n .join(', ');\n throw new Error(`Unknown schema \"${schemaName}\"; use one of ${keys} or define customTags array`);\n }\n }\n if (Array.isArray(customTags)) {\n for (const tag of customTags)\n tags = tags.concat(tag);\n }\n else if (typeof customTags === 'function') {\n tags = customTags(tags.slice());\n }\n if (addMergeTag)\n tags = tags.concat(merge.merge);\n return tags.reduce((tags, tag) => {\n const tagObj = typeof tag === 'string' ? tagsByName[tag] : tag;\n if (!tagObj) {\n const tagName = JSON.stringify(tag);\n const keys = Object.keys(tagsByName)\n .map(key => JSON.stringify(key))\n .join(', ');\n throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);\n }\n if (!tags.includes(tagObj))\n tags.push(tagObj);\n return tags;\n }, []);\n}\n\nexports.coreKnownTags = coreKnownTags;\nexports.getTags = getTags;\n",
48
+ "'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar map = require('./common/map.js');\nvar seq = require('./common/seq.js');\nvar string = require('./common/string.js');\nvar tags = require('./tags.js');\n\nconst sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;\nclass Schema {\n constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {\n this.compat = Array.isArray(compat)\n ? tags.getTags(compat, 'compat')\n : compat\n ? tags.getTags(null, compat)\n : null;\n this.name = (typeof schema === 'string' && schema) || 'core';\n this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};\n this.tags = tags.getTags(customTags, this.name, merge);\n this.toStringOptions = toStringDefaults ?? null;\n Object.defineProperty(this, identity.MAP, { value: map.map });\n Object.defineProperty(this, identity.SCALAR, { value: string.string });\n Object.defineProperty(this, identity.SEQ, { value: seq.seq });\n // Used by createMap()\n this.sortMapEntries =\n typeof sortMapEntries === 'function'\n ? sortMapEntries\n : sortMapEntries === true\n ? sortMapEntriesByKey\n : null;\n }\n clone() {\n const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));\n copy.tags = this.tags.slice();\n return copy;\n }\n}\n\nexports.Schema = Schema;\n",
49
+ "'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar stringify = require('./stringify.js');\nvar stringifyComment = require('./stringifyComment.js');\n\nfunction stringifyDocument(doc, options) {\n const lines = [];\n let hasDirectives = options.directives === true;\n if (options.directives !== false && doc.directives) {\n const dir = doc.directives.toString(doc);\n if (dir) {\n lines.push(dir);\n hasDirectives = true;\n }\n else if (doc.directives.docStart)\n hasDirectives = true;\n }\n if (hasDirectives)\n lines.push('---');\n const ctx = stringify.createStringifyContext(doc, options);\n const { commentString } = ctx.options;\n if (doc.commentBefore) {\n if (lines.length !== 1)\n lines.unshift('');\n const cs = commentString(doc.commentBefore);\n lines.unshift(stringifyComment.indentComment(cs, ''));\n }\n let chompKeep = false;\n let contentComment = null;\n if (doc.contents) {\n if (identity.isNode(doc.contents)) {\n if (doc.contents.spaceBefore && hasDirectives)\n lines.push('');\n if (doc.contents.commentBefore) {\n const cs = commentString(doc.contents.commentBefore);\n lines.push(stringifyComment.indentComment(cs, ''));\n }\n // top-level block scalars need to be indented if followed by a comment\n ctx.forceBlockIndent = !!doc.comment;\n contentComment = doc.contents.comment;\n }\n const onChompKeep = contentComment ? undefined : () => (chompKeep = true);\n let body = stringify.stringify(doc.contents, ctx, () => (contentComment = null), onChompKeep);\n if (contentComment)\n body += stringifyComment.lineComment(body, '', commentString(contentComment));\n if ((body[0] === '|' || body[0] === '>') &&\n lines[lines.length - 1] === '---') {\n // Top-level block scalars with a preceding doc marker ought to use the\n // same line for their header.\n lines[lines.length - 1] = `--- ${body}`;\n }\n else\n lines.push(body);\n }\n else {\n lines.push(stringify.stringify(doc.contents, ctx));\n }\n if (doc.directives?.docEnd) {\n if (doc.comment) {\n const cs = commentString(doc.comment);\n if (cs.includes('\\n')) {\n lines.push('...');\n lines.push(stringifyComment.indentComment(cs, ''));\n }\n else {\n lines.push(`... ${cs}`);\n }\n }\n else {\n lines.push('...');\n }\n }\n else {\n let dc = doc.comment;\n if (dc && chompKeep)\n dc = dc.replace(/^\\n+/, '');\n if (dc) {\n if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')\n lines.push('');\n lines.push(stringifyComment.indentComment(commentString(dc), ''));\n }\n }\n return lines.join('\\n') + '\\n';\n}\n\nexports.stringifyDocument = stringifyDocument;\n",
50
+ "'use strict';\n\nvar Alias = require('../nodes/Alias.js');\nvar Collection = require('../nodes/Collection.js');\nvar identity = require('../nodes/identity.js');\nvar Pair = require('../nodes/Pair.js');\nvar toJS = require('../nodes/toJS.js');\nvar Schema = require('../schema/Schema.js');\nvar stringifyDocument = require('../stringify/stringifyDocument.js');\nvar anchors = require('./anchors.js');\nvar applyReviver = require('./applyReviver.js');\nvar createNode = require('./createNode.js');\nvar directives = require('./directives.js');\n\nclass Document {\n constructor(value, replacer, options) {\n /** A comment before this Document */\n this.commentBefore = null;\n /** A comment immediately after this Document */\n this.comment = null;\n /** Errors encountered during parsing. */\n this.errors = [];\n /** Warnings encountered during parsing. */\n this.warnings = [];\n Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC });\n let _replacer = null;\n if (typeof replacer === 'function' || Array.isArray(replacer)) {\n _replacer = replacer;\n }\n else if (options === undefined && replacer) {\n options = replacer;\n replacer = undefined;\n }\n const opt = Object.assign({\n intAsBigInt: false,\n keepSourceTokens: false,\n logLevel: 'warn',\n prettyErrors: true,\n strict: true,\n stringKeys: false,\n uniqueKeys: true,\n version: '1.2'\n }, options);\n this.options = opt;\n let { version } = opt;\n if (options?._directives) {\n this.directives = options._directives.atDocument();\n if (this.directives.yaml.explicit)\n version = this.directives.yaml.version;\n }\n else\n this.directives = new directives.Directives({ version });\n this.setSchema(version, options);\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents =\n value === undefined ? null : this.createNode(value, _replacer, options);\n }\n /**\n * Create a deep copy of this Document and its contents.\n *\n * Custom Node values that inherit from `Object` still refer to their original instances.\n */\n clone() {\n const copy = Object.create(Document.prototype, {\n [identity.NODE_TYPE]: { value: identity.DOC }\n });\n copy.commentBefore = this.commentBefore;\n copy.comment = this.comment;\n copy.errors = this.errors.slice();\n copy.warnings = this.warnings.slice();\n copy.options = Object.assign({}, this.options);\n if (this.directives)\n copy.directives = this.directives.clone();\n copy.schema = this.schema.clone();\n // @ts-expect-error We can't really know that this matches Contents.\n copy.contents = identity.isNode(this.contents)\n ? this.contents.clone(copy.schema)\n : this.contents;\n if (this.range)\n copy.range = this.range.slice();\n return copy;\n }\n /** Adds a value to the document. */\n add(value) {\n if (assertCollection(this.contents))\n this.contents.add(value);\n }\n /** Adds a value to the document. */\n addIn(path, value) {\n if (assertCollection(this.contents))\n this.contents.addIn(path, value);\n }\n /**\n * Create a new `Alias` node, ensuring that the target `node` has the required anchor.\n *\n * If `node` already has an anchor, `name` is ignored.\n * Otherwise, the `node.anchor` value will be set to `name`,\n * or if an anchor with that name is already present in the document,\n * `name` will be used as a prefix for a new unique anchor.\n * If `name` is undefined, the generated anchor will use 'a' as a prefix.\n */\n createAlias(node, name) {\n if (!node.anchor) {\n const prev = anchors.anchorNames(this);\n node.anchor =\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n !name || prev.has(name) ? anchors.findNewAnchor(name || 'a', prev) : name;\n }\n return new Alias.Alias(node.anchor);\n }\n createNode(value, replacer, options) {\n let _replacer = undefined;\n if (typeof replacer === 'function') {\n value = replacer.call({ '': value }, '', value);\n _replacer = replacer;\n }\n else if (Array.isArray(replacer)) {\n const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;\n const asStr = replacer.filter(keyToStr).map(String);\n if (asStr.length > 0)\n replacer = replacer.concat(asStr);\n _replacer = replacer;\n }\n else if (options === undefined && replacer) {\n options = replacer;\n replacer = undefined;\n }\n const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};\n const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this, \n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n anchorPrefix || 'a');\n const ctx = {\n aliasDuplicateObjects: aliasDuplicateObjects ?? true,\n keepUndefined: keepUndefined ?? false,\n onAnchor,\n onTagObj,\n replacer: _replacer,\n schema: this.schema,\n sourceObjects\n };\n const node = createNode.createNode(value, tag, ctx);\n if (flow && identity.isCollection(node))\n node.flow = true;\n setAnchors();\n return node;\n }\n /**\n * Convert a key and a value into a `Pair` using the current schema,\n * recursively wrapping all values as `Scalar` or `Collection` nodes.\n */\n createPair(key, value, options = {}) {\n const k = this.createNode(key, null, options);\n const v = this.createNode(value, null, options);\n return new Pair.Pair(k, v);\n }\n /**\n * Removes a value from the document.\n * @returns `true` if the item was found and removed.\n */\n delete(key) {\n return assertCollection(this.contents) ? this.contents.delete(key) : false;\n }\n /**\n * Removes a value from the document.\n * @returns `true` if the item was found and removed.\n */\n deleteIn(path) {\n if (Collection.isEmptyPath(path)) {\n if (this.contents == null)\n return false;\n // @ts-expect-error Presumed impossible if Strict extends false\n this.contents = null;\n return true;\n }\n return assertCollection(this.contents)\n ? this.contents.deleteIn(path)\n : false;\n }\n /**\n * Returns item at `key`, or `undefined` if not found. By default unwraps\n * scalar values from their surrounding node; to disable set `keepScalar` to\n * `true` (collections are always returned intact).\n */\n get(key, keepScalar) {\n return identity.isCollection(this.contents)\n ? this.contents.get(key, keepScalar)\n : undefined;\n }\n /**\n * Returns item at `path`, or `undefined` if not found. By default unwraps\n * scalar values from their surrounding node; to disable set `keepScalar` to\n * `true` (collections are always returned intact).\n */\n getIn(path, keepScalar) {\n if (Collection.isEmptyPath(path))\n return !keepScalar && identity.isScalar(this.contents)\n ? this.contents.value\n : this.contents;\n return identity.isCollection(this.contents)\n ? this.contents.getIn(path, keepScalar)\n : undefined;\n }\n /**\n * Checks if the document includes a value with the key `key`.\n */\n has(key) {\n return identity.isCollection(this.contents) ? this.contents.has(key) : false;\n }\n /**\n * Checks if the document includes a value at `path`.\n */\n hasIn(path) {\n if (Collection.isEmptyPath(path))\n return this.contents !== undefined;\n return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false;\n }\n /**\n * Sets a value in this document. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n */\n set(key, value) {\n if (this.contents == null) {\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents = Collection.collectionFromPath(this.schema, [key], value);\n }\n else if (assertCollection(this.contents)) {\n this.contents.set(key, value);\n }\n }\n /**\n * Sets a value in this document. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n */\n setIn(path, value) {\n if (Collection.isEmptyPath(path)) {\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents = value;\n }\n else if (this.contents == null) {\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value);\n }\n else if (assertCollection(this.contents)) {\n this.contents.setIn(path, value);\n }\n }\n /**\n * Change the YAML version and schema used by the document.\n * A `null` version disables support for directives, explicit tags, anchors, and aliases.\n * It also requires the `schema` option to be given as a `Schema` instance value.\n *\n * Overrides all previously set schema options.\n */\n setSchema(version, options = {}) {\n if (typeof version === 'number')\n version = String(version);\n let opt;\n switch (version) {\n case '1.1':\n if (this.directives)\n this.directives.yaml.version = '1.1';\n else\n this.directives = new directives.Directives({ version: '1.1' });\n opt = { resolveKnownTags: false, schema: 'yaml-1.1' };\n break;\n case '1.2':\n case 'next':\n if (this.directives)\n this.directives.yaml.version = version;\n else\n this.directives = new directives.Directives({ version });\n opt = { resolveKnownTags: true, schema: 'core' };\n break;\n case null:\n if (this.directives)\n delete this.directives;\n opt = null;\n break;\n default: {\n const sv = JSON.stringify(version);\n throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);\n }\n }\n // Not using `instanceof Schema` to allow for duck typing\n if (options.schema instanceof Object)\n this.schema = options.schema;\n else if (opt)\n this.schema = new Schema.Schema(Object.assign(opt, options));\n else\n throw new Error(`With a null YAML version, the { schema: Schema } option is required`);\n }\n // json & jsonArg are only used from toJSON()\n toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n const ctx = {\n anchors: new Map(),\n doc: this,\n keep: !json,\n mapAsMap: mapAsMap === true,\n mapKeyWarned: false,\n maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n };\n const res = toJS.toJS(this.contents, jsonArg ?? '', ctx);\n if (typeof onAnchor === 'function')\n for (const { count, res } of ctx.anchors.values())\n onAnchor(res, count);\n return typeof reviver === 'function'\n ? applyReviver.applyReviver(reviver, { '': res }, '', res)\n : res;\n }\n /**\n * A JSON representation of the document `contents`.\n *\n * @param jsonArg Used by `JSON.stringify` to indicate the array index or\n * property name.\n */\n toJSON(jsonArg, onAnchor) {\n return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });\n }\n /** A YAML representation of the document. */\n toString(options = {}) {\n if (this.errors.length > 0)\n throw new Error('Document with errors cannot be stringified');\n if ('indent' in options &&\n (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {\n const s = JSON.stringify(options.indent);\n throw new Error(`\"indent\" option must be a positive integer, not ${s}`);\n }\n return stringifyDocument.stringifyDocument(this, options);\n }\n}\nfunction assertCollection(contents) {\n if (identity.isCollection(contents))\n return true;\n throw new Error('Expected a YAML collection as document contents');\n}\n\nexports.Document = Document;\n",
51
+ "'use strict';\n\nclass YAMLError extends Error {\n constructor(name, pos, code, message) {\n super();\n this.name = name;\n this.code = code;\n this.message = message;\n this.pos = pos;\n }\n}\nclass YAMLParseError extends YAMLError {\n constructor(pos, code, message) {\n super('YAMLParseError', pos, code, message);\n }\n}\nclass YAMLWarning extends YAMLError {\n constructor(pos, code, message) {\n super('YAMLWarning', pos, code, message);\n }\n}\nconst prettifyError = (src, lc) => (error) => {\n if (error.pos[0] === -1)\n return;\n error.linePos = error.pos.map(pos => lc.linePos(pos));\n const { line, col } = error.linePos[0];\n error.message += ` at line ${line}, column ${col}`;\n let ci = col - 1;\n let lineStr = src\n .substring(lc.lineStarts[line - 1], lc.lineStarts[line])\n .replace(/[\\n\\r]+$/, '');\n // Trim to max 80 chars, keeping col position near the middle\n if (ci >= 60 && lineStr.length > 80) {\n const trimStart = Math.min(ci - 39, lineStr.length - 79);\n lineStr = '…' + lineStr.substring(trimStart);\n ci -= trimStart - 1;\n }\n if (lineStr.length > 80)\n lineStr = lineStr.substring(0, 79) + '…';\n // Include previous line in context if pointing at line start\n if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {\n // Regexp won't match if start is trimmed\n let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);\n if (prev.length > 80)\n prev = prev.substring(0, 79) + '…\\n';\n lineStr = prev + lineStr;\n }\n if (/[^ ]/.test(lineStr)) {\n let count = 1;\n const end = error.linePos[1];\n if (end?.line === line && end.col > col) {\n count = Math.max(1, Math.min(end.col - col, 80 - ci));\n }\n const pointer = ' '.repeat(ci) + '^'.repeat(count);\n error.message += `:\\n\\n${lineStr}\\n${pointer}\\n`;\n }\n};\n\nexports.YAMLError = YAMLError;\nexports.YAMLParseError = YAMLParseError;\nexports.YAMLWarning = YAMLWarning;\nexports.prettifyError = prettifyError;\n",
52
+ "'use strict';\n\nfunction resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {\n let spaceBefore = false;\n let atNewline = startOnNewline;\n let hasSpace = startOnNewline;\n let comment = '';\n let commentSep = '';\n let hasNewline = false;\n let reqSpace = false;\n let tab = null;\n let anchor = null;\n let tag = null;\n let newlineAfterProp = null;\n let comma = null;\n let found = null;\n let start = null;\n for (const token of tokens) {\n if (reqSpace) {\n if (token.type !== 'space' &&\n token.type !== 'newline' &&\n token.type !== 'comma')\n onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');\n reqSpace = false;\n }\n if (tab) {\n if (atNewline && token.type !== 'comment' && token.type !== 'newline') {\n onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');\n }\n tab = null;\n }\n switch (token.type) {\n case 'space':\n // At the doc level, tabs at line start may be parsed\n // as leading white space rather than indentation.\n // In a flow collection, only the parser handles indent.\n if (!flow &&\n (indicator !== 'doc-start' || next?.type !== 'flow-collection') &&\n token.source.includes('\\t')) {\n tab = token;\n }\n hasSpace = true;\n break;\n case 'comment': {\n if (!hasSpace)\n onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');\n const cb = token.source.substring(1) || ' ';\n if (!comment)\n comment = cb;\n else\n comment += commentSep + cb;\n commentSep = '';\n atNewline = false;\n break;\n }\n case 'newline':\n if (atNewline) {\n if (comment)\n comment += token.source;\n else if (!found || indicator !== 'seq-item-ind')\n spaceBefore = true;\n }\n else\n commentSep += token.source;\n atNewline = true;\n hasNewline = true;\n if (anchor || tag)\n newlineAfterProp = token;\n hasSpace = true;\n break;\n case 'anchor':\n if (anchor)\n onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor');\n if (token.source.endsWith(':'))\n onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true);\n anchor = token;\n start ?? (start = token.offset);\n atNewline = false;\n hasSpace = false;\n reqSpace = true;\n break;\n case 'tag': {\n if (tag)\n onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag');\n tag = token;\n start ?? (start = token.offset);\n atNewline = false;\n hasSpace = false;\n reqSpace = true;\n break;\n }\n case indicator:\n // Could here handle preceding comments differently\n if (anchor || tag)\n onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`);\n if (found)\n onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`);\n found = token;\n atNewline =\n indicator === 'seq-item-ind' || indicator === 'explicit-key-ind';\n hasSpace = false;\n break;\n case 'comma':\n if (flow) {\n if (comma)\n onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`);\n comma = token;\n atNewline = false;\n hasSpace = false;\n break;\n }\n // else fallthrough\n default:\n onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`);\n atNewline = false;\n hasSpace = false;\n }\n }\n const last = tokens[tokens.length - 1];\n const end = last ? last.offset + last.source.length : offset;\n if (reqSpace &&\n next &&\n next.type !== 'space' &&\n next.type !== 'newline' &&\n next.type !== 'comma' &&\n (next.type !== 'scalar' || next.source !== '')) {\n onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');\n }\n if (tab &&\n ((atNewline && tab.indent <= parentIndent) ||\n next?.type === 'block-map' ||\n next?.type === 'block-seq'))\n onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');\n return {\n comma,\n found,\n spaceBefore,\n comment,\n hasNewline,\n anchor,\n tag,\n newlineAfterProp,\n end,\n start: start ?? end\n };\n}\n\nexports.resolveProps = resolveProps;\n",
53
+ "'use strict';\n\nfunction containsNewline(key) {\n if (!key)\n return null;\n switch (key.type) {\n case 'alias':\n case 'scalar':\n case 'double-quoted-scalar':\n case 'single-quoted-scalar':\n if (key.source.includes('\\n'))\n return true;\n if (key.end)\n for (const st of key.end)\n if (st.type === 'newline')\n return true;\n return false;\n case 'flow-collection':\n for (const it of key.items) {\n for (const st of it.start)\n if (st.type === 'newline')\n return true;\n if (it.sep)\n for (const st of it.sep)\n if (st.type === 'newline')\n return true;\n if (containsNewline(it.key) || containsNewline(it.value))\n return true;\n }\n return false;\n default:\n return true;\n }\n}\n\nexports.containsNewline = containsNewline;\n",
54
+ "'use strict';\n\nvar utilContainsNewline = require('./util-contains-newline.js');\n\nfunction flowIndentCheck(indent, fc, onError) {\n if (fc?.type === 'flow-collection') {\n const end = fc.end[0];\n if (end.indent === indent &&\n (end.source === ']' || end.source === '}') &&\n utilContainsNewline.containsNewline(fc)) {\n const msg = 'Flow end indicator should be more indented than parent';\n onError(end, 'BAD_INDENT', msg, true);\n }\n }\n}\n\nexports.flowIndentCheck = flowIndentCheck;\n",
55
+ "'use strict';\n\nvar identity = require('../nodes/identity.js');\n\nfunction mapIncludes(ctx, items, search) {\n const { uniqueKeys } = ctx.options;\n if (uniqueKeys === false)\n return false;\n const isEqual = typeof uniqueKeys === 'function'\n ? uniqueKeys\n : (a, b) => a === b || (identity.isScalar(a) && identity.isScalar(b) && a.value === b.value);\n return items.some(pair => isEqual(pair.key, search));\n}\n\nexports.mapIncludes = mapIncludes;\n",
56
+ "'use strict';\n\nvar Pair = require('../nodes/Pair.js');\nvar YAMLMap = require('../nodes/YAMLMap.js');\nvar resolveProps = require('./resolve-props.js');\nvar utilContainsNewline = require('./util-contains-newline.js');\nvar utilFlowIndentCheck = require('./util-flow-indent-check.js');\nvar utilMapIncludes = require('./util-map-includes.js');\n\nconst startColMsg = 'All mapping items must start at the same column';\nfunction resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {\n const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap;\n const map = new NodeClass(ctx.schema);\n if (ctx.atRoot)\n ctx.atRoot = false;\n let offset = bm.offset;\n let commentEnd = null;\n for (const collItem of bm.items) {\n const { start, key, sep, value } = collItem;\n // key properties\n const keyProps = resolveProps.resolveProps(start, {\n indicator: 'explicit-key-ind',\n next: key ?? sep?.[0],\n offset,\n onError,\n parentIndent: bm.indent,\n startOnNewline: true\n });\n const implicitKey = !keyProps.found;\n if (implicitKey) {\n if (key) {\n if (key.type === 'block-seq')\n onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key');\n else if ('indent' in key && key.indent !== bm.indent)\n onError(offset, 'BAD_INDENT', startColMsg);\n }\n if (!keyProps.anchor && !keyProps.tag && !sep) {\n commentEnd = keyProps.end;\n if (keyProps.comment) {\n if (map.comment)\n map.comment += '\\n' + keyProps.comment;\n else\n map.comment = keyProps.comment;\n }\n continue;\n }\n if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) {\n onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line');\n }\n }\n else if (keyProps.found?.indent !== bm.indent) {\n onError(offset, 'BAD_INDENT', startColMsg);\n }\n // key value\n ctx.atKey = true;\n const keyStart = keyProps.end;\n const keyNode = key\n ? composeNode(ctx, key, keyProps, onError)\n : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);\n if (ctx.schema.compat)\n utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError);\n ctx.atKey = false;\n if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))\n onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');\n // value properties\n const valueProps = resolveProps.resolveProps(sep ?? [], {\n indicator: 'map-value-ind',\n next: value,\n offset: keyNode.range[2],\n onError,\n parentIndent: bm.indent,\n startOnNewline: !key || key.type === 'block-scalar'\n });\n offset = valueProps.end;\n if (valueProps.found) {\n if (implicitKey) {\n if (value?.type === 'block-map' && !valueProps.hasNewline)\n onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings');\n if (ctx.options.strict &&\n keyProps.start < valueProps.found.offset - 1024)\n onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key');\n }\n // value value\n const valueNode = value\n ? composeNode(ctx, value, valueProps, onError)\n : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);\n if (ctx.schema.compat)\n utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);\n offset = valueNode.range[2];\n const pair = new Pair.Pair(keyNode, valueNode);\n if (ctx.options.keepSourceTokens)\n pair.srcToken = collItem;\n map.items.push(pair);\n }\n else {\n // key with no value\n if (implicitKey)\n onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values');\n if (valueProps.comment) {\n if (keyNode.comment)\n keyNode.comment += '\\n' + valueProps.comment;\n else\n keyNode.comment = valueProps.comment;\n }\n const pair = new Pair.Pair(keyNode);\n if (ctx.options.keepSourceTokens)\n pair.srcToken = collItem;\n map.items.push(pair);\n }\n }\n if (commentEnd && commentEnd < offset)\n onError(commentEnd, 'IMPOSSIBLE', 'Map comment with trailing content');\n map.range = [bm.offset, offset, commentEnd ?? offset];\n return map;\n}\n\nexports.resolveBlockMap = resolveBlockMap;\n",
57
+ "'use strict';\n\nvar YAMLSeq = require('../nodes/YAMLSeq.js');\nvar resolveProps = require('./resolve-props.js');\nvar utilFlowIndentCheck = require('./util-flow-indent-check.js');\n\nfunction resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {\n const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq;\n const seq = new NodeClass(ctx.schema);\n if (ctx.atRoot)\n ctx.atRoot = false;\n if (ctx.atKey)\n ctx.atKey = false;\n let offset = bs.offset;\n let commentEnd = null;\n for (const { start, value } of bs.items) {\n const props = resolveProps.resolveProps(start, {\n indicator: 'seq-item-ind',\n next: value,\n offset,\n onError,\n parentIndent: bs.indent,\n startOnNewline: true\n });\n if (!props.found) {\n if (props.anchor || props.tag || value) {\n if (value?.type === 'block-seq')\n onError(props.end, 'BAD_INDENT', 'All sequence items must start at the same column');\n else\n onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator');\n }\n else {\n commentEnd = props.end;\n if (props.comment)\n seq.comment = props.comment;\n continue;\n }\n }\n const node = value\n ? composeNode(ctx, value, props, onError)\n : composeEmptyNode(ctx, props.end, start, null, props, onError);\n if (ctx.schema.compat)\n utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError);\n offset = node.range[2];\n seq.items.push(node);\n }\n seq.range = [bs.offset, offset, commentEnd ?? offset];\n return seq;\n}\n\nexports.resolveBlockSeq = resolveBlockSeq;\n",
58
+ "'use strict';\n\nfunction resolveEnd(end, offset, reqSpace, onError) {\n let comment = '';\n if (end) {\n let hasSpace = false;\n let sep = '';\n for (const token of end) {\n const { source, type } = token;\n switch (type) {\n case 'space':\n hasSpace = true;\n break;\n case 'comment': {\n if (reqSpace && !hasSpace)\n onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');\n const cb = source.substring(1) || ' ';\n if (!comment)\n comment = cb;\n else\n comment += sep + cb;\n sep = '';\n break;\n }\n case 'newline':\n if (comment)\n sep += source;\n hasSpace = true;\n break;\n default:\n onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`);\n }\n offset += source.length;\n }\n }\n return { comment, offset };\n}\n\nexports.resolveEnd = resolveEnd;\n",
59
+ "'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Pair = require('../nodes/Pair.js');\nvar YAMLMap = require('../nodes/YAMLMap.js');\nvar YAMLSeq = require('../nodes/YAMLSeq.js');\nvar resolveEnd = require('./resolve-end.js');\nvar resolveProps = require('./resolve-props.js');\nvar utilContainsNewline = require('./util-contains-newline.js');\nvar utilMapIncludes = require('./util-map-includes.js');\n\nconst blockMsg = 'Block collections are not allowed within flow collections';\nconst isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');\nfunction resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {\n const isMap = fc.start.source === '{';\n const fcName = isMap ? 'flow map' : 'flow sequence';\n const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq));\n const coll = new NodeClass(ctx.schema);\n coll.flow = true;\n const atRoot = ctx.atRoot;\n if (atRoot)\n ctx.atRoot = false;\n if (ctx.atKey)\n ctx.atKey = false;\n let offset = fc.offset + fc.start.source.length;\n for (let i = 0; i < fc.items.length; ++i) {\n const collItem = fc.items[i];\n const { start, key, sep, value } = collItem;\n const props = resolveProps.resolveProps(start, {\n flow: fcName,\n indicator: 'explicit-key-ind',\n next: key ?? sep?.[0],\n offset,\n onError,\n parentIndent: fc.indent,\n startOnNewline: false\n });\n if (!props.found) {\n if (!props.anchor && !props.tag && !sep && !value) {\n if (i === 0 && props.comma)\n onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);\n else if (i < fc.items.length - 1)\n onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`);\n if (props.comment) {\n if (coll.comment)\n coll.comment += '\\n' + props.comment;\n else\n coll.comment = props.comment;\n }\n offset = props.end;\n continue;\n }\n if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key))\n onError(key, // checked by containsNewline()\n 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');\n }\n if (i === 0) {\n if (props.comma)\n onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);\n }\n else {\n if (!props.comma)\n onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`);\n if (props.comment) {\n let prevItemComment = '';\n loop: for (const st of start) {\n switch (st.type) {\n case 'comma':\n case 'space':\n break;\n case 'comment':\n prevItemComment = st.source.substring(1);\n break loop;\n default:\n break loop;\n }\n }\n if (prevItemComment) {\n let prev = coll.items[coll.items.length - 1];\n if (identity.isPair(prev))\n prev = prev.value ?? prev.key;\n if (prev.comment)\n prev.comment += '\\n' + prevItemComment;\n else\n prev.comment = prevItemComment;\n props.comment = props.comment.substring(prevItemComment.length + 1);\n }\n }\n }\n if (!isMap && !sep && !props.found) {\n // item is a value in a seq\n // → key & sep are empty, start does not include ? or :\n const valueNode = value\n ? composeNode(ctx, value, props, onError)\n : composeEmptyNode(ctx, props.end, sep, null, props, onError);\n coll.items.push(valueNode);\n offset = valueNode.range[2];\n if (isBlock(value))\n onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);\n }\n else {\n // item is a key+value pair\n // key value\n ctx.atKey = true;\n const keyStart = props.end;\n const keyNode = key\n ? composeNode(ctx, key, props, onError)\n : composeEmptyNode(ctx, keyStart, start, null, props, onError);\n if (isBlock(key))\n onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg);\n ctx.atKey = false;\n // value properties\n const valueProps = resolveProps.resolveProps(sep ?? [], {\n flow: fcName,\n indicator: 'map-value-ind',\n next: value,\n offset: keyNode.range[2],\n onError,\n parentIndent: fc.indent,\n startOnNewline: false\n });\n if (valueProps.found) {\n if (!isMap && !props.found && ctx.options.strict) {\n if (sep)\n for (const st of sep) {\n if (st === valueProps.found)\n break;\n if (st.type === 'newline') {\n onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');\n break;\n }\n }\n if (props.start < valueProps.found.offset - 1024)\n onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key');\n }\n }\n else if (value) {\n if ('source' in value && value.source?.[0] === ':')\n onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`);\n else\n onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`);\n }\n // value value\n const valueNode = value\n ? composeNode(ctx, value, valueProps, onError)\n : valueProps.found\n ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError)\n : null;\n if (valueNode) {\n if (isBlock(value))\n onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);\n }\n else if (valueProps.comment) {\n if (keyNode.comment)\n keyNode.comment += '\\n' + valueProps.comment;\n else\n keyNode.comment = valueProps.comment;\n }\n const pair = new Pair.Pair(keyNode, valueNode);\n if (ctx.options.keepSourceTokens)\n pair.srcToken = collItem;\n if (isMap) {\n const map = coll;\n if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))\n onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');\n map.items.push(pair);\n }\n else {\n const map = new YAMLMap.YAMLMap(ctx.schema);\n map.flow = true;\n map.items.push(pair);\n const endRange = (valueNode ?? keyNode).range;\n map.range = [keyNode.range[0], endRange[1], endRange[2]];\n coll.items.push(map);\n }\n offset = valueNode ? valueNode.range[2] : valueProps.end;\n }\n }\n const expectedEnd = isMap ? '}' : ']';\n const [ce, ...ee] = fc.end;\n let cePos = offset;\n if (ce?.source === expectedEnd)\n cePos = ce.offset + ce.source.length;\n else {\n const name = fcName[0].toUpperCase() + fcName.substring(1);\n const msg = atRoot\n ? `${name} must end with a ${expectedEnd}`\n : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;\n onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg);\n if (ce && ce.source.length !== 1)\n ee.unshift(ce);\n }\n if (ee.length > 0) {\n const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError);\n if (end.comment) {\n if (coll.comment)\n coll.comment += '\\n' + end.comment;\n else\n coll.comment = end.comment;\n }\n coll.range = [fc.offset, cePos, end.offset];\n }\n else {\n coll.range = [fc.offset, cePos, cePos];\n }\n return coll;\n}\n\nexports.resolveFlowCollection = resolveFlowCollection;\n",
60
+ "'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\nvar YAMLMap = require('../nodes/YAMLMap.js');\nvar YAMLSeq = require('../nodes/YAMLSeq.js');\nvar resolveBlockMap = require('./resolve-block-map.js');\nvar resolveBlockSeq = require('./resolve-block-seq.js');\nvar resolveFlowCollection = require('./resolve-flow-collection.js');\n\nfunction resolveCollection(CN, ctx, token, onError, tagName, tag) {\n const coll = token.type === 'block-map'\n ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag)\n : token.type === 'block-seq'\n ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag)\n : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag);\n const Coll = coll.constructor;\n // If we got a tagName matching the class, or the tag name is '!',\n // then use the tagName from the node class used to create it.\n if (tagName === '!' || tagName === Coll.tagName) {\n coll.tag = Coll.tagName;\n return coll;\n }\n if (tagName)\n coll.tag = tagName;\n return coll;\n}\nfunction composeCollection(CN, ctx, token, props, onError) {\n const tagToken = props.tag;\n const tagName = !tagToken\n ? null\n : ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));\n if (token.type === 'block-seq') {\n const { anchor, newlineAfterProp: nl } = props;\n const lastProp = anchor && tagToken\n ? anchor.offset > tagToken.offset\n ? anchor\n : tagToken\n : (anchor ?? tagToken);\n if (lastProp && (!nl || nl.offset < lastProp.offset)) {\n const message = 'Missing newline after block sequence props';\n onError(lastProp, 'MISSING_CHAR', message);\n }\n }\n const expType = token.type === 'block-map'\n ? 'map'\n : token.type === 'block-seq'\n ? 'seq'\n : token.start.source === '{'\n ? 'map'\n : 'seq';\n // shortcut: check if it's a generic YAMLMap or YAMLSeq\n // before jumping into the custom tag logic.\n if (!tagToken ||\n !tagName ||\n tagName === '!' ||\n (tagName === YAMLMap.YAMLMap.tagName && expType === 'map') ||\n (tagName === YAMLSeq.YAMLSeq.tagName && expType === 'seq')) {\n return resolveCollection(CN, ctx, token, onError, tagName);\n }\n let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType);\n if (!tag) {\n const kt = ctx.schema.knownTags[tagName];\n if (kt?.collection === expType) {\n ctx.schema.tags.push(Object.assign({}, kt, { default: false }));\n tag = kt;\n }\n else {\n if (kt) {\n onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? 'scalar'}`, true);\n }\n else {\n onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);\n }\n return resolveCollection(CN, ctx, token, onError, tagName);\n }\n }\n const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);\n const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll;\n const node = identity.isNode(res)\n ? res\n : new Scalar.Scalar(res);\n node.range = coll.range;\n node.tag = tagName;\n if (tag?.format)\n node.format = tag.format;\n return node;\n}\n\nexports.composeCollection = composeCollection;\n",
61
+ "'use strict';\n\nvar Scalar = require('../nodes/Scalar.js');\n\nfunction resolveBlockScalar(ctx, scalar, onError) {\n const start = scalar.offset;\n const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);\n if (!header)\n return { value: '', type: null, comment: '', range: [start, start, start] };\n const type = header.mode === '>' ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;\n const lines = scalar.source ? splitLines(scalar.source) : [];\n // determine the end of content & start of chomping\n let chompStart = lines.length;\n for (let i = lines.length - 1; i >= 0; --i) {\n const content = lines[i][1];\n if (content === '' || content === '\\r')\n chompStart = i;\n else\n break;\n }\n // shortcut for empty contents\n if (chompStart === 0) {\n const value = header.chomp === '+' && lines.length > 0\n ? '\\n'.repeat(Math.max(1, lines.length - 1))\n : '';\n let end = start + header.length;\n if (scalar.source)\n end += scalar.source.length;\n return { value, type, comment: header.comment, range: [start, end, end] };\n }\n // find the indentation level to trim from start\n let trimIndent = scalar.indent + header.indent;\n let offset = scalar.offset + header.length;\n let contentStart = 0;\n for (let i = 0; i < chompStart; ++i) {\n const [indent, content] = lines[i];\n if (content === '' || content === '\\r') {\n if (header.indent === 0 && indent.length > trimIndent)\n trimIndent = indent.length;\n }\n else {\n if (indent.length < trimIndent) {\n const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';\n onError(offset + indent.length, 'MISSING_CHAR', message);\n }\n if (header.indent === 0)\n trimIndent = indent.length;\n contentStart = i;\n if (trimIndent === 0 && !ctx.atRoot) {\n const message = 'Block scalar values in collections must be indented';\n onError(offset, 'BAD_INDENT', message);\n }\n break;\n }\n offset += indent.length + content.length + 1;\n }\n // include trailing more-indented empty lines in content\n for (let i = lines.length - 1; i >= chompStart; --i) {\n if (lines[i][0].length > trimIndent)\n chompStart = i + 1;\n }\n let value = '';\n let sep = '';\n let prevMoreIndented = false;\n // leading whitespace is kept intact\n for (let i = 0; i < contentStart; ++i)\n value += lines[i][0].slice(trimIndent) + '\\n';\n for (let i = contentStart; i < chompStart; ++i) {\n let [indent, content] = lines[i];\n offset += indent.length + content.length + 1;\n const crlf = content[content.length - 1] === '\\r';\n if (crlf)\n content = content.slice(0, -1);\n /* istanbul ignore if already caught in lexer */\n if (content && indent.length < trimIndent) {\n const src = header.indent\n ? 'explicit indentation indicator'\n : 'first line';\n const message = `Block scalar lines must not be less indented than their ${src}`;\n onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message);\n indent = '';\n }\n if (type === Scalar.Scalar.BLOCK_LITERAL) {\n value += sep + indent.slice(trimIndent) + content;\n sep = '\\n';\n }\n else if (indent.length > trimIndent || content[0] === '\\t') {\n // more-indented content within a folded block\n if (sep === ' ')\n sep = '\\n';\n else if (!prevMoreIndented && sep === '\\n')\n sep = '\\n\\n';\n value += sep + indent.slice(trimIndent) + content;\n sep = '\\n';\n prevMoreIndented = true;\n }\n else if (content === '') {\n // empty line\n if (sep === '\\n')\n value += '\\n';\n else\n sep = '\\n';\n }\n else {\n value += sep + content;\n sep = ' ';\n prevMoreIndented = false;\n }\n }\n switch (header.chomp) {\n case '-':\n break;\n case '+':\n for (let i = chompStart; i < lines.length; ++i)\n value += '\\n' + lines[i][0].slice(trimIndent);\n if (value[value.length - 1] !== '\\n')\n value += '\\n';\n break;\n default:\n value += '\\n';\n }\n const end = start + header.length + scalar.source.length;\n return { value, type, comment: header.comment, range: [start, end, end] };\n}\nfunction parseBlockScalarHeader({ offset, props }, strict, onError) {\n /* istanbul ignore if should not happen */\n if (props[0].type !== 'block-scalar-header') {\n onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found');\n return null;\n }\n const { source } = props[0];\n const mode = source[0];\n let indent = 0;\n let chomp = '';\n let error = -1;\n for (let i = 1; i < source.length; ++i) {\n const ch = source[i];\n if (!chomp && (ch === '-' || ch === '+'))\n chomp = ch;\n else {\n const n = Number(ch);\n if (!indent && n)\n indent = n;\n else if (error === -1)\n error = offset + i;\n }\n }\n if (error !== -1)\n onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`);\n let hasSpace = false;\n let comment = '';\n let length = source.length;\n for (let i = 1; i < props.length; ++i) {\n const token = props[i];\n switch (token.type) {\n case 'space':\n hasSpace = true;\n // fallthrough\n case 'newline':\n length += token.source.length;\n break;\n case 'comment':\n if (strict && !hasSpace) {\n const message = 'Comments must be separated from other tokens by white space characters';\n onError(token, 'MISSING_CHAR', message);\n }\n length += token.source.length;\n comment = token.source.substring(1);\n break;\n case 'error':\n onError(token, 'UNEXPECTED_TOKEN', token.message);\n length += token.source.length;\n break;\n /* istanbul ignore next should not happen */\n default: {\n const message = `Unexpected token in block scalar header: ${token.type}`;\n onError(token, 'UNEXPECTED_TOKEN', message);\n const ts = token.source;\n if (ts && typeof ts === 'string')\n length += ts.length;\n }\n }\n }\n return { mode, indent, chomp, comment, length };\n}\n/** @returns Array of lines split up as `[indent, content]` */\nfunction splitLines(source) {\n const split = source.split(/\\n( *)/);\n const first = split[0];\n const m = first.match(/^( *)/);\n const line0 = m?.[1]\n ? [m[1], first.slice(m[1].length)]\n : ['', first];\n const lines = [line0];\n for (let i = 1; i < split.length; i += 2)\n lines.push([split[i], split[i + 1]]);\n return lines;\n}\n\nexports.resolveBlockScalar = resolveBlockScalar;\n",
62
+ "'use strict';\n\nvar Scalar = require('../nodes/Scalar.js');\nvar resolveEnd = require('./resolve-end.js');\n\nfunction resolveFlowScalar(scalar, strict, onError) {\n const { offset, type, source, end } = scalar;\n let _type;\n let value;\n const _onError = (rel, code, msg) => onError(offset + rel, code, msg);\n switch (type) {\n case 'scalar':\n _type = Scalar.Scalar.PLAIN;\n value = plainValue(source, _onError);\n break;\n case 'single-quoted-scalar':\n _type = Scalar.Scalar.QUOTE_SINGLE;\n value = singleQuotedValue(source, _onError);\n break;\n case 'double-quoted-scalar':\n _type = Scalar.Scalar.QUOTE_DOUBLE;\n value = doubleQuotedValue(source, _onError);\n break;\n /* istanbul ignore next should not happen */\n default:\n onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`);\n return {\n value: '',\n type: null,\n comment: '',\n range: [offset, offset + source.length, offset + source.length]\n };\n }\n const valueEnd = offset + source.length;\n const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError);\n return {\n value,\n type: _type,\n comment: re.comment,\n range: [offset, valueEnd, re.offset]\n };\n}\nfunction plainValue(source, onError) {\n let badChar = '';\n switch (source[0]) {\n /* istanbul ignore next should not happen */\n case '\\t':\n badChar = 'a tab character';\n break;\n case ',':\n badChar = 'flow indicator character ,';\n break;\n case '%':\n badChar = 'directive indicator character %';\n break;\n case '|':\n case '>': {\n badChar = `block scalar indicator ${source[0]}`;\n break;\n }\n case '@':\n case '`': {\n badChar = `reserved character ${source[0]}`;\n break;\n }\n }\n if (badChar)\n onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`);\n return foldLines(source);\n}\nfunction singleQuotedValue(source, onError) {\n if (source[source.length - 1] !== \"'\" || source.length === 1)\n onError(source.length, 'MISSING_CHAR', \"Missing closing 'quote\");\n return foldLines(source.slice(1, -1)).replace(/''/g, \"'\");\n}\nfunction foldLines(source) {\n /**\n * The negative lookbehind here and in the `re` RegExp is to\n * prevent causing a polynomial search time in certain cases.\n *\n * The try-catch is for Safari, which doesn't support this yet:\n * https://caniuse.com/js-regexp-lookbehind\n */\n let first, line;\n try {\n first = new RegExp('(.*?)(?<![ \\t])[ \\t]*\\r?\\n', 'sy');\n line = new RegExp('[ \\t]*(.*?)(?:(?<![ \\t])[ \\t]*)?\\r?\\n', 'sy');\n }\n catch {\n first = /(.*?)[ \\t]*\\r?\\n/sy;\n line = /[ \\t]*(.*?)[ \\t]*\\r?\\n/sy;\n }\n let match = first.exec(source);\n if (!match)\n return source;\n let res = match[1];\n let sep = ' ';\n let pos = first.lastIndex;\n line.lastIndex = pos;\n while ((match = line.exec(source))) {\n if (match[1] === '') {\n if (sep === '\\n')\n res += sep;\n else\n sep = '\\n';\n }\n else {\n res += sep + match[1];\n sep = ' ';\n }\n pos = line.lastIndex;\n }\n const last = /[ \\t]*(.*)/sy;\n last.lastIndex = pos;\n match = last.exec(source);\n return res + sep + (match?.[1] ?? '');\n}\nfunction doubleQuotedValue(source, onError) {\n let res = '';\n for (let i = 1; i < source.length - 1; ++i) {\n const ch = source[i];\n if (ch === '\\r' && source[i + 1] === '\\n')\n continue;\n if (ch === '\\n') {\n const { fold, offset } = foldNewline(source, i);\n res += fold;\n i = offset;\n }\n else if (ch === '\\\\') {\n let next = source[++i];\n const cc = escapeCodes[next];\n if (cc)\n res += cc;\n else if (next === '\\n') {\n // skip escaped newlines, but still trim the following line\n next = source[i + 1];\n while (next === ' ' || next === '\\t')\n next = source[++i + 1];\n }\n else if (next === '\\r' && source[i + 1] === '\\n') {\n // skip escaped CRLF newlines, but still trim the following line\n next = source[++i + 1];\n while (next === ' ' || next === '\\t')\n next = source[++i + 1];\n }\n else if (next === 'x' || next === 'u' || next === 'U') {\n const length = { x: 2, u: 4, U: 8 }[next];\n res += parseCharCode(source, i + 1, length, onError);\n i += length;\n }\n else {\n const raw = source.substr(i - 1, 2);\n onError(i - 1, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);\n res += raw;\n }\n }\n else if (ch === ' ' || ch === '\\t') {\n // trim trailing whitespace\n const wsStart = i;\n let next = source[i + 1];\n while (next === ' ' || next === '\\t')\n next = source[++i + 1];\n if (next !== '\\n' && !(next === '\\r' && source[i + 2] === '\\n'))\n res += i > wsStart ? source.slice(wsStart, i + 1) : ch;\n }\n else {\n res += ch;\n }\n }\n if (source[source.length - 1] !== '\"' || source.length === 1)\n onError(source.length, 'MISSING_CHAR', 'Missing closing \"quote');\n return res;\n}\n/**\n * Fold a single newline into a space, multiple newlines to N - 1 newlines.\n * Presumes `source[offset] === '\\n'`\n */\nfunction foldNewline(source, offset) {\n let fold = '';\n let ch = source[offset + 1];\n while (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') {\n if (ch === '\\r' && source[offset + 2] !== '\\n')\n break;\n if (ch === '\\n')\n fold += '\\n';\n offset += 1;\n ch = source[offset + 1];\n }\n if (!fold)\n fold = ' ';\n return { fold, offset };\n}\nconst escapeCodes = {\n '0': '\\0', // null character\n a: '\\x07', // bell character\n b: '\\b', // backspace\n e: '\\x1b', // escape character\n f: '\\f', // form feed\n n: '\\n', // line feed\n r: '\\r', // carriage return\n t: '\\t', // horizontal tab\n v: '\\v', // vertical tab\n N: '\\u0085', // Unicode next line\n _: '\\u00a0', // Unicode non-breaking space\n L: '\\u2028', // Unicode line separator\n P: '\\u2029', // Unicode paragraph separator\n ' ': ' ',\n '\"': '\"',\n '/': '/',\n '\\\\': '\\\\',\n '\\t': '\\t'\n};\nfunction parseCharCode(source, offset, length, onError) {\n const cc = source.substr(offset, length);\n const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);\n const code = ok ? parseInt(cc, 16) : NaN;\n if (isNaN(code)) {\n const raw = source.substr(offset - 2, length + 2);\n onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);\n return raw;\n }\n return String.fromCodePoint(code);\n}\n\nexports.resolveFlowScalar = resolveFlowScalar;\n",
63
+ "'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\nvar resolveBlockScalar = require('./resolve-block-scalar.js');\nvar resolveFlowScalar = require('./resolve-flow-scalar.js');\n\nfunction composeScalar(ctx, token, tagToken, onError) {\n const { value, type, comment, range } = token.type === 'block-scalar'\n ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError)\n : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError);\n const tagName = tagToken\n ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg))\n : null;\n let tag;\n if (ctx.options.stringKeys && ctx.atKey) {\n tag = ctx.schema[identity.SCALAR];\n }\n else if (tagName)\n tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError);\n else if (token.type === 'scalar')\n tag = findScalarTagByTest(ctx, value, token, onError);\n else\n tag = ctx.schema[identity.SCALAR];\n let scalar;\n try {\n const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options);\n scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res);\n }\n catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg);\n scalar = new Scalar.Scalar(value);\n }\n scalar.range = range;\n scalar.source = value;\n if (type)\n scalar.type = type;\n if (tagName)\n scalar.tag = tagName;\n if (tag.format)\n scalar.format = tag.format;\n if (comment)\n scalar.comment = comment;\n return scalar;\n}\nfunction findScalarTagByName(schema, value, tagName, tagToken, onError) {\n if (tagName === '!')\n return schema[identity.SCALAR]; // non-specific tag\n const matchWithTest = [];\n for (const tag of schema.tags) {\n if (!tag.collection && tag.tag === tagName) {\n if (tag.default && tag.test)\n matchWithTest.push(tag);\n else\n return tag;\n }\n }\n for (const tag of matchWithTest)\n if (tag.test?.test(value))\n return tag;\n const kt = schema.knownTags[tagName];\n if (kt && !kt.collection) {\n // Ensure that the known tag is available for stringifying,\n // but does not get used by default.\n schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));\n return kt;\n }\n onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str');\n return schema[identity.SCALAR];\n}\nfunction findScalarTagByTest({ atKey, directives, schema }, value, token, onError) {\n const tag = schema.tags.find(tag => (tag.default === true || (atKey && tag.default === 'key')) &&\n tag.test?.test(value)) || schema[identity.SCALAR];\n if (schema.compat) {\n const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ??\n schema[identity.SCALAR];\n if (tag.tag !== compat.tag) {\n const ts = directives.tagString(tag.tag);\n const cs = directives.tagString(compat.tag);\n const msg = `Value may be parsed as either ${ts} or ${cs}`;\n onError(token, 'TAG_RESOLVE_FAILED', msg, true);\n }\n }\n return tag;\n}\n\nexports.composeScalar = composeScalar;\n",
64
+ "'use strict';\n\nfunction emptyScalarPosition(offset, before, pos) {\n if (before) {\n pos ?? (pos = before.length);\n for (let i = pos - 1; i >= 0; --i) {\n let st = before[i];\n switch (st.type) {\n case 'space':\n case 'comment':\n case 'newline':\n offset -= st.source.length;\n continue;\n }\n // Technically, an empty scalar is immediately after the last non-empty\n // node, but it's more useful to place it after any whitespace.\n st = before[++i];\n while (st?.type === 'space') {\n offset += st.source.length;\n st = before[++i];\n }\n break;\n }\n }\n return offset;\n}\n\nexports.emptyScalarPosition = emptyScalarPosition;\n",
65
+ "'use strict';\n\nvar Alias = require('../nodes/Alias.js');\nvar identity = require('../nodes/identity.js');\nvar composeCollection = require('./compose-collection.js');\nvar composeScalar = require('./compose-scalar.js');\nvar resolveEnd = require('./resolve-end.js');\nvar utilEmptyScalarPosition = require('./util-empty-scalar-position.js');\n\nconst CN = { composeNode, composeEmptyNode };\nfunction composeNode(ctx, token, props, onError) {\n const atKey = ctx.atKey;\n const { spaceBefore, comment, anchor, tag } = props;\n let node;\n let isSrcToken = true;\n switch (token.type) {\n case 'alias':\n node = composeAlias(ctx, token, onError);\n if (anchor || tag)\n onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties');\n break;\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar':\n case 'block-scalar':\n node = composeScalar.composeScalar(ctx, token, tag, onError);\n if (anchor)\n node.anchor = anchor.source.substring(1);\n break;\n case 'block-map':\n case 'block-seq':\n case 'flow-collection':\n node = composeCollection.composeCollection(CN, ctx, token, props, onError);\n if (anchor)\n node.anchor = anchor.source.substring(1);\n break;\n default: {\n const message = token.type === 'error'\n ? token.message\n : `Unsupported token (type: ${token.type})`;\n onError(token, 'UNEXPECTED_TOKEN', message);\n node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError);\n isSrcToken = false;\n }\n }\n if (anchor && node.anchor === '')\n onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');\n if (atKey &&\n ctx.options.stringKeys &&\n (!identity.isScalar(node) ||\n typeof node.value !== 'string' ||\n (node.tag && node.tag !== 'tag:yaml.org,2002:str'))) {\n const msg = 'With stringKeys, all keys must be strings';\n onError(tag ?? token, 'NON_STRING_KEY', msg);\n }\n if (spaceBefore)\n node.spaceBefore = true;\n if (comment) {\n if (token.type === 'scalar' && token.source === '')\n node.comment = comment;\n else\n node.commentBefore = comment;\n }\n // @ts-expect-error Type checking misses meaning of isSrcToken\n if (ctx.options.keepSourceTokens && isSrcToken)\n node.srcToken = token;\n return node;\n}\nfunction composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {\n const token = {\n type: 'scalar',\n offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos),\n indent: -1,\n source: ''\n };\n const node = composeScalar.composeScalar(ctx, token, tag, onError);\n if (anchor) {\n node.anchor = anchor.source.substring(1);\n if (node.anchor === '')\n onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');\n }\n if (spaceBefore)\n node.spaceBefore = true;\n if (comment) {\n node.comment = comment;\n node.range[2] = end;\n }\n return node;\n}\nfunction composeAlias({ options }, { offset, source, end }, onError) {\n const alias = new Alias.Alias(source.substring(1));\n if (alias.source === '')\n onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string');\n if (alias.source.endsWith(':'))\n onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true);\n const valueEnd = offset + source.length;\n const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError);\n alias.range = [offset, valueEnd, re.offset];\n if (re.comment)\n alias.comment = re.comment;\n return alias;\n}\n\nexports.composeEmptyNode = composeEmptyNode;\nexports.composeNode = composeNode;\n",
66
+ "'use strict';\n\nvar Document = require('../doc/Document.js');\nvar composeNode = require('./compose-node.js');\nvar resolveEnd = require('./resolve-end.js');\nvar resolveProps = require('./resolve-props.js');\n\nfunction composeDoc(options, directives, { offset, start, value, end }, onError) {\n const opts = Object.assign({ _directives: directives }, options);\n const doc = new Document.Document(undefined, opts);\n const ctx = {\n atKey: false,\n atRoot: true,\n directives: doc.directives,\n options: doc.options,\n schema: doc.schema\n };\n const props = resolveProps.resolveProps(start, {\n indicator: 'doc-start',\n next: value ?? end?.[0],\n offset,\n onError,\n parentIndent: 0,\n startOnNewline: true\n });\n if (props.found) {\n doc.directives.docStart = true;\n if (value &&\n (value.type === 'block-map' || value.type === 'block-seq') &&\n !props.hasNewline)\n onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');\n }\n // @ts-expect-error If Contents is set, let's trust the user\n doc.contents = value\n ? composeNode.composeNode(ctx, value, props, onError)\n : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);\n const contentEnd = doc.contents.range[2];\n const re = resolveEnd.resolveEnd(end, contentEnd, false, onError);\n if (re.comment)\n doc.comment = re.comment;\n doc.range = [offset, contentEnd, re.offset];\n return doc;\n}\n\nexports.composeDoc = composeDoc;\n",
67
+ "'use strict';\n\nvar node_process = require('process');\nvar directives = require('../doc/directives.js');\nvar Document = require('../doc/Document.js');\nvar errors = require('../errors.js');\nvar identity = require('../nodes/identity.js');\nvar composeDoc = require('./compose-doc.js');\nvar resolveEnd = require('./resolve-end.js');\n\nfunction getErrorPos(src) {\n if (typeof src === 'number')\n return [src, src + 1];\n if (Array.isArray(src))\n return src.length === 2 ? src : [src[0], src[1]];\n const { offset, source } = src;\n return [offset, offset + (typeof source === 'string' ? source.length : 1)];\n}\nfunction parsePrelude(prelude) {\n let comment = '';\n let atComment = false;\n let afterEmptyLine = false;\n for (let i = 0; i < prelude.length; ++i) {\n const source = prelude[i];\n switch (source[0]) {\n case '#':\n comment +=\n (comment === '' ? '' : afterEmptyLine ? '\\n\\n' : '\\n') +\n (source.substring(1) || ' ');\n atComment = true;\n afterEmptyLine = false;\n break;\n case '%':\n if (prelude[i + 1]?.[0] !== '#')\n i += 1;\n atComment = false;\n break;\n default:\n // This may be wrong after doc-end, but in that case it doesn't matter\n if (!atComment)\n afterEmptyLine = true;\n atComment = false;\n }\n }\n return { comment, afterEmptyLine };\n}\n/**\n * Compose a stream of CST nodes into a stream of YAML Documents.\n *\n * ```ts\n * import { Composer, Parser } from 'yaml'\n *\n * const src: string = ...\n * const tokens = new Parser().parse(src)\n * const docs = new Composer().compose(tokens)\n * ```\n */\nclass Composer {\n constructor(options = {}) {\n this.doc = null;\n this.atDirectives = false;\n this.prelude = [];\n this.errors = [];\n this.warnings = [];\n this.onError = (source, code, message, warning) => {\n const pos = getErrorPos(source);\n if (warning)\n this.warnings.push(new errors.YAMLWarning(pos, code, message));\n else\n this.errors.push(new errors.YAMLParseError(pos, code, message));\n };\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n this.directives = new directives.Directives({ version: options.version || '1.2' });\n this.options = options;\n }\n decorate(doc, afterDoc) {\n const { comment, afterEmptyLine } = parsePrelude(this.prelude);\n //console.log({ dc: doc.comment, prelude, comment })\n if (comment) {\n const dc = doc.contents;\n if (afterDoc) {\n doc.comment = doc.comment ? `${doc.comment}\\n${comment}` : comment;\n }\n else if (afterEmptyLine || doc.directives.docStart || !dc) {\n doc.commentBefore = comment;\n }\n else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) {\n let it = dc.items[0];\n if (identity.isPair(it))\n it = it.key;\n const cb = it.commentBefore;\n it.commentBefore = cb ? `${comment}\\n${cb}` : comment;\n }\n else {\n const cb = dc.commentBefore;\n dc.commentBefore = cb ? `${comment}\\n${cb}` : comment;\n }\n }\n if (afterDoc) {\n Array.prototype.push.apply(doc.errors, this.errors);\n Array.prototype.push.apply(doc.warnings, this.warnings);\n }\n else {\n doc.errors = this.errors;\n doc.warnings = this.warnings;\n }\n this.prelude = [];\n this.errors = [];\n this.warnings = [];\n }\n /**\n * Current stream status information.\n *\n * Mostly useful at the end of input for an empty stream.\n */\n streamInfo() {\n return {\n comment: parsePrelude(this.prelude).comment,\n directives: this.directives,\n errors: this.errors,\n warnings: this.warnings\n };\n }\n /**\n * Compose tokens into documents.\n *\n * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.\n * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.\n */\n *compose(tokens, forceDoc = false, endOffset = -1) {\n for (const token of tokens)\n yield* this.next(token);\n yield* this.end(forceDoc, endOffset);\n }\n /** Advance the composer by one CST token. */\n *next(token) {\n if (node_process.env.LOG_STREAM)\n console.dir(token, { depth: null });\n switch (token.type) {\n case 'directive':\n this.directives.add(token.source, (offset, message, warning) => {\n const pos = getErrorPos(token);\n pos[0] += offset;\n this.onError(pos, 'BAD_DIRECTIVE', message, warning);\n });\n this.prelude.push(token.source);\n this.atDirectives = true;\n break;\n case 'document': {\n const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError);\n if (this.atDirectives && !doc.directives.docStart)\n this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line');\n this.decorate(doc, false);\n if (this.doc)\n yield this.doc;\n this.doc = doc;\n this.atDirectives = false;\n break;\n }\n case 'byte-order-mark':\n case 'space':\n break;\n case 'comment':\n case 'newline':\n this.prelude.push(token.source);\n break;\n case 'error': {\n const msg = token.source\n ? `${token.message}: ${JSON.stringify(token.source)}`\n : token.message;\n const error = new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg);\n if (this.atDirectives || !this.doc)\n this.errors.push(error);\n else\n this.doc.errors.push(error);\n break;\n }\n case 'doc-end': {\n if (!this.doc) {\n const msg = 'Unexpected doc-end without preceding document';\n this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg));\n break;\n }\n this.doc.directives.docEnd = true;\n const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);\n this.decorate(this.doc, true);\n if (end.comment) {\n const dc = this.doc.comment;\n this.doc.comment = dc ? `${dc}\\n${end.comment}` : end.comment;\n }\n this.doc.range[2] = end.offset;\n break;\n }\n default:\n this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`));\n }\n }\n /**\n * Call at end of input to yield any remaining document.\n *\n * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.\n * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.\n */\n *end(forceDoc = false, endOffset = -1) {\n if (this.doc) {\n this.decorate(this.doc, true);\n yield this.doc;\n this.doc = null;\n }\n else if (forceDoc) {\n const opts = Object.assign({ _directives: this.directives }, this.options);\n const doc = new Document.Document(undefined, opts);\n if (this.atDirectives)\n this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line');\n doc.range = [0, endOffset, endOffset];\n this.decorate(doc, false);\n yield doc;\n }\n }\n}\n\nexports.Composer = Composer;\n",
68
+ "'use strict';\n\nvar resolveBlockScalar = require('../compose/resolve-block-scalar.js');\nvar resolveFlowScalar = require('../compose/resolve-flow-scalar.js');\nvar errors = require('../errors.js');\nvar stringifyString = require('../stringify/stringifyString.js');\n\nfunction resolveAsScalar(token, strict = true, onError) {\n if (token) {\n const _onError = (pos, code, message) => {\n const offset = typeof pos === 'number' ? pos : Array.isArray(pos) ? pos[0] : pos.offset;\n if (onError)\n onError(offset, code, message);\n else\n throw new errors.YAMLParseError([offset, offset + 1], code, message);\n };\n switch (token.type) {\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar':\n return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);\n case 'block-scalar':\n return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);\n }\n }\n return null;\n}\n/**\n * Create a new scalar token with `value`\n *\n * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,\n * as this function does not support any schema operations and won't check for such conflicts.\n *\n * @param value The string representation of the value, which will have its content properly indented.\n * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added.\n * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.\n * @param context.indent The indent level of the token.\n * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value.\n * @param context.offset The offset position of the token.\n * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.\n */\nfunction createScalarToken(value, context) {\n const { implicitKey = false, indent, inFlow = false, offset = -1, type = 'PLAIN' } = context;\n const source = stringifyString.stringifyString({ type, value }, {\n implicitKey,\n indent: indent > 0 ? ' '.repeat(indent) : '',\n inFlow,\n options: { blockQuote: true, lineWidth: -1 }\n });\n const end = context.end ?? [\n { type: 'newline', offset: -1, indent, source: '\\n' }\n ];\n switch (source[0]) {\n case '|':\n case '>': {\n const he = source.indexOf('\\n');\n const head = source.substring(0, he);\n const body = source.substring(he + 1) + '\\n';\n const props = [\n { type: 'block-scalar-header', offset, indent, source: head }\n ];\n if (!addEndtoBlockProps(props, end))\n props.push({ type: 'newline', offset: -1, indent, source: '\\n' });\n return { type: 'block-scalar', offset, indent, props, source: body };\n }\n case '\"':\n return { type: 'double-quoted-scalar', offset, indent, source, end };\n case \"'\":\n return { type: 'single-quoted-scalar', offset, indent, source, end };\n default:\n return { type: 'scalar', offset, indent, source, end };\n }\n}\n/**\n * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have.\n *\n * Best efforts are made to retain any comments previously associated with the `token`,\n * though all contents within a collection's `items` will be overwritten.\n *\n * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,\n * as this function does not support any schema operations and won't check for such conflicts.\n *\n * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key.\n * @param value The string representation of the value, which will have its content properly indented.\n * @param context.afterKey In most cases, values after a key should have an additional level of indentation.\n * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.\n * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value.\n * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.\n */\nfunction setScalarValue(token, value, context = {}) {\n let { afterKey = false, implicitKey = false, inFlow = false, type } = context;\n let indent = 'indent' in token ? token.indent : null;\n if (afterKey && typeof indent === 'number')\n indent += 2;\n if (!type)\n switch (token.type) {\n case 'single-quoted-scalar':\n type = 'QUOTE_SINGLE';\n break;\n case 'double-quoted-scalar':\n type = 'QUOTE_DOUBLE';\n break;\n case 'block-scalar': {\n const header = token.props[0];\n if (header.type !== 'block-scalar-header')\n throw new Error('Invalid block scalar header');\n type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL';\n break;\n }\n default:\n type = 'PLAIN';\n }\n const source = stringifyString.stringifyString({ type, value }, {\n implicitKey: implicitKey || indent === null,\n indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '',\n inFlow,\n options: { blockQuote: true, lineWidth: -1 }\n });\n switch (source[0]) {\n case '|':\n case '>':\n setBlockScalarValue(token, source);\n break;\n case '\"':\n setFlowScalarValue(token, source, 'double-quoted-scalar');\n break;\n case \"'\":\n setFlowScalarValue(token, source, 'single-quoted-scalar');\n break;\n default:\n setFlowScalarValue(token, source, 'scalar');\n }\n}\nfunction setBlockScalarValue(token, source) {\n const he = source.indexOf('\\n');\n const head = source.substring(0, he);\n const body = source.substring(he + 1) + '\\n';\n if (token.type === 'block-scalar') {\n const header = token.props[0];\n if (header.type !== 'block-scalar-header')\n throw new Error('Invalid block scalar header');\n header.source = head;\n token.source = body;\n }\n else {\n const { offset } = token;\n const indent = 'indent' in token ? token.indent : -1;\n const props = [\n { type: 'block-scalar-header', offset, indent, source: head }\n ];\n if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined))\n props.push({ type: 'newline', offset: -1, indent, source: '\\n' });\n for (const key of Object.keys(token))\n if (key !== 'type' && key !== 'offset')\n delete token[key];\n Object.assign(token, { type: 'block-scalar', indent, props, source: body });\n }\n}\n/** @returns `true` if last token is a newline */\nfunction addEndtoBlockProps(props, end) {\n if (end)\n for (const st of end)\n switch (st.type) {\n case 'space':\n case 'comment':\n props.push(st);\n break;\n case 'newline':\n props.push(st);\n return true;\n }\n return false;\n}\nfunction setFlowScalarValue(token, source, type) {\n switch (token.type) {\n case 'scalar':\n case 'double-quoted-scalar':\n case 'single-quoted-scalar':\n token.type = type;\n token.source = source;\n break;\n case 'block-scalar': {\n const end = token.props.slice(1);\n let oa = source.length;\n if (token.props[0].type === 'block-scalar-header')\n oa -= token.props[0].source.length;\n for (const tok of end)\n tok.offset += oa;\n delete token.props;\n Object.assign(token, { type, source, end });\n break;\n }\n case 'block-map':\n case 'block-seq': {\n const offset = token.offset + source.length;\n const nl = { type: 'newline', offset, indent: token.indent, source: '\\n' };\n delete token.items;\n Object.assign(token, { type, source, end: [nl] });\n break;\n }\n default: {\n const indent = 'indent' in token ? token.indent : -1;\n const end = 'end' in token && Array.isArray(token.end)\n ? token.end.filter(st => st.type === 'space' ||\n st.type === 'comment' ||\n st.type === 'newline')\n : [];\n for (const key of Object.keys(token))\n if (key !== 'type' && key !== 'offset')\n delete token[key];\n Object.assign(token, { type, indent, source, end });\n }\n }\n}\n\nexports.createScalarToken = createScalarToken;\nexports.resolveAsScalar = resolveAsScalar;\nexports.setScalarValue = setScalarValue;\n",
69
+ "'use strict';\n\n/**\n * Stringify a CST document, token, or collection item\n *\n * Fair warning: This applies no validation whatsoever, and\n * simply concatenates the sources in their logical order.\n */\nconst stringify = (cst) => 'type' in cst ? stringifyToken(cst) : stringifyItem(cst);\nfunction stringifyToken(token) {\n switch (token.type) {\n case 'block-scalar': {\n let res = '';\n for (const tok of token.props)\n res += stringifyToken(tok);\n return res + token.source;\n }\n case 'block-map':\n case 'block-seq': {\n let res = '';\n for (const item of token.items)\n res += stringifyItem(item);\n return res;\n }\n case 'flow-collection': {\n let res = token.start.source;\n for (const item of token.items)\n res += stringifyItem(item);\n for (const st of token.end)\n res += st.source;\n return res;\n }\n case 'document': {\n let res = stringifyItem(token);\n if (token.end)\n for (const st of token.end)\n res += st.source;\n return res;\n }\n default: {\n let res = token.source;\n if ('end' in token && token.end)\n for (const st of token.end)\n res += st.source;\n return res;\n }\n }\n}\nfunction stringifyItem({ start, key, sep, value }) {\n let res = '';\n for (const st of start)\n res += st.source;\n if (key)\n res += stringifyToken(key);\n if (sep)\n for (const st of sep)\n res += st.source;\n if (value)\n res += stringifyToken(value);\n return res;\n}\n\nexports.stringify = stringify;\n",
70
+ "'use strict';\n\nconst BREAK = Symbol('break visit');\nconst SKIP = Symbol('skip children');\nconst REMOVE = Symbol('remove item');\n/**\n * Apply a visitor to a CST document or item.\n *\n * Walks through the tree (depth-first) starting from the root, calling a\n * `visitor` function with two arguments when entering each item:\n * - `item`: The current item, which included the following members:\n * - `start: SourceToken[]` – Source tokens before the key or value,\n * possibly including its anchor or tag.\n * - `key?: Token | null` – Set for pair values. May then be `null`, if\n * the key before the `:` separator is empty.\n * - `sep?: SourceToken[]` – Source tokens between the key and the value,\n * which should include the `:` map value indicator if `value` is set.\n * - `value?: Token` – The value of a sequence item, or of a map pair.\n * - `path`: The steps from the root to the current node, as an array of\n * `['key' | 'value', number]` tuples.\n *\n * The return value of the visitor may be used to control the traversal:\n * - `undefined` (default): Do nothing and continue\n * - `visit.SKIP`: Do not visit the children of this token, continue with\n * next sibling\n * - `visit.BREAK`: Terminate traversal completely\n * - `visit.REMOVE`: Remove the current item, then continue with the next one\n * - `number`: Set the index of the next step. This is useful especially if\n * the index of the current token has changed.\n * - `function`: Define the next visitor for this item. After the original\n * visitor is called on item entry, next visitors are called after handling\n * a non-empty `key` and when exiting the item.\n */\nfunction visit(cst, visitor) {\n if ('type' in cst && cst.type === 'document')\n cst = { start: cst.start, value: cst.value };\n _visit(Object.freeze([]), cst, visitor);\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisit.BREAK = BREAK;\n/** Do not visit the children of the current item */\nvisit.SKIP = SKIP;\n/** Remove the current item */\nvisit.REMOVE = REMOVE;\n/** Find the item at `path` from `cst` as the root */\nvisit.itemAtPath = (cst, path) => {\n let item = cst;\n for (const [field, index] of path) {\n const tok = item?.[field];\n if (tok && 'items' in tok) {\n item = tok.items[index];\n }\n else\n return undefined;\n }\n return item;\n};\n/**\n * Get the immediate parent collection of the item at `path` from `cst` as the root.\n *\n * Throws an error if the collection is not found, which should never happen if the item itself exists.\n */\nvisit.parentCollection = (cst, path) => {\n const parent = visit.itemAtPath(cst, path.slice(0, -1));\n const field = path[path.length - 1][0];\n const coll = parent?.[field];\n if (coll && 'items' in coll)\n return coll;\n throw new Error('Parent collection not found');\n};\nfunction _visit(path, item, visitor) {\n let ctrl = visitor(item, path);\n if (typeof ctrl === 'symbol')\n return ctrl;\n for (const field of ['key', 'value']) {\n const token = item[field];\n if (token && 'items' in token) {\n for (let i = 0; i < token.items.length; ++i) {\n const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);\n if (typeof ci === 'number')\n i = ci - 1;\n else if (ci === BREAK)\n return BREAK;\n else if (ci === REMOVE) {\n token.items.splice(i, 1);\n i -= 1;\n }\n }\n if (typeof ctrl === 'function' && field === 'key')\n ctrl = ctrl(item, path);\n }\n }\n return typeof ctrl === 'function' ? ctrl(item, path) : ctrl;\n}\n\nexports.visit = visit;\n",
71
+ "'use strict';\n\nvar cstScalar = require('./cst-scalar.js');\nvar cstStringify = require('./cst-stringify.js');\nvar cstVisit = require('./cst-visit.js');\n\n/** The byte order mark */\nconst BOM = '\\u{FEFF}';\n/** Start of doc-mode */\nconst DOCUMENT = '\\x02'; // C0: Start of Text\n/** Unexpected end of flow-mode */\nconst FLOW_END = '\\x18'; // C0: Cancel\n/** Next token is a scalar value */\nconst SCALAR = '\\x1f'; // C0: Unit Separator\n/** @returns `true` if `token` is a flow or block collection */\nconst isCollection = (token) => !!token && 'items' in token;\n/** @returns `true` if `token` is a flow or block scalar; not an alias */\nconst isScalar = (token) => !!token &&\n (token.type === 'scalar' ||\n token.type === 'single-quoted-scalar' ||\n token.type === 'double-quoted-scalar' ||\n token.type === 'block-scalar');\n/* istanbul ignore next */\n/** Get a printable representation of a lexer token */\nfunction prettyToken(token) {\n switch (token) {\n case BOM:\n return '<BOM>';\n case DOCUMENT:\n return '<DOC>';\n case FLOW_END:\n return '<FLOW_END>';\n case SCALAR:\n return '<SCALAR>';\n default:\n return JSON.stringify(token);\n }\n}\n/** Identify the type of a lexer token. May return `null` for unknown tokens. */\nfunction tokenType(source) {\n switch (source) {\n case BOM:\n return 'byte-order-mark';\n case DOCUMENT:\n return 'doc-mode';\n case FLOW_END:\n return 'flow-error-end';\n case SCALAR:\n return 'scalar';\n case '---':\n return 'doc-start';\n case '...':\n return 'doc-end';\n case '':\n case '\\n':\n case '\\r\\n':\n return 'newline';\n case '-':\n return 'seq-item-ind';\n case '?':\n return 'explicit-key-ind';\n case ':':\n return 'map-value-ind';\n case '{':\n return 'flow-map-start';\n case '}':\n return 'flow-map-end';\n case '[':\n return 'flow-seq-start';\n case ']':\n return 'flow-seq-end';\n case ',':\n return 'comma';\n }\n switch (source[0]) {\n case ' ':\n case '\\t':\n return 'space';\n case '#':\n return 'comment';\n case '%':\n return 'directive-line';\n case '*':\n return 'alias';\n case '&':\n return 'anchor';\n case '!':\n return 'tag';\n case \"'\":\n return 'single-quoted-scalar';\n case '\"':\n return 'double-quoted-scalar';\n case '|':\n case '>':\n return 'block-scalar-header';\n }\n return null;\n}\n\nexports.createScalarToken = cstScalar.createScalarToken;\nexports.resolveAsScalar = cstScalar.resolveAsScalar;\nexports.setScalarValue = cstScalar.setScalarValue;\nexports.stringify = cstStringify.stringify;\nexports.visit = cstVisit.visit;\nexports.BOM = BOM;\nexports.DOCUMENT = DOCUMENT;\nexports.FLOW_END = FLOW_END;\nexports.SCALAR = SCALAR;\nexports.isCollection = isCollection;\nexports.isScalar = isScalar;\nexports.prettyToken = prettyToken;\nexports.tokenType = tokenType;\n",
72
+ "'use strict';\n\nvar cst = require('./cst.js');\n\n/*\nSTART -> stream\n\nstream\n directive -> line-end -> stream\n indent + line-end -> stream\n [else] -> line-start\n\nline-end\n comment -> line-end\n newline -> .\n input-end -> END\n\nline-start\n doc-start -> doc\n doc-end -> stream\n [else] -> indent -> block-start\n\nblock-start\n seq-item-start -> block-start\n explicit-key-start -> block-start\n map-value-start -> block-start\n [else] -> doc\n\ndoc\n line-end -> line-start\n spaces -> doc\n anchor -> doc\n tag -> doc\n flow-start -> flow -> doc\n flow-end -> error -> doc\n seq-item-start -> error -> doc\n explicit-key-start -> error -> doc\n map-value-start -> doc\n alias -> doc\n quote-start -> quoted-scalar -> doc\n block-scalar-header -> line-end -> block-scalar(min) -> line-start\n [else] -> plain-scalar(false, min) -> doc\n\nflow\n line-end -> flow\n spaces -> flow\n anchor -> flow\n tag -> flow\n flow-start -> flow -> flow\n flow-end -> .\n seq-item-start -> error -> flow\n explicit-key-start -> flow\n map-value-start -> flow\n alias -> flow\n quote-start -> quoted-scalar -> flow\n comma -> flow\n [else] -> plain-scalar(true, 0) -> flow\n\nquoted-scalar\n quote-end -> .\n [else] -> quoted-scalar\n\nblock-scalar(min)\n newline + peek(indent < min) -> .\n [else] -> block-scalar(min)\n\nplain-scalar(is-flow, min)\n scalar-end(is-flow) -> .\n peek(newline + (indent < min)) -> .\n [else] -> plain-scalar(min)\n*/\nfunction isEmpty(ch) {\n switch (ch) {\n case undefined:\n case ' ':\n case '\\n':\n case '\\r':\n case '\\t':\n return true;\n default:\n return false;\n }\n}\nconst hexDigits = new Set('0123456789ABCDEFabcdef');\nconst tagChars = new Set(\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()\");\nconst flowIndicatorChars = new Set(',[]{}');\nconst invalidAnchorChars = new Set(' ,[]{}\\n\\r\\t');\nconst isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);\n/**\n * Splits an input string into lexical tokens, i.e. smaller strings that are\n * easily identifiable by `tokens.tokenType()`.\n *\n * Lexing starts always in a \"stream\" context. Incomplete input may be buffered\n * until a complete token can be emitted.\n *\n * In addition to slices of the original input, the following control characters\n * may also be emitted:\n *\n * - `\\x02` (Start of Text): A document starts with the next token\n * - `\\x18` (Cancel): Unexpected end of flow-mode (indicates an error)\n * - `\\x1f` (Unit Separator): Next token is a scalar value\n * - `\\u{FEFF}` (Byte order mark): Emitted separately outside documents\n */\nclass Lexer {\n constructor() {\n /**\n * Flag indicating whether the end of the current buffer marks the end of\n * all input\n */\n this.atEnd = false;\n /**\n * Explicit indent set in block scalar header, as an offset from the current\n * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not\n * explicitly set.\n */\n this.blockScalarIndent = -1;\n /**\n * Block scalars that include a + (keep) chomping indicator in their header\n * include trailing empty lines, which are otherwise excluded from the\n * scalar's contents.\n */\n this.blockScalarKeep = false;\n /** Current input */\n this.buffer = '';\n /**\n * Flag noting whether the map value indicator : can immediately follow this\n * node within a flow context.\n */\n this.flowKey = false;\n /** Count of surrounding flow collection levels. */\n this.flowLevel = 0;\n /**\n * Minimum level of indentation required for next lines to be parsed as a\n * part of the current scalar value.\n */\n this.indentNext = 0;\n /** Indentation level of the current line. */\n this.indentValue = 0;\n /** Position of the next \\n character. */\n this.lineEndPos = null;\n /** Stores the state of the lexer if reaching the end of incpomplete input */\n this.next = null;\n /** A pointer to `buffer`; the current position of the lexer. */\n this.pos = 0;\n }\n /**\n * Generate YAML tokens from the `source` string. If `incomplete`,\n * a part of the last line may be left as a buffer for the next call.\n *\n * @returns A generator of lexical tokens\n */\n *lex(source, incomplete = false) {\n if (source) {\n if (typeof source !== 'string')\n throw TypeError('source is not a string');\n this.buffer = this.buffer ? this.buffer + source : source;\n this.lineEndPos = null;\n }\n this.atEnd = !incomplete;\n let next = this.next ?? 'stream';\n while (next && (incomplete || this.hasChars(1)))\n next = yield* this.parseNext(next);\n }\n atLineEnd() {\n let i = this.pos;\n let ch = this.buffer[i];\n while (ch === ' ' || ch === '\\t')\n ch = this.buffer[++i];\n if (!ch || ch === '#' || ch === '\\n')\n return true;\n if (ch === '\\r')\n return this.buffer[i + 1] === '\\n';\n return false;\n }\n charAt(n) {\n return this.buffer[this.pos + n];\n }\n continueScalar(offset) {\n let ch = this.buffer[offset];\n if (this.indentNext > 0) {\n let indent = 0;\n while (ch === ' ')\n ch = this.buffer[++indent + offset];\n if (ch === '\\r') {\n const next = this.buffer[indent + offset + 1];\n if (next === '\\n' || (!next && !this.atEnd))\n return offset + indent + 1;\n }\n return ch === '\\n' || indent >= this.indentNext || (!ch && !this.atEnd)\n ? offset + indent\n : -1;\n }\n if (ch === '-' || ch === '.') {\n const dt = this.buffer.substr(offset, 3);\n if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3]))\n return -1;\n }\n return offset;\n }\n getLine() {\n let end = this.lineEndPos;\n if (typeof end !== 'number' || (end !== -1 && end < this.pos)) {\n end = this.buffer.indexOf('\\n', this.pos);\n this.lineEndPos = end;\n }\n if (end === -1)\n return this.atEnd ? this.buffer.substring(this.pos) : null;\n if (this.buffer[end - 1] === '\\r')\n end -= 1;\n return this.buffer.substring(this.pos, end);\n }\n hasChars(n) {\n return this.pos + n <= this.buffer.length;\n }\n setNext(state) {\n this.buffer = this.buffer.substring(this.pos);\n this.pos = 0;\n this.lineEndPos = null;\n this.next = state;\n return null;\n }\n peek(n) {\n return this.buffer.substr(this.pos, n);\n }\n *parseNext(next) {\n switch (next) {\n case 'stream':\n return yield* this.parseStream();\n case 'line-start':\n return yield* this.parseLineStart();\n case 'block-start':\n return yield* this.parseBlockStart();\n case 'doc':\n return yield* this.parseDocument();\n case 'flow':\n return yield* this.parseFlowCollection();\n case 'quoted-scalar':\n return yield* this.parseQuotedScalar();\n case 'block-scalar':\n return yield* this.parseBlockScalar();\n case 'plain-scalar':\n return yield* this.parsePlainScalar();\n }\n }\n *parseStream() {\n let line = this.getLine();\n if (line === null)\n return this.setNext('stream');\n if (line[0] === cst.BOM) {\n yield* this.pushCount(1);\n line = line.substring(1);\n }\n if (line[0] === '%') {\n let dirEnd = line.length;\n let cs = line.indexOf('#');\n while (cs !== -1) {\n const ch = line[cs - 1];\n if (ch === ' ' || ch === '\\t') {\n dirEnd = cs - 1;\n break;\n }\n else {\n cs = line.indexOf('#', cs + 1);\n }\n }\n while (true) {\n const ch = line[dirEnd - 1];\n if (ch === ' ' || ch === '\\t')\n dirEnd -= 1;\n else\n break;\n }\n const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));\n yield* this.pushCount(line.length - n); // possible comment\n this.pushNewline();\n return 'stream';\n }\n if (this.atLineEnd()) {\n const sp = yield* this.pushSpaces(true);\n yield* this.pushCount(line.length - sp);\n yield* this.pushNewline();\n return 'stream';\n }\n yield cst.DOCUMENT;\n return yield* this.parseLineStart();\n }\n *parseLineStart() {\n const ch = this.charAt(0);\n if (!ch && !this.atEnd)\n return this.setNext('line-start');\n if (ch === '-' || ch === '.') {\n if (!this.atEnd && !this.hasChars(4))\n return this.setNext('line-start');\n const s = this.peek(3);\n if ((s === '---' || s === '...') && isEmpty(this.charAt(3))) {\n yield* this.pushCount(3);\n this.indentValue = 0;\n this.indentNext = 0;\n return s === '---' ? 'doc' : 'stream';\n }\n }\n this.indentValue = yield* this.pushSpaces(false);\n if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))\n this.indentNext = this.indentValue;\n return yield* this.parseBlockStart();\n }\n *parseBlockStart() {\n const [ch0, ch1] = this.peek(2);\n if (!ch1 && !this.atEnd)\n return this.setNext('block-start');\n if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) {\n const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));\n this.indentNext = this.indentValue + 1;\n this.indentValue += n;\n return yield* this.parseBlockStart();\n }\n return 'doc';\n }\n *parseDocument() {\n yield* this.pushSpaces(true);\n const line = this.getLine();\n if (line === null)\n return this.setNext('doc');\n let n = yield* this.pushIndicators();\n switch (line[n]) {\n case '#':\n yield* this.pushCount(line.length - n);\n // fallthrough\n case undefined:\n yield* this.pushNewline();\n return yield* this.parseLineStart();\n case '{':\n case '[':\n yield* this.pushCount(1);\n this.flowKey = false;\n this.flowLevel = 1;\n return 'flow';\n case '}':\n case ']':\n // this is an error\n yield* this.pushCount(1);\n return 'doc';\n case '*':\n yield* this.pushUntil(isNotAnchorChar);\n return 'doc';\n case '\"':\n case \"'\":\n return yield* this.parseQuotedScalar();\n case '|':\n case '>':\n n += yield* this.parseBlockScalarHeader();\n n += yield* this.pushSpaces(true);\n yield* this.pushCount(line.length - n);\n yield* this.pushNewline();\n return yield* this.parseBlockScalar();\n default:\n return yield* this.parsePlainScalar();\n }\n }\n *parseFlowCollection() {\n let nl, sp;\n let indent = -1;\n do {\n nl = yield* this.pushNewline();\n if (nl > 0) {\n sp = yield* this.pushSpaces(false);\n this.indentValue = indent = sp;\n }\n else {\n sp = 0;\n }\n sp += yield* this.pushSpaces(true);\n } while (nl + sp > 0);\n const line = this.getLine();\n if (line === null)\n return this.setNext('flow');\n if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') ||\n (indent === 0 &&\n (line.startsWith('---') || line.startsWith('...')) &&\n isEmpty(line[3]))) {\n // Allowing for the terminal ] or } at the same (rather than greater)\n // indent level as the initial [ or { is technically invalid, but\n // failing here would be surprising to users.\n const atFlowEndMarker = indent === this.indentNext - 1 &&\n this.flowLevel === 1 &&\n (line[0] === ']' || line[0] === '}');\n if (!atFlowEndMarker) {\n // this is an error\n this.flowLevel = 0;\n yield cst.FLOW_END;\n return yield* this.parseLineStart();\n }\n }\n let n = 0;\n while (line[n] === ',') {\n n += yield* this.pushCount(1);\n n += yield* this.pushSpaces(true);\n this.flowKey = false;\n }\n n += yield* this.pushIndicators();\n switch (line[n]) {\n case undefined:\n return 'flow';\n case '#':\n yield* this.pushCount(line.length - n);\n return 'flow';\n case '{':\n case '[':\n yield* this.pushCount(1);\n this.flowKey = false;\n this.flowLevel += 1;\n return 'flow';\n case '}':\n case ']':\n yield* this.pushCount(1);\n this.flowKey = true;\n this.flowLevel -= 1;\n return this.flowLevel ? 'flow' : 'doc';\n case '*':\n yield* this.pushUntil(isNotAnchorChar);\n return 'flow';\n case '\"':\n case \"'\":\n this.flowKey = true;\n return yield* this.parseQuotedScalar();\n case ':': {\n const next = this.charAt(1);\n if (this.flowKey || isEmpty(next) || next === ',') {\n this.flowKey = false;\n yield* this.pushCount(1);\n yield* this.pushSpaces(true);\n return 'flow';\n }\n }\n // fallthrough\n default:\n this.flowKey = false;\n return yield* this.parsePlainScalar();\n }\n }\n *parseQuotedScalar() {\n const quote = this.charAt(0);\n let end = this.buffer.indexOf(quote, this.pos + 1);\n if (quote === \"'\") {\n while (end !== -1 && this.buffer[end + 1] === \"'\")\n end = this.buffer.indexOf(\"'\", end + 2);\n }\n else {\n // double-quote\n while (end !== -1) {\n let n = 0;\n while (this.buffer[end - 1 - n] === '\\\\')\n n += 1;\n if (n % 2 === 0)\n break;\n end = this.buffer.indexOf('\"', end + 1);\n }\n }\n // Only looking for newlines within the quotes\n const qb = this.buffer.substring(0, end);\n let nl = qb.indexOf('\\n', this.pos);\n if (nl !== -1) {\n while (nl !== -1) {\n const cs = this.continueScalar(nl + 1);\n if (cs === -1)\n break;\n nl = qb.indexOf('\\n', cs);\n }\n if (nl !== -1) {\n // this is an error caused by an unexpected unindent\n end = nl - (qb[nl - 1] === '\\r' ? 2 : 1);\n }\n }\n if (end === -1) {\n if (!this.atEnd)\n return this.setNext('quoted-scalar');\n end = this.buffer.length;\n }\n yield* this.pushToIndex(end + 1, false);\n return this.flowLevel ? 'flow' : 'doc';\n }\n *parseBlockScalarHeader() {\n this.blockScalarIndent = -1;\n this.blockScalarKeep = false;\n let i = this.pos;\n while (true) {\n const ch = this.buffer[++i];\n if (ch === '+')\n this.blockScalarKeep = true;\n else if (ch > '0' && ch <= '9')\n this.blockScalarIndent = Number(ch) - 1;\n else if (ch !== '-')\n break;\n }\n return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#');\n }\n *parseBlockScalar() {\n let nl = this.pos - 1; // may be -1 if this.pos === 0\n let indent = 0;\n let ch;\n loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) {\n switch (ch) {\n case ' ':\n indent += 1;\n break;\n case '\\n':\n nl = i;\n indent = 0;\n break;\n case '\\r': {\n const next = this.buffer[i + 1];\n if (!next && !this.atEnd)\n return this.setNext('block-scalar');\n if (next === '\\n')\n break;\n } // fallthrough\n default:\n break loop;\n }\n }\n if (!ch && !this.atEnd)\n return this.setNext('block-scalar');\n if (indent >= this.indentNext) {\n if (this.blockScalarIndent === -1)\n this.indentNext = indent;\n else {\n this.indentNext =\n this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);\n }\n do {\n const cs = this.continueScalar(nl + 1);\n if (cs === -1)\n break;\n nl = this.buffer.indexOf('\\n', cs);\n } while (nl !== -1);\n if (nl === -1) {\n if (!this.atEnd)\n return this.setNext('block-scalar');\n nl = this.buffer.length;\n }\n }\n // Trailing insufficiently indented tabs are invalid.\n // To catch that during parsing, we include them in the block scalar value.\n let i = nl + 1;\n ch = this.buffer[i];\n while (ch === ' ')\n ch = this.buffer[++i];\n if (ch === '\\t') {\n while (ch === '\\t' || ch === ' ' || ch === '\\r' || ch === '\\n')\n ch = this.buffer[++i];\n nl = i - 1;\n }\n else if (!this.blockScalarKeep) {\n do {\n let i = nl - 1;\n let ch = this.buffer[i];\n if (ch === '\\r')\n ch = this.buffer[--i];\n const lastChar = i; // Drop the line if last char not more indented\n while (ch === ' ')\n ch = this.buffer[--i];\n if (ch === '\\n' && i >= this.pos && i + 1 + indent > lastChar)\n nl = i;\n else\n break;\n } while (true);\n }\n yield cst.SCALAR;\n yield* this.pushToIndex(nl + 1, true);\n return yield* this.parseLineStart();\n }\n *parsePlainScalar() {\n const inFlow = this.flowLevel > 0;\n let end = this.pos - 1;\n let i = this.pos - 1;\n let ch;\n while ((ch = this.buffer[++i])) {\n if (ch === ':') {\n const next = this.buffer[i + 1];\n if (isEmpty(next) || (inFlow && flowIndicatorChars.has(next)))\n break;\n end = i;\n }\n else if (isEmpty(ch)) {\n let next = this.buffer[i + 1];\n if (ch === '\\r') {\n if (next === '\\n') {\n i += 1;\n ch = '\\n';\n next = this.buffer[i + 1];\n }\n else\n end = i;\n }\n if (next === '#' || (inFlow && flowIndicatorChars.has(next)))\n break;\n if (ch === '\\n') {\n const cs = this.continueScalar(i + 1);\n if (cs === -1)\n break;\n i = Math.max(i, cs - 2); // to advance, but still account for ' #'\n }\n }\n else {\n if (inFlow && flowIndicatorChars.has(ch))\n break;\n end = i;\n }\n }\n if (!ch && !this.atEnd)\n return this.setNext('plain-scalar');\n yield cst.SCALAR;\n yield* this.pushToIndex(end + 1, true);\n return inFlow ? 'flow' : 'doc';\n }\n *pushCount(n) {\n if (n > 0) {\n yield this.buffer.substr(this.pos, n);\n this.pos += n;\n return n;\n }\n return 0;\n }\n *pushToIndex(i, allowEmpty) {\n const s = this.buffer.slice(this.pos, i);\n if (s) {\n yield s;\n this.pos += s.length;\n return s.length;\n }\n else if (allowEmpty)\n yield '';\n return 0;\n }\n *pushIndicators() {\n switch (this.charAt(0)) {\n case '!':\n return ((yield* this.pushTag()) +\n (yield* this.pushSpaces(true)) +\n (yield* this.pushIndicators()));\n case '&':\n return ((yield* this.pushUntil(isNotAnchorChar)) +\n (yield* this.pushSpaces(true)) +\n (yield* this.pushIndicators()));\n case '-': // this is an error\n case '?': // this is an error outside flow collections\n case ':': {\n const inFlow = this.flowLevel > 0;\n const ch1 = this.charAt(1);\n if (isEmpty(ch1) || (inFlow && flowIndicatorChars.has(ch1))) {\n if (!inFlow)\n this.indentNext = this.indentValue + 1;\n else if (this.flowKey)\n this.flowKey = false;\n return ((yield* this.pushCount(1)) +\n (yield* this.pushSpaces(true)) +\n (yield* this.pushIndicators()));\n }\n }\n }\n return 0;\n }\n *pushTag() {\n if (this.charAt(1) === '<') {\n let i = this.pos + 2;\n let ch = this.buffer[i];\n while (!isEmpty(ch) && ch !== '>')\n ch = this.buffer[++i];\n return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false);\n }\n else {\n let i = this.pos + 1;\n let ch = this.buffer[i];\n while (ch) {\n if (tagChars.has(ch))\n ch = this.buffer[++i];\n else if (ch === '%' &&\n hexDigits.has(this.buffer[i + 1]) &&\n hexDigits.has(this.buffer[i + 2])) {\n ch = this.buffer[(i += 3)];\n }\n else\n break;\n }\n return yield* this.pushToIndex(i, false);\n }\n }\n *pushNewline() {\n const ch = this.buffer[this.pos];\n if (ch === '\\n')\n return yield* this.pushCount(1);\n else if (ch === '\\r' && this.charAt(1) === '\\n')\n return yield* this.pushCount(2);\n else\n return 0;\n }\n *pushSpaces(allowTabs) {\n let i = this.pos - 1;\n let ch;\n do {\n ch = this.buffer[++i];\n } while (ch === ' ' || (allowTabs && ch === '\\t'));\n const n = i - this.pos;\n if (n > 0) {\n yield this.buffer.substr(this.pos, n);\n this.pos = i;\n }\n return n;\n }\n *pushUntil(test) {\n let i = this.pos;\n let ch = this.buffer[i];\n while (!test(ch))\n ch = this.buffer[++i];\n return yield* this.pushToIndex(i, false);\n }\n}\n\nexports.Lexer = Lexer;\n",
73
+ "'use strict';\n\n/**\n * Tracks newlines during parsing in order to provide an efficient API for\n * determining the one-indexed `{ line, col }` position for any offset\n * within the input.\n */\nclass LineCounter {\n constructor() {\n this.lineStarts = [];\n /**\n * Should be called in ascending order. Otherwise, call\n * `lineCounter.lineStarts.sort()` before calling `linePos()`.\n */\n this.addNewLine = (offset) => this.lineStarts.push(offset);\n /**\n * Performs a binary search and returns the 1-indexed { line, col }\n * position of `offset`. If `line === 0`, `addNewLine` has never been\n * called or `offset` is before the first known newline.\n */\n this.linePos = (offset) => {\n let low = 0;\n let high = this.lineStarts.length;\n while (low < high) {\n const mid = (low + high) >> 1; // Math.floor((low + high) / 2)\n if (this.lineStarts[mid] < offset)\n low = mid + 1;\n else\n high = mid;\n }\n if (this.lineStarts[low] === offset)\n return { line: low + 1, col: 1 };\n if (low === 0)\n return { line: 0, col: offset };\n const start = this.lineStarts[low - 1];\n return { line: low, col: offset - start + 1 };\n };\n }\n}\n\nexports.LineCounter = LineCounter;\n",
74
+ "'use strict';\n\nvar node_process = require('process');\nvar cst = require('./cst.js');\nvar lexer = require('./lexer.js');\n\nfunction includesToken(list, type) {\n for (let i = 0; i < list.length; ++i)\n if (list[i].type === type)\n return true;\n return false;\n}\nfunction findNonEmptyIndex(list) {\n for (let i = 0; i < list.length; ++i) {\n switch (list[i].type) {\n case 'space':\n case 'comment':\n case 'newline':\n break;\n default:\n return i;\n }\n }\n return -1;\n}\nfunction isFlowToken(token) {\n switch (token?.type) {\n case 'alias':\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar':\n case 'flow-collection':\n return true;\n default:\n return false;\n }\n}\nfunction getPrevProps(parent) {\n switch (parent.type) {\n case 'document':\n return parent.start;\n case 'block-map': {\n const it = parent.items[parent.items.length - 1];\n return it.sep ?? it.start;\n }\n case 'block-seq':\n return parent.items[parent.items.length - 1].start;\n /* istanbul ignore next should not happen */\n default:\n return [];\n }\n}\n/** Note: May modify input array */\nfunction getFirstKeyStartProps(prev) {\n if (prev.length === 0)\n return [];\n let i = prev.length;\n loop: while (--i >= 0) {\n switch (prev[i].type) {\n case 'doc-start':\n case 'explicit-key-ind':\n case 'map-value-ind':\n case 'seq-item-ind':\n case 'newline':\n break loop;\n }\n }\n while (prev[++i]?.type === 'space') {\n /* loop */\n }\n return prev.splice(i, prev.length);\n}\nfunction fixFlowSeqItems(fc) {\n if (fc.start.type === 'flow-seq-start') {\n for (const it of fc.items) {\n if (it.sep &&\n !it.value &&\n !includesToken(it.start, 'explicit-key-ind') &&\n !includesToken(it.sep, 'map-value-ind')) {\n if (it.key)\n it.value = it.key;\n delete it.key;\n if (isFlowToken(it.value)) {\n if (it.value.end)\n Array.prototype.push.apply(it.value.end, it.sep);\n else\n it.value.end = it.sep;\n }\n else\n Array.prototype.push.apply(it.start, it.sep);\n delete it.sep;\n }\n }\n }\n}\n/**\n * A YAML concrete syntax tree (CST) parser\n *\n * ```ts\n * const src: string = ...\n * for (const token of new Parser().parse(src)) {\n * // token: Token\n * }\n * ```\n *\n * To use the parser with a user-provided lexer:\n *\n * ```ts\n * function* parse(source: string, lexer: Lexer) {\n * const parser = new Parser()\n * for (const lexeme of lexer.lex(source))\n * yield* parser.next(lexeme)\n * yield* parser.end()\n * }\n *\n * const src: string = ...\n * const lexer = new Lexer()\n * for (const token of parse(src, lexer)) {\n * // token: Token\n * }\n * ```\n */\nclass Parser {\n /**\n * @param onNewLine - If defined, called separately with the start position of\n * each new line (in `parse()`, including the start of input).\n */\n constructor(onNewLine) {\n /** If true, space and sequence indicators count as indentation */\n this.atNewLine = true;\n /** If true, next token is a scalar value */\n this.atScalar = false;\n /** Current indentation level */\n this.indent = 0;\n /** Current offset since the start of parsing */\n this.offset = 0;\n /** On the same line with a block map key */\n this.onKeyLine = false;\n /** Top indicates the node that's currently being built */\n this.stack = [];\n /** The source of the current token, set in parse() */\n this.source = '';\n /** The type of the current token, set in parse() */\n this.type = '';\n // Must be defined after `next()`\n this.lexer = new lexer.Lexer();\n this.onNewLine = onNewLine;\n }\n /**\n * Parse `source` as a YAML stream.\n * If `incomplete`, a part of the last line may be left as a buffer for the next call.\n *\n * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.\n *\n * @returns A generator of tokens representing each directive, document, and other structure.\n */\n *parse(source, incomplete = false) {\n if (this.onNewLine && this.offset === 0)\n this.onNewLine(0);\n for (const lexeme of this.lexer.lex(source, incomplete))\n yield* this.next(lexeme);\n if (!incomplete)\n yield* this.end();\n }\n /**\n * Advance the parser by the `source` of one lexical token.\n */\n *next(source) {\n this.source = source;\n if (node_process.env.LOG_TOKENS)\n console.log('|', cst.prettyToken(source));\n if (this.atScalar) {\n this.atScalar = false;\n yield* this.step();\n this.offset += source.length;\n return;\n }\n const type = cst.tokenType(source);\n if (!type) {\n const message = `Not a YAML token: ${source}`;\n yield* this.pop({ type: 'error', offset: this.offset, message, source });\n this.offset += source.length;\n }\n else if (type === 'scalar') {\n this.atNewLine = false;\n this.atScalar = true;\n this.type = 'scalar';\n }\n else {\n this.type = type;\n yield* this.step();\n switch (type) {\n case 'newline':\n this.atNewLine = true;\n this.indent = 0;\n if (this.onNewLine)\n this.onNewLine(this.offset + source.length);\n break;\n case 'space':\n if (this.atNewLine && source[0] === ' ')\n this.indent += source.length;\n break;\n case 'explicit-key-ind':\n case 'map-value-ind':\n case 'seq-item-ind':\n if (this.atNewLine)\n this.indent += source.length;\n break;\n case 'doc-mode':\n case 'flow-error-end':\n return;\n default:\n this.atNewLine = false;\n }\n this.offset += source.length;\n }\n }\n /** Call at end of input to push out any remaining constructions */\n *end() {\n while (this.stack.length > 0)\n yield* this.pop();\n }\n get sourceToken() {\n const st = {\n type: this.type,\n offset: this.offset,\n indent: this.indent,\n source: this.source\n };\n return st;\n }\n *step() {\n const top = this.peek(1);\n if (this.type === 'doc-end' && top?.type !== 'doc-end') {\n while (this.stack.length > 0)\n yield* this.pop();\n this.stack.push({\n type: 'doc-end',\n offset: this.offset,\n source: this.source\n });\n return;\n }\n if (!top)\n return yield* this.stream();\n switch (top.type) {\n case 'document':\n return yield* this.document(top);\n case 'alias':\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar':\n return yield* this.scalar(top);\n case 'block-scalar':\n return yield* this.blockScalar(top);\n case 'block-map':\n return yield* this.blockMap(top);\n case 'block-seq':\n return yield* this.blockSequence(top);\n case 'flow-collection':\n return yield* this.flowCollection(top);\n case 'doc-end':\n return yield* this.documentEnd(top);\n }\n /* istanbul ignore next should not happen */\n yield* this.pop();\n }\n peek(n) {\n return this.stack[this.stack.length - n];\n }\n *pop(error) {\n const token = error ?? this.stack.pop();\n /* istanbul ignore if should not happen */\n if (!token) {\n const message = 'Tried to pop an empty stack';\n yield { type: 'error', offset: this.offset, source: '', message };\n }\n else if (this.stack.length === 0) {\n yield token;\n }\n else {\n const top = this.peek(1);\n if (token.type === 'block-scalar') {\n // Block scalars use their parent rather than header indent\n token.indent = 'indent' in top ? top.indent : 0;\n }\n else if (token.type === 'flow-collection' && top.type === 'document') {\n // Ignore all indent for top-level flow collections\n token.indent = 0;\n }\n if (token.type === 'flow-collection')\n fixFlowSeqItems(token);\n switch (top.type) {\n case 'document':\n top.value = token;\n break;\n case 'block-scalar':\n top.props.push(token); // error\n break;\n case 'block-map': {\n const it = top.items[top.items.length - 1];\n if (it.value) {\n top.items.push({ start: [], key: token, sep: [] });\n this.onKeyLine = true;\n return;\n }\n else if (it.sep) {\n it.value = token;\n }\n else {\n Object.assign(it, { key: token, sep: [] });\n this.onKeyLine = !it.explicitKey;\n return;\n }\n break;\n }\n case 'block-seq': {\n const it = top.items[top.items.length - 1];\n if (it.value)\n top.items.push({ start: [], value: token });\n else\n it.value = token;\n break;\n }\n case 'flow-collection': {\n const it = top.items[top.items.length - 1];\n if (!it || it.value)\n top.items.push({ start: [], key: token, sep: [] });\n else if (it.sep)\n it.value = token;\n else\n Object.assign(it, { key: token, sep: [] });\n return;\n }\n /* istanbul ignore next should not happen */\n default:\n yield* this.pop();\n yield* this.pop(token);\n }\n if ((top.type === 'document' ||\n top.type === 'block-map' ||\n top.type === 'block-seq') &&\n (token.type === 'block-map' || token.type === 'block-seq')) {\n const last = token.items[token.items.length - 1];\n if (last &&\n !last.sep &&\n !last.value &&\n last.start.length > 0 &&\n findNonEmptyIndex(last.start) === -1 &&\n (token.indent === 0 ||\n last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) {\n if (top.type === 'document')\n top.end = last.start;\n else\n top.items.push({ start: last.start });\n token.items.splice(-1, 1);\n }\n }\n }\n }\n *stream() {\n switch (this.type) {\n case 'directive-line':\n yield { type: 'directive', offset: this.offset, source: this.source };\n return;\n case 'byte-order-mark':\n case 'space':\n case 'comment':\n case 'newline':\n yield this.sourceToken;\n return;\n case 'doc-mode':\n case 'doc-start': {\n const doc = {\n type: 'document',\n offset: this.offset,\n start: []\n };\n if (this.type === 'doc-start')\n doc.start.push(this.sourceToken);\n this.stack.push(doc);\n return;\n }\n }\n yield {\n type: 'error',\n offset: this.offset,\n message: `Unexpected ${this.type} token in YAML stream`,\n source: this.source\n };\n }\n *document(doc) {\n if (doc.value)\n return yield* this.lineEnd(doc);\n switch (this.type) {\n case 'doc-start': {\n if (findNonEmptyIndex(doc.start) !== -1) {\n yield* this.pop();\n yield* this.step();\n }\n else\n doc.start.push(this.sourceToken);\n return;\n }\n case 'anchor':\n case 'tag':\n case 'space':\n case 'comment':\n case 'newline':\n doc.start.push(this.sourceToken);\n return;\n }\n const bv = this.startBlockValue(doc);\n if (bv)\n this.stack.push(bv);\n else {\n yield {\n type: 'error',\n offset: this.offset,\n message: `Unexpected ${this.type} token in YAML document`,\n source: this.source\n };\n }\n }\n *scalar(scalar) {\n if (this.type === 'map-value-ind') {\n const prev = getPrevProps(this.peek(2));\n const start = getFirstKeyStartProps(prev);\n let sep;\n if (scalar.end) {\n sep = scalar.end;\n sep.push(this.sourceToken);\n delete scalar.end;\n }\n else\n sep = [this.sourceToken];\n const map = {\n type: 'block-map',\n offset: scalar.offset,\n indent: scalar.indent,\n items: [{ start, key: scalar, sep }]\n };\n this.onKeyLine = true;\n this.stack[this.stack.length - 1] = map;\n }\n else\n yield* this.lineEnd(scalar);\n }\n *blockScalar(scalar) {\n switch (this.type) {\n case 'space':\n case 'comment':\n case 'newline':\n scalar.props.push(this.sourceToken);\n return;\n case 'scalar':\n scalar.source = this.source;\n // block-scalar source includes trailing newline\n this.atNewLine = true;\n this.indent = 0;\n if (this.onNewLine) {\n let nl = this.source.indexOf('\\n') + 1;\n while (nl !== 0) {\n this.onNewLine(this.offset + nl);\n nl = this.source.indexOf('\\n', nl) + 1;\n }\n }\n yield* this.pop();\n break;\n /* istanbul ignore next should not happen */\n default:\n yield* this.pop();\n yield* this.step();\n }\n }\n *blockMap(map) {\n const it = map.items[map.items.length - 1];\n // it.sep is true-ish if pair already has key or : separator\n switch (this.type) {\n case 'newline':\n this.onKeyLine = false;\n if (it.value) {\n const end = 'end' in it.value ? it.value.end : undefined;\n const last = Array.isArray(end) ? end[end.length - 1] : undefined;\n if (last?.type === 'comment')\n end?.push(this.sourceToken);\n else\n map.items.push({ start: [this.sourceToken] });\n }\n else if (it.sep) {\n it.sep.push(this.sourceToken);\n }\n else {\n it.start.push(this.sourceToken);\n }\n return;\n case 'space':\n case 'comment':\n if (it.value) {\n map.items.push({ start: [this.sourceToken] });\n }\n else if (it.sep) {\n it.sep.push(this.sourceToken);\n }\n else {\n if (this.atIndentedComment(it.start, map.indent)) {\n const prev = map.items[map.items.length - 2];\n const end = prev?.value?.end;\n if (Array.isArray(end)) {\n Array.prototype.push.apply(end, it.start);\n end.push(this.sourceToken);\n map.items.pop();\n return;\n }\n }\n it.start.push(this.sourceToken);\n }\n return;\n }\n if (this.indent >= map.indent) {\n const atMapIndent = !this.onKeyLine && this.indent === map.indent;\n const atNextItem = atMapIndent &&\n (it.sep || it.explicitKey) &&\n this.type !== 'seq-item-ind';\n // For empty nodes, assign newline-separated not indented empty tokens to following node\n let start = [];\n if (atNextItem && it.sep && !it.value) {\n const nl = [];\n for (let i = 0; i < it.sep.length; ++i) {\n const st = it.sep[i];\n switch (st.type) {\n case 'newline':\n nl.push(i);\n break;\n case 'space':\n break;\n case 'comment':\n if (st.indent > map.indent)\n nl.length = 0;\n break;\n default:\n nl.length = 0;\n }\n }\n if (nl.length >= 2)\n start = it.sep.splice(nl[1]);\n }\n switch (this.type) {\n case 'anchor':\n case 'tag':\n if (atNextItem || it.value) {\n start.push(this.sourceToken);\n map.items.push({ start });\n this.onKeyLine = true;\n }\n else if (it.sep) {\n it.sep.push(this.sourceToken);\n }\n else {\n it.start.push(this.sourceToken);\n }\n return;\n case 'explicit-key-ind':\n if (!it.sep && !it.explicitKey) {\n it.start.push(this.sourceToken);\n it.explicitKey = true;\n }\n else if (atNextItem || it.value) {\n start.push(this.sourceToken);\n map.items.push({ start, explicitKey: true });\n }\n else {\n this.stack.push({\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start: [this.sourceToken], explicitKey: true }]\n });\n }\n this.onKeyLine = true;\n return;\n case 'map-value-ind':\n if (it.explicitKey) {\n if (!it.sep) {\n if (includesToken(it.start, 'newline')) {\n Object.assign(it, { key: null, sep: [this.sourceToken] });\n }\n else {\n const start = getFirstKeyStartProps(it.start);\n this.stack.push({\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start, key: null, sep: [this.sourceToken] }]\n });\n }\n }\n else if (it.value) {\n map.items.push({ start: [], key: null, sep: [this.sourceToken] });\n }\n else if (includesToken(it.sep, 'map-value-ind')) {\n this.stack.push({\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start, key: null, sep: [this.sourceToken] }]\n });\n }\n else if (isFlowToken(it.key) &&\n !includesToken(it.sep, 'newline')) {\n const start = getFirstKeyStartProps(it.start);\n const key = it.key;\n const sep = it.sep;\n sep.push(this.sourceToken);\n // @ts-expect-error type guard is wrong here\n delete it.key;\n // @ts-expect-error type guard is wrong here\n delete it.sep;\n this.stack.push({\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start, key, sep }]\n });\n }\n else if (start.length > 0) {\n // Not actually at next item\n it.sep = it.sep.concat(start, this.sourceToken);\n }\n else {\n it.sep.push(this.sourceToken);\n }\n }\n else {\n if (!it.sep) {\n Object.assign(it, { key: null, sep: [this.sourceToken] });\n }\n else if (it.value || atNextItem) {\n map.items.push({ start, key: null, sep: [this.sourceToken] });\n }\n else if (includesToken(it.sep, 'map-value-ind')) {\n this.stack.push({\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start: [], key: null, sep: [this.sourceToken] }]\n });\n }\n else {\n it.sep.push(this.sourceToken);\n }\n }\n this.onKeyLine = true;\n return;\n case 'alias':\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar': {\n const fs = this.flowScalar(this.type);\n if (atNextItem || it.value) {\n map.items.push({ start, key: fs, sep: [] });\n this.onKeyLine = true;\n }\n else if (it.sep) {\n this.stack.push(fs);\n }\n else {\n Object.assign(it, { key: fs, sep: [] });\n this.onKeyLine = true;\n }\n return;\n }\n default: {\n const bv = this.startBlockValue(map);\n if (bv) {\n if (bv.type === 'block-seq') {\n if (!it.explicitKey &&\n it.sep &&\n !includesToken(it.sep, 'newline')) {\n yield* this.pop({\n type: 'error',\n offset: this.offset,\n message: 'Unexpected block-seq-ind on same line with key',\n source: this.source\n });\n return;\n }\n }\n else if (atMapIndent) {\n map.items.push({ start });\n }\n this.stack.push(bv);\n return;\n }\n }\n }\n }\n yield* this.pop();\n yield* this.step();\n }\n *blockSequence(seq) {\n const it = seq.items[seq.items.length - 1];\n switch (this.type) {\n case 'newline':\n if (it.value) {\n const end = 'end' in it.value ? it.value.end : undefined;\n const last = Array.isArray(end) ? end[end.length - 1] : undefined;\n if (last?.type === 'comment')\n end?.push(this.sourceToken);\n else\n seq.items.push({ start: [this.sourceToken] });\n }\n else\n it.start.push(this.sourceToken);\n return;\n case 'space':\n case 'comment':\n if (it.value)\n seq.items.push({ start: [this.sourceToken] });\n else {\n if (this.atIndentedComment(it.start, seq.indent)) {\n const prev = seq.items[seq.items.length - 2];\n const end = prev?.value?.end;\n if (Array.isArray(end)) {\n Array.prototype.push.apply(end, it.start);\n end.push(this.sourceToken);\n seq.items.pop();\n return;\n }\n }\n it.start.push(this.sourceToken);\n }\n return;\n case 'anchor':\n case 'tag':\n if (it.value || this.indent <= seq.indent)\n break;\n it.start.push(this.sourceToken);\n return;\n case 'seq-item-ind':\n if (this.indent !== seq.indent)\n break;\n if (it.value || includesToken(it.start, 'seq-item-ind'))\n seq.items.push({ start: [this.sourceToken] });\n else\n it.start.push(this.sourceToken);\n return;\n }\n if (this.indent > seq.indent) {\n const bv = this.startBlockValue(seq);\n if (bv) {\n this.stack.push(bv);\n return;\n }\n }\n yield* this.pop();\n yield* this.step();\n }\n *flowCollection(fc) {\n const it = fc.items[fc.items.length - 1];\n if (this.type === 'flow-error-end') {\n let top;\n do {\n yield* this.pop();\n top = this.peek(1);\n } while (top?.type === 'flow-collection');\n }\n else if (fc.end.length === 0) {\n switch (this.type) {\n case 'comma':\n case 'explicit-key-ind':\n if (!it || it.sep)\n fc.items.push({ start: [this.sourceToken] });\n else\n it.start.push(this.sourceToken);\n return;\n case 'map-value-ind':\n if (!it || it.value)\n fc.items.push({ start: [], key: null, sep: [this.sourceToken] });\n else if (it.sep)\n it.sep.push(this.sourceToken);\n else\n Object.assign(it, { key: null, sep: [this.sourceToken] });\n return;\n case 'space':\n case 'comment':\n case 'newline':\n case 'anchor':\n case 'tag':\n if (!it || it.value)\n fc.items.push({ start: [this.sourceToken] });\n else if (it.sep)\n it.sep.push(this.sourceToken);\n else\n it.start.push(this.sourceToken);\n return;\n case 'alias':\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar': {\n const fs = this.flowScalar(this.type);\n if (!it || it.value)\n fc.items.push({ start: [], key: fs, sep: [] });\n else if (it.sep)\n this.stack.push(fs);\n else\n Object.assign(it, { key: fs, sep: [] });\n return;\n }\n case 'flow-map-end':\n case 'flow-seq-end':\n fc.end.push(this.sourceToken);\n return;\n }\n const bv = this.startBlockValue(fc);\n /* istanbul ignore else should not happen */\n if (bv)\n this.stack.push(bv);\n else {\n yield* this.pop();\n yield* this.step();\n }\n }\n else {\n const parent = this.peek(2);\n if (parent.type === 'block-map' &&\n ((this.type === 'map-value-ind' && parent.indent === fc.indent) ||\n (this.type === 'newline' &&\n !parent.items[parent.items.length - 1].sep))) {\n yield* this.pop();\n yield* this.step();\n }\n else if (this.type === 'map-value-ind' &&\n parent.type !== 'flow-collection') {\n const prev = getPrevProps(parent);\n const start = getFirstKeyStartProps(prev);\n fixFlowSeqItems(fc);\n const sep = fc.end.splice(1, fc.end.length);\n sep.push(this.sourceToken);\n const map = {\n type: 'block-map',\n offset: fc.offset,\n indent: fc.indent,\n items: [{ start, key: fc, sep }]\n };\n this.onKeyLine = true;\n this.stack[this.stack.length - 1] = map;\n }\n else {\n yield* this.lineEnd(fc);\n }\n }\n }\n flowScalar(type) {\n if (this.onNewLine) {\n let nl = this.source.indexOf('\\n') + 1;\n while (nl !== 0) {\n this.onNewLine(this.offset + nl);\n nl = this.source.indexOf('\\n', nl) + 1;\n }\n }\n return {\n type,\n offset: this.offset,\n indent: this.indent,\n source: this.source\n };\n }\n startBlockValue(parent) {\n switch (this.type) {\n case 'alias':\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar':\n return this.flowScalar(this.type);\n case 'block-scalar-header':\n return {\n type: 'block-scalar',\n offset: this.offset,\n indent: this.indent,\n props: [this.sourceToken],\n source: ''\n };\n case 'flow-map-start':\n case 'flow-seq-start':\n return {\n type: 'flow-collection',\n offset: this.offset,\n indent: this.indent,\n start: this.sourceToken,\n items: [],\n end: []\n };\n case 'seq-item-ind':\n return {\n type: 'block-seq',\n offset: this.offset,\n indent: this.indent,\n items: [{ start: [this.sourceToken] }]\n };\n case 'explicit-key-ind': {\n this.onKeyLine = true;\n const prev = getPrevProps(parent);\n const start = getFirstKeyStartProps(prev);\n start.push(this.sourceToken);\n return {\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start, explicitKey: true }]\n };\n }\n case 'map-value-ind': {\n this.onKeyLine = true;\n const prev = getPrevProps(parent);\n const start = getFirstKeyStartProps(prev);\n return {\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start, key: null, sep: [this.sourceToken] }]\n };\n }\n }\n return null;\n }\n atIndentedComment(start, indent) {\n if (this.type !== 'comment')\n return false;\n if (this.indent <= indent)\n return false;\n return start.every(st => st.type === 'newline' || st.type === 'space');\n }\n *documentEnd(docEnd) {\n if (this.type !== 'doc-mode') {\n if (docEnd.end)\n docEnd.end.push(this.sourceToken);\n else\n docEnd.end = [this.sourceToken];\n if (this.type === 'newline')\n yield* this.pop();\n }\n }\n *lineEnd(token) {\n switch (this.type) {\n case 'comma':\n case 'doc-start':\n case 'doc-end':\n case 'flow-seq-end':\n case 'flow-map-end':\n case 'map-value-ind':\n yield* this.pop();\n yield* this.step();\n break;\n case 'newline':\n this.onKeyLine = false;\n // fallthrough\n case 'space':\n case 'comment':\n default:\n // all other values are errors\n if (token.end)\n token.end.push(this.sourceToken);\n else\n token.end = [this.sourceToken];\n if (this.type === 'newline')\n yield* this.pop();\n }\n }\n}\n\nexports.Parser = Parser;\n",
75
+ "'use strict';\n\nvar composer = require('./compose/composer.js');\nvar Document = require('./doc/Document.js');\nvar errors = require('./errors.js');\nvar log = require('./log.js');\nvar identity = require('./nodes/identity.js');\nvar lineCounter = require('./parse/line-counter.js');\nvar parser = require('./parse/parser.js');\n\nfunction parseOptions(options) {\n const prettyErrors = options.prettyErrors !== false;\n const lineCounter$1 = options.lineCounter || (prettyErrors && new lineCounter.LineCounter()) || null;\n return { lineCounter: lineCounter$1, prettyErrors };\n}\n/**\n * Parse the input as a stream of YAML documents.\n *\n * Documents should be separated from each other by `...` or `---` marker lines.\n *\n * @returns If an empty `docs` array is returned, it will be of type\n * EmptyStream and contain additional stream information. In\n * TypeScript, you should use `'empty' in docs` as a type guard for it.\n */\nfunction parseAllDocuments(source, options = {}) {\n const { lineCounter, prettyErrors } = parseOptions(options);\n const parser$1 = new parser.Parser(lineCounter?.addNewLine);\n const composer$1 = new composer.Composer(options);\n const docs = Array.from(composer$1.compose(parser$1.parse(source)));\n if (prettyErrors && lineCounter)\n for (const doc of docs) {\n doc.errors.forEach(errors.prettifyError(source, lineCounter));\n doc.warnings.forEach(errors.prettifyError(source, lineCounter));\n }\n if (docs.length > 0)\n return docs;\n return Object.assign([], { empty: true }, composer$1.streamInfo());\n}\n/** Parse an input string into a single YAML.Document */\nfunction parseDocument(source, options = {}) {\n const { lineCounter, prettyErrors } = parseOptions(options);\n const parser$1 = new parser.Parser(lineCounter?.addNewLine);\n const composer$1 = new composer.Composer(options);\n // `doc` is always set by compose.end(true) at the very latest\n let doc = null;\n for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) {\n if (!doc)\n doc = _doc;\n else if (doc.options.logLevel !== 'silent') {\n doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()'));\n break;\n }\n }\n if (prettyErrors && lineCounter) {\n doc.errors.forEach(errors.prettifyError(source, lineCounter));\n doc.warnings.forEach(errors.prettifyError(source, lineCounter));\n }\n return doc;\n}\nfunction parse(src, reviver, options) {\n let _reviver = undefined;\n if (typeof reviver === 'function') {\n _reviver = reviver;\n }\n else if (options === undefined && reviver && typeof reviver === 'object') {\n options = reviver;\n }\n const doc = parseDocument(src, options);\n if (!doc)\n return null;\n doc.warnings.forEach(warning => log.warn(doc.options.logLevel, warning));\n if (doc.errors.length > 0) {\n if (doc.options.logLevel !== 'silent')\n throw doc.errors[0];\n else\n doc.errors = [];\n }\n return doc.toJS(Object.assign({ reviver: _reviver }, options));\n}\nfunction stringify(value, replacer, options) {\n let _replacer = null;\n if (typeof replacer === 'function' || Array.isArray(replacer)) {\n _replacer = replacer;\n }\n else if (options === undefined && replacer) {\n options = replacer;\n }\n if (typeof options === 'string')\n options = options.length;\n if (typeof options === 'number') {\n const indent = Math.round(options);\n options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };\n }\n if (value === undefined) {\n const { keepUndefined } = options ?? replacer ?? {};\n if (!keepUndefined)\n return undefined;\n }\n if (identity.isDocument(value) && !_replacer)\n return value.toString(options);\n return new Document.Document(value, _replacer, options).toString(options);\n}\n\nexports.parse = parse;\nexports.parseAllDocuments = parseAllDocuments;\nexports.parseDocument = parseDocument;\nexports.stringify = stringify;\n",
76
+ "'use strict';\n\nvar composer = require('./compose/composer.js');\nvar Document = require('./doc/Document.js');\nvar Schema = require('./schema/Schema.js');\nvar errors = require('./errors.js');\nvar Alias = require('./nodes/Alias.js');\nvar identity = require('./nodes/identity.js');\nvar Pair = require('./nodes/Pair.js');\nvar Scalar = require('./nodes/Scalar.js');\nvar YAMLMap = require('./nodes/YAMLMap.js');\nvar YAMLSeq = require('./nodes/YAMLSeq.js');\nvar cst = require('./parse/cst.js');\nvar lexer = require('./parse/lexer.js');\nvar lineCounter = require('./parse/line-counter.js');\nvar parser = require('./parse/parser.js');\nvar publicApi = require('./public-api.js');\nvar visit = require('./visit.js');\n\n\n\nexports.Composer = composer.Composer;\nexports.Document = Document.Document;\nexports.Schema = Schema.Schema;\nexports.YAMLError = errors.YAMLError;\nexports.YAMLParseError = errors.YAMLParseError;\nexports.YAMLWarning = errors.YAMLWarning;\nexports.Alias = Alias.Alias;\nexports.isAlias = identity.isAlias;\nexports.isCollection = identity.isCollection;\nexports.isDocument = identity.isDocument;\nexports.isMap = identity.isMap;\nexports.isNode = identity.isNode;\nexports.isPair = identity.isPair;\nexports.isScalar = identity.isScalar;\nexports.isSeq = identity.isSeq;\nexports.Pair = Pair.Pair;\nexports.Scalar = Scalar.Scalar;\nexports.YAMLMap = YAMLMap.YAMLMap;\nexports.YAMLSeq = YAMLSeq.YAMLSeq;\nexports.CST = cst;\nexports.Lexer = lexer.Lexer;\nexports.LineCounter = lineCounter.LineCounter;\nexports.Parser = parser.Parser;\nexports.parse = publicApi.parse;\nexports.parseAllDocuments = publicApi.parseAllDocuments;\nexports.parseDocument = publicApi.parseDocument;\nexports.stringify = publicApi.stringify;\nexports.visit = visit.visit;\nexports.visitAsync = visit.visitAsync;\n",
77
+ "// -----------------------------------------------------------------------------\n// MOTOR DE EXPRESIONES MATEMÁTICAS Y VARIABLES\n// -----------------------------------------------------------------------------\n\nimport type { TriggerContext } from \"../types\";\n\nexport class ExpressionEngine {\n /**\n * Evalúa una expresión matemática simple o una interpolación de variables\n * Soporta operadores: +, -, *, /, %, **, y funciones matemáticas básicas\n */\n\n static evaluate(expression: string, context: TriggerContext): any {\n try {\n // Check for template string interpolation first\n if (expression.includes(\"${\")) {\n const interpolated = this.interpolate(expression, context);\n // If the result is a number-like string, convert it\n if (!isNaN(Number(interpolated)) && interpolated.trim() !== \"\") {\n return Number(interpolated);\n }\n return interpolated;\n }\n\n // Use the flexible JS evaluator by default to support globals and function calls\n return this.evaluateExpression(expression, context);\n } catch (error) {\n console.error(`Error evaluating expression: ${expression}`, error);\n return null;\n }\n }\n\n /**\n * Realiza interpolación de variables en una plantilla de texto\n * Ejemplo: \"Hola ${data.username}, hoy es ${new Date().toLocaleDateString()}\"\n */\n static interpolate(template: string, context: TriggerContext): string {\n return template.replace(/\\$\\{([^}]+)\\}/g, (match, expression) => {\n try {\n const result = this.evaluateExpression(expression, context);\n if (result === undefined || result === null) {\n return \"undefined\"; // Explicitly return string \"undefined\" or \"\"?\n // User request: \"cases without o incorrect data ${data.username} if data is null\"\n // Usually keeping it as \"undefined\" is honest but ugly.\n // Let's use a standard \"N/A\" or empty string? \n // Or better: check if the user wants default values e.g. ${name || 'Guest'}\n // evaluateExpression might handle || operator if it falls back to JS evaluation.\n return \"undefined\"; \n }\n return String(result);\n } catch (error) {\n console.error(`Error en interpolación: ${match}`, error);\n return match; // Devuelve la expresión original si hay error\n }\n });\n }\n /**\n * Evalúa una expresión matemática segura usando Function constructor\n */\n private static evaluateMathExpression(expression: string): any {\n try {\n // Crear una función segura que solo permita operaciones matemáticas básicas\n const mathFunction = new Function(\"Math\", `return ${expression}`);\n return mathFunction(Math);\n } catch (error) {\n throw new Error(`Error evaluando expresión matemática: ${expression}`);\n }\n }\n\n /**\n * Evalúa una expresión individual en el contexto\n */\n private static evaluateExpression(\n expression: string,\n context: TriggerContext,\n ): any {\n // Intentar obtener un valor del contexto SI es una ruta simple (sin espacios, operadores, etc.)\n // Regex: Start with reserved root, followed by dots and words. No spaces.\n if (/^(data|globals|request|computed)(\\.[a-zA-Z0-9_]+)+$/.test(expression)) {\n const val = this.getNestedValue(expression, context);\n // If found, return. If undefined, we might accept it as undefined, \n // OR if technically it shouldn't be undefined, we might fail? \n // But for robustness, let's return it.\n return val;\n }\n\n // Intentar evaluar como expresión de JavaScript\n try {\n return new Function(\n \"context\",\n \"with(context) { return \" + expression + \" }\",\n )(context);\n } catch (error) {\n console.error(`ERROR evaluating expression '${expression}':`, error);\n // Si falla, devolver la expresión original\n return expression;\n }\n }\n\n /**\n * Obtiene un valor anidado de un objeto usando notación de puntos\n * Ejemplo: getNestedValue(\"data.user.profile.name\", context)\n */\n static getNestedValue(path: string, context: TriggerContext): any {\n const parts = path.split(\".\");\n let current: any = context;\n\n for (const part of parts) {\n if (current === null || current === undefined || !(part in current)) {\n return undefined;\n }\n current = current[part];\n }\n\n return current;\n }\n\n /**\n * Ejecuta una expresión matemática específica (como \"1 + 2\")\n */\n static evaluateMath(expression: string, context: TriggerContext): number {\n // Extraer variables de la expresión\n let processedExpression = expression;\n\n // Reemplazar variables de contexto en la expresión\n processedExpression = processedExpression.replace(\n /\\b[a-zA-Z_][a-zA-Z0-9_]*\\b/g,\n (match) => {\n // Verificar si es una palabra reservada de JavaScript o función Math\n if (\n [\n \"Math\",\n \"random\",\n \"floor\",\n \"ceil\",\n \"round\",\n \"sqrt\",\n \"abs\",\n \"pow\",\n \"min\",\n \"max\",\n \"sin\",\n \"cos\",\n \"tan\",\n ].includes(match)\n ) {\n return match;\n }\n\n // Intentar obtener valor del contexto\n const value = this.getNestedValue(match, context);\n if (value !== undefined) {\n return typeof value === \"string\" ? `\"${value}\"` : String(value);\n }\n\n return match;\n },\n );\n\n try {\n // Evaluar la expresión matemática\n return this.evaluateMathExpression(processedExpression);\n } catch (error) {\n console.error(`Error en evaluación matemática: ${expression}`, error);\n return NaN;\n }\n }\n}\n",
78
+ "\r\nimport type { TriggerContext } from \"../types\";\r\nimport { RuleEngine } from \"./rule-engine\";\r\n\r\nexport interface EventQueueConfig {\r\n maxBatchSize: number;\r\n flushIntervalMs: number;\r\n}\r\n\r\nexport class EventQueue {\r\n private queue: TriggerContext[] = [];\r\n private engine: RuleEngine;\r\n private config: EventQueueConfig;\r\n private timer: Timer | null = null;\r\n private isProcessing = false;\r\n\r\n constructor(engine: RuleEngine, config: EventQueueConfig = { maxBatchSize: 10, flushIntervalMs: 100 }) {\r\n this.engine = engine;\r\n this.config = config;\r\n }\r\n\r\n /**\r\n * Enqueue a new event context.\r\n * Automatically triggers processing if batch size reached.\r\n */\r\n push(context: TriggerContext) {\r\n this.queue.push(context);\r\n \r\n if (this.queue.length >= this.config.maxBatchSize) {\r\n this.processQueue();\r\n } else if (!this.timer) {\r\n this.timer = setTimeout(() => this.processQueue(), this.config.flushIntervalMs);\r\n }\r\n }\r\n\r\n /**\r\n * Process all buffered events.\r\n */\r\n async processQueue() {\r\n if (this.isProcessing) return;\r\n this.isProcessing = true;\r\n\r\n if (this.timer) {\r\n clearTimeout(this.timer);\r\n this.timer = null;\r\n }\r\n\r\n const batch = this.queue.splice(0, this.config.maxBatchSize);\r\n if (batch.length === 0) {\r\n this.isProcessing = false;\r\n return;\r\n }\r\n\r\n console.debug(`[EventQueue] Processing batch of ${batch.length} events.`);\r\n\r\n // Process sequentially to maintain state consistency\r\n // (Or parallel if state not involved, but for \"Stateful Triggers\" sequential is safer)\r\n for (const context of batch) {\r\n try {\r\n await this.engine.evaluateContext(context);\r\n } catch (error) {\r\n console.error(`[EventQueue] Error processing event ${context.event}:`, error);\r\n }\r\n }\r\n\r\n // If more items remain, schedule immediate next tick\r\n if (this.queue.length > 0) {\r\n setTimeout(() => this.processQueue(), 0);\r\n }\r\n \r\n this.isProcessing = false;\r\n }\r\n\r\n getQueueLength(): number {\r\n return this.queue.length;\r\n }\r\n}\r\n",
79
+ "\r\n/**\r\n * Persistence Adapter Interface\r\n * Allows the StateManager to save/load state from external storage (Redis, SQLite, File, etc.)\r\n */\r\nexport interface PersistenceAdapter {\r\n /**\r\n * Load state from storage on startup\r\n */\r\n loadState(): Promise<Map<string, any>>;\r\n\r\n /**\r\n * Save a single key-value pair\r\n */\r\n saveState(key: string, value: any): Promise<void>;\r\n\r\n /**\r\n * Delete a key\r\n */\r\n deleteState(key: string): Promise<void>;\r\n\r\n /**\r\n * Clear all state\r\n */\r\n clearState(): Promise<void>;\r\n}\r\n\r\n/**\r\n * InMemory Adapter (Default)\r\n * Does not persist across restarts, but fulfills the interface.\r\n */\r\nexport class InMemoryPersistence implements PersistenceAdapter {\r\n private store = new Map<string, any>();\r\n\r\n async loadState(): Promise<Map<string, any>> {\r\n return new Map(this.store);\r\n }\r\n\r\n async saveState(key: string, value: any): Promise<void> {\r\n this.store.set(key, value);\r\n }\r\n\r\n async deleteState(key: string): Promise<void> {\r\n this.store.delete(key);\r\n }\r\n\r\n async clearState(): Promise<void> {\r\n this.store.clear();\r\n }\r\n}\r\n",
80
+ "\r\nimport { type PersistenceAdapter } from \"./persistence\";\r\n\r\n/**\r\n * Browser LocalStorage Persistence Adapter\r\n * Uses window.localStorage to save state.\r\n * Fallbacks to in-memory if not available (e.g. Node env without polyfill).\r\n */\r\nexport class BrowserPersistence implements PersistenceAdapter {\r\n private keyPrefix: string;\r\n private cache: Map<string, any> = new Map();\r\n private isLoaded: boolean = false;\r\n\r\n constructor(prefix: string = \"trigger_system:\") {\r\n this.keyPrefix = prefix;\r\n }\r\n\r\n private isAvailable(): boolean {\r\n return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';\r\n }\r\n\r\n private ensureLoaded() {\r\n if (this.isLoaded) return;\r\n \r\n if (this.isAvailable()) {\r\n try {\r\n const raw = window.localStorage.getItem(this.keyPrefix + \"state\");\r\n if (raw) {\r\n const json = JSON.parse(raw);\r\n this.cache = new Map(Object.entries(json));\r\n }\r\n } catch (error) {\r\n console.error(`[BrowserPersistence] Failed to load from localStorage:`, error);\r\n }\r\n }\r\n this.isLoaded = true;\r\n }\r\n\r\n private persist() {\r\n if (this.isAvailable()) {\r\n try {\r\n const obj = Object.fromEntries(this.cache);\r\n window.localStorage.setItem(this.keyPrefix + \"state\", JSON.stringify(obj));\r\n } catch (error) {\r\n console.error(`[BrowserPersistence] Failed to save to localStorage:`, error);\r\n }\r\n }\r\n }\r\n\r\n async loadState(): Promise<Map<string, any>> {\r\n this.ensureLoaded();\r\n return new Map(this.cache);\r\n }\r\n\r\n async saveState(key: string, value: any): Promise<void> {\r\n this.ensureLoaded();\r\n this.cache.set(key, value);\r\n this.persist();\r\n }\r\n\r\n async deleteState(key: string): Promise<void> {\r\n this.ensureLoaded();\r\n this.cache.delete(key);\r\n this.persist();\r\n }\r\n\r\n async clearState(): Promise<void> {\r\n this.cache.clear();\r\n this.persist();\r\n }\r\n}\r\n",
81
+ "\r\nimport { type PersistenceAdapter, InMemoryPersistence } from \"./persistence\";\r\n\r\n/**\r\n * State Manager\r\n * Handles persistent state across rule executions.\r\n * Allows for \"Stateful Triggers\" like counters, sequences, and goals.\r\n */\r\nexport class StateManager {\r\n private static instance: StateManager;\r\n private state: Map<string, any>;\r\n private persistence: PersistenceAdapter;\r\n\r\n private constructor() {\r\n this.state = new Map();\r\n this.persistence = new InMemoryPersistence();\r\n }\r\n\r\n static getInstance(): StateManager {\r\n if (!StateManager.instance) {\r\n StateManager.instance = new StateManager();\r\n }\r\n return StateManager.instance;\r\n }\r\n\r\n /**\r\n * Configure the persistence adapter.\r\n */\r\n setPersistence(adapter: PersistenceAdapter) {\r\n this.persistence = adapter;\r\n }\r\n\r\n /**\r\n * Load state from persistence. Should be called at startup.\r\n */\r\n async initialize(): Promise<void> {\r\n const loaded = await this.persistence.loadState();\r\n this.state = loaded;\r\n console.log(`[StateManager] Initialized with ${this.state.size} keys.`);\r\n }\r\n\r\n /**\r\n * Get a value from the state. \r\n */\r\n get(key: string): any {\r\n return this.state.get(key);\r\n }\r\n\r\n /**\r\n * Set a value in the state and persist it.\r\n */\r\n async set(key: string, value: any): Promise<void> {\r\n this.state.set(key, value);\r\n await this.persistence.saveState(key, value);\r\n }\r\n\r\n /**\r\n * Increment a numeric value explicitly.\r\n */\r\n async increment(key: string, amount: number = 1): Promise<number> {\r\n const current = this.get(key) || 0;\r\n const newVal = Number(current) + amount;\r\n await this.set(key, newVal);\r\n return newVal;\r\n }\r\n \r\n async decrement(key: string, amount: number = 1): Promise<number> {\r\n return this.increment(key, -amount);\r\n }\r\n\r\n async delete(key: string): Promise<boolean> {\r\n const deleted = this.state.delete(key);\r\n if (deleted) {\r\n await this.persistence.deleteState(key);\r\n }\r\n return deleted;\r\n }\r\n\r\n async clear(): Promise<void> {\r\n this.state.clear();\r\n await this.persistence.clearState();\r\n }\r\n\r\n /**\r\n * Export state as a plain object (for Context injection).\r\n */\r\n getAll(): Record<string, any> {\r\n return Object.fromEntries(this.state);\r\n }\r\n}\r\n",
82
+ "import type { TriggerAction, TriggerContext } from \"../types\";\r\nimport { ExpressionEngine } from \"./expression-engine\";\r\nimport { StateManager } from \"./state-manager\";\r\n\r\nexport type ActionHandler = (action: TriggerAction, context: TriggerContext) => Promise<any> | any;\r\n\r\nexport class ActionRegistry {\r\n private static instance: ActionRegistry;\r\n private handlers = new Map<string, ActionHandler>();\r\n\r\n private constructor() {\r\n this.registerDefaults();\r\n }\r\n\r\n static getInstance(): ActionRegistry {\r\n if (!this.instance) {\r\n this.instance = new ActionRegistry();\r\n }\r\n return this.instance;\r\n }\r\n\r\n register(type: string, handler: ActionHandler) {\r\n this.handlers.set(type.toUpperCase(), handler);\r\n }\r\n\r\n get(type: string): ActionHandler | undefined {\r\n return this.handlers.get(type.toUpperCase());\r\n }\r\n\r\n\r\n private registerDefaults() {\r\n // Log Action\r\n this.register(\"log\", (action, context) => {\r\n const messageTemplate = action.params?.message || action.params?.content || \"Log Trigger\";\r\n const message = ExpressionEngine.interpolate(messageTemplate, context);\r\n console.log(`[TriggerLog] ${message}`);\r\n return { message };\r\n });\r\n\r\n // Response Action\r\n this.register(\"response\", (action, context) => {\r\n const contentTemplate = action.params?.content || action.params?.body || \"\";\r\n const content = ExpressionEngine.interpolate(contentTemplate, context);\r\n return {\r\n statusCode: action.params?.statusCode || 200,\r\n headers: action.params?.headers || { \"Content-Type\": \"application/json\" },\r\n body: content,\r\n };\r\n });\r\n\r\n // Execute Action\r\n this.register(\"execute\", async (action, context) => {\r\n const commandTemplate = action.params?.command || action.params?.content || \"\";\r\n const command = ExpressionEngine.interpolate(commandTemplate, context);\r\n\r\n if (!action.params?.safe) {\r\n console.warn(`[Trigger] Ejecutando comando no seguro: ${command}`);\r\n }\r\n\r\n try {\r\n const proc = Bun.spawn(command.split(\" \"), {\r\n stdout: \"pipe\",\r\n stderr: \"pipe\",\r\n });\r\n const [stdout, stderr] = await Promise.all([\r\n new Response(proc.stdout).text(),\r\n new Response(proc.stderr).text(),\r\n ]);\r\n return {\r\n command,\r\n stdout,\r\n stderr,\r\n exitCode: await proc.exited,\r\n };\r\n } catch (error) {\r\n return { command, error: String(error) };\r\n }\r\n });\r\n\r\n // Forward Action\r\n this.register(\"forward\", async (action, context) => {\r\n const urlTemplate = action.params?.url || \"\";\r\n const url = ExpressionEngine.interpolate(urlTemplate, context);\r\n const method = action.params?.method || \"POST\";\r\n\r\n try {\r\n const response = await fetch(url, {\r\n method,\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n ...action.params?.headers,\r\n },\r\n body: JSON.stringify(context.data),\r\n });\r\n return {\r\n url,\r\n method,\r\n status: response.status,\r\n headers: (() => {\r\n const h: Record<string, string> = {};\r\n response.headers.forEach((v, k) => h[k] = v);\r\n return h;\r\n })(),\r\n body: await response.text(),\r\n };\r\n } catch (error) {\r\n return { url, method, error: String(error) };\r\n }\r\n });\r\n\r\n\r\n // --- State Actions ---\r\n\r\n this.register(\"STATE_SET\", async (action, context) => {\r\n const key = action.params?.key;\r\n const value = action.params?.value;\r\n if (!key) return { error: \"Missing key for STATE_SET\" };\r\n \r\n // Evaluate value if it's dynamic\r\n let finalValue = value;\r\n if (typeof value === 'string' && value.includes('${')) {\r\n finalValue = ExpressionEngine.interpolate(value, context);\r\n }\r\n\r\n await StateManager.getInstance().set(key, finalValue);\r\n return { key, value: finalValue };\r\n });\r\n\r\n this.register(\"STATE_INCREMENT\", async (action, context) => {\r\n const key = action.params?.key;\r\n const amount = Number(action.params?.amount) || 1;\r\n if (!key) return { error: \"Missing key for STATE_INCREMENT\" };\r\n\r\n const newValue = await StateManager.getInstance().increment(key, amount);\r\n return { key, newValue };\r\n });\r\n\r\n this.register(\"EMIT_EVENT\", (action, context) => {\r\n // This action is special. The engine or host must handle the result \r\n // and feed it back if desired. \r\n // We simply return the instruction to emit.\r\n return { \r\n event: action.params?.event, \r\n payload: action.params?.data || {} \r\n };\r\n });\r\n }\r\n}\r\n",
83
+ "\r\nimport type { TriggerContext } from \"../types\";\r\n\r\nexport interface ContextSource {\r\n type: string;\r\n payload: any;\r\n timestamp?: number;\r\n}\r\n\r\nexport class ContextAdapter {\r\n \r\n /**\r\n * Creates a standardized TriggerContext from a generic source.\r\n */\r\n static create(event: string, data: any, globals: Record<string, any> = {}): TriggerContext {\r\n return {\r\n event,\r\n timestamp: Date.now(),\r\n data: typeof data === 'object' ? data : { value: data },\r\n globals,\r\n helpers: this.getDefaultHelpers()\r\n };\r\n }\r\n\r\n /**\r\n * Adapts a standard HTTP Request (like from Bun.serve) into a TriggerContext.\r\n * Note: Accessing body requires it to be read previously or passed mainly as objects.\r\n */\r\n static fromRequest(req: Request, bodyData?: any, globals: Record<string, any> = {}): TriggerContext {\r\n const url = new URL(req.url);\r\n \r\n return {\r\n event: \"HTTP_REQUEST\",\r\n timestamp: Date.now(),\r\n data: {\r\n method: req.method,\r\n path: url.pathname,\r\n query: Object.fromEntries(url.searchParams),\r\n headers: (() => {\r\n const h: Record<string, string> = {};\r\n req.headers.forEach((v, k) => h[k] = v);\r\n return h;\r\n })(),\r\n body: bodyData || {}\r\n },\r\n globals: {\r\n ...globals,\r\n ip: req.headers.get(\"x-forwarded-for\") || \"unknown\"\r\n },\r\n helpers: this.getDefaultHelpers()\r\n };\r\n }\r\n\r\n /**\r\n * Adapts a generic Webhook payload.\r\n */\r\n static fromWebhook(provider: string, eventName: string, payload: any, globals: Record<string, any> = {}): TriggerContext {\r\n return {\r\n event: `WEBHOOK_${provider.toUpperCase()}_${eventName.toUpperCase()}`,\r\n timestamp: Date.now(),\r\n data: payload,\r\n globals: {\r\n ...globals,\r\n provider\r\n },\r\n helpers: this.getDefaultHelpers()\r\n };\r\n }\r\n\r\n private static getDefaultHelpers(): Record<string, Function> {\r\n return {\r\n now: () => Date.now(),\r\n uuid: () => crypto.randomUUID(),\r\n jsonParse: (str: string) => JSON.parse(str),\r\n jsonStringify: (obj: any) => JSON.stringify(obj)\r\n };\r\n }\r\n}\r\n",
84
+ "type Handler<T = any> = (data: T) => void;\r\n\r\n/**\r\n * Enumeration of all built-in engine events.\r\n * Use these constants instead of raw strings to ensure type safety.\r\n */\r\nexport enum EngineEvent {\r\n ENGINE_START = 'engine:start',\r\n ENGINE_DONE = 'engine:done',\r\n RULE_MATCH = 'rule:match',\r\n ACTION_SUCCESS = 'action:success',\r\n ACTION_ERROR = 'action:error'\r\n}\r\nexport const engineEvents = EngineEvent;\r\nexport class TriggerEmitter {\r\n private static instance: TriggerEmitter;\r\n private handlers = new Map<string, Set<Handler>>();\r\n\r\n private constructor() {}\r\n\r\n static getInstance(): TriggerEmitter {\r\n if (!this.instance) {\r\n this.instance = new TriggerEmitter();\r\n }\r\n return this.instance;\r\n }\r\n\r\n on<T = any>(event: EngineEvent | string, handler: Handler<T>): () => void {\r\n const eventName = event as string;\r\n if (!this.handlers.has(eventName)) {\r\n this.handlers.set(eventName, new Set());\r\n }\r\n this.handlers.get(eventName)!.add(handler);\r\n \r\n // Return unsubscribe function\r\n return () => this.off(eventName, handler);\r\n }\r\n\r\n off(event: EngineEvent | string, handler: Handler): void {\r\n const eventName = event as string;\r\n const set = this.handlers.get(eventName);\r\n if (set) {\r\n set.delete(handler);\r\n }\r\n }\r\n\r\n emit<T = any>(event: EngineEvent | string, data: T): void {\r\n const eventName = event as string;\r\n const set = this.handlers.get(eventName);\r\n if (set) {\r\n set.forEach(handler => {\r\n try {\r\n handler(data);\r\n } catch (error) {\r\n console.error(`Error in event handler for ${eventName}:`, error);\r\n }\r\n });\r\n }\r\n }\r\n\r\n}\r\n\r\n// Shortcut export\r\nexport const triggerEmitter = TriggerEmitter.getInstance();\r\n",
85
+ "// -----------------------------------------------------------------------------\n// MOTOR DE REGLAS PARA TRIGGERS\n// -----------------------------------------------------------------------------\n\nimport type {\n TriggerRule,\n TriggerCondition,\n ConditionGroup,\n RuleCondition,\n TriggerAction,\n ActionGroup,\n TriggerContext,\n TriggerResult,\n RuleEngineConfig,\n} from \"../types\";\nimport { ExpressionEngine } from \"../core/expression-engine\";\n\n\nimport { ActionRegistry } from \"./action-registry\";\nimport { StateManager } from \"./state-manager\";\nimport { triggerEmitter, EngineEvent } from \"../utils/emitter\";\n\n\nexport class RuleEngine {\n private rules: TriggerRule[] = [];\n private config: RuleEngineConfig;\n private lastExecutionTimes: Map<string, number> = new Map();\n private actionRegistry: ActionRegistry;\n\n constructor(config: RuleEngineConfig) {\n this.config = config;\n this.rules = [...config.rules];\n this.rules.sort((a, b) => (b.priority || 0) - (a.priority || 0));\n this.actionRegistry = ActionRegistry.getInstance();\n }\n\n /**\n * Convenience method to process an event with a simple payload\n */\n async processEvent(eventType: string, data: Record<string, any> = {}, globals: Record<string, any> = {}): Promise<TriggerResult[]> {\n const context: TriggerContext = {\n event: eventType,\n data: data,\n globals: globals,\n timestamp: Date.now(),\n state: {} // State will be injected by evaluateContext\n };\n return this.evaluateContext(context);\n }\n\n\n /**\n * Evalúa todas las reglas contra el contexto proporcionado\n */\n async evaluateContext(context: TriggerContext): Promise<TriggerResult[]> {\n const results: TriggerResult[] = [];\n \n // Inject current state into context\n context.state = StateManager.getInstance().getAll();\n\n if (this.config.globalSettings.debugMode) {\n console.log(\n `[RuleEngine] Evaluando contexto con ${this.rules.length} reglas para evento: ${context.event}`,\n );\n }\n\n triggerEmitter.emit(EngineEvent.ENGINE_START, { context, rulesCount: this.rules.length });\n\n\n for (const rule of this.rules) {\n if (rule.enabled === false) continue;\n \n // Check event type match\n if (rule.on !== context.event) continue;\n\n // Verificar cooldown\n if (rule.cooldown && !this.checkCooldown(rule.id, rule.cooldown)) {\n if (this.config.globalSettings.debugMode) {\n console.log(`[RuleEngine] Regla ${rule.id} en cooldown`);\n }\n continue;\n }\n\n // Evaluar condiciones\n // rule.if can be undefined (always true), a single condition, or an array\n const conditionMet = this.evaluateRuleConditions(rule.if, context);\n\n if (conditionMet) {\n if (this.config.globalSettings.debugMode) {\n console.log(\n `[RuleEngine] Ejecutando regla: ${rule.name || rule.id}`,\n );\n }\n\n triggerEmitter.emit(EngineEvent.RULE_MATCH, { rule, context });\n\n\n // Ejecutar acciones\n const executedActions = await this.executeRuleActions(rule.do, context);\n\n results.push({\n ruleId: rule.id,\n executedActions: executedActions,\n success: true,\n });\n\n // Actualizar tiempo de última ejecución\n this.lastExecutionTimes.set(rule.id, Date.now());\n\n // Si no se deben evaluar todas las reglas, salir después de la primera coincidencia\n if (!this.config.globalSettings.evaluateAll) {\n break;\n }\n }\n }\n\n triggerEmitter.emit(EngineEvent.ENGINE_DONE, { results, context });\n\n return results;\n }\n\n // --- Condition Evaluation ---\n\n private evaluateRuleConditions(\n conditions: RuleCondition | RuleCondition[] | undefined,\n context: TriggerContext\n ): boolean {\n if (!conditions) return true; // No conditions = always trigger if event matches\n\n if (Array.isArray(conditions)) {\n // Implicit AND for array of conditions at root\n return conditions.every(c => this.evaluateRecursiveCondition(c, context));\n } else {\n return this.evaluateRecursiveCondition(conditions, context);\n }\n }\n\n private evaluateRecursiveCondition(\n condition: RuleCondition,\n context: TriggerContext\n ): boolean {\n // Check if it's a group\n if ('conditions' in condition && 'operator' in condition) {\n return this.evaluateConditionGroup(condition as ConditionGroup, context);\n } else {\n return this.evaluateSingleCondition(condition as TriggerCondition, context);\n }\n }\n\n private evaluateConditionGroup(group: ConditionGroup, context: TriggerContext): boolean {\n if (group.operator === 'OR') {\n return group.conditions.some(c => this.evaluateRecursiveCondition(c, context));\n } else {\n // AND\n return group.conditions.every(c => this.evaluateRecursiveCondition(c, context));\n }\n }\n\n\n /**\n * Evalúa una condición individual\n */\n private evaluateSingleCondition(\n condition: TriggerCondition,\n context: TriggerContext,\n ): boolean {\n try {\n // Obtener el valor del campo especificado\n const fieldValue = ExpressionEngine.getNestedValue(\n condition.field,\n context,\n );\n\n // Process condition.value - if it's a string, try to interpolate it\n // This allows comparing field: \"data.amount\" with value: \"${globals.threshold}\"\n let targetValue = condition.value;\n if (typeof targetValue === 'string' && (targetValue.includes('${') || targetValue.startsWith('data.') || targetValue.startsWith('globals.'))) {\n // If it looks like an expression or variable reference, evaluate it\n targetValue = ExpressionEngine.evaluate(targetValue, context);\n }\n\n // Helper for Date comparisons\n const getDate = (val: any) => {\n if (val instanceof Date) return val.getTime();\n if (typeof val === 'number') return val;\n const d = new Date(val);\n return isNaN(d.getTime()) ? 0 : d.getTime();\n };\n\n // Helper for Safe Numeric comparisons\n // Returns null if values are not strictly comparable as numbers (prevents null -> 0 coercion)\n const getSafeNumber = (val: any): number | null => {\n if (typeof val === 'number') return val;\n if (val === null || val === undefined || val === '') return null;\n const num = Number(val);\n return isNaN(num) ? null : num;\n };\n\n // Evaluar según el operador\n switch (condition.operator) {\n case \"EQ\":\n case \"==\":\n return fieldValue == targetValue; // Loose equality for flexibility\n\n case \"NEQ\":\n case \"!=\":\n return fieldValue != targetValue;\n\n case \"GT\":\n case \">\": {\n const nField = getSafeNumber(fieldValue);\n const nTarget = getSafeNumber(targetValue);\n return (nField !== null && nTarget !== null) && nField > nTarget;\n }\n\n case \"GTE\":\n case \">=\": {\n const nField = getSafeNumber(fieldValue);\n const nTarget = getSafeNumber(targetValue);\n return (nField !== null && nTarget !== null) && nField >= nTarget;\n }\n\n case \"LT\":\n case \"<\": {\n const nField = getSafeNumber(fieldValue);\n const nTarget = getSafeNumber(targetValue);\n return (nField !== null && nTarget !== null) && nField < nTarget;\n }\n\n case \"LTE\":\n case \"<=\": {\n const nField = getSafeNumber(fieldValue);\n const nTarget = getSafeNumber(targetValue);\n return (nField !== null && nTarget !== null) && nField <= nTarget;\n }\n\n case \"CONTAINS\":\n return String(fieldValue).includes(String(targetValue));\n \n case \"MATCHES\":\n return new RegExp(String(targetValue)).test(String(fieldValue));\n \n case \"IN\":\n return Array.isArray(targetValue) && targetValue.includes(fieldValue);\n\n case \"NOT_IN\":\n return Array.isArray(targetValue) && !targetValue.includes(fieldValue);\n \n // Date operators\n case \"SINCE\": // field >= value (Chronologically after or same)\n case \"AFTER\":\n return getDate(fieldValue) >= getDate(targetValue);\n \n case \"BEFORE\": // field < value\n case \"UNTIL\":\n return getDate(fieldValue) < getDate(targetValue);\n\n case \"RANGE\": // Special Case: Value should be [min, max]\n if (Array.isArray(targetValue) && targetValue.length === 2) {\n const nField = getSafeNumber(fieldValue);\n return nField !== null && nField >= Number(targetValue[0]) && nField <= Number(targetValue[1]);\n }\n return false;\n\n default:\n console.error(`Operador desconocido: ${condition.operator}`);\n return false;\n }\n } catch (error) {\n console.error(`Error evaluando condición:`, condition, error);\n return false;\n }\n }\n\n // --- Action Execution ---\n\n private async executeRuleActions(\n actions: TriggerAction | TriggerAction[] | ActionGroup,\n context: TriggerContext\n ): Promise<TriggerResult['executedActions']> {\n const enactedActions: TriggerResult['executedActions'] = [];\n\n let actionList: TriggerAction[] = [];\n let mode: 'ALL' | 'SEQUENCE' | 'EITHER' = 'ALL';\n\n if (this.isActionGroup(actions)) {\n actionList = actions.actions;\n mode = actions.mode;\n } else if (Array.isArray(actions)) {\n actionList = actions;\n } else {\n actionList = [actions];\n }\n\n if (mode === 'EITHER' && actionList.length > 0) {\n // Pick one randomly\n // Support probability later, for now uniform\n const randomIndex = Math.floor(Math.random() * actionList.length);\n const selectedAction = actionList[randomIndex];\n if (selectedAction) {\n actionList = [selectedAction];\n }\n }\n\n // Execute\n if (mode === 'SEQUENCE') {\n for (const action of actionList) {\n const result = await this.executeSingleAction(action, context);\n enactedActions.push(result);\n }\n } else {\n // ALL (Parallel-ish)\n // Note: We await them sequentially here to simplify, but logically they are \"all\". \n // If true parallel is needed, Promise.all could be used, but side-effects might clash.\n for (const action of actionList) {\n const result = await this.executeSingleAction(action, context);\n enactedActions.push(result);\n }\n }\n\n return enactedActions;\n }\n\n private isActionGroup(action: any): action is ActionGroup {\n return 'mode' in action && 'actions' in action;\n }\n\n\n private async executeSingleAction(\n action: TriggerAction,\n context: TriggerContext,\n ): Promise<TriggerResult['executedActions'][0]> {\n \n // Check probability\n if (action.probability !== undefined && Math.random() > action.probability) {\n return {\n type: action.type,\n timestamp: Date.now(),\n result: { skipped: \"probability check failed\" }\n };\n }\n\n // Check delay\n if (action.delay && action.delay > 0) {\n await new Promise(resolve => setTimeout(resolve, action.delay));\n }\n\n try {\n const handler = this.actionRegistry.get(action.type);\n let result;\n\n if (handler) {\n result = await handler(action, context);\n } else {\n const msg = `Tipo de acción genérica o desconocida: ${action.type}`;\n if (this.config.globalSettings.strictActions) {\n throw new Error(msg);\n }\n console.warn(msg);\n result = { warning: `Generic action executed: ${action.type}` };\n }\n\n triggerEmitter.emit(EngineEvent.ACTION_SUCCESS, { action, context, result });\n\n return {\n type: action.type,\n result,\n timestamp: Date.now()\n };\n } catch (error) {\n console.error(`Error ejecutando acción:`, action, error);\n triggerEmitter.emit(EngineEvent.ACTION_ERROR, { action, context, error: String(error) });\n\n return {\n type: action.type,\n error: String(error),\n timestamp: Date.now()\n };\n }\n }\n\n\n /**\n * Verifica si una regla está en cooldown\n */\n private checkCooldown(ruleId: string, cooldownMs: number): boolean {\n const lastExecution = this.lastExecutionTimes.get(ruleId);\n\n if (!lastExecution) return true;\n\n return Date.now() - lastExecution > cooldownMs;\n }\n\n /**\n * Actualiza las reglas del motor\n */\n updateRules(newRules: TriggerRule[]): void {\n this.rules = [...newRules];\n this.rules.sort((a, b) => (b.priority || 0) - (a.priority || 0));\n }\n\n /**\n * Obtiene todas las reglas\n */\n getRules(): TriggerRule[] {\n return [...this.rules];\n }\n}\n",
86
+ "// src/trigger_system/utils.ts\r\nimport type { TriggerContext } from \"../types\";\r\n\r\nexport class TriggerUtils {\r\n /**\r\n * Retrieves a nested value from the context using dot notation.\r\n * supports: data.field, globals.envVal, computed.result\r\n */\r\n static getNestedValue(path: string, context: TriggerContext): any {\r\n const parts = path.split(\".\");\r\n let current: any = context;\r\n\r\n for (const part of parts) {\r\n if (current === null || current === undefined) {\r\n return undefined;\r\n }\r\n current = current[part];\r\n }\r\n\r\n return current;\r\n }\r\n\r\n /**\r\n * Interpolates a string with values from the context.\r\n * Example: \"Hello ${data.username}\" -> \"Hello Steve\"\r\n */\r\n static interpolate(template: string, context: TriggerContext): string {\r\n if (typeof template !== 'string') return template;\r\n \r\n return template.replace(/\\$\\{([^}]+)\\}/g, (match, expression) => {\r\n // 1. Try direct path access first (fast)\r\n const directValue = this.getNestedValue(expression, context);\r\n if (directValue !== undefined) {\r\n return String(directValue);\r\n }\r\n \r\n // 2. Fallback to simple math evaluation if needed (optional, keeps it safe)\r\n // For now, we return the match if not found to avoid crashing or weird replacements\r\n return match;\r\n });\r\n }\r\n \r\n /**\r\n * Checks if a value satisfies a comparison operator against a criteria.\r\n */\r\n static compare(actual: any, operator: string, criteria: any): boolean {\r\n switch (operator) {\r\n case 'EQ':\r\n case '==':\r\n return actual == criteria;\r\n case 'NEQ':\r\n case '!=':\r\n return actual != criteria;\r\n case 'GT':\r\n case '>':\r\n return Number(actual) > Number(criteria);\r\n case 'GTE':\r\n case '>=':\r\n return Number(actual) >= Number(criteria);\r\n case 'LT':\r\n case '<':\r\n return Number(actual) < Number(criteria);\r\n case 'LTE':\r\n case '<=':\r\n return Number(actual) <= Number(criteria);\r\n case 'IN':\r\n return Array.isArray(criteria) && criteria.includes(actual);\r\n case 'NOT_IN':\r\n return Array.isArray(criteria) && !criteria.includes(actual);\r\n case 'CONTAINS':\r\n if (Array.isArray(actual) || typeof actual === 'string') {\r\n return actual.includes(criteria);\r\n }\r\n return false;\r\n case 'MATCHES':\r\n return new RegExp(criteria).test(String(actual));\r\n case 'RANGE':\r\n // criteria should be [min, max]\r\n if (Array.isArray(criteria) && criteria.length === 2) {\r\n const val = Number(actual);\r\n return val >= criteria[0] && val <= criteria[1];\r\n }\r\n return false;\r\n default:\r\n console.warn(`Unknown operator: ${operator}`);\r\n return false;\r\n }\r\n }\r\n}\r\n",
87
+ "// src/trigger_system/engine.ts\r\nimport type { \r\n TriggerRule, \r\n TriggerContext, \r\n TriggerResult, \r\n Action, \r\n ActionGroup, \r\n RuleCondition,\r\n Condition,\r\n ConditionGroup\r\n} from \"../types\";\r\nimport { TriggerUtils } from \"../utils/utils\";\r\n// import { TriggerLoader } from \"../io/loader\"; // Removed dependency\r\nimport { ExpressionEngine } from \"./expression-engine\";\r\n\r\nexport type EngineActionHandler = (params: any, context: TriggerContext) => Promise<any> | any;\r\n\r\nexport class TriggerEngine {\r\n private rules: TriggerRule[] = [];\r\n private actionHandlers: Map<string, EngineActionHandler> = new Map();\r\n private lastExecution: Map<string, number> = new Map();\r\n\r\n // Rules should be loaded externally and passed here\r\n constructor(rules: TriggerRule[] = []) {\r\n this.rules = rules;\r\n // Sort logic moved to where rules are set\r\n this.sortRules();\r\n }\r\n\r\n private sortRules() {\r\n this.rules.sort((a, b) => (b.priority || 0) - (a.priority || 0));\r\n }\r\n\r\n\r\n /**\r\n * Register a handler for a specific action type\r\n */\r\n registerAction(type: string, handler: EngineActionHandler) {\r\n this.actionHandlers.set(type, handler);\r\n }\r\n\r\n /**\r\n * Process an incoming event\r\n */\r\n async processEvent(context: TriggerContext): Promise<TriggerResult[]> {\r\n const results: TriggerResult[] = [];\r\n\r\n // Filter rules by event name\r\n const candidates = this.rules.filter(r => r.enabled !== false && r.on === context.event);\r\n\r\n for (const rule of candidates) {\r\n // Check Cooldown\r\n if (rule.cooldown && this.checkCooldown(rule.id, rule.cooldown)) {\r\n continue; // Skip if in cooldown\r\n }\r\n\r\n // Evaluate Conditions\r\n if (this.evaluateConditions(rule.if, context)) {\r\n // Execute Actions\r\n const execResult = await this.executeRuleActions(rule.do, context);\r\n \r\n // Update Cooldown\r\n this.lastExecution.set(rule.id, Date.now());\r\n\r\n results.push({\r\n ruleId: rule.id,\r\n success: true,\r\n executedActions: execResult\r\n });\r\n }\r\n }\r\n\r\n return results;\r\n }\r\n\r\n private checkCooldown(ruleId: string, cooldown: number): boolean {\r\n const last = this.lastExecution.get(ruleId);\r\n if (!last) return false;\r\n return (Date.now() - last) < cooldown;\r\n }\r\n\r\n private evaluateConditions(\r\n condition: RuleCondition | RuleCondition[] | undefined, \r\n context: TriggerContext\r\n ): boolean {\r\n if (!condition) return true; // No conditions = always true\r\n\r\n if (Array.isArray(condition)) {\r\n // Implicit AND for array of conditions\r\n return condition.every(c => this.evaluateSingleCondition(c, context));\r\n }\r\n\r\n return this.evaluateSingleCondition(condition, context);\r\n }\r\n\r\n private evaluateSingleCondition(cond: RuleCondition, context: TriggerContext): boolean {\r\n // Check if it's a Group\r\n if ('operator' in cond && 'conditions' in cond) {\r\n const group = cond as ConditionGroup;\r\n if (group.operator === 'OR') {\r\n return group.conditions.some(c => this.evaluateSingleCondition(c, context));\r\n } else { // AND\r\n return group.conditions.every(c => this.evaluateSingleCondition(c, context));\r\n }\r\n }\r\n\r\n // It's a simple Condition\r\n const c = cond as Condition;\r\n const actualValue = TriggerUtils.getNestedValue(c.field, context);\r\n // Interpolate the expected value if it's a string containing variables\r\n let expectedValue = c.value;\r\n if (typeof expectedValue === 'string' && expectedValue.includes('${')) {\r\n expectedValue = ExpressionEngine.interpolate(expectedValue, context);\r\n }\r\n \r\n return TriggerUtils.compare(actualValue, c.operator, expectedValue);\r\n }\r\n\r\n private async executeRuleActions(\r\n actionConfig: Action | Action[] | ActionGroup, \r\n context: TriggerContext\r\n ): Promise<any[]> {\r\n const executionLogs: any[] = [];\r\n\r\n // Normalize to ActionGroup or List\r\n let actionsToExecute: Action[] = [];\r\n let mode = 'ALL';\r\n\r\n if (Array.isArray(actionConfig)) {\r\n actionsToExecute = actionConfig;\r\n } else if ('mode' in actionConfig && 'actions' in actionConfig) {\r\n const group = actionConfig as ActionGroup;\r\n mode = group.mode;\r\n actionsToExecute = group.actions;\r\n } else {\r\n // Single Action\r\n actionsToExecute = [actionConfig as Action];\r\n }\r\n\r\n // Handle Modes\r\n if (mode === 'EITHER') {\r\n // Pick one randomly\r\n // Support probability weights if present?\r\n // For now simple random\r\n const totalWeight = actionsToExecute.reduce((sum, a) => sum + (a.probability || 1), 0);\r\n let random = Math.random() * totalWeight;\r\n \r\n let selected: Action | undefined;\r\n for (const action of actionsToExecute) {\r\n const weight = action.probability || 1;\r\n random -= weight;\r\n if (random <= 0) {\r\n selected = action;\r\n break;\r\n }\r\n }\r\n // Fallback\r\n if (!selected && actionsToExecute.length > 0) selected = actionsToExecute[actionsToExecute.length - 1];\r\n\r\n if (selected) {\r\n actionsToExecute = [selected];\r\n } else {\r\n actionsToExecute = [];\r\n }\r\n }\r\n\r\n // Execute\r\n for (const action of actionsToExecute) {\r\n // Interpolate Params\r\n const processedParams = this.interpolateParams(action.params || {}, context);\r\n const handler = this.actionHandlers.get(action.type);\r\n\r\n if (handler) {\r\n try {\r\n // Handle Delay\r\n if (action.delay && action.delay > 0) {\r\n await new Promise(r => setTimeout(r, action.delay));\r\n }\r\n\r\n const result = await handler(processedParams, context);\r\n executionLogs.push({\r\n type: action.type,\r\n result,\r\n timestamp: Date.now()\r\n });\r\n } catch (err) {\r\n console.error(`Action ${action.type} failed:`, err);\r\n executionLogs.push({\r\n type: action.type,\r\n error: err,\r\n timestamp: Date.now()\r\n });\r\n }\r\n } else {\r\n console.warn(`No handler registered for action type: ${action.type}`);\r\n executionLogs.push({\r\n type: action.type,\r\n error: \"No handler registered\",\r\n timestamp: Date.now()\r\n });\r\n }\r\n }\r\n\r\n return executionLogs;\r\n }\r\n\r\n private interpolateParams(params: Record<string, any>, context: TriggerContext): Record<string, any> {\r\n const result: Record<string, any> = {};\r\n for (const [key, val] of Object.entries(params)) {\r\n if (typeof val === 'string') {\r\n result[key] = ExpressionEngine.interpolate(val, context);\r\n } else if (typeof val === 'object' && val !== null) {\r\n // Recursive?\r\n // JSON objects might need deep interpolation.\r\n // For now simple 1-level or stringify\r\n // Let's do simple recursion for nice nested params\r\n result[key] = this.interpolateDeep(val, context);\r\n } else {\r\n result[key] = val;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n private interpolateDeep(obj: any, context: TriggerContext): any {\r\n if (typeof obj === 'string') return ExpressionEngine.interpolate(obj, context);\r\n if (Array.isArray(obj)) return obj.map(v => this.interpolateDeep(v, context));\r\n if (typeof obj === 'object' && obj !== null) {\r\n const res: any = {};\r\n for(const k in obj) res[k] = this.interpolateDeep(obj[k], context);\r\n return res;\r\n }\r\n return obj;\r\n }\r\n}\r\n",
88
+ "/**\n * Extracts duplicated elements and their indices from an array, returning them.\n *\n * Note that given `a === b && b === c`, then `c === a` must be `true` for this to give accurate results.\n *\n * @param arr The array to extract duplicate elements from.\n */ export const getDuplicatesOf = (arr, opts) => {\n const isEqual = opts?.isEqual ?? ((l, r) => l === r);\n const elementFirstSeenIndx = new Map();\n const duplicates = [];\n for (const [indx, element] of arr.entries()) {\n const duplicatesIndx = duplicates.findIndex(duplicate => isEqual(duplicate.element, element));\n if (duplicatesIndx !== -1) {\n // This is at least the third occurrence of an item equal to `element`,\n // so add this index to the list of indices where the element is duplicated.\n duplicates[duplicatesIndx].indices.push(indx);\n continue;\n }\n // At this point, we know this is either the first\n // or second occurrence of an item equal to `element`...\n let found = false;\n for (const [existingElement, firstSeenIndx] of elementFirstSeenIndx) {\n if (isEqual(element, existingElement)) {\n // This is the second occurrence of an item equal to `element`,\n // so store it as a duplicate.\n found = true;\n duplicates.push({\n element: existingElement,\n indices: [firstSeenIndx, indx]\n });\n }\n }\n if (!found) {\n // We haven't seen this element before,\n // so just store the index it was first seen\n elementFirstSeenIndx.set(element, indx);\n }\n }\n return duplicates;\n};\nexport const join = (segments, delimiter) => segments.join(delimiter);\nexport const getPath = (root, path) => {\n let result = root;\n for (const segment of path) {\n if (typeof result !== \"object\" || result === null)\n return undefined;\n result = result[segment];\n }\n return result;\n};\nexport const intersectUniqueLists = (l, r) => {\n const intersection = [...l];\n for (const item of r)\n if (!l.includes(item))\n intersection.push(item);\n return intersection;\n};\nexport const liftArray = (data) => (Array.isArray(data) ? data : [data]);\n/**\n * Splits an array into two arrays based on the result of a predicate\n *\n * @param predicate - The guard function used to determine which items to include.\n * @returns A tuple containing two arrays:\n * \t\t\t\t- the first includes items for which `predicate` returns true\n * \t\t\t\t- the second includes items for which `predicate` returns false\n *\n * @example\n * const list = [1, \"2\", \"3\", 4, 5];\n * const [numbers, strings] = spliterate(list, (x) => typeof x === \"number\");\n * // Type: number[]\n * // Output: [1, 4, 5]\n * console.log(evens);\n * // Type: string[]\n * // Output: [\"2\", \"3\"]\n * console.log(odds);\n */\nexport const spliterate = (arr, predicate) => {\n const result = [[], []];\n for (const item of arr) {\n if (predicate(item))\n result[0].push(item);\n else\n result[1].push(item);\n }\n return result;\n};\nexport const ReadonlyArray = Array;\nexport const includes = (array, element) => array.includes(element);\nexport const range = (length, offset = 0) => [...new Array(length)].map((_, i) => i + offset);\n/**\n * Adds a value or array to an array, returning the concatenated result\n */\nexport const append = (to, value, opts) => {\n if (to === undefined) {\n return (value === undefined ? []\n : Array.isArray(value) ? value\n : [value]);\n }\n if (opts?.prepend) {\n if (Array.isArray(value))\n to.unshift(...value);\n else\n to.unshift(value);\n }\n else {\n if (Array.isArray(value))\n to.push(...value);\n else\n to.push(value);\n }\n return to;\n};\n/**\n * Concatenates an element or list with a readonly list\n */\nexport const conflatenate = (to, elementOrList) => {\n if (elementOrList === undefined || elementOrList === null)\n return to ?? [];\n if (to === undefined || to === null)\n return liftArray(elementOrList);\n return to.concat(elementOrList);\n};\n/**\n * Concatenates a variadic list of elements or lists with a readonly list\n */\nexport const conflatenateAll = (...elementsOrLists) => elementsOrLists.reduce(conflatenate, []);\n/**\n * Appends a value or concatenates an array to an array if it is not already included, returning the array\n */\nexport const appendUnique = (to, value, opts) => {\n if (to === undefined)\n return Array.isArray(value) ? value : [value];\n const isEqual = opts?.isEqual ?? ((l, r) => l === r);\n for (const v of liftArray(value))\n if (!to.some(existing => isEqual(existing, v)))\n to.push(v);\n return to;\n};\nexport const groupBy = (array, discriminant) => array.reduce((result, item) => {\n const key = item[discriminant];\n result[key] = append(result[key], item);\n return result;\n}, {});\nexport const arrayEquals = (l, r, opts) => l.length === r.length &&\n l.every(opts?.isEqual ?\n (lItem, i) => opts.isEqual(lItem, r[i])\n : (lItem, i) => lItem === r[i]);\n",
89
+ "export const hasDomain = (data, kind) => domainOf(data) === kind;\nexport const domainOf = (data) => {\n const builtinType = typeof data;\n return (builtinType === \"object\" ?\n data === null ?\n \"null\"\n : \"object\"\n : builtinType === \"function\" ? \"object\"\n : builtinType);\n};\n/** Each domain's completion for the phrase \"must be _____\" */\nexport const domainDescriptions = {\n boolean: \"boolean\",\n null: \"null\",\n undefined: \"undefined\",\n bigint: \"a bigint\",\n number: \"a number\",\n object: \"an object\",\n string: \"a string\",\n symbol: \"a symbol\"\n};\nexport const jsTypeOfDescriptions = {\n ...domainDescriptions,\n function: \"a function\"\n};\n",
90
+ "export class InternalArktypeError extends Error {\n}\nexport const throwInternalError = message => throwError(message, InternalArktypeError);\nexport const throwError = (message, ctor = Error) => {\n throw new ctor(message);\n};\nexport class ParseError extends Error {\n name = \"ParseError\";\n}\nexport const throwParseError = message => throwError(message, ParseError);\n/**\n * TypeScript won't suggest strings beginning with a space as properties.\n * Useful for symbol-like string properties.\n */\nexport const noSuggest = (s) => ` ${s}`;\n/** Unrendered character (U+200B) used to mark a string type */\nexport const ZeroWidthSpace = \"\\u{200B}\";\n",
91
+ "import { append } from \"./arrays.js\";\nexport const flatMorph = (o, flatMapEntry) => {\n const result = {};\n const inputIsArray = Array.isArray(o);\n let outputShouldBeArray = false;\n for (const [i, entry] of Object.entries(o).entries()) {\n const mapped = inputIsArray ? flatMapEntry(i, entry[1]) : flatMapEntry(...entry, i);\n outputShouldBeArray ||= typeof mapped[0] === \"number\";\n const flattenedEntries = Array.isArray(mapped[0]) || mapped.length === 0 ?\n // if we have an empty array (for filtering) or an array with\n // another array as its first element, treat it as a list\n mapped\n // otherwise, it should be a single entry, so nest it in a tuple\n // so it doesn't get spread when the result is flattened\n : [mapped];\n for (const [k, v] of flattenedEntries) {\n if (typeof k === \"object\")\n result[k.group] = append(result[k.group], v);\n else\n result[k] = v;\n }\n }\n return outputShouldBeArray ? Object.values(result) : result;\n};\n",
92
+ "import { noSuggest, ZeroWidthSpace } from \"./errors.js\";\nimport { flatMorph } from \"./flatMorph.js\";\n/**\n * Object.entries wrapper providing narrowed types for objects with known sets\n * of keys, e.g. those defined internally as configs\n */\nexport const entriesOf = Object.entries;\nexport const fromEntries = (entries) => Object.fromEntries(entries);\nexport const keysOf = (o) => Object.keys(o);\nexport const isKeyOf = (k, o) => k in o;\nexport const hasKey = (o, k) => k in o;\n// must be defined this way to avoid https://github.com/microsoft/TypeScript/issues/55049\nexport const hasDefinedKey = (o, k) => o[k] !== undefined;\nexport const InnerDynamicBase = class {\n};\nexport class DynamicBase {\n constructor(properties) {\n Object.assign(this, properties);\n }\n}\nexport const NoopBase = class {\n};\n/** @ts-ignore (needed to extend `t`) **/\nexport class CastableBase extends NoopBase {\n}\nexport const splitByKeys = (o, leftKeys) => {\n const l = {};\n const r = {};\n let k;\n for (k in o) {\n if (k in leftKeys)\n l[k] = o[k];\n else\n r[k] = o[k];\n }\n return [l, r];\n};\nexport const pick = (o, keys) => splitByKeys(o, keys)[0];\nexport const omit = (o, keys) => splitByKeys(o, keys)[1];\nexport const isEmptyObject = (o) => Object.keys(o).length === 0;\nexport const stringAndSymbolicEntriesOf = (o) => [\n ...Object.entries(o),\n ...Object.getOwnPropertySymbols(o).map(k => [k, o[k]])\n];\n/** Like Object.assign, but it will preserve getters instead of evaluating them. */\nexport const defineProperties = (base, merged) => \n// declared like this to avoid https://github.com/microsoft/TypeScript/issues/55049\nObject.defineProperties(base, Object.getOwnPropertyDescriptors(merged));\n/** Copies enumerable keys of o to a new object in alphabetical order */\nexport const withAlphabetizedKeys = (o) => {\n const keys = Object.keys(o).sort();\n const result = {};\n for (let i = 0; i < keys.length; i++)\n result[keys[i]] = o[keys[i]];\n return result;\n};\nexport const invert = (t) => flatMorph(t, (k, v) => [v, k]);\nexport const unset = noSuggest(`unset${ZeroWidthSpace}`);\nexport const enumValues = (tsEnum) => Object.values(tsEnum).filter(v => {\n if (typeof v === \"number\")\n return true;\n return typeof tsEnum[v] !== \"number\";\n});\n",
93
+ "import { domainOf } from \"./domain.js\";\nimport { isKeyOf } from \"./records.js\";\n// ECMAScript Objects\n// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects\nexport const ecmascriptConstructors = {\n Array,\n Boolean,\n Date,\n Error,\n Function,\n Map,\n Number,\n Promise,\n RegExp,\n Set,\n String,\n WeakMap,\n WeakSet\n};\n/** Node18 */\nexport const FileConstructor = globalThis.File ?? Blob;\n// Platform APIs\n// See https://developer.mozilla.org/en-US/docs/Web/API\n// Must be implemented in Node etc. as well as the browser to include here\nexport const platformConstructors = {\n ArrayBuffer,\n Blob,\n File: FileConstructor,\n FormData,\n Headers,\n Request,\n Response,\n URL\n};\nexport const typedArrayConstructors = {\n Int8Array,\n Uint8Array,\n Uint8ClampedArray,\n Int16Array,\n Uint16Array,\n Int32Array,\n Uint32Array,\n Float32Array,\n Float64Array,\n BigInt64Array,\n BigUint64Array\n};\n// Built-in object constructors based on a subset of:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects\nexport const builtinConstructors = {\n ...ecmascriptConstructors,\n ...platformConstructors,\n ...typedArrayConstructors,\n String,\n Number,\n Boolean\n};\nexport const objectKindOf = (data) => {\n let prototype = Object.getPrototypeOf(data);\n while (prototype?.constructor &&\n (!isKeyOf(prototype.constructor.name, builtinConstructors) ||\n !(data instanceof builtinConstructors[prototype.constructor.name])))\n prototype = Object.getPrototypeOf(prototype);\n const name = prototype?.constructor?.name;\n if (name === undefined || name === \"Object\")\n return undefined;\n return name;\n};\nexport const objectKindOrDomainOf = (data) => (typeof data === \"object\" && data !== null ?\n (objectKindOf(data) ?? \"object\")\n : domainOf(data));\nexport const hasObjectKind = (data, kind) => objectKindOf(data) === kind;\nexport const isArray = Array.isArray;\nexport const ecmascriptDescriptions = {\n Array: \"an array\",\n Function: \"a function\",\n Date: \"a Date\",\n RegExp: \"a RegExp\",\n Error: \"an Error\",\n Map: \"a Map\",\n Set: \"a Set\",\n String: \"a String object\",\n Number: \"a Number object\",\n Boolean: \"a Boolean object\",\n Promise: \"a Promise\",\n WeakMap: \"a WeakMap\",\n WeakSet: \"a WeakSet\"\n};\nexport const platformDescriptions = {\n ArrayBuffer: \"an ArrayBuffer instance\",\n Blob: \"a Blob instance\",\n File: \"a File instance\",\n FormData: \"a FormData instance\",\n Headers: \"a Headers instance\",\n Request: \"a Request instance\",\n Response: \"a Response instance\",\n URL: \"a URL instance\"\n};\nexport const typedArrayDescriptions = {\n Int8Array: \"an Int8Array\",\n Uint8Array: \"a Uint8Array\",\n Uint8ClampedArray: \"a Uint8ClampedArray\",\n Int16Array: \"an Int16Array\",\n Uint16Array: \"a Uint16Array\",\n Int32Array: \"an Int32Array\",\n Uint32Array: \"a Uint32Array\",\n Float32Array: \"a Float32Array\",\n Float64Array: \"a Float64Array\",\n BigInt64Array: \"a BigInt64Array\",\n BigUint64Array: \"a BigUint64Array\"\n};\n/** Each defaultObjectKind's completion for the phrase \"must be _____\" */\nexport const objectKindDescriptions = {\n ...ecmascriptDescriptions,\n ...platformDescriptions,\n ...typedArrayDescriptions\n};\n/**\n * this will only return an object kind if it's the root constructor\n * example TypeError would return null not 'Error'\n **/\nexport const getBuiltinNameOfConstructor = (ctor) => {\n const constructorName = Object(ctor).name ?? null;\n return (constructorName &&\n isKeyOf(constructorName, builtinConstructors) &&\n builtinConstructors[constructorName] === ctor) ?\n constructorName\n : null;\n};\n/**\n * Returns an array of constructors for all ancestors (i.e., prototypes) of a given object.\n */\nexport const ancestorsOf = (o) => {\n let proto = Object.getPrototypeOf(o);\n const result = [];\n while (proto !== null) {\n result.push(proto.constructor);\n proto = Object.getPrototypeOf(proto);\n }\n return result;\n};\nexport const constructorExtends = (ctor, base) => {\n let current = ctor.prototype;\n while (current !== null) {\n if (current === base.prototype)\n return true;\n current = Object.getPrototypeOf(current);\n }\n return false;\n};\n",
94
+ "import { getBuiltinNameOfConstructor } from \"./objectKinds.js\";\n/** Shallowly copy the properties of the object. */\nexport const shallowClone = input => _clone(input, null);\n/** Deeply copy the properties of the a non-subclassed Object, Array or Date.*/\nexport const deepClone = (input) => _clone(input, new Map());\nconst _clone = (input, seen) => {\n if (typeof input !== \"object\" || input === null)\n return input;\n if (seen?.has(input))\n return seen.get(input);\n const builtinConstructorName = getBuiltinNameOfConstructor(input.constructor);\n if (builtinConstructorName === \"Date\")\n return new Date(input.getTime());\n // we don't try and clone other prototypes here since this we can't guarantee arrow functions attached to the object\n // are rebound in case they reference `this` (see https://x.com/colinhacks/status/1818422039210049985)\n if (builtinConstructorName && builtinConstructorName !== \"Array\")\n return input;\n const cloned = Array.isArray(input) ?\n input.slice()\n : Object.create(Object.getPrototypeOf(input));\n const propertyDescriptors = Object.getOwnPropertyDescriptors(input);\n if (seen) {\n seen.set(input, cloned);\n for (const k in propertyDescriptors) {\n const desc = propertyDescriptors[k];\n if (\"get\" in desc || \"set\" in desc)\n continue;\n desc.value = _clone(desc.value, seen);\n }\n }\n Object.defineProperties(cloned, propertyDescriptors);\n return cloned;\n};\n",
95
+ "import { throwInternalError } from \"./errors.js\";\nimport { unset } from \"./records.js\";\nexport const cached = (thunk) => {\n let result = unset;\n return () => (result === unset ? (result = thunk()) : result);\n};\nexport const isThunk = (value) => typeof value === \"function\" && value.length === 0;\nexport const tryCatch = (fn, onError) => {\n try {\n return fn();\n }\n catch (e) {\n return onError?.(e);\n }\n};\nexport const DynamicFunction = class extends Function {\n constructor(...args) {\n const params = args.slice(0, -1);\n const body = args[args.length - 1];\n try {\n super(...params, body);\n }\n catch (e) {\n return throwInternalError(`Encountered an unexpected error while compiling your definition:\n Message: ${e} \n Source: (${args.slice(0, -1)}) => {\n ${args[args.length - 1]}\n }`);\n }\n }\n};\nexport class Callable {\n constructor(fn, ...[opts]) {\n return Object.assign(Object.setPrototypeOf(fn.bind(opts?.bind ?? this), this.constructor.prototype), opts?.attach);\n }\n}\n/**\n * Checks if the environment has Content Security Policy (CSP) enabled,\n * preventing JIT-optimized code from being compiled via new Function().\n *\n * @returns `true` if a function created using new Function() can be\n * successfully invoked in the environment, `false` otherwise.\n *\n * The result is cached for subsequent invocations.\n */\nexport const envHasCsp = cached(() => {\n try {\n return new Function(\"return false\")();\n }\n catch {\n return true;\n }\n});\n",
96
+ "import { noSuggest } from \"./errors.js\";\nexport const brand = noSuggest(\"brand\");\nexport const narrow = (t) => t;\n/** primitive key used to represent an inferred type at compile-time */\nexport const inferred = noSuggest(\"arkInferred\");\n",
97
+ "import { noSuggest } from \"./errors.js\";\nconst args = noSuggest(\"args\");\nexport class Hkt {\n constructor() { }\n}\n",
98
+ "// based on the util of the same name in @ark/fs\n// isolated here for use with registry\n/** get a CJS/ESM compatible string representing the current file */\nconst fileName = () => {\n try {\n const error = new Error();\n const stackLine = error.stack?.split(\"\\n\")[2]?.trim() || \"\"; // [1]=this func, [2]=caller\n const filePath = stackLine.match(/\\(?(.+?)(?::\\d+:\\d+)?\\)?$/)?.[1] || \"unknown\";\n return filePath.replace(/^file:\\/\\//, \"\");\n }\n catch {\n return \"unknown\";\n }\n};\nconst env = globalThis.process?.env ?? {};\nexport const isomorphic = {\n fileName,\n env\n};\n",
99
+ "export const capitalize = (s) => (s[0].toUpperCase() + s.slice(1));\nexport const uncapitalize = (s) => (s[0].toLowerCase() + s.slice(1));\nexport const anchoredRegex = (regex) => new RegExp(anchoredSource(regex), typeof regex === \"string\" ? \"\" : regex.flags);\nexport const deanchoredRegex = (regex) => new RegExp(deanchoredSource(regex), typeof regex === \"string\" ? \"\" : regex.flags);\nexport const anchoredSource = (regex) => {\n const source = typeof regex === \"string\" ? regex : regex.source;\n return `^(?:${source})$`;\n};\nexport const deanchoredSource = (regex) => {\n const source = typeof regex === \"string\" ? regex : regex.source;\n if (source.startsWith(\"^(?:\") && source.endsWith(\")$\"))\n return source.slice(4, -2);\n return source.slice(source[0] === \"^\" ? 1 : 0, source[source.length - 1] === \"$\" ? -1 : undefined);\n};\nexport const RegexPatterns = {\n negativeLookahead: (pattern) => `(?!${pattern})`,\n nonCapturingGroup: (pattern) => `(?:${pattern})`\n};\nexport const Backslash = \"\\\\\";\nexport const whitespaceChars = {\n \" \": 1,\n \"\\n\": 1,\n \"\\t\": 1\n};\nexport const emojiToUnicode = (emoji) => emoji\n .split(\"\")\n .map(char => {\n const codePoint = char.codePointAt(0);\n return codePoint ? `\\\\u${codePoint.toString(16).padStart(4, \"0\")}` : \"\";\n})\n .join(\"\");\nexport const alphabet = [\n \"a\",\n \"b\",\n \"c\",\n \"d\",\n \"e\",\n \"f\",\n \"g\",\n \"h\",\n \"i\",\n \"j\",\n \"k\",\n \"l\",\n \"m\",\n \"n\",\n \"o\",\n \"p\",\n \"q\",\n \"r\",\n \"s\",\n \"t\",\n \"u\",\n \"v\",\n \"w\",\n \"x\",\n \"y\",\n \"z\"\n];\n",
100
+ "import { throwParseError } from \"./errors.js\";\nimport { anchoredRegex, RegexPatterns } from \"./strings.js\";\n/*\n * The goal of the number literal and bigint literal regular expressions is to:\n *\n * 1. Ensure definitions form a bijection with the values they represent.\n * 2. Attempt to mirror TypeScript's own format for stringification of numeric\n * values such that the regex should match a given definition if any only if\n * a precise literal type will be inferred (in TS4.8+).\n */\nconst anchoredNegativeZeroPattern = /^-0\\.?0*$/.source;\nconst positiveIntegerPattern = /[1-9]\\d*/.source;\nconst looseDecimalPattern = /\\.\\d+/.source;\nconst strictDecimalPattern = /\\.\\d*[1-9]/.source;\nconst createNumberMatcher = (opts) => anchoredRegex(RegexPatterns.negativeLookahead(anchoredNegativeZeroPattern) +\n RegexPatterns.nonCapturingGroup(\"-?\" +\n RegexPatterns.nonCapturingGroup(RegexPatterns.nonCapturingGroup(\"0|\" + positiveIntegerPattern) +\n RegexPatterns.nonCapturingGroup(opts.decimalPattern) +\n \"?\") +\n (opts.allowDecimalOnly ? \"|\" + opts.decimalPattern : \"\") +\n \"?\"));\n/**\n * Matches a well-formatted numeric expression according to the following rules:\n * 1. Must include an integer portion (i.e. '.321' must be written as '0.321')\n * 2. The first digit of the value must not be 0, unless the entire integer portion is 0\n * 3. If the value includes a decimal, its last digit may not be 0\n * 4. The value may not be \"-0\"\n */\nexport const wellFormedNumberMatcher = createNumberMatcher({\n decimalPattern: strictDecimalPattern,\n allowDecimalOnly: false\n});\nexport const isWellFormedNumber = wellFormedNumberMatcher.test.bind(wellFormedNumberMatcher);\n/**\n * Similar to wellFormedNumber but more permissive in the following ways:\n *\n * - Allows numbers without an integer portion like \".5\" (well-formed equivalent is \"0.5\")\n * - Allows decimals with trailing zeroes like \"0.10\" (well-formed equivalent is \"0.1\")\n */\nexport const numericStringMatcher = createNumberMatcher({\n decimalPattern: looseDecimalPattern,\n allowDecimalOnly: true\n});\nexport const isNumericString = numericStringMatcher.test.bind(numericStringMatcher);\nexport const numberLikeMatcher = /^-?\\d*\\.?\\d*$/;\nconst isNumberLike = (s) => s.length !== 0 && numberLikeMatcher.test(s);\n/**\n * Matches a well-formatted integer according to the following rules:\n * 1. must begin with an integer, the first digit of which cannot be 0 unless the entire value is 0\n * 2. The value may not be \"-0\"\n */\nexport const wellFormedIntegerMatcher = anchoredRegex(RegexPatterns.negativeLookahead(\"^-0$\") +\n \"-?\" +\n RegexPatterns.nonCapturingGroup(RegexPatterns.nonCapturingGroup(\"0|\" + positiveIntegerPattern)));\nexport const isWellFormedInteger = wellFormedIntegerMatcher.test.bind(wellFormedIntegerMatcher);\nexport const integerLikeMatcher = /^-?\\d+$/;\nconst isIntegerLike = integerLikeMatcher.test.bind(integerLikeMatcher);\nconst numericLiteralDescriptions = {\n number: \"a number\",\n bigint: \"a bigint\",\n integer: \"an integer\"\n};\nexport const writeMalformedNumericLiteralMessage = (def, kind) => `'${def}' was parsed as ${numericLiteralDescriptions[kind]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`;\nconst isWellFormed = (def, kind) => kind === \"number\" ? isWellFormedNumber(def) : isWellFormedInteger(def);\nconst parseKind = (def, kind) => kind === \"number\" ? Number(def) : Number.parseInt(def);\nconst isKindLike = (def, kind) => kind === \"number\" ? isNumberLike(def) : isIntegerLike(def);\nexport const tryParseNumber = (token, options) => parseNumeric(token, \"number\", options);\nexport const tryParseWellFormedNumber = (token, options) => parseNumeric(token, \"number\", { ...options, strict: true });\nexport const tryParseInteger = (token, options) => parseNumeric(token, \"integer\", options);\nconst parseNumeric = (token, kind, options) => {\n const value = parseKind(token, kind);\n if (!Number.isNaN(value)) {\n if (isKindLike(token, kind)) {\n if (options?.strict) {\n return isWellFormed(token, kind) ? value : (throwParseError(writeMalformedNumericLiteralMessage(token, kind)));\n }\n return value;\n }\n }\n return (options?.errorOnFail ?\n throwParseError(options?.errorOnFail === true ?\n `Failed to parse ${numericLiteralDescriptions[kind]} from '${token}'`\n : options?.errorOnFail)\n : undefined);\n};\nexport const tryParseWellFormedBigint = (def) => {\n if (def[def.length - 1] !== \"n\")\n return;\n const maybeIntegerLiteral = def.slice(0, -1);\n let value;\n try {\n value = BigInt(maybeIntegerLiteral);\n }\n catch {\n return;\n }\n if (wellFormedIntegerMatcher.test(maybeIntegerLiteral))\n return value;\n if (integerLikeMatcher.test(maybeIntegerLiteral)) {\n // If the definition looks like a bigint but is\n // not well-formed, throw.\n return throwParseError(writeMalformedNumericLiteralMessage(def, \"bigint\"));\n }\n};\n/**\n * Returns the next or previous representable floating-point number after the given input.\n *\n * @param {\"+\" | \"-\"} [direction=\"+\"] - The direction to find the nearest float. \"+\" for the next float, \"-\" for the previous float.\n * @throws {Error} If the input is not a finite number.\n *\n * @example\n * console.log(nearestFloat(0)); // Smallest positive number\n * console.log(nearestFloat(2)); // 2.0000000000000004\n * console.log(nearestFloat(2.1)); // 2.1000000000000005\n * console.log(nearestFloat(2, \"-\")); // 1.9999999999999998\n * console.log(nearestFloat(2.1, \"-\")); // 2.0999999999999996\n * // as size of input increases, the increments become larger to stay within what\n * // JS can represent in a numeric value\n * console.log(nearestFloat(5555555555555555)); // 5555555555555556\n * console.log(nearestFloat(5555555555555555, \"-\")); // 5555555555555554\n */\nexport const nearestFloat = (n, direction = \"+\") => {\n const buffer = new ArrayBuffer(8);\n const f64 = new Float64Array(buffer);\n const u32 = new Uint32Array(buffer);\n f64[0] = n;\n if (n === 0) {\n u32[0] = 1;\n u32[1] = direction === \"-\" ? 1 << 31 : 0;\n }\n else if ((n > 0 && direction === \"+\") || (n < 0 && direction === \"-\")) {\n if (u32[0]++ === 0xffffffff)\n u32[1]++;\n }\n else if (u32[0]-- === 0)\n u32[1]--;\n return f64[0];\n};\n",
101
+ "import { domainOf } from \"./domain.js\";\nimport { throwInternalError } from \"./errors.js\";\nimport { isomorphic } from \"./isomorphic.js\";\nimport { FileConstructor, objectKindOf } from \"./objectKinds.js\";\n// Eventually we can just import from package.json in the source itself\n// but for now, import assertions are too unstable and it wouldn't support\n// recent node versions (https://nodejs.org/api/esm.html#json-modules).\n// For now, we assert this matches the package.json version via a unit test.\nexport const arkUtilVersion = \"0.56.0\";\nexport const initialRegistryContents = {\n version: arkUtilVersion,\n filename: isomorphic.fileName(),\n FileConstructor\n};\nexport const registry = initialRegistryContents;\nconst namesByResolution = new Map();\nconst nameCounts = Object.create(null);\nexport const register = (value) => {\n const existingName = namesByResolution.get(value);\n if (existingName)\n return existingName;\n let name = baseNameFor(value);\n if (nameCounts[name])\n name = `${name}${nameCounts[name]++}`;\n else\n nameCounts[name] = 1;\n registry[name] = value;\n namesByResolution.set(value, name);\n return name;\n};\nexport const isDotAccessible = (keyName) => /^[$A-Z_a-z][\\w$]*$/.test(keyName);\nconst baseNameFor = (value) => {\n switch (typeof value) {\n case \"object\": {\n if (value === null)\n break;\n const prefix = objectKindOf(value) ?? \"object\";\n // convert to camelCase\n return prefix[0].toLowerCase() + prefix.slice(1);\n }\n case \"function\":\n return isDotAccessible(value.name) ? value.name : \"fn\";\n case \"symbol\":\n return value.description && isDotAccessible(value.description) ?\n value.description\n : \"symbol\";\n }\n return throwInternalError(`Unexpected attempt to register serializable value of type ${domainOf(value)}`);\n};\n",
102
+ "export const serializePrimitive = (value) => (typeof value === \"string\" ? JSON.stringify(value)\n : typeof value === \"bigint\" ? `${value}n`\n : `${value}`);\n",
103
+ "import { domainOf } from \"./domain.js\";\nimport { serializePrimitive } from \"./primitive.js\";\nimport { stringAndSymbolicEntriesOf } from \"./records.js\";\nimport { isDotAccessible, register } from \"./registry.js\";\nexport const snapshot = (data, opts = {}) => _serialize(data, {\n onUndefined: `$ark.undefined`,\n onBigInt: n => `$ark.bigint-${n}`,\n ...opts\n}, []);\nexport const print = (data, opts) => console.log(printable(data, opts));\nexport const printable = (data, opts) => {\n switch (domainOf(data)) {\n case \"object\":\n const o = data;\n const ctorName = o.constructor?.name ?? \"Object\";\n return (ctorName === \"Object\" || ctorName === \"Array\" ?\n opts?.quoteKeys === false ?\n stringifyUnquoted(o, opts?.indent ?? 0, \"\")\n : JSON.stringify(_serialize(o, printableOpts, []), null, opts?.indent)\n : stringifyUnquoted(o, opts?.indent ?? 0, \"\"));\n case \"symbol\":\n return printableOpts.onSymbol(data);\n default:\n return serializePrimitive(data);\n }\n};\nconst stringifyUnquoted = (value, indent, currentIndent) => {\n if (typeof value === \"function\")\n return printableOpts.onFunction(value);\n if (typeof value !== \"object\" || value === null)\n return serializePrimitive(value);\n const nextIndent = currentIndent + \" \".repeat(indent);\n if (Array.isArray(value)) {\n if (value.length === 0)\n return \"[]\";\n const items = value\n .map(item => stringifyUnquoted(item, indent, nextIndent))\n .join(\",\\n\" + nextIndent);\n return indent ? `[\\n${nextIndent}${items}\\n${currentIndent}]` : `[${items}]`;\n }\n const ctorName = value.constructor?.name ?? \"Object\";\n if (ctorName === \"Object\") {\n const keyValues = stringAndSymbolicEntriesOf(value).map(([key, val]) => {\n const stringifiedKey = typeof key === \"symbol\" ? printableOpts.onSymbol(key)\n : isDotAccessible(key) ? key\n : JSON.stringify(key);\n const stringifiedValue = stringifyUnquoted(val, indent, nextIndent);\n return `${nextIndent}${stringifiedKey}: ${stringifiedValue}`;\n });\n if (keyValues.length === 0)\n return \"{}\";\n return indent ?\n `{\\n${keyValues.join(\",\\n\")}\\n${currentIndent}}`\n : `{${keyValues.join(\", \")}}`;\n }\n if (value instanceof Date)\n return describeCollapsibleDate(value);\n if (\"expression\" in value && typeof value.expression === \"string\")\n return value.expression;\n return ctorName;\n};\nconst printableOpts = {\n onCycle: () => \"(cycle)\",\n onSymbol: v => `Symbol(${register(v)})`,\n onFunction: v => `Function(${register(v)})`\n};\nconst _serialize = (data, opts, seen) => {\n switch (domainOf(data)) {\n case \"object\": {\n const o = data;\n if (\"toJSON\" in o && typeof o.toJSON === \"function\")\n return o.toJSON();\n if (typeof o === \"function\")\n return printableOpts.onFunction(o);\n if (seen.includes(o))\n return \"(cycle)\";\n const nextSeen = [...seen, o];\n if (Array.isArray(o))\n return o.map(item => _serialize(item, opts, nextSeen));\n if (o instanceof Date)\n return o.toDateString();\n const result = {};\n for (const k in o)\n result[k] = _serialize(o[k], opts, nextSeen);\n for (const s of Object.getOwnPropertySymbols(o)) {\n result[opts.onSymbol?.(s) ?? s.toString()] = _serialize(o[s], opts, nextSeen);\n }\n return result;\n }\n case \"symbol\":\n return printableOpts.onSymbol(data);\n case \"bigint\":\n return opts.onBigInt?.(data) ?? `${data}n`;\n case \"undefined\":\n return opts.onUndefined ?? \"undefined\";\n case \"string\":\n return data.replace(/\\\\/g, \"\\\\\\\\\");\n default:\n return data;\n }\n};\n/**\n * Converts a Date instance to a human-readable description relative to its precision\n */\nexport const describeCollapsibleDate = (date) => {\n const year = date.getFullYear();\n const month = date.getMonth();\n const dayOfMonth = date.getDate();\n const hours = date.getHours();\n const minutes = date.getMinutes();\n const seconds = date.getSeconds();\n const milliseconds = date.getMilliseconds();\n if (month === 0 &&\n dayOfMonth === 1 &&\n hours === 0 &&\n minutes === 0 &&\n seconds === 0 &&\n milliseconds === 0)\n return `${year}`;\n const datePortion = `${months[month]} ${dayOfMonth}, ${year}`;\n if (hours === 0 && minutes === 0 && seconds === 0 && milliseconds === 0)\n return datePortion;\n let timePortion = date.toLocaleTimeString();\n const suffix = timePortion.endsWith(\" AM\") || timePortion.endsWith(\" PM\") ?\n timePortion.slice(-3)\n : \"\";\n if (suffix)\n timePortion = timePortion.slice(0, -suffix.length);\n if (milliseconds)\n timePortion += `.${pad(milliseconds, 3)}`;\n else if (timeWithUnnecessarySeconds.test(timePortion))\n timePortion = timePortion.slice(0, -3);\n return `${timePortion + suffix}, ${datePortion}`;\n};\nconst months = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"\n];\nconst timeWithUnnecessarySeconds = /:\\d\\d:00$/;\nconst pad = (value, length) => String(value).padStart(length, \"0\");\n",
104
+ "import { ReadonlyArray } from \"./arrays.js\";\nimport { throwParseError } from \"./errors.js\";\nimport { isDotAccessible } from \"./registry.js\";\nimport { printable } from \"./serialize.js\";\nexport const appendStringifiedKey = (path, prop, ...[opts]) => {\n const stringifySymbol = opts?.stringifySymbol ?? printable;\n let propAccessChain = path;\n switch (typeof prop) {\n case \"string\":\n propAccessChain =\n isDotAccessible(prop) ?\n path === \"\" ?\n prop\n : `${path}.${prop}`\n : `${path}[${JSON.stringify(prop)}]`;\n break;\n case \"number\":\n propAccessChain = `${path}[${prop}]`;\n break;\n case \"symbol\":\n propAccessChain = `${path}[${stringifySymbol(prop)}]`;\n break;\n default:\n if (opts?.stringifyNonKey)\n propAccessChain = `${path}[${opts.stringifyNonKey(prop)}]`;\n else {\n throwParseError(`${printable(prop)} must be a PropertyKey or stringifyNonKey must be passed to options`);\n }\n }\n return propAccessChain;\n};\nexport const stringifyPath = (path, ...opts) => path.reduce((s, k) => appendStringifiedKey(s, k, ...opts), \"\");\nexport class ReadonlyPath extends ReadonlyArray {\n // alternate strategy for caching since the base object is frozen\n cache = {};\n constructor(...items) {\n super();\n this.push(...items);\n }\n toJSON() {\n if (this.cache.json)\n return this.cache.json;\n this.cache.json = [];\n for (let i = 0; i < this.length; i++) {\n this.cache.json.push(typeof this[i] === \"symbol\" ? printable(this[i]) : this[i]);\n }\n return this.cache.json;\n }\n stringify() {\n if (this.cache.stringify)\n return this.cache.stringify;\n return (this.cache.stringify = stringifyPath(this));\n }\n stringifyAncestors() {\n if (this.cache.stringifyAncestors)\n return this.cache.stringifyAncestors;\n let propString = \"\";\n const result = [propString];\n for (const path of this) {\n propString = appendStringifiedKey(propString, path);\n result.push(propString);\n }\n return (this.cache.stringifyAncestors = result);\n }\n}\n",
105
+ "import { Backslash, whitespaceChars } from \"./strings.js\";\nexport class Scanner {\n chars;\n i;\n def;\n constructor(def) {\n this.def = def;\n this.chars = [...def];\n this.i = 0;\n }\n /** Get lookahead and advance scanner by one */\n shift() {\n return (this.chars[this.i++] ?? \"\");\n }\n get lookahead() {\n return (this.chars[this.i] ?? \"\");\n }\n get nextLookahead() {\n return this.chars[this.i + 1] ?? \"\";\n }\n get length() {\n return this.chars.length;\n }\n shiftUntil(condition) {\n let shifted = \"\";\n while (this.lookahead) {\n if (condition(this, shifted))\n break;\n else\n shifted += this.shift();\n }\n return shifted;\n }\n shiftUntilEscapable(condition) {\n let shifted = \"\";\n while (this.lookahead) {\n if (this.lookahead === Backslash) {\n this.shift();\n if (condition(this, shifted))\n shifted += this.shift();\n else if (this.lookahead === Backslash)\n shifted += this.shift();\n else\n shifted += `${Backslash}${this.shift()}`;\n }\n else if (condition(this, shifted))\n break;\n else\n shifted += this.shift();\n }\n return shifted;\n }\n shiftUntilLookahead(charOrSet) {\n return typeof charOrSet === \"string\" ?\n this.shiftUntil(s => s.lookahead === charOrSet)\n : this.shiftUntil(s => s.lookahead in charOrSet);\n }\n shiftUntilNonWhitespace() {\n return this.shiftUntil(() => !(this.lookahead in whitespaceChars));\n }\n jumpToIndex(i) {\n this.i = i < 0 ? this.length + i : i;\n }\n jumpForward(count) {\n this.i += count;\n }\n get location() {\n return this.i;\n }\n get unscanned() {\n return this.chars.slice(this.i, this.length).join(\"\");\n }\n get scanned() {\n return this.chars.slice(0, this.i).join(\"\");\n }\n sliceChars(start, end) {\n return this.chars.slice(start, end).join(\"\");\n }\n lookaheadIs(char) {\n return this.lookahead === char;\n }\n lookaheadIsIn(tokens) {\n return this.lookahead in tokens;\n }\n}\nexport const writeUnmatchedGroupCloseMessage = (char, unscanned) => `Unmatched ${char}${(unscanned === \"\" ? \"\" : ` before ${unscanned}`)}`;\nexport const writeUnclosedGroupMessage = (missingChar) => `Missing ${missingChar}`;\n",
106
+ "import { hasDomain } from \"./domain.js\";\nimport { noSuggest } from \"./errors.js\";\nimport { ancestorsOf } from \"./objectKinds.js\";\nimport { NoopBase } from \"./records.js\";\n// even though the value we attach will be identical, we use this so classes\n// won't be treated as instanceof a Trait\nconst implementedTraits = noSuggest(\"implementedTraits\");\nexport const hasTrait = (traitClass) => (o) => {\n if (!hasDomain(o, \"object\"))\n return false;\n if (implementedTraits in o.constructor &&\n o.constructor[implementedTraits].includes(traitClass))\n return true;\n // emulate standard instanceof behavior\n return ancestorsOf(o).includes(traitClass);\n};\n/** @ts-ignore required to extend NoopBase */\nexport class Trait extends NoopBase {\n static get [Symbol.hasInstance]() {\n return hasTrait(this);\n }\n traitsOf() {\n return implementedTraits in this.constructor ?\n this.constructor[implementedTraits]\n : [];\n }\n}\nconst collectPrototypeDescriptors = (trait) => {\n let proto = trait.prototype;\n let result = {};\n do {\n // ensure prototypes are sorted from lowest to highest precedence\n result = Object.assign(Object.getOwnPropertyDescriptors(proto), result);\n proto = Object.getPrototypeOf(proto);\n } while (proto !== Object.prototype && proto !== null);\n return result;\n};\nexport const compose = ((...traits) => {\n const base = function (...args) {\n for (const trait of traits) {\n const instance = Reflect.construct(trait, args, this.constructor);\n Object.assign(this, instance);\n }\n };\n const flatImplementedTraits = [];\n for (const trait of traits) {\n // copy static properties\n Object.assign(base, trait);\n // flatten and copy prototype\n Object.defineProperties(base.prototype, collectPrototypeDescriptors(trait));\n if (implementedTraits in trait) {\n // add any ancestor traits from which the current trait was composed\n for (const innerTrait of trait[implementedTraits]) {\n if (!flatImplementedTraits.includes(innerTrait))\n flatImplementedTraits.push(innerTrait);\n }\n }\n if (!flatImplementedTraits.includes(trait))\n flatImplementedTraits.push(trait);\n }\n Object.defineProperty(base, implementedTraits, {\n value: flatImplementedTraits,\n enumerable: false\n });\n return base;\n});\nexport const implement = (...args) => {\n if (args[args.length - 1] instanceof Trait)\n return compose(...args);\n const implementation = args[args.length - 1];\n const base = compose(...args.slice(0, -1));\n // copy implementation last since it overrides traits\n Object.defineProperties(base.prototype, Object.getOwnPropertyDescriptors(implementation));\n return base;\n};\n",
107
+ "import { register, registry } from \"@ark/util\";\nlet _registryName = \"$ark\";\nlet suffix = 2;\nwhile (_registryName in globalThis)\n _registryName = `$ark${suffix++}`;\nexport const registryName = _registryName;\nglobalThis[registryName] = registry;\nexport const $ark = registry;\nexport const reference = (name) => `${registryName}.${name}`;\nexport const registeredReference = (value) => reference(register(value));\n",
108
+ "import { CastableBase, DynamicFunction, hasDomain, isDotAccessible, serializePrimitive } from \"@ark/util\";\nimport { registeredReference } from \"./registry.js\";\nexport class CompiledFunction extends CastableBase {\n argNames;\n body = \"\";\n constructor(...args) {\n super();\n this.argNames = args;\n for (const arg of args) {\n if (arg in this) {\n throw new Error(`Arg name '${arg}' would overwrite an existing property on FunctionBody`);\n }\n ;\n this[arg] = arg;\n }\n }\n indentation = 0;\n indent() {\n this.indentation += 4;\n return this;\n }\n dedent() {\n this.indentation -= 4;\n return this;\n }\n prop(key, optional = false) {\n return compileLiteralPropAccess(key, optional);\n }\n index(key, optional = false) {\n return indexPropAccess(`${key}`, optional);\n }\n line(statement) {\n ;\n this.body += `${\" \".repeat(this.indentation)}${statement}\\n`;\n return this;\n }\n const(identifier, expression) {\n this.line(`const ${identifier} = ${expression}`);\n return this;\n }\n let(identifier, expression) {\n return this.line(`let ${identifier} = ${expression}`);\n }\n set(identifier, expression) {\n return this.line(`${identifier} = ${expression}`);\n }\n if(condition, then) {\n return this.block(`if (${condition})`, then);\n }\n elseIf(condition, then) {\n return this.block(`else if (${condition})`, then);\n }\n else(then) {\n return this.block(\"else\", then);\n }\n /** Current index is \"i\" */\n for(until, body, initialValue = 0) {\n return this.block(`for (let i = ${initialValue}; ${until}; i++)`, body);\n }\n /** Current key is \"k\" */\n forIn(object, body) {\n return this.block(`for (const k in ${object})`, body);\n }\n block(prefix, contents, suffix = \"\") {\n this.line(`${prefix} {`);\n this.indent();\n contents(this);\n this.dedent();\n return this.line(`}${suffix}`);\n }\n return(expression = \"\") {\n return this.line(`return ${expression}`);\n }\n write(name = \"anonymous\", indent = 0) {\n return `${name}(${this.argNames.join(\", \")}) { ${indent ?\n this.body\n .split(\"\\n\")\n .map(l => \" \".repeat(indent) + `${l}`)\n .join(\"\\n\")\n : this.body} }`;\n }\n compile() {\n return new DynamicFunction(...this.argNames, this.body);\n }\n}\nexport const compileSerializedValue = (value) => hasDomain(value, \"object\") || typeof value === \"symbol\" ?\n registeredReference(value)\n : serializePrimitive(value);\nexport const compileLiteralPropAccess = (key, optional = false) => {\n if (typeof key === \"string\" && isDotAccessible(key))\n return `${optional ? \"?\" : \"\"}.${key}`;\n return indexPropAccess(serializeLiteralKey(key), optional);\n};\nexport const serializeLiteralKey = (key) => typeof key === \"symbol\" ? registeredReference(key) : JSON.stringify(key);\nexport const indexPropAccess = (key, optional = false) => `${optional ? \"?.\" : \"\"}[${key}]`;\nexport class NodeCompiler extends CompiledFunction {\n traversalKind;\n optimistic;\n constructor(ctx) {\n super(\"data\", \"ctx\");\n this.traversalKind = ctx.kind;\n this.optimistic = ctx.optimistic === true;\n }\n invoke(node, opts) {\n const arg = opts?.arg ?? this.data;\n const requiresContext = typeof node === \"string\" ? true : this.requiresContextFor(node);\n const id = typeof node === \"string\" ? node : node.id;\n if (requiresContext)\n return `${this.referenceToId(id, opts)}(${arg}, ${this.ctx})`;\n return `${this.referenceToId(id, opts)}(${arg})`;\n }\n referenceToId(id, opts) {\n const invokedKind = opts?.kind ?? this.traversalKind;\n const base = `this.${id}${invokedKind}`;\n return opts?.bind ? `${base}.bind(${opts?.bind})` : base;\n }\n requiresContextFor(node) {\n return this.traversalKind === \"Apply\" || node.allowsRequiresContext;\n }\n initializeErrorCount() {\n return this.const(\"errorCount\", \"ctx.currentErrorCount\");\n }\n returnIfFail() {\n return this.if(\"ctx.currentErrorCount > errorCount\", () => this.return());\n }\n returnIfFailFast() {\n return this.if(\"ctx.failFast && ctx.currentErrorCount > errorCount\", () => this.return());\n }\n traverseKey(keyExpression, accessExpression, node) {\n const requiresContext = this.requiresContextFor(node);\n if (requiresContext)\n this.line(`${this.ctx}.path.push(${keyExpression})`);\n this.check(node, {\n arg: accessExpression\n });\n if (requiresContext)\n this.line(`${this.ctx}.path.pop()`);\n return this;\n }\n check(node, opts) {\n return this.traversalKind === \"Allows\" ?\n this.if(`!${this.invoke(node, opts)}`, () => this.return(false))\n : this.line(this.invoke(node, opts));\n }\n}\n",
109
+ "import { flatMorph, isArray, noSuggest } from \"@ark/util\";\nexport const makeRootAndArrayPropertiesMutable = (o) => \n// this cast should not be required, but it seems TS is referencing\n// the wrong parameters here?\nflatMorph(o, (k, v) => [k, isArray(v) ? [...v] : v]);\nexport const arkKind = noSuggest(\"arkKind\");\nexport const hasArkKind = (value, kind) => value?.[arkKind] === kind;\nexport const isNode = (value) => hasArkKind(value, \"root\") || hasArkKind(value, \"constraint\");\n",
110
+ "import { flatMorph, printable, throwParseError } from \"@ark/util\";\nimport { compileSerializedValue } from \"./compile.js\";\nimport { isNode } from \"./utils.js\";\nexport const basisKinds = [\"unit\", \"proto\", \"domain\"];\nexport const structuralKinds = [\n \"required\",\n \"optional\",\n \"index\",\n \"sequence\"\n];\nexport const prestructuralKinds = [\n \"pattern\",\n \"divisor\",\n \"exactLength\",\n \"max\",\n \"min\",\n \"maxLength\",\n \"minLength\",\n \"before\",\n \"after\"\n];\nexport const refinementKinds = [\n ...prestructuralKinds,\n \"structure\",\n \"predicate\"\n];\nexport const constraintKinds = [...refinementKinds, ...structuralKinds];\nexport const rootKinds = [\n \"alias\",\n \"union\",\n \"morph\",\n \"unit\",\n \"intersection\",\n \"proto\",\n \"domain\"\n];\nexport const nodeKinds = [...rootKinds, ...constraintKinds];\nexport const constraintKeys = flatMorph(constraintKinds, (i, kind) => [kind, 1]);\nexport const structureKeys = flatMorph([...structuralKinds, \"undeclared\"], (i, k) => [k, 1]);\nexport const precedenceByKind = flatMorph(nodeKinds, (i, kind) => [kind, i]);\nexport const isNodeKind = (value) => typeof value === \"string\" && value in precedenceByKind;\nexport function assertNodeKind(value, kind) {\n const valueIsNode = isNode(value);\n if (!valueIsNode || value.kind !== kind) {\n throwParseError(`Expected node of kind ${kind} (was ${valueIsNode ? `${value.kind} node` : printable(value)})`);\n }\n}\nexport const precedenceOfKind = (kind) => precedenceByKind[kind];\nexport const schemaKindsRightOf = (kind) => rootKinds.slice(precedenceOfKind(kind) + 1);\nexport const unionChildKinds = [\n ...schemaKindsRightOf(\"union\"),\n \"alias\"\n];\nexport const morphChildKinds = [\n ...schemaKindsRightOf(\"morph\"),\n \"alias\"\n];\nexport const defaultValueSerializer = (v) => {\n if (typeof v === \"string\" || typeof v === \"boolean\" || v === null)\n return v;\n if (typeof v === \"number\") {\n if (Number.isNaN(v))\n return \"NaN\";\n if (v === Number.POSITIVE_INFINITY)\n return \"Infinity\";\n if (v === Number.NEGATIVE_INFINITY)\n return \"-Infinity\";\n return v;\n }\n return compileSerializedValue(v);\n};\nexport const compileObjectLiteral = (ctx) => {\n let result = \"{ \";\n for (const [k, v] of Object.entries(ctx))\n result += `${k}: ${compileSerializedValue(v)}, `;\n return result + \" }\";\n};\nexport const implementNode = (_) => {\n const implementation = _;\n if (implementation.hasAssociatedError) {\n implementation.defaults.expected ??= ctx => \"description\" in ctx ?\n ctx.description\n : implementation.defaults.description(ctx);\n implementation.defaults.actual ??= data => printable(data);\n implementation.defaults.problem ??= ctx => `must be ${ctx.expected}${ctx.actual ? ` (was ${ctx.actual})` : \"\"}`;\n implementation.defaults.message ??= ctx => {\n if (ctx.path.length === 0)\n return ctx.problem;\n const problemWithLocation = `${ctx.propString} ${ctx.problem}`;\n if (problemWithLocation[0] === \"[\") {\n // clarify paths like [1], [0][1], and [\"key!\"] that could be confusing\n return `value at ${problemWithLocation}`;\n }\n return problemWithLocation;\n };\n }\n return implementation;\n};\n",
111
+ "import { printable, throwInternalError } from \"@ark/util\";\nclass ToJsonSchemaError extends Error {\n name = \"ToJsonSchemaError\";\n code;\n context;\n constructor(code, context) {\n super(printable(context, { quoteKeys: false, indent: 4 }));\n this.code = code;\n this.context = context;\n }\n hasCode(code) {\n return this.code === code;\n }\n}\nconst defaultConfig = {\n target: \"draft-2020-12\",\n dialect: \"https://json-schema.org/draft/2020-12/schema\",\n useRefs: false,\n fallback: {\n arrayObject: ctx => ToJsonSchema.throw(\"arrayObject\", ctx),\n arrayPostfix: ctx => ToJsonSchema.throw(\"arrayPostfix\", ctx),\n defaultValue: ctx => ToJsonSchema.throw(\"defaultValue\", ctx),\n domain: ctx => ToJsonSchema.throw(\"domain\", ctx),\n morph: ctx => ToJsonSchema.throw(\"morph\", ctx),\n patternIntersection: ctx => ToJsonSchema.throw(\"patternIntersection\", ctx),\n predicate: ctx => ToJsonSchema.throw(\"predicate\", ctx),\n proto: ctx => ToJsonSchema.throw(\"proto\", ctx),\n symbolKey: ctx => ToJsonSchema.throw(\"symbolKey\", ctx),\n unit: ctx => ToJsonSchema.throw(\"unit\", ctx),\n date: ctx => ToJsonSchema.throw(\"date\", ctx)\n }\n};\nexport const ToJsonSchema = {\n Error: ToJsonSchemaError,\n throw: (...args) => {\n throw new ToJsonSchema.Error(...args);\n },\n throwInternalOperandError: (kind, schema) => throwInternalError(`Unexpected JSON Schema input for ${kind}: ${printable(schema)}`),\n defaultConfig\n};\n",
112
+ "import { isNodeKind } from \"./shared/implement.js\";\nimport { $ark } from \"./shared/registry.js\";\nimport { ToJsonSchema } from \"./shared/toJsonSchema.js\";\n// $ark.config could already be set if it were imported previously from the\n// dedicated config entrypoint, in which case we don't want to reinitialize it\n$ark.config ??= {};\nexport const configureSchema = (config) => {\n const result = Object.assign($ark.config, mergeConfigs($ark.config, config));\n if ($ark.resolvedConfig)\n $ark.resolvedConfig = mergeConfigs($ark.resolvedConfig, result);\n return result;\n};\nexport const mergeConfigs = (base, merged) => {\n if (!merged)\n return base;\n const result = { ...base };\n let k;\n for (k in merged) {\n const keywords = { ...base.keywords };\n if (k === \"keywords\") {\n for (const flatAlias in merged[k]) {\n const v = merged.keywords[flatAlias];\n if (v === undefined)\n continue;\n keywords[flatAlias] = typeof v === \"string\" ? { description: v } : v;\n }\n result.keywords = keywords;\n }\n else if (k === \"toJsonSchema\") {\n result[k] = mergeToJsonSchemaConfigs(base.toJsonSchema, merged.toJsonSchema);\n }\n else if (isNodeKind(k)) {\n result[k] =\n // not casting this makes TS compute a very inefficient\n // type that is not needed\n {\n ...base[k],\n ...merged[k]\n };\n }\n else\n result[k] = merged[k];\n }\n return result;\n};\nconst jsonSchemaTargetToDialect = {\n \"draft-2020-12\": \"https://json-schema.org/draft/2020-12/schema\",\n \"draft-07\": \"http://json-schema.org/draft-07/schema#\"\n};\nexport const mergeToJsonSchemaConfigs = ((baseConfig, mergedConfig) => {\n if (!baseConfig)\n return resolveTargetToDialect(mergedConfig ?? {}, undefined);\n if (!mergedConfig)\n return baseConfig;\n const result = { ...baseConfig };\n let k;\n for (k in mergedConfig) {\n if (k === \"fallback\") {\n result.fallback = mergeFallbacks(baseConfig.fallback, mergedConfig.fallback);\n }\n else\n result[k] = mergedConfig[k];\n }\n return resolveTargetToDialect(result, mergedConfig);\n});\nconst resolveTargetToDialect = (opts, userOpts) => {\n // If user explicitly provided a dialect, use it\n // Otherwise, if user provided a target, resolve it to dialect\n // If neither, use the default dialect from opts\n if (userOpts?.dialect !== undefined)\n return opts; // dialect was already merged\n if (userOpts?.target !== undefined) {\n return {\n ...opts,\n dialect: jsonSchemaTargetToDialect[userOpts.target]\n };\n }\n return opts;\n};\nconst mergeFallbacks = (base, merged) => {\n base = normalizeFallback(base);\n merged = normalizeFallback(merged);\n const result = {};\n let code;\n for (code in ToJsonSchema.defaultConfig.fallback) {\n result[code] =\n merged[code] ??\n merged.default ??\n base[code] ??\n base.default ??\n ToJsonSchema.defaultConfig.fallback[code];\n }\n return result;\n};\nconst normalizeFallback = (fallback) => typeof fallback === \"function\" ? { default: fallback } : (fallback ?? {});\n",
113
+ "import { CastableBase, ReadonlyArray, ReadonlyPath, append, conflatenateAll, defineProperties, flatMorph, stringifyPath } from \"@ark/util\";\nimport { arkKind } from \"./utils.js\";\nexport class ArkError extends CastableBase {\n [arkKind] = \"error\";\n path;\n data;\n nodeConfig;\n input;\n ctx;\n // TS gets confused by <code>, so internally we just use the base type for input\n constructor({ prefixPath, relativePath, ...input }, ctx) {\n super();\n this.input = input;\n this.ctx = ctx;\n defineProperties(this, input);\n const data = ctx.data;\n if (input.code === \"union\") {\n input.errors = input.errors.flatMap(innerError => {\n // flatten union errors to avoid repeating context like \"foo must be foo must be\"...\n const flat = innerError.hasCode(\"union\") ? innerError.errors : [innerError];\n if (!prefixPath && !relativePath)\n return flat;\n return flat.map(e => e.transform(e => ({\n ...e,\n path: conflatenateAll(prefixPath, e.path, relativePath)\n })));\n });\n }\n this.nodeConfig = ctx.config[this.code];\n const basePath = [...(input.path ?? ctx.path)];\n if (relativePath)\n basePath.push(...relativePath);\n if (prefixPath)\n basePath.unshift(...prefixPath);\n this.path = new ReadonlyPath(...basePath);\n this.data = \"data\" in input ? input.data : data;\n }\n transform(f) {\n return new ArkError(f({\n data: this.data,\n path: this.path,\n ...this.input\n }), this.ctx);\n }\n hasCode(code) {\n return this.code === code;\n }\n get propString() {\n return stringifyPath(this.path);\n }\n get expected() {\n if (this.input.expected)\n return this.input.expected;\n const config = this.meta?.expected ?? this.nodeConfig.expected;\n return typeof config === \"function\" ? config(this.input) : config;\n }\n get actual() {\n if (this.input.actual)\n return this.input.actual;\n const config = this.meta?.actual ?? this.nodeConfig.actual;\n return typeof config === \"function\" ? config(this.data) : config;\n }\n get problem() {\n if (this.input.problem)\n return this.input.problem;\n const config = this.meta?.problem ?? this.nodeConfig.problem;\n return typeof config === \"function\" ? config(this) : config;\n }\n get message() {\n if (this.input.message)\n return this.input.message;\n const config = this.meta?.message ?? this.nodeConfig.message;\n return typeof config === \"function\" ? config(this) : config;\n }\n get flat() {\n return this.hasCode(\"intersection\") ? [...this.errors] : [this];\n }\n toJSON() {\n return {\n data: this.data,\n path: this.path,\n ...this.input,\n expected: this.expected,\n actual: this.actual,\n problem: this.problem,\n message: this.message\n };\n }\n toString() {\n return this.message;\n }\n throw() {\n throw this;\n }\n}\n/**\n * A ReadonlyArray of `ArkError`s returned by a Type on invalid input.\n *\n * Subsequent errors added at an existing path are merged into an\n * ArkError intersection.\n */\nexport class ArkErrors extends ReadonlyArray {\n [arkKind] = \"errors\";\n ctx;\n constructor(ctx) {\n super();\n this.ctx = ctx;\n }\n /**\n * Errors by a pathString representing their location.\n */\n byPath = Object.create(null);\n /**\n * {@link byPath} flattened so that each value is an array of ArkError instances at that path.\n *\n * ✅ Since \"intersection\" errors will be flattened to their constituent `.errors`,\n * they will never be directly present in this representation.\n */\n get flatByPath() {\n return flatMorph(this.byPath, (k, v) => [k, v.flat]);\n }\n /**\n * {@link byPath} flattened so that each value is an array of problem strings at that path.\n */\n get flatProblemsByPath() {\n return flatMorph(this.byPath, (k, v) => [k, v.flat.map(e => e.problem)]);\n }\n /**\n * All pathStrings at which errors are present mapped to the errors occuring\n * at that path or any nested path within it.\n */\n byAncestorPath = Object.create(null);\n count = 0;\n mutable = this;\n /**\n * Throw a TraversalError based on these errors.\n */\n throw() {\n throw this.toTraversalError();\n }\n /**\n * Converts ArkErrors to TraversalError, a subclass of `Error` suitable for throwing with nice\n * formatting.\n */\n toTraversalError() {\n return new TraversalError(this);\n }\n /**\n * Append an ArkError to this array, ignoring duplicates.\n */\n add(error) {\n const existing = this.byPath[error.propString];\n if (existing) {\n if (error === existing)\n return;\n // If the existing error is an error for a value constrained to \"never\",\n // then we don't want to intersect the error messages.\n if (existing.hasCode(\"union\") && existing.errors.length === 0)\n return;\n // If the new error is an error for a value constrained to \"never\",\n // then we want to override any existing errors.\n const errorIntersection = error.hasCode(\"union\") && error.errors.length === 0 ?\n error\n : new ArkError({\n code: \"intersection\",\n errors: existing.hasCode(\"intersection\") ?\n [...existing.errors, error]\n : [existing, error]\n }, this.ctx);\n const existingIndex = this.indexOf(existing);\n this.mutable[existingIndex === -1 ? this.length : existingIndex] =\n errorIntersection;\n this.byPath[error.propString] = errorIntersection;\n // add the original error here rather than the intersection\n // since the intersection is reflected by the array of errors at\n // this path\n this.addAncestorPaths(error);\n }\n else {\n this.byPath[error.propString] = error;\n this.addAncestorPaths(error);\n this.mutable.push(error);\n }\n this.count++;\n }\n transform(f) {\n const result = new ArkErrors(this.ctx);\n for (const e of this)\n result.add(f(e));\n return result;\n }\n /**\n * Add all errors from an ArkErrors instance, ignoring duplicates and\n * prefixing their paths with that of the current Traversal.\n */\n merge(errors) {\n for (const e of errors) {\n this.add(new ArkError({ ...e, path: [...this.ctx.path, ...e.path] }, this.ctx));\n }\n }\n /**\n * @internal\n */\n affectsPath(path) {\n if (this.length === 0)\n return false;\n return (\n // this would occur if there is an existing error at a prefix of path\n // e.g. the path is [\"foo\", \"bar\"] and there is an error at [\"foo\"]\n path.stringifyAncestors().some(s => s in this.byPath) ||\n // this would occur if there is an existing error at a suffix of path\n // e.g. the path is [\"foo\"] and there is an error at [\"foo\", \"bar\"]\n path.stringify() in this.byAncestorPath);\n }\n /**\n * A human-readable summary of all errors.\n */\n get summary() {\n return this.toString();\n }\n /**\n * Alias of this ArkErrors instance for StandardSchema compatibility.\n */\n get issues() {\n return this;\n }\n toJSON() {\n return [...this.map(e => e.toJSON())];\n }\n toString() {\n return this.join(\"\\n\");\n }\n addAncestorPaths(error) {\n for (const propString of error.path.stringifyAncestors()) {\n this.byAncestorPath[propString] = append(this.byAncestorPath[propString], error);\n }\n }\n}\nexport class TraversalError extends Error {\n name = \"TraversalError\";\n constructor(errors) {\n if (errors.length === 1)\n super(errors.summary);\n else\n super(\"\\n\" + errors.map(error => ` • ${indent(error)}`).join(\"\\n\"));\n Object.defineProperty(this, \"arkErrors\", {\n value: errors,\n enumerable: false\n });\n }\n}\nconst indent = (error) => error.toString().split(\"\\n\").join(\"\\n \");\n",
114
+ "import { ReadonlyPath, stringifyPath } from \"@ark/util\";\nimport { ArkError, ArkErrors } from \"./errors.js\";\nimport { isNode } from \"./utils.js\";\nexport class Traversal {\n /**\n * #### the path being validated or morphed\n *\n * ✅ array indices represented as numbers\n * ⚠️ mutated during traversal - use `path.slice(0)` to snapshot\n * 🔗 use {@link propString} for a stringified version\n */\n path = [];\n /**\n * #### {@link ArkErrors} that will be part of this traversal's finalized result\n *\n * ✅ will always be an empty array for a valid traversal\n */\n errors = new ArkErrors(this);\n /**\n * #### the original value being traversed\n */\n root;\n /**\n * #### configuration for this traversal\n *\n * ✅ options can affect traversal results and error messages\n * ✅ defaults < global config < scope config\n * ✅ does not include options configured on individual types\n */\n config;\n queuedMorphs = [];\n branches = [];\n seen = {};\n constructor(root, config) {\n this.root = root;\n this.config = config;\n }\n /**\n * #### the data being validated or morphed\n *\n * ✅ extracted from {@link root} at {@link path}\n */\n get data() {\n let result = this.root;\n for (const segment of this.path)\n result = result?.[segment];\n return result;\n }\n /**\n * #### a string representing {@link path}\n *\n * @propString\n */\n get propString() {\n return stringifyPath(this.path);\n }\n /**\n * #### add an {@link ArkError} and return `false`\n *\n * ✅ useful for predicates like `.narrow`\n */\n reject(input) {\n this.error(input);\n return false;\n }\n /**\n * #### add an {@link ArkError} from a description and return `false`\n *\n * ✅ useful for predicates like `.narrow`\n * 🔗 equivalent to {@link reject}({ expected })\n */\n mustBe(expected) {\n this.error(expected);\n return false;\n }\n error(input) {\n const errCtx = typeof input === \"object\" ?\n input.code ?\n input\n : { ...input, code: \"predicate\" }\n : { code: \"predicate\", expected: input };\n return this.errorFromContext(errCtx);\n }\n /**\n * #### whether {@link currentBranch} (or the traversal root, outside a union) has one or more errors\n */\n hasError() {\n return this.currentErrorCount !== 0;\n }\n get currentBranch() {\n return this.branches[this.branches.length - 1];\n }\n queueMorphs(morphs) {\n const input = {\n path: new ReadonlyPath(...this.path),\n morphs\n };\n if (this.currentBranch)\n this.currentBranch.queuedMorphs.push(input);\n else\n this.queuedMorphs.push(input);\n }\n finalize(onFail) {\n if (this.queuedMorphs.length) {\n if (typeof this.root === \"object\" &&\n this.root !== null &&\n this.config.clone)\n this.root = this.config.clone(this.root);\n this.applyQueuedMorphs();\n }\n if (this.hasError())\n return onFail ? onFail(this.errors) : this.errors;\n return this.root;\n }\n get currentErrorCount() {\n return (this.currentBranch ?\n this.currentBranch.error ?\n 1\n : 0\n : this.errors.count);\n }\n get failFast() {\n return this.branches.length !== 0;\n }\n pushBranch() {\n this.branches.push({\n error: undefined,\n queuedMorphs: []\n });\n }\n popBranch() {\n return this.branches.pop();\n }\n /**\n * @internal\n * Convenience for casting from InternalTraversal to Traversal\n * for cases where the extra methods on the external type are expected, e.g.\n * a morph or predicate.\n */\n get external() {\n return this;\n }\n errorFromNodeContext(input) {\n return this.errorFromContext(input);\n }\n errorFromContext(errCtx) {\n const error = new ArkError(errCtx, this);\n if (this.currentBranch)\n this.currentBranch.error = error;\n else\n this.errors.add(error);\n return error;\n }\n applyQueuedMorphs() {\n // invoking morphs that are Nodes will reuse this context, potentially\n // adding additional morphs, so we have to continue looping until\n // queuedMorphs is empty rather than iterating over the list once\n while (this.queuedMorphs.length) {\n const queuedMorphs = this.queuedMorphs;\n this.queuedMorphs = [];\n for (const { path, morphs } of queuedMorphs) {\n // even if we already have an error, apply morphs that are not at a path\n // with errors to capture potential validation errors\n if (this.errors.affectsPath(path))\n continue;\n this.applyMorphsAtPath(path, morphs);\n }\n }\n }\n applyMorphsAtPath(path, morphs) {\n const key = path[path.length - 1];\n let parent;\n if (key !== undefined) {\n // find the object on which the key to be morphed exists\n parent = this.root;\n for (let pathIndex = 0; pathIndex < path.length - 1; pathIndex++)\n parent = parent[path[pathIndex]];\n }\n for (const morph of morphs) {\n // ensure morphs are applied relative to the correct path\n // in case previous operations modified this.path\n this.path = [...path];\n const morphIsNode = isNode(morph);\n const result = morph((parent === undefined ? this.root : parent[key]), this);\n if (result instanceof ArkError) {\n // if an ArkError was returned, ensure it has been added to errors\n // (it may have already been added via ctx.error() within the morph)\n // Only add if it's not already in the errors collection\n if (!this.errors.includes(result))\n this.errors.add(result);\n // skip any remaining morphs at the current path\n break;\n }\n if (result instanceof ArkErrors) {\n // if the morph was a direct reference to another node,\n // errors will have been added directly via this piped context\n if (!morphIsNode) {\n // otherwise, we have to ensure each error has been added\n this.errors.merge(result);\n }\n // skip any remaining morphs at the current path\n this.queuedMorphs = [];\n break;\n }\n // if the morph was successful, assign the result to the\n // corresponding property, or to root if path is empty\n if (parent === undefined)\n this.root = result;\n else\n parent[key] = result;\n // if the current morph queued additional morphs,\n // applying them before subsequent morphs\n this.applyQueuedMorphs();\n }\n }\n}\nexport const traverseKey = (key, fn, \n// ctx will be undefined if this node isn't context-dependent\nctx) => {\n if (!ctx)\n return fn();\n ctx.path.push(key);\n const result = fn();\n ctx.path.pop();\n return result;\n};\n",
115
+ "import { Callable, appendUnique, flatMorph, includes, isArray, isEmptyObject, isKeyOf, liftArray, printable, stringifyPath, throwError, throwInternalError } from \"@ark/util\";\nimport { basisKinds, constraintKinds, precedenceOfKind, refinementKinds, rootKinds, structuralKinds } from \"./shared/implement.js\";\nimport { $ark } from \"./shared/registry.js\";\nimport { Traversal } from \"./shared/traversal.js\";\nimport { isNode } from \"./shared/utils.js\";\nexport class BaseNode extends Callable {\n attachments;\n $;\n onFail;\n includesTransform;\n includesContextualPredicate;\n isCyclic;\n allowsRequiresContext;\n rootApplyStrategy;\n contextFreeMorph;\n rootApply;\n referencesById;\n shallowReferences;\n flatRefs;\n flatMorphs;\n allows;\n get shallowMorphs() {\n return [];\n }\n constructor(attachments, $) {\n super((data, pipedFromCtx, onFail = this.onFail) => {\n if (pipedFromCtx) {\n this.traverseApply(data, pipedFromCtx);\n return pipedFromCtx.hasError() ?\n pipedFromCtx.errors\n : pipedFromCtx.data;\n }\n return this.rootApply(data, onFail);\n }, { attach: attachments });\n this.attachments = attachments;\n this.$ = $;\n this.onFail = this.meta.onFail ?? this.$.resolvedConfig.onFail;\n this.includesTransform =\n this.hasKind(\"morph\") ||\n (this.hasKind(\"structure\") && this.structuralMorph !== undefined) ||\n (this.hasKind(\"sequence\") && this.inner.defaultables !== undefined);\n // if a predicate accepts exactly one arg, we can safely skip passing context\n // technically, a predicate could be written like `(data, ...[ctx]) => ctx.mustBe(\"malicious\")`\n // that would break here, but it feels like a pathological case and is better to let people optimize\n this.includesContextualPredicate =\n this.hasKind(\"predicate\") && this.inner.predicate.length !== 1;\n this.isCyclic = this.kind === \"alias\";\n this.referencesById = { [this.id]: this };\n this.shallowReferences =\n this.hasKind(\"structure\") ?\n [this, ...this.children]\n : this.children.reduce((acc, child) => appendUniqueNodes(acc, child.shallowReferences), [this]);\n const isStructural = this.isStructural();\n this.flatRefs = [];\n this.flatMorphs = [];\n for (let i = 0; i < this.children.length; i++) {\n this.includesTransform ||= this.children[i].includesTransform;\n this.includesContextualPredicate ||=\n this.children[i].includesContextualPredicate;\n this.isCyclic ||= this.children[i].isCyclic;\n if (!isStructural) {\n const childFlatRefs = this.children[i].flatRefs;\n for (let j = 0; j < childFlatRefs.length; j++) {\n const childRef = childFlatRefs[j];\n if (!this.flatRefs.some(existing => flatRefsAreEqual(existing, childRef))) {\n this.flatRefs.push(childRef);\n for (const branch of childRef.node.branches) {\n if (branch.hasKind(\"morph\") ||\n (branch.hasKind(\"intersection\") &&\n branch.structure?.structuralMorph !== undefined)) {\n this.flatMorphs.push({\n path: childRef.path,\n propString: childRef.propString,\n node: branch\n });\n }\n }\n }\n }\n }\n Object.assign(this.referencesById, this.children[i].referencesById);\n }\n this.flatRefs.sort((l, r) => l.path.length > r.path.length ? 1\n : l.path.length < r.path.length ? -1\n : l.propString > r.propString ? 1\n : l.propString < r.propString ? -1\n : l.node.expression < r.node.expression ? -1\n : 1);\n this.allowsRequiresContext =\n this.includesContextualPredicate || this.isCyclic;\n this.rootApplyStrategy =\n !this.allowsRequiresContext && this.flatMorphs.length === 0 ?\n this.shallowMorphs.length === 0 ? \"allows\"\n : (this.shallowMorphs.every(morph => morph.length === 1 || morph.name === \"$arkStructuralMorph\")) ?\n this.hasKind(\"union\") ?\n // multiple morphs not yet supported for optimistic compilation\n this.branches.some(branch => branch.shallowMorphs.length > 1) ?\n \"contextual\"\n : \"branchedOptimistic\"\n : this.shallowMorphs.length > 1 ? \"contextual\"\n : \"optimistic\"\n : \"contextual\"\n : \"contextual\";\n this.rootApply = this.createRootApply();\n this.allows =\n this.allowsRequiresContext ?\n data => this.traverseAllows(data, new Traversal(data, this.$.resolvedConfig))\n : data => this.traverseAllows(data);\n }\n createRootApply() {\n switch (this.rootApplyStrategy) {\n case \"allows\":\n return (data, onFail) => {\n if (this.allows(data))\n return data;\n const ctx = new Traversal(data, this.$.resolvedConfig);\n this.traverseApply(data, ctx);\n return ctx.finalize(onFail);\n };\n case \"contextual\":\n return (data, onFail) => {\n const ctx = new Traversal(data, this.$.resolvedConfig);\n this.traverseApply(data, ctx);\n return ctx.finalize(onFail);\n };\n case \"optimistic\":\n this.contextFreeMorph = this.shallowMorphs[0];\n const clone = this.$.resolvedConfig.clone;\n return (data, onFail) => {\n if (this.allows(data)) {\n return this.contextFreeMorph((clone &&\n ((typeof data === \"object\" && data !== null) ||\n typeof data === \"function\")) ?\n clone(data)\n : data);\n }\n const ctx = new Traversal(data, this.$.resolvedConfig);\n this.traverseApply(data, ctx);\n return ctx.finalize(onFail);\n };\n case \"branchedOptimistic\":\n return this.createBranchedOptimisticRootApply();\n default:\n this.rootApplyStrategy;\n return throwInternalError(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`);\n }\n }\n compiledMeta = compileMeta(this.metaJson);\n cacheGetter(name, value) {\n Object.defineProperty(this, name, { value });\n return value;\n }\n get description() {\n return this.cacheGetter(\"description\", this.meta?.description ??\n this.$.resolvedConfig[this.kind].description(this));\n }\n // we don't cache this currently since it can be updated once a scope finishes\n // resolving cyclic references, although it may be possible to ensure it is cached safely\n get references() {\n return Object.values(this.referencesById);\n }\n precedence = precedenceOfKind(this.kind);\n precompilation;\n // defined as an arrow function since it is often detached, e.g. when passing to tRPC\n // otherwise, would run into issues with this binding\n assert = (data, pipedFromCtx) => this(data, pipedFromCtx, errors => errors.throw());\n traverse(data, pipedFromCtx) {\n return this(data, pipedFromCtx, null);\n }\n /** rawIn should be used internally instead */\n get in() {\n // ensure the node has been finalized if in is being used externally\n return this.cacheGetter(\"in\", this.rawIn.isRoot() ? this.$.finalize(this.rawIn) : this.rawIn);\n }\n get rawIn() {\n return this.cacheGetter(\"rawIn\", this.getIo(\"in\"));\n }\n /** rawOut should be used internally instead */\n get out() {\n // ensure the node has been finalized if out is being used externally\n return this.cacheGetter(\"out\", this.rawOut.isRoot() ? this.$.finalize(this.rawOut) : this.rawOut);\n }\n get rawOut() {\n return this.cacheGetter(\"rawOut\", this.getIo(\"out\"));\n }\n // Should be refactored to use transform\n // https://github.com/arktypeio/arktype/issues/1020\n getIo(ioKind) {\n if (!this.includesTransform)\n return this;\n const ioInner = {};\n for (const [k, v] of this.innerEntries) {\n const keySchemaImplementation = this.impl.keys[k];\n if (keySchemaImplementation.reduceIo)\n keySchemaImplementation.reduceIo(ioKind, ioInner, v);\n else if (keySchemaImplementation.child) {\n const childValue = v;\n ioInner[k] =\n isArray(childValue) ?\n childValue.map(child => ioKind === \"in\" ? child.rawIn : child.rawOut)\n : ioKind === \"in\" ? childValue.rawIn\n : childValue.rawOut;\n }\n else\n ioInner[k] = v;\n }\n return this.$.node(this.kind, ioInner);\n }\n toJSON() {\n return this.json;\n }\n toString() {\n return `Type<${this.expression}>`;\n }\n equals(r) {\n const rNode = isNode(r) ? r : this.$.parseDefinition(r);\n return this.innerHash === rNode.innerHash;\n }\n ifEquals(r) {\n return this.equals(r) ? this : undefined;\n }\n hasKind(kind) {\n return this.kind === kind;\n }\n assertHasKind(kind) {\n if (this.kind !== kind)\n throwError(`${this.kind} node was not of asserted kind ${kind}`);\n return this;\n }\n hasKindIn(...kinds) {\n return kinds.includes(this.kind);\n }\n assertHasKindIn(...kinds) {\n if (!includes(kinds, this.kind))\n throwError(`${this.kind} node was not one of asserted kinds ${kinds}`);\n return this;\n }\n isBasis() {\n return includes(basisKinds, this.kind);\n }\n isConstraint() {\n return includes(constraintKinds, this.kind);\n }\n isStructural() {\n return includes(structuralKinds, this.kind);\n }\n isRefinement() {\n return includes(refinementKinds, this.kind);\n }\n isRoot() {\n return includes(rootKinds, this.kind);\n }\n isUnknown() {\n return this.hasKind(\"intersection\") && this.children.length === 0;\n }\n isNever() {\n return this.hasKind(\"union\") && this.children.length === 0;\n }\n hasUnit(value) {\n return this.hasKind(\"unit\") && this.allows(value);\n }\n hasOpenIntersection() {\n return this.impl.intersectionIsOpen;\n }\n get nestableExpression() {\n return this.expression;\n }\n select(selector) {\n const normalized = NodeSelector.normalize(selector);\n return this._select(normalized);\n }\n _select(selector) {\n let nodes = NodeSelector.applyBoundary[selector.boundary ?? \"references\"](this);\n if (selector.kind)\n nodes = nodes.filter(n => n.kind === selector.kind);\n if (selector.where)\n nodes = nodes.filter(selector.where);\n return NodeSelector.applyMethod[selector.method ?? \"filter\"](nodes, this, selector);\n }\n transform(mapper, opts) {\n return this._transform(mapper, this._createTransformContext(opts));\n }\n _createTransformContext(opts) {\n return {\n root: this,\n selected: undefined,\n seen: {},\n path: [],\n parseOptions: {\n prereduced: opts?.prereduced ?? false\n },\n undeclaredKeyHandling: undefined,\n ...opts\n };\n }\n _transform(mapper, ctx) {\n const $ = ctx.bindScope ?? this.$;\n if (ctx.seen[this.id])\n // Cyclic handling needs to be made more robust\n // https://github.com/arktypeio/arktype/issues/944\n return this.$.lazilyResolve(ctx.seen[this.id]);\n if (ctx.shouldTransform?.(this, ctx) === false)\n return this;\n let transformedNode;\n ctx.seen[this.id] = () => transformedNode;\n if (this.hasKind(\"structure\") &&\n this.undeclared !== ctx.undeclaredKeyHandling) {\n ctx = {\n ...ctx,\n undeclaredKeyHandling: this.undeclared\n };\n }\n const innerWithTransformedChildren = flatMorph(this.inner, (k, v) => {\n if (!this.impl.keys[k].child)\n return [k, v];\n const children = v;\n if (!isArray(children)) {\n const transformed = children._transform(mapper, ctx);\n return transformed ? [k, transformed] : [];\n }\n // if the value was previously explicitly set to an empty list,\n // (e.g. branches for `never`), ensure it is not pruned\n if (children.length === 0)\n return [k, v];\n const transformed = children.flatMap(n => {\n const transformedChild = n._transform(mapper, ctx);\n return transformedChild ?? [];\n });\n return transformed.length ? [k, transformed] : [];\n });\n delete ctx.seen[this.id];\n const innerWithMeta = Object.assign(innerWithTransformedChildren, {\n meta: this.meta\n });\n const transformedInner = ctx.selected && !ctx.selected.includes(this) ?\n innerWithMeta\n : mapper(this.kind, innerWithMeta, ctx);\n if (transformedInner === null)\n return null;\n if (isNode(transformedInner))\n return (transformedNode = transformedInner);\n const transformedKeys = Object.keys(transformedInner);\n const hasNoTypedKeys = transformedKeys.length === 0 ||\n (transformedKeys.length === 1 && transformedKeys[0] === \"meta\");\n if (hasNoTypedKeys &&\n // if inner was previously an empty object (e.g. unknown) ensure it is not pruned\n !isEmptyObject(this.inner))\n return null;\n if ((this.kind === \"required\" ||\n this.kind === \"optional\" ||\n this.kind === \"index\") &&\n !(\"value\" in transformedInner)) {\n return ctx.undeclaredKeyHandling ?\n { ...transformedInner, value: $ark.intrinsic.unknown }\n : null;\n }\n if (this.kind === \"morph\") {\n ;\n transformedInner.in ??= $ark.intrinsic\n .unknown;\n }\n return (transformedNode = $.node(this.kind, transformedInner, ctx.parseOptions));\n }\n configureReferences(meta, selector = \"references\") {\n const normalized = NodeSelector.normalize(selector);\n const mapper = (typeof meta === \"string\" ?\n (kind, inner) => ({\n ...inner,\n meta: { ...inner.meta, description: meta }\n })\n : typeof meta === \"function\" ?\n (kind, inner) => ({ ...inner, meta: meta(inner.meta) })\n : (kind, inner) => ({\n ...inner,\n meta: { ...inner.meta, ...meta }\n }));\n if (normalized.boundary === \"self\") {\n return this.$.node(this.kind, mapper(this.kind, { ...this.inner, meta: this.meta }));\n }\n const rawSelected = this._select(normalized);\n const selected = rawSelected && liftArray(rawSelected);\n const shouldTransform = normalized.boundary === \"child\" ?\n (node, ctx) => ctx.root.children.includes(node)\n : normalized.boundary === \"shallow\" ? node => node.kind !== \"structure\"\n : () => true;\n return this.$.finalize(this.transform(mapper, {\n shouldTransform,\n selected\n }));\n }\n}\nconst NodeSelector = {\n applyBoundary: {\n self: node => [node],\n child: node => [...node.children],\n shallow: node => [...node.shallowReferences],\n references: node => [...node.references]\n },\n applyMethod: {\n filter: nodes => nodes,\n assertFilter: (nodes, from, selector) => {\n if (nodes.length === 0)\n throwError(writeSelectAssertionMessage(from, selector));\n return nodes;\n },\n find: nodes => nodes[0],\n assertFind: (nodes, from, selector) => {\n if (nodes.length === 0)\n throwError(writeSelectAssertionMessage(from, selector));\n return nodes[0];\n }\n },\n normalize: (selector) => typeof selector === \"function\" ?\n { boundary: \"references\", method: \"filter\", where: selector }\n : typeof selector === \"string\" ?\n isKeyOf(selector, NodeSelector.applyBoundary) ?\n { method: \"filter\", boundary: selector }\n : { boundary: \"references\", method: \"filter\", kind: selector }\n : { boundary: \"references\", method: \"filter\", ...selector }\n};\nconst writeSelectAssertionMessage = (from, selector) => `${from} had no references matching ${printable(selector)}.`;\nexport const typePathToPropString = (path) => stringifyPath(path, {\n stringifyNonKey: node => node.expression\n});\nconst referenceMatcher = /\"(\\$ark\\.[^\"]+)\"/g;\nconst compileMeta = (metaJson) => JSON.stringify(metaJson).replace(referenceMatcher, \"$1\");\nexport const flatRef = (path, node) => ({\n path,\n node,\n propString: typePathToPropString(path)\n});\nexport const flatRefsAreEqual = (l, r) => l.propString === r.propString && l.node.equals(r.node);\nexport const appendUniqueFlatRefs = (existing, refs) => appendUnique(existing, refs, {\n isEqual: flatRefsAreEqual\n});\nexport const appendUniqueNodes = (existing, refs) => appendUnique(existing, refs, {\n isEqual: (l, r) => l.equals(r)\n});\n",
116
+ "import { isArray, stringifyPath, throwParseError } from \"@ark/util\";\nimport { $ark } from \"./registry.js\";\nimport { isNode } from \"./utils.js\";\nexport class Disjoint extends Array {\n static init(kind, l, r, ctx) {\n return new Disjoint({\n kind,\n l,\n r,\n path: ctx?.path ?? [],\n optional: ctx?.optional ?? false\n });\n }\n add(kind, l, r, ctx) {\n this.push({\n kind,\n l,\n r,\n path: ctx?.path ?? [],\n optional: ctx?.optional ?? false\n });\n return this;\n }\n get summary() {\n return this.describeReasons();\n }\n describeReasons() {\n if (this.length === 1) {\n const { path, l, r } = this[0];\n const pathString = stringifyPath(path);\n return writeUnsatisfiableExpressionError(`Intersection${pathString && ` at ${pathString}`} of ${describeReasons(l, r)}`);\n }\n return `The following intersections result in unsatisfiable types:\\n• ${this.map(({ path, l, r }) => `${path}: ${describeReasons(l, r)}`).join(\"\\n• \")}`;\n }\n throw() {\n return throwParseError(this.describeReasons());\n }\n invert() {\n const result = this.map(entry => ({\n ...entry,\n l: entry.r,\n r: entry.l\n }));\n // Workaround for Static Hermes, which doesn't preserve the Array subclass here\n // https://github.com/arktypeio/arktype/issues/1027\n if (!(result instanceof Disjoint))\n return new Disjoint(...result);\n return result;\n }\n withPrefixKey(key, kind) {\n return this.map(entry => ({\n ...entry,\n path: [key, ...entry.path],\n optional: entry.optional || kind === \"optional\"\n }));\n }\n toNeverIfDisjoint() {\n return $ark.intrinsic.never;\n }\n}\nconst describeReasons = (l, r) => `${describeReason(l)} and ${describeReason(r)}`;\nconst describeReason = (value) => isNode(value) ? value.expression\n : isArray(value) ? value.map(describeReason).join(\" | \") || \"never\"\n : String(value);\nexport const writeUnsatisfiableExpressionError = (expression) => `${expression} results in an unsatisfiable type`;\n",
117
+ "import { Disjoint } from \"./disjoint.js\";\nimport { rootKinds } from \"./implement.js\";\nimport { isNode } from \"./utils.js\";\nconst intersectionCache = {};\nexport const intersectNodesRoot = (l, r, $) => intersectOrPipeNodes(l, r, {\n $,\n invert: false,\n pipe: false\n});\nexport const pipeNodesRoot = (l, r, $) => intersectOrPipeNodes(l, r, {\n $,\n invert: false,\n pipe: true\n});\nexport const intersectOrPipeNodes = ((l, r, ctx) => {\n const operator = ctx.pipe ? \"|>\" : \"&\";\n const lrCacheKey = `${l.hash}${operator}${r.hash}`;\n if (intersectionCache[lrCacheKey] !== undefined)\n return intersectionCache[lrCacheKey];\n if (!ctx.pipe) {\n // we can only use this for the commutative & operator\n const rlCacheKey = `${r.hash}${operator}${l.hash}`;\n if (intersectionCache[rlCacheKey] !== undefined) {\n // if the cached result was a Disjoint and the operands originally\n // appeared in the opposite order, we need to invert it to match\n const rlResult = intersectionCache[rlCacheKey];\n const lrResult = rlResult instanceof Disjoint ? rlResult.invert() : rlResult;\n // add the lr result to the cache directly to bypass this check in the future\n intersectionCache[lrCacheKey] = lrResult;\n return lrResult;\n }\n }\n const isPureIntersection = !ctx.pipe || (!l.includesTransform && !r.includesTransform);\n if (isPureIntersection && l.equals(r))\n return l;\n let result = isPureIntersection ? _intersectNodes(l, r, ctx)\n : l.hasKindIn(...rootKinds) ?\n // if l is a RootNode, r will be as well\n _pipeNodes(l, r, ctx)\n : _intersectNodes(l, r, ctx);\n if (isNode(result)) {\n // if the result equals one of the operands, preserve its metadata by\n // returning the original reference\n if (l.equals(result))\n result = l;\n else if (r.equals(result))\n result = r;\n }\n intersectionCache[lrCacheKey] = result;\n return result;\n});\nconst _intersectNodes = (l, r, ctx) => {\n const leftmostKind = l.precedence < r.precedence ? l.kind : r.kind;\n const implementation = l.impl.intersections[r.kind] ?? r.impl.intersections[l.kind];\n if (implementation === undefined) {\n // should be two ConstraintNodes that have no relation\n // this could also happen if a user directly intersects a Type and a ConstraintNode,\n // but that is not allowed by the external function signature\n return null;\n }\n else if (leftmostKind === l.kind)\n return implementation(l, r, ctx);\n else {\n let result = implementation(r, l, { ...ctx, invert: !ctx.invert });\n if (result instanceof Disjoint)\n result = result.invert();\n return result;\n }\n};\nconst _pipeNodes = (l, r, ctx) => l.includesTransform || r.includesTransform ?\n ctx.invert ?\n pipeMorphed(r, l, ctx)\n : pipeMorphed(l, r, ctx)\n : _intersectNodes(l, r, ctx);\nconst pipeMorphed = (from, to, ctx) => from.distribute(fromBranch => _pipeMorphed(fromBranch, to, ctx), results => {\n const viableBranches = results.filter(isNode);\n if (viableBranches.length === 0)\n return Disjoint.init(\"union\", from.branches, to.branches);\n // if the input type has changed, create a new node without preserving metadata\n if (viableBranches.length < from.branches.length ||\n !from.branches.every((branch, i) => branch.rawIn.equals(viableBranches[i].rawIn)))\n return ctx.$.parseSchema(viableBranches);\n // otherwise, the input has not changed so preserve metadata\n let meta;\n if (viableBranches.length === 1) {\n const onlyBranch = viableBranches[0];\n if (!meta)\n return onlyBranch;\n return ctx.$.node(\"morph\", {\n ...onlyBranch.inner,\n in: onlyBranch.rawIn.configure(meta, \"self\")\n });\n }\n const schema = {\n branches: viableBranches\n };\n if (meta)\n schema.meta = meta;\n return ctx.$.parseSchema(schema);\n});\nconst _pipeMorphed = (from, to, ctx) => {\n const fromIsMorph = from.hasKind(\"morph\");\n if (fromIsMorph) {\n const morphs = [...from.morphs];\n if (from.lastMorphIfNode) {\n // still piped from context, so allows appending additional morphs\n const outIntersection = intersectOrPipeNodes(from.lastMorphIfNode, to, ctx);\n if (outIntersection instanceof Disjoint)\n return outIntersection;\n morphs[morphs.length - 1] = outIntersection;\n }\n else\n morphs.push(to);\n return ctx.$.node(\"morph\", {\n morphs,\n in: from.inner.in\n });\n }\n if (to.hasKind(\"morph\")) {\n const inTersection = intersectOrPipeNodes(from, to.rawIn, ctx);\n if (inTersection instanceof Disjoint)\n return inTersection;\n return ctx.$.node(\"morph\", {\n morphs: [to],\n in: inTersection\n });\n }\n return ctx.$.node(\"morph\", {\n morphs: [to],\n in: from\n });\n};\n",
118
+ "import { append, appendUnique, capitalize, isArray, throwInternalError, throwParseError } from \"@ark/util\";\nimport { BaseNode } from \"./node.js\";\nimport { Disjoint } from \"./shared/disjoint.js\";\nimport { compileObjectLiteral, constraintKeys } from \"./shared/implement.js\";\nimport { intersectNodesRoot, intersectOrPipeNodes } from \"./shared/intersections.js\";\nimport { $ark } from \"./shared/registry.js\";\nimport { arkKind } from \"./shared/utils.js\";\nexport class BaseConstraint extends BaseNode {\n constructor(attachments, $) {\n super(attachments, $);\n // define as a getter to avoid it being enumerable/spreadable\n Object.defineProperty(this, arkKind, {\n value: \"constraint\",\n enumerable: false\n });\n }\n impliedSiblings;\n intersect(r) {\n return intersectNodesRoot(this, r, this.$);\n }\n}\nexport class InternalPrimitiveConstraint extends BaseConstraint {\n traverseApply = (data, ctx) => {\n if (!this.traverseAllows(data, ctx))\n ctx.errorFromNodeContext(this.errorContext);\n };\n compile(js) {\n if (js.traversalKind === \"Allows\")\n js.return(this.compiledCondition);\n else {\n js.if(this.compiledNegation, () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`));\n }\n }\n get errorContext() {\n return {\n code: this.kind,\n description: this.description,\n meta: this.meta,\n ...this.inner\n };\n }\n get compiledErrorContext() {\n return compileObjectLiteral(this.errorContext);\n }\n}\nexport const constraintKeyParser = (kind) => (schema, ctx) => {\n if (isArray(schema)) {\n if (schema.length === 0) {\n // Omit empty lists as input\n return;\n }\n const nodes = schema.map(schema => ctx.$.node(kind, schema));\n // predicate order must be preserved to ensure inputs are narrowed\n // and checked in the correct order\n if (kind === \"predicate\")\n return nodes;\n return nodes.sort((l, r) => (l.hash < r.hash ? -1 : 1));\n }\n const child = ctx.$.node(kind, schema);\n return (child.hasOpenIntersection() ? [child] : child);\n};\nexport const intersectConstraints = (s) => {\n const head = s.r.shift();\n if (!head) {\n let result = s.l.length === 0 && s.kind === \"structure\" ?\n $ark.intrinsic.unknown.internal\n : s.ctx.$.node(s.kind, Object.assign(s.baseInner, unflattenConstraints(s.l)), { prereduced: true });\n for (const root of s.roots) {\n if (result instanceof Disjoint)\n return result;\n result = intersectOrPipeNodes(root, result, s.ctx);\n }\n return result;\n }\n let matched = false;\n for (let i = 0; i < s.l.length; i++) {\n const result = intersectOrPipeNodes(s.l[i], head, s.ctx);\n if (result === null)\n continue;\n if (result instanceof Disjoint)\n return result;\n if (result.isRoot()) {\n s.roots.push(result);\n s.l.splice(i);\n return intersectConstraints(s);\n }\n if (!matched) {\n s.l[i] = result;\n matched = true;\n }\n else if (!s.l.includes(result)) {\n return throwInternalError(`Unexpectedly encountered multiple distinct intersection results for refinement ${head}`);\n }\n }\n if (!matched)\n s.l.push(head);\n if (s.kind === \"intersection\") {\n if (head.impliedSiblings)\n for (const node of head.impliedSiblings)\n appendUnique(s.r, node);\n }\n return intersectConstraints(s);\n};\nexport const flattenConstraints = (inner) => {\n const result = Object.entries(inner)\n .flatMap(([k, v]) => k in constraintKeys ? v : [])\n .sort((l, r) => l.precedence < r.precedence ? -1\n : l.precedence > r.precedence ? 1\n // preserve order for predicates\n : l.kind === \"predicate\" && r.kind === \"predicate\" ? 0\n : l.hash < r.hash ? -1\n : 1);\n return result;\n};\nexport const unflattenConstraints = (constraints) => {\n const inner = {};\n for (const constraint of constraints) {\n if (constraint.hasOpenIntersection()) {\n inner[constraint.kind] = append(inner[constraint.kind], constraint);\n }\n else {\n if (inner[constraint.kind]) {\n return throwInternalError(`Unexpected intersection of closed refinements of kind ${constraint.kind}`);\n }\n inner[constraint.kind] = constraint;\n }\n }\n return inner;\n};\nexport const throwInvalidOperandError = (...args) => throwParseError(writeInvalidOperandMessage(...args));\nexport const writeInvalidOperandMessage = (kind, expected, actual) => {\n const actualDescription = actual.hasKind(\"morph\") ? \"a morph\"\n : actual.isUnknown() ? \"unknown\"\n : actual.exclude(expected).defaultShortDescription;\n return `${capitalize(kind)} operand must be ${expected.description} (was ${actualDescription})`;\n};\n",
119
+ "import { Callable, flatMorph, snapshot, throwParseError } from \"@ark/util\";\nimport { $ark } from \"./shared/registry.js\";\nimport { arkKind } from \"./shared/utils.js\";\nexport const parseGeneric = (paramDefs, bodyDef, $) => new GenericRoot(paramDefs, bodyDef, $, $, null);\nexport class LazyGenericBody extends Callable {\n}\nexport class GenericRoot extends Callable {\n [arkKind] = \"generic\";\n paramDefs;\n bodyDef;\n $;\n arg$;\n baseInstantiation;\n hkt;\n description;\n constructor(paramDefs, bodyDef, $, arg$, hkt) {\n super((...args) => {\n const argNodes = flatMorph(this.names, (i, name) => {\n const arg = this.arg$.parse(args[i]);\n if (!arg.extends(this.constraints[i])) {\n throwParseError(writeUnsatisfiedParameterConstraintMessage(name, this.constraints[i].expression, arg.expression));\n }\n return [name, arg];\n });\n if (this.defIsLazy()) {\n const def = this.bodyDef(argNodes);\n return this.$.parse(def);\n }\n return this.$.parse(bodyDef, { args: argNodes });\n });\n this.paramDefs = paramDefs;\n this.bodyDef = bodyDef;\n this.$ = $;\n this.arg$ = arg$;\n this.hkt = hkt;\n this.description =\n hkt ?\n (new hkt().description ?? `a generic type for ${hkt.constructor.name}`)\n : \"a generic type\";\n this.baseInstantiation = this(...this.constraints);\n }\n defIsLazy() {\n return this.bodyDef instanceof LazyGenericBody;\n }\n cacheGetter(name, value) {\n Object.defineProperty(this, name, { value });\n return value;\n }\n get json() {\n return this.cacheGetter(\"json\", {\n params: this.params.map(param => param[1].isUnknown() ? param[0] : [param[0], param[1].json]),\n body: snapshot(this.bodyDef)\n });\n }\n get params() {\n return this.cacheGetter(\"params\", this.paramDefs.map(param => typeof param === \"string\" ?\n [param, $ark.intrinsic.unknown]\n : [param[0], this.$.parse(param[1])]));\n }\n get names() {\n return this.cacheGetter(\"names\", this.params.map(e => e[0]));\n }\n get constraints() {\n return this.cacheGetter(\"constraints\", this.params.map(e => e[1]));\n }\n get internal() {\n return this;\n }\n get referencesById() {\n return this.baseInstantiation.internal.referencesById;\n }\n get references() {\n return this.baseInstantiation.internal.references;\n }\n}\nexport const writeUnsatisfiedParameterConstraintMessage = (name, constraint, arg) => `${name} must be assignable to ${constraint} (was ${arg})`;\n",
120
+ "import { BaseConstraint } from \"./constraint.js\";\nimport { compileObjectLiteral, implementNode } from \"./shared/implement.js\";\nimport { registeredReference } from \"./shared/registry.js\";\nconst implementation = implementNode({\n kind: \"predicate\",\n hasAssociatedError: true,\n collapsibleKey: \"predicate\",\n keys: {\n predicate: {}\n },\n normalize: schema => typeof schema === \"function\" ? { predicate: schema } : schema,\n defaults: {\n description: node => `valid according to ${node.predicate.name || \"an anonymous predicate\"}`\n },\n intersectionIsOpen: true,\n intersections: {\n // as long as the narrows in l and r are individually safe to check\n // in the order they're specified, checking them in the order\n // resulting from this intersection should also be safe.\n predicate: () => null\n }\n});\nexport class PredicateNode extends BaseConstraint {\n serializedPredicate = registeredReference(this.predicate);\n compiledCondition = `${this.serializedPredicate}(data, ctx)`;\n compiledNegation = `!${this.compiledCondition}`;\n impliedBasis = null;\n expression = this.serializedPredicate;\n traverseAllows = this.predicate;\n errorContext = {\n code: \"predicate\",\n description: this.description,\n meta: this.meta\n };\n compiledErrorContext = compileObjectLiteral(this.errorContext);\n traverseApply = (data, ctx) => {\n const errorCount = ctx.currentErrorCount;\n if (!this.predicate(data, ctx.external) &&\n ctx.currentErrorCount === errorCount)\n ctx.errorFromNodeContext(this.errorContext);\n };\n compile(js) {\n if (js.traversalKind === \"Allows\") {\n js.return(this.compiledCondition);\n return;\n }\n js.initializeErrorCount();\n js.if(\n // only add the default error if the predicate didn't add one itself\n `${this.compiledNegation} && ctx.currentErrorCount === errorCount`, () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`));\n }\n reduceJsonSchema(base, ctx) {\n return ctx.fallback.predicate({\n code: \"predicate\",\n base,\n predicate: this.predicate\n });\n }\n}\nexport const Predicate = {\n implementation,\n Node: PredicateNode\n};\n",
121
+ "import { throwParseError } from \"@ark/util\";\nimport { InternalPrimitiveConstraint, writeInvalidOperandMessage } from \"../constraint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nconst implementation = implementNode({\n kind: \"divisor\",\n collapsibleKey: \"rule\",\n keys: {\n rule: {\n parse: divisor => Number.isInteger(divisor) ? divisor : (throwParseError(writeNonIntegerDivisorMessage(divisor)))\n }\n },\n normalize: schema => typeof schema === \"number\" ? { rule: schema } : schema,\n hasAssociatedError: true,\n defaults: {\n description: node => node.rule === 1 ? \"an integer\"\n : node.rule === 2 ? \"even\"\n : `a multiple of ${node.rule}`\n },\n intersections: {\n divisor: (l, r, ctx) => ctx.$.node(\"divisor\", {\n rule: Math.abs((l.rule * r.rule) / greatestCommonDivisor(l.rule, r.rule))\n })\n },\n obviatesBasisDescription: true\n});\nexport class DivisorNode extends InternalPrimitiveConstraint {\n traverseAllows = data => data % this.rule === 0;\n compiledCondition = `data % ${this.rule} === 0`;\n compiledNegation = `data % ${this.rule} !== 0`;\n impliedBasis = $ark.intrinsic.number.internal;\n expression = `% ${this.rule}`;\n reduceJsonSchema(schema) {\n schema.type = \"integer\";\n if (this.rule === 1)\n return schema;\n schema.multipleOf = this.rule;\n return schema;\n }\n}\nexport const Divisor = {\n implementation,\n Node: DivisorNode\n};\nexport const writeIndivisibleMessage = (t) => writeInvalidOperandMessage(\"divisor\", $ark.intrinsic.number, t);\nexport const writeNonIntegerDivisorMessage = (divisor) => `divisor must be an integer (was ${divisor})`;\n// https://en.wikipedia.org/wiki/Euclidean_algorithm\nconst greatestCommonDivisor = (l, r) => {\n let previous;\n let greatestCommonDivisor = l;\n let current = r;\n while (current !== 0) {\n previous = current;\n current = greatestCommonDivisor % current;\n greatestCommonDivisor = previous;\n }\n return greatestCommonDivisor;\n};\n",
122
+ "import { isKeyOf, throwParseError } from \"@ark/util\";\nimport { InternalPrimitiveConstraint } from \"../constraint.js\";\nexport class BaseRange extends InternalPrimitiveConstraint {\n boundOperandKind = operandKindsByBoundKind[this.kind];\n compiledActual = this.boundOperandKind === \"value\" ? `data`\n : this.boundOperandKind === \"length\" ? `data.length`\n : `data.valueOf()`;\n comparator = compileComparator(this.kind, this.exclusive);\n numericLimit = this.rule.valueOf();\n expression = `${this.comparator} ${this.rule}`;\n compiledCondition = `${this.compiledActual} ${this.comparator} ${this.numericLimit}`;\n compiledNegation = `${this.compiledActual} ${negatedComparators[this.comparator]} ${this.numericLimit}`;\n // we need to compute stringLimit before errorContext, which references it\n // transitively through description for date bounds\n stringLimit = this.boundOperandKind === \"date\" ?\n dateLimitToString(this.numericLimit)\n : `${this.numericLimit}`;\n limitKind = this.comparator[\"0\"] === \"<\" ? \"upper\" : \"lower\";\n isStricterThan(r) {\n const thisLimitIsStricter = this.limitKind === \"upper\" ?\n this.numericLimit < r.numericLimit\n : this.numericLimit > r.numericLimit;\n return (thisLimitIsStricter ||\n (this.numericLimit === r.numericLimit &&\n this.exclusive === true &&\n !r.exclusive));\n }\n overlapsRange(r) {\n if (this.isStricterThan(r))\n return false;\n if (this.numericLimit === r.numericLimit && (this.exclusive || r.exclusive))\n return false;\n return true;\n }\n overlapIsUnit(r) {\n return (this.numericLimit === r.numericLimit && !this.exclusive && !r.exclusive);\n }\n}\nconst negatedComparators = {\n \"<\": \">=\",\n \"<=\": \">\",\n \">\": \"<=\",\n \">=\": \"<\"\n};\nexport const boundKindPairsByLower = {\n min: \"max\",\n minLength: \"maxLength\",\n after: \"before\"\n};\nexport const parseExclusiveKey = {\n // omit key with value false since it is the default\n parse: (flag) => flag || undefined\n};\nexport const createLengthSchemaNormalizer = (kind) => (schema) => {\n if (typeof schema === \"number\")\n return { rule: schema };\n const { exclusive, ...normalized } = schema;\n return exclusive ?\n {\n ...normalized,\n rule: kind === \"minLength\" ? normalized.rule + 1 : normalized.rule - 1\n }\n : normalized;\n};\nexport const createDateSchemaNormalizer = (kind) => (schema) => {\n if (typeof schema === \"number\" ||\n typeof schema === \"string\" ||\n schema instanceof Date)\n return { rule: schema };\n const { exclusive, ...normalized } = schema;\n if (!exclusive)\n return normalized;\n const numericLimit = typeof normalized.rule === \"number\" ? normalized.rule\n : typeof normalized.rule === \"string\" ?\n new Date(normalized.rule).valueOf()\n : normalized.rule.valueOf();\n return exclusive ?\n {\n ...normalized,\n rule: kind === \"after\" ? numericLimit + 1 : numericLimit - 1\n }\n : normalized;\n};\nexport const parseDateLimit = (limit) => typeof limit === \"string\" || typeof limit === \"number\" ?\n new Date(limit)\n : limit;\nexport const writeInvalidLengthBoundMessage = (kind, limit) => `${kind} bound must be a positive integer (was ${limit})`;\nexport const createLengthRuleParser = (kind) => (limit) => {\n if (!Number.isInteger(limit) || limit < 0)\n throwParseError(writeInvalidLengthBoundMessage(kind, limit));\n return limit;\n};\nconst operandKindsByBoundKind = {\n min: \"value\",\n max: \"value\",\n minLength: \"length\",\n maxLength: \"length\",\n after: \"date\",\n before: \"date\"\n};\nexport const compileComparator = (kind, exclusive) => `${isKeyOf(kind, boundKindPairsByLower) ? \">\" : \"<\"}${exclusive ? \"\" : \"=\"}`;\nexport const dateLimitToString = (limit) => typeof limit === \"string\" ? limit : new Date(limit).toLocaleString();\nexport const writeUnboundableMessage = (root) => `Bounded expression ${root} must be exactly one of number, string, Array, or Date`;\n",
123
+ "import { describeCollapsibleDate } from \"@ark/util\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { BaseRange, createDateSchemaNormalizer, parseDateLimit } from \"./range.js\";\nconst implementation = implementNode({\n kind: \"after\",\n collapsibleKey: \"rule\",\n hasAssociatedError: true,\n keys: {\n rule: {\n parse: parseDateLimit,\n serialize: schema => schema.toISOString()\n }\n },\n normalize: createDateSchemaNormalizer(\"after\"),\n defaults: {\n description: node => `${node.collapsibleLimitString} or later`,\n actual: describeCollapsibleDate\n },\n intersections: {\n after: (l, r) => (l.isStricterThan(r) ? l : r)\n }\n});\nexport class AfterNode extends BaseRange {\n impliedBasis = $ark.intrinsic.Date.internal;\n collapsibleLimitString = describeCollapsibleDate(this.rule);\n traverseAllows = data => data >= this.rule;\n reduceJsonSchema(base, ctx) {\n return ctx.fallback.date({ code: \"date\", base, after: this.rule });\n }\n}\nexport const After = {\n implementation,\n Node: AfterNode\n};\n",
124
+ "import { describeCollapsibleDate } from \"@ark/util\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { BaseRange, createDateSchemaNormalizer, parseDateLimit } from \"./range.js\";\nconst implementation = implementNode({\n kind: \"before\",\n collapsibleKey: \"rule\",\n hasAssociatedError: true,\n keys: {\n rule: {\n parse: parseDateLimit,\n serialize: schema => schema.toISOString()\n }\n },\n normalize: createDateSchemaNormalizer(\"before\"),\n defaults: {\n description: node => `${node.collapsibleLimitString} or earlier`,\n actual: describeCollapsibleDate\n },\n intersections: {\n before: (l, r) => (l.isStricterThan(r) ? l : r),\n after: (before, after, ctx) => before.overlapsRange(after) ?\n before.overlapIsUnit(after) ?\n ctx.$.node(\"unit\", { unit: before.rule })\n : null\n : Disjoint.init(\"range\", before, after)\n }\n});\nexport class BeforeNode extends BaseRange {\n collapsibleLimitString = describeCollapsibleDate(this.rule);\n traverseAllows = data => data <= this.rule;\n impliedBasis = $ark.intrinsic.Date.internal;\n reduceJsonSchema(base, ctx) {\n return ctx.fallback.date({ code: \"date\", base, before: this.rule });\n }\n}\nexport const Before = {\n implementation,\n Node: BeforeNode\n};\n",
125
+ "import { InternalPrimitiveConstraint } from \"../constraint.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { ToJsonSchema } from \"../shared/toJsonSchema.js\";\nimport { createLengthRuleParser } from \"./range.js\";\nconst implementation = implementNode({\n kind: \"exactLength\",\n collapsibleKey: \"rule\",\n keys: {\n rule: {\n parse: createLengthRuleParser(\"exactLength\")\n }\n },\n normalize: schema => typeof schema === \"number\" ? { rule: schema } : schema,\n hasAssociatedError: true,\n defaults: {\n description: node => `exactly length ${node.rule}`,\n actual: data => `${data.length}`\n },\n intersections: {\n exactLength: (l, r, ctx) => Disjoint.init(\"unit\", ctx.$.node(\"unit\", { unit: l.rule }), ctx.$.node(\"unit\", { unit: r.rule }), { path: [\"length\"] }),\n minLength: (exactLength, minLength) => exactLength.rule >= minLength.rule ?\n exactLength\n : Disjoint.init(\"range\", exactLength, minLength),\n maxLength: (exactLength, maxLength) => exactLength.rule <= maxLength.rule ?\n exactLength\n : Disjoint.init(\"range\", exactLength, maxLength)\n }\n});\nexport class ExactLengthNode extends InternalPrimitiveConstraint {\n traverseAllows = data => data.length === this.rule;\n compiledCondition = `data.length === ${this.rule}`;\n compiledNegation = `data.length !== ${this.rule}`;\n impliedBasis = $ark.intrinsic.lengthBoundable.internal;\n expression = `== ${this.rule}`;\n reduceJsonSchema(schema) {\n switch (schema.type) {\n case \"string\":\n schema.minLength = this.rule;\n schema.maxLength = this.rule;\n return schema;\n case \"array\":\n schema.minItems = this.rule;\n schema.maxItems = this.rule;\n return schema;\n default:\n return ToJsonSchema.throwInternalOperandError(\"exactLength\", schema);\n }\n }\n}\nexport const ExactLength = {\n implementation,\n Node: ExactLengthNode\n};\n",
126
+ "import { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { BaseRange, parseExclusiveKey } from \"./range.js\";\nconst implementation = implementNode({\n kind: \"max\",\n collapsibleKey: \"rule\",\n hasAssociatedError: true,\n keys: {\n rule: {},\n exclusive: parseExclusiveKey\n },\n normalize: schema => typeof schema === \"number\" ? { rule: schema } : schema,\n defaults: {\n description: node => {\n if (node.rule === 0)\n return node.exclusive ? \"negative\" : \"non-positive\";\n return `${node.exclusive ? \"less than\" : \"at most\"} ${node.rule}`;\n }\n },\n intersections: {\n max: (l, r) => (l.isStricterThan(r) ? l : r),\n min: (max, min, ctx) => max.overlapsRange(min) ?\n max.overlapIsUnit(min) ?\n ctx.$.node(\"unit\", { unit: max.rule })\n : null\n : Disjoint.init(\"range\", max, min)\n },\n obviatesBasisDescription: true\n});\nexport class MaxNode extends BaseRange {\n impliedBasis = $ark.intrinsic.number.internal;\n traverseAllows = this.exclusive ? data => data < this.rule : data => data <= this.rule;\n reduceJsonSchema(schema) {\n if (this.exclusive)\n schema.exclusiveMaximum = this.rule;\n else\n schema.maximum = this.rule;\n return schema;\n }\n}\nexport const Max = {\n implementation,\n Node: MaxNode\n};\n",
127
+ "import { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { ToJsonSchema } from \"../shared/toJsonSchema.js\";\nimport { BaseRange, createLengthRuleParser, createLengthSchemaNormalizer } from \"./range.js\";\nconst implementation = implementNode({\n kind: \"maxLength\",\n collapsibleKey: \"rule\",\n hasAssociatedError: true,\n keys: {\n rule: {\n parse: createLengthRuleParser(\"maxLength\")\n }\n },\n reduce: (inner, $) => inner.rule === 0 ? $.node(\"exactLength\", inner) : undefined,\n normalize: createLengthSchemaNormalizer(\"maxLength\"),\n defaults: {\n description: node => `at most length ${node.rule}`,\n actual: data => `${data.length}`\n },\n intersections: {\n maxLength: (l, r) => (l.isStricterThan(r) ? l : r),\n minLength: (max, min, ctx) => max.overlapsRange(min) ?\n max.overlapIsUnit(min) ?\n ctx.$.node(\"exactLength\", { rule: max.rule })\n : null\n : Disjoint.init(\"range\", max, min)\n }\n});\nexport class MaxLengthNode extends BaseRange {\n impliedBasis = $ark.intrinsic.lengthBoundable.internal;\n traverseAllows = data => data.length <= this.rule;\n reduceJsonSchema(schema) {\n switch (schema.type) {\n case \"string\":\n schema.maxLength = this.rule;\n return schema;\n case \"array\":\n schema.maxItems = this.rule;\n return schema;\n default:\n return ToJsonSchema.throwInternalOperandError(\"maxLength\", schema);\n }\n }\n}\nexport const MaxLength = {\n implementation,\n Node: MaxLengthNode\n};\n",
128
+ "import { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { BaseRange, parseExclusiveKey } from \"./range.js\";\nconst implementation = implementNode({\n kind: \"min\",\n collapsibleKey: \"rule\",\n hasAssociatedError: true,\n keys: {\n rule: {},\n exclusive: parseExclusiveKey\n },\n normalize: schema => typeof schema === \"number\" ? { rule: schema } : schema,\n defaults: {\n description: node => {\n if (node.rule === 0)\n return node.exclusive ? \"positive\" : \"non-negative\";\n return `${node.exclusive ? \"more than\" : \"at least\"} ${node.rule}`;\n }\n },\n intersections: {\n min: (l, r) => (l.isStricterThan(r) ? l : r)\n },\n obviatesBasisDescription: true\n});\nexport class MinNode extends BaseRange {\n impliedBasis = $ark.intrinsic.number.internal;\n traverseAllows = this.exclusive ? data => data > this.rule : data => data >= this.rule;\n reduceJsonSchema(schema) {\n if (this.exclusive)\n schema.exclusiveMinimum = this.rule;\n else\n schema.minimum = this.rule;\n return schema;\n }\n}\nexport const Min = {\n implementation,\n Node: MinNode\n};\n",
129
+ "import { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { ToJsonSchema } from \"../shared/toJsonSchema.js\";\nimport { BaseRange, createLengthRuleParser, createLengthSchemaNormalizer } from \"./range.js\";\nconst implementation = implementNode({\n kind: \"minLength\",\n collapsibleKey: \"rule\",\n hasAssociatedError: true,\n keys: {\n rule: {\n parse: createLengthRuleParser(\"minLength\")\n }\n },\n reduce: inner => inner.rule === 0 ?\n // a minimum length of zero is trivially satisfied\n $ark.intrinsic.unknown\n : undefined,\n normalize: createLengthSchemaNormalizer(\"minLength\"),\n defaults: {\n description: node => node.rule === 1 ? \"non-empty\" : `at least length ${node.rule}`,\n // avoid default message like \"must be non-empty (was 0)\"\n actual: data => (data.length === 0 ? \"\" : `${data.length}`)\n },\n intersections: {\n minLength: (l, r) => (l.isStricterThan(r) ? l : r)\n }\n});\nexport class MinLengthNode extends BaseRange {\n impliedBasis = $ark.intrinsic.lengthBoundable.internal;\n traverseAllows = data => data.length >= this.rule;\n reduceJsonSchema(schema) {\n switch (schema.type) {\n case \"string\":\n schema.minLength = this.rule;\n return schema;\n case \"array\":\n schema.minItems = this.rule;\n return schema;\n default:\n return ToJsonSchema.throwInternalOperandError(\"minLength\", schema);\n }\n }\n}\nexport const MinLength = {\n implementation,\n Node: MinLengthNode\n};\n",
130
+ "import { After } from \"./after.js\";\nimport { Before } from \"./before.js\";\nimport { ExactLength } from \"./exactLength.js\";\nimport { Max } from \"./max.js\";\nimport { MaxLength } from \"./maxLength.js\";\nimport { Min } from \"./min.js\";\nimport { MinLength } from \"./minLength.js\";\nexport const boundImplementationsByKind = {\n min: Min.implementation,\n max: Max.implementation,\n minLength: MinLength.implementation,\n maxLength: MaxLength.implementation,\n exactLength: ExactLength.implementation,\n after: After.implementation,\n before: Before.implementation\n};\nexport const boundClassesByKind = {\n min: Min.Node,\n max: Max.Node,\n minLength: MinLength.Node,\n maxLength: MaxLength.Node,\n exactLength: ExactLength.Node,\n after: After.Node,\n before: Before.Node\n};\n",
131
+ "import { InternalPrimitiveConstraint } from \"../constraint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nconst implementation = implementNode({\n kind: \"pattern\",\n collapsibleKey: \"rule\",\n keys: {\n rule: {},\n flags: {}\n },\n normalize: schema => typeof schema === \"string\" ? { rule: schema }\n : schema instanceof RegExp ?\n schema.flags ?\n { rule: schema.source, flags: schema.flags }\n : { rule: schema.source }\n : schema,\n obviatesBasisDescription: true,\n obviatesBasisExpression: true,\n hasAssociatedError: true,\n intersectionIsOpen: true,\n defaults: {\n description: node => `matched by ${node.rule}`\n },\n intersections: {\n // for now, non-equal regex are naively intersected:\n // https://github.com/arktypeio/arktype/issues/853\n pattern: () => null\n }\n});\nexport class PatternNode extends InternalPrimitiveConstraint {\n instance = new RegExp(this.rule, this.flags);\n expression = `${this.instance}`;\n traverseAllows = this.instance.test.bind(this.instance);\n compiledCondition = `${this.expression}.test(data)`;\n compiledNegation = `!${this.compiledCondition}`;\n impliedBasis = $ark.intrinsic.string.internal;\n reduceJsonSchema(base, ctx) {\n if (base.pattern) {\n return ctx.fallback.patternIntersection({\n code: \"patternIntersection\",\n base: base,\n pattern: this.rule\n });\n }\n base.pattern = this.rule;\n return base;\n }\n}\nexport const Pattern = {\n implementation,\n Node: PatternNode\n};\n",
132
+ "import { domainDescriptions, entriesOf, flatMorph, hasDomain, isArray, isEmptyObject, printable, throwInternalError, throwParseError, unset } from \"@ark/util\";\nimport { nodeClassesByKind, nodeImplementationsByKind } from \"./kinds.js\";\nimport { Disjoint } from \"./shared/disjoint.js\";\nimport { constraintKeys, defaultValueSerializer, isNodeKind, precedenceOfKind } from \"./shared/implement.js\";\nimport { $ark } from \"./shared/registry.js\";\nimport { hasArkKind, isNode } from \"./shared/utils.js\";\nexport const schemaKindOf = (schema, allowedKinds) => {\n const kind = discriminateRootKind(schema);\n if (allowedKinds && !allowedKinds.includes(kind)) {\n return throwParseError(`Root of kind ${kind} should be one of ${allowedKinds}`);\n }\n return kind;\n};\nconst discriminateRootKind = (schema) => {\n if (hasArkKind(schema, \"root\"))\n return schema.kind;\n if (typeof schema === \"string\") {\n return (schema[0] === \"$\" ? \"alias\"\n : schema in domainDescriptions ? \"domain\"\n : \"proto\");\n }\n if (typeof schema === \"function\")\n return \"proto\";\n // throw at end of function\n if (typeof schema !== \"object\" || schema === null)\n return throwParseError(writeInvalidSchemaMessage(schema));\n if (\"morphs\" in schema)\n return \"morph\";\n if (\"branches\" in schema || isArray(schema))\n return \"union\";\n if (\"unit\" in schema)\n return \"unit\";\n if (\"reference\" in schema)\n return \"alias\";\n const schemaKeys = Object.keys(schema);\n if (schemaKeys.length === 0 || schemaKeys.some(k => k in constraintKeys))\n return \"intersection\";\n if (\"proto\" in schema)\n return \"proto\";\n if (\"domain\" in schema)\n return \"domain\";\n return throwParseError(writeInvalidSchemaMessage(schema));\n};\nexport const writeInvalidSchemaMessage = (schema) => `${printable(schema)} is not a valid type schema`;\nconst nodeCountsByPrefix = {};\nconst serializeListableChild = (listableNode) => isArray(listableNode) ?\n listableNode.map(node => node.collapsibleJson)\n : listableNode.collapsibleJson;\nexport const nodesByRegisteredId = {};\n$ark.nodesByRegisteredId = nodesByRegisteredId;\nexport const registerNodeId = (prefix) => {\n nodeCountsByPrefix[prefix] ??= 0;\n return `${prefix}${++nodeCountsByPrefix[prefix]}`;\n};\nexport const parseNode = (ctx) => {\n const impl = nodeImplementationsByKind[ctx.kind];\n const configuredSchema = impl.applyConfig?.(ctx.def, ctx.$.resolvedConfig) ?? ctx.def;\n const inner = {};\n const { meta: metaSchema, ...innerSchema } = configuredSchema;\n const meta = metaSchema === undefined ? {}\n : typeof metaSchema === \"string\" ? { description: metaSchema }\n : metaSchema;\n // ensure node entries are parsed in order of precedence, with non-children\n // parsed first\n const innerSchemaEntries = entriesOf(innerSchema)\n .sort(([lKey], [rKey]) => isNodeKind(lKey) ?\n isNodeKind(rKey) ? precedenceOfKind(lKey) - precedenceOfKind(rKey)\n : 1\n : isNodeKind(rKey) ? -1\n : lKey < rKey ? -1\n : 1)\n .filter(([k, v]) => {\n // move meta. prefixed props to meta, overwriting existing nested\n // props of the same name if they exist\n if (k.startsWith(\"meta.\")) {\n const metaKey = k.slice(5);\n meta[metaKey] = v;\n return false;\n }\n return true;\n });\n for (const entry of innerSchemaEntries) {\n const k = entry[0];\n const keyImpl = impl.keys[k];\n if (!keyImpl)\n return throwParseError(`Key ${k} is not valid on ${ctx.kind} schema`);\n const v = keyImpl.parse ? keyImpl.parse(entry[1], ctx) : entry[1];\n if (v !== unset && (v !== undefined || keyImpl.preserveUndefined))\n inner[k] = v;\n }\n if (impl.reduce && !ctx.prereduced) {\n const reduced = impl.reduce(inner, ctx.$);\n if (reduced) {\n if (reduced instanceof Disjoint)\n return reduced.throw();\n // we can't cache this reduction for now in case the reduction involved\n // impliedSiblings\n return withMeta(reduced, meta);\n }\n }\n const node = createNode({\n id: ctx.id,\n kind: ctx.kind,\n inner,\n meta,\n $: ctx.$\n });\n return node;\n};\nexport const createNode = ({ id, kind, inner, meta, $, ignoreCache }) => {\n const impl = nodeImplementationsByKind[kind];\n const innerEntries = entriesOf(inner);\n const children = [];\n let innerJson = {};\n for (const [k, v] of innerEntries) {\n const keyImpl = impl.keys[k];\n const serialize = keyImpl.serialize ??\n (keyImpl.child ? serializeListableChild : defaultValueSerializer);\n innerJson[k] = serialize(v);\n if (keyImpl.child === true) {\n const listableNode = v;\n if (isArray(listableNode))\n children.push(...listableNode);\n else\n children.push(listableNode);\n }\n else if (typeof keyImpl.child === \"function\")\n children.push(...keyImpl.child(v));\n }\n if (impl.finalizeInnerJson)\n innerJson = impl.finalizeInnerJson(innerJson);\n let json = { ...innerJson };\n let metaJson = {};\n if (!isEmptyObject(meta)) {\n metaJson = flatMorph(meta, (k, v) => [\n k,\n k === \"examples\" ? v : defaultValueSerializer(v)\n ]);\n json.meta = possiblyCollapse(metaJson, \"description\", true);\n }\n innerJson = possiblyCollapse(innerJson, impl.collapsibleKey, false);\n const innerHash = JSON.stringify({ kind, ...innerJson });\n json = possiblyCollapse(json, impl.collapsibleKey, false);\n const collapsibleJson = possiblyCollapse(json, impl.collapsibleKey, true);\n const hash = JSON.stringify({ kind, ...json });\n // we have to wait until after reduction to return a cached entry,\n // since reduction can add impliedSiblings\n if ($.nodesByHash[hash] && !ignoreCache)\n return $.nodesByHash[hash];\n const attachments = {\n id,\n kind,\n impl,\n inner,\n innerEntries,\n innerJson,\n innerHash,\n meta,\n metaJson,\n json,\n hash,\n collapsibleJson: collapsibleJson,\n children\n };\n if (kind !== \"intersection\") {\n for (const k in inner)\n if (k !== \"in\" && k !== \"out\")\n attachments[k] = inner[k];\n }\n const node = new nodeClassesByKind[kind](attachments, $);\n return ($.nodesByHash[hash] = node);\n};\nexport const withId = (node, id) => {\n if (node.id === id)\n return node;\n if (isNode(nodesByRegisteredId[id]))\n throwInternalError(`Unexpected attempt to overwrite node id ${id}`);\n // have to ignore cache to force creation of new potentially cyclic id\n return createNode({\n id,\n kind: node.kind,\n inner: node.inner,\n meta: node.meta,\n $: node.$,\n ignoreCache: true\n });\n};\nexport const withMeta = (node, meta, id) => {\n if (id && isNode(nodesByRegisteredId[id]))\n throwInternalError(`Unexpected attempt to overwrite node id ${id}`);\n return createNode({\n id: id ?? registerNodeId(meta.alias ?? node.kind),\n kind: node.kind,\n inner: node.inner,\n meta,\n $: node.$\n });\n};\nconst possiblyCollapse = (json, toKey, allowPrimitive) => {\n const collapsibleKeys = Object.keys(json);\n if (collapsibleKeys.length === 1 && collapsibleKeys[0] === toKey) {\n const collapsed = json[toKey];\n if (allowPrimitive)\n return collapsed;\n if (\n // if the collapsed value is still an object\n hasDomain(collapsed, \"object\") &&\n // and the JSON did not include any implied keys\n (Object.keys(collapsed).length === 1 || Array.isArray(collapsed))) {\n // we can replace it with its collapsed value\n return collapsed;\n }\n }\n return json;\n};\n",
133
+ "import { append, printable, throwParseError, unset } from \"@ark/util\";\nimport { BaseConstraint } from \"../constraint.js\";\nimport { flatRef } from \"../node.js\";\nimport { compileSerializedValue } from \"../shared/compile.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { intersectOrPipeNodes } from \"../shared/intersections.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { traverseKey } from \"../shared/traversal.js\";\nexport const intersectProps = (l, r, ctx) => {\n if (l.key !== r.key)\n return null;\n const key = l.key;\n let value = intersectOrPipeNodes(l.value, r.value, ctx);\n const kind = l.required || r.required ? \"required\" : \"optional\";\n if (value instanceof Disjoint) {\n if (kind === \"optional\")\n value = $ark.intrinsic.never.internal;\n else {\n // if either operand was optional, the Disjoint has to be treated as optional\n return value.withPrefixKey(l.key, l.required && r.required ? \"required\" : \"optional\");\n }\n }\n if (kind === \"required\") {\n return ctx.$.node(\"required\", {\n key,\n value\n });\n }\n const defaultIntersection = l.hasDefault() ?\n r.hasDefault() ?\n l.default === r.default ?\n l.default\n : throwParseError(writeDefaultIntersectionMessage(l.default, r.default))\n : l.default\n : r.hasDefault() ? r.default\n : unset;\n return ctx.$.node(\"optional\", {\n key,\n value,\n // unset is stripped during parsing\n default: defaultIntersection\n });\n};\nexport class BaseProp extends BaseConstraint {\n required = this.kind === \"required\";\n optional = this.kind === \"optional\";\n impliedBasis = $ark.intrinsic.object.internal;\n serializedKey = compileSerializedValue(this.key);\n compiledKey = typeof this.key === \"string\" ? this.key : this.serializedKey;\n flatRefs = append(this.value.flatRefs.map(ref => flatRef([this.key, ...ref.path], ref.node)), flatRef([this.key], this.value));\n _transform(mapper, ctx) {\n ctx.path.push(this.key);\n const result = super._transform(mapper, ctx);\n ctx.path.pop();\n return result;\n }\n hasDefault() {\n return \"default\" in this.inner;\n }\n traverseAllows = (data, ctx) => {\n if (this.key in data) {\n // ctx will be undefined if this node isn't context-dependent\n return traverseKey(this.key, () => this.value.traverseAllows(data[this.key], ctx), ctx);\n }\n return this.optional;\n };\n traverseApply = (data, ctx) => {\n if (this.key in data) {\n traverseKey(this.key, () => this.value.traverseApply(data[this.key], ctx), ctx);\n }\n else if (this.hasKind(\"required\"))\n ctx.errorFromNodeContext(this.errorContext);\n };\n compile(js) {\n js.if(`${this.serializedKey} in data`, () => js.traverseKey(this.serializedKey, `data${js.prop(this.key)}`, this.value));\n if (this.hasKind(\"required\")) {\n js.else(() => js.traversalKind === \"Apply\" ?\n js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`)\n : js.return(false));\n }\n if (js.traversalKind === \"Allows\")\n js.return(true);\n }\n}\nexport const writeDefaultIntersectionMessage = (lValue, rValue) => `Invalid intersection of default values ${printable(lValue)} & ${printable(rValue)}`;\n",
134
+ "import { hasDomain, isThunk, omit, printable, throwParseError } from \"@ark/util\";\nimport { intrinsic } from \"../intrinsic.js\";\nimport { compileSerializedValue } from \"../shared/compile.js\";\nimport { ArkErrors } from \"../shared/errors.js\";\nimport { defaultValueSerializer, implementNode } from \"../shared/implement.js\";\nimport { registeredReference } from \"../shared/registry.js\";\nimport { traverseKey } from \"../shared/traversal.js\";\nimport { BaseProp, intersectProps } from \"./prop.js\";\nconst implementation = implementNode({\n kind: \"optional\",\n hasAssociatedError: false,\n intersectionIsOpen: true,\n keys: {\n key: {},\n value: {\n child: true,\n parse: (schema, ctx) => ctx.$.parseSchema(schema)\n },\n default: {\n preserveUndefined: true\n }\n },\n normalize: schema => schema,\n reduce: (inner, $) => {\n if ($.resolvedConfig.exactOptionalPropertyTypes === false) {\n if (!inner.value.allows(undefined)) {\n return $.node(\"optional\", { ...inner, value: inner.value.or(intrinsic.undefined) }, { prereduced: true });\n }\n }\n },\n defaults: {\n description: node => `${node.compiledKey}?: ${node.value.description}`\n },\n intersections: {\n optional: intersectProps\n }\n});\nexport class OptionalNode extends BaseProp {\n constructor(...args) {\n super(...args);\n if (\"default\" in this.inner)\n assertDefaultValueAssignability(this.value, this.inner.default, this.key);\n }\n get rawIn() {\n const baseIn = super.rawIn;\n if (!this.hasDefault())\n return baseIn;\n return this.$.node(\"optional\", omit(baseIn.inner, { default: true }), {\n prereduced: true\n });\n }\n get outProp() {\n if (!this.hasDefault())\n return this;\n const { default: defaultValue, ...requiredInner } = this.inner;\n return this.cacheGetter(\"outProp\", this.$.node(\"required\", requiredInner, { prereduced: true }));\n }\n expression = this.hasDefault() ?\n `${this.compiledKey}: ${this.value.expression} = ${printable(this.inner.default)}`\n : `${this.compiledKey}?: ${this.value.expression}`;\n defaultValueMorph = getDefaultableMorph(this);\n defaultValueMorphRef = this.defaultValueMorph && registeredReference(this.defaultValueMorph);\n}\nexport const Optional = {\n implementation,\n Node: OptionalNode\n};\nconst defaultableMorphCache = {};\nconst getDefaultableMorph = (node) => {\n if (!node.hasDefault())\n return;\n const cacheKey = `{${node.compiledKey}: ${node.value.id} = ${defaultValueSerializer(node.default)}}`;\n return (defaultableMorphCache[cacheKey] ??= computeDefaultValueMorph(node.key, node.value, node.default));\n};\nexport const computeDefaultValueMorph = (key, value, defaultInput) => {\n if (typeof defaultInput === \"function\") {\n // if the value has a morph, pipe context through it\n return value.includesTransform ?\n (data, ctx) => {\n traverseKey(key, () => value((data[key] = defaultInput()), ctx), ctx);\n return data;\n }\n : data => {\n data[key] = defaultInput();\n return data;\n };\n }\n // non-functional defaults can be safely cached as long as the morph is\n // guaranteed to be pure and the output is primitive\n const precomputedMorphedDefault = value.includesTransform ? value.assert(defaultInput) : defaultInput;\n return hasDomain(precomputedMorphedDefault, \"object\") ?\n // the type signature only allows this if the value was morphed\n (data, ctx) => {\n traverseKey(key, () => value((data[key] = defaultInput), ctx), ctx);\n return data;\n }\n : data => {\n data[key] = precomputedMorphedDefault;\n return data;\n };\n};\nexport const assertDefaultValueAssignability = (node, value, key) => {\n const wrapped = isThunk(value);\n if (hasDomain(value, \"object\") && !wrapped)\n throwParseError(writeNonPrimitiveNonFunctionDefaultValueMessage(key));\n // if the node has a default value, finalize it and apply JIT optimizations\n // if applicable to ensure behavior + error logging is externally consistent\n // (using .in here insead of .rawIn triggers finalization)\n const out = node.in(wrapped ? value() : value);\n if (out instanceof ArkErrors) {\n if (key === null) {\n // e.g. \"Default must be assignable to number (was string)\"\n throwParseError(`Default ${out.summary}`);\n }\n const atPath = out.transform(e => e.transform(input => ({ ...input, prefixPath: [key] })));\n // e.g. \"Default for bar must be assignable to number (was string)\"\n // e.g. \"Default for value at [0] must be assignable to number (was string)\"\n throwParseError(`Default for ${atPath.summary}`);\n }\n return value;\n};\nexport const writeNonPrimitiveNonFunctionDefaultValueMessage = (key) => {\n const keyDescription = key === null ? \"\"\n : typeof key === \"number\" ? `for value at [${key}] `\n : `for ${compileSerializedValue(key)} `;\n return `Non-primitive default ${keyDescription}must be specified as a function like () => ({my: 'object'})`;\n};\n",
135
+ "import { arrayEquals, flatMorph, includes, inferred, omit, throwInternalError, throwParseError } from \"@ark/util\";\nimport { mergeToJsonSchemaConfigs } from \"../config.js\";\nimport { throwInvalidOperandError } from \"../constraint.js\";\nimport { BaseNode } from \"../node.js\";\nimport { Disjoint, writeUnsatisfiableExpressionError } from \"../shared/disjoint.js\";\nimport { ArkErrors } from \"../shared/errors.js\";\nimport { structuralKinds } from \"../shared/implement.js\";\nimport { intersectNodesRoot, pipeNodesRoot } from \"../shared/intersections.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { arkKind, hasArkKind } from \"../shared/utils.js\";\nimport { assertDefaultValueAssignability } from \"../structure/optional.js\";\nexport class BaseRoot extends BaseNode {\n constructor(attachments, $) {\n super(attachments, $);\n // define as a getter to avoid it being enumerable/spreadable\n Object.defineProperty(this, arkKind, { value: \"root\", enumerable: false });\n }\n // doesn't seem possible to override this at a type-level (e.g. via declare)\n // without TS complaining about getters\n get rawIn() {\n return super.rawIn;\n }\n get rawOut() {\n return super.rawOut;\n }\n get internal() {\n return this;\n }\n get \"~standard\"() {\n return {\n vendor: \"arktype\",\n version: 1,\n validate: input => {\n const out = this(input);\n if (out instanceof ArkErrors)\n return out;\n return { value: out };\n },\n jsonSchema: {\n input: opts => this.rawIn.toJsonSchema({\n target: validateStandardJsonSchemaTarget(opts.target),\n ...opts.libraryOptions\n }),\n output: opts => this.rawOut.toJsonSchema({\n target: validateStandardJsonSchemaTarget(opts.target),\n ...opts.libraryOptions\n })\n }\n };\n }\n as() {\n return this;\n }\n brand(name) {\n if (name === \"\")\n return throwParseError(emptyBrandNameMessage);\n return this;\n }\n readonly() {\n return this;\n }\n branches = this.hasKind(\"union\") ? this.inner.branches : [this];\n distribute(mapBranch, reduceMapped) {\n const mappedBranches = this.branches.map(mapBranch);\n return reduceMapped?.(mappedBranches) ?? mappedBranches;\n }\n get shortDescription() {\n return this.meta.description ?? this.defaultShortDescription;\n }\n toJsonSchema(opts = {}) {\n const ctx = mergeToJsonSchemaConfigs(this.$.resolvedConfig.toJsonSchema, opts);\n ctx.useRefs ||= this.isCyclic;\n // ensure $schema is the first key if present\n const schema = typeof ctx.dialect === \"string\" ? { $schema: ctx.dialect } : {};\n Object.assign(schema, this.toJsonSchemaRecurse(ctx));\n if (ctx.useRefs) {\n const defs = flatMorph(this.references, (i, ref) => ref.isRoot() && !ref.alwaysExpandJsonSchema ?\n [ref.id, ref.toResolvedJsonSchema(ctx)]\n : []);\n // draft-2020-12 uses $defs, draft-07 uses definitions\n if (ctx.target === \"draft-07\")\n Object.assign(schema, { definitions: defs });\n else\n schema.$defs = defs;\n }\n return schema;\n }\n toJsonSchemaRecurse(ctx) {\n if (ctx.useRefs && !this.alwaysExpandJsonSchema) {\n // draft-2020-12 uses $defs, draft-07 uses definitions\n const defsKey = ctx.target === \"draft-07\" ? \"definitions\" : \"$defs\";\n return { $ref: `#/${defsKey}/${this.id}` };\n }\n return this.toResolvedJsonSchema(ctx);\n }\n get alwaysExpandJsonSchema() {\n return (this.isBasis() ||\n this.kind === \"alias\" ||\n (this.hasKind(\"union\") && this.isBoolean));\n }\n toResolvedJsonSchema(ctx) {\n const result = this.innerToJsonSchema(ctx);\n return Object.assign(result, this.metaJson);\n }\n intersect(r) {\n const rNode = this.$.parseDefinition(r);\n const result = this.rawIntersect(rNode);\n if (result instanceof Disjoint)\n return result;\n return this.$.finalize(result);\n }\n rawIntersect(r) {\n return intersectNodesRoot(this, r, this.$);\n }\n toNeverIfDisjoint() {\n return this;\n }\n and(r) {\n const result = this.intersect(r);\n return result instanceof Disjoint ? result.throw() : result;\n }\n rawAnd(r) {\n const result = this.rawIntersect(r);\n return result instanceof Disjoint ? result.throw() : result;\n }\n or(r) {\n const rNode = this.$.parseDefinition(r);\n return this.$.finalize(this.rawOr(rNode));\n }\n rawOr(r) {\n const branches = [...this.branches, ...r.branches];\n return this.$.node(\"union\", branches);\n }\n map(flatMapEntry) {\n return this.$.schema(this.applyStructuralOperation(\"map\", [flatMapEntry]));\n }\n pick(...keys) {\n return this.$.schema(this.applyStructuralOperation(\"pick\", keys));\n }\n omit(...keys) {\n return this.$.schema(this.applyStructuralOperation(\"omit\", keys));\n }\n required() {\n return this.$.schema(this.applyStructuralOperation(\"required\", []));\n }\n partial() {\n return this.$.schema(this.applyStructuralOperation(\"partial\", []));\n }\n _keyof;\n keyof() {\n if (this._keyof)\n return this._keyof;\n const result = this.applyStructuralOperation(\"keyof\", []).reduce((result, branch) => result.intersect(branch).toNeverIfDisjoint(), $ark.intrinsic.unknown.internal);\n if (result.branches.length === 0) {\n throwParseError(writeUnsatisfiableExpressionError(`keyof ${this.expression}`));\n }\n return (this._keyof = this.$.finalize(result));\n }\n get props() {\n if (this.branches.length !== 1)\n return throwParseError(writeLiteralUnionEntriesMessage(this.expression));\n return [...this.applyStructuralOperation(\"props\", [])[0]];\n }\n merge(r) {\n const rNode = this.$.parseDefinition(r);\n return this.$.schema(rNode.distribute(branch => this.applyStructuralOperation(\"merge\", [\n structureOf(branch) ??\n throwParseError(writeNonStructuralOperandMessage(\"merge\", branch.expression))\n ])));\n }\n applyStructuralOperation(operation, args) {\n return this.distribute(branch => {\n if (branch.equals($ark.intrinsic.object) && operation !== \"merge\")\n // ideally this wouldn't be a special case, but for now it\n // allows us to bypass `assertHasKeys` checks on base\n // instantiations of generics like Pick and Omit. Could\n // potentially be removed once constraints can reference each other:\n // https://github.com/arktypeio/arktype/issues/1053\n return branch;\n const structure = structureOf(branch);\n if (!structure) {\n throwParseError(writeNonStructuralOperandMessage(operation, branch.expression));\n }\n if (operation === \"keyof\")\n return structure.keyof();\n if (operation === \"get\")\n return structure.get(...args);\n if (operation === \"props\")\n return structure.props;\n const structuralMethodName = operation === \"required\" ? \"require\"\n : operation === \"partial\" ? \"optionalize\"\n : operation;\n return this.$.node(\"intersection\", {\n domain: \"object\",\n structure: structure[structuralMethodName](...args)\n });\n });\n }\n get(...path) {\n if (path[0] === undefined)\n return this;\n return this.$.schema(this.applyStructuralOperation(\"get\", path));\n }\n extract(r) {\n const rNode = this.$.parseDefinition(r);\n return this.$.schema(this.branches.filter(branch => branch.extends(rNode)));\n }\n exclude(r) {\n const rNode = this.$.parseDefinition(r);\n return this.$.schema(this.branches.filter(branch => !branch.extends(rNode)));\n }\n array() {\n return this.$.schema(this.isUnknown() ?\n { proto: Array }\n : {\n proto: Array,\n sequence: this\n }, { prereduced: true });\n }\n overlaps(r) {\n const intersection = this.intersect(r);\n return !(intersection instanceof Disjoint);\n }\n extends(r) {\n if (this.isNever())\n return true;\n const intersection = this.intersect(r);\n return (!(intersection instanceof Disjoint) && this.equals(intersection));\n }\n ifExtends(r) {\n return this.extends(r) ? this : undefined;\n }\n subsumes(r) {\n const rNode = this.$.parseDefinition(r);\n return rNode.extends(this);\n }\n configure(meta, selector = \"shallow\") {\n return this.configureReferences(meta, selector);\n }\n describe(description, selector = \"shallow\") {\n return this.configure({ description }, selector);\n }\n // these should ideally be implemented in arktype since they use its syntax\n // https://github.com/arktypeio/arktype/issues/1223\n optional() {\n return [this, \"?\"];\n }\n // these should ideally be implemented in arktype since they use its syntax\n // https://github.com/arktypeio/arktype/issues/1223\n default(thunkableValue) {\n assertDefaultValueAssignability(this, thunkableValue, null);\n return [this, \"=\", thunkableValue];\n }\n from(input) {\n // ideally we might not validate here but for now we need to do determine\n // which morphs to apply\n return this.assert(input);\n }\n _pipe(...morphs) {\n const result = morphs.reduce((acc, morph) => acc.rawPipeOnce(morph), this);\n return this.$.finalize(result);\n }\n tryPipe(...morphs) {\n const result = morphs.reduce((acc, morph) => acc.rawPipeOnce(hasArkKind(morph, \"root\") ? morph : ((In, ctx) => {\n try {\n return morph(In, ctx);\n }\n catch (e) {\n return ctx.error({\n code: \"predicate\",\n predicate: morph,\n actual: `aborted due to error:\\n ${e}\\n`\n });\n }\n })), this);\n return this.$.finalize(result);\n }\n pipe = Object.assign(this._pipe.bind(this), {\n try: this.tryPipe.bind(this)\n });\n to(def) {\n return this.$.finalize(this.toNode(this.$.parseDefinition(def)));\n }\n toNode(root) {\n const result = pipeNodesRoot(this, root, this.$);\n if (result instanceof Disjoint)\n return result.throw();\n return result;\n }\n rawPipeOnce(morph) {\n if (hasArkKind(morph, \"root\"))\n return this.toNode(morph);\n return this.distribute(branch => branch.hasKind(\"morph\") ?\n this.$.node(\"morph\", {\n in: branch.inner.in,\n morphs: [...branch.morphs, morph]\n })\n : this.$.node(\"morph\", {\n in: branch,\n morphs: [morph]\n }), this.$.parseSchema);\n }\n narrow(predicate) {\n return this.constrainOut(\"predicate\", predicate);\n }\n constrain(kind, schema) {\n return this._constrain(\"root\", kind, schema);\n }\n constrainIn(kind, schema) {\n return this._constrain(\"in\", kind, schema);\n }\n constrainOut(kind, schema) {\n return this._constrain(\"out\", kind, schema);\n }\n _constrain(io, kind, schema) {\n const constraint = this.$.node(kind, schema);\n if (constraint.isRoot()) {\n // if the node reduces to `unknown`, nothing to do (e.g. minLength: 0)\n return constraint.isUnknown() ? this : (throwInternalError(`Unexpected constraint node ${constraint}`));\n }\n const operand = io === \"root\" ? this\n : io === \"in\" ? this.rawIn\n : this.rawOut;\n if (operand.hasKind(\"morph\") ||\n (constraint.impliedBasis && !operand.extends(constraint.impliedBasis))) {\n return throwInvalidOperandError(kind, constraint.impliedBasis, this);\n }\n const partialIntersection = this.$.node(\"intersection\", {\n // important this is constraint.kind instead of kind in case\n // the node was reduced during parsing\n [constraint.kind]: constraint\n });\n const result = io === \"out\" ?\n pipeNodesRoot(this, partialIntersection, this.$)\n : intersectNodesRoot(this, partialIntersection, this.$);\n if (result instanceof Disjoint)\n result.throw();\n return this.$.finalize(result);\n }\n onUndeclaredKey(cfg) {\n const rule = typeof cfg === \"string\" ? cfg : cfg.rule;\n const deep = typeof cfg === \"string\" ? false : cfg.deep;\n return this.$.finalize(this.transform((kind, inner) => kind === \"structure\" ?\n rule === \"ignore\" ?\n omit(inner, { undeclared: 1 })\n : { ...inner, undeclared: rule }\n : inner, deep ? undefined : ({ shouldTransform: node => !includes(structuralKinds, node.kind) })));\n }\n hasEqualMorphs(r) {\n if (!this.includesTransform && !r.includesTransform)\n return true;\n if (!arrayEquals(this.shallowMorphs, r.shallowMorphs))\n return false;\n if (!arrayEquals(this.flatMorphs, r.flatMorphs, {\n isEqual: (l, r) => l.propString === r.propString &&\n (l.node.hasKind(\"morph\") && r.node.hasKind(\"morph\") ?\n l.node.hasEqualMorphs(r.node)\n : l.node.hasKind(\"intersection\") && r.node.hasKind(\"intersection\") ?\n l.node.structure?.structuralMorphRef ===\n r.node.structure?.structuralMorphRef\n : false)\n }))\n return false;\n return true;\n }\n onDeepUndeclaredKey(behavior) {\n return this.onUndeclaredKey({ rule: behavior, deep: true });\n }\n filter(predicate) {\n return this.constrainIn(\"predicate\", predicate);\n }\n divisibleBy(schema) {\n return this.constrain(\"divisor\", schema);\n }\n matching(schema) {\n return this.constrain(\"pattern\", schema);\n }\n atLeast(schema) {\n return this.constrain(\"min\", schema);\n }\n atMost(schema) {\n return this.constrain(\"max\", schema);\n }\n moreThan(schema) {\n return this.constrain(\"min\", exclusivizeRangeSchema(schema));\n }\n lessThan(schema) {\n return this.constrain(\"max\", exclusivizeRangeSchema(schema));\n }\n atLeastLength(schema) {\n return this.constrain(\"minLength\", schema);\n }\n atMostLength(schema) {\n return this.constrain(\"maxLength\", schema);\n }\n moreThanLength(schema) {\n return this.constrain(\"minLength\", exclusivizeRangeSchema(schema));\n }\n lessThanLength(schema) {\n return this.constrain(\"maxLength\", exclusivizeRangeSchema(schema));\n }\n exactlyLength(schema) {\n return this.constrain(\"exactLength\", schema);\n }\n atOrAfter(schema) {\n return this.constrain(\"after\", schema);\n }\n atOrBefore(schema) {\n return this.constrain(\"before\", schema);\n }\n laterThan(schema) {\n return this.constrain(\"after\", exclusivizeRangeSchema(schema));\n }\n earlierThan(schema) {\n return this.constrain(\"before\", exclusivizeRangeSchema(schema));\n }\n}\nexport const emptyBrandNameMessage = `Expected a non-empty brand name after #`;\nconst supportedJsonSchemaTargets = [\n \"draft-2020-12\",\n \"draft-07\"\n];\nexport const writeInvalidJsonSchemaTargetMessage = (target) => `JSONSchema target '${target}' is not supported (must be ${supportedJsonSchemaTargets.map(t => `\"${t}\"`).join(\" or \")})`;\nconst validateStandardJsonSchemaTarget = (target) => {\n if (!includes(supportedJsonSchemaTargets, target))\n throwParseError(writeInvalidJsonSchemaTargetMessage(target));\n return target;\n};\nexport const exclusivizeRangeSchema = (schema) => (typeof schema === \"object\" && !(schema instanceof Date) ?\n { ...schema, exclusive: true }\n : {\n rule: schema,\n exclusive: true\n });\nexport const typeOrTermExtends = (t, base) => hasArkKind(base, \"root\") ?\n hasArkKind(t, \"root\") ? t.extends(base)\n : base.allows(t)\n : hasArkKind(t, \"root\") ? t.hasUnit(base)\n : base === t;\nconst structureOf = (branch) => {\n if (branch.hasKind(\"morph\"))\n return null;\n if (branch.hasKind(\"intersection\")) {\n return (branch.inner.structure ??\n (branch.basis?.domain === \"object\" ?\n branch.$.bindReference($ark.intrinsic.emptyStructure)\n : null));\n }\n if (branch.isBasis() && branch.domain === \"object\")\n return branch.$.bindReference($ark.intrinsic.emptyStructure);\n return null;\n};\nexport const writeLiteralUnionEntriesMessage = (expression) => `Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:\n${expression}`;\nexport const writeNonStructuralOperandMessage = (operation, operand) => `${operation} operand must be an object (was ${operand})`;\n",
136
+ "import { flatMorph } from \"@ark/util\";\nimport { schemaKindsRightOf } from \"../shared/implement.js\";\nexport const defineRightwardIntersections = (kind, implementation) => flatMorph(schemaKindsRightOf(kind), (i, kind) => [\n kind,\n implementation\n]);\n",
137
+ "import { append, domainDescriptions, printable, throwInternalError, throwParseError } from \"@ark/util\";\nimport { nodesByRegisteredId } from \"../parse.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { intersectOrPipeNodes } from \"../shared/intersections.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { hasArkKind } from \"../shared/utils.js\";\nimport { BaseRoot } from \"./root.js\";\nimport { defineRightwardIntersections } from \"./utils.js\";\nexport const normalizeAliasSchema = (schema) => typeof schema === \"string\" ? { reference: schema } : schema;\nconst neverIfDisjoint = (result) => result instanceof Disjoint ? $ark.intrinsic.never.internal : result;\nconst implementation = implementNode({\n kind: \"alias\",\n hasAssociatedError: false,\n collapsibleKey: \"reference\",\n keys: {\n reference: {\n serialize: s => (s.startsWith(\"$\") ? s : `$ark.${s}`)\n },\n resolve: {}\n },\n normalize: normalizeAliasSchema,\n defaults: {\n description: node => node.reference\n },\n intersections: {\n alias: (l, r, ctx) => ctx.$.lazilyResolve(() => neverIfDisjoint(intersectOrPipeNodes(l.resolution, r.resolution, ctx)), `${l.reference}${ctx.pipe ? \"=>\" : \"&\"}${r.reference}`),\n ...defineRightwardIntersections(\"alias\", (l, r, ctx) => {\n if (r.isUnknown())\n return l;\n if (r.isNever())\n return r;\n if (r.isBasis() && !r.overlaps($ark.intrinsic.object)) {\n // can be more robust as part of https://github.com/arktypeio/arktype/issues/1026\n return Disjoint.init(\"assignability\", $ark.intrinsic.object, r);\n }\n return ctx.$.lazilyResolve(() => neverIfDisjoint(intersectOrPipeNodes(l.resolution, r, ctx)), `${l.reference}${ctx.pipe ? \"=>\" : \"&\"}${r.id}`);\n })\n }\n});\nexport class AliasNode extends BaseRoot {\n expression = this.reference;\n structure = undefined;\n get resolution() {\n const result = this._resolve();\n return (nodesByRegisteredId[this.id] = result);\n }\n _resolve() {\n if (this.resolve)\n return this.resolve();\n if (this.reference[0] === \"$\")\n return this.$.resolveRoot(this.reference.slice(1));\n const id = this.reference;\n let resolution = nodesByRegisteredId[id];\n const seen = [];\n while (hasArkKind(resolution, \"context\")) {\n if (seen.includes(resolution.id)) {\n return throwParseError(writeShallowCycleErrorMessage(resolution.id, seen));\n }\n seen.push(resolution.id);\n resolution = nodesByRegisteredId[resolution.id];\n }\n if (!hasArkKind(resolution, \"root\")) {\n return throwInternalError(`Unexpected resolution for reference ${this.reference}\nSeen: [${seen.join(\"->\")}] \nResolution: ${printable(resolution)}`);\n }\n return resolution;\n }\n get resolutionId() {\n if (this.reference.includes(\"&\") || this.reference.includes(\"=>\"))\n return this.resolution.id;\n if (this.reference[0] !== \"$\")\n return this.reference;\n const alias = this.reference.slice(1);\n const resolution = this.$.resolutions[alias];\n if (typeof resolution === \"string\")\n return resolution;\n if (hasArkKind(resolution, \"root\"))\n return resolution.id;\n return throwInternalError(`Unexpected resolution for reference ${this.reference}: ${printable(resolution)}`);\n }\n get defaultShortDescription() {\n return domainDescriptions.object;\n }\n innerToJsonSchema(ctx) {\n return this.resolution.toJsonSchemaRecurse(ctx);\n }\n traverseAllows = (data, ctx) => {\n const seen = ctx.seen[this.reference];\n if (seen?.includes(data))\n return true;\n ctx.seen[this.reference] = append(seen, data);\n return this.resolution.traverseAllows(data, ctx);\n };\n traverseApply = (data, ctx) => {\n const seen = ctx.seen[this.reference];\n if (seen?.includes(data))\n return;\n ctx.seen[this.reference] = append(seen, data);\n this.resolution.traverseApply(data, ctx);\n };\n compile(js) {\n const id = this.resolutionId;\n js.if(`ctx.seen.${id} && ctx.seen.${id}.includes(data)`, () => js.return(true));\n js.if(`!ctx.seen.${id}`, () => js.line(`ctx.seen.${id} = []`));\n js.line(`ctx.seen.${id}.push(data)`);\n js.return(js.invoke(id));\n }\n}\nexport const writeShallowCycleErrorMessage = (name, seen) => `Alias '${name}' has a shallow resolution cycle: ${[...seen, name].join(\"->\")}`;\nexport const Alias = {\n implementation,\n Node: AliasNode\n};\n",
138
+ "import { compileObjectLiteral } from \"../shared/implement.js\";\nimport { BaseRoot } from \"./root.js\";\nexport class InternalBasis extends BaseRoot {\n traverseApply = (data, ctx) => {\n if (!this.traverseAllows(data, ctx))\n ctx.errorFromNodeContext(this.errorContext);\n };\n get errorContext() {\n return {\n code: this.kind,\n description: this.description,\n meta: this.meta,\n ...this.inner\n };\n }\n get compiledErrorContext() {\n return compileObjectLiteral(this.errorContext);\n }\n compile(js) {\n if (js.traversalKind === \"Allows\")\n js.return(this.compiledCondition);\n else {\n js.if(this.compiledNegation, () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`));\n }\n }\n}\n",
139
+ "import { domainDescriptions, domainOf, hasKey, throwParseError } from \"@ark/util\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { InternalBasis } from \"./basis.js\";\nconst implementation = implementNode({\n kind: \"domain\",\n hasAssociatedError: true,\n collapsibleKey: \"domain\",\n keys: {\n domain: {},\n numberAllowsNaN: {}\n },\n normalize: schema => typeof schema === \"string\" ? { domain: schema }\n : hasKey(schema, \"numberAllowsNaN\") && schema.domain !== \"number\" ?\n throwParseError(Domain.writeBadAllowNanMessage(schema.domain))\n : schema,\n applyConfig: (schema, config) => (schema.numberAllowsNaN === undefined &&\n schema.domain === \"number\" &&\n config.numberAllowsNaN) ?\n { ...schema, numberAllowsNaN: true }\n : schema,\n defaults: {\n description: node => domainDescriptions[node.domain],\n actual: data => Number.isNaN(data) ? \"NaN\" : domainDescriptions[domainOf(data)]\n },\n intersections: {\n domain: (l, r) => \n // since l === r is handled by default, remaining cases are disjoint\n // outside those including options like numberAllowsNaN\n l.domain === \"number\" && r.domain === \"number\" ?\n l.numberAllowsNaN ?\n r\n : l\n : Disjoint.init(\"domain\", l, r)\n }\n});\nexport class DomainNode extends InternalBasis {\n requiresNaNCheck = this.domain === \"number\" && !this.numberAllowsNaN;\n traverseAllows = this.requiresNaNCheck ?\n data => typeof data === \"number\" && !Number.isNaN(data)\n : data => domainOf(data) === this.domain;\n compiledCondition = this.domain === \"object\" ?\n `((typeof data === \"object\" && data !== null) || typeof data === \"function\")`\n : `typeof data === \"${this.domain}\"${this.requiresNaNCheck ? \" && !Number.isNaN(data)\" : \"\"}`;\n compiledNegation = this.domain === \"object\" ?\n `((typeof data !== \"object\" || data === null) && typeof data !== \"function\")`\n : `typeof data !== \"${this.domain}\"${this.requiresNaNCheck ? \" || Number.isNaN(data)\" : \"\"}`;\n expression = this.numberAllowsNaN ? \"number | NaN\" : this.domain;\n get nestableExpression() {\n return this.numberAllowsNaN ? `(${this.expression})` : this.expression;\n }\n get defaultShortDescription() {\n return domainDescriptions[this.domain];\n }\n innerToJsonSchema(ctx) {\n if (this.domain === \"bigint\" || this.domain === \"symbol\") {\n return ctx.fallback.domain({\n code: \"domain\",\n base: {},\n domain: this.domain\n });\n }\n return {\n type: this.domain\n };\n }\n}\nexport const Domain = {\n implementation,\n Node: DomainNode,\n writeBadAllowNanMessage: (actual) => `numberAllowsNaN may only be specified with domain \"number\" (was ${actual})`\n};\n",
140
+ "import { flatMorph, hasDomain, includes, isEmptyObject, isKeyOf, throwParseError } from \"@ark/util\";\nimport { constraintKeyParser, flattenConstraints, intersectConstraints } from \"../constraint.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode, prestructuralKinds, structureKeys } from \"../shared/implement.js\";\nimport { intersectOrPipeNodes } from \"../shared/intersections.js\";\nimport { hasArkKind, isNode } from \"../shared/utils.js\";\nimport { BaseRoot } from \"./root.js\";\nimport { defineRightwardIntersections } from \"./utils.js\";\nconst implementation = implementNode({\n kind: \"intersection\",\n hasAssociatedError: true,\n normalize: rawSchema => {\n if (isNode(rawSchema))\n return rawSchema;\n const { structure, ...schema } = rawSchema;\n const hasRootStructureKey = !!structure;\n const normalizedStructure = structure ?? {};\n const normalized = flatMorph(schema, (k, v) => {\n if (isKeyOf(k, structureKeys)) {\n if (hasRootStructureKey) {\n throwParseError(`Flattened structure key ${k} cannot be specified alongside a root 'structure' key.`);\n }\n normalizedStructure[k] = v;\n return [];\n }\n return [k, v];\n });\n if (hasArkKind(normalizedStructure, \"constraint\") ||\n !isEmptyObject(normalizedStructure))\n normalized.structure = normalizedStructure;\n return normalized;\n },\n finalizeInnerJson: ({ structure, ...rest }) => hasDomain(structure, \"object\") ? { ...structure, ...rest } : rest,\n keys: {\n domain: {\n child: true,\n parse: (schema, ctx) => ctx.$.node(\"domain\", schema)\n },\n proto: {\n child: true,\n parse: (schema, ctx) => ctx.$.node(\"proto\", schema)\n },\n structure: {\n child: true,\n parse: (schema, ctx) => ctx.$.node(\"structure\", schema),\n serialize: node => {\n if (!node.sequence?.minLength)\n return node.collapsibleJson;\n const { sequence, ...structureJson } = node.collapsibleJson;\n const { minVariadicLength, ...sequenceJson } = sequence;\n const collapsibleSequenceJson = sequenceJson.variadic && Object.keys(sequenceJson).length === 1 ?\n sequenceJson.variadic\n : sequenceJson;\n return { ...structureJson, sequence: collapsibleSequenceJson };\n }\n },\n divisor: {\n child: true,\n parse: constraintKeyParser(\"divisor\")\n },\n max: {\n child: true,\n parse: constraintKeyParser(\"max\")\n },\n min: {\n child: true,\n parse: constraintKeyParser(\"min\")\n },\n maxLength: {\n child: true,\n parse: constraintKeyParser(\"maxLength\")\n },\n minLength: {\n child: true,\n parse: constraintKeyParser(\"minLength\")\n },\n exactLength: {\n child: true,\n parse: constraintKeyParser(\"exactLength\")\n },\n before: {\n child: true,\n parse: constraintKeyParser(\"before\")\n },\n after: {\n child: true,\n parse: constraintKeyParser(\"after\")\n },\n pattern: {\n child: true,\n parse: constraintKeyParser(\"pattern\")\n },\n predicate: {\n child: true,\n parse: constraintKeyParser(\"predicate\")\n }\n },\n // leverage reduction logic from intersection and identity to ensure initial\n // parse result is reduced\n reduce: (inner, $) => \n // we cast union out of the result here since that only occurs when intersecting two sequences\n // that cannot occur when reducing a single intersection schema using unknown\n intersectIntersections({}, inner, {\n $,\n invert: false,\n pipe: false\n }),\n defaults: {\n description: node => {\n if (node.children.length === 0)\n return \"unknown\";\n if (node.structure)\n return node.structure.description;\n const childDescriptions = [];\n if (node.basis &&\n !node.prestructurals.some(r => r.impl.obviatesBasisDescription))\n childDescriptions.push(node.basis.description);\n if (node.prestructurals.length) {\n const sortedRefinementDescriptions = node.prestructurals\n .slice()\n // override alphabetization to describe min before max\n .sort((l, r) => (l.kind === \"min\" && r.kind === \"max\" ? -1 : 0))\n .map(r => r.description);\n childDescriptions.push(...sortedRefinementDescriptions);\n }\n if (node.inner.predicate) {\n childDescriptions.push(...node.inner.predicate.map(p => p.description));\n }\n return childDescriptions.join(\" and \");\n },\n expected: source => ` ◦ ${source.errors.map(e => e.expected).join(\"\\n ◦ \")}`,\n problem: ctx => `(${ctx.actual}) must be...\\n${ctx.expected}`\n },\n intersections: {\n intersection: (l, r, ctx) => intersectIntersections(l.inner, r.inner, ctx),\n ...defineRightwardIntersections(\"intersection\", (l, r, ctx) => {\n // if l is unknown, return r\n if (l.children.length === 0)\n return r;\n const { domain, proto, ...lInnerConstraints } = l.inner;\n const lBasis = proto ?? domain;\n const basis = lBasis ? intersectOrPipeNodes(lBasis, r, ctx) : r;\n return (basis instanceof Disjoint ? basis\n : l?.basis?.equals(basis) ?\n // if the basis doesn't change, return the original intesection\n l\n // given we've already precluded l being unknown, the result must\n // be an intersection with the new basis result integrated\n : l.$.node(\"intersection\", { ...lInnerConstraints, [basis.kind]: basis }, { prereduced: true }));\n })\n }\n});\nexport class IntersectionNode extends BaseRoot {\n basis = this.inner.domain ?? this.inner.proto ?? null;\n prestructurals = [];\n refinements = this.children.filter((node) => {\n if (!node.isRefinement())\n return false;\n if (includes(prestructuralKinds, node.kind))\n // mutation is fine during initialization\n this.prestructurals.push(node);\n return true;\n });\n structure = this.inner.structure;\n expression = writeIntersectionExpression(this);\n get shallowMorphs() {\n return this.inner.structure?.structuralMorph ?\n [this.inner.structure.structuralMorph]\n : [];\n }\n get defaultShortDescription() {\n return this.basis?.defaultShortDescription ?? \"present\";\n }\n innerToJsonSchema(ctx) {\n return this.children.reduce(\n // cast is required since TS doesn't know children have compatible schema prerequisites\n (schema, child) => child.isBasis() ?\n child.toJsonSchemaRecurse(ctx)\n : child.reduceJsonSchema(schema, ctx), {});\n }\n traverseAllows = (data, ctx) => this.children.every(child => child.traverseAllows(data, ctx));\n traverseApply = (data, ctx) => {\n const errorCount = ctx.currentErrorCount;\n if (this.basis) {\n this.basis.traverseApply(data, ctx);\n if (ctx.currentErrorCount > errorCount)\n return;\n }\n if (this.prestructurals.length) {\n for (let i = 0; i < this.prestructurals.length - 1; i++) {\n this.prestructurals[i].traverseApply(data, ctx);\n if (ctx.failFast && ctx.currentErrorCount > errorCount)\n return;\n }\n this.prestructurals[this.prestructurals.length - 1].traverseApply(data, ctx);\n if (ctx.currentErrorCount > errorCount)\n return;\n }\n if (this.structure) {\n this.structure.traverseApply(data, ctx);\n if (ctx.currentErrorCount > errorCount)\n return;\n }\n if (this.inner.predicate) {\n for (let i = 0; i < this.inner.predicate.length - 1; i++) {\n this.inner.predicate[i].traverseApply(data, ctx);\n if (ctx.failFast && ctx.currentErrorCount > errorCount)\n return;\n }\n this.inner.predicate[this.inner.predicate.length - 1].traverseApply(data, ctx);\n }\n };\n compile(js) {\n if (js.traversalKind === \"Allows\") {\n for (const child of this.children)\n js.check(child);\n js.return(true);\n return;\n }\n js.initializeErrorCount();\n if (this.basis) {\n js.check(this.basis);\n // we only have to return conditionally if this is not the last check\n if (this.children.length > 1)\n js.returnIfFail();\n }\n if (this.prestructurals.length) {\n for (let i = 0; i < this.prestructurals.length - 1; i++) {\n js.check(this.prestructurals[i]);\n js.returnIfFailFast();\n }\n js.check(this.prestructurals[this.prestructurals.length - 1]);\n if (this.structure || this.inner.predicate)\n js.returnIfFail();\n }\n if (this.structure) {\n js.check(this.structure);\n if (this.inner.predicate)\n js.returnIfFail();\n }\n if (this.inner.predicate) {\n for (let i = 0; i < this.inner.predicate.length - 1; i++) {\n js.check(this.inner.predicate[i]);\n // since predicates can be chained, we have to fail immediately\n // if one fails\n js.returnIfFail();\n }\n js.check(this.inner.predicate[this.inner.predicate.length - 1]);\n }\n }\n}\nexport const Intersection = {\n implementation,\n Node: IntersectionNode\n};\nconst writeIntersectionExpression = (node) => {\n if (node.structure?.expression)\n return node.structure.expression;\n const basisExpression = (node.basis &&\n !node.prestructurals.some(n => n.impl.obviatesBasisExpression)) ?\n node.basis.nestableExpression\n : \"\";\n const refinementsExpression = node.prestructurals\n .map(n => n.expression)\n .join(\" & \");\n const fullExpression = `${basisExpression}${basisExpression ? \" \" : \"\"}${refinementsExpression}`;\n if (fullExpression === \"Array == 0\")\n return \"[]\";\n return fullExpression || \"unknown\";\n};\nconst intersectIntersections = (l, r, ctx) => {\n const baseInner = {};\n const lBasis = l.proto ?? l.domain;\n const rBasis = r.proto ?? r.domain;\n const basisResult = lBasis ?\n rBasis ?\n intersectOrPipeNodes(lBasis, rBasis, ctx)\n : lBasis\n : rBasis;\n if (basisResult instanceof Disjoint)\n return basisResult;\n if (basisResult)\n baseInner[basisResult.kind] = basisResult;\n return intersectConstraints({\n kind: \"intersection\",\n baseInner,\n l: flattenConstraints(l),\n r: flattenConstraints(r),\n roots: [],\n ctx\n });\n};\n",
141
+ "import { arrayEquals, liftArray, throwParseError } from \"@ark/util\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { intersectOrPipeNodes } from \"../shared/intersections.js\";\nimport { $ark, registeredReference } from \"../shared/registry.js\";\nimport { hasArkKind } from \"../shared/utils.js\";\nimport { BaseRoot } from \"./root.js\";\nimport { defineRightwardIntersections } from \"./utils.js\";\nconst implementation = implementNode({\n kind: \"morph\",\n hasAssociatedError: false,\n keys: {\n in: {\n child: true,\n parse: (schema, ctx) => ctx.$.parseSchema(schema)\n },\n morphs: {\n parse: liftArray,\n serialize: morphs => morphs.map(m => hasArkKind(m, \"root\") ? m.json : registeredReference(m))\n },\n declaredIn: {\n child: false,\n serialize: node => node.json\n },\n declaredOut: {\n child: false,\n serialize: node => node.json\n }\n },\n normalize: schema => schema,\n defaults: {\n description: node => `a morph from ${node.rawIn.description} to ${node.rawOut?.description ?? \"unknown\"}`\n },\n intersections: {\n morph: (l, r, ctx) => {\n if (!l.hasEqualMorphs(r)) {\n return throwParseError(writeMorphIntersectionMessage(l.expression, r.expression));\n }\n const inTersection = intersectOrPipeNodes(l.rawIn, r.rawIn, ctx);\n if (inTersection instanceof Disjoint)\n return inTersection;\n const baseInner = {\n morphs: l.morphs\n };\n if (l.declaredIn || r.declaredIn) {\n const declaredIn = intersectOrPipeNodes(l.rawIn, r.rawIn, ctx);\n // we can't treat this as a normal Disjoint since it's just declared\n // it should only happen if someone's essentially trying to create a broken type\n if (declaredIn instanceof Disjoint)\n return declaredIn.throw();\n else\n baseInner.declaredIn = declaredIn;\n }\n if (l.declaredOut || r.declaredOut) {\n const declaredOut = intersectOrPipeNodes(l.rawOut, r.rawOut, ctx);\n if (declaredOut instanceof Disjoint)\n return declaredOut.throw();\n else\n baseInner.declaredOut = declaredOut;\n }\n // in case from is a union, we need to distribute the branches\n // to can be a union as any schema is allowed\n return inTersection.distribute(inBranch => ctx.$.node(\"morph\", {\n ...baseInner,\n in: inBranch\n }), ctx.$.parseSchema);\n },\n ...defineRightwardIntersections(\"morph\", (l, r, ctx) => {\n const inTersection = l.inner.in ? intersectOrPipeNodes(l.inner.in, r, ctx) : r;\n return (inTersection instanceof Disjoint ? inTersection\n : inTersection.equals(l.inner.in) ? l\n : ctx.$.node(\"morph\", {\n ...l.inner,\n in: inTersection\n }));\n })\n }\n});\nexport class MorphNode extends BaseRoot {\n serializedMorphs = this.morphs.map(registeredReference);\n compiledMorphs = `[${this.serializedMorphs}]`;\n lastMorph = this.inner.morphs[this.inner.morphs.length - 1];\n lastMorphIfNode = hasArkKind(this.lastMorph, \"root\") ? this.lastMorph : undefined;\n introspectableIn = this.inner.in;\n introspectableOut = this.lastMorphIfNode ?\n Object.assign(this.referencesById, this.lastMorphIfNode.referencesById) &&\n this.lastMorphIfNode.rawOut\n : undefined;\n get shallowMorphs() {\n // if the morph input is a union, it should not contain any other shallow morphs\n return Array.isArray(this.inner.in?.shallowMorphs) ?\n [...this.inner.in.shallowMorphs, ...this.morphs]\n : this.morphs;\n }\n get rawIn() {\n return (this.declaredIn ?? this.inner.in?.rawIn ?? $ark.intrinsic.unknown.internal);\n }\n get rawOut() {\n return (this.declaredOut ??\n this.introspectableOut ??\n $ark.intrinsic.unknown.internal);\n }\n declareIn(declaredIn) {\n return this.$.node(\"morph\", {\n ...this.inner,\n declaredIn\n });\n }\n declareOut(declaredOut) {\n return this.$.node(\"morph\", {\n ...this.inner,\n declaredOut\n });\n }\n expression = `(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode ? \"To\" : \"Out\"}<${this.rawOut.expression}>`;\n get defaultShortDescription() {\n return this.rawIn.meta.description ?? this.rawIn.defaultShortDescription;\n }\n innerToJsonSchema(ctx) {\n return ctx.fallback.morph({\n code: \"morph\",\n base: this.rawIn.toJsonSchemaRecurse(ctx),\n out: this.introspectableOut?.toJsonSchemaRecurse(ctx) ?? null\n });\n }\n compile(js) {\n if (js.traversalKind === \"Allows\") {\n if (!this.introspectableIn)\n return;\n js.return(js.invoke(this.introspectableIn));\n return;\n }\n if (this.introspectableIn)\n js.line(js.invoke(this.introspectableIn));\n js.line(`ctx.queueMorphs(${this.compiledMorphs})`);\n }\n traverseAllows = (data, ctx) => !this.introspectableIn || this.introspectableIn.traverseAllows(data, ctx);\n traverseApply = (data, ctx) => {\n if (this.introspectableIn)\n this.introspectableIn.traverseApply(data, ctx);\n ctx.queueMorphs(this.morphs);\n };\n /** Check if the morphs of r are equal to those of this node */\n hasEqualMorphs(r) {\n return arrayEquals(this.morphs, r.morphs, {\n isEqual: (lMorph, rMorph) => lMorph === rMorph ||\n (hasArkKind(lMorph, \"root\") &&\n hasArkKind(rMorph, \"root\") &&\n lMorph.equals(rMorph))\n });\n }\n}\nexport const Morph = {\n implementation,\n Node: MorphNode\n};\nexport const writeMorphIntersectionMessage = (lDescription, rDescription) => `The intersection of distinct morphs at a single path is indeterminate:\nLeft: ${lDescription}\nRight: ${rDescription}`;\n",
142
+ "import { builtinConstructors, constructorExtends, domainOf, getBuiltinNameOfConstructor, hasKey, objectKindDescriptions, objectKindOrDomainOf, throwParseError } from \"@ark/util\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { defaultValueSerializer, implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { isNode } from \"../shared/utils.js\";\nimport { InternalBasis } from \"./basis.js\";\nconst implementation = implementNode({\n kind: \"proto\",\n hasAssociatedError: true,\n collapsibleKey: \"proto\",\n keys: {\n proto: {\n serialize: ctor => getBuiltinNameOfConstructor(ctor) ?? defaultValueSerializer(ctor)\n },\n dateAllowsInvalid: {}\n },\n normalize: schema => {\n const normalized = typeof schema === \"string\" ? { proto: builtinConstructors[schema] }\n : typeof schema === \"function\" ?\n isNode(schema) ? schema\n : { proto: schema }\n : typeof schema.proto === \"string\" ?\n { ...schema, proto: builtinConstructors[schema.proto] }\n : schema;\n if (typeof normalized.proto !== \"function\")\n throwParseError(Proto.writeInvalidSchemaMessage(normalized.proto));\n if (hasKey(normalized, \"dateAllowsInvalid\") && normalized.proto !== Date)\n throwParseError(Proto.writeBadInvalidDateMessage(normalized.proto));\n return normalized;\n },\n applyConfig: (schema, config) => {\n if (schema.dateAllowsInvalid === undefined &&\n schema.proto === Date &&\n config.dateAllowsInvalid)\n return { ...schema, dateAllowsInvalid: true };\n return schema;\n },\n defaults: {\n description: node => node.builtinName ?\n objectKindDescriptions[node.builtinName]\n : `an instance of ${node.proto.name}`,\n actual: data => data instanceof Date && data.toString() === \"Invalid Date\" ?\n \"an invalid Date\"\n : objectKindOrDomainOf(data)\n },\n intersections: {\n proto: (l, r) => l.proto === Date && r.proto === Date ?\n // since l === r is handled by default,\n // exactly one of l or r must have allow invalid dates\n l.dateAllowsInvalid ?\n r\n : l\n : constructorExtends(l.proto, r.proto) ? l\n : constructorExtends(r.proto, l.proto) ? r\n : Disjoint.init(\"proto\", l, r),\n domain: (proto, domain) => domain.domain === \"object\" ?\n proto\n : Disjoint.init(\"domain\", $ark.intrinsic.object.internal, domain)\n }\n});\nexport class ProtoNode extends InternalBasis {\n builtinName = getBuiltinNameOfConstructor(this.proto);\n serializedConstructor = this.json.proto;\n requiresInvalidDateCheck = this.proto === Date && !this.dateAllowsInvalid;\n traverseAllows = this.requiresInvalidDateCheck ?\n data => data instanceof Date && data.toString() !== \"Invalid Date\"\n : data => data instanceof this.proto;\n compiledCondition = `data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck ? ` && data.toString() !== \"Invalid Date\"` : \"\"}`;\n compiledNegation = `!(${this.compiledCondition})`;\n innerToJsonSchema(ctx) {\n switch (this.builtinName) {\n case \"Array\":\n return {\n type: \"array\"\n };\n case \"Date\":\n return (ctx.fallback.date?.({ code: \"date\", base: {} }) ??\n ctx.fallback.proto({ code: \"proto\", base: {}, proto: this.proto }));\n default:\n return ctx.fallback.proto({\n code: \"proto\",\n base: {},\n proto: this.proto\n });\n }\n }\n expression = this.dateAllowsInvalid ? \"Date | InvalidDate\" : this.proto.name;\n get nestableExpression() {\n return this.dateAllowsInvalid ? `(${this.expression})` : this.expression;\n }\n domain = \"object\";\n get defaultShortDescription() {\n return this.description;\n }\n}\nexport const Proto = {\n implementation,\n Node: ProtoNode,\n writeBadInvalidDateMessage: (actual) => `dateAllowsInvalid may only be specified with constructor Date (was ${actual.name})`,\n writeInvalidSchemaMessage: (actual) => `instanceOf operand must be a function (was ${domainOf(actual)})`\n};\n",
143
+ "import { appendUnique, arrayEquals, domainDescriptions, flatMorph, groupBy, hasKey, isArray, jsTypeOfDescriptions, printable, range, throwParseError, unset } from \"@ark/util\";\nimport { compileLiteralPropAccess, compileSerializedValue } from \"../shared/compile.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { intersectNodesRoot, intersectOrPipeNodes } from \"../shared/intersections.js\";\nimport { $ark, registeredReference } from \"../shared/registry.js\";\nimport { Traversal } from \"../shared/traversal.js\";\nimport { hasArkKind } from \"../shared/utils.js\";\nimport { BaseRoot } from \"./root.js\";\nimport { defineRightwardIntersections } from \"./utils.js\";\nconst implementation = implementNode({\n kind: \"union\",\n hasAssociatedError: true,\n collapsibleKey: \"branches\",\n keys: {\n ordered: {},\n branches: {\n child: true,\n parse: (schema, ctx) => {\n const branches = [];\n for (const branchSchema of schema) {\n const branchNodes = hasArkKind(branchSchema, \"root\") ?\n branchSchema.branches\n : ctx.$.parseSchema(branchSchema).branches;\n for (const node of branchNodes) {\n if (node.hasKind(\"morph\")) {\n const matchingMorphIndex = branches.findIndex(matching => matching.hasKind(\"morph\") && matching.hasEqualMorphs(node));\n if (matchingMorphIndex === -1)\n branches.push(node);\n else {\n const matchingMorph = branches[matchingMorphIndex];\n branches[matchingMorphIndex] = ctx.$.node(\"morph\", {\n ...matchingMorph.inner,\n in: matchingMorph.rawIn.rawOr(node.rawIn)\n });\n }\n }\n else\n branches.push(node);\n }\n }\n if (!ctx.def.ordered)\n branches.sort((l, r) => (l.hash < r.hash ? -1 : 1));\n return branches;\n }\n }\n },\n normalize: schema => (isArray(schema) ? { branches: schema } : schema),\n reduce: (inner, $) => {\n const reducedBranches = reduceBranches(inner);\n if (reducedBranches.length === 1)\n return reducedBranches[0];\n if (reducedBranches.length === inner.branches.length)\n return;\n return $.node(\"union\", {\n ...inner,\n branches: reducedBranches\n }, { prereduced: true });\n },\n defaults: {\n description: node => node.distribute(branch => branch.description, describeBranches),\n expected: ctx => {\n const byPath = groupBy(ctx.errors, \"propString\");\n const pathDescriptions = Object.entries(byPath).map(([path, errors]) => {\n const branchesAtPath = [];\n for (const errorAtPath of errors)\n appendUnique(branchesAtPath, errorAtPath.expected);\n const expected = describeBranches(branchesAtPath);\n // if there are multiple actual descriptions that differ,\n // just fall back to printable, which is the most specific\n const actual = errors.every(e => e.actual === errors[0].actual) ?\n errors[0].actual\n : printable(errors[0].data);\n return `${path && `${path} `}must be ${expected}${actual && ` (was ${actual})`}`;\n });\n return describeBranches(pathDescriptions);\n },\n problem: ctx => ctx.expected,\n message: ctx => {\n if (ctx.problem[0] === \"[\") {\n // clarify paths like [1], [0][1], and [\"key!\"] that could be confusing\n return `value at ${ctx.problem}`;\n }\n return ctx.problem;\n }\n },\n intersections: {\n union: (l, r, ctx) => {\n if (l.isNever !== r.isNever) {\n // if exactly one operand is never, we can use it to discriminate based on presence\n return Disjoint.init(\"presence\", l, r);\n }\n let resultBranches;\n if (l.ordered) {\n if (r.ordered) {\n throwParseError(writeOrderedIntersectionMessage(l.expression, r.expression));\n }\n resultBranches = intersectBranches(r.branches, l.branches, ctx);\n if (resultBranches instanceof Disjoint)\n resultBranches.invert();\n }\n else\n resultBranches = intersectBranches(l.branches, r.branches, ctx);\n if (resultBranches instanceof Disjoint)\n return resultBranches;\n return ctx.$.parseSchema(l.ordered || r.ordered ?\n {\n branches: resultBranches,\n ordered: true\n }\n : { branches: resultBranches });\n },\n ...defineRightwardIntersections(\"union\", (l, r, ctx) => {\n const branches = intersectBranches(l.branches, [r], ctx);\n if (branches instanceof Disjoint)\n return branches;\n if (branches.length === 1)\n return branches[0];\n return ctx.$.parseSchema(l.ordered ? { branches, ordered: true } : { branches });\n })\n }\n});\nexport class UnionNode extends BaseRoot {\n isBoolean = this.branches.length === 2 &&\n this.branches[0].hasUnit(false) &&\n this.branches[1].hasUnit(true);\n get branchGroups() {\n const branchGroups = [];\n let firstBooleanIndex = -1;\n for (const branch of this.branches) {\n if (branch.hasKind(\"unit\") && branch.domain === \"boolean\") {\n if (firstBooleanIndex === -1) {\n firstBooleanIndex = branchGroups.length;\n branchGroups.push(branch);\n }\n else\n branchGroups[firstBooleanIndex] = $ark.intrinsic.boolean;\n continue;\n }\n branchGroups.push(branch);\n }\n return branchGroups;\n }\n unitBranches = this.branches.filter((n) => n.rawIn.hasKind(\"unit\"));\n discriminant = this.discriminate();\n discriminantJson = this.discriminant ? discriminantToJson(this.discriminant) : null;\n expression = this.distribute(n => n.nestableExpression, expressBranches);\n createBranchedOptimisticRootApply() {\n return (data, onFail) => {\n const optimisticResult = this.traverseOptimistic(data);\n if (optimisticResult !== unset)\n return optimisticResult;\n const ctx = new Traversal(data, this.$.resolvedConfig);\n this.traverseApply(data, ctx);\n return ctx.finalize(onFail);\n };\n }\n get shallowMorphs() {\n return this.branches.reduce((morphs, branch) => appendUnique(morphs, branch.shallowMorphs), []);\n }\n get defaultShortDescription() {\n return this.distribute(branch => branch.defaultShortDescription, describeBranches);\n }\n innerToJsonSchema(ctx) {\n // special case to simplify { const: true } | { const: false }\n // to the canonical JSON Schema representation { type: \"boolean\" }\n if (this.branchGroups.length === 1 &&\n this.branchGroups[0].equals($ark.intrinsic.boolean))\n return { type: \"boolean\" };\n const jsonSchemaBranches = this.branchGroups.map(group => group.toJsonSchemaRecurse(ctx));\n if (jsonSchemaBranches.every((branch) => \n // iff all branches are pure unit values with no metadata,\n // we can simplify the representation to an enum\n Object.keys(branch).length === 1 && hasKey(branch, \"const\"))) {\n return {\n enum: jsonSchemaBranches.map(branch => branch.const)\n };\n }\n return {\n anyOf: jsonSchemaBranches\n };\n }\n traverseAllows = (data, ctx) => this.branches.some(b => b.traverseAllows(data, ctx));\n traverseApply = (data, ctx) => {\n const errors = [];\n for (let i = 0; i < this.branches.length; i++) {\n ctx.pushBranch();\n this.branches[i].traverseApply(data, ctx);\n if (!ctx.hasError()) {\n if (this.branches[i].includesTransform)\n return ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs);\n return ctx.popBranch();\n }\n errors.push(ctx.popBranch().error);\n }\n ctx.errorFromNodeContext({ code: \"union\", errors, meta: this.meta });\n };\n traverseOptimistic = (data) => {\n for (let i = 0; i < this.branches.length; i++) {\n const branch = this.branches[i];\n if (branch.traverseAllows(data)) {\n if (branch.contextFreeMorph)\n return branch.contextFreeMorph(data);\n // if we're calling this function and the matching branch didn't have\n // a context-free morph, it shouldn't have morphs at all\n return data;\n }\n }\n return unset;\n };\n compile(js) {\n if (!this.discriminant ||\n // if we have a union of two units like `boolean`, the\n // undiscriminated compilation will be just as fast\n (this.unitBranches.length === this.branches.length &&\n this.branches.length === 2))\n return this.compileIndiscriminable(js);\n // we need to access the path as optional so we don't throw if it isn't present\n let condition = this.discriminant.optionallyChainedPropString;\n if (this.discriminant.kind === \"domain\")\n condition = `typeof ${condition} === \"object\" ? ${condition} === null ? \"null\" : \"object\" : typeof ${condition} === \"function\" ? \"object\" : typeof ${condition}`;\n const cases = this.discriminant.cases;\n const caseKeys = Object.keys(cases);\n const { optimistic } = js;\n // only the first layer can be optimistic\n js.optimistic = false;\n js.block(`switch(${condition})`, () => {\n for (const k in cases) {\n const v = cases[k];\n const caseCondition = k === \"default\" ? k : `case ${k}`;\n let caseResult;\n if (v === true)\n caseResult = optimistic ? \"data\" : \"true\";\n else if (optimistic) {\n if (v.rootApplyStrategy === \"branchedOptimistic\")\n caseResult = js.invoke(v, { kind: \"Optimistic\" });\n else if (v.contextFreeMorph)\n caseResult = `${js.invoke(v)} ? ${registeredReference(v.contextFreeMorph)}(data) : \"${unset}\"`;\n else\n caseResult = `${js.invoke(v)} ? data : \"${unset}\"`;\n }\n else\n caseResult = js.invoke(v);\n js.line(`${caseCondition}: return ${caseResult}`);\n }\n return js;\n });\n if (js.traversalKind === \"Allows\") {\n js.return(optimistic ? `\"${unset}\"` : false);\n return;\n }\n const expected = describeBranches(this.discriminant.kind === \"domain\" ?\n caseKeys.map(k => {\n const jsTypeOf = k.slice(1, -1);\n return jsTypeOf === \"function\" ?\n domainDescriptions.object\n : domainDescriptions[jsTypeOf];\n })\n : caseKeys);\n const serializedPathSegments = this.discriminant.path.map(k => typeof k === \"symbol\" ? registeredReference(k) : JSON.stringify(k));\n const serializedExpected = JSON.stringify(expected);\n const serializedActual = this.discriminant.kind === \"domain\" ?\n `${serializedTypeOfDescriptions}[${condition}]`\n : `${serializedPrintable}(${condition})`;\n js.line(`ctx.errorFromNodeContext({\n\tcode: \"predicate\",\n\texpected: ${serializedExpected},\n\tactual: ${serializedActual},\n\trelativePath: [${serializedPathSegments}],\n\tmeta: ${this.compiledMeta}\n})`);\n }\n compileIndiscriminable(js) {\n if (js.traversalKind === \"Apply\") {\n js.const(\"errors\", \"[]\");\n for (const branch of this.branches) {\n js.line(\"ctx.pushBranch()\")\n .line(js.invoke(branch))\n .if(\"!ctx.hasError()\", () => js.return(branch.includesTransform ?\n \"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)\"\n : \"ctx.popBranch()\"))\n .line(\"errors.push(ctx.popBranch().error)\");\n }\n js.line(`ctx.errorFromNodeContext({ code: \"union\", errors, meta: ${this.compiledMeta} })`);\n }\n else {\n const { optimistic } = js;\n // only the first layer can be optimistic\n js.optimistic = false;\n for (const branch of this.branches) {\n js.if(`${js.invoke(branch)}`, () => js.return(optimistic ?\n branch.contextFreeMorph ?\n `${registeredReference(branch.contextFreeMorph)}(data)`\n : \"data\"\n : true));\n }\n js.return(optimistic ? `\"${unset}\"` : false);\n }\n }\n get nestableExpression() {\n // avoid adding unnecessary parentheses around boolean since it's\n // already collapsed to a single keyword\n return this.isBoolean ? \"boolean\" : `(${this.expression})`;\n }\n discriminate() {\n if (this.branches.length < 2 || this.isCyclic)\n return null;\n if (this.unitBranches.length === this.branches.length) {\n const cases = flatMorph(this.unitBranches, (i, n) => [\n `${n.rawIn.serializedValue}`,\n n.hasKind(\"morph\") ? n : true\n ]);\n return {\n kind: \"unit\",\n path: [],\n optionallyChainedPropString: \"data\",\n cases\n };\n }\n const candidates = [];\n for (let lIndex = 0; lIndex < this.branches.length - 1; lIndex++) {\n const l = this.branches[lIndex];\n for (let rIndex = lIndex + 1; rIndex < this.branches.length; rIndex++) {\n const r = this.branches[rIndex];\n const result = intersectNodesRoot(l.rawIn, r.rawIn, l.$);\n if (!(result instanceof Disjoint))\n continue;\n for (const entry of result) {\n if (!entry.kind || entry.optional)\n continue;\n let lSerialized;\n let rSerialized;\n if (entry.kind === \"domain\") {\n const lValue = entry.l;\n const rValue = entry.r;\n lSerialized = `\"${typeof lValue === \"string\" ? lValue : lValue.domain}\"`;\n rSerialized = `\"${typeof rValue === \"string\" ? rValue : rValue.domain}\"`;\n }\n else if (entry.kind === \"unit\") {\n lSerialized = entry.l.serializedValue;\n rSerialized = entry.r.serializedValue;\n }\n else\n continue;\n const matching = candidates.find(d => arrayEquals(d.path, entry.path) && d.kind === entry.kind);\n if (!matching) {\n candidates.push({\n kind: entry.kind,\n cases: {\n [lSerialized]: {\n branchIndices: [lIndex],\n condition: entry.l\n },\n [rSerialized]: {\n branchIndices: [rIndex],\n condition: entry.r\n }\n },\n path: entry.path\n });\n }\n else {\n if (matching.cases[lSerialized]) {\n matching.cases[lSerialized].branchIndices = appendUnique(matching.cases[lSerialized].branchIndices, lIndex);\n }\n else {\n matching.cases[lSerialized] ??= {\n branchIndices: [lIndex],\n condition: entry.l\n };\n }\n if (matching.cases[rSerialized]) {\n matching.cases[rSerialized].branchIndices = appendUnique(matching.cases[rSerialized].branchIndices, rIndex);\n }\n else {\n matching.cases[rSerialized] ??= {\n branchIndices: [rIndex],\n condition: entry.r\n };\n }\n }\n }\n }\n }\n const viableCandidates = this.ordered ?\n viableOrderedCandidates(candidates, this.branches)\n : candidates;\n if (!viableCandidates.length)\n return null;\n const ctx = createCaseResolutionContext(viableCandidates, this);\n const cases = {};\n for (const k in ctx.best.cases) {\n const resolution = resolveCase(ctx, k);\n if (resolution === null) {\n cases[k] = true;\n continue;\n }\n // if all the branches ended up back in pruned, we'd loop if we continued\n // so just bail out- nothing left to discriminate\n if (resolution.length === this.branches.length)\n return null;\n if (this.ordered) {\n // ensure the original order of the pruned branches is preserved\n resolution.sort((l, r) => l.originalIndex - r.originalIndex);\n }\n const branches = resolution.map(entry => entry.branch);\n const caseNode = branches.length === 1 ?\n branches[0]\n : this.$.node(\"union\", this.ordered ? { branches, ordered: true } : branches);\n Object.assign(this.referencesById, caseNode.referencesById);\n cases[k] = caseNode;\n }\n if (ctx.defaultEntries.length) {\n // we don't have to worry about order here as it is always preserved\n // within defaultEntries\n const branches = ctx.defaultEntries.map(entry => entry.branch);\n cases.default = this.$.node(\"union\", this.ordered ? { branches, ordered: true } : branches, {\n prereduced: true\n });\n Object.assign(this.referencesById, cases.default.referencesById);\n }\n return Object.assign(ctx.location, {\n cases\n });\n }\n}\nconst createCaseResolutionContext = (viableCandidates, node) => {\n const ordered = viableCandidates.sort((l, r) => l.path.length === r.path.length ?\n Object.keys(r.cases).length - Object.keys(l.cases).length\n // prefer shorter paths first\n : l.path.length - r.path.length);\n const best = ordered[0];\n const location = {\n kind: best.kind,\n path: best.path,\n optionallyChainedPropString: optionallyChainPropString(best.path)\n };\n const defaultEntries = node.branches.map((branch, originalIndex) => ({\n originalIndex,\n branch\n }));\n return {\n best,\n location,\n defaultEntries,\n node\n };\n};\nconst resolveCase = (ctx, key) => {\n const caseCtx = ctx.best.cases[key];\n const discriminantNode = discriminantCaseToNode(caseCtx.condition, ctx.location.path, ctx.node.$);\n let resolvedEntries = [];\n const nextDefaults = [];\n for (let i = 0; i < ctx.defaultEntries.length; i++) {\n const entry = ctx.defaultEntries[i];\n if (caseCtx.branchIndices.includes(entry.originalIndex)) {\n const pruned = pruneDiscriminant(ctx.node.branches[entry.originalIndex], ctx.location);\n if (pruned === null) {\n // if any branch of the union has no constraints (i.e. is\n // unknown), the others won't affect the resolution type, but could still\n // remove additional cases from defaultEntries\n resolvedEntries = null;\n }\n else {\n resolvedEntries?.push({\n originalIndex: entry.originalIndex,\n branch: pruned\n });\n }\n }\n else if (\n // we shouldn't need a special case for alias to avoid the below\n // once alias resolution issues are improved:\n // https://github.com/arktypeio/arktype/issues/1026\n entry.branch.hasKind(\"alias\") &&\n discriminantNode.hasKind(\"domain\") &&\n discriminantNode.domain === \"object\")\n resolvedEntries?.push(entry);\n else {\n if (entry.branch.rawIn.overlaps(discriminantNode)) {\n // include cases where an object not including the\n // discriminant path might have that value present as an undeclared key\n const overlapping = pruneDiscriminant(entry.branch, ctx.location);\n resolvedEntries?.push({\n originalIndex: entry.originalIndex,\n branch: overlapping\n });\n }\n nextDefaults.push(entry);\n }\n }\n ctx.defaultEntries = nextDefaults;\n return resolvedEntries;\n};\nconst viableOrderedCandidates = (candidates, originalBranches) => {\n const viableCandidates = candidates.filter(candidate => {\n const caseGroups = Object.values(candidate.cases).map(caseCtx => caseCtx.branchIndices);\n // compare each group against all subsequent groups.\n for (let i = 0; i < caseGroups.length - 1; i++) {\n const currentGroup = caseGroups[i];\n for (let j = i + 1; j < caseGroups.length; j++) {\n const nextGroup = caseGroups[j];\n // for each group pair, check for branches whose order was reversed\n for (const currentIndex of currentGroup) {\n for (const nextIndex of nextGroup) {\n if (currentIndex > nextIndex) {\n if (originalBranches[currentIndex].overlaps(originalBranches[nextIndex])) {\n // if the order was not preserved and the branches overlap,\n // this is not a viable discriminant as it cannot guarantee the same behavior\n return false;\n }\n }\n }\n }\n }\n }\n // branch groups preserved order for non-disjoint pairs and is viable\n return true;\n });\n return viableCandidates;\n};\nconst discriminantCaseToNode = (caseDiscriminant, path, $) => {\n let node = caseDiscriminant === \"undefined\" ? $.node(\"unit\", { unit: undefined })\n : caseDiscriminant === \"null\" ? $.node(\"unit\", { unit: null })\n : caseDiscriminant === \"boolean\" ? $.units([true, false])\n : caseDiscriminant;\n for (let i = path.length - 1; i >= 0; i--) {\n const key = path[i];\n node = $.node(\"intersection\", typeof key === \"number\" ?\n {\n proto: \"Array\",\n // create unknown for preceding elements (could be optimized with safe imports)\n sequence: [...range(key).map(_ => ({})), node]\n }\n : {\n domain: \"object\",\n required: [{ key, value: node }]\n });\n }\n return node;\n};\nconst optionallyChainPropString = (path) => path.reduce((acc, k) => acc + compileLiteralPropAccess(k, true), \"data\");\nconst serializedTypeOfDescriptions = registeredReference(jsTypeOfDescriptions);\nconst serializedPrintable = registeredReference(printable);\nexport const Union = {\n implementation,\n Node: UnionNode\n};\nconst discriminantToJson = (discriminant) => ({\n kind: discriminant.kind,\n path: discriminant.path.map(k => typeof k === \"string\" ? k : compileSerializedValue(k)),\n cases: flatMorph(discriminant.cases, (k, node) => [\n k,\n node === true ? node\n : node.hasKind(\"union\") && node.discriminantJson ? node.discriminantJson\n : node.json\n ])\n});\nconst describeExpressionOptions = {\n delimiter: \" | \",\n finalDelimiter: \" | \"\n};\nconst expressBranches = (expressions) => describeBranches(expressions, describeExpressionOptions);\nexport const describeBranches = (descriptions, opts) => {\n const delimiter = opts?.delimiter ?? \", \";\n const finalDelimiter = opts?.finalDelimiter ?? \" or \";\n if (descriptions.length === 0)\n return \"never\";\n if (descriptions.length === 1)\n return descriptions[0];\n if ((descriptions.length === 2 &&\n descriptions[0] === \"false\" &&\n descriptions[1] === \"true\") ||\n (descriptions[0] === \"true\" && descriptions[1] === \"false\"))\n return \"boolean\";\n // keep track of seen descriptions to avoid duplication\n const seen = {};\n const unique = descriptions.filter(s => (seen[s] ? false : (seen[s] = true)));\n const last = unique.pop();\n return `${unique.join(delimiter)}${unique.length ? finalDelimiter : \"\"}${last}`;\n};\nexport const intersectBranches = (l, r, ctx) => {\n // If the corresponding r branch is identified as a subtype of an l branch, the\n // value at rIndex is set to null so we can avoid including previous/future\n // intersections in the reduced result.\n const batchesByR = r.map(() => []);\n for (let lIndex = 0; lIndex < l.length; lIndex++) {\n let candidatesByR = {};\n for (let rIndex = 0; rIndex < r.length; rIndex++) {\n if (batchesByR[rIndex] === null) {\n // rBranch is a subtype of an lBranch and\n // will not yield any distinct intersection\n continue;\n }\n if (l[lIndex].equals(r[rIndex])) {\n // Combination of subtype and supertype cases\n batchesByR[rIndex] = null;\n candidatesByR = {};\n break;\n }\n const branchIntersection = intersectOrPipeNodes(l[lIndex], r[rIndex], ctx);\n if (branchIntersection instanceof Disjoint) {\n // Doesn't tell us anything useful about their relationships\n // with other branches\n continue;\n }\n if (branchIntersection.equals(l[lIndex])) {\n // If the current l branch is a subtype of r, intersections\n // with previous and remaining branches of r won't lead to\n // distinct intersections.\n batchesByR[rIndex].push(l[lIndex]);\n candidatesByR = {};\n break;\n }\n if (branchIntersection.equals(r[rIndex])) {\n // If the current r branch is a subtype of l, set its batch to\n // null, removing any previous intersections and preventing any\n // of its remaining intersections from being computed.\n batchesByR[rIndex] = null;\n }\n else {\n // If neither l nor r is a subtype of the other, add their\n // intersection as a candidate (could still be removed if it is\n // determined l or r is a subtype of a remaining branch).\n candidatesByR[rIndex] = branchIntersection;\n }\n }\n for (const rIndex in candidatesByR) {\n // batchesByR at rIndex should never be null if it is in candidatesByR\n batchesByR[rIndex][lIndex] = candidatesByR[rIndex];\n }\n }\n // Compile the reduced intersection result, including:\n // \t\t1. Remaining candidates resulting from distinct intersections or strict subtypes of r\n // \t\t2. Original r branches corresponding to indices with a null batch (subtypes of l)\n const resultBranches = batchesByR.flatMap(\n // ensure unions returned from branchable intersections like sequence are flattened\n (batch, i) => batch?.flatMap(branch => branch.branches) ?? r[i]);\n return resultBranches.length === 0 ?\n Disjoint.init(\"union\", l, r)\n : resultBranches;\n};\nexport const reduceBranches = ({ branches, ordered }) => {\n if (branches.length < 2)\n return branches;\n const uniquenessByIndex = branches.map(() => true);\n for (let i = 0; i < branches.length; i++) {\n for (let j = i + 1; j < branches.length && uniquenessByIndex[i] && uniquenessByIndex[j]; j++) {\n if (branches[i].equals(branches[j])) {\n // if the two branches are equal, only \"j\" is marked as\n // redundant so at least one copy could still be included in\n // the final set of branches.\n uniquenessByIndex[j] = false;\n continue;\n }\n const intersection = intersectNodesRoot(branches[i].rawIn, branches[j].rawIn, branches[0].$);\n if (intersection instanceof Disjoint)\n continue;\n if (!ordered)\n assertDeterminateOverlap(branches[i], branches[j]);\n if (intersection.equals(branches[i].rawIn)) {\n // preserve ordered branches that are a subtype of a subsequent branch\n uniquenessByIndex[i] = !!ordered;\n }\n else if (intersection.equals(branches[j].rawIn))\n uniquenessByIndex[j] = false;\n }\n }\n return branches.filter((_, i) => uniquenessByIndex[i]);\n};\nconst assertDeterminateOverlap = (l, r) => {\n if (!l.includesTransform && !r.includesTransform)\n return;\n if (!arrayEquals(l.shallowMorphs, r.shallowMorphs)) {\n throwParseError(writeIndiscriminableMorphMessage(l.expression, r.expression));\n }\n if (!arrayEquals(l.flatMorphs, r.flatMorphs, {\n isEqual: (l, r) => l.propString === r.propString &&\n (l.node.hasKind(\"morph\") && r.node.hasKind(\"morph\") ?\n l.node.hasEqualMorphs(r.node)\n : l.node.hasKind(\"intersection\") && r.node.hasKind(\"intersection\") ?\n l.node.structure?.structuralMorphRef ===\n r.node.structure?.structuralMorphRef\n : false)\n })) {\n throwParseError(writeIndiscriminableMorphMessage(l.expression, r.expression));\n }\n};\nexport const pruneDiscriminant = (discriminantBranch, discriminantCtx) => discriminantBranch.transform((nodeKind, inner) => {\n if (nodeKind === \"domain\" || nodeKind === \"unit\")\n return null;\n return inner;\n}, {\n shouldTransform: (node, ctx) => {\n // safe to cast here as index nodes are never discriminants\n const propString = optionallyChainPropString(ctx.path);\n if (!discriminantCtx.optionallyChainedPropString.startsWith(propString))\n return false;\n if (node.hasKind(\"domain\") && node.domain === \"object\")\n // if we've already checked a path at least as long as the current one,\n // we don't need to revalidate that we're in an object\n return true;\n if ((node.hasKind(\"domain\") || discriminantCtx.kind === \"unit\") &&\n propString === discriminantCtx.optionallyChainedPropString)\n // if the discriminant has already checked the domain at the current path\n // (or a unit literal, implying a domain), we don't need to recheck it\n return true;\n // we don't need to recurse into index nodes as they will never\n // have a required path therefore can't be used to discriminate\n return node.children.length !== 0 && node.kind !== \"index\";\n }\n});\nexport const writeIndiscriminableMorphMessage = (lDescription, rDescription) => `An unordered union of a type including a morph and a type with overlapping input is indeterminate:\nLeft: ${lDescription}\nRight: ${rDescription}`;\nexport const writeOrderedIntersectionMessage = (lDescription, rDescription) => `The intersection of two ordered unions is indeterminate:\nLeft: ${lDescription}\nRight: ${rDescription}`;\n",
144
+ "import { domainDescriptions, domainOf, printable } from \"@ark/util\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { defaultValueSerializer, implementNode } from \"../shared/implement.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { InternalBasis } from \"./basis.js\";\nimport { defineRightwardIntersections } from \"./utils.js\";\nconst implementation = implementNode({\n kind: \"unit\",\n hasAssociatedError: true,\n keys: {\n unit: {\n preserveUndefined: true,\n serialize: schema => schema instanceof Date ?\n schema.toISOString()\n : defaultValueSerializer(schema)\n }\n },\n normalize: schema => schema,\n defaults: {\n description: node => printable(node.unit),\n problem: ({ expected, actual }) => `${expected === actual ? `must be reference equal to ${expected} (serialized to the same value)` : `must be ${expected} (was ${actual})`}`\n },\n intersections: {\n unit: (l, r) => Disjoint.init(\"unit\", l, r),\n ...defineRightwardIntersections(\"unit\", (l, r) => {\n if (r.allows(l.unit))\n return l;\n // will always be a disjoint at this point, but we try to use\n // a domain Disjoint if possible since it's better for discrimination\n const rBasis = r.hasKind(\"intersection\") ? r.basis : r;\n if (rBasis) {\n const rDomain = rBasis.hasKind(\"domain\") ? rBasis : $ark.intrinsic.object;\n if (l.domain !== rDomain.domain) {\n const lDomainDisjointValue = (l.domain === \"undefined\" ||\n l.domain === \"null\" ||\n l.domain === \"boolean\") ?\n l.domain\n : $ark.intrinsic[l.domain];\n return Disjoint.init(\"domain\", lDomainDisjointValue, rDomain);\n }\n }\n return Disjoint.init(\"assignability\", l, r.hasKind(\"intersection\") ?\n r.children.find(rConstraint => !rConstraint.allows(l.unit))\n : r);\n })\n }\n});\nexport class UnitNode extends InternalBasis {\n compiledValue = this.json.unit;\n serializedValue = typeof this.unit === \"string\" || this.unit instanceof Date ?\n JSON.stringify(this.compiledValue)\n : `${this.compiledValue}`;\n compiledCondition = compileEqualityCheck(this.unit, this.serializedValue);\n compiledNegation = compileEqualityCheck(this.unit, this.serializedValue, \"negated\");\n expression = printable(this.unit);\n domain = domainOf(this.unit);\n get defaultShortDescription() {\n return this.domain === \"object\" ?\n domainDescriptions.object\n : this.description;\n }\n innerToJsonSchema(ctx) {\n return (\n // this is the more standard JSON schema representation, especially for Open API\n this.unit === null ? { type: \"null\" }\n : $ark.intrinsic.jsonPrimitive.allows(this.unit) ? { const: this.unit }\n : ctx.fallback.unit({ code: \"unit\", base: {}, unit: this.unit }));\n }\n traverseAllows = this.unit instanceof Date ?\n data => data instanceof Date && data.toISOString() === this.compiledValue\n : Number.isNaN(this.unit) ? data => Number.isNaN(data)\n : data => data === this.unit;\n}\nexport const Unit = {\n implementation,\n Node: UnitNode\n};\nconst compileEqualityCheck = (unit, serializedValue, negated) => {\n if (unit instanceof Date) {\n const condition = `data instanceof Date && data.toISOString() === ${serializedValue}`;\n return negated ? `!(${condition})` : condition;\n }\n if (Number.isNaN(unit))\n return `${negated ? \"!\" : \"\"}Number.isNaN(data)`;\n return `data ${negated ? \"!\" : \"=\"}== ${serializedValue}`;\n};\n",
145
+ "import { append, printable, stringAndSymbolicEntriesOf, throwParseError } from \"@ark/util\";\nimport { BaseConstraint } from \"../constraint.js\";\nimport { flatRef } from \"../node.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { intersectOrPipeNodes } from \"../shared/intersections.js\";\nimport { $ark } from \"../shared/registry.js\";\nimport { traverseKey } from \"../shared/traversal.js\";\nconst implementation = implementNode({\n kind: \"index\",\n hasAssociatedError: false,\n intersectionIsOpen: true,\n keys: {\n signature: {\n child: true,\n parse: (schema, ctx) => {\n const key = ctx.$.parseSchema(schema);\n if (!key.extends($ark.intrinsic.key)) {\n return throwParseError(writeInvalidPropertyKeyMessage(key.expression));\n }\n const enumerableBranches = key.branches.filter(b => b.hasKind(\"unit\"));\n if (enumerableBranches.length) {\n return throwParseError(writeEnumerableIndexBranches(enumerableBranches.map(b => printable(b.unit))));\n }\n return key;\n }\n },\n value: {\n child: true,\n parse: (schema, ctx) => ctx.$.parseSchema(schema)\n }\n },\n normalize: schema => schema,\n defaults: {\n description: node => `[${node.signature.expression}]: ${node.value.description}`\n },\n intersections: {\n index: (l, r, ctx) => {\n if (l.signature.equals(r.signature)) {\n const valueIntersection = intersectOrPipeNodes(l.value, r.value, ctx);\n const value = valueIntersection instanceof Disjoint ?\n $ark.intrinsic.never.internal\n : valueIntersection;\n return ctx.$.node(\"index\", { signature: l.signature, value });\n }\n // if r constrains all of l's keys to a subtype of l's value, r is a subtype of l\n if (l.signature.extends(r.signature) && l.value.subsumes(r.value))\n return r;\n // if l constrains all of r's keys to a subtype of r's value, l is a subtype of r\n if (r.signature.extends(l.signature) && r.value.subsumes(l.value))\n return l;\n // other relationships between index signatures can't be generally reduced\n return null;\n }\n }\n});\nexport class IndexNode extends BaseConstraint {\n impliedBasis = $ark.intrinsic.object.internal;\n expression = `[${this.signature.expression}]: ${this.value.expression}`;\n flatRefs = append(this.value.flatRefs.map(ref => flatRef([this.signature, ...ref.path], ref.node)), flatRef([this.signature], this.value));\n traverseAllows = (data, ctx) => stringAndSymbolicEntriesOf(data).every(entry => {\n if (this.signature.traverseAllows(entry[0], ctx)) {\n return traverseKey(entry[0], () => this.value.traverseAllows(entry[1], ctx), ctx);\n }\n return true;\n });\n traverseApply = (data, ctx) => {\n for (const entry of stringAndSymbolicEntriesOf(data)) {\n if (this.signature.traverseAllows(entry[0], ctx)) {\n traverseKey(entry[0], () => this.value.traverseApply(entry[1], ctx), ctx);\n }\n }\n };\n _transform(mapper, ctx) {\n ctx.path.push(this.signature);\n const result = super._transform(mapper, ctx);\n ctx.path.pop();\n return result;\n }\n compile() {\n // this is currently handled by StructureNode\n }\n}\nexport const Index = {\n implementation,\n Node: IndexNode\n};\nexport const writeEnumerableIndexBranches = (keys) => `Index keys ${keys.join(\", \")} should be specified as named props.`;\nexport const writeInvalidPropertyKeyMessage = (indexSchema) => `Indexed key definition '${indexSchema}' must be a string or symbol`;\n",
146
+ "import { compileObjectLiteral, implementNode } from \"../shared/implement.js\";\nimport { BaseProp, intersectProps } from \"./prop.js\";\nconst implementation = implementNode({\n kind: \"required\",\n hasAssociatedError: true,\n intersectionIsOpen: true,\n keys: {\n key: {},\n value: {\n child: true,\n parse: (schema, ctx) => ctx.$.parseSchema(schema)\n }\n },\n normalize: schema => schema,\n defaults: {\n description: node => `${node.compiledKey}: ${node.value.description}`,\n expected: ctx => ctx.missingValueDescription,\n actual: () => \"missing\"\n },\n intersections: {\n required: intersectProps,\n optional: intersectProps\n }\n});\nexport class RequiredNode extends BaseProp {\n expression = `${this.compiledKey}: ${this.value.expression}`;\n errorContext = Object.freeze({\n code: \"required\",\n missingValueDescription: this.value.defaultShortDescription,\n relativePath: [this.key],\n meta: this.meta\n });\n compiledErrorContext = compileObjectLiteral(this.errorContext);\n}\nexport const Required = {\n implementation,\n Node: RequiredNode\n};\n",
147
+ "import { append, conflatenate, printable, throwInternalError, throwParseError } from \"@ark/util\";\nimport { BaseConstraint } from \"../constraint.js\";\nimport { appendUniqueFlatRefs, flatRef } from \"../node.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { defaultValueSerializer, implementNode } from \"../shared/implement.js\";\nimport { intersectOrPipeNodes } from \"../shared/intersections.js\";\nimport { $ark, registeredReference } from \"../shared/registry.js\";\nimport { traverseKey } from \"../shared/traversal.js\";\nimport { assertDefaultValueAssignability, computeDefaultValueMorph } from \"./optional.js\";\nimport { writeDefaultIntersectionMessage } from \"./prop.js\";\nconst implementation = implementNode({\n kind: \"sequence\",\n hasAssociatedError: false,\n collapsibleKey: \"variadic\",\n keys: {\n prefix: {\n child: true,\n parse: (schema, ctx) => {\n // empty affixes are omitted. an empty array should therefore\n // be specified as `{ proto: Array, length: 0 }`\n if (schema.length === 0)\n return undefined;\n return schema.map(element => ctx.$.parseSchema(element));\n }\n },\n optionals: {\n child: true,\n parse: (schema, ctx) => {\n if (schema.length === 0)\n return undefined;\n return schema.map(element => ctx.$.parseSchema(element));\n }\n },\n defaultables: {\n child: defaultables => defaultables.map(element => element[0]),\n parse: (defaultables, ctx) => {\n if (defaultables.length === 0)\n return undefined;\n return defaultables.map(element => {\n const node = ctx.$.parseSchema(element[0]);\n assertDefaultValueAssignability(node, element[1], null);\n return [node, element[1]];\n });\n },\n serialize: defaults => defaults.map(element => [\n element[0].collapsibleJson,\n defaultValueSerializer(element[1])\n ]),\n reduceIo: (ioKind, inner, defaultables) => {\n if (ioKind === \"in\") {\n inner.optionals = defaultables.map(d => d[0].rawIn);\n return;\n }\n inner.prefix = defaultables.map(d => d[0].rawOut);\n return;\n }\n },\n variadic: {\n child: true,\n parse: (schema, ctx) => ctx.$.parseSchema(schema, ctx)\n },\n minVariadicLength: {\n // minVariadicLength is reflected in the id of this node,\n // but not its IntersectionNode parent since it is superceded by the minLength\n // node it implies\n parse: min => (min === 0 ? undefined : min)\n },\n postfix: {\n child: true,\n parse: (schema, ctx) => {\n if (schema.length === 0)\n return undefined;\n return schema.map(element => ctx.$.parseSchema(element));\n }\n }\n },\n normalize: schema => {\n if (typeof schema === \"string\")\n return { variadic: schema };\n if (\"variadic\" in schema ||\n \"prefix\" in schema ||\n \"defaultables\" in schema ||\n \"optionals\" in schema ||\n \"postfix\" in schema ||\n \"minVariadicLength\" in schema) {\n if (schema.postfix?.length) {\n if (!schema.variadic)\n return throwParseError(postfixWithoutVariadicMessage);\n if (schema.optionals?.length || schema.defaultables?.length)\n return throwParseError(postfixAfterOptionalOrDefaultableMessage);\n }\n if (schema.minVariadicLength && !schema.variadic) {\n return throwParseError(\"minVariadicLength may not be specified without a variadic element\");\n }\n return schema;\n }\n return { variadic: schema };\n },\n reduce: (raw, $) => {\n let minVariadicLength = raw.minVariadicLength ?? 0;\n const prefix = raw.prefix?.slice() ?? [];\n const defaultables = raw.defaultables?.slice() ?? [];\n const optionals = raw.optionals?.slice() ?? [];\n const postfix = raw.postfix?.slice() ?? [];\n if (raw.variadic) {\n // optional elements equivalent to the variadic parameter are redundant\n while (optionals[optionals.length - 1]?.equals(raw.variadic))\n optionals.pop();\n if (optionals.length === 0 && defaultables.length === 0) {\n // If there are no optional, normalize prefix\n // elements adjacent and equivalent to variadic:\n // \t\t{ variadic: number, prefix: [string, number] }\n // reduces to:\n // \t\t{ variadic: number, prefix: [string], minVariadicLength: 1 }\n while (prefix[prefix.length - 1]?.equals(raw.variadic)) {\n prefix.pop();\n minVariadicLength++;\n }\n }\n // Normalize postfix elements adjacent and equivalent to variadic:\n // \t\t{ variadic: number, postfix: [number, number, 5] }\n // reduces to:\n // \t\t{ variadic: number, postfix: [5], minVariadicLength: 2 }\n while (postfix[0]?.equals(raw.variadic)) {\n postfix.shift();\n minVariadicLength++;\n }\n }\n else if (optionals.length === 0 && defaultables.length === 0) {\n // if there's no variadic, optional or defaultable elements,\n // postfix can just be appended to prefix\n prefix.push(...postfix.splice(0));\n }\n if (\n // if any variadic adjacent elements were moved to minVariadicLength\n minVariadicLength !== raw.minVariadicLength ||\n // or any postfix elements were moved to prefix\n (raw.prefix && raw.prefix.length !== prefix.length)) {\n // reparse the reduced def\n return $.node(\"sequence\", {\n ...raw,\n // empty lists will be omitted during parsing\n prefix,\n defaultables,\n optionals,\n postfix,\n minVariadicLength\n }, { prereduced: true });\n }\n },\n defaults: {\n description: node => {\n if (node.isVariadicOnly)\n return `${node.variadic.nestableExpression}[]`;\n const innerDescription = node.tuple\n .map(element => element.kind === \"defaultables\" ?\n `${element.node.nestableExpression} = ${printable(element.default)}`\n : element.kind === \"optionals\" ?\n `${element.node.nestableExpression}?`\n : element.kind === \"variadic\" ?\n `...${element.node.nestableExpression}[]`\n : element.node.expression)\n .join(\", \");\n return `[${innerDescription}]`;\n }\n },\n intersections: {\n sequence: (l, r, ctx) => {\n const rootState = _intersectSequences({\n l: l.tuple,\n r: r.tuple,\n disjoint: new Disjoint(),\n result: [],\n fixedVariants: [],\n ctx\n });\n const viableBranches = rootState.disjoint.length === 0 ?\n [rootState, ...rootState.fixedVariants]\n : rootState.fixedVariants;\n return (viableBranches.length === 0 ? rootState.disjoint\n : viableBranches.length === 1 ?\n ctx.$.node(\"sequence\", sequenceTupleToInner(viableBranches[0].result))\n : ctx.$.node(\"union\", viableBranches.map(state => ({\n proto: Array,\n sequence: sequenceTupleToInner(state.result)\n }))));\n }\n // exactLength, minLength, and maxLength don't need to be defined\n // here since impliedSiblings guarantees they will be added\n // directly to the IntersectionNode parent of the SequenceNode\n // they exist on\n }\n});\nexport class SequenceNode extends BaseConstraint {\n impliedBasis = $ark.intrinsic.Array.internal;\n tuple = sequenceInnerToTuple(this.inner);\n prefixLength = this.prefix?.length ?? 0;\n defaultablesLength = this.defaultables?.length ?? 0;\n optionalsLength = this.optionals?.length ?? 0;\n postfixLength = this.postfix?.length ?? 0;\n defaultablesAndOptionals = [];\n prevariadic = this.tuple.filter((el) => {\n if (el.kind === \"defaultables\" || el.kind === \"optionals\") {\n // populate defaultablesAndOptionals while filtering prevariadic\n this.defaultablesAndOptionals.push(el.node);\n return true;\n }\n return el.kind === \"prefix\";\n });\n variadicOrPostfix = conflatenate(this.variadic && [this.variadic], this.postfix);\n // have to wait until prevariadic and variadicOrPostfix are set to calculate\n flatRefs = this.addFlatRefs();\n addFlatRefs() {\n appendUniqueFlatRefs(this.flatRefs, this.prevariadic.flatMap((element, i) => append(element.node.flatRefs.map(ref => flatRef([`${i}`, ...ref.path], ref.node)), flatRef([`${i}`], element.node))));\n appendUniqueFlatRefs(this.flatRefs, this.variadicOrPostfix.flatMap(element => \n // a postfix index can't be directly represented as a type\n // key, so we just use the same matcher for variadic\n append(element.flatRefs.map(ref => flatRef([$ark.intrinsic.nonNegativeIntegerString.internal, ...ref.path], ref.node)), flatRef([$ark.intrinsic.nonNegativeIntegerString.internal], element))));\n return this.flatRefs;\n }\n isVariadicOnly = this.prevariadic.length + this.postfixLength === 0;\n minVariadicLength = this.inner.minVariadicLength ?? 0;\n minLength = this.prefixLength + this.minVariadicLength + this.postfixLength;\n minLengthNode = this.minLength === 0 ?\n null\n // cast is safe here as the only time this would not be a\n // MinLengthNode would be when minLength is 0\n : this.$.node(\"minLength\", this.minLength);\n maxLength = this.variadic ? null : this.tuple.length;\n maxLengthNode = this.maxLength === null ? null : this.$.node(\"maxLength\", this.maxLength);\n impliedSiblings = this.minLengthNode ?\n this.maxLengthNode ?\n [this.minLengthNode, this.maxLengthNode]\n : [this.minLengthNode]\n : this.maxLengthNode ? [this.maxLengthNode]\n : [];\n defaultValueMorphs = getDefaultableMorphs(this);\n defaultValueMorphsReference = this.defaultValueMorphs.length ?\n registeredReference(this.defaultValueMorphs)\n : undefined;\n elementAtIndex(data, index) {\n if (index < this.prevariadic.length)\n return this.tuple[index];\n const firstPostfixIndex = data.length - this.postfixLength;\n if (index >= firstPostfixIndex)\n return { kind: \"postfix\", node: this.postfix[index - firstPostfixIndex] };\n return {\n kind: \"variadic\",\n node: this.variadic ??\n throwInternalError(`Unexpected attempt to access index ${index} on ${this}`)\n };\n }\n // minLength/maxLength should be checked by Intersection before either traversal\n traverseAllows = (data, ctx) => {\n for (let i = 0; i < data.length; i++) {\n if (!this.elementAtIndex(data, i).node.traverseAllows(data[i], ctx))\n return false;\n }\n return true;\n };\n traverseApply = (data, ctx) => {\n let i = 0;\n for (; i < data.length; i++) {\n traverseKey(i, () => this.elementAtIndex(data, i).node.traverseApply(data[i], ctx), ctx);\n }\n };\n get element() {\n return this.cacheGetter(\"element\", this.$.node(\"union\", this.children));\n }\n // minLength/maxLength compilation should be handled by Intersection\n compile(js) {\n if (this.prefix) {\n for (const [i, node] of this.prefix.entries())\n js.traverseKey(`${i}`, `data[${i}]`, node);\n }\n for (const [i, node] of this.defaultablesAndOptionals.entries()) {\n const dataIndex = `${i + this.prefixLength}`;\n js.if(`${dataIndex} >= data.length`, () => js.traversalKind === \"Allows\" ? js.return(true) : js.return());\n js.traverseKey(dataIndex, `data[${dataIndex}]`, node);\n }\n if (this.variadic) {\n if (this.postfix) {\n js.const(\"firstPostfixIndex\", `data.length${this.postfix ? `- ${this.postfix.length}` : \"\"}`);\n }\n js.for(`i < ${this.postfix ? \"firstPostfixIndex\" : \"data.length\"}`, () => js.traverseKey(\"i\", \"data[i]\", this.variadic), this.prevariadic.length);\n if (this.postfix) {\n for (const [i, node] of this.postfix.entries()) {\n const keyExpression = `firstPostfixIndex + ${i}`;\n js.traverseKey(keyExpression, `data[${keyExpression}]`, node);\n }\n }\n }\n if (js.traversalKind === \"Allows\")\n js.return(true);\n }\n _transform(mapper, ctx) {\n ctx.path.push($ark.intrinsic.nonNegativeIntegerString.internal);\n const result = super._transform(mapper, ctx);\n ctx.path.pop();\n return result;\n }\n // this depends on tuple so needs to come after it\n expression = this.description;\n reduceJsonSchema(schema, ctx) {\n const isDraft07 = ctx.target === \"draft-07\";\n if (this.prevariadic.length) {\n const prefixSchemas = this.prevariadic.map(el => {\n const valueSchema = el.node.toJsonSchemaRecurse(ctx);\n if (el.kind === \"defaultables\") {\n const value = typeof el.default === \"function\" ? el.default() : el.default;\n valueSchema.default =\n $ark.intrinsic.jsonData.allows(value) ?\n value\n : ctx.fallback.defaultValue({\n code: \"defaultValue\",\n base: valueSchema,\n value\n });\n }\n return valueSchema;\n });\n // draft-07 uses items as array, draft-2020-12 uses prefixItems\n if (isDraft07)\n schema.items = prefixSchemas;\n else\n schema.prefixItems = prefixSchemas;\n }\n // by default JSON schema prefixElements are optional\n // add minLength here if there are any required prefix elements\n if (this.minLength)\n schema.minItems = this.minLength;\n if (this.variadic) {\n const variadicItemSchema = this.variadic.toJsonSchemaRecurse(ctx);\n // draft-07 uses additionalItems when items is an array (tuple),\n // draft-2020-12 uses items\n if (isDraft07 && this.prevariadic.length)\n schema.additionalItems = variadicItemSchema;\n else\n schema.items = variadicItemSchema;\n // maxLength constraint will be enforced by items: false\n // for non-variadic arrays\n if (this.maxLength)\n schema.maxItems = this.maxLength;\n // postfix can only be present if variadic is present so nesting this is fine\n if (this.postfix) {\n const elements = this.postfix.map(el => el.toJsonSchemaRecurse(ctx));\n schema = ctx.fallback.arrayPostfix({\n code: \"arrayPostfix\",\n base: schema,\n elements\n });\n }\n }\n else {\n // For fixed-length tuples without variadic elements\n // draft-07 uses additionalItems: false, draft-2020-12 uses items: false\n if (isDraft07)\n schema.additionalItems = false;\n else\n schema.items = false;\n // delete maxItems constraint that will have been added by the\n // base intersection node to enforce fixed length\n delete schema.maxItems;\n }\n return schema;\n }\n}\nconst defaultableMorphsCache = {};\nconst getDefaultableMorphs = (node) => {\n if (!node.defaultables)\n return [];\n const morphs = [];\n let cacheKey = \"[\";\n const lastDefaultableIndex = node.prefixLength + node.defaultablesLength - 1;\n for (let i = node.prefixLength; i <= lastDefaultableIndex; i++) {\n const [elementNode, defaultValue] = node.defaultables[i - node.prefixLength];\n morphs.push(computeDefaultValueMorph(i, elementNode, defaultValue));\n cacheKey += `${i}: ${elementNode.id} = ${defaultValueSerializer(defaultValue)}, `;\n }\n cacheKey += \"]\";\n return (defaultableMorphsCache[cacheKey] ??= morphs);\n};\nexport const Sequence = {\n implementation,\n Node: SequenceNode\n};\nconst sequenceInnerToTuple = (inner) => {\n const tuple = [];\n if (inner.prefix)\n for (const node of inner.prefix)\n tuple.push({ kind: \"prefix\", node });\n if (inner.defaultables) {\n for (const [node, defaultValue] of inner.defaultables)\n tuple.push({ kind: \"defaultables\", node, default: defaultValue });\n }\n if (inner.optionals)\n for (const node of inner.optionals)\n tuple.push({ kind: \"optionals\", node });\n if (inner.variadic)\n tuple.push({ kind: \"variadic\", node: inner.variadic });\n if (inner.postfix)\n for (const node of inner.postfix)\n tuple.push({ kind: \"postfix\", node });\n return tuple;\n};\nconst sequenceTupleToInner = (tuple) => tuple.reduce((result, element) => {\n if (element.kind === \"variadic\")\n result.variadic = element.node;\n else if (element.kind === \"defaultables\") {\n result.defaultables = append(result.defaultables, [\n [element.node, element.default]\n ]);\n }\n else\n result[element.kind] = append(result[element.kind], element.node);\n return result;\n}, {});\nexport const postfixAfterOptionalOrDefaultableMessage = \"A postfix required element cannot follow an optional or defaultable element\";\nexport const postfixWithoutVariadicMessage = \"A postfix element requires a variadic element\";\nconst _intersectSequences = (s) => {\n const [lHead, ...lTail] = s.l;\n const [rHead, ...rTail] = s.r;\n if (!lHead || !rHead)\n return s;\n const lHasPostfix = lTail[lTail.length - 1]?.kind === \"postfix\";\n const rHasPostfix = rTail[rTail.length - 1]?.kind === \"postfix\";\n const kind = lHead.kind === \"prefix\" || rHead.kind === \"prefix\" ? \"prefix\"\n : lHead.kind === \"postfix\" || rHead.kind === \"postfix\" ? \"postfix\"\n : lHead.kind === \"variadic\" && rHead.kind === \"variadic\" ? \"variadic\"\n // if either operand has postfix elements, the full-length\n // intersection can't include optional elements (though they may\n // exist in some of the fixed length variants)\n : lHasPostfix || rHasPostfix ? \"prefix\"\n : lHead.kind === \"defaultables\" || rHead.kind === \"defaultables\" ?\n \"defaultables\"\n : \"optionals\";\n if (lHead.kind === \"prefix\" && rHead.kind === \"variadic\" && rHasPostfix) {\n const postfixBranchResult = _intersectSequences({\n ...s,\n fixedVariants: [],\n r: rTail.map(element => ({ ...element, kind: \"prefix\" }))\n });\n if (postfixBranchResult.disjoint.length === 0)\n s.fixedVariants.push(postfixBranchResult);\n }\n else if (rHead.kind === \"prefix\" &&\n lHead.kind === \"variadic\" &&\n lHasPostfix) {\n const postfixBranchResult = _intersectSequences({\n ...s,\n fixedVariants: [],\n l: lTail.map(element => ({ ...element, kind: \"prefix\" }))\n });\n if (postfixBranchResult.disjoint.length === 0)\n s.fixedVariants.push(postfixBranchResult);\n }\n const result = intersectOrPipeNodes(lHead.node, rHead.node, s.ctx);\n if (result instanceof Disjoint) {\n if (kind === \"prefix\" || kind === \"postfix\") {\n s.disjoint.push(...result.withPrefixKey(\n // ideally we could handle disjoint paths more precisely here,\n // but not trivial to serialize postfix elements as keys\n kind === \"prefix\" ? s.result.length : `-${lTail.length + 1}`, \n // both operands must be required for the disjoint to be considered required\n elementIsRequired(lHead) && elementIsRequired(rHead) ?\n \"required\"\n : \"optional\"));\n s.result = [...s.result, { kind, node: $ark.intrinsic.never.internal }];\n }\n else if (kind === \"optionals\" || kind === \"defaultables\") {\n // if the element result is optional and unsatisfiable, the\n // intersection can still be satisfied as long as the tuple\n // ends before the disjoint element would occur\n return s;\n }\n else {\n // if the element is variadic and unsatisfiable, the intersection\n // can be satisfied with a fixed length variant including zero\n // variadic elements\n return _intersectSequences({\n ...s,\n fixedVariants: [],\n // if there were any optional elements, there will be no postfix elements\n // so this mapping will never occur (which would be illegal otherwise)\n l: lTail.map(element => ({ ...element, kind: \"prefix\" })),\n r: lTail.map(element => ({ ...element, kind: \"prefix\" }))\n });\n }\n }\n else if (kind === \"defaultables\") {\n if (lHead.kind === \"defaultables\" &&\n rHead.kind === \"defaultables\" &&\n lHead.default !== rHead.default) {\n throwParseError(writeDefaultIntersectionMessage(lHead.default, rHead.default));\n }\n s.result = [\n ...s.result,\n {\n kind,\n node: result,\n default: lHead.kind === \"defaultables\" ? lHead.default\n : rHead.kind === \"defaultables\" ? rHead.default\n : throwInternalError(`Unexpected defaultable intersection from ${lHead.kind} and ${rHead.kind} elements.`)\n }\n ];\n }\n else\n s.result = [...s.result, { kind, node: result }];\n const lRemaining = s.l.length;\n const rRemaining = s.r.length;\n if (lHead.kind !== \"variadic\" ||\n (lRemaining >= rRemaining &&\n (rHead.kind === \"variadic\" || rRemaining === 1)))\n s.l = lTail;\n if (rHead.kind !== \"variadic\" ||\n (rRemaining >= lRemaining &&\n (lHead.kind === \"variadic\" || lRemaining === 1)))\n s.r = rTail;\n return _intersectSequences(s);\n};\nconst elementIsRequired = (el) => el.kind === \"prefix\" || el.kind === \"postfix\";\n",
148
+ "import { append, conflatenate, flatMorph, printable, spliterate, throwInternalError, throwParseError } from \"@ark/util\";\nimport { BaseConstraint, constraintKeyParser, flattenConstraints, intersectConstraints } from \"../constraint.js\";\nimport { intrinsic } from \"../intrinsic.js\";\nimport { typeOrTermExtends } from \"../roots/root.js\";\nimport { compileSerializedValue } from \"../shared/compile.js\";\nimport { Disjoint } from \"../shared/disjoint.js\";\nimport { implementNode } from \"../shared/implement.js\";\nimport { intersectNodesRoot } from \"../shared/intersections.js\";\nimport { $ark, registeredReference } from \"../shared/registry.js\";\nimport { ToJsonSchema } from \"../shared/toJsonSchema.js\";\nimport { traverseKey } from \"../shared/traversal.js\";\nimport { hasArkKind, isNode, makeRootAndArrayPropertiesMutable } from \"../shared/utils.js\";\nimport { Optional } from \"./optional.js\";\nconst createStructuralWriter = (childStringProp) => (node) => {\n if (node.props.length || node.index) {\n const parts = node.index?.map(index => index[childStringProp]) ?? [];\n for (const prop of node.props)\n parts.push(prop[childStringProp]);\n if (node.undeclared)\n parts.push(`+ (undeclared): ${node.undeclared}`);\n const objectLiteralDescription = `{ ${parts.join(\", \")} }`;\n return node.sequence ?\n `${objectLiteralDescription} & ${node.sequence.description}`\n : objectLiteralDescription;\n }\n return node.sequence?.description ?? \"{}\";\n};\nconst structuralDescription = createStructuralWriter(\"description\");\nconst structuralExpression = createStructuralWriter(\"expression\");\nconst intersectPropsAndIndex = (l, r, $) => {\n const kind = l.required ? \"required\" : \"optional\";\n if (!r.signature.allows(l.key))\n return null;\n const value = intersectNodesRoot(l.value, r.value, $);\n if (value instanceof Disjoint) {\n return kind === \"optional\" ?\n $.node(\"optional\", {\n key: l.key,\n value: $ark.intrinsic.never.internal\n })\n : value.withPrefixKey(l.key, l.kind);\n }\n return null;\n};\nconst implementation = implementNode({\n kind: \"structure\",\n hasAssociatedError: false,\n normalize: schema => schema,\n applyConfig: (schema, config) => {\n if (!schema.undeclared && config.onUndeclaredKey !== \"ignore\") {\n return {\n ...schema,\n undeclared: config.onUndeclaredKey\n };\n }\n return schema;\n },\n keys: {\n required: {\n child: true,\n parse: constraintKeyParser(\"required\"),\n reduceIo: (ioKind, inner, nodes) => {\n // ensure we don't overwrite nodes added by optional\n inner.required = append(inner.required, nodes.map(node => (ioKind === \"in\" ? node.rawIn : node.rawOut)));\n return;\n }\n },\n optional: {\n child: true,\n parse: constraintKeyParser(\"optional\"),\n reduceIo: (ioKind, inner, nodes) => {\n if (ioKind === \"in\") {\n inner.optional = nodes.map(node => node.rawIn);\n return;\n }\n for (const node of nodes) {\n inner[node.outProp.kind] = append(inner[node.outProp.kind], node.outProp.rawOut);\n }\n }\n },\n index: {\n child: true,\n parse: constraintKeyParser(\"index\")\n },\n sequence: {\n child: true,\n parse: constraintKeyParser(\"sequence\")\n },\n undeclared: {\n parse: behavior => (behavior === \"ignore\" ? undefined : behavior),\n reduceIo: (ioKind, inner, value) => {\n if (value === \"reject\") {\n inner.undeclared = \"reject\";\n return;\n }\n // if base is \"delete\", undeclared keys are \"ignore\" (i.e. unconstrained)\n // on input and \"reject\" on output\n if (ioKind === \"in\")\n delete inner.undeclared;\n else\n inner.undeclared = \"reject\";\n }\n }\n },\n defaults: {\n description: structuralDescription\n },\n intersections: {\n structure: (l, r, ctx) => {\n const lInner = { ...l.inner };\n const rInner = { ...r.inner };\n const disjointResult = new Disjoint();\n if (l.undeclared) {\n const lKey = l.keyof();\n for (const k of r.requiredKeys) {\n if (!lKey.allows(k)) {\n disjointResult.add(\"presence\", $ark.intrinsic.never.internal, r.propsByKey[k].value, {\n path: [k]\n });\n }\n }\n if (rInner.optional)\n rInner.optional = rInner.optional.filter(n => lKey.allows(n.key));\n if (rInner.index) {\n rInner.index = rInner.index.flatMap(n => {\n if (n.signature.extends(lKey))\n return n;\n const indexOverlap = intersectNodesRoot(lKey, n.signature, ctx.$);\n if (indexOverlap instanceof Disjoint)\n return [];\n const normalized = normalizeIndex(indexOverlap, n.value, ctx.$);\n if (normalized.required) {\n rInner.required = conflatenate(rInner.required, normalized.required);\n }\n if (normalized.optional) {\n rInner.optional = conflatenate(rInner.optional, normalized.optional);\n }\n return normalized.index ?? [];\n });\n }\n }\n if (r.undeclared) {\n const rKey = r.keyof();\n for (const k of l.requiredKeys) {\n if (!rKey.allows(k)) {\n disjointResult.add(\"presence\", l.propsByKey[k].value, $ark.intrinsic.never.internal, {\n path: [k]\n });\n }\n }\n if (lInner.optional)\n lInner.optional = lInner.optional.filter(n => rKey.allows(n.key));\n if (lInner.index) {\n lInner.index = lInner.index.flatMap(n => {\n if (n.signature.extends(rKey))\n return n;\n const indexOverlap = intersectNodesRoot(rKey, n.signature, ctx.$);\n if (indexOverlap instanceof Disjoint)\n return [];\n const normalized = normalizeIndex(indexOverlap, n.value, ctx.$);\n if (normalized.required) {\n lInner.required = conflatenate(lInner.required, normalized.required);\n }\n if (normalized.optional) {\n lInner.optional = conflatenate(lInner.optional, normalized.optional);\n }\n return normalized.index ?? [];\n });\n }\n }\n const baseInner = {};\n if (l.undeclared || r.undeclared) {\n baseInner.undeclared =\n l.undeclared === \"reject\" || r.undeclared === \"reject\" ?\n \"reject\"\n : \"delete\";\n }\n const childIntersectionResult = intersectConstraints({\n kind: \"structure\",\n baseInner,\n l: flattenConstraints(lInner),\n r: flattenConstraints(rInner),\n roots: [],\n ctx\n });\n if (childIntersectionResult instanceof Disjoint)\n disjointResult.push(...childIntersectionResult);\n if (disjointResult.length)\n return disjointResult;\n return childIntersectionResult;\n }\n },\n reduce: (inner, $) => {\n if (!inner.required && !inner.optional)\n return;\n const seen = {};\n let updated = false;\n const newOptionalProps = inner.optional ? [...inner.optional] : [];\n // check required keys for duplicates and handle index intersections\n if (inner.required) {\n for (let i = 0; i < inner.required.length; i++) {\n const requiredProp = inner.required[i];\n if (requiredProp.key in seen)\n throwParseError(writeDuplicateKeyMessage(requiredProp.key));\n seen[requiredProp.key] = true;\n if (inner.index) {\n for (const index of inner.index) {\n const intersection = intersectPropsAndIndex(requiredProp, index, $);\n if (intersection instanceof Disjoint)\n return intersection;\n }\n }\n }\n }\n // check optional keys for duplicates and handle index intersections\n if (inner.optional) {\n for (let i = 0; i < inner.optional.length; i++) {\n const optionalProp = inner.optional[i];\n if (optionalProp.key in seen)\n throwParseError(writeDuplicateKeyMessage(optionalProp.key));\n seen[optionalProp.key] = true;\n if (inner.index) {\n for (const index of inner.index) {\n const intersection = intersectPropsAndIndex(optionalProp, index, $);\n if (intersection instanceof Disjoint)\n return intersection;\n if (intersection !== null) {\n newOptionalProps[i] = intersection;\n updated = true;\n }\n }\n }\n }\n }\n if (updated) {\n return $.node(\"structure\", { ...inner, optional: newOptionalProps }, { prereduced: true });\n }\n }\n});\nexport class StructureNode extends BaseConstraint {\n impliedBasis = $ark.intrinsic.object.internal;\n impliedSiblings = this.children.flatMap(n => n.impliedSiblings ?? []);\n props = conflatenate(this.required, this.optional);\n propsByKey = flatMorph(this.props, (i, node) => [node.key, node]);\n propsByKeyReference = registeredReference(this.propsByKey);\n expression = structuralExpression(this);\n requiredKeys = this.required?.map(node => node.key) ?? [];\n optionalKeys = this.optional?.map(node => node.key) ?? [];\n literalKeys = [...this.requiredKeys, ...this.optionalKeys];\n _keyof;\n keyof() {\n if (this._keyof)\n return this._keyof;\n let branches = this.$.units(this.literalKeys).branches;\n if (this.index) {\n for (const { signature } of this.index)\n branches = branches.concat(signature.branches);\n }\n return (this._keyof = this.$.node(\"union\", branches));\n }\n map(flatMapProp) {\n return this.$.node(\"structure\", this.props\n .flatMap(flatMapProp)\n .reduce((structureInner, mapped) => {\n const originalProp = this.propsByKey[mapped.key];\n if (isNode(mapped)) {\n if (mapped.kind !== \"required\" && mapped.kind !== \"optional\") {\n return throwParseError(`Map result must have kind \"required\" or \"optional\" (was ${mapped.kind})`);\n }\n structureInner[mapped.kind] = append(structureInner[mapped.kind], mapped);\n return structureInner;\n }\n const mappedKind = mapped.kind ?? originalProp?.kind ?? \"required\";\n // extract the inner keys from the map result in case a node was spread,\n // which would otherwise lead to invalid keys\n const mappedPropInner = flatMorph(mapped, (k, v) => (k in Optional.implementation.keys ? [k, v] : []));\n structureInner[mappedKind] = append(structureInner[mappedKind], this.$.node(mappedKind, mappedPropInner));\n return structureInner;\n }, {}));\n }\n assertHasKeys(keys) {\n const invalidKeys = keys.filter(k => !typeOrTermExtends(k, this.keyof()));\n if (invalidKeys.length) {\n return throwParseError(writeInvalidKeysMessage(this.expression, invalidKeys));\n }\n }\n get(indexer, ...path) {\n let value;\n let required = false;\n const key = indexerToKey(indexer);\n if ((typeof key === \"string\" || typeof key === \"symbol\") &&\n this.propsByKey[key]) {\n value = this.propsByKey[key].value;\n required = this.propsByKey[key].required;\n }\n if (this.index) {\n for (const n of this.index) {\n if (typeOrTermExtends(key, n.signature))\n value = value?.and(n.value) ?? n.value;\n }\n }\n if (this.sequence &&\n typeOrTermExtends(key, $ark.intrinsic.nonNegativeIntegerString)) {\n if (hasArkKind(key, \"root\")) {\n if (this.sequence.variadic)\n // if there is a variadic element and we're accessing an index, return a union\n // of all possible elements. If there is no variadic expression, we're in a tuple\n // so this access wouldn't be safe based on the array indices\n value = value?.and(this.sequence.element) ?? this.sequence.element;\n }\n else {\n const index = Number.parseInt(key);\n if (index < this.sequence.prevariadic.length) {\n const fixedElement = this.sequence.prevariadic[index].node;\n value = value?.and(fixedElement) ?? fixedElement;\n required ||= index < this.sequence.prefixLength;\n }\n else if (this.sequence.variadic) {\n // ideally we could return something more specific for postfix\n // but there is no way to represent it using an index alone\n const nonFixedElement = this.$.node(\"union\", this.sequence.variadicOrPostfix);\n value = value?.and(nonFixedElement) ?? nonFixedElement;\n }\n }\n }\n if (!value) {\n if (this.sequence?.variadic &&\n hasArkKind(key, \"root\") &&\n key.extends($ark.intrinsic.number)) {\n return throwParseError(writeNumberIndexMessage(key.expression, this.sequence.expression));\n }\n return throwParseError(writeInvalidKeysMessage(this.expression, [key]));\n }\n const result = value.get(...path);\n return required ? result : result.or($ark.intrinsic.undefined);\n }\n pick(...keys) {\n this.assertHasKeys(keys);\n return this.$.node(\"structure\", this.filterKeys(\"pick\", keys));\n }\n omit(...keys) {\n this.assertHasKeys(keys);\n return this.$.node(\"structure\", this.filterKeys(\"omit\", keys));\n }\n optionalize() {\n const { required, ...inner } = this.inner;\n return this.$.node(\"structure\", {\n ...inner,\n optional: this.props.map(prop => prop.hasKind(\"required\") ? this.$.node(\"optional\", prop.inner) : prop)\n });\n }\n require() {\n const { optional, ...inner } = this.inner;\n return this.$.node(\"structure\", {\n ...inner,\n required: this.props.map(prop => prop.hasKind(\"optional\") ?\n {\n key: prop.key,\n value: prop.value\n }\n : prop)\n });\n }\n merge(r) {\n const inner = this.filterKeys(\"omit\", [r.keyof()]);\n if (r.required)\n inner.required = append(inner.required, r.required);\n if (r.optional)\n inner.optional = append(inner.optional, r.optional);\n if (r.index)\n inner.index = append(inner.index, r.index);\n if (r.sequence)\n inner.sequence = r.sequence;\n if (r.undeclared)\n inner.undeclared = r.undeclared;\n else\n delete inner.undeclared;\n return this.$.node(\"structure\", inner);\n }\n filterKeys(operation, keys) {\n const result = makeRootAndArrayPropertiesMutable(this.inner);\n const shouldKeep = (key) => {\n const matchesKey = keys.some(k => typeOrTermExtends(key, k));\n return operation === \"pick\" ? matchesKey : !matchesKey;\n };\n if (result.required)\n result.required = result.required.filter(prop => shouldKeep(prop.key));\n if (result.optional)\n result.optional = result.optional.filter(prop => shouldKeep(prop.key));\n if (result.index)\n result.index = result.index.filter(index => shouldKeep(index.signature));\n return result;\n }\n traverseAllows = (data, ctx) => this._traverse(\"Allows\", data, ctx);\n traverseApply = (data, ctx) => this._traverse(\"Apply\", data, ctx);\n _traverse = (traversalKind, data, ctx) => {\n const errorCount = ctx?.currentErrorCount ?? 0;\n for (let i = 0; i < this.props.length; i++) {\n if (traversalKind === \"Allows\") {\n if (!this.props[i].traverseAllows(data, ctx))\n return false;\n }\n else {\n this.props[i].traverseApply(data, ctx);\n if (ctx.failFast && ctx.currentErrorCount > errorCount)\n return false;\n }\n }\n if (this.sequence) {\n if (traversalKind === \"Allows\") {\n if (!this.sequence.traverseAllows(data, ctx))\n return false;\n }\n else {\n this.sequence.traverseApply(data, ctx);\n if (ctx.failFast && ctx.currentErrorCount > errorCount)\n return false;\n }\n }\n if (this.index || this.undeclared === \"reject\") {\n const keys = Object.keys(data);\n keys.push(...Object.getOwnPropertySymbols(data));\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (this.index) {\n for (const node of this.index) {\n if (node.signature.traverseAllows(k, ctx)) {\n if (traversalKind === \"Allows\") {\n const result = traverseKey(k, () => node.value.traverseAllows(data[k], ctx), ctx);\n if (!result)\n return false;\n }\n else {\n traverseKey(k, () => node.value.traverseApply(data[k], ctx), ctx);\n if (ctx.failFast && ctx.currentErrorCount > errorCount)\n return false;\n }\n }\n }\n }\n if (this.undeclared === \"reject\" && !this.declaresKey(k)) {\n if (traversalKind === \"Allows\")\n return false;\n // this should have its own error code:\n // https://github.com/arktypeio/arktype/issues/1403\n ctx.errorFromNodeContext({\n code: \"predicate\",\n expected: \"removed\",\n actual: \"\",\n relativePath: [k],\n meta: this.meta\n });\n if (ctx.failFast)\n return false;\n }\n }\n }\n // added additional ctx check here to address\n // https://github.com/arktypeio/arktype/issues/1346\n if (this.structuralMorph && ctx && !ctx.hasError())\n ctx.queueMorphs([this.structuralMorph]);\n return true;\n };\n get defaultable() {\n return this.cacheGetter(\"defaultable\", this.optional?.filter(o => o.hasDefault()) ?? []);\n }\n declaresKey = (k) => k in this.propsByKey ||\n this.index?.some(n => n.signature.allows(k)) ||\n (this.sequence !== undefined &&\n $ark.intrinsic.nonNegativeIntegerString.allows(k));\n _compileDeclaresKey(js) {\n const parts = [];\n if (this.props.length)\n parts.push(`k in ${this.propsByKeyReference}`);\n if (this.index) {\n for (const index of this.index)\n parts.push(js.invoke(index.signature, { kind: \"Allows\", arg: \"k\" }));\n }\n if (this.sequence)\n parts.push(\"$ark.intrinsic.nonNegativeIntegerString.allows(k)\");\n // if parts is empty, this is a structure like { \"+\": \"reject\" }\n // that declares no keys, so return false\n return parts.join(\" || \") || \"false\";\n }\n get structuralMorph() {\n return this.cacheGetter(\"structuralMorph\", getPossibleMorph(this));\n }\n structuralMorphRef = this.structuralMorph && registeredReference(this.structuralMorph);\n compile(js) {\n if (js.traversalKind === \"Apply\")\n js.initializeErrorCount();\n for (const prop of this.props) {\n js.check(prop);\n if (js.traversalKind === \"Apply\")\n js.returnIfFailFast();\n }\n if (this.sequence) {\n js.check(this.sequence);\n if (js.traversalKind === \"Apply\")\n js.returnIfFailFast();\n }\n if (this.index || this.undeclared === \"reject\") {\n js.const(\"keys\", \"Object.keys(data)\");\n js.line(\"keys.push(...Object.getOwnPropertySymbols(data))\");\n js.for(\"i < keys.length\", () => this.compileExhaustiveEntry(js));\n }\n if (js.traversalKind === \"Allows\")\n return js.return(true);\n // always queue deleteUndeclared on valid traversal for \"delete\"\n if (this.structuralMorphRef) {\n // added additional ctx check here to address\n // https://github.com/arktypeio/arktype/issues/1346\n js.if(\"ctx && !ctx.hasError()\", () => {\n js.line(`ctx.queueMorphs([`);\n precompileMorphs(js, this);\n return js.line(\"])\");\n });\n }\n }\n compileExhaustiveEntry(js) {\n js.const(\"k\", \"keys[i]\");\n if (this.index) {\n for (const node of this.index) {\n js.if(`${js.invoke(node.signature, { arg: \"k\", kind: \"Allows\" })}`, () => js.traverseKey(\"k\", \"data[k]\", node.value));\n }\n }\n if (this.undeclared === \"reject\") {\n js.if(`!(${this._compileDeclaresKey(js)})`, () => {\n if (js.traversalKind === \"Allows\")\n return js.return(false);\n return js\n .line(`ctx.errorFromNodeContext({ code: \"predicate\", expected: \"removed\", actual: \"\", relativePath: [k], meta: ${this.compiledMeta} })`)\n .if(\"ctx.failFast\", () => js.return());\n });\n }\n return js;\n }\n reduceJsonSchema(schema, ctx) {\n switch (schema.type) {\n case \"object\":\n return this.reduceObjectJsonSchema(schema, ctx);\n case \"array\":\n const arraySchema = this.sequence?.reduceJsonSchema(schema, ctx) ?? schema;\n if (this.props.length || this.index) {\n return ctx.fallback.arrayObject({\n code: \"arrayObject\",\n base: arraySchema,\n object: this.reduceObjectJsonSchema({ type: \"object\" }, ctx)\n });\n }\n return arraySchema;\n default:\n return ToJsonSchema.throwInternalOperandError(\"structure\", schema);\n }\n }\n reduceObjectJsonSchema(schema, ctx) {\n if (this.props.length) {\n schema.properties = {};\n for (const prop of this.props) {\n const valueSchema = prop.value.toJsonSchemaRecurse(ctx);\n if (typeof prop.key === \"symbol\") {\n ctx.fallback.symbolKey({\n code: \"symbolKey\",\n base: schema,\n key: prop.key,\n value: valueSchema,\n optional: prop.optional\n });\n continue;\n }\n if (prop.hasDefault()) {\n const value = typeof prop.default === \"function\" ? prop.default() : prop.default;\n valueSchema.default =\n $ark.intrinsic.jsonData.allows(value) ?\n value\n : ctx.fallback.defaultValue({\n code: \"defaultValue\",\n base: valueSchema,\n value\n });\n }\n schema.properties[prop.key] = valueSchema;\n }\n if (this.requiredKeys.length && schema.properties) {\n schema.required = this.requiredKeys.filter((k) => typeof k === \"string\" && k in schema.properties);\n }\n }\n if (this.index) {\n for (const index of this.index) {\n const valueJsonSchema = index.value.toJsonSchemaRecurse(ctx);\n if (index.signature.equals($ark.intrinsic.string)) {\n schema.additionalProperties = valueJsonSchema;\n continue;\n }\n for (const keyBranch of index.signature.branches) {\n if (!keyBranch.extends($ark.intrinsic.string)) {\n schema = ctx.fallback.symbolKey({\n code: \"symbolKey\",\n base: schema,\n key: null,\n value: valueJsonSchema,\n optional: false\n });\n continue;\n }\n let keySchema = { type: \"string\" };\n if (keyBranch.hasKind(\"morph\")) {\n keySchema = ctx.fallback.morph({\n code: \"morph\",\n base: keyBranch.rawIn.toJsonSchemaRecurse(ctx),\n out: keyBranch.rawOut.toJsonSchemaRecurse(ctx)\n });\n }\n if (!keyBranch.hasKind(\"intersection\")) {\n return throwInternalError(`Unexpected index branch kind ${keyBranch.kind}.`);\n }\n const { pattern } = keyBranch.inner;\n if (pattern) {\n const keySchemaWithPattern = Object.assign(keySchema, {\n pattern: pattern[0].rule\n });\n for (let i = 1; i < pattern.length; i++) {\n keySchema = ctx.fallback.patternIntersection({\n code: \"patternIntersection\",\n base: keySchemaWithPattern,\n pattern: pattern[i].rule\n });\n }\n schema.patternProperties ??= {};\n schema.patternProperties[keySchemaWithPattern.pattern] =\n valueJsonSchema;\n }\n }\n }\n }\n if (this.undeclared && !schema.additionalProperties)\n schema.additionalProperties = false;\n return schema;\n }\n}\nconst defaultableMorphsCache = {};\nconst constructStructuralMorphCacheKey = (node) => {\n let cacheKey = \"\";\n for (let i = 0; i < node.defaultable.length; i++)\n cacheKey += node.defaultable[i].defaultValueMorphRef;\n if (node.sequence?.defaultValueMorphsReference)\n cacheKey += node.sequence?.defaultValueMorphsReference;\n if (node.undeclared === \"delete\") {\n cacheKey += \"delete !(\";\n if (node.required)\n for (const n of node.required)\n cacheKey += n.compiledKey + \" | \";\n if (node.optional)\n for (const n of node.optional)\n cacheKey += n.compiledKey + \" | \";\n if (node.index)\n for (const index of node.index)\n cacheKey += index.signature.id + \" | \";\n if (node.sequence) {\n if (node.sequence.maxLength === null)\n cacheKey += intrinsic.nonNegativeIntegerString.id;\n else {\n for (let i = 0; i < node.sequence.tuple.length; i++)\n cacheKey += i + \" | \";\n }\n }\n cacheKey += \")\";\n }\n return cacheKey;\n};\nconst getPossibleMorph = (node) => {\n const cacheKey = constructStructuralMorphCacheKey(node);\n if (!cacheKey)\n return undefined;\n if (defaultableMorphsCache[cacheKey])\n return defaultableMorphsCache[cacheKey];\n const $arkStructuralMorph = (data, ctx) => {\n for (let i = 0; i < node.defaultable.length; i++) {\n if (!(node.defaultable[i].key in data))\n node.defaultable[i].defaultValueMorph(data, ctx);\n }\n if (node.sequence?.defaultables) {\n for (let i = data.length - node.sequence.prefixLength; i < node.sequence.defaultables.length; i++)\n node.sequence.defaultValueMorphs[i](data, ctx);\n }\n if (node.undeclared === \"delete\")\n for (const k in data)\n if (!node.declaresKey(k))\n delete data[k];\n return data;\n };\n return (defaultableMorphsCache[cacheKey] = $arkStructuralMorph);\n};\nconst precompileMorphs = (js, node) => {\n const requiresContext = node.defaultable.some(node => node.defaultValueMorph.length === 2) ||\n node.sequence?.defaultValueMorphs.some(morph => morph.length === 2);\n const args = `(data${requiresContext ? \", ctx\" : \"\"})`;\n return js.block(`${args} => `, js => {\n for (let i = 0; i < node.defaultable.length; i++) {\n const { serializedKey, defaultValueMorphRef } = node.defaultable[i];\n js.if(`!(${serializedKey} in data)`, js => js.line(`${defaultValueMorphRef}${args}`));\n }\n if (node.sequence?.defaultables) {\n js.for(`i < ${node.sequence.defaultables.length}`, js => js.set(`data[i]`, 5), `data.length - ${node.sequence.prefixLength}`);\n }\n if (node.undeclared === \"delete\") {\n js.forIn(\"data\", js => js.if(`!(${node._compileDeclaresKey(js)})`, js => js.line(`delete data[k]`)));\n }\n return js.return(\"data\");\n });\n};\nexport const Structure = {\n implementation,\n Node: StructureNode\n};\nconst indexerToKey = (indexable) => {\n if (hasArkKind(indexable, \"root\") && indexable.hasKind(\"unit\"))\n indexable = indexable.unit;\n if (typeof indexable === \"number\")\n indexable = `${indexable}`;\n return indexable;\n};\nexport const writeNumberIndexMessage = (indexExpression, sequenceExpression) => `${indexExpression} is not allowed as an array index on ${sequenceExpression}. Use the 'nonNegativeIntegerString' keyword instead.`;\n/** extract enumerable named props from an index signature */\nexport const normalizeIndex = (signature, value, $) => {\n const [enumerableBranches, nonEnumerableBranches] = spliterate(signature.branches, k => k.hasKind(\"unit\"));\n if (!enumerableBranches.length)\n return { index: $.node(\"index\", { signature, value }) };\n const normalized = {};\n for (const n of enumerableBranches) {\n // since required can be reduced to optional if it has a default or\n // optional meta on its value, we have to assign it depending on the\n // compiled kind\n const prop = $.node(\"required\", { key: n.unit, value });\n normalized[prop.kind] = append(normalized[prop.kind], prop);\n }\n if (nonEnumerableBranches.length) {\n normalized.index = $.node(\"index\", {\n signature: nonEnumerableBranches,\n value\n });\n }\n return normalized;\n};\nexport const typeKeyToString = (k) => hasArkKind(k, \"root\") ? k.expression : printable(k);\nexport const writeInvalidKeysMessage = (o, keys) => `Key${keys.length === 1 ? \"\" : \"s\"} ${keys.map(typeKeyToString).join(\", \")} ${keys.length === 1 ? \"does\" : \"do\"} not exist on ${o}`;\nexport const writeDuplicateKeyMessage = (key) => `Duplicate key ${compileSerializedValue(key)}`;\n",
149
+ "import { deepClone, envHasCsp, flatMorph, withAlphabetizedKeys } from \"@ark/util\";\nimport { mergeConfigs } from \"./config.js\";\nimport { Predicate } from \"./predicate.js\";\nimport { Divisor } from \"./refinements/divisor.js\";\nimport { boundClassesByKind, boundImplementationsByKind } from \"./refinements/kinds.js\";\nimport { Pattern } from \"./refinements/pattern.js\";\nimport { Alias } from \"./roots/alias.js\";\nimport { Domain } from \"./roots/domain.js\";\nimport { Intersection } from \"./roots/intersection.js\";\nimport { Morph } from \"./roots/morph.js\";\nimport { Proto } from \"./roots/proto.js\";\nimport { Union } from \"./roots/union.js\";\nimport { Unit } from \"./roots/unit.js\";\nimport { $ark } from \"./shared/registry.js\";\nimport { ToJsonSchema } from \"./shared/toJsonSchema.js\";\nimport { Index } from \"./structure/index.js\";\nimport { Optional } from \"./structure/optional.js\";\nimport { Required } from \"./structure/required.js\";\nimport { Sequence } from \"./structure/sequence.js\";\nimport { Structure } from \"./structure/structure.js\";\nexport const nodeImplementationsByKind = {\n ...boundImplementationsByKind,\n alias: Alias.implementation,\n domain: Domain.implementation,\n unit: Unit.implementation,\n proto: Proto.implementation,\n union: Union.implementation,\n morph: Morph.implementation,\n intersection: Intersection.implementation,\n divisor: Divisor.implementation,\n pattern: Pattern.implementation,\n predicate: Predicate.implementation,\n required: Required.implementation,\n optional: Optional.implementation,\n index: Index.implementation,\n sequence: Sequence.implementation,\n structure: Structure.implementation\n};\n$ark.defaultConfig = withAlphabetizedKeys(Object.assign(flatMorph(nodeImplementationsByKind, (kind, implementation) => [\n kind,\n implementation.defaults\n]), {\n jitless: envHasCsp(),\n clone: deepClone,\n onUndeclaredKey: \"ignore\",\n exactOptionalPropertyTypes: true,\n numberAllowsNaN: false,\n dateAllowsInvalid: false,\n onFail: null,\n keywords: {},\n toJsonSchema: ToJsonSchema.defaultConfig\n}));\n$ark.resolvedConfig = mergeConfigs($ark.defaultConfig, $ark.config);\nexport const nodeClassesByKind = {\n ...boundClassesByKind,\n alias: Alias.Node,\n domain: Domain.Node,\n unit: Unit.Node,\n proto: Proto.Node,\n union: Union.Node,\n morph: Morph.Node,\n intersection: Intersection.Node,\n divisor: Divisor.Node,\n pattern: Pattern.Node,\n predicate: Predicate.Node,\n required: Required.Node,\n optional: Optional.Node,\n index: Index.Node,\n sequence: Sequence.Node,\n structure: Structure.Node\n};\n",
150
+ "import { DynamicBase, flatMorph } from \"@ark/util\";\nimport { arkKind, hasArkKind } from \"./shared/utils.js\";\nexport class RootModule extends DynamicBase {\n // ensure `[arkKind]` is non-enumerable so it doesn't get spread on import/export\n get [arkKind]() {\n return \"module\";\n }\n}\nexport const bindModule = (module, $) => new RootModule(flatMorph(module, (alias, value) => [\n alias,\n hasArkKind(value, \"module\") ?\n bindModule(value, $)\n : $.bindReference(value)\n]));\nexport const SchemaModule = RootModule;\n",
151
+ "import { ParseError, flatMorph, hasDomain, isArray, isThunk, printable, throwInternalError, throwParseError } from \"@ark/util\";\nimport { mergeConfigs } from \"./config.js\";\nimport { GenericRoot, LazyGenericBody } from \"./generic.js\";\nimport { nodeImplementationsByKind } from \"./kinds.js\";\nimport { RootModule, bindModule } from \"./module.js\";\nimport { nodesByRegisteredId, parseNode, registerNodeId, schemaKindOf, withId } from \"./parse.js\";\nimport { Alias } from \"./roots/alias.js\";\nimport { CompiledFunction, NodeCompiler } from \"./shared/compile.js\";\nimport { $ark } from \"./shared/registry.js\";\nimport { Traversal } from \"./shared/traversal.js\";\nimport { arkKind, hasArkKind, isNode } from \"./shared/utils.js\";\nconst schemaBranchesOf = (schema) => isArray(schema) ? schema\n : \"branches\" in schema && isArray(schema.branches) ? schema.branches\n : undefined;\nconst throwMismatchedNodeRootError = (expected, actual) => throwParseError(`Node of kind ${actual} is not valid as a ${expected} definition`);\nexport const writeDuplicateAliasError = (alias) => `#${alias} duplicates public alias ${alias}`;\nconst scopesByName = {};\n$ark.ambient ??= {};\nlet rawUnknownUnion;\nconst rootScopeFnName = \"function $\";\nconst precompile = (references) => bindPrecompilation(references, precompileReferences(references));\nconst bindPrecompilation = (references, precompiler) => {\n const precompilation = precompiler.write(rootScopeFnName, 4);\n const compiledTraversals = precompiler.compile()();\n for (const node of references) {\n if (node.precompilation) {\n // if node has already been bound to another scope or anonymous type, don't rebind it\n continue;\n }\n node.traverseAllows =\n compiledTraversals[`${node.id}Allows`].bind(compiledTraversals);\n if (node.isRoot() && !node.allowsRequiresContext) {\n // if the reference doesn't require context, we can assign over\n // it directly to avoid having to initialize it\n node.allows = node.traverseAllows;\n }\n node.traverseApply =\n compiledTraversals[`${node.id}Apply`].bind(compiledTraversals);\n if (compiledTraversals[`${node.id}Optimistic`]) {\n ;\n node.traverseOptimistic =\n compiledTraversals[`${node.id}Optimistic`].bind(compiledTraversals);\n }\n node.precompilation = precompilation;\n }\n};\nconst precompileReferences = (references) => new CompiledFunction().return(references.reduce((js, node) => {\n const allowsCompiler = new NodeCompiler({ kind: \"Allows\" }).indent();\n node.compile(allowsCompiler);\n const allowsJs = allowsCompiler.write(`${node.id}Allows`);\n const applyCompiler = new NodeCompiler({ kind: \"Apply\" }).indent();\n node.compile(applyCompiler);\n const applyJs = applyCompiler.write(`${node.id}Apply`);\n const result = `${js}${allowsJs},\\n${applyJs},\\n`;\n if (!node.hasKind(\"union\"))\n return result;\n const optimisticCompiler = new NodeCompiler({\n kind: \"Allows\",\n optimistic: true\n }).indent();\n node.compile(optimisticCompiler);\n const optimisticJs = optimisticCompiler.write(`${node.id}Optimistic`);\n return `${result}${optimisticJs},\\n`;\n}, \"{\\n\") + \"}\");\nexport class BaseScope {\n config;\n resolvedConfig;\n name;\n get [arkKind]() {\n return \"scope\";\n }\n referencesById = {};\n references = [];\n resolutions = {};\n exportedNames = [];\n aliases = {};\n resolved = false;\n nodesByHash = {};\n intrinsic;\n constructor(\n /** The set of names defined at the root-level of the scope mapped to their\n * corresponding definitions.**/\n def, config) {\n this.config = mergeConfigs($ark.config, config);\n this.resolvedConfig = mergeConfigs($ark.resolvedConfig, config);\n this.name =\n this.resolvedConfig.name ??\n `anonymousScope${Object.keys(scopesByName).length}`;\n if (this.name in scopesByName)\n throwParseError(`A Scope already named ${this.name} already exists`);\n scopesByName[this.name] = this;\n const aliasEntries = Object.entries(def).map(entry => this.preparseOwnAliasEntry(...entry));\n for (const [k, v] of aliasEntries) {\n let name = k;\n if (k[0] === \"#\") {\n name = k.slice(1);\n if (name in this.aliases)\n throwParseError(writeDuplicateAliasError(name));\n this.aliases[name] = v;\n }\n else {\n if (name in this.aliases)\n throwParseError(writeDuplicateAliasError(k));\n this.aliases[name] = v;\n this.exportedNames.push(name);\n }\n if (!hasArkKind(v, \"module\") &&\n !hasArkKind(v, \"generic\") &&\n !isThunk(v)) {\n const preparsed = this.preparseOwnDefinitionFormat(v, { alias: name });\n this.resolutions[name] =\n hasArkKind(preparsed, \"root\") ?\n this.bindReference(preparsed)\n : this.createParseContext(preparsed).id;\n }\n }\n // reduce union of all possible values reduces to unknown\n rawUnknownUnion ??= this.node(\"union\", {\n branches: [\n \"string\",\n \"number\",\n \"object\",\n \"bigint\",\n \"symbol\",\n { unit: true },\n { unit: false },\n { unit: undefined },\n { unit: null }\n ]\n }, { prereduced: true });\n this.nodesByHash[rawUnknownUnion.hash] = this.node(\"intersection\", {}, { prereduced: true });\n this.intrinsic =\n $ark.intrinsic ?\n flatMorph($ark.intrinsic, (k, v) => \n // don't include cyclic aliases from JSON scope\n k.startsWith(\"json\") ? [] : [k, this.bindReference(v)])\n // intrinsic won't be available during bootstrapping, so we lie\n // about the type here as an extrnal convenience\n : {};\n }\n cacheGetter(name, value) {\n Object.defineProperty(this, name, { value });\n return value;\n }\n get internal() {\n return this;\n }\n // json is populated when the scope is exported, so ensure it is populated\n // before allowing external access\n _json;\n get json() {\n if (!this._json)\n this.export();\n return this._json;\n }\n defineSchema(def) {\n return def;\n }\n generic = (...params) => {\n const $ = this;\n return (def, possibleHkt) => new GenericRoot(params, possibleHkt ? new LazyGenericBody(def) : def, $, $, possibleHkt ?? null);\n };\n units = (values, opts) => {\n const uniqueValues = [];\n for (const value of values)\n if (!uniqueValues.includes(value))\n uniqueValues.push(value);\n const branches = uniqueValues.map(unit => this.node(\"unit\", { unit }, opts));\n return this.node(\"union\", branches, {\n ...opts,\n prereduced: true\n });\n };\n lazyResolutions = [];\n lazilyResolve(resolve, syntheticAlias) {\n const node = this.node(\"alias\", {\n reference: syntheticAlias ?? \"synthetic\",\n resolve\n }, { prereduced: true });\n if (!this.resolved)\n this.lazyResolutions.push(node);\n return node;\n }\n schema = (schema, opts) => this.finalize(this.parseSchema(schema, opts));\n parseSchema = (schema, opts) => this.node(schemaKindOf(schema), schema, opts);\n preparseNode(kinds, schema, opts) {\n let kind = typeof kinds === \"string\" ? kinds : schemaKindOf(schema, kinds);\n if (isNode(schema) && schema.kind === kind)\n return schema;\n if (kind === \"alias\" && !opts?.prereduced) {\n const { reference } = Alias.implementation.normalize(schema, this);\n if (reference.startsWith(\"$\")) {\n const resolution = this.resolveRoot(reference.slice(1));\n schema = resolution;\n kind = resolution.kind;\n }\n }\n else if (kind === \"union\" && hasDomain(schema, \"object\")) {\n const branches = schemaBranchesOf(schema);\n if (branches?.length === 1) {\n schema = branches[0];\n kind = schemaKindOf(schema);\n }\n }\n if (isNode(schema) && schema.kind === kind)\n return schema;\n const impl = nodeImplementationsByKind[kind];\n const normalizedSchema = impl.normalize?.(schema, this) ?? schema;\n // check again after normalization in case a node is a valid collapsed\n // schema for the kind (e.g. sequence can collapse to element accepting a Node')\n if (isNode(normalizedSchema)) {\n return normalizedSchema.kind === kind ?\n normalizedSchema\n : throwMismatchedNodeRootError(kind, normalizedSchema.kind);\n }\n return {\n ...opts,\n $: this,\n kind,\n def: normalizedSchema,\n prefix: opts.alias ?? kind\n };\n }\n bindReference(reference) {\n let bound;\n if (isNode(reference)) {\n bound =\n reference.$ === this ?\n reference\n : new reference.constructor(reference.attachments, this);\n }\n else {\n bound =\n reference.$ === this ?\n reference\n : new GenericRoot(reference.params, reference.bodyDef, reference.$, this, reference.hkt);\n }\n if (!this.resolved) {\n // we're still parsing the scope itself, so defer compilation but\n // add the node as a reference\n Object.assign(this.referencesById, bound.referencesById);\n }\n return bound;\n }\n resolveRoot(name) {\n return (this.maybeResolveRoot(name) ??\n throwParseError(writeUnresolvableMessage(name)));\n }\n maybeResolveRoot(name) {\n const result = this.maybeResolve(name);\n if (hasArkKind(result, \"generic\"))\n return;\n return result;\n }\n /** If name is a valid reference to a submodule alias, return its resolution */\n maybeResolveSubalias(name) {\n return (maybeResolveSubalias(this.aliases, name) ??\n maybeResolveSubalias(this.ambient, name));\n }\n get ambient() {\n return $ark.ambient;\n }\n maybeResolve(name) {\n const cached = this.resolutions[name];\n if (cached) {\n if (typeof cached !== \"string\")\n return this.bindReference(cached);\n const v = nodesByRegisteredId[cached];\n if (hasArkKind(v, \"root\"))\n return (this.resolutions[name] = v);\n if (hasArkKind(v, \"context\")) {\n if (v.phase === \"resolving\") {\n return this.node(\"alias\", { reference: `$${name}` }, { prereduced: true });\n }\n if (v.phase === \"resolved\") {\n return throwInternalError(`Unexpected resolved context for was uncached by its scope: ${printable(v)}`);\n }\n v.phase = \"resolving\";\n const node = this.bindReference(this.parseOwnDefinitionFormat(v.def, v));\n v.phase = \"resolved\";\n nodesByRegisteredId[node.id] = node;\n nodesByRegisteredId[v.id] = node;\n return (this.resolutions[name] = node);\n }\n return throwInternalError(`Unexpected nodesById entry for ${cached}: ${printable(v)}`);\n }\n let def = this.aliases[name] ?? this.ambient?.[name];\n if (!def)\n return this.maybeResolveSubalias(name);\n def = this.normalizeRootScopeValue(def);\n if (hasArkKind(def, \"generic\"))\n return (this.resolutions[name] = this.bindReference(def));\n if (hasArkKind(def, \"module\")) {\n if (!def.root)\n throwParseError(writeMissingSubmoduleAccessMessage(name));\n return (this.resolutions[name] = this.bindReference(def.root));\n }\n return (this.resolutions[name] = this.parse(def, {\n alias: name\n }));\n }\n createParseContext(input) {\n const id = input.id ?? registerNodeId(input.prefix);\n return (nodesByRegisteredId[id] = Object.assign(input, {\n [arkKind]: \"context\",\n $: this,\n id,\n phase: \"unresolved\"\n }));\n }\n traversal(root) {\n return new Traversal(root, this.resolvedConfig);\n }\n import(...names) {\n return new RootModule(flatMorph(this.export(...names), (alias, value) => [\n `#${alias}`,\n value\n ]));\n }\n precompilation;\n _exportedResolutions;\n _exports;\n export(...names) {\n if (!this._exports) {\n this._exports = {};\n for (const name of this.exportedNames) {\n const def = this.aliases[name];\n this._exports[name] =\n hasArkKind(def, \"module\") ?\n bindModule(def, this)\n : bootstrapAliasReferences(this.maybeResolve(name));\n }\n // force node.resolution getter evaluation\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n for (const node of this.lazyResolutions)\n node.resolution;\n this._exportedResolutions = resolutionsOfModule(this, this._exports);\n this._json = resolutionsToJson(this._exportedResolutions);\n Object.assign(this.resolutions, this._exportedResolutions);\n this.references = Object.values(this.referencesById);\n if (!this.resolvedConfig.jitless) {\n const precompiler = precompileReferences(this.references);\n this.precompilation = precompiler.write(rootScopeFnName, 4);\n bindPrecompilation(this.references, precompiler);\n }\n this.resolved = true;\n }\n const namesToExport = names.length ? names : this.exportedNames;\n return new RootModule(flatMorph(namesToExport, (_, name) => [\n name,\n this._exports[name]\n ]));\n }\n resolve(name) {\n return this.export()[name];\n }\n node = (kinds, nodeSchema, opts = {}) => {\n const ctxOrNode = this.preparseNode(kinds, nodeSchema, opts);\n if (isNode(ctxOrNode))\n return this.bindReference(ctxOrNode);\n const ctx = this.createParseContext(ctxOrNode);\n const node = parseNode(ctx);\n const bound = this.bindReference(node);\n return (nodesByRegisteredId[ctx.id] = bound);\n };\n parse = (def, opts = {}) => this.finalize(this.parseDefinition(def, opts));\n parseDefinition(def, opts = {}) {\n if (hasArkKind(def, \"root\"))\n return this.bindReference(def);\n const ctxInputOrNode = this.preparseOwnDefinitionFormat(def, opts);\n if (hasArkKind(ctxInputOrNode, \"root\"))\n return this.bindReference(ctxInputOrNode);\n const ctx = this.createParseContext(ctxInputOrNode);\n nodesByRegisteredId[ctx.id] = ctx;\n let node = this.bindReference(this.parseOwnDefinitionFormat(def, ctx));\n // if the node is recursive e.g. { box: \"this\" }, we need to make sure it\n // has the original id from context so that its references compile correctly\n if (node.isCyclic)\n node = withId(node, ctx.id);\n nodesByRegisteredId[ctx.id] = node;\n return node;\n }\n finalize(node) {\n bootstrapAliasReferences(node);\n if (!node.precompilation && !this.resolvedConfig.jitless)\n precompile(node.references);\n return node;\n }\n}\nexport class SchemaScope extends BaseScope {\n parseOwnDefinitionFormat(def, ctx) {\n return parseNode(ctx);\n }\n preparseOwnDefinitionFormat(schema, opts) {\n return this.preparseNode(schemaKindOf(schema), schema, opts);\n }\n preparseOwnAliasEntry(k, v) {\n return [k, v];\n }\n normalizeRootScopeValue(v) {\n return v;\n }\n}\nconst bootstrapAliasReferences = (resolution) => {\n const aliases = resolution.references.filter(node => node.hasKind(\"alias\"));\n for (const aliasNode of aliases) {\n Object.assign(aliasNode.referencesById, aliasNode.resolution.referencesById);\n for (const ref of resolution.references) {\n if (aliasNode.id in ref.referencesById)\n Object.assign(ref.referencesById, aliasNode.referencesById);\n }\n }\n return resolution;\n};\nconst resolutionsToJson = (resolutions) => flatMorph(resolutions, (k, v) => [\n k,\n hasArkKind(v, \"root\") || hasArkKind(v, \"generic\") ? v.json\n : hasArkKind(v, \"module\") ? resolutionsToJson(v)\n : throwInternalError(`Unexpected resolution ${printable(v)}`)\n]);\nconst maybeResolveSubalias = (base, name) => {\n const dotIndex = name.indexOf(\".\");\n if (dotIndex === -1)\n return;\n const dotPrefix = name.slice(0, dotIndex);\n const prefixSchema = base[dotPrefix];\n // if the name includes \".\", but the prefix is not an alias, it\n // might be something like a decimal literal, so just fall through to return\n if (prefixSchema === undefined)\n return;\n if (!hasArkKind(prefixSchema, \"module\"))\n return throwParseError(writeNonSubmoduleDotMessage(dotPrefix));\n const subalias = name.slice(dotIndex + 1);\n const resolution = prefixSchema[subalias];\n if (resolution === undefined)\n return maybeResolveSubalias(prefixSchema, subalias);\n if (hasArkKind(resolution, \"root\") || hasArkKind(resolution, \"generic\"))\n return resolution;\n if (hasArkKind(resolution, \"module\")) {\n return (resolution.root ??\n throwParseError(writeMissingSubmoduleAccessMessage(name)));\n }\n throwInternalError(`Unexpected resolution for alias '${name}': ${printable(resolution)}`);\n};\nexport const schemaScope = (aliases, config) => new SchemaScope(aliases, config);\nexport const rootSchemaScope = new SchemaScope({});\nexport const parseAsSchema = (def, opts) => {\n try {\n return rootSchema(def, opts);\n }\n catch (e) {\n if (e instanceof ParseError)\n return e;\n throw e;\n }\n};\nconst resolutionsOfModule = ($, typeSet) => {\n const result = {};\n for (const k in typeSet) {\n const v = typeSet[k];\n if (hasArkKind(v, \"module\")) {\n const innerResolutions = resolutionsOfModule($, v);\n const prefixedResolutions = flatMorph(innerResolutions, (innerK, innerV) => [`${k}.${innerK}`, innerV]);\n Object.assign(result, prefixedResolutions);\n }\n else if (hasArkKind(v, \"root\") || hasArkKind(v, \"generic\"))\n result[k] = v;\n else\n throwInternalError(`Unexpected scope resolution ${printable(v)}`);\n }\n return result;\n};\nexport const writeUnresolvableMessage = (token) => `'${token}' is unresolvable`;\nexport const writeNonSubmoduleDotMessage = (name) => `'${name}' must reference a module to be accessed using dot syntax`;\nexport const writeMissingSubmoduleAccessMessage = (name) => `Reference to submodule '${name}' must specify an alias`;\n// ensure the scope is resolved so JIT will be applied to future types\nrootSchemaScope.export();\nexport const rootSchema = rootSchemaScope.schema;\nexport const node = rootSchemaScope.node;\nexport const defineSchema = rootSchemaScope.defineSchema;\nexport const genericNode = rootSchemaScope.generic;\n",
152
+ "import { registeredReference } from \"../shared/registry.js\";\nexport const arrayIndexSource = `^(?:0|[1-9]\\\\d*)$`;\nexport const arrayIndexMatcher = new RegExp(arrayIndexSource);\nexport const arrayIndexMatcherReference = registeredReference(arrayIndexMatcher);\n",
153
+ "import { node, schemaScope } from \"./scope.js\";\nimport { $ark } from \"./shared/registry.js\";\nimport { arrayIndexSource } from \"./structure/shared.js\";\nconst intrinsicBases = schemaScope({\n bigint: \"bigint\",\n // since we know this won't be reduced, it can be safely cast to a union\n boolean: [{ unit: false }, { unit: true }],\n false: { unit: false },\n never: [],\n null: { unit: null },\n number: \"number\",\n object: \"object\",\n string: \"string\",\n symbol: \"symbol\",\n true: { unit: true },\n unknown: {},\n undefined: { unit: undefined },\n Array,\n Date\n}, { prereducedAliases: true }).export();\n$ark.intrinsic = { ...intrinsicBases };\nconst intrinsicRoots = schemaScope({\n integer: {\n domain: \"number\",\n divisor: 1\n },\n lengthBoundable: [\"string\", Array],\n key: [\"string\", \"symbol\"],\n nonNegativeIntegerString: { domain: \"string\", pattern: arrayIndexSource }\n}, { prereducedAliases: true }).export();\n// needed to parse index signatures for JSON\nObject.assign($ark.intrinsic, intrinsicRoots);\nconst intrinsicJson = schemaScope({\n jsonPrimitive: [\n \"string\",\n \"number\",\n { unit: true },\n { unit: false },\n { unit: null }\n ],\n jsonObject: {\n domain: \"object\",\n index: {\n signature: \"string\",\n value: \"$jsonData\"\n }\n },\n jsonData: [\"$jsonPrimitive\", \"$jsonObject\"]\n}, { prereducedAliases: true }).export();\nexport const intrinsic = {\n ...intrinsicBases,\n ...intrinsicRoots,\n ...intrinsicJson,\n emptyStructure: node(\"structure\", {}, { prereduced: true })\n};\n$ark.intrinsic = { ...intrinsic };\n",
154
+ "export const regex = ((src, flags) => new RegExp(src, flags));\nObject.assign(regex, { as: regex });\n",
155
+ "import { throwParseError, tryParseNumber } from \"@ark/util\";\nexport const isDateLiteral = (value) => typeof value === \"string\" &&\n value[0] === \"d\" &&\n (value[1] === \"'\" || value[1] === '\"') &&\n value[value.length - 1] === value[1];\nexport const isValidDate = (d) => d.toString() !== \"Invalid Date\";\nexport const extractDateLiteralSource = (literal) => literal.slice(2, -1);\nexport const writeInvalidDateMessage = (source) => `'${source}' could not be parsed by the Date constructor`;\nexport const tryParseDate = (source, errorOnFail) => maybeParseDate(source, errorOnFail);\nconst maybeParseDate = (source, errorOnFail) => {\n const stringParsedDate = new Date(source);\n if (isValidDate(stringParsedDate))\n return stringParsedDate;\n const epochMillis = tryParseNumber(source);\n if (epochMillis !== undefined) {\n const numberParsedDate = new Date(epochMillis);\n if (isValidDate(numberParsedDate))\n return numberParsedDate;\n }\n return errorOnFail ?\n throwParseError(errorOnFail === true ? writeInvalidDateMessage(source) : errorOnFail)\n : undefined;\n};\n",
156
+ "import { rootSchema } from \"@ark/schema\";\nimport { isKeyOf, throwParseError } from \"@ark/util\";\nimport { tryParseDate, writeInvalidDateMessage } from \"./date.js\";\nconst regexExecArray = rootSchema({\n proto: \"Array\",\n sequence: \"string\",\n required: {\n key: \"groups\",\n value: [\"object\", { unit: undefined }]\n }\n});\nexport const parseEnclosed = (s, enclosing) => {\n const enclosed = s.scanner.shiftUntilEscapable(untilLookaheadIsClosing[enclosingTokens[enclosing]]);\n if (s.scanner.lookahead === \"\")\n return s.error(writeUnterminatedEnclosedMessage(enclosed, enclosing));\n // Shift the scanner one additional time for the second enclosing token\n s.scanner.shift();\n if (enclosing in enclosingRegexTokens) {\n let regex;\n try {\n regex = new RegExp(enclosed);\n }\n catch (e) {\n throwParseError(String(e));\n }\n s.root = s.ctx.$.node(\"intersection\", {\n domain: \"string\",\n pattern: enclosed\n }, { prereduced: true });\n if (enclosing === \"x/\") {\n s.root = s.ctx.$.node(\"morph\", {\n in: s.root,\n morphs: (s) => regex.exec(s),\n declaredOut: regexExecArray\n });\n }\n }\n else if (isKeyOf(enclosing, enclosingQuote))\n s.root = s.ctx.$.node(\"unit\", { unit: enclosed });\n else {\n const date = tryParseDate(enclosed, writeInvalidDateMessage(enclosed));\n s.root = s.ctx.$.node(\"unit\", { meta: enclosed, unit: date });\n }\n};\nexport const enclosingQuote = {\n \"'\": 1,\n '\"': 1\n};\nexport const enclosingChar = {\n \"/\": 1,\n \"'\": 1,\n '\"': 1\n};\nexport const enclosingLiteralTokens = {\n \"d'\": \"'\",\n 'd\"': '\"',\n \"'\": \"'\",\n '\"': '\"'\n};\nexport const enclosingRegexTokens = {\n \"/\": \"/\",\n \"x/\": \"/\"\n};\nexport const enclosingTokens = {\n ...enclosingLiteralTokens,\n ...enclosingRegexTokens\n};\nexport const untilLookaheadIsClosing = {\n \"'\": scanner => scanner.lookahead === `'`,\n '\"': scanner => scanner.lookahead === `\"`,\n \"/\": scanner => scanner.lookahead === `/`\n};\nconst enclosingCharDescriptions = {\n '\"': \"double-quote\",\n \"'\": \"single-quote\",\n \"/\": \"forward slash\"\n};\nexport const writeUnterminatedEnclosedMessage = (fragment, enclosingStart) => `${enclosingStart}${fragment} requires a closing ${enclosingCharDescriptions[enclosingTokens[enclosingStart]]}`;\n",
157
+ "export const writePrefixedPrivateReferenceMessage = (name) => `Private type references should not include '#'. Use '${name}' instead.`;\nexport const shallowOptionalMessage = \"Optional definitions like 'string?' are only valid as properties in an object or tuple\";\nexport const shallowDefaultableMessage = \"Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple\";\n",
158
+ "import { isKeyOf, whitespaceChars } from \"@ark/util\";\nexport const terminatingChars = {\n \"<\": 1,\n \">\": 1,\n \"=\": 1,\n \"|\": 1,\n \"&\": 1,\n \")\": 1,\n \"[\": 1,\n \"%\": 1,\n \",\": 1,\n \":\": 1,\n \"?\": 1,\n \"#\": 1,\n ...whitespaceChars\n};\nexport const finalizingLookaheads = {\n \">\": 1,\n \",\": 1,\n \"\": 1,\n \"=\": 1,\n \"?\": 1\n};\nexport const lookaheadIsFinalizing = (lookahead, unscanned) => lookahead === \">\" ?\n unscanned[0] === \"=\" ?\n // >== would only occur in an expression like Array<number>==5\n // otherwise, >= would only occur as part of a bound like number>=5\n unscanned[1] === \"=\"\n // if > is the end of a generic instantiation, the next token will be\n // an operator or the end of the string\n : unscanned.trimStart() === \"\" ||\n isKeyOf(unscanned.trimStart()[0], terminatingChars)\n // \"=\" is a finalizer on its own (representing a default value),\n // but not with a second \"=\" (an equality comparator)\n : lookahead === \"=\" ? unscanned[0] !== \"=\"\n // \",\" and \"?\" are unambiguously finalizers\n : lookahead === \",\" || lookahead === \"?\";\n",
159
+ "import { writeUnclosedGroupMessage } from \"@ark/util\";\nexport const parseGenericArgs = (name, g, s) => _parseGenericArgs(name, g, s, []);\nconst _parseGenericArgs = (name, g, s, argNodes) => {\n const argState = s.parseUntilFinalizer();\n argNodes.push(argState.root);\n if (argState.finalizer === \">\") {\n if (argNodes.length !== g.params.length) {\n return s.error(writeInvalidGenericArgCountMessage(name, g.names, argNodes.map(arg => arg.expression)));\n }\n return argNodes;\n }\n if (argState.finalizer === \",\")\n return _parseGenericArgs(name, g, s, argNodes);\n return argState.error(writeUnclosedGroupMessage(\">\"));\n};\nexport const writeInvalidGenericArgCountMessage = (name, params, argDefs) => `${name}<${params.join(\", \")}> requires exactly ${params.length} args (got ${argDefs.length}${argDefs.length === 0 ? \"\" : `: ${argDefs.join(\", \")}`})`;\n",
160
+ "import { hasArkKind, writeUnresolvableMessage } from \"@ark/schema\";\nimport { printable, throwParseError, tryParseWellFormedBigint, tryParseWellFormedNumber } from \"@ark/util\";\nimport { writePrefixedPrivateReferenceMessage } from \"../../ast/validate.js\";\nimport { terminatingChars } from \"../tokens.js\";\nimport { parseGenericArgs, writeInvalidGenericArgCountMessage } from \"./genericArgs.js\";\nexport const parseUnenclosed = (s) => {\n const token = s.scanner.shiftUntilLookahead(terminatingChars);\n if (token === \"keyof\")\n s.addPrefix(\"keyof\");\n else\n s.root = unenclosedToNode(s, token);\n};\nexport const parseGenericInstantiation = (name, g, s) => {\n s.scanner.shiftUntilNonWhitespace();\n const lookahead = s.scanner.shift();\n if (lookahead !== \"<\")\n return s.error(writeInvalidGenericArgCountMessage(name, g.names, []));\n const parsedArgs = parseGenericArgs(name, g, s);\n return g(...parsedArgs);\n};\nconst unenclosedToNode = (s, token) => maybeParseReference(s, token) ??\n maybeParseUnenclosedLiteral(s, token) ??\n s.error(token === \"\" ?\n s.scanner.lookahead === \"#\" ?\n writePrefixedPrivateReferenceMessage(s.shiftedBy(1).scanner.shiftUntilLookahead(terminatingChars))\n : writeMissingOperandMessage(s)\n : writeUnresolvableMessage(token));\nconst maybeParseReference = (s, token) => {\n if (s.ctx.args?.[token]) {\n const arg = s.ctx.args[token];\n if (typeof arg !== \"string\")\n return arg;\n return s.ctx.$.node(\"alias\", { reference: arg }, { prereduced: true });\n }\n const resolution = s.ctx.$.maybeResolve(token);\n if (hasArkKind(resolution, \"root\"))\n return resolution;\n if (resolution === undefined)\n return;\n if (hasArkKind(resolution, \"generic\"))\n return parseGenericInstantiation(token, resolution, s);\n return throwParseError(`Unexpected resolution ${printable(resolution)}`);\n};\nconst maybeParseUnenclosedLiteral = (s, token) => {\n const maybeNumber = tryParseWellFormedNumber(token);\n if (maybeNumber !== undefined)\n return s.ctx.$.node(\"unit\", { unit: maybeNumber });\n const maybeBigint = tryParseWellFormedBigint(token);\n if (maybeBigint !== undefined)\n return s.ctx.$.node(\"unit\", { unit: maybeBigint });\n};\nexport const writeMissingOperandMessage = (s) => {\n const operator = s.previousOperator();\n return operator ?\n writeMissingRightOperandMessage(operator, s.scanner.unscanned)\n : writeExpressionExpectedMessage(s.scanner.unscanned);\n};\nexport const writeMissingRightOperandMessage = (token, unscanned = \"\") => `Token '${token}' requires a right operand${unscanned ? ` before '${unscanned}'` : \"\"}`;\nexport const writeExpressionExpectedMessage = (unscanned) => `Expected an expression${unscanned ? ` before '${unscanned}'` : \"\"}`;\n",
161
+ "import { whitespaceChars } from \"@ark/util\";\nimport { enclosingChar, enclosingQuote, parseEnclosed } from \"./enclosed.js\";\nimport { parseUnenclosed, writeMissingOperandMessage } from \"./unenclosed.js\";\nexport const parseOperand = (s) => s.scanner.lookahead === \"\" ? s.error(writeMissingOperandMessage(s))\n : s.scanner.lookahead === \"(\" ? s.shiftedBy(1).reduceGroupOpen()\n : s.scanner.lookaheadIsIn(enclosingChar) ? parseEnclosed(s, s.scanner.shift())\n : s.scanner.lookaheadIsIn(whitespaceChars) ? parseOperand(s.shiftedBy(1))\n : s.scanner.lookahead === \"d\" ?\n s.scanner.nextLookahead in enclosingQuote ?\n parseEnclosed(s, `${s.scanner.shift()}${s.scanner.shift()}`)\n : parseUnenclosed(s)\n : s.scanner.lookahead === \"x\" ?\n s.scanner.nextLookahead === \"/\" ?\n s.shiftedBy(2) && parseEnclosed(s, \"x/\")\n : parseUnenclosed(s)\n : parseUnenclosed(s);\n",
162
+ "export const minComparators = {\n \">\": true,\n \">=\": true\n};\nexport const maxComparators = {\n \"<\": true,\n \"<=\": true\n};\nexport const comparators = {\n \">\": true,\n \">=\": true,\n \"<\": true,\n \"<=\": true,\n \"==\": true\n};\nexport const invertedComparators = {\n \"<\": \">\",\n \">\": \"<\",\n \"<=\": \">=\",\n \">=\": \"<=\",\n \"==\": \"==\"\n};\nexport const writeOpenRangeMessage = (min, comparator) => `Left bounds are only valid when paired with right bounds (try ...${comparator}${min})`;\nexport const writeUnpairableComparatorMessage = (comparator) => `Left-bounded expressions must specify their limits using < or <= (was ${comparator})`;\nexport const writeMultipleLeftBoundsMessage = (openLimit, openComparator, limit, comparator) => `An expression may have at most one left bound (parsed ${openLimit}${invertedComparators[openComparator]}, ${limit}${invertedComparators[comparator]})`;\n",
163
+ "import { $ark, writeUnboundableMessage } from \"@ark/schema\";\nimport { isKeyOf, throwParseError } from \"@ark/util\";\nimport { invertedComparators, maxComparators, writeUnpairableComparatorMessage } from \"../../reduce/shared.js\";\nimport { extractDateLiteralSource, isDateLiteral } from \"../operand/date.js\";\nexport const parseBound = (s, start) => {\n const comparator = shiftComparator(s, start);\n if (s.root.hasKind(\"unit\")) {\n if (typeof s.root.unit === \"number\") {\n s.reduceLeftBound(s.root.unit, comparator);\n s.unsetRoot();\n return;\n }\n if (s.root.unit instanceof Date) {\n const literal = `d'${s.root.description ?? s.root.unit.toISOString()}'`;\n s.unsetRoot();\n s.reduceLeftBound(literal, comparator);\n return;\n }\n }\n return parseRightBound(s, comparator);\n};\nexport const comparatorStartChars = {\n \"<\": 1,\n \">\": 1,\n \"=\": 1\n};\nconst shiftComparator = (s, start) => s.scanner.lookaheadIs(\"=\") ?\n `${start}${s.scanner.shift()}`\n : start;\nexport const writeIncompatibleRangeMessage = (l, r) => `Bound kinds ${l} and ${r} are incompatible`;\nexport const getBoundKinds = (comparator, limit, root, boundKind) => {\n if (root.extends($ark.intrinsic.number)) {\n if (typeof limit !== \"number\") {\n return throwParseError(writeInvalidLimitMessage(comparator, limit, boundKind));\n }\n return (comparator === \"==\" ? [\"min\", \"max\"]\n : comparator[0] === \">\" ? [\"min\"]\n : [\"max\"]);\n }\n if (root.extends($ark.intrinsic.lengthBoundable)) {\n if (typeof limit !== \"number\") {\n return throwParseError(writeInvalidLimitMessage(comparator, limit, boundKind));\n }\n return (comparator === \"==\" ? [\"exactLength\"]\n : comparator[0] === \">\" ? [\"minLength\"]\n : [\"maxLength\"]);\n }\n if (root.extends($ark.intrinsic.Date)) {\n // allow either numeric or date limits\n return (comparator === \"==\" ? [\"after\", \"before\"]\n : comparator[0] === \">\" ? [\"after\"]\n : [\"before\"]);\n }\n return throwParseError(writeUnboundableMessage(root.expression));\n};\nconst openLeftBoundToRoot = (leftBound) => ({\n rule: isDateLiteral(leftBound.limit) ?\n extractDateLiteralSource(leftBound.limit)\n : leftBound.limit,\n exclusive: leftBound.comparator.length === 1\n});\nexport const parseRightBound = (s, comparator) => {\n // store the node that will be bounded\n const previousRoot = s.unsetRoot();\n const previousScannerIndex = s.scanner.location;\n s.parseOperand();\n const limitNode = s.unsetRoot();\n // after parsing the next operand, use the locations to get the\n // token from which it was parsed\n const limitToken = s.scanner.sliceChars(previousScannerIndex, s.scanner.location);\n s.root = previousRoot;\n if (!limitNode.hasKind(\"unit\") ||\n (typeof limitNode.unit !== \"number\" && !(limitNode.unit instanceof Date)))\n return s.error(writeInvalidLimitMessage(comparator, limitToken, \"right\"));\n const limit = limitNode.unit;\n // apply the newly-parsed right bound\n const exclusive = comparator.length === 1;\n const boundKinds = getBoundKinds(comparator, typeof limit === \"number\" ? limit : limitToken, previousRoot, \"right\");\n for (const kind of boundKinds) {\n s.constrainRoot(kind, comparator === \"==\" ? { rule: limit } : { rule: limit, exclusive });\n }\n if (!s.branches.leftBound)\n return;\n // if there's an open left bound, perform additional validation and apply it\n if (!isKeyOf(comparator, maxComparators))\n return s.error(writeUnpairableComparatorMessage(comparator));\n const lowerBoundKind = getBoundKinds(s.branches.leftBound.comparator, s.branches.leftBound.limit, previousRoot, \"left\");\n s.constrainRoot(lowerBoundKind[0], openLeftBoundToRoot(s.branches.leftBound));\n s.branches.leftBound = null;\n};\nexport const writeInvalidLimitMessage = (comparator, limit, boundKind) => `Comparator ${boundKind === \"left\" ? invertedComparators[comparator] : comparator} must be ${boundKind === \"left\" ? \"preceded\" : \"followed\"} by a corresponding literal (was ${limit})`;\n",
164
+ "import { terminatingChars } from \"../tokens.js\";\nexport const parseBrand = (s) => {\n s.scanner.shiftUntilNonWhitespace();\n const brandName = s.scanner.shiftUntilLookahead(terminatingChars);\n s.root = s.root.brand(brandName);\n};\n",
165
+ "import { tryParseInteger } from \"@ark/util\";\nimport { terminatingChars } from \"../tokens.js\";\nexport const parseDivisor = (s) => {\n s.scanner.shiftUntilNonWhitespace();\n const divisorToken = s.scanner.shiftUntilLookahead(terminatingChars);\n const divisor = tryParseInteger(divisorToken, {\n errorOnFail: writeInvalidDivisorMessage(divisorToken)\n });\n if (divisor === 0)\n s.error(writeInvalidDivisorMessage(0));\n s.root = s.root.constrain(\"divisor\", divisor);\n};\nexport const writeInvalidDivisorMessage = (divisor) => `% operator must be followed by a non-zero integer literal (was ${divisor})`;\n",
166
+ "import { isKeyOf, whitespaceChars } from \"@ark/util\";\nimport { lookaheadIsFinalizing } from \"../tokens.js\";\nimport { comparatorStartChars, parseBound } from \"./bounds.js\";\nimport { parseBrand } from \"./brand.js\";\nimport { parseDivisor } from \"./divisor.js\";\nexport const parseOperator = (s) => {\n const lookahead = s.scanner.shift();\n return (lookahead === \"\" ? s.finalize(\"\")\n : lookahead === \"[\" ?\n s.scanner.shift() === \"]\" ?\n s.setRoot(s.root.array())\n : s.error(incompleteArrayTokenMessage)\n : lookahead === \"|\" ?\n s.scanner.lookahead === \">\" ?\n s.shiftedBy(1).pushRootToBranch(\"|>\")\n : s.pushRootToBranch(lookahead)\n : lookahead === \"&\" ? s.pushRootToBranch(lookahead)\n : lookahead === \")\" ? s.finalizeGroup()\n : lookaheadIsFinalizing(lookahead, s.scanner.unscanned) ?\n s.finalize(lookahead)\n : isKeyOf(lookahead, comparatorStartChars) ? parseBound(s, lookahead)\n : lookahead === \"%\" ? parseDivisor(s)\n : lookahead === \"#\" ? parseBrand(s)\n : lookahead in whitespaceChars ? parseOperator(s)\n : s.error(writeUnexpectedCharacterMessage(lookahead)));\n};\nexport const writeUnexpectedCharacterMessage = (char, shouldBe = \"\") => `'${char}' is not allowed here${shouldBe && ` (should be ${shouldBe})`}`;\nexport const incompleteArrayTokenMessage = `Missing expected ']'`;\n",
167
+ "export const parseDefault = (s) => {\n // store the node that will be bounded\n const baseNode = s.unsetRoot();\n s.parseOperand();\n const defaultNode = s.unsetRoot();\n // after parsing the next operand, use the locations to get the\n // token from which it was parsed\n if (!defaultNode.hasKind(\"unit\"))\n return s.error(writeNonLiteralDefaultMessage(defaultNode.expression));\n const defaultValue = defaultNode.unit instanceof Date ?\n () => new Date(defaultNode.unit)\n : defaultNode.unit;\n return [baseNode, \"=\", defaultValue];\n};\nexport const writeNonLiteralDefaultMessage = (defaultDef) => `Default value '${defaultDef}' must be a literal value`;\n",
168
+ "import { Scanner, throwInternalError, throwParseError } from \"@ark/util\";\nimport { RuntimeState } from \"./reduce/dynamic.js\";\nimport { parseDefault } from \"./shift/operator/default.js\";\nimport { writeUnexpectedCharacterMessage } from \"./shift/operator/operator.js\";\nexport const parseString = (def, ctx) => {\n const aliasResolution = ctx.$.maybeResolveRoot(def);\n if (aliasResolution)\n return aliasResolution;\n if (def.endsWith(\"[]\")) {\n const possibleElementResolution = ctx.$.maybeResolveRoot(def.slice(0, -2));\n if (possibleElementResolution)\n return possibleElementResolution.array();\n }\n const s = new RuntimeState(new Scanner(def), ctx);\n const node = fullStringParse(s);\n if (s.finalizer === \">\")\n throwParseError(writeUnexpectedCharacterMessage(\">\"));\n return node;\n};\nexport const fullStringParse = (s) => {\n s.parseOperand();\n let result = parseUntilFinalizer(s).root;\n if (!result) {\n return throwInternalError(`Root was unexpectedly unset after parsing string '${s.scanner.scanned}'`);\n }\n if (s.finalizer === \"=\")\n result = parseDefault(s);\n else if (s.finalizer === \"?\")\n result = [result, \"?\"];\n s.scanner.shiftUntilNonWhitespace();\n if (s.scanner.lookahead) {\n // throw a parse error if non-whitespace characters made it here without being parsed\n throwParseError(writeUnexpectedCharacterMessage(s.scanner.lookahead));\n }\n return result;\n};\nexport const parseUntilFinalizer = (s) => {\n while (s.finalizer === undefined)\n next(s);\n return s;\n};\nconst next = (s) => s.hasRoot() ? s.parseOperator() : s.parseOperand();\n",
169
+ "import { isKeyOf, throwInternalError, throwParseError, writeUnclosedGroupMessage, writeUnmatchedGroupCloseMessage } from \"@ark/util\";\nimport { parseOperand } from \"../shift/operand/operand.js\";\nimport { parseOperator } from \"../shift/operator/operator.js\";\nimport { parseUntilFinalizer } from \"../string.js\";\nimport { invertedComparators, minComparators, writeMultipleLeftBoundsMessage, writeOpenRangeMessage, writeUnpairableComparatorMessage } from \"./shared.js\";\nexport class RuntimeState {\n root;\n branches = {\n prefixes: [],\n leftBound: null,\n intersection: null,\n union: null,\n pipe: null\n };\n finalizer;\n groups = [];\n scanner;\n ctx;\n constructor(scanner, ctx) {\n this.scanner = scanner;\n this.ctx = ctx;\n }\n error(message) {\n return throwParseError(message);\n }\n hasRoot() {\n return this.root !== undefined;\n }\n setRoot(root) {\n this.root = root;\n }\n unsetRoot() {\n const value = this.root;\n this.root = undefined;\n return value;\n }\n constrainRoot(...args) {\n this.root = this.root.constrain(args[0], args[1]);\n }\n finalize(finalizer) {\n if (this.groups.length)\n return this.error(writeUnclosedGroupMessage(\")\"));\n this.finalizeBranches();\n this.finalizer = finalizer;\n }\n reduceLeftBound(limit, comparator) {\n const invertedComparator = invertedComparators[comparator];\n if (!isKeyOf(invertedComparator, minComparators))\n return this.error(writeUnpairableComparatorMessage(comparator));\n if (this.branches.leftBound) {\n return this.error(writeMultipleLeftBoundsMessage(this.branches.leftBound.limit, this.branches.leftBound.comparator, limit, invertedComparator));\n }\n this.branches.leftBound = {\n comparator: invertedComparator,\n limit\n };\n }\n finalizeBranches() {\n this.assertRangeUnset();\n if (this.branches.pipe) {\n this.pushRootToBranch(\"|>\");\n this.root = this.branches.pipe;\n return;\n }\n if (this.branches.union) {\n this.pushRootToBranch(\"|\");\n this.root = this.branches.union;\n return;\n }\n if (this.branches.intersection) {\n this.pushRootToBranch(\"&\");\n this.root = this.branches.intersection;\n return;\n }\n this.applyPrefixes();\n }\n finalizeGroup() {\n this.finalizeBranches();\n const topBranchState = this.groups.pop();\n if (!topBranchState) {\n return this.error(writeUnmatchedGroupCloseMessage(\")\", this.scanner.unscanned));\n }\n this.branches = topBranchState;\n }\n addPrefix(prefix) {\n this.branches.prefixes.push(prefix);\n }\n applyPrefixes() {\n while (this.branches.prefixes.length) {\n const lastPrefix = this.branches.prefixes.pop();\n this.root =\n lastPrefix === \"keyof\" ?\n this.root.keyof()\n : throwInternalError(`Unexpected prefix '${lastPrefix}'`);\n }\n }\n pushRootToBranch(token) {\n this.assertRangeUnset();\n this.applyPrefixes();\n const root = this.root;\n this.root = undefined;\n this.branches.intersection =\n this.branches.intersection?.rawAnd(root) ?? root;\n if (token === \"&\")\n return;\n this.branches.union =\n this.branches.union?.rawOr(this.branches.intersection) ??\n this.branches.intersection;\n this.branches.intersection = null;\n if (token === \"|\")\n return;\n this.branches.pipe =\n this.branches.pipe?.rawPipeOnce(this.branches.union) ??\n this.branches.union;\n this.branches.union = null;\n }\n parseUntilFinalizer() {\n return parseUntilFinalizer(new RuntimeState(this.scanner, this.ctx));\n }\n parseOperator() {\n return parseOperator(this);\n }\n parseOperand() {\n return parseOperand(this);\n }\n assertRangeUnset() {\n if (this.branches.leftBound) {\n return this.error(writeOpenRangeMessage(this.branches.leftBound.limit, this.branches.leftBound.comparator));\n }\n }\n reduceGroupOpen() {\n this.groups.push(this.branches);\n this.branches = {\n prefixes: [],\n leftBound: null,\n union: null,\n intersection: null,\n pipe: null\n };\n }\n previousOperator() {\n return (this.branches.leftBound?.comparator ??\n this.branches.prefixes[this.branches.prefixes.length - 1] ??\n (this.branches.intersection ? \"&\"\n : this.branches.union ? \"|\"\n : this.branches.pipe ? \"|>\"\n : undefined));\n }\n shiftedBy(count) {\n this.scanner.jumpForward(count);\n return this;\n }\n}\n",
170
+ "import { GenericRoot } from \"@ark/schema\";\nimport { throwParseError } from \"@ark/util\";\nimport { RuntimeState } from \"./parser/reduce/dynamic.js\";\nimport { terminatingChars } from \"./parser/shift/tokens.js\";\nimport { parseUntilFinalizer } from \"./parser/string.js\";\nexport const Generic = GenericRoot;\nexport const emptyGenericParameterMessage = \"An empty string is not a valid generic parameter name\";\nexport const parseGenericParamName = (scanner, result, ctx) => {\n scanner.shiftUntilNonWhitespace();\n const name = scanner.shiftUntilLookahead(terminatingChars);\n if (name === \"\") {\n // if we've reached the end of the string and have parsed at least one\n // param, return the valid result\n if (scanner.lookahead === \"\" && result.length)\n return result;\n return throwParseError(emptyGenericParameterMessage);\n }\n scanner.shiftUntilNonWhitespace();\n return _parseOptionalConstraint(scanner, name, result, ctx);\n};\nconst extendsToken = \"extends \";\nconst _parseOptionalConstraint = (scanner, name, result, ctx) => {\n scanner.shiftUntilNonWhitespace();\n if (scanner.unscanned.startsWith(extendsToken))\n scanner.jumpForward(extendsToken.length);\n else {\n // if we don't have a contraining token here, return now so we can\n // assume in the rest of the function body we do have a constraint\n if (scanner.lookahead === \",\")\n scanner.shift();\n result.push(name);\n return parseGenericParamName(scanner, result, ctx);\n }\n const s = parseUntilFinalizer(new RuntimeState(scanner, ctx));\n result.push([name, s.root]);\n return parseGenericParamName(scanner, result, ctx);\n};\n",
171
+ "import { Callable, throwParseError } from \"@ark/util\";\nexport class InternalFnParser extends Callable {\n constructor($) {\n const attach = {\n $: $,\n raw: $.fn\n };\n super((...signature) => {\n const returnOperatorIndex = signature.indexOf(\":\");\n const lastParamIndex = returnOperatorIndex === -1 ?\n signature.length - 1\n : returnOperatorIndex - 1;\n const paramDefs = signature.slice(0, lastParamIndex + 1);\n const paramTuple = $.parse(paramDefs).assertHasKind(\"intersection\");\n let returnType = $.intrinsic.unknown;\n if (returnOperatorIndex !== -1) {\n if (returnOperatorIndex !== signature.length - 2)\n return throwParseError(badFnReturnTypeMessage);\n returnType = $.parse(signature[returnOperatorIndex + 1]);\n }\n return (impl) => new InternalTypedFn(impl, paramTuple, returnType);\n }, { attach });\n }\n}\nexport class InternalTypedFn extends Callable {\n raw;\n params;\n returns;\n expression;\n constructor(raw, params, returns) {\n const typedName = `typed ${raw.name}`;\n const typed = {\n // assign to a key with the expected name to force it to be created that way\n [typedName]: (...args) => {\n const validatedArgs = params.assert(args);\n const returned = raw(...validatedArgs);\n return returns.assert(returned);\n }\n }[typedName];\n super(typed);\n this.raw = raw;\n this.params = params;\n this.returns = returns;\n let argsExpression = params.expression;\n if (argsExpression[0] === \"[\" &&\n argsExpression[argsExpression.length - 1] === \"]\")\n argsExpression = argsExpression.slice(1, -1);\n else if (argsExpression.endsWith(\"[]\"))\n argsExpression = `...${argsExpression}`;\n this.expression = `(${argsExpression}) => ${returns?.expression ?? \"unknown\"}`;\n }\n}\nexport const badFnReturnTypeMessage = `\":\" must be followed by exactly one return type e.g:\nfn(\"string\", \":\", \"number\")(s => s.length)`;\n",
172
+ "import { intrinsic } from \"@ark/schema\";\nimport { Callable, domainOf, throwParseError } from \"@ark/util\";\nexport class InternalMatchParser extends Callable {\n $;\n constructor($) {\n super((...args) => new InternalChainedMatchParser($)(...args), {\n bind: $\n });\n this.$ = $;\n }\n in(def) {\n return new InternalChainedMatchParser(this.$, def === undefined ? undefined : this.$.parse(def));\n }\n at(key, cases) {\n return new InternalChainedMatchParser(this.$).at(key, cases);\n }\n case(when, then) {\n return new InternalChainedMatchParser(this.$).case(when, then);\n }\n}\nexport class InternalChainedMatchParser extends Callable {\n $;\n in;\n key;\n branches = [];\n constructor($, In) {\n super(cases => this.caseEntries(Object.entries(cases).map(([k, v]) => k === \"default\" ? [k, v] : [this.$.parse(k), v])));\n this.$ = $;\n this.in = In;\n }\n at(key, cases) {\n if (this.key)\n throwParseError(doubleAtMessage);\n if (this.branches.length)\n throwParseError(chainedAtMessage);\n this.key = key;\n return cases ? this.match(cases) : this;\n }\n case(def, resolver) {\n return this.caseEntry(this.$.parse(def), resolver);\n }\n caseEntry(node, resolver) {\n const wrappableNode = this.key ? this.$.parse({ [this.key]: node }) : node;\n const branch = wrappableNode.pipe(resolver);\n this.branches.push(branch);\n return this;\n }\n match(cases) {\n return this(cases);\n }\n strings(cases) {\n return this.caseEntries(Object.entries(cases).map(([k, v]) => k === \"default\" ?\n [k, v]\n : [this.$.node(\"unit\", { unit: k }), v]));\n }\n caseEntries(entries) {\n for (let i = 0; i < entries.length; i++) {\n const [k, v] = entries[i];\n if (k === \"default\") {\n if (i !== entries.length - 1) {\n throwParseError(`default may only be specified as the last key of a switch definition`);\n }\n return this.default(v);\n }\n if (typeof v !== \"function\") {\n return throwParseError(`Value for case \"${k}\" must be a function (was ${domainOf(v)})`);\n }\n this.caseEntry(k, v);\n }\n return this;\n }\n default(defaultCase) {\n if (typeof defaultCase === \"function\")\n this.case(intrinsic.unknown, defaultCase);\n const schema = {\n branches: this.branches,\n ordered: true\n };\n if (defaultCase === \"never\" || defaultCase === \"assert\")\n schema.meta = { onFail: throwOnDefault };\n const cases = this.$.node(\"union\", schema);\n if (!this.in)\n return this.$.finalize(cases);\n let inputValidatedCases = this.in.pipe(cases);\n if (defaultCase === \"never\" || defaultCase === \"assert\") {\n inputValidatedCases = inputValidatedCases.configureReferences({\n onFail: throwOnDefault\n }, \"self\");\n }\n return this.$.finalize(inputValidatedCases);\n }\n}\nexport const throwOnDefault = errors => errors.throw();\nexport const chainedAtMessage = `A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')`;\nexport const doubleAtMessage = `At most one key matcher may be specified per expression`;\n",
173
+ "import { isArray } from \"@ark/util\";\nimport { parseInnerDefinition } from \"./definition.js\";\nexport const parseProperty = (def, ctx) => {\n if (isArray(def)) {\n if (def[1] === \"=\")\n return [ctx.$.parseOwnDefinitionFormat(def[0], ctx), \"=\", def[2]];\n if (def[1] === \"?\")\n return [ctx.$.parseOwnDefinitionFormat(def[0], ctx), \"?\"];\n }\n // string-embedded defaults/optionals are handled by the string parser\n return parseInnerDefinition(def, ctx);\n};\n// single quote use here is better for TypeScript's inlined error to avoid escapes\nexport const invalidOptionalKeyKindMessage = `Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }`;\n// single quote use here is better for TypeScript's inlined error to avoid escapes\nexport const invalidDefaultableKeyKindMessage = `Only required keys may specify default values, e.g. { value: 'number = 0' }`;\n",
174
+ "import { intrinsic, normalizeIndex } from \"@ark/schema\";\nimport { append, Backslash, isArray, isEmptyObject, printable, stringAndSymbolicEntriesOf, throwParseError } from \"@ark/util\";\nimport { invalidDefaultableKeyKindMessage, invalidOptionalKeyKindMessage, parseProperty } from \"./property.js\";\nexport const parseObjectLiteral = (def, ctx) => {\n let spread;\n const structure = {};\n // We only allow a spread operator to be used as the first key in an object\n // because to match JS behavior any keys before the spread are overwritten\n // by the values in the target object, so there'd be no useful purpose in having it\n // anywhere except for the beginning.\n const defEntries = stringAndSymbolicEntriesOf(def);\n for (const [k, v] of defEntries) {\n const parsedKey = preparseKey(k);\n if (parsedKey.kind === \"spread\") {\n if (!isEmptyObject(structure))\n return throwParseError(nonLeadingSpreadError);\n const operand = ctx.$.parseOwnDefinitionFormat(v, ctx);\n // treat object domain as empty for spreading (useful for generic constraints)\n if (operand.equals(intrinsic.object))\n continue;\n if (!operand.hasKind(\"intersection\") ||\n // still error on attempts to spread proto nodes like ...Date\n !operand.basis?.equals(intrinsic.object)) {\n return throwParseError(writeInvalidSpreadTypeMessage(operand.expression));\n }\n spread = operand.structure;\n continue;\n }\n if (parsedKey.kind === \"undeclared\") {\n if (v !== \"reject\" && v !== \"delete\" && v !== \"ignore\")\n throwParseError(writeInvalidUndeclaredBehaviorMessage(v));\n structure.undeclared = v;\n continue;\n }\n const parsedValue = parseProperty(v, ctx);\n const parsedEntryKey = parsedKey;\n if (parsedKey.kind === \"required\") {\n if (!isArray(parsedValue)) {\n appendNamedProp(structure, \"required\", {\n key: parsedKey.normalized,\n value: parsedValue\n }, ctx);\n }\n else {\n appendNamedProp(structure, \"optional\", parsedValue[1] === \"=\" ?\n {\n key: parsedKey.normalized,\n value: parsedValue[0],\n default: parsedValue[2]\n }\n : {\n key: parsedKey.normalized,\n value: parsedValue[0]\n }, ctx);\n }\n continue;\n }\n if (isArray(parsedValue)) {\n if (parsedValue[1] === \"?\")\n throwParseError(invalidOptionalKeyKindMessage);\n if (parsedValue[1] === \"=\")\n throwParseError(invalidDefaultableKeyKindMessage);\n }\n // value must be a BaseRoot at this point\n if (parsedKey.kind === \"optional\") {\n appendNamedProp(structure, \"optional\", {\n key: parsedKey.normalized,\n value: parsedValue\n }, ctx);\n continue;\n }\n // must be index at this point\n const signature = ctx.$.parseOwnDefinitionFormat(parsedEntryKey.normalized, ctx);\n const normalized = normalizeIndex(signature, parsedValue, ctx.$);\n if (normalized.index)\n structure.index = append(structure.index, normalized.index);\n if (normalized.required)\n structure.required = append(structure.required, normalized.required);\n }\n const structureNode = ctx.$.node(\"structure\", structure);\n return ctx.$.parseSchema({\n domain: \"object\",\n structure: spread?.merge(structureNode) ?? structureNode\n });\n};\nconst appendNamedProp = (structure, kind, inner, ctx) => {\n structure[kind] = append(\n // doesn't seem like this cast should be necessary\n structure[kind], ctx.$.node(kind, inner));\n};\nexport const writeInvalidUndeclaredBehaviorMessage = (actual) => `Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${printable(actual)})`;\nexport const nonLeadingSpreadError = \"Spread operator may only be used as the first key in an object\";\nexport const preparseKey = (key) => typeof key === \"symbol\" ? { kind: \"required\", normalized: key }\n : key[key.length - 1] === \"?\" ?\n key[key.length - 2] === Backslash ?\n { kind: \"required\", normalized: `${key.slice(0, -2)}?` }\n : {\n kind: \"optional\",\n normalized: key.slice(0, -1)\n }\n : key[0] === \"[\" && key[key.length - 1] === \"]\" ?\n { kind: \"index\", normalized: key.slice(1, -1) }\n : key[0] === Backslash && key[1] === \"[\" && key[key.length - 1] === \"]\" ?\n { kind: \"required\", normalized: key.slice(1) }\n : key === \"...\" ? { kind: \"spread\" }\n : key === \"+\" ? { kind: \"undeclared\" }\n : {\n kind: \"required\",\n normalized: key === \"\\\\...\" ? \"...\"\n : key === \"\\\\+\" ? \"+\"\n : key\n };\nexport const writeInvalidSpreadTypeMessage = (def) => `Spread operand must resolve to an object literal type (was ${def})`;\n",
175
+ "import { Disjoint, intersectNodesRoot, pipeNodesRoot } from \"@ark/schema\";\nimport { objectKindOrDomainOf, throwParseError } from \"@ark/util\";\nimport { shallowDefaultableMessage, shallowOptionalMessage } from \"./ast/validate.js\";\nimport { writeMissingRightOperandMessage } from \"./shift/operand/unenclosed.js\";\nexport const maybeParseTupleExpression = (def, ctx) => isIndexZeroExpression(def) ? indexZeroParsers[def[0]](def, ctx)\n : isIndexOneExpression(def) ? indexOneParsers[def[1]](def, ctx)\n : null;\nexport const parseKeyOfTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[1], ctx).keyof();\nconst parseBranchTuple = (def, ctx) => {\n if (def[2] === undefined)\n return throwParseError(writeMissingRightOperandMessage(def[1], \"\"));\n const l = ctx.$.parseOwnDefinitionFormat(def[0], ctx);\n const r = ctx.$.parseOwnDefinitionFormat(def[2], ctx);\n if (def[1] === \"|\")\n return ctx.$.node(\"union\", { branches: [l, r] });\n const result = def[1] === \"&\" ?\n intersectNodesRoot(l, r, ctx.$)\n : pipeNodesRoot(l, r, ctx.$);\n if (result instanceof Disjoint)\n return result.throw();\n return result;\n};\nconst parseArrayTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).array();\nexport const parseMorphTuple = (def, ctx) => {\n if (typeof def[2] !== \"function\") {\n return throwParseError(writeMalformedFunctionalExpressionMessage(\"=>\", def[2]));\n }\n return ctx.$.parseOwnDefinitionFormat(def[0], ctx).pipe(def[2]);\n};\nexport const writeMalformedFunctionalExpressionMessage = (operator, value) => `${operator === \":\" ? \"Narrow\" : \"Morph\"} expression requires a function following '${operator}' (was ${typeof value})`;\nexport const parseNarrowTuple = (def, ctx) => {\n if (typeof def[2] !== \"function\") {\n return throwParseError(writeMalformedFunctionalExpressionMessage(\":\", def[2]));\n }\n return ctx.$.parseOwnDefinitionFormat(def[0], ctx).constrain(\"predicate\", def[2]);\n};\nconst parseMetaTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).configure(def[2], def[3]);\nconst defineIndexOneParsers = (parsers) => parsers;\nconst postfixParsers = defineIndexOneParsers({\n \"[]\": parseArrayTuple,\n \"?\": () => throwParseError(shallowOptionalMessage)\n});\nconst infixParsers = defineIndexOneParsers({\n \"|\": parseBranchTuple,\n \"&\": parseBranchTuple,\n \":\": parseNarrowTuple,\n \"=>\": parseMorphTuple,\n \"|>\": parseBranchTuple,\n \"@\": parseMetaTuple,\n // since object and tuple literals parse there via `parseProperty`,\n // they must be shallow if parsed directly as a tuple expression\n \"=\": () => throwParseError(shallowDefaultableMessage)\n});\nconst indexOneParsers = { ...postfixParsers, ...infixParsers };\nconst isIndexOneExpression = (def) => indexOneParsers[def[1]] !== undefined;\nconst defineIndexZeroParsers = (parsers) => parsers;\nconst indexZeroParsers = defineIndexZeroParsers({\n keyof: parseKeyOfTuple,\n instanceof: (def, ctx) => {\n if (typeof def[1] !== \"function\") {\n return throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(def[1])));\n }\n const branches = def\n .slice(1)\n .map(ctor => typeof ctor === \"function\" ?\n ctx.$.node(\"proto\", { proto: ctor })\n : throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(ctor))));\n return branches.length === 1 ?\n branches[0]\n : ctx.$.node(\"union\", { branches });\n },\n \"===\": (def, ctx) => ctx.$.units(def.slice(1))\n});\nconst isIndexZeroExpression = (def) => indexZeroParsers[def[0]] !== undefined;\nexport const writeInvalidConstructorMessage = (actual) => `Expected a constructor following 'instanceof' operator (was ${actual})`;\n",
176
+ "import { $ark, makeRootAndArrayPropertiesMutable, postfixAfterOptionalOrDefaultableMessage } from \"@ark/schema\";\nimport { append, isArray, isEmptyObject, throwParseError } from \"@ark/util\";\nimport { parseProperty } from \"./property.js\";\nexport const parseTupleLiteral = (def, ctx) => {\n let sequences = [{}];\n let i = 0;\n while (i < def.length) {\n let spread = false;\n if (def[i] === \"...\" && i < def.length - 1) {\n spread = true;\n i++;\n }\n const parsedProperty = parseProperty(def[i], ctx);\n const [valueNode, operator, possibleDefaultValue] = !isArray(parsedProperty) ? [parsedProperty] : parsedProperty;\n i++;\n if (spread) {\n if (!valueNode.extends($ark.intrinsic.Array))\n return throwParseError(writeNonArraySpreadMessage(valueNode.expression));\n // a spread must be distributed over branches e.g.:\n // def: [string, ...(number[] | [true, false])]\n // nodes: [string, ...number[]] | [string, true, false]\n sequences = sequences.flatMap(base => \n // since appendElement mutates base, we have to shallow-ish clone it for each branch\n valueNode.distribute(branch => appendSpreadBranch(makeRootAndArrayPropertiesMutable(base), branch)));\n }\n else {\n sequences = sequences.map(base => {\n if (operator === \"?\")\n return appendOptionalElement(base, valueNode);\n if (operator === \"=\")\n return appendDefaultableElement(base, valueNode, possibleDefaultValue);\n return appendRequiredElement(base, valueNode);\n });\n }\n }\n return ctx.$.parseSchema(sequences.map(sequence => isEmptyObject(sequence) ?\n {\n proto: Array,\n exactLength: 0\n }\n : {\n proto: Array,\n sequence\n }));\n};\nconst appendRequiredElement = (base, element) => {\n if (base.defaultables || base.optionals) {\n return throwParseError(base.variadic ?\n // e.g. [boolean = true, ...string[], number]\n postfixAfterOptionalOrDefaultableMessage\n // e.g. [string?, number]\n : requiredPostOptionalMessage);\n }\n if (base.variadic) {\n // e.g. [...string[], number]\n base.postfix = append(base.postfix, element);\n }\n else {\n // e.g. [string, number]\n base.prefix = append(base.prefix, element);\n }\n return base;\n};\nconst appendOptionalElement = (base, element) => {\n if (base.variadic)\n // e.g. [...string[], number?]\n return throwParseError(optionalOrDefaultableAfterVariadicMessage);\n // e.g. [string, number?]\n base.optionals = append(base.optionals, element);\n return base;\n};\nconst appendDefaultableElement = (base, element, value) => {\n if (base.variadic)\n // e.g. [...string[], number = 0]\n return throwParseError(optionalOrDefaultableAfterVariadicMessage);\n if (base.optionals)\n // e.g. [string?, number = 0]\n return throwParseError(defaultablePostOptionalMessage);\n // value's assignability to element will be checked when the\n // sequence is instantiated by @ark/schema\n // e.g. [string, number = 0]\n base.defaultables = append(base.defaultables, [[element, value]]);\n return base;\n};\nconst appendVariadicElement = (base, element) => {\n // e.g. [...string[], number, ...string[]]\n if (base.postfix)\n throwParseError(multipleVariadicMesage);\n if (base.variadic) {\n if (!base.variadic.equals(element)) {\n // e.g. [...string[], ...number[]]\n throwParseError(multipleVariadicMesage);\n }\n // e.g. [...string[], ...string[]]\n // do nothing, second spread doesn't change the type\n }\n else {\n // e.g. [string, ...number[]]\n base.variadic = element.internal;\n }\n return base;\n};\nconst appendSpreadBranch = (base, branch) => {\n const spread = branch.select({ method: \"find\", kind: \"sequence\" });\n if (!spread) {\n // the only array with no sequence reference is unknown[]\n return appendVariadicElement(base, $ark.intrinsic.unknown);\n }\n if (spread.prefix)\n for (const node of spread.prefix)\n appendRequiredElement(base, node);\n if (spread.optionals)\n for (const node of spread.optionals)\n appendOptionalElement(base, node);\n if (spread.variadic)\n appendVariadicElement(base, spread.variadic);\n if (spread.postfix)\n for (const node of spread.postfix)\n appendRequiredElement(base, node);\n return base;\n};\nexport const writeNonArraySpreadMessage = (operand) => `Spread element must be an array (was ${operand})`;\nexport const multipleVariadicMesage = \"A tuple may have at most one variadic element\";\nexport const requiredPostOptionalMessage = \"A required element may not follow an optional element\";\nexport const optionalOrDefaultableAfterVariadicMessage = \"An optional element may not follow a variadic element\";\nexport const spreadOptionalMessage = \"A spread element cannot be optional\";\nexport const spreadDefaultableMessage = \"A spread element cannot have a default\";\nexport const defaultablePostOptionalMessage = \"A defaultable element may not follow an optional element without a default\";\n",
177
+ "import { hasArkKind } from \"@ark/schema\";\nimport { domainOf, hasDomain, isThunk, objectKindOf, printable, throwParseError, uncapitalize } from \"@ark/util\";\nimport { parseObjectLiteral } from \"./objectLiteral.js\";\nimport { parseString } from \"./string.js\";\nimport { maybeParseTupleExpression } from \"./tupleExpressions.js\";\nimport { parseTupleLiteral } from \"./tupleLiteral.js\";\nconst parseCache = {};\nexport const parseInnerDefinition = (def, ctx) => {\n if (typeof def === \"string\") {\n if (ctx.args && Object.keys(ctx.args).some(k => def.includes(k))) {\n // we can only rely on the cache if there are no contextual\n // resolutions like \"this\" or generic args\n return parseString(def, ctx);\n }\n const scopeCache = (parseCache[ctx.$.name] ??= {});\n return (scopeCache[def] ??= parseString(def, ctx));\n }\n return hasDomain(def, \"object\") ?\n parseObject(def, ctx)\n : throwParseError(writeBadDefinitionTypeMessage(domainOf(def)));\n};\nexport const parseObject = (def, ctx) => {\n const objectKind = objectKindOf(def);\n switch (objectKind) {\n case undefined:\n if (hasArkKind(def, \"root\"))\n return def;\n if (\"~standard\" in def)\n return parseStandardSchema(def, ctx);\n return parseObjectLiteral(def, ctx);\n case \"Array\":\n return parseTuple(def, ctx);\n case \"RegExp\":\n return ctx.$.node(\"intersection\", {\n domain: \"string\",\n pattern: def\n }, { prereduced: true });\n case \"Function\": {\n const resolvedDef = isThunk(def) ? def() : def;\n if (hasArkKind(resolvedDef, \"root\"))\n return resolvedDef;\n return throwParseError(writeBadDefinitionTypeMessage(\"Function\"));\n }\n default:\n return throwParseError(writeBadDefinitionTypeMessage(objectKind ?? printable(def)));\n }\n};\nconst parseStandardSchema = (def, ctx) => ctx.$.intrinsic.unknown.pipe((v, ctx) => {\n const result = def[\"~standard\"].validate(v);\n if (!result.issues)\n return result.value;\n for (const { message, path } of result.issues) {\n if (path) {\n if (path.length) {\n ctx.error({\n problem: uncapitalize(message),\n relativePath: path.map(k => (typeof k === \"object\" ? k.key : k))\n });\n }\n else {\n ctx.error({\n message\n });\n }\n }\n else {\n ctx.error({\n message\n });\n }\n }\n});\nexport const parseTuple = (def, ctx) => maybeParseTupleExpression(def, ctx) ?? parseTupleLiteral(def, ctx);\nexport const writeBadDefinitionTypeMessage = (actual) => `Type definitions must be strings or objects (was ${actual})`;\n",
178
+ "import { ArkErrors, BaseRoot, GenericRoot } from \"@ark/schema\";\nimport { Callable, Hkt } from \"@ark/util\";\nexport class InternalTypeParser extends Callable {\n constructor($) {\n const attach = Object.assign({\n errors: ArkErrors,\n hkt: Hkt,\n $: $,\n raw: $.parse,\n module: $.constructor.module,\n scope: $.constructor.scope,\n declare: $.declare,\n define: $.define,\n match: $.match,\n generic: $.generic,\n schema: $.schema,\n // this won't be defined during bootstrapping, but externally always will be\n keywords: $.ambient,\n unit: $.unit,\n enumerated: $.enumerated,\n instanceOf: $.instanceOf,\n valueOf: $.valueOf,\n or: $.or,\n and: $.and,\n merge: $.merge,\n pipe: $.pipe,\n fn: $.fn\n }, \n // also won't be defined during bootstrapping\n $.ambientAttachments);\n super((...args) => {\n if (args.length === 1) {\n // treat as a simple definition\n return $.parse(args[0]);\n }\n if (args.length === 2 &&\n typeof args[0] === \"string\" &&\n args[0][0] === \"<\" &&\n args[0][args[0].length - 1] === \">\") {\n // if there are exactly two args, the first of which looks like <${string}>,\n // treat as a generic\n const paramString = args[0].slice(1, -1);\n const params = $.parseGenericParams(paramString, {});\n return new GenericRoot(params, args[1], $, $, null);\n }\n // otherwise, treat as a tuple expression. technically, this also allows\n // non-expression tuple definitions to be parsed, but it's not a supported\n // part of the API as specified by the associated types\n return $.parse(args);\n }, {\n attach\n });\n }\n}\nexport const Type = BaseRoot;\n",
179
+ "import { $ark, BaseScope, hasArkKind, parseGeneric } from \"@ark/schema\";\nimport { Scanner, enumValues, flatMorph, isArray, isThunk, throwParseError } from \"@ark/util\";\nimport { InternalFnParser } from \"./fn.js\";\nimport { parseGenericParamName } from \"./generic.js\";\nimport { InternalMatchParser } from \"./match.js\";\nimport { shallowDefaultableMessage, shallowOptionalMessage } from \"./parser/ast/validate.js\";\nimport { parseInnerDefinition } from \"./parser/definition.js\";\nimport { InternalTypeParser } from \"./type.js\";\nexport const $arkTypeRegistry = $ark;\nexport class InternalScope extends BaseScope {\n get ambientAttachments() {\n if (!$arkTypeRegistry.typeAttachments)\n return;\n return this.cacheGetter(\"ambientAttachments\", flatMorph($arkTypeRegistry.typeAttachments, (k, v) => [\n k,\n this.bindReference(v)\n ]));\n }\n preparseOwnAliasEntry(alias, def) {\n const firstParamIndex = alias.indexOf(\"<\");\n if (firstParamIndex === -1) {\n if (hasArkKind(def, \"module\") || hasArkKind(def, \"generic\"))\n return [alias, def];\n const qualifiedName = this.name === \"ark\" ? alias\n : alias === \"root\" ? this.name\n : `${this.name}.${alias}`;\n const config = this.resolvedConfig.keywords?.[qualifiedName];\n if (config)\n def = [def, \"@\", config];\n return [alias, def];\n }\n if (alias[alias.length - 1] !== \">\") {\n throwParseError(`'>' must be the last character of a generic declaration in a scope`);\n }\n const name = alias.slice(0, firstParamIndex);\n const paramString = alias.slice(firstParamIndex + 1, -1);\n return [\n name,\n // use a thunk definition for the generic so that we can parse\n // constraints within the current scope\n () => {\n const params = this.parseGenericParams(paramString, { alias: name });\n const generic = parseGeneric(params, def, this);\n return generic;\n }\n ];\n }\n parseGenericParams(def, opts) {\n return parseGenericParamName(new Scanner(def), [], this.createParseContext({\n ...opts,\n def,\n prefix: \"generic\"\n }));\n }\n normalizeRootScopeValue(resolution) {\n if (isThunk(resolution) && !hasArkKind(resolution, \"generic\"))\n return resolution();\n return resolution;\n }\n preparseOwnDefinitionFormat(def, opts) {\n return {\n ...opts,\n def,\n prefix: opts.alias ?? \"type\"\n };\n }\n parseOwnDefinitionFormat(def, ctx) {\n const isScopeAlias = ctx.alias && ctx.alias in this.aliases;\n // if the definition being parsed is not a scope alias and is not a\n // generic instantiation (i.e. opts don't include args), add `this` as a resolution.\n // if we're parsing a nested string, ctx.args will have already been set\n if (!isScopeAlias && !ctx.args)\n ctx.args = { this: ctx.id };\n const result = parseInnerDefinition(def, ctx);\n if (isArray(result)) {\n if (result[1] === \"=\")\n return throwParseError(shallowDefaultableMessage);\n if (result[1] === \"?\")\n return throwParseError(shallowOptionalMessage);\n }\n return result;\n }\n unit = value => this.units([value]);\n valueOf = tsEnum => this.units(enumValues(tsEnum));\n enumerated = (...values) => this.units(values);\n instanceOf = ctor => this.node(\"proto\", { proto: ctor }, { prereduced: true });\n or = (...defs) => this.schema(defs.map(def => this.parse(def)));\n and = (...defs) => defs.reduce((node, def) => node.and(this.parse(def)), this.intrinsic.unknown);\n merge = (...defs) => defs.reduce((node, def) => node.merge(this.parse(def)), this.intrinsic.object);\n pipe = (...morphs) => this.intrinsic.unknown.pipe(...morphs);\n fn = new InternalFnParser(this);\n match = new InternalMatchParser(this);\n declare = () => ({\n type: this.type\n });\n define(def) {\n return def;\n }\n type = new InternalTypeParser(this);\n static scope = ((def, config = {}) => new InternalScope(def, config));\n static module = ((def, config = {}) => this.scope(def, config).export());\n}\nexport const scope = Object.assign(InternalScope.scope, {\n define: (def) => def\n});\nexport const Scope = InternalScope;\n",
180
+ "import { genericNode, intrinsic } from \"@ark/schema\";\nimport { Hkt } from \"@ark/util\";\nimport { Scope } from \"../scope.js\";\nclass MergeHkt extends Hkt {\n description = 'merge an object\\'s properties onto another like `Merge(User, { isAdmin: \"true\" })`';\n}\nconst Merge = genericNode([\"base\", intrinsic.object], [\"props\", intrinsic.object])(args => args.base.merge(args.props), MergeHkt);\nexport const arkBuiltins = Scope.module({\n Key: intrinsic.key,\n Merge\n});\n",
181
+ "import { genericNode, intrinsic, rootSchema } from \"@ark/schema\";\nimport { Hkt, liftArray } from \"@ark/util\";\nimport { Scope } from \"../scope.js\";\nclass liftFromHkt extends Hkt {\n}\nconst liftFrom = genericNode(\"element\")(args => {\n const nonArrayElement = args.element.exclude(intrinsic.Array);\n const lifted = nonArrayElement.array();\n return nonArrayElement\n .rawOr(lifted)\n .pipe(liftArray)\n .distribute(branch => branch.assertHasKind(\"morph\").declareOut(lifted), rootSchema);\n}, liftFromHkt);\nexport const arkArray = Scope.module({\n root: intrinsic.Array,\n readonly: \"root\",\n index: intrinsic.nonNegativeIntegerString,\n liftFrom\n}, {\n name: \"Array\"\n});\n",
182
+ "import { rootSchema } from \"@ark/schema\";\nimport { registry } from \"@ark/util\";\nimport { Scope } from \"../scope.js\";\nconst value = rootSchema([\"string\", registry.FileConstructor]);\nconst parsedFormDataValue = value.rawOr(value.array());\nconst parsed = rootSchema({\n meta: \"an object representing parsed form data\",\n domain: \"object\",\n index: {\n signature: \"string\",\n value: parsedFormDataValue\n }\n});\nexport const arkFormData = Scope.module({\n root: [\"instanceof\", FormData],\n value,\n parsed,\n parse: rootSchema({\n in: FormData,\n morphs: (data) => {\n const result = {};\n for (const [k, v] of data) {\n if (k in result) {\n const existing = result[k];\n if (typeof existing === \"string\" ||\n existing instanceof registry.FileConstructor)\n result[k] = [existing, v];\n else\n existing.push(v);\n }\n else\n result[k] = v;\n }\n return result;\n },\n declaredOut: parsed\n })\n}, {\n name: \"FormData\"\n});\n",
183
+ "import { Scope } from \"../scope.js\";\nexport const TypedArray = Scope.module({\n Int8: [\"instanceof\", Int8Array],\n Uint8: [\"instanceof\", Uint8Array],\n Uint8Clamped: [\"instanceof\", Uint8ClampedArray],\n Int16: [\"instanceof\", Int16Array],\n Uint16: [\"instanceof\", Uint16Array],\n Int32: [\"instanceof\", Int32Array],\n Uint32: [\"instanceof\", Uint32Array],\n Float32: [\"instanceof\", Float32Array],\n Float64: [\"instanceof\", Float64Array],\n BigInt64: [\"instanceof\", BigInt64Array],\n BigUint64: [\"instanceof\", BigUint64Array]\n}, {\n name: \"TypedArray\"\n});\n",
184
+ "import { ecmascriptConstructors, flatMorph, platformConstructors } from \"@ark/util\";\nimport { Scope } from \"../scope.js\";\nimport { arkArray } from \"./Array.js\";\nimport { arkFormData } from \"./FormData.js\";\nimport { TypedArray } from \"./TypedArray.js\";\nconst omittedPrototypes = {\n Boolean: 1,\n Number: 1,\n String: 1\n};\nexport const arkPrototypes = Scope.module({\n ...flatMorph({ ...ecmascriptConstructors, ...platformConstructors }, (k, v) => (k in omittedPrototypes ? [] : [k, [\"instanceof\", v]])),\n Array: arkArray,\n TypedArray,\n FormData: arkFormData\n});\n",
185
+ "import { intrinsic, rootSchema } from \"@ark/schema\";\nimport { Scope } from \"../scope.js\";\n/**\n * As per the ECMA-262 specification:\n * A time value supports a slightly smaller range of -8,640,000,000,000,000 to 8,640,000,000,000,000 milliseconds.\n *\n * @see https://262.ecma-international.org/15.0/index.html#sec-time-values-and-time-range\n */\nexport const epoch = rootSchema({\n domain: {\n domain: \"number\",\n meta: \"a number representing a Unix timestamp\"\n },\n divisor: {\n rule: 1,\n meta: `an integer representing a Unix timestamp`\n },\n min: {\n rule: -8640000000000000,\n meta: `a Unix timestamp after -8640000000000000`\n },\n max: {\n rule: 8640000000000000,\n meta: \"a Unix timestamp before 8640000000000000\"\n },\n meta: \"an integer representing a safe Unix timestamp\"\n});\nexport const integer = rootSchema({\n domain: \"number\",\n divisor: 1\n});\nexport const number = Scope.module({\n root: intrinsic.number,\n integer,\n epoch,\n safe: rootSchema({\n domain: {\n domain: \"number\",\n numberAllowsNaN: false\n },\n min: Number.MIN_SAFE_INTEGER,\n max: Number.MAX_SAFE_INTEGER\n }),\n NaN: [\"===\", Number.NaN],\n Infinity: [\"===\", Number.POSITIVE_INFINITY],\n NegativeInfinity: [\"===\", Number.NEGATIVE_INFINITY]\n}, {\n name: \"number\"\n});\n",
186
+ "import { ArkErrors, intrinsic, node, rootSchema } from \"@ark/schema\";\nimport { flatMorph, numericStringMatcher, wellFormedIntegerMatcher } from \"@ark/util\";\nimport { Scope } from \"../scope.js\";\nimport { number } from \"./number.js\";\n// non-trivial expressions should have an explanation or attribution\nexport const regexStringNode = (regex, description, jsonSchemaFormat) => {\n const schema = {\n domain: \"string\",\n pattern: {\n rule: regex.source,\n flags: regex.flags,\n meta: description\n }\n };\n if (jsonSchemaFormat)\n schema.meta = { format: jsonSchemaFormat };\n return node(\"intersection\", schema);\n};\nconst stringIntegerRoot = regexStringNode(wellFormedIntegerMatcher, \"a well-formed integer string\");\nexport const stringInteger = Scope.module({\n root: stringIntegerRoot,\n parse: rootSchema({\n in: stringIntegerRoot,\n morphs: (s, ctx) => {\n const parsed = Number.parseInt(s);\n return Number.isSafeInteger(parsed) ? parsed : (ctx.error(\"an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER\"));\n },\n declaredOut: intrinsic.integer\n })\n}, {\n name: \"string.integer\"\n});\nconst hex = regexStringNode(/^[\\dA-Fa-f]+$/, \"hex characters only\");\nconst base64 = Scope.module({\n root: regexStringNode(/^(?:[\\d+/A-Za-z]{4})*(?:[\\d+/A-Za-z]{2}==|[\\d+/A-Za-z]{3}=)?$/, \"base64-encoded\"),\n url: regexStringNode(/^(?:[\\w-]{4})*(?:[\\w-]{2}(?:==|%3D%3D)?|[\\w-]{3}(?:=|%3D)?)?$/, \"base64url-encoded\")\n}, {\n name: \"string.base64\"\n});\nconst preformattedCapitalize = regexStringNode(/^[A-Z].*$/, \"capitalized\");\nexport const capitalize = Scope.module({\n root: rootSchema({\n in: \"string\",\n morphs: (s) => s.charAt(0).toUpperCase() + s.slice(1),\n declaredOut: preformattedCapitalize\n }),\n preformatted: preformattedCapitalize\n}, {\n name: \"string.capitalize\"\n});\n// https://github.com/validatorjs/validator.js/blob/master/src/lib/isLuhnNumber.js\nexport const isLuhnValid = (creditCardInput) => {\n const sanitized = creditCardInput.replace(/[ -]+/g, \"\");\n let sum = 0;\n let digit;\n let tmpNum;\n let shouldDouble = false;\n for (let i = sanitized.length - 1; i >= 0; i--) {\n digit = sanitized.substring(i, i + 1);\n tmpNum = Number.parseInt(digit, 10);\n if (shouldDouble) {\n tmpNum *= 2;\n sum += tmpNum >= 10 ? (tmpNum % 10) + 1 : tmpNum;\n }\n else\n sum += tmpNum;\n shouldDouble = !shouldDouble;\n }\n return !!(sum % 10 === 0 ? sanitized : false);\n};\n// https://github.com/validatorjs/validator.js/blob/master/src/lib/isCreditCard.js\nconst creditCardMatcher = /^(?:4\\d{12}(?:\\d{3,6})?|5[1-5]\\d{14}|(222[1-9]|22[3-9]\\d|2[3-6]\\d{2}|27[01]\\d|2720)\\d{12}|6(?:011|5\\d\\d)\\d{12,15}|3[47]\\d{13}|3(?:0[0-5]|[68]\\d)\\d{11}|(?:2131|1800|35\\d{3})\\d{11}|6[27]\\d{14}|^(81\\d{14,17}))$/;\nexport const creditCard = rootSchema({\n domain: \"string\",\n pattern: {\n meta: \"a credit card number\",\n rule: creditCardMatcher.source\n },\n predicate: {\n meta: \"a credit card number\",\n predicate: isLuhnValid\n }\n});\nconst dayDelimiterMatcher = /^[./-]$/;\n// ISO 8601 date/time modernized from https://github.com/validatorjs/validator.js/blob/master/src/lib/isISO8601.js\n// Based on https://tc39.es/ecma262/#sec-date-time-string-format, the T\n// delimiter for date/time is mandatory. Regex from validator.js strict matcher:\nexport const iso8601Matcher = /^([+-]?\\d{4}(?!\\d{2}\\b))((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?|W([0-4]\\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6])))(T((([01]\\d|2[0-3])((:?)[0-5]\\d)?|24:?00)([,.]\\d+(?!:))?)?(\\17[0-5]\\d([,.]\\d+)?)?([Zz]|([+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)?)?$/;\nconst isValidDateInstance = (date) => !Number.isNaN(+date);\nconst writeFormattedExpected = (format) => `a ${format}-formatted date`;\nexport const tryParseDatePattern = (data, opts) => {\n if (!opts?.format) {\n const result = new Date(data);\n return isValidDateInstance(result) ? result : \"a valid date\";\n }\n if (opts.format === \"iso\") {\n return iso8601Matcher.test(data) ?\n new Date(data)\n : writeFormattedExpected(\"iso\");\n }\n const dataParts = data.split(dayDelimiterMatcher);\n // will be the first delimiter matched, if there is one\n const delimiter = data[dataParts[0].length];\n const formatParts = delimiter ? opts.format.split(delimiter) : [opts.format];\n if (dataParts.length !== formatParts.length)\n return writeFormattedExpected(opts.format);\n const parsedParts = {};\n for (let i = 0; i < formatParts.length; i++) {\n if (dataParts[i].length !== formatParts[i].length &&\n // if format is \"m\" or \"d\", data is allowed to be 1 or 2 characters\n !(formatParts[i].length === 1 && dataParts[i].length === 2))\n return writeFormattedExpected(opts.format);\n parsedParts[formatParts[i][0]] = dataParts[i];\n }\n const date = new Date(`${parsedParts.m}/${parsedParts.d}/${parsedParts.y}`);\n if (`${date.getDate()}` === parsedParts.d)\n return date;\n return writeFormattedExpected(opts.format);\n};\nconst isParsableDate = (s) => !Number.isNaN(new Date(s).valueOf());\nconst parsableDate = rootSchema({\n domain: \"string\",\n predicate: {\n meta: \"a parsable date\",\n predicate: isParsableDate\n }\n}).assertHasKind(\"intersection\");\nconst epochRoot = stringInteger.root.internal\n .narrow((s, ctx) => {\n // this is safe since it has already\n // been validated as an integer string\n const n = Number.parseInt(s);\n const out = number.epoch(n);\n if (out instanceof ArkErrors) {\n ctx.errors.merge(out);\n return false;\n }\n return true;\n})\n .configure({\n description: \"an integer string representing a safe Unix timestamp\"\n}, \"self\")\n .assertHasKind(\"intersection\");\nconst epoch = Scope.module({\n root: epochRoot,\n parse: rootSchema({\n in: epochRoot,\n morphs: (s) => new Date(s),\n declaredOut: intrinsic.Date\n })\n}, {\n name: \"string.date.epoch\"\n});\nconst isoRoot = regexStringNode(iso8601Matcher, \"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date\").internal.assertHasKind(\"intersection\");\nconst iso = Scope.module({\n root: isoRoot,\n parse: rootSchema({\n in: isoRoot,\n morphs: (s) => new Date(s),\n declaredOut: intrinsic.Date\n })\n}, {\n name: \"string.date.iso\"\n});\nexport const stringDate = Scope.module({\n root: parsableDate,\n parse: rootSchema({\n declaredIn: parsableDate,\n in: \"string\",\n morphs: (s, ctx) => {\n const date = new Date(s);\n if (Number.isNaN(date.valueOf()))\n return ctx.error(\"a parsable date\");\n return date;\n },\n declaredOut: intrinsic.Date\n }),\n iso,\n epoch\n}, {\n name: \"string.date\"\n});\nconst email = regexStringNode(\n// considered https://colinhacks.com/essays/reasonable-email-regex but it includes a lookahead\n// which breaks some integrations e.g. fast-check\n// regex based on:\n// https://www.regular-expressions.info/email.html\n/^[\\w%+.-]+@[\\d.A-Za-z-]+\\.[A-Za-z]{2,}$/, \"an email address\", \"email\");\n// based on https://github.com/validatorjs/validator.js/blob/master/src/lib/isIP.js\nconst ipv4Segment = \"(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\";\nconst ipv4Address = `(${ipv4Segment}[.]){3}${ipv4Segment}`;\nconst ipv4Matcher = new RegExp(`^${ipv4Address}$`);\nconst ipv6Segment = \"(?:[0-9a-fA-F]{1,4})\";\nconst ipv6Matcher = new RegExp(\"^(\" +\n `(?:${ipv6Segment}:){7}(?:${ipv6Segment}|:)|` +\n `(?:${ipv6Segment}:){6}(?:${ipv4Address}|:${ipv6Segment}|:)|` +\n `(?:${ipv6Segment}:){5}(?::${ipv4Address}|(:${ipv6Segment}){1,2}|:)|` +\n `(?:${ipv6Segment}:){4}(?:(:${ipv6Segment}){0,1}:${ipv4Address}|(:${ipv6Segment}){1,3}|:)|` +\n `(?:${ipv6Segment}:){3}(?:(:${ipv6Segment}){0,2}:${ipv4Address}|(:${ipv6Segment}){1,4}|:)|` +\n `(?:${ipv6Segment}:){2}(?:(:${ipv6Segment}){0,3}:${ipv4Address}|(:${ipv6Segment}){1,5}|:)|` +\n `(?:${ipv6Segment}:){1}(?:(:${ipv6Segment}){0,4}:${ipv4Address}|(:${ipv6Segment}){1,6}|:)|` +\n `(?::((?::${ipv6Segment}){0,5}:${ipv4Address}|(?::${ipv6Segment}){1,7}|:))` +\n \")(%[0-9a-zA-Z.]{1,})?$\");\nexport const ip = Scope.module({\n root: [\"v4 | v6\", \"@\", \"an IP address\"],\n v4: regexStringNode(ipv4Matcher, \"an IPv4 address\", \"ipv4\"),\n v6: regexStringNode(ipv6Matcher, \"an IPv6 address\", \"ipv6\")\n}, {\n name: \"string.ip\"\n});\nconst jsonStringDescription = \"a JSON string\";\nexport const writeJsonSyntaxErrorProblem = (error) => {\n if (!(error instanceof SyntaxError))\n throw error;\n return `must be ${jsonStringDescription} (${error})`;\n};\nconst jsonRoot = rootSchema({\n meta: jsonStringDescription,\n domain: \"string\",\n predicate: {\n meta: jsonStringDescription,\n predicate: (s, ctx) => {\n try {\n JSON.parse(s);\n return true;\n }\n catch (e) {\n return ctx.reject({\n code: \"predicate\",\n expected: jsonStringDescription,\n problem: writeJsonSyntaxErrorProblem(e)\n });\n }\n }\n }\n});\nconst parseJson = (s, ctx) => {\n if (s.length === 0) {\n return ctx.error({\n code: \"predicate\",\n expected: jsonStringDescription,\n actual: \"empty\"\n });\n }\n try {\n return JSON.parse(s);\n }\n catch (e) {\n return ctx.error({\n code: \"predicate\",\n expected: jsonStringDescription,\n problem: writeJsonSyntaxErrorProblem(e)\n });\n }\n};\nexport const json = Scope.module({\n root: jsonRoot,\n parse: rootSchema({\n meta: \"safe JSON string parser\",\n in: \"string\",\n morphs: parseJson,\n declaredOut: intrinsic.jsonObject\n })\n}, {\n name: \"string.json\"\n});\nconst preformattedLower = regexStringNode(/^[a-z]*$/, \"only lowercase letters\");\nconst lower = Scope.module({\n root: rootSchema({\n in: \"string\",\n morphs: (s) => s.toLowerCase(),\n declaredOut: preformattedLower\n }),\n preformatted: preformattedLower\n}, {\n name: \"string.lower\"\n});\nexport const normalizedForms = [\"NFC\", \"NFD\", \"NFKC\", \"NFKD\"];\nconst preformattedNodes = flatMorph(normalizedForms, (i, form) => [\n form,\n rootSchema({\n domain: \"string\",\n predicate: (s) => s.normalize(form) === s,\n meta: `${form}-normalized unicode`\n })\n]);\nconst normalizeNodes = flatMorph(normalizedForms, (i, form) => [\n form,\n rootSchema({\n in: \"string\",\n morphs: (s) => s.normalize(form),\n declaredOut: preformattedNodes[form]\n })\n]);\nexport const NFC = Scope.module({\n root: normalizeNodes.NFC,\n preformatted: preformattedNodes.NFC\n}, {\n name: \"string.normalize.NFC\"\n});\nexport const NFD = Scope.module({\n root: normalizeNodes.NFD,\n preformatted: preformattedNodes.NFD\n}, {\n name: \"string.normalize.NFD\"\n});\nexport const NFKC = Scope.module({\n root: normalizeNodes.NFKC,\n preformatted: preformattedNodes.NFKC\n}, {\n name: \"string.normalize.NFKC\"\n});\nexport const NFKD = Scope.module({\n root: normalizeNodes.NFKD,\n preformatted: preformattedNodes.NFKD\n}, {\n name: \"string.normalize.NFKD\"\n});\nexport const normalize = Scope.module({\n root: \"NFC\",\n NFC,\n NFD,\n NFKC,\n NFKD\n}, {\n name: \"string.normalize\"\n});\nconst numericRoot = regexStringNode(numericStringMatcher, \"a well-formed numeric string\");\nexport const stringNumeric = Scope.module({\n root: numericRoot,\n parse: rootSchema({\n in: numericRoot,\n morphs: (s) => Number.parseFloat(s),\n declaredOut: intrinsic.number\n })\n}, {\n name: \"string.numeric\"\n});\nconst regexPatternDescription = \"a regex pattern\";\nconst regex = rootSchema({\n domain: \"string\",\n predicate: {\n meta: regexPatternDescription,\n predicate: (s, ctx) => {\n try {\n new RegExp(s);\n return true;\n }\n catch (e) {\n return ctx.reject({\n code: \"predicate\",\n expected: regexPatternDescription,\n problem: String(e)\n });\n }\n }\n },\n meta: { format: \"regex\" }\n});\nconst semverMatcher = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[A-Za-z-][\\dA-Za-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[A-Za-z-][\\dA-Za-z-]*))*))?(?:\\+([\\dA-Za-z-]+(?:\\.[\\dA-Za-z-]+)*))?$/;\nconst semver = regexStringNode(semverMatcher, \"a semantic version (see https://semver.org/)\");\nconst preformattedTrim = regexStringNode(\n// no leading or trailing whitespace\n/^\\S.*\\S$|^\\S?$/, \"trimmed\");\nconst trim = Scope.module({\n root: rootSchema({\n in: \"string\",\n morphs: (s) => s.trim(),\n declaredOut: preformattedTrim\n }),\n preformatted: preformattedTrim\n}, {\n name: \"string.trim\"\n});\nconst preformattedUpper = regexStringNode(/^[A-Z]*$/, \"only uppercase letters\");\nconst upper = Scope.module({\n root: rootSchema({\n in: \"string\",\n morphs: (s) => s.toUpperCase(),\n declaredOut: preformattedUpper\n }),\n preformatted: preformattedUpper\n}, {\n name: \"string.upper\"\n});\nconst isParsableUrl = (s) => URL.canParse(s);\nconst urlRoot = rootSchema({\n domain: \"string\",\n predicate: {\n meta: \"a URL string\",\n predicate: isParsableUrl\n },\n // URL.canParse allows a subset of the RFC-3986 URI spec\n // since there is no other serializable validation, best include a format\n meta: { format: \"uri\" }\n});\nexport const url = Scope.module({\n root: urlRoot,\n parse: rootSchema({\n declaredIn: urlRoot,\n in: \"string\",\n morphs: (s, ctx) => {\n try {\n return new URL(s);\n }\n catch {\n return ctx.error(\"a URL string\");\n }\n },\n declaredOut: rootSchema(URL)\n })\n}, {\n name: \"string.url\"\n});\n// based on https://github.com/validatorjs/validator.js/blob/master/src/lib/isUUID.js\nexport const uuid = Scope.module({\n // the meta tuple expression ensures the error message does not delegate\n // to the individual branches, which are too detailed\n root: [\n \"versioned | nil | max\",\n \"@\",\n { description: \"a UUID\", format: \"uuid\" }\n ],\n \"#nil\": \"'00000000-0000-0000-0000-000000000000'\",\n \"#max\": \"'ffffffff-ffff-ffff-ffff-ffffffffffff'\",\n \"#versioned\": /[\\da-f]{8}-[\\da-f]{4}-[1-8][\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}/i,\n v1: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-1[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv1\"),\n v2: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-2[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv2\"),\n v3: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-3[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv3\"),\n v4: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-4[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv4\"),\n v5: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-5[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv5\"),\n v6: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-6[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv6\"),\n v7: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-7[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv7\"),\n v8: regexStringNode(/^[\\da-f]{8}-[\\da-f]{4}-8[\\da-f]{3}-[89ab][\\da-f]{3}-[\\da-f]{12}$/i, \"a UUIDv8\")\n}, {\n name: \"string.uuid\"\n});\nexport const string = Scope.module({\n root: intrinsic.string,\n alpha: regexStringNode(/^[A-Za-z]*$/, \"only letters\"),\n alphanumeric: regexStringNode(/^[\\dA-Za-z]*$/, \"only letters and digits 0-9\"),\n hex,\n base64,\n capitalize,\n creditCard,\n date: stringDate,\n digits: regexStringNode(/^\\d*$/, \"only digits 0-9\"),\n email,\n integer: stringInteger,\n ip,\n json,\n lower,\n normalize,\n numeric: stringNumeric,\n regex,\n semver,\n trim,\n upper,\n url,\n uuid\n}, {\n name: \"string\"\n});\n",
187
+ "import { genericNode, intrinsic, node } from \"@ark/schema\";\nimport { Hkt } from \"@ark/util\";\nimport { Scope } from \"../scope.js\";\nexport const arkTsKeywords = Scope.module({\n bigint: intrinsic.bigint,\n boolean: intrinsic.boolean,\n false: intrinsic.false,\n never: intrinsic.never,\n null: intrinsic.null,\n number: intrinsic.number,\n object: intrinsic.object,\n string: intrinsic.string,\n symbol: intrinsic.symbol,\n true: intrinsic.true,\n unknown: intrinsic.unknown,\n undefined: intrinsic.undefined\n});\nexport const unknown = Scope.module({\n root: intrinsic.unknown,\n any: intrinsic.unknown\n}, {\n name: \"unknown\"\n});\nexport const json = Scope.module({\n root: intrinsic.jsonObject,\n stringify: node(\"morph\", {\n in: intrinsic.jsonObject,\n morphs: (data) => JSON.stringify(data),\n declaredOut: intrinsic.string\n })\n}, {\n name: \"object.json\"\n});\nexport const object = Scope.module({\n root: intrinsic.object,\n json\n}, {\n name: \"object\"\n});\nclass RecordHkt extends Hkt {\n description = 'instantiate an object from an index signature and corresponding value type like `Record(\"string\", \"number\")`';\n}\nconst Record = genericNode([\"K\", intrinsic.key], \"V\")(args => ({\n domain: \"object\",\n index: {\n signature: args.K,\n value: args.V\n }\n}), RecordHkt);\nclass PickHkt extends Hkt {\n description = 'pick a set of properties from an object like `Pick(User, \"name | age\")`';\n}\nconst Pick = genericNode([\"T\", intrinsic.object], [\"K\", intrinsic.key])(args => args.T.pick(args.K), PickHkt);\nclass OmitHkt extends Hkt {\n description = 'omit a set of properties from an object like `Omit(User, \"age\")`';\n}\nconst Omit = genericNode([\"T\", intrinsic.object], [\"K\", intrinsic.key])(args => args.T.omit(args.K), OmitHkt);\nclass PartialHkt extends Hkt {\n description = \"make all named properties of an object optional like `Partial(User)`\";\n}\nconst Partial = genericNode([\"T\", intrinsic.object])(args => args.T.partial(), PartialHkt);\nclass RequiredHkt extends Hkt {\n description = \"make all named properties of an object required like `Required(User)`\";\n}\nconst Required = genericNode([\"T\", intrinsic.object])(args => args.T.required(), RequiredHkt);\nclass ExcludeHkt extends Hkt {\n description = 'exclude branches of a union like `Exclude(\"boolean\", \"true\")`';\n}\nconst Exclude = genericNode(\"T\", \"U\")(args => args.T.exclude(args.U), ExcludeHkt);\nclass ExtractHkt extends Hkt {\n description = 'extract branches of a union like `Extract(\"0 | false | 1\", \"number\")`';\n}\nconst Extract = genericNode(\"T\", \"U\")(args => args.T.extract(args.U), ExtractHkt);\nexport const arkTsGenerics = Scope.module({\n Exclude,\n Extract,\n Omit,\n Partial,\n Pick,\n Record,\n Required\n});\n",
188
+ "import { $arkTypeRegistry, scope } from \"../scope.js\";\nimport { arkBuiltins } from \"./builtins.js\";\nimport { arkPrototypes } from \"./constructors.js\";\nimport { number } from \"./number.js\";\nimport { string } from \"./string.js\";\nimport { arkTsGenerics, arkTsKeywords, object, unknown } from \"./ts.js\";\nexport const ark = scope({\n ...arkTsKeywords,\n ...arkTsGenerics,\n ...arkPrototypes,\n ...arkBuiltins,\n string,\n number,\n object,\n unknown\n}, { prereducedAliases: true, name: \"ark\" });\nexport const keywords = ark.export();\nObject.assign($arkTypeRegistry.ambient, keywords);\n$arkTypeRegistry.typeAttachments = {\n string: keywords.string.root,\n number: keywords.number.root,\n bigint: keywords.bigint,\n boolean: keywords.boolean,\n symbol: keywords.symbol,\n undefined: keywords.undefined,\n null: keywords.null,\n object: keywords.object.root,\n unknown: keywords.unknown.root,\n false: keywords.false,\n true: keywords.true,\n never: keywords.never,\n arrayIndex: keywords.Array.index,\n Key: keywords.Key,\n Record: keywords.Record,\n Array: keywords.Array.root,\n Date: keywords.Date\n};\nexport const type = Object.assign(ark.type, \n// assign attachments newly parsed in keywords\n// future scopes add these directly from the\n// registry when their TypeParsers are instantiated\n$arkTypeRegistry.typeAttachments);\nexport const match = ark.match;\nexport const fn = ark.fn;\nexport const generic = ark.generic;\nexport const schema = ark.schema;\nexport const define = ark.define;\nexport const declare = ark.declare;\n",
189
+ "// src/domain/validator.ts\r\nimport { type, scope } from \"arktype\";\r\nimport type { TriggerRule } from \"../types\";\r\n\r\n// --- ArkType Scope & Schemas ---\r\n\r\n// Define a Validation Scope to handle recursive types and mutual dependencies\r\nconst types = scope({\r\n\r\n // List of allowed operators\r\n Operator: \"'EQ' | '==' | 'NEQ' | '!=' | 'GT' | '>' | 'GTE' | '>=' | 'LT' | '<' | 'LTE' | '<=' | 'IN' | 'NOT_IN' | 'CONTAINS' | 'MATCHES' | 'RANGE' | 'SINCE' | 'AFTER' | 'BEFORE' | 'UNTIL'\",\r\n \r\n // Discriminated union for better value validation based on operator\r\n Condition: \"RangeCondition | ListCondition | ContainsCondition | NumericCondition | RegexCondition | BasicCondition\",\r\n \r\n RangeCondition: {\r\n field: \"string > 0\",\r\n operator: \"'RANGE'\",\r\n value: \"unknown[] == 2\" // Requires an array of exactly 2 items\r\n },\r\n \r\n ListCondition: {\r\n field: \"string > 0\",\r\n operator: \"'IN' | 'NOT_IN'\",\r\n value: \"unknown[]\" // Requires an array\r\n },\r\n\r\n ContainsCondition: {\r\n field: \"string > 0\",\r\n operator: \"'CONTAINS'\",\r\n value: \"string | unknown[]\" // Can be string (substring) or array (includes)\r\n },\r\n \r\n NumericCondition: {\r\n field: \"string > 0\",\r\n operator: \"'>' | '>=' | '<' | '<=' | 'GT' | 'GTE' | 'LT' | 'LTE'\",\r\n value: \"number | string\" // Numbers or expressions\r\n },\r\n \r\n RegexCondition: {\r\n field: \"string > 0\",\r\n operator: \"'MATCHES'\",\r\n value: \"string\" // Regex pattern must be a string\r\n },\r\n \r\n BasicCondition: {\r\n field: \"string > 0\",\r\n operator: \"Operator\",\r\n value: \"unknown\"\r\n },\r\n \r\n ConditionGroup: {\r\n operator: \"'AND' | 'OR'\",\r\n // Recursive reference to Condition or ConditionGroup\r\n conditions: \"(Condition | ConditionGroup)[] >= 1\" // Must have at least 1 condition\r\n },\r\n \r\n RuleCondition: \"Condition | ConditionGroup\",\r\n\r\n Action: {\r\n type: \"string > 0\", // Must define a type\r\n \"params?\": \"object\", // Must be an object if present\r\n \"delay?\": \"number.integer >= 0\", // Integer check for milliseconds\r\n \"probability?\": \"0 <= number <= 1\"\r\n },\r\n\r\n ActionGroup: {\r\n \"mode?\": \"'ALL' | 'EITHER' | 'SEQUENCE'\",\r\n actions: \"(Action | ActionGroup)[] >= 1\" // Recursive\r\n },\r\n\r\n RuleAction: \"Action | ActionGroup\",\r\n\r\n TriggerRule: {\r\n id: \"string > 0\",\r\n \"name?\": \"string\",\r\n \"description?\": \"string\",\r\n \"priority?\": \"number.integer\", // Priority is integer\r\n \"enabled?\": \"boolean\",\r\n \"cooldown?\": \"number.integer >= 0\", // Milliseconds\r\n \"tags?\": \"string[]\",\r\n on: \"string > 0\", // Non-empty event name\r\n \r\n \"if?\": \"RuleCondition | RuleCondition[]\",\r\n \r\n do: \"RuleAction | RuleAction[]\",\r\n \"comment?\": \"string\"\r\n }\r\n}).export();\r\n\r\n// Export individual schemas for external usage if needed\r\nexport const ComparisonOperatorSchema = types.Operator;\r\nexport const ConditionSchema = types.Condition;\r\nexport const ConditionGroupSchema = types.ConditionGroup;\r\nexport const RuleConditionSchema = types.RuleCondition;\r\nexport const ActionSchema = types.Action;\r\nexport const ActionGroupSchema = types.ActionGroup;\r\nexport const TriggerRuleSchema = types.TriggerRule;\r\n\r\n// --- Validation Result Types ---\r\n\r\nexport interface ValidationSuccess {\r\n valid: true;\r\n rule: TriggerRule;\r\n}\r\n\r\nexport interface ValidationIssue {\r\n path: string;\r\n message: string;\r\n suggestion?: string;\r\n severity: \"error\" | \"warning\";\r\n}\r\n\r\nexport interface ValidationFailure {\r\n valid: false;\r\n issues: ValidationIssue[];\r\n}\r\n\r\nexport type ValidationResult = ValidationSuccess | ValidationFailure;\r\n\r\n// --- Validator Class ---\r\n\r\nexport class TriggerValidator {\r\n \r\n static validate(data: any): ValidationResult {\r\n // ArkType validation\r\n const out = TriggerRuleSchema(data);\r\n\r\n if (out instanceof type.errors) {\r\n const issues: ValidationIssue[] = [];\r\n \r\n // Iterate over problems (ArkType specific)\r\n for (const problem of out) {\r\n const path = problem.path.join(\".\");\r\n let message = problem.message;\r\n let suggestion = undefined;\r\n\r\n // Custom Error Enhancements (replicating Zod logic)\r\n // ArkType error for missing string might differ, typically says \"must be a string\"\r\n if (path.endsWith(\"on\") && (message.includes(\"string\") || message.includes(\"must be\"))) {\r\n // Heuristic check if it failed because it was interpretted as boolean 'true' in YAML\r\n // We can't see the original value easily here without checking 'data' at path\r\n // But we can just suggest it generally.\r\n if (typeof data === 'object' && data && data.on === true) {\r\n message = \"The 'on' field is incorrect (boolean true found).\";\r\n suggestion = \"In YAML, 'on' is a boolean keyword (true). Quote it: \\\"on\\\": \\\"EventName\\\"\";\r\n } else {\r\n // Generic suggestion\r\n suggestion = \"Ensure 'on' is a string event name.\";\r\n }\r\n }\r\n\r\n issues.push({\r\n path,\r\n message,\r\n suggestion,\r\n severity: \"error\"\r\n });\r\n }\r\n\r\n return { valid: false, issues };\r\n }\r\n \r\n // Structural validation passed. Now perform Semantic Validation (Value Types)\r\n const rule = out as TriggerRule;\r\n const semanticIssues: ValidationIssue[] = [];\r\n \r\n this.validateConditionsRecursive(rule.if, semanticIssues, 'if');\r\n\r\n if (semanticIssues.length > 0) {\r\n return { valid: false, issues: semanticIssues };\r\n }\r\n\r\n return { valid: true, rule };\r\n }\r\n\r\n private static validateConditionsRecursive(\r\n condition: any, \r\n issues: ValidationIssue[], \r\n path: string\r\n ): void {\r\n if (!condition) return;\r\n\r\n if (Array.isArray(condition)) {\r\n condition.forEach((c, idx) => {\r\n this.validateConditionsRecursive(c, issues, `${path}.${idx}`);\r\n });\r\n return;\r\n }\r\n\r\n // Check if it's a ConditionGroup (has 'conditions')\r\n if ('conditions' in condition && Array.isArray(condition.conditions)) {\r\n condition.conditions.forEach((c: any, idx: number) => {\r\n this.validateConditionsRecursive(c, issues, `${path}.conditions.${idx}`);\r\n });\r\n return;\r\n }\r\n\r\n // It must be a Condition\r\n if ('operator' in condition && 'value' in condition) {\r\n this.validateConditionValue(condition, issues, path);\r\n }\r\n }\r\n\r\n private static validateConditionValue(\r\n condition: any, \r\n issues: ValidationIssue[], \r\n path: string\r\n ): void {\r\n const { operator, value } = condition;\r\n \r\n // 1. List/Collection Operators (IN, NOT_IN, RANGE, CONTAINS)\r\n if (['IN', 'NOT_IN', 'RANGE', 'CONTAINS'].includes(operator)) {\r\n if (operator === 'CONTAINS') {\r\n if (typeof value !== 'string' && !Array.isArray(value)) {\r\n issues.push({\r\n path: `${path}.value`,\r\n message: `Incorrect value type: Operator 'CONTAINS' expects a String or List (Array), but received ${typeof value}.`,\r\n suggestion: \"Use a substring or a list of items.\",\r\n severity: \"error\"\r\n });\r\n }\r\n return;\r\n }\r\n\r\n if (!Array.isArray(value)) {\r\n issues.push({\r\n path: `${path}.value`,\r\n message: `Incorrect value type: Operator '${operator}' expects a List (Array), but received ${typeof value}.`,\r\n suggestion: operator === 'RANGE' ? \"Use format [min, max]\" : \"Use format [item1, item2]\",\r\n severity: \"error\"\r\n });\r\n return;\r\n }\r\n\r\n if (operator === 'RANGE') {\r\n if (value.length !== 2) {\r\n issues.push({\r\n path: `${path}.value`,\r\n message: `Invalid Range: Operator 'RANGE' requires exactly 2 values (min and max).`,\r\n suggestion: \"Use format [min, max], e.g. [1, 10]\",\r\n severity: \"error\"\r\n });\r\n } else if (typeof value[0] !== 'number' && typeof value[0] !== 'string') {\r\n issues.push({\r\n path: `${path}.value`,\r\n message: `Incorrect range type: Range values must be numbers or expression strings.`,\r\n severity: \"error\"\r\n });\r\n }\r\n }\r\n } \r\n // 2. Regex\r\n else if (operator === 'MATCHES') {\r\n if (typeof value !== 'string') {\r\n issues.push({\r\n path: `${path}.value`,\r\n message: `Incorrect value type: Operator 'MATCHES' expects a string (regex pattern), but received ${typeof value}.`,\r\n severity: \"error\"\r\n });\r\n } else {\r\n try {\r\n new RegExp(value);\r\n } catch (e) {\r\n issues.push({\r\n path: `${path}.value`,\r\n message: `Invalid Regex pattern: ${(e as Error).message}`,\r\n severity: \"error\"\r\n });\r\n }\r\n }\r\n }\r\n // 3. Numeric Comparisons (GT, LT, etc)\r\n else if (['GT', 'GTE', 'LT', 'LTE', '>', '>=', '<', '<='].includes(operator)) {\r\n if (typeof value !== 'number' && typeof value !== 'string') {\r\n issues.push({\r\n path: `${path}.value`,\r\n message: `Incorrect value type: Operator '${operator}' expects a number or expression string, but received ${typeof value}.`,\r\n severity: \"error\"\r\n });\r\n }\r\n }\r\n }\r\n}\r\n",
190
+ "import type { \r\n TriggerRule, \r\n RuleCondition, \r\n Action, \r\n ActionGroup, \r\n ComparisonOperator,\r\n ExecutionMode,\r\n Condition,\r\n ConditionGroup\r\n} from \"../types\";\r\n\r\nexport class ConditionBuilder {\r\n private conditions: (Condition | ConditionGroup)[] = [];\r\n private op: 'AND' | 'OR' = 'AND';\r\n\r\n constructor(operator: 'AND' | 'OR' = 'AND') {\r\n this.op = operator;\r\n }\r\n\r\n where(field: string, operator: ComparisonOperator, value: any): this {\r\n this.conditions.push({ field, operator, value });\r\n return this;\r\n }\r\n\r\n and(sub: (builder: ConditionBuilder) => ConditionBuilder): this {\r\n const builder = new ConditionBuilder('AND');\r\n this.conditions.push(sub(builder).build());\r\n return this;\r\n }\r\n\r\n or(sub: (builder: ConditionBuilder) => ConditionBuilder): this {\r\n const builder = new ConditionBuilder('OR');\r\n this.conditions.push(sub(builder).build());\r\n return this;\r\n }\r\n\r\n build(): RuleCondition {\r\n if (this.conditions.length === 0) {\r\n throw new Error(\"Condition group must have at least one condition\");\r\n }\r\n if (this.conditions.length === 1 && this.op === 'AND') {\r\n return this.conditions[0] as RuleCondition;\r\n }\r\n const group: ConditionGroup = {\r\n operator: this.op,\r\n conditions: this.conditions\r\n };\r\n return group as RuleCondition;\r\n }\r\n}\r\n\r\nexport class ActionBuilder {\r\n private actions: Action[] = [];\r\n private mode: ExecutionMode = 'ALL';\r\n\r\n setMode(mode: ExecutionMode): this {\r\n this.mode = mode;\r\n return this;\r\n }\r\n\r\n add(type: string, params?: Record<string, any>, options?: { delay?: number, probability?: number }): this {\r\n this.actions.push({\r\n type,\r\n params,\r\n ...options\r\n });\r\n return this;\r\n }\r\n\r\n build(): Action | Action[] | ActionGroup {\r\n if (this.actions.length === 0) {\r\n throw new Error(\"Action group must have at least one action\");\r\n }\r\n if (this.actions.length === 1 && this.mode === 'ALL') {\r\n return this.actions[0] as Action;\r\n }\r\n if (this.mode === 'ALL') {\r\n return this.actions as Action[];\r\n }\r\n const group: ActionGroup = {\r\n mode: this.mode,\r\n actions: this.actions\r\n };\r\n return group as ActionGroup;\r\n }\r\n}\r\n\r\n\r\n\r\nexport class RuleBuilder {\r\n private rule: Partial<TriggerRule> = {\r\n enabled: true,\r\n priority: 0\r\n };\r\n\r\n withId(id: string): this {\r\n this.rule.id = id;\r\n return this;\r\n }\r\n\r\n withName(name: string): this {\r\n this.rule.name = name;\r\n return this;\r\n }\r\n\r\n withDescription(description: string): this {\r\n this.rule.description = description;\r\n return this;\r\n }\r\n\r\n withPriority(priority: number): this {\r\n this.rule.priority = priority;\r\n return this;\r\n }\r\n\r\n withCooldown(cooldown: number): this {\r\n this.rule.cooldown = cooldown;\r\n return this;\r\n }\r\n\r\n withTags(tags: string[]): this {\r\n this.rule.tags = tags;\r\n return this;\r\n }\r\n\r\n on(event: string): this {\r\n this.rule.on = event;\r\n return this;\r\n }\r\n\r\n if(field: string, operator: ComparisonOperator, value: any): this {\r\n if (!this.rule.if) {\r\n this.rule.if = { field, operator, value };\r\n } else if (Array.isArray(this.rule.if)) {\r\n (this.rule.if as any[]).push({ field, operator, value });\r\n } else {\r\n this.rule.if = [this.rule.if as any, { field, operator, value }];\r\n }\r\n return this;\r\n }\r\n\r\n ifComplex(sub: (builder: ConditionBuilder) => ConditionBuilder): this {\r\n const builder = new ConditionBuilder();\r\n const result = sub(builder).build();\r\n this.rule.if = result;\r\n return this;\r\n }\r\n\r\n do(type: string, params?: Record<string, any>, options?: { delay?: number, probability?: number }): this {\r\n const action: Action = { type, params, ...options };\r\n if (!this.rule.do) {\r\n this.rule.do = action;\r\n } else if (Array.isArray(this.rule.do)) {\r\n this.rule.do.push(action);\r\n } else if (this.rule.do && typeof this.rule.do === 'object' && 'actions' in this.rule.do) {\r\n (this.rule.do as ActionGroup).actions.push(action);\r\n } else {\r\n this.rule.do = [this.rule.do as Action, action];\r\n }\r\n return this;\r\n }\r\n\r\n doComplex(sub: (builder: ActionBuilder) => ActionBuilder): this {\r\n const builder = new ActionBuilder();\r\n const result = sub(builder).build();\r\n this.rule.do = result;\r\n return this;\r\n }\r\n\r\n\r\n build(): TriggerRule {\r\n if (!this.rule.id) throw new Error(\"Rule ID is required\");\r\n if (!this.rule.on) throw new Error(\"Rule 'on' event is required\");\r\n if (!this.rule.do) throw new Error(\"Rule 'do' action is required\");\r\n\r\n return this.rule as TriggerRule;\r\n }\r\n}\r\n",
191
+ "import type { TriggerRule } from \"../types\";\r\nimport { RuleBuilder } from \"./builder\";\r\nimport YAML from \"yaml\";\r\n\r\nexport class RuleExporter {\r\n /**\r\n * Converts a rule or array of rules to a YAML string.\r\n */\r\n static toYaml(rules: TriggerRule | TriggerRule[]): string {\r\n const data = Array.isArray(rules) ? rules : [rules];\r\n return YAML.stringify(data);\r\n }\r\n\r\n\r\n /**\r\n * For Node.js only: Saves a rule or array of rules to a file.\r\n * This is part of the 'Server SDK' functionality.\r\n */\r\n static async saveToFile(rules: TriggerRule | TriggerRule[], filePath: string): Promise<void> {\r\n const yamlContent = this.toYaml(rules);\r\n if (typeof process !== 'undefined' && process.versions && process.versions.node) {\r\n const fs = await import(\"fs/promises\");\r\n const path = await import(\"path\");\r\n const dir = path.dirname(filePath);\r\n await fs.mkdir(dir, { recursive: true });\r\n await fs.writeFile(filePath, yamlContent, \"utf8\");\r\n } else {\r\n throw new Error(\"saveToFile is only supported in Node.js/Bun environments\");\r\n }\r\n }\r\n}\r\n",
192
+ "\r\nimport { type PersistenceAdapter } from \"./persistence\";\r\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\r\nimport { dirname } from \"path\";\r\n\r\n/**\r\n * FileSystem Persistence Adapter\r\n * Saves state to a JSON file on disk.\r\n */\r\nexport class FilePersistence implements PersistenceAdapter {\r\n private filePath: string;\r\n private cache: Map<string, any> = new Map();\r\n private isLoaded: boolean = false;\r\n\r\n constructor(filePath: string) {\r\n this.filePath = filePath;\r\n }\r\n\r\n private ensureLoaded() {\r\n if (this.isLoaded) return;\r\n \r\n try {\r\n if (existsSync(this.filePath)) {\r\n const data = readFileSync(this.filePath, 'utf-8');\r\n const json = JSON.parse(data);\r\n this.cache = new Map(Object.entries(json));\r\n }\r\n } catch (error) {\r\n console.error(`[FilePersistence] Failed to load state from ${this.filePath}:`, error);\r\n // Start empty if corrupt or error\r\n this.cache = new Map();\r\n }\r\n this.isLoaded = true;\r\n }\r\n\r\n private persist() {\r\n try {\r\n const dir = dirname(this.filePath);\r\n if (!existsSync(dir)) {\r\n mkdirSync(dir, { recursive: true });\r\n }\r\n \r\n const obj = Object.fromEntries(this.cache);\r\n writeFileSync(this.filePath, JSON.stringify(obj, null, 2), 'utf-8');\r\n } catch (error) {\r\n console.error(`[FilePersistence] Failed to save state to ${this.filePath}:`, error);\r\n }\r\n }\r\n\r\n async loadState(): Promise<Map<string, any>> {\r\n this.ensureLoaded();\r\n return new Map(this.cache);\r\n }\r\n\r\n async saveState(key: string, value: any): Promise<void> {\r\n this.ensureLoaded();\r\n this.cache.set(key, value);\r\n this.persist();\r\n }\r\n\r\n async deleteState(key: string): Promise<void> {\r\n this.ensureLoaded();\r\n this.cache.delete(key);\r\n this.persist();\r\n }\r\n\r\n async clearState(): Promise<void> {\r\n this.cache.clear();\r\n this.persist();\r\n }\r\n}\r\n",
193
+ "\r\nimport * as path from \"path\";\r\nimport * as fs from \"fs\";\r\nimport { parse } from \"yaml\";\r\nimport type { TriggerRule } from \"../types\";\r\nimport { TriggerValidator } from \"../domain/validator\";\r\nimport { parseAllDocuments } from \"yaml\";\r\nexport class TriggerLoader {\r\n /**\r\n * Loads all YAML rule files from a directory\r\n */\r\n static async loadRulesFromDir(dirPath: string): Promise<TriggerRule[]> {\r\n const rules: TriggerRule[] = [];\r\n \r\n // Recursive walker function\r\n const walk = async (dir: string) => {\r\n let files;\r\n try {\r\n files = await fs.promises.readdir(dir, { withFileTypes: true });\r\n } catch (e) {\r\n console.error(`[TriggerLoader] Failed to readdir ${dir}:`, e);\r\n return;\r\n }\r\n\r\n for (const dirent of files) {\r\n const res = path.resolve(dir, dirent.name);\r\n if (dirent.isDirectory()) {\r\n await walk(res);\r\n } else if (res.toLowerCase().endsWith('.yaml') || res.toLowerCase().endsWith('.yml')) {\r\n // Case insensitive extension check\r\n try {\r\n const loaded = await this.loadRule(res);\r\n rules.push(...loaded);\r\n } catch (err) {\r\n console.error(`Failed to load rule from ${res}:`, err);\r\n }\r\n }\r\n }\r\n };\r\n\r\n if (fs.existsSync(dirPath)) {\r\n await walk(dirPath);\r\n } else {\r\n console.warn(`[TriggerLoader] Directory not found: ${dirPath}`);\r\n }\r\n\r\n return rules;\r\n }\r\n\r\n /**\r\n * Loads rules from a YAML file (supports multi-document)\r\n */\r\n static async loadRule(filePath: string): Promise<TriggerRule[]> {\r\n try {\r\n const content = await fs.promises.readFile(filePath, 'utf-8');\r\n \r\n // Support multi-document YAML\r\n const yamlDocs = parseAllDocuments(content);\r\n \r\n // Check for parsing errors\r\n for (const doc of yamlDocs) {\r\n // In some yaml versions errors is an array on the doc\r\n if (doc.errors && doc.errors.length > 0) {\r\n throw new Error(`YAML syntax error in ${filePath}: ${doc.errors.map(e => e.message).join(', ')}`);\r\n }\r\n }\r\n\r\n const docs = yamlDocs.map(doc => doc.toJS());\r\n \r\n const rules: TriggerRule[] = [];\r\n\r\n // Flatten docs if the root is an array (Single doc with list of rules)\r\n let flattenedDocs: any[] = [];\r\n docs.forEach(d => {\r\n if (Array.isArray(d)) {\r\n flattenedDocs.push(...d);\r\n } else {\r\n flattenedDocs.push(d);\r\n }\r\n });\r\n\r\n flattenedDocs.forEach((doc: any, index: number) => {\r\n // Normalize 'actions' to 'do' alias\r\n if (doc && typeof doc === 'object' && doc.actions && !doc.do) {\r\n doc.do = doc.actions;\r\n }\r\n\r\n const validation = TriggerValidator.validate(doc);\r\n \r\n if (validation.valid) {\r\n const rule = validation.rule;\r\n // Assign ID from filename if missing, with index suffix if multidoc\r\n if (!rule.id) {\r\n const base = path.basename(filePath, path.extname(filePath));\r\n rule.id = flattenedDocs.length > 1 ? `${base}-${index}` : base;\r\n }\r\n rules.push(rule);\r\n } else {\r\n // LOG ERROR TO STDERR so it shows up in tests\r\n console.error(`\\n[TriggerLoader] ⚠️ Validation Problem in ${filePath} (item #${index + 1})`);\r\n validation.issues.forEach(issue => {\r\n console.error(` - [${issue.path}] ${issue.message}`);\r\n if (issue.suggestion) {\r\n console.error(` 💡 Suggestion: ${issue.suggestion}`);\r\n }\r\n });\r\n }\r\n });\r\n\r\n return rules;\r\n } catch (error) {\r\n console.error(`Error parsing YAML file ${filePath}:`, error);\r\n throw error;\r\n }\r\n }\r\n\r\n static watchRules(dirPath: string, onUpdate: (rules: TriggerRule[]) => void) {\r\n this.loadRulesFromDir(dirPath).then(onUpdate);\r\n console.log(`[TriggerLoader] Watching for changes in ${dirPath}...`);\r\n const watcher = fs.watch(dirPath, { recursive: true }, async (event, filename) => {\r\n if (filename && (String(filename).endsWith('.yaml') || String(filename).endsWith('.yml'))) {\r\n console.log(`[TriggerLoader] Detected change in ${filename} (${event}). Reloading rules...`);\r\n try {\r\n const rules = await this.loadRulesFromDir(dirPath);\r\n onUpdate(rules);\r\n console.log(`[TriggerLoader] Reloaded ${rules.length} rules.`);\r\n } catch (err) {\r\n console.error(\"[TriggerLoader] Failed to reload rules:\", err);\r\n }\r\n }\r\n });\r\n return watcher;\r\n }\r\n}\r\n"
194
+ ],
195
+ "mappings": "wdAEA,IAAM,GAAQ,OAAO,IAAI,YAAY,EAC/B,GAAM,OAAO,IAAI,eAAe,EAChC,GAAM,OAAO,IAAI,UAAU,EAC3B,GAAO,OAAO,IAAI,WAAW,EAC7B,GAAS,OAAO,IAAI,aAAa,EACjC,GAAM,OAAO,IAAI,UAAU,EAC3B,GAAY,OAAO,IAAI,gBA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