eliscript 0.0.3 → 0.0.4

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 (96) hide show
  1. package/README.md +5 -5
  2. package/bootstrap/README.md +13 -8
  3. package/bootstrap/host/build.eli +2 -0
  4. package/bootstrap/host/bun.eli +2 -0
  5. package/bootstrap/host/check-cli-legacy.eli +2 -0
  6. package/bootstrap/host/evaluation-cli.eli +2 -0
  7. package/bootstrap/host/evaluation.eli +2 -0
  8. package/bootstrap/host/format-cli.eli +2 -0
  9. package/bootstrap/host/project-cli-legacy.eli +2 -0
  10. package/bootstrap/host/project-legacy.eli +2 -0
  11. package/bootstrap/host/watch-cli.eli +2 -0
  12. package/bootstrap/host/watch.eli +2 -0
  13. package/browser/README.md +33 -0
  14. package/browser/host.eli +2 -0
  15. package/browser/worker.eli +2 -0
  16. package/package.json +2 -1
  17. package/platform/README.md +33 -12
  18. package/platform/browser.eli +2 -0
  19. package/platform/http.eli +2 -0
  20. package/platform/worker.eli +2 -0
  21. package/runtime/README.md +34 -14
  22. package/runtime/array-text.eli +2 -0
  23. package/runtime/core/collection-internals.eli +2 -0
  24. package/runtime/core/collection.eli +2 -0
  25. package/runtime/core/collection.mjs +99 -17
  26. package/runtime/core/data-text.eli +2 -0
  27. package/runtime/core/data.eli +2 -0
  28. package/runtime/core/data.mjs +7 -5
  29. package/runtime/core/identifier.eli +2 -0
  30. package/runtime/core/lazy-sequence.eli +2 -0
  31. package/runtime/core/list-internals.eli +2 -0
  32. package/runtime/core/list.eli +2 -0
  33. package/runtime/core/list.mjs +3 -0
  34. package/runtime/core/map-internals.eli +2 -0
  35. package/runtime/core/map.eli +2 -0
  36. package/runtime/core/map.mjs +5 -0
  37. package/runtime/core/metadata-internals.eli +2 -0
  38. package/runtime/core/metadata.eli +2 -0
  39. package/runtime/core/metadata.mjs +14 -0
  40. package/runtime/core/object.eli +2 -0
  41. package/runtime/core/order.eli +2 -0
  42. package/runtime/core/order.mjs +35 -6
  43. package/runtime/core/persistent-kind.eli +2 -0
  44. package/runtime/core/persistent-kind.mjs +6 -0
  45. package/runtime/core/protocol-error.eli +2 -0
  46. package/runtime/core/protocol.eli +2 -0
  47. package/runtime/core/queue-internals.eli +2 -0
  48. package/runtime/core/queue.eli +2 -0
  49. package/runtime/core/queue.mjs +3 -0
  50. package/runtime/core/record.eli +2 -0
  51. package/runtime/core/regex.eli +2 -0
  52. package/runtime/core/sequence.eli +2 -0
  53. package/runtime/core/sequence.mjs +75 -13
  54. package/runtime/core/set-algebra.eli +2 -0
  55. package/runtime/core/set-internals.eli +2 -0
  56. package/runtime/core/set.eli +2 -0
  57. package/runtime/core/sorted-internals.eli +2 -0
  58. package/runtime/core/sorted.eli +2 -0
  59. package/runtime/core/text.eli +2 -0
  60. package/runtime/core/transducer.eli +2 -0
  61. package/runtime/core/transient-internals.eli +2 -0
  62. package/runtime/core/transient.eli +2 -0
  63. package/runtime/core/transient.mjs +59 -10
  64. package/runtime/core/truth.eli +2 -0
  65. package/runtime/core/type.eli +2 -0
  66. package/runtime/core/value-internals.eli +2 -0
  67. package/runtime/core/value.eli +2 -0
  68. package/runtime/core/vector-internals.eli +2 -0
  69. package/runtime/core/vector-internals.mjs +3 -6
  70. package/runtime/core/vector.eli +2 -0
  71. package/runtime/core/vector.mjs +125 -7
  72. package/runtime/literals.eli +2 -0
  73. package/runtime/number-radix.eli +2 -0
  74. package/runtime/source-mapping.eli +2 -0
  75. package/runtime/testing/list.eli +2 -0
  76. package/runtime/testing/map.eli +2 -0
  77. package/runtime/testing/queue.eli +2 -0
  78. package/runtime/testing/set.eli +2 -0
  79. package/runtime/testing/sorted.eli +2 -0
  80. package/runtime/testing/value.eli +2 -0
  81. package/runtime/testing/vector.eli +2 -0
  82. package/runtime/wire/http-rpc.eli +2 -0
  83. package/runtime/wire/markdown.eli +2 -0
  84. package/runtime/wire/schema.eli +2 -0
  85. package/runtime/worker-value-codec.eli +2 -0
  86. package/runtime/worker-value-stream.eli +2 -0
  87. package/runtime/worker.eli +2 -0
  88. package/stdlib/README.md +2 -2
  89. package/stdlib/core/order.eli +36 -10
  90. package/stdlib/core/seq.eli +104 -75
  91. package/stdlib/core/zipper.eli +238 -98
  92. package/stdlib/managed-literal-protocols.eli +5 -5
  93. package/stdlib/managed-runtime-order.eli +32 -10
  94. package/stdlib/managed-runtime-sequence.eli +69 -28
  95. package/tools/acceptance/check.eli +13 -3
  96. package/tools/backends/compiler-build.mjs +140 -140
@@ -0,0 +1,2 @@
1
+ (module capsules.runtime.source-mapping
2
+ (js* "const base64Vlq = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\nexport class SourceMappingError extends Error {\n constructor(code, message) {\n super(message);\n this.name = \"SourceMappingError\";\n this.code = code;\n }\n}\n\nfunction fail(code, message) {\n throw new SourceMappingError(code, message);\n}\n\nfunction isPlainObject(value) {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction decodeVlq(segment) {\n const values = [];\n let index = 0;\n while (index < segment.length) {\n let value = 0;\n let shift = 0;\n let continuation;\n do {\n if (index >= segment.length) {\n fail(\"invalid-vlq\", \"unterminated Base64 VLQ value\");\n }\n const digit = base64Vlq.indexOf(segment[index]);\n if (digit === -1) fail(\"invalid-vlq\", \"invalid Base64 VLQ digit\");\n index += 1;\n value += (digit & 31) * (2 ** shift);\n continuation = (digit & 32) !== 0;\n shift += 5;\n if (shift > 50) fail(\"invalid-vlq\", \"Base64 VLQ value exceeds safe bounds\");\n } while (continuation);\n const negative = (value & 1) === 1;\n const magnitude = Math.floor(value / 2);\n values.push(negative ? -magnitude : magnitude);\n }\n return values;\n}\n\nexport function decodeSourceMappings(mappings) {\n if (typeof mappings !== \"string\") {\n fail(\"invalid-mappings\", \"source mappings must be a string\");\n }\n let source = 0;\n let originalLine = 0;\n let originalColumn = 0;\n return Object.freeze(mappings.split(\";\").map((encodedLine) => {\n let generatedColumn = 0;\n const line = [];\n for (const encoded of encodedLine.split(\",\")) {\n if (encoded.length === 0) continue;\n const values = decodeVlq(encoded);\n if (![1, 4, 5].includes(values.length)) {\n fail(\"invalid-segment\", \"source map segments must contain 1, 4, or 5 fields\");\n }\n generatedColumn += values[0];\n if (generatedColumn < 0) {\n fail(\"invalid-segment\", \"generated source map columns must not be negative\");\n }\n const decoded = { generatedColumn };\n if (values.length >= 4) {\n source += values[1];\n originalLine += values[2];\n originalColumn += values[3];\n if (source < 0 || originalLine < 0 || originalColumn < 0) {\n fail(\"invalid-segment\", \"decoded source map positions must not be negative\");\n }\n decoded.source = source;\n decoded.originalLine = originalLine;\n decoded.originalColumn = originalColumn;\n }\n line.push(Object.freeze(decoded));\n }\n return Object.freeze(line);\n }));\n}\n\nexport function sourceMapDescriptor(value) {\n if (!isPlainObject(value) || typeof value.generatedFile !== \"string\" ||\n value.generatedFile.length === 0 || !Array.isArray(value.sources) ||\n value.sources.length === 0 || value.sources.some(\n (source) => typeof source !== \"string\" || source.length === 0,\n )) {\n fail(\n \"invalid-source-map\",\n \"source map descriptor requires generatedFile sources and mappings\",\n );\n }\n const lines = value.lines === undefined\n ? decodeSourceMappings(value.mappings)\n : value.lines;\n if (!Array.isArray(lines) || lines.some((line) => !Array.isArray(line))) {\n fail(\"invalid-source-map\", \"source map descriptor lines must be arrays\");\n }\n for (const line of lines) {\n for (const segment of line) {\n if (!isPlainObject(segment) ||\n !Number.isInteger(segment.generatedColumn) ||\n segment.generatedColumn < 0 ||\n (segment.source !== undefined &&\n (!Number.isInteger(segment.source) || segment.source < 0 ||\n !Number.isInteger(segment.originalLine) ||\n segment.originalLine < 0 ||\n !Number.isInteger(segment.originalColumn) ||\n segment.originalColumn < 0))) {\n fail(\"invalid-source-map\", \"source map descriptor contains an invalid segment\");\n }\n }\n }\n return Object.freeze({\n generatedFile: value.generatedFile,\n sources: Object.freeze([...value.sources]),\n lines: Object.freeze(lines.map((line) => Object.freeze(\n line.map((segment) => Object.freeze({ ...segment })),\n ))),\n });\n}\n\nexport function parseJavaScriptStack(stack, options = {}) {\n if (typeof stack !== \"string\") return Object.freeze([]);\n const normalizeFile = typeof options.normalizeFile === \"function\"\n ? options.normalizeFile\n : (file) => file;\n const frames = [];\n for (const line of stack.split(\"\\n\")) {\n const v8 = /^\\s*at (?:(.*?) \\()?(.+):(\\d+):(\\d+)\\)?$/u.exec(line);\n const browser = v8 ? null : /^(.*?)@(.+):(\\d+):(\\d+)$/u.exec(line.trim());\n const match = v8 ?? browser;\n if (!match) continue;\n frames.push(Object.freeze({\n function: match[1] || undefined,\n file: normalizeFile(match[2]),\n line: Number(match[3]),\n column: Number(match[4]),\n }));\n }\n return Object.freeze(frames);\n}\n\nfunction cleanIdentity(value) {\n try {\n const url = new URL(value);\n url.search = \"\";\n url.hash = \"\";\n return url.href;\n } catch {\n return value.replace(/[?#].*$/u, \"\");\n }\n}\n\nfunction sourceIdentities(value) {\n const clean = cleanIdentity(value);\n const identities = [clean];\n try {\n const url = new URL(clean);\n if (url.protocol === \"file:\") identities.push(decodeURIComponent(url.pathname));\n } catch {\n // Plain filesystem paths and runtime pseudo-URLs keep their clean identity.\n }\n return identities;\n}\n\nexport function mapSourceFrames(frames, sourceMaps) {\n if (!Array.isArray(frames) || !Array.isArray(sourceMaps)) {\n fail(\"invalid-frames\", \"frames and source maps must be arrays\");\n }\n const mapsByFile = new Map();\n for (const sourceMap of sourceMaps) {\n for (const identity of sourceIdentities(sourceMap.generatedFile)) {\n mapsByFile.set(identity, sourceMap);\n }\n }\n return Object.freeze(frames.map((frame) => {\n const sourceMap = sourceIdentities(frame.file)\n .map((identity) => mapsByFile.get(identity))\n .find(Boolean);\n const mapping = sourceMap?.lines[frame.line - 1];\n if (!mapping) return frame;\n const generatedColumn = Math.max(0, frame.column - 1);\n let segment;\n for (const candidate of mapping) {\n if (candidate.generatedColumn > generatedColumn) break;\n segment = candidate;\n }\n if (segment?.source === undefined ||\n sourceMap.sources[segment.source] === undefined) return frame;\n return Object.freeze({\n ...frame,\n generated: Object.freeze({\n file: frame.file,\n line: frame.line,\n column: frame.column,\n }),\n file: sourceMap.sources[segment.source],\n line: segment.originalLine + 1,\n column: segment.originalColumn + 1,\n });\n }));\n}\n\nexport function sourceMappedFailure(error, sourceMaps, options = {}) {\n const stack = typeof error?.stack === \"string\" ? error.stack : undefined;\n const frames = stack\n ? mapSourceFrames(parseJavaScriptStack(stack, options), sourceMaps)\n : Object.freeze([]);\n const location = frames.find((frame) => frame.file.endsWith(\".eli\")) ??\n frames[0];\n return Object.freeze({\n name: typeof error?.name === \"string\" ? error.name : \"Error\",\n message: typeof error?.message === \"string\" ? error.message : String(error),\n ...(stack ? { stack } : {}),\n frames,\n ...(location ? { location } : {}),\n });\n}\n"))
@@ -0,0 +1,2 @@
1
+ (module capsules.runtime.testing.list
2
+ (js* "import {\n LIST_STATE,\n readListMetrics,\n resetListMetrics,\n} from \"../core/list-internals.mjs\";\n\nfunction stateOf(list) {\n const state = list?.[LIST_STATE];\n if (state === undefined) {\n throw new TypeError(\"expected an Eliscript persistent list\");\n }\n return state;\n}\n\nfunction collectNodes(list) {\n const nodes = new Set();\n let node = list;\n while (!stateOf(node).empty) {\n nodes.add(node);\n node = stateOf(node).rest;\n }\n return nodes;\n}\n\nexport function resetPersistentListMetrics() {\n resetListMetrics();\n}\n\nexport function persistentListMetrics() {\n return readListMetrics();\n}\n\nexport function inspectPersistentList(list) {\n const state = stateOf(list);\n return Object.freeze({\n count: state.count,\n empty: state.empty,\n nodeCount: collectNodes(list).size,\n });\n}\n\nexport function sharedPersistentListNodes(left, right) {\n const leftNodes = collectNodes(left);\n const rightNodes = collectNodes(right);\n let shared = 0;\n for (const node of leftNodes) {\n if (rightNodes.has(node)) {\n shared += 1;\n }\n }\n return shared;\n}\n"))
@@ -0,0 +1,2 @@
1
+ (module capsules.runtime.testing.map
2
+ (js* "import {\n MAP_STATE,\n TRANSIENT_MAP_STATE,\n ArrayNode,\n BitmapIndexedNode,\n HashCollisionNode,\n MapEntry,\n readMapMetrics,\n readTransientMapMetrics,\n resetMapMetrics,\n resetTransientMapMetrics as resetTransientMapMetricsInternal,\n} from \"../core/map-internals.mjs\";\n\nfunction stateOf(map) {\n const state = map?.[MAP_STATE];\n if (state === undefined) {\n throw new TypeError(\"expected an Eliscript persistent hash map\");\n }\n return state;\n}\n\nfunction transientStateOf(map) {\n const state = map?.[TRANSIENT_MAP_STATE];\n if (state === undefined) {\n throw new TypeError(\"expected an Eliscript transient hash map\");\n }\n return state;\n}\n\nfunction inspectItem(item, depth, result, nodes) {\n if (item instanceof MapEntry) {\n result.entries += 1;\n result.maxDepth = Math.max(result.maxDepth, depth);\n return;\n }\n if (nodes.has(item)) {\n return;\n }\n nodes.add(item);\n result.maxDepth = Math.max(result.maxDepth, depth);\n if (item instanceof BitmapIndexedNode) {\n result.bitmapNodes += 1;\n for (const child of item.items) {\n inspectItem(child, depth + 1, result, nodes);\n }\n return;\n }\n if (item instanceof ArrayNode) {\n result.arrayNodes += 1;\n for (const child of item.children) {\n if (child !== undefined) {\n inspectItem(child, depth + 1, result, nodes);\n }\n }\n return;\n }\n if (item instanceof HashCollisionNode) {\n result.collisionNodes += 1;\n for (const entry of item.entries) {\n inspectItem(entry, depth + 1, result, nodes);\n }\n }\n}\n\nfunction collectNodes(item, nodes) {\n if (item instanceof MapEntry || nodes.has(item)) {\n return;\n }\n nodes.add(item);\n const children = item instanceof BitmapIndexedNode\n ? item.items\n : item instanceof ArrayNode\n ? item.children\n : item.entries;\n for (const child of children) {\n if (child !== undefined) {\n collectNodes(child, nodes);\n }\n }\n}\n\nexport function resetPersistentMapMetrics() {\n resetMapMetrics();\n}\n\nexport function persistentMapMetrics() {\n return readMapMetrics();\n}\n\nexport function resetTransientMapMetrics() {\n resetTransientMapMetricsInternal();\n}\n\nexport function transientMapMetrics() {\n return readTransientMapMetrics();\n}\n\nexport function inspectTransientMap(map) {\n const state = transientStateOf(map);\n const nodes = new Set();\n collectNodes(state.root, nodes);\n let ownedNodeCount = 0;\n for (const node of nodes) {\n if (node.owner === state.owner) {\n ownedNodeCount += 1;\n }\n }\n return Object.freeze({\n active: state.active,\n count: state.count,\n nodeCount: nodes.size,\n ownedNodeCount,\n sharesSourceRoot: state.root === state.source?.[MAP_STATE].root,\n });\n}\n\nexport function inspectPersistentMap(map) {\n const result = {\n count: stateOf(map).count,\n bitmapNodes: 0,\n arrayNodes: 0,\n collisionNodes: 0,\n entries: 0,\n nodeCount: 0,\n maxDepth: 0,\n };\n const nodes = new Set();\n inspectItem(stateOf(map).root, 1, result, nodes);\n result.nodeCount = nodes.size;\n return Object.freeze(result);\n}\n\nexport function sharedPersistentMapNodes(left, right) {\n const leftNodes = new Set();\n const rightNodes = new Set();\n collectNodes(stateOf(left).root, leftNodes);\n collectNodes(stateOf(right).root, rightNodes);\n let shared = 0;\n for (const node of leftNodes) {\n if (rightNodes.has(node)) {\n shared += 1;\n }\n }\n return shared;\n}\n"))
@@ -0,0 +1,2 @@
1
+ (module capsules.runtime.testing.queue
2
+ (js* "import {\n QUEUE_STATE,\n readQueueMetrics,\n resetQueueMetrics,\n} from \"../core/queue-internals.mjs\";\nimport { sharedPersistentVectorNodes } from \"./vector.mjs\";\n\nfunction stateOf(queue) {\n const state = queue?.[QUEUE_STATE];\n if (state === undefined) {\n throw new TypeError(\"expected an Eliscript persistent queue\");\n }\n return state;\n}\n\nexport function resetPersistentQueueMetrics() {\n resetQueueMetrics();\n}\n\nexport function persistentQueueMetrics() {\n return readQueueMetrics();\n}\n\nexport function inspectPersistentQueue(queue) {\n const state = stateOf(queue);\n return Object.freeze({\n count: state.count,\n frontCount: state.front.count,\n rearCount: state.rear.count,\n });\n}\n\nexport function sharedPersistentQueueParts(left, right) {\n const leftState = stateOf(left);\n const rightState = stateOf(right);\n return Object.freeze({\n frontIdentity: leftState.front === rightState.front,\n rearIdentity: leftState.rear === rightState.rear,\n rearPromotedToFront: leftState.rear === rightState.front,\n sharedFrontNodes: sharedPersistentVectorNodes(\n leftState.front,\n rightState.front,\n ),\n sharedRearNodes: sharedPersistentVectorNodes(\n leftState.rear,\n rightState.rear,\n ),\n });\n}\n"))
@@ -0,0 +1,2 @@
1
+ (module capsules.runtime.testing.set
2
+ (js* "import {\n SET_STATE,\n TRANSIENT_SET_STATE,\n readTransientSetMetrics,\n resetTransientSetMetrics as resetTransientSetMetricsInternal,\n} from \"../core/set-internals.mjs\";\nimport {\n inspectPersistentMap,\n inspectTransientMap,\n persistentMapMetrics,\n resetPersistentMapMetrics,\n resetTransientMapMetrics,\n sharedPersistentMapNodes,\n transientMapMetrics,\n} from \"./map.mjs\";\n\nfunction mapOf(set) {\n const state = set?.[SET_STATE];\n if (state === undefined) {\n throw new TypeError(\"expected an Eliscript persistent hash set\");\n }\n return state.map;\n}\n\nexport function resetPersistentSetMetrics() {\n resetPersistentMapMetrics();\n}\n\nexport function persistentSetMetrics() {\n return persistentMapMetrics();\n}\n\nexport function resetTransientSetMetrics() {\n resetTransientSetMetricsInternal();\n resetTransientMapMetrics();\n}\n\nexport function transientSetMetrics() {\n const set = readTransientSetMetrics();\n return Object.freeze({\n ...transientMapMetrics(),\n setPersistentCalls: set.persistentCalls,\n setInvalidCalls: set.invalidCalls,\n });\n}\n\nexport function inspectTransientSet(set) {\n const state = set?.[TRANSIENT_SET_STATE];\n if (state === undefined) {\n throw new TypeError(\"expected an Eliscript transient hash set\");\n }\n return inspectTransientMap(state.map);\n}\n\nexport function inspectPersistentSet(set) {\n return inspectPersistentMap(mapOf(set));\n}\n\nexport function sharedPersistentSetNodes(left, right) {\n return sharedPersistentMapNodes(mapOf(left), mapOf(right));\n}\n"))
@@ -0,0 +1,2 @@
1
+ (module capsules.runtime.testing.sorted
2
+ (js* "import {\n SORTED_MAP_STATE,\n SORTED_SET_STATE,\n SortedNode,\n readSortedMetrics,\n resetSortedMetrics as resetMetrics,\n} from \"../core/sorted-internals.mjs\";\n\nfunction mapState(value) {\n if (value?.[SORTED_MAP_STATE] !== undefined) {\n return value[SORTED_MAP_STATE];\n }\n if (value?.[SORTED_SET_STATE] !== undefined) {\n return value[SORTED_SET_STATE].map[SORTED_MAP_STATE];\n }\n throw new TypeError(\"expected an Eliscript persistent sorted collection\");\n}\n\nfunction inspectNode(node, comparison, minimum, maximum, nodes, result) {\n if (node === null) return { height: 0, size: 0 };\n if (!(node instanceof SortedNode) || nodes.has(node)) {\n throw new TypeError(\"persistent sorted collection contains an invalid tree\");\n }\n nodes.add(node);\n if (minimum !== null && comparison(node.key, minimum) <= 0) {\n throw new TypeError(\"persistent sorted collection violates lower ordering\");\n }\n if (maximum !== null && comparison(node.key, maximum) >= 0) {\n throw new TypeError(\"persistent sorted collection violates upper ordering\");\n }\n const left = inspectNode(\n node.left,\n comparison,\n minimum,\n node.key,\n nodes,\n result,\n );\n const right = inspectNode(\n node.right,\n comparison,\n node.key,\n maximum,\n nodes,\n result,\n );\n const height = Math.max(left.height, right.height) + 1;\n const size = left.size + right.size + 1;\n if (node.height !== height || node.size !== size ||\n Math.abs(left.height - right.height) > 1) {\n throw new TypeError(\"persistent sorted collection violates AVL balance\");\n }\n result.maxBalance = Math.max(\n result.maxBalance,\n Math.abs(left.height - right.height),\n );\n return { height, size };\n}\n\nfunction collectNodes(node, result) {\n if (node === null || result.has(node)) return;\n result.add(node);\n collectNodes(node.left, result);\n collectNodes(node.right, result);\n}\n\nexport function inspectPersistentSortedCollection(value) {\n const state = mapState(value);\n const nodes = new Set();\n const result = { maxBalance: 0 };\n const tree = inspectNode(\n state.root,\n state.comparison,\n null,\n null,\n nodes,\n result,\n );\n return Object.freeze({\n count: tree.size,\n height: tree.height,\n nodes: nodes.size,\n maxBalance: result.maxBalance,\n });\n}\n\nexport function sharedPersistentSortedNodes(left, right) {\n const leftNodes = new Set();\n const rightNodes = new Set();\n collectNodes(mapState(left).root, leftNodes);\n collectNodes(mapState(right).root, rightNodes);\n let shared = 0;\n for (const node of leftNodes) {\n if (rightNodes.has(node)) shared += 1;\n }\n return shared;\n}\n\nexport function resetSortedMetrics() {\n resetMetrics();\n}\n\nexport function sortedMetrics() {\n return readSortedMetrics();\n}\n"))
@@ -0,0 +1,2 @@
1
+ (module capsules.runtime.testing.value
2
+ (js* "import {\n clearValueCaches,\n readValueMetrics,\n resetValueMetrics,\n} from \"../core/value-internals.mjs\";\n\nexport function resetValueHashMetrics() {\n resetValueMetrics();\n}\n\nexport function clearValueHashCaches() {\n clearValueCaches();\n}\n\nexport function valueHashMetrics() {\n return readValueMetrics();\n}\n"))
@@ -0,0 +1,2 @@
1
+ (module capsules.runtime.testing.vector
2
+ (js* "import {\n VECTOR_STATE,\n TRANSIENT_VECTOR_STATE,\n VectorNode,\n readTransientVectorMetrics,\n readVectorMetrics,\n resetTransientVectorMetrics as resetTransientVectorMetricsInternal,\n resetVectorMetrics,\n} from \"../core/vector-internals.mjs\";\n\nfunction stateOf(vector) {\n const state = vector?.[VECTOR_STATE];\n if (state === undefined) {\n throw new TypeError(\"expected an Eliscript persistent vector\");\n }\n return state;\n}\n\nfunction transientStateOf(vector) {\n const state = vector?.[TRANSIENT_VECTOR_STATE];\n if (state === undefined) {\n throw new TypeError(\"expected an Eliscript transient vector\");\n }\n return state;\n}\n\nfunction collectNodes(node, nodes) {\n if (nodes.has(node)) {\n return;\n }\n nodes.add(node);\n for (const child of node.slots) {\n if (child instanceof VectorNode) {\n collectNodes(child, nodes);\n }\n }\n}\n\nexport function resetPersistentVectorMetrics() {\n resetVectorMetrics();\n}\n\nexport function persistentVectorMetrics() {\n return readVectorMetrics();\n}\n\nexport function resetTransientVectorMetrics() {\n resetTransientVectorMetricsInternal();\n}\n\nexport function transientVectorMetrics() {\n return readTransientVectorMetrics();\n}\n\nexport function inspectTransientVector(vector) {\n const state = transientStateOf(vector);\n const nodes = new Set();\n collectNodes(state.root, nodes);\n let ownedNodeCount = 0;\n for (const node of nodes) {\n if (node.owner === state.owner) {\n ownedNodeCount += 1;\n }\n }\n return Object.freeze({\n active: state.active,\n count: state.count,\n shift: state.shift,\n tailOwned: state.tailOwned,\n nodeCount: nodes.size,\n ownedNodeCount,\n sharesSourceRoot: state.root === state.source?.[VECTOR_STATE].root,\n sharesSourceTail: state.tail === state.source?.[VECTOR_STATE].tail,\n });\n}\n\nexport function inspectPersistentVector(vector) {\n const state = stateOf(vector);\n const nodes = new Set();\n collectNodes(state.root, nodes);\n return Object.freeze({\n count: state.count,\n shift: state.shift,\n depth: state.shift / 5 + 1,\n tailLength: state.tail.length,\n nodeCount: nodes.size,\n });\n}\n\nexport function sharedPersistentVectorNodes(left, right) {\n const leftNodes = new Set();\n const rightNodes = new Set();\n collectNodes(stateOf(left).root, leftNodes);\n collectNodes(stateOf(right).root, rightNodes);\n let shared = 0;\n for (const node of leftNodes) {\n if (rightNodes.has(node)) {\n shared += 1;\n }\n }\n return shared;\n}\n"))
@@ -0,0 +1,2 @@
1
+ (module capsules.runtime.wire.http-rpc
2
+ (js* "const mediaType = 'text/markdown; charset=utf-8';\nconst line = value => String(value).replace(/[\\r\\n]/gu, ' ');\nfunction path(value) {\n if (typeof value !== 'string' || !value.startsWith('/') || /[\\s?#`\\\\]/u.test(value) || value.includes('//') || (value !== '/' && value.endsWith('/')) || value.split('/').some(p => p === '.' || p === '..') || ['/.well-known/gepo', '/.gepo'].some(p => value === p || value.startsWith(p + '/')) || new URL(value, 'https://local.invalid').pathname !== value) throw new TypeError('Expected a canonical public operation path');\n return value;\n}\nfunction target(value) {\n const url = new URL(value);\n if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new TypeError('Expected an HTTP URL without credentials');\n url.hash = ''; return url;\n}\nfunction parent(value) { return value === '/' ? null : value.slice(0, value.lastIndexOf('/')) || '/'; }\n\nexport function defineOperation(options) {\n path(options.path);\n if (typeof options.execute !== 'function') throw new TypeError('Operation requires an execute function');\n return Object.freeze({ title: options.path, summary: 'Invoke this operation.', contentType: 'application/json', request: 'Body is service-defined.', success: 'Use HTTP status and response representation.', failures: [], effect: 'Service-defined.', retry: 'No automatic POST retry.', ...options });\n}\n\nexport function usageMarkdown(operation) {\n path(operation.path);\n return `# ${line(operation.title ?? operation.path)}\\n\\nPOST \\`${operation.path}\\` with Content-Type: ${line(operation.contentType ?? 'application/json')}.\\n\\nPurpose: ${line(operation.summary ?? '')}\\nRequest: ${line(operation.request ?? 'Body is service-defined.')}\\nSuccess: ${line(operation.success ?? 'Use HTTP status and response representation.')}\\nFailures: ${line((operation.failures ?? []).join('; ') || 'Use applicable HTTP error statuses.')}\\nEffect: ${line(operation.effect ?? 'Service-defined.')}\\nRetry: ${line(operation.retry ?? 'No automatic POST retry.')}\\n`;\n}\n\nfunction tree(operations) {\n const nodes = new Map([['/', { operation: null, children: new Set() }]]);\n for (const operation of operations) {\n path(operation.path);\n if (nodes.get(operation.path)?.operation) throw new TypeError('Duplicate operation path');\n if (!nodes.has(operation.path)) nodes.set(operation.path, { operation: null, children: new Set() });\n nodes.get(operation.path).operation = operation;\n let child = operation.path;\n while (parent(child) !== null) {\n const directory = parent(child);\n if (!nodes.has(directory)) nodes.set(directory, { operation: null, children: new Set() });\n nodes.get(directory).children.add(child); child = directory;\n }\n }\n return nodes;\n}\n\nexport function pathIndexMarkdown(title, operations, location = '/') {\n path(location);\n const nodes = tree(operations), node = nodes.get(location);\n if (!node) return null;\n const children = [...node.children].sort();\n const kind = node.operation ? (children.length ? 'operation and directory' : 'operation') : 'directory';\n let result = `# ${line(title ?? 'Service')}\\n\\nGEPO 0.2\\nPath: \\`${location}\\`\\nParent: ${parent(location) === null ? 'none' : `\\`${parent(location)}\\``}\\nKind: ${kind}\\n`;\n if (node.operation) result += `\\n## Usage\\n\\n${usageMarkdown(node.operation)}`;\n result += '\\n## Children\\n\\n';\n if (!children.length) result += node.operation ? 'No immediate child paths.\\n' : 'The visible capability set is empty.\\n';\n else for (const child of children) result += `- \\`${child}\\` — ${line(nodes.get(child).operation?.summary ?? 'Directory')}\\n`;\n return result;\n}\n\nexport function discoveryCandidates(value) {\n const url = target(value); url.search = '';\n const root = url.origin;\n return [...new Set([...(url.pathname !== '/' ? [`${url.href}?.gepo`] : []), `${root}/?.gepo`, `${root}/.gepo`, `${root}/.well-known/gepo`])];\n}\n\nexport function classifyDiscovery(response) {\n if (response.status < 200 || response.status >= 300 || !response.contentType) return { accepted: false, paths: [], empty: false };\n const type = response.contentType.split(';')[0].trim().toLowerCase();\n if (!['text/markdown', 'text/plain'].includes(type) || !/\\bGEPO\\b/u.test(response.body)) return { accepted: false, paths: [], empty: false };\n const children = response.body.split(/^## Children\\s*$/mu).at(-1);\n const paths = [...new Set([...children.matchAll(/^\\s*-\\s+`(\\/[^`\\s]*)`/gmu)].map(m => m[1]))];\n if (!paths.length && /^Path: `\\/`$/mu.test(response.body) && /^Kind: operation$/mu.test(response.body)) paths.push('/');\n const empty = /visible capability set is empty|no visible (?:operations|capabilities)/iu.test(children);\n return { accepted: paths.length > 0 || empty, paths, empty };\n}\n\nexport function createService({ title = 'Service', operations = [], authorize = () => true, visible = () => true } = {}) {\n const entries = operations.map(defineOperation); tree(entries);\n const response = (body, status = 200, headers = {}) => new Response(body, { status, headers: { 'Content-Type': mediaType, 'Cache-Control': 'private, no-store', ...headers } });\n return async function serve(request) {\n const url = new URL(request.url);\n const fixedEntry = ['/.gepo', '/.well-known/gepo'].includes(url.pathname);\n const discovery = ['GET', 'HEAD'].includes(request.method) && (url.searchParams.has('.gepo') || fixedEntry);\n const location = fixedEntry ? '/' : url.pathname;\n const available = [];\n for (const operation of entries) if (await visible(request, operation)) available.push(operation);\n const nodes = tree(available), node = nodes.get(location);\n if (!node) return response('Unknown path', 404);\n const permission = await authorize(request, node.operation, discovery ? 'index' : request.method === 'POST' ? 'invoke' : 'usage');\n if (permission instanceof Response) return permission;\n if (permission !== true) return response('Forbidden', 403);\n const allow = node.operation && !fixedEntry ? 'GET, HEAD, OPTIONS, POST' : 'GET, HEAD, OPTIONS';\n if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: { Allow: allow } });\n if (request.method === 'GET' || request.method === 'HEAD') {\n const body = discovery || !node.operation ? pathIndexMarkdown(title, available, location) : usageMarkdown(node.operation);\n return response(request.method === 'HEAD' ? null : body);\n }\n if (request.method !== 'POST' || !node.operation || ['/.gepo', '/.well-known/gepo'].includes(url.pathname)) return response('Method not allowed', 405, { Allow: allow });\n const result = await node.operation.execute(request);\n if (!(result instanceof Response)) throw new TypeError('Operation must return a Response');\n return result;\n };\n}\n\nexport function createClient({ fetch: transport = globalThis.fetch, headers: defaults = {}, maxBytes = 2097152, timeoutMs = 30000, classify = classifyDiscovery } = {}) {\n if (typeof transport !== 'function' || typeof classify !== 'function' || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1) throw new TypeError('Invalid client options');\n const defaultHeaders = new Headers(defaults);\n async function send(url, method, body, options = {}) {\n const headers = new Headers(defaultHeaders);\n new Headers(options.headers).forEach((value, key) => headers.set(key, value));\n if (!headers.has('Accept')) headers.set('Accept', 'text/markdown, text/plain;q=0.8, */*;q=0.1');\n if (options.contentType) headers.set('Content-Type', options.contentType);\n const controller = new AbortController();\n const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;\n if (signal.aborted) throw signal.reason ?? new Error('HTTP request aborted');\n const timer = setTimeout(() => controller.abort(new Error('HTTP timeout')), timeoutMs);\n let onAbort;\n const aborted = new Promise((resolve, reject) => {\n onAbort = () => reject(signal.reason ?? new Error('HTTP request aborted'));\n signal.addEventListener('abort', onAbort, { once: true });\n });\n try {\n const reply = await Promise.race([aborted, transport(url.href, { method, body, headers, redirect: 'manual', signal })]);\n if (reply.status >= 300 && reply.status < 400) { await reply.body?.cancel(); throw new Error('Redirect requires explicit caller handling'); }\n const chunks = []; let size = 0;\n if (reply.body) {\n const reader = reply.body.getReader();\n try {\n while (true) {\n const { done, value } = await Promise.race([aborted, reader.read()]); if (done) break;\n size += value.byteLength;\n if (size > maxBytes) { await reader.cancel(); throw new RangeError('HTTP response byte limit'); }\n chunks.push(value);\n }\n } catch (error) { await reader.cancel().catch(() => {}); throw error; }\n finally { reader.releaseLock(); }\n }\n const bytes = new Uint8Array(size); let offset = 0;\n for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }\n return { url: url.href, status: reply.status, contentType: reply.headers.get('Content-Type'), headers: reply.headers, body: new TextDecoder().decode(bytes) };\n } finally { clearTimeout(timer); signal.removeEventListener('abort', onAbort); }\n }\n async function usage(value, options = {}) {\n const url = target(value); url.searchParams.delete('.gepo');\n return send(url, 'GET', undefined, options);\n }\n async function index(value, options = {}) {\n const url = target(value); url.search = '.gepo';\n return send(url, 'GET', undefined, options);\n }\n return Object.freeze({ usage, index,\n async discover(value, options = {}) {\n const attempts = [];\n for (const candidate of discoveryCandidates(value)) {\n const reply = await send(target(candidate), 'GET', undefined, options);\n const result = await classify(reply);\n attempts.push({ url: reply.url, status: reply.status, accepted: result.accepted });\n if (result.accepted) return { ...reply, paths: result.paths, state: result.empty ? 'empty' : 'found', attempts };\n }\n return { state: 'not-found', attempts };\n },\n async invoke(value, body, options = {}) {\n if (options.allowPost !== true) throw new TypeError('Invocation requires allowPost: true');\n if (body === undefined) throw new TypeError('Invocation requires an explicit body');\n const url = target(value);\n if (url.searchParams.has('.gepo')) throw new TypeError('Discovery parameter is reserved');\n const description = await usage(url, options);\n if (description.status < 200 || description.status >= 300) throw new Error(`Usage request failed: ${description.status}`);\n return send(url, 'POST', body, options);\n },\n });\n}\n"))
@@ -0,0 +1,2 @@
1
+ (module capsules.runtime.wire.markdown
2
+ (js* "const own = (value, key) => Object.hasOwn(value, key);\nconst object = value => value !== null && typeof value === 'object' && !Array.isArray(value);\nconst put = (target, key, value) => Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });\nconst number = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/u;\n\nexport class MarkdownError extends Error {\n constructor(code, line, message) { super(`${code} at line ${line}: ${message}`); this.name = 'MarkdownError'; this.code = code; this.line = line; }\n}\nconst fail = (code, line, message) => { throw new MarkdownError(code, line, message); };\n\nfunction scalar(text) {\n if (text.startsWith('\"') && text.endsWith('\"') && text.length >= 2)\n return text.slice(1, -1).replace(/\\\\([\"\\\\ntr])/gu, (_, c) => ({ n: '\\n', t: '\\t', r: '\\r' }[c] ?? c));\n if (number.test(text)) {\n const value = Number(text);\n if (!Number.isFinite(value)) throw new RangeError('Number exceeds finite IEEE 754 range');\n return value;\n }\n if (text === 'true') return true;\n if (text === 'false') return false;\n if (text === 'null' || text === '') return null;\n if (text === '{}') return {};\n if (text === '[]') return [];\n return text;\n}\n\nfunction cells(text) {\n const result = []; let cell = '';\n for (let i = 1; i < text.length - 1; i++) {\n if (text[i] === '\\\\' && text[i + 1] === '|') { cell += '|'; i++; }\n else if (text[i] === '|') { result.push(cell.trim()); cell = ''; }\n else cell += text[i];\n }\n result.push(cell.trim()); return result;\n}\n\nfunction tokenize(source) {\n const lines = source.replace(/^\\uFEFF/u, '').split(/\\r\\n?|\\n/u);\n const tokens = []; let fence = null; let html = null;\n for (let i = 0; i < lines.length; i++) {\n const raw = lines[i], text = raw.trim(), line = i + 1;\n if (fence) { if (new RegExp(`^ {0,3}${fence.char}{${fence.size},}\\\\s*$`, 'u').test(raw)) fence = null; continue; }\n if (html) { if (html === 'blank' ? text === '' : html.test(raw)) html = null; continue; }\n const fenced = raw.match(/^ {0,3}(`{3,}|~{3,})/u);\n if (fenced) { fence = { char: fenced[1][0], size: fenced[1].length }; continue; }\n if (/^ {0,3}<!--/u.test(raw)) { if (!raw.includes('-->')) html = /-->/u; continue; }\n const special = raw.match(/^ {0,3}<(script|pre|style|textarea)(?:\\s|>)/iu);\n if (special) { const end = new RegExp(`</${special[1]}>`, 'iu'); if (!end.test(raw)) html = end; continue; }\n if (/^ {0,3}<\\?/u.test(raw)) { if (!raw.includes('?>')) html = /\\?>/u; continue; }\n if (/^ {0,3}<!\\[CDATA\\[/u.test(raw)) { if (!raw.includes(']]>')) html = /\\]\\]>/u; continue; }\n if (/^ {0,3}<![A-Z]/u.test(raw)) { if (!raw.includes('>')) html = />/u; continue; }\n const blockTag = /^ {0,3}<\\/?(?:address|article|aside|base|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\\s|\\/?>)/iu;\n if (blockTag.test(raw) || /^ {0,3}<\\/?[A-Za-z][\\w-]*(?:\\s[^>]*|\\/?)>\\s*$/u.test(raw)) { html = 'blank'; continue; }\n const heading = raw.match(/^ {0,3}(#{1,2})(?:[ \\t]+(.*)|$)/u);\n if (heading) {\n const title = (heading[2] ?? '').replace(/(?:^|\\s+)#+\\s*$/u, '').trim();\n if (!title) fail('MDP-E007', line, 'Empty heading');\n tokens.push({ kind: 'heading', level: heading[1].length, title, line }); continue;\n }\n const field = text.match(/^-\\s+([^]*?):(?: (.*)|\\s*)$/u);\n const pipe = text.startsWith('|') && text.endsWith('|') && text.length > 1;\n if (!field && !pipe) continue;\n const leading = raw.match(/^\\s*/u)[0];\n if (leading.includes('\\t')) fail('MDP-E009', line, 'Tab indentation');\n const level = Math.floor(leading.length / 2);\n if (field) { tokens.push({ kind: 'field', key: field[1].trim(), text: (field[2] ?? '').trim(), level, line }); continue; }\n if (i + 1 >= lines.length || !lines[i + 1].trim().startsWith('|') || !lines[i + 1].trim().endsWith('|')) continue;\n const separator = cells(lines[i + 1].trim());\n if (!separator.every(c => /^:?-+:?$/u.test(c))) continue;\n if (lines[i + 1].match(/^\\s*/u)[0].includes('\\t')) fail('MDP-E009', line + 1, 'Tab indentation');\n const headers = cells(text);\n if (headers.some(h => !h) || new Set(headers).size !== headers.length) fail('MDP-E005', line, 'Invalid table header');\n if (separator.length !== headers.length) fail('MDP-E004', line + 1, 'Separator width');\n const rows = []; i++;\n while (i + 1 < lines.length && /^\\s*\\|.*\\|\\s*$/u.test(lines[i + 1])) {\n if (lines[i + 1].match(/^\\s*/u)[0].includes('\\t')) fail('MDP-E009', i + 2, 'Tab indentation');\n const row = cells(lines[++i].trim());\n if (row.length !== headers.length) fail('MDP-E004', i + 1, 'Row width');\n if (headers.length === 1) rows.push(scalar(row[0]));\n else { const value = {}; row.forEach((c, j) => { if (c !== '') put(value, headers[j], scalar(c)); }); rows.push(value); }\n }\n tokens.push({ kind: 'table', value: rows, level, line });\n }\n return tokens;\n}\n\nexport function parse(source, options = {}) {\n const { maxLength = 16777216, maxDepth = 256 } = options;\n if (typeof source !== 'string') throw new TypeError('Markdown source must be a string');\n if (!Number.isSafeInteger(maxLength) || maxLength < 1 || !Number.isSafeInteger(maxDepth) || maxDepth < 0 || maxDepth > 512) throw new RangeError('Invalid parser limits');\n if (source.length > maxLength) throw new RangeError('Markdown length limit');\n const tokens = tokenize(source); let cursor = 0;\n function block(level, root = false) {\n if (level > maxDepth) throw new RangeError('Markdown depth limit');\n let value = {}, mode = 'object', populated = false;\n while (cursor < tokens.length) {\n const token = tokens[cursor];\n if (token.kind === 'heading' || token.level < level) break;\n if (token.level > level && !(token.kind === 'table' && level === 0 && token.level <= 1))\n fail(token.kind === 'table' || token.key === '' ? 'MDP-E006' : 'MDP-E009', token.line, 'Unattached indentation');\n cursor++;\n if (token.kind === 'table') {\n if (root) fail('MDP-E006', token.line, 'Root table');\n if (populated) fail('MDP-E002', token.line, 'Mixed contents');\n value = token.value; mode = 'table'; populated = true; continue;\n }\n const element = token.key === '';\n if (element && root) fail('MDP-E006', token.line, 'Root element');\n if (mode === 'table' || (populated && element !== (mode === 'elements'))) fail('MDP-E002', token.line, 'Mixed contents');\n if (element && !populated) { value = []; mode = 'elements'; }\n if (!element && own(value, token.key)) fail('MDP-E003', token.line, 'Duplicate key');\n let child = scalar(token.text);\n const next = tokens[cursor];\n if (next && next.kind !== 'heading' && next.level > level) {\n if (next.level !== level + 1 || token.text !== '') fail(next.kind === 'table' ? 'MDP-E006' : 'MDP-E009', next.line, 'Child requires a container');\n child = block(level + 1);\n }\n if (element) value.push(child); else put(value, token.key, child);\n populated = true;\n }\n return value;\n }\n const result = block(0, true); let current = null;\n while (cursor < tokens.length) {\n const token = tokens[cursor++];\n if (token.level === 1) {\n if (own(result, token.title)) fail('MDP-E003', token.line, 'Duplicate section');\n current = block(0); put(result, token.title, current);\n } else {\n if (current === null) fail('MDP-E001', token.line, 'Orphan heading');\n if (Array.isArray(current)) fail('MDP-E002', token.line, 'Table with subsection');\n if (own(current, token.title)) fail('MDP-E003', token.line, 'Duplicate subsection');\n put(current, token.title, block(0));\n }\n }\n return result;\n}\n\nfunction atom(value) {\n if (value === null) return 'null';\n if (typeof value === 'string') {\n return value === '' || value.trim() !== value || /[\\n\\r\\t]/u.test(value) || number.test(value) || ['true', 'false', 'null', '{}', '[]'].includes(value) || (value.startsWith('\"') && value.endsWith('\"'))\n ? '\"' + value.replace(/[\"\\\\\\n\\r\\t]/gu, c => ({ '\"': '\\\\\"', '\\\\': '\\\\\\\\', '\\n': '\\\\n', '\\r': '\\\\r', '\\t': '\\\\t' }[c])) + '\"' : value;\n }\n if (typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))) return String(value);\n if (Array.isArray(value) && value.length === 0) return '[]';\n if (object(value) && [Object.prototype, null].includes(Object.getPrototypeOf(value)) && Object.keys(value).length === 0) return '{}';\n throw new TypeError('Expected a finite JSON scalar');\n}\nconst leaf = value => value === null || typeof value !== 'object' || (Array.isArray(value) ? value.length === 0 : Object.keys(value).length === 0);\nfunction keyText(key, heading = false) {\n if (!key || key.trim() !== key || /[\\r\\n\\t]/u.test(key) || (heading ? /\\s#+$/u.test(key) : /: /u.test(key))) throw new TypeError('Unrepresentable Markdown key');\n return key;\n}\n\nexport function encode(value, options = {}) {\n const { maxDepth = 256, maxLength = 16777216 } = options;\n if (!object(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw new TypeError('Markdown document must be a plain object');\n if (!Number.isSafeInteger(maxDepth) || maxDepth < 0 || maxDepth > 512 || !Number.isSafeInteger(maxLength) || maxLength < 1) throw new RangeError('Invalid encoder limits');\n const active = new Set();\n function body(data, depth) {\n if (depth > maxDepth) throw new RangeError('Markdown depth limit');\n if (active.has(data)) throw new TypeError('Cyclic Markdown value');\n active.add(data); const pad = ' '.repeat(depth); let lines = [];\n if (Array.isArray(data)) {\n for (let i = 0; i < data.length; i++) if (!own(data, i)) throw new TypeError('Sparse arrays are not JSON values');\n if (data.every(v => leaf(v))) lines = [`${pad}| value |`, `${pad}| --- |`, ...data.map(v => `${pad}| ${atom(v).replaceAll('|', '\\\\|')} |`)];\n else {\n const keys = [...new Set(data.flatMap(v => object(v) ? Object.keys(v) : []))];\n if (keys.length > 1 && data.every(v => object(v) && Object.values(v).every(leaf))) {\n const row = values => `${pad}| ${values.join(' | ')} |`;\n const cell = v => atom(v).replaceAll('|', '\\\\|');\n lines = [row(keys.map(k => keyText(k).replaceAll('|', '\\\\|'))), row(keys.map(() => '---')), ...data.map(v => row(keys.map(k => own(v, k) ? cell(v[k]) : '')))];\n } else for (const child of data) {\n if (leaf(child)) lines.push(`${pad}- : ${atom(child)}`);\n else lines.push(`${pad}- :`, ...body(child, depth + 1));\n }\n }\n } else if (object(data)) {\n if (Object.getPrototypeOf(data) !== Object.prototype && Object.getPrototypeOf(data) !== null) throw new TypeError('Expected plain JSON object');\n for (const [key, child] of Object.entries(data)) {\n if (leaf(child)) lines.push(`${pad}- ${keyText(key)}: ${atom(child)}`);\n else lines.push(`${pad}- ${keyText(key)}:`, ...body(child, depth + 1));\n }\n } else throw new TypeError('Expected JSON container');\n active.delete(data); return lines;\n }\n active.add(value); const preamble = [], sections = [];\n for (const [key, child] of Object.entries(value)) {\n if (leaf(child)) preamble.push(`- ${keyText(key)}: ${atom(child)}`);\n else sections.push(`# ${keyText(key, true)}\\n\\n${body(child, 0).join('\\n')}`);\n }\n const output = [...(preamble.length ? [preamble.join('\\n')] : []), ...sections].join('\\n\\n') + '\\n';\n if (output.length > maxLength) throw new RangeError('Markdown length limit');\n return output;\n}\n"))
@@ -0,0 +1,2 @@
1
+ (module capsules.runtime.wire.schema
2
+ (js* "import { parse } from './markdown.mjs';\n\nconst own = (value, key) => Object.hasOwn(value, key);\nconst object = value => value !== null && typeof value === 'object' && !Array.isArray(value);\nconst types = new Set(['any', 'string', 'int', 'float', 'number', 'bool', 'null', 'date', 'datetime']);\nconst reserved = new Set(['Preamble', 'Sections']);\nfunction at(document, path) {\n let value = document;\n for (const part of path.split('.')) {\n if (!object(value) || !own(value, part)) return undefined;\n value = value[part];\n }\n return value;\n}\nfunction date(value) {\n if (typeof value !== 'string' || !/^\\d{4}-\\d{2}-\\d{2}$/u.test(value)) return false;\n const parsed = new Date(`${value}T00:00:00Z`);\n return Number.isFinite(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;\n}\nfunction typed(value, type) {\n switch (type) {\n case 'any': return true;\n case 'string': return typeof value === 'string';\n case 'int': return Number.isFinite(value) && Number.isInteger(value);\n case 'float': case 'number': return typeof value === 'number' && Number.isFinite(value);\n case 'bool': return typeof value === 'boolean';\n case 'null': return value === null;\n case 'date': return date(value);\n case 'datetime': return typeof value === 'string' && /^\\d{4}-\\d{2}-\\d{2}[Tt]\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:[Zz]|[+-]\\d{2}:\\d{2})$/u.test(value) && date(value.slice(0, 10)) && Number.isFinite(Date.parse(value));\n }\n}\n\nexport function validate(data, schema) {\n if (typeof data === 'string') data = parse(data);\n if (typeof schema === 'string') schema = parse(schema);\n if (!object(data) || !object(schema) || schema.mds !== '0.1') throw new TypeError('Expected object data and an MDS/0.1 schema');\n for (const [name, value] of Object.entries(schema)) {\n if (!reserved.has(name) && object(value)) throw new TypeError('Schema field definition must be a table');\n }\n const definitions = Object.keys(schema).filter(k => !reserved.has(k) && Array.isArray(schema[k]));\n const fields = new Map();\n for (const name of [...definitions, ...(own(schema, 'Preamble') ? ['Preamble'] : [])]) {\n const rows = schema[name];\n if (!Array.isArray(rows)) throw new TypeError('Schema field definition must be a table');\n const seen = new Set();\n fields.set(name, rows.map(row => {\n if (!object(row) || typeof row.name !== 'string' || !row.name || !types.has(row.type) || seen.has(row.name)) throw new TypeError('Invalid schema field declaration');\n seen.add(row.name);\n if (own(row, 'required') && typeof row.required !== 'boolean') throw new TypeError('required must be boolean');\n for (const key of ['min', 'max', 'min_len', 'max_len']) if (own(row, key) && (typeof row[key] !== 'number' || !Number.isFinite(row[key]) || (key.endsWith('_len') && (!Number.isInteger(row[key]) || row[key] < 0)))) throw new TypeError(`Invalid ${key} constraint`);\n if ((row.min !== undefined && row.max !== undefined && row.min > row.max) || (row.min_len !== undefined && row.max_len !== undefined && row.min_len > row.max_len)) throw new TypeError('Inverted field bounds');\n if (own(row, 'enum') && typeof row.enum !== 'string') throw new TypeError('enum must be text');\n let pattern;\n if (own(row, 'pattern')) {\n if (typeof row.pattern !== 'string') throw new TypeError('pattern must be text');\n pattern = new RegExp(row.pattern, 'u');\n }\n return { ...row, pattern };\n }));\n }\n let declarations;\n if (own(schema, 'Sections')) {\n if (!Array.isArray(schema.Sections)) throw new TypeError('Sections must be a table');\n declarations = schema.Sections;\n } else declarations = definitions.map(name => ({ name, required: true }));\n const declared = new Map();\n for (const row of declarations) {\n if (!object(row) || typeof row.name !== 'string' || !row.name || row.name.split('.').some(p => !p) || declared.has(row.name) || !['object', 'list', 'any'].includes(row.kind ?? 'any')) throw new TypeError('Invalid section declaration');\n for (const key of ['required', 'additional']) if (own(row, key) && typeof row[key] !== 'boolean') throw new TypeError(`${key} must be boolean`);\n for (const key of ['min_rows', 'max_rows']) if (own(row, key) && (!Number.isSafeInteger(row[key]) || row[key] < 0)) throw new TypeError(`Invalid ${key} constraint`);\n if (row.min_rows !== undefined && row.max_rows !== undefined && row.min_rows > row.max_rows) throw new TypeError('Inverted row bounds');\n declared.set(row.name, row);\n }\n const errors = [];\n const error = (path, rule, expected, actual) => errors.push({ path, rule, expected, actual });\n function checkRow(value, rows, path, additional = true) {\n if (!object(value)) { error(path, 'kind', 'object', value); return; }\n for (const row of rows) {\n const fieldPath = `${path}.${row.name}`;\n if (!own(value, row.name)) { if (row.required) error(fieldPath, 'required', true, 'missing'); continue; }\n const actual = value[row.name];\n if (!typed(actual, row.type)) { error(fieldPath, 'type', row.type, actual); continue; }\n if (row.enum !== undefined && !row.enum.split(',').map(v => v.trim()).includes(String(actual))) error(fieldPath, 'enum', row.enum, actual);\n for (const key of ['min', 'max']) if (typeof actual === 'number' && row[key] !== undefined && (key === 'min' ? actual < row[key] : actual > row[key])) error(fieldPath, key, row[key], actual);\n if (typeof actual === 'string') {\n const length = [...actual].length;\n for (const key of ['min_len', 'max_len']) if (row[key] !== undefined && (key === 'min_len' ? length < row[key] : length > row[key])) error(fieldPath, key, row[key], length);\n if (row.pattern && !row.pattern.test(actual)) error(fieldPath, 'pattern', row.pattern.source, actual);\n }\n }\n if (!additional) {\n const allowed = new Set(rows.map(r => r.name));\n for (const key of Object.keys(value)) if (!allowed.has(key) && (value[key] === null || typeof value[key] !== 'object')) error(`${path}.${key}`, 'additional', false, value[key]);\n }\n }\n if (fields.has('Preamble')) checkRow(data, fields.get('Preamble'), 'preamble');\n for (const name of new Set([...definitions, ...declared.keys()])) {\n const policy = declared.get(name) ?? {};\n const value = at(data, name);\n if (value === undefined) { if (policy.required) error(name, 'required', true, 'missing'); continue; }\n const kind = Array.isArray(value) ? 'list' : object(value) ? 'object' : 'scalar';\n if (policy.kind && policy.kind !== 'any' && policy.kind !== kind) { error(name, 'kind', policy.kind, kind); continue; }\n if (Array.isArray(value)) {\n for (const key of ['min_rows', 'max_rows']) if (policy[key] !== undefined && (key === 'min_rows' ? value.length < policy[key] : value.length > policy[key])) error(name, key, policy[key], value.length);\n if (fields.has(name)) value.forEach((row, i) => checkRow(row, fields.get(name), `${name}[${i}]`, policy.additional));\n } else if (fields.has(name)) checkRow(value, fields.get(name), name, policy.additional);\n }\n return { valid: errors.length === 0, errors };\n}\n"))
@@ -0,0 +1,2 @@
1
+ (module capsules.runtime.worker-value-codec
2
+ (js* "import {\n eliscriptSymbol,\n isEliscriptSymbol,\n isKeyword,\n keyword,\n} from \"./core/identifier.mjs\";\nimport {\n isPersistentList,\n persistentList,\n} from \"./core/list.mjs\";\nimport {\n isPersistentHashMap,\n persistentHashMap,\n} from \"./core/map.mjs\";\nimport { meta, withMeta } from \"./core/metadata.mjs\";\nimport {\n isPersistentHashSet,\n persistentHashSet,\n} from \"./core/set.mjs\";\nimport {\n isPersistentVector,\n persistentVector,\n} from \"./core/vector.mjs\";\n\nexport const workerValueEncoding = \"eliscript-value-v1\";\n\nexport const workerValueLimits = Object.freeze({\n maxDepth: 64,\n maxNodes: 100_000,\n maxCollectionLength: 100_000,\n});\n\nconst SPECIAL_NUMBERS = new Map([\n [\"nan\", Number.NaN],\n [\"positive-infinity\", Number.POSITIVE_INFINITY],\n [\"negative-infinity\", Number.NEGATIVE_INFINITY],\n [\"negative-zero\", -0],\n]);\nconst wireEncoder = new TextEncoder();\n\nexport class WorkerValueCodecError extends TypeError {\n constructor(code, message, path = \"$\") {\n super(`${message} at ${path}`);\n this.name = \"WorkerValueCodecError\";\n this.code = code;\n this.path = path;\n }\n}\n\nfunction normalizedLimits(options = {}) {\n const limits = { ...workerValueLimits, ...options };\n for (const name of Object.keys(workerValueLimits)) {\n if (!Number.isInteger(limits[name]) || limits[name] < 1) {\n throw new TypeError(`${name} must be a positive integer`);\n }\n }\n return limits;\n}\n\nfunction createState(mode, options) {\n return {\n active: new WeakSet(),\n limits: normalizedLimits(options),\n mode,\n nodes: 0,\n };\n}\n\nfunction visit(state, depth, path) {\n state.nodes += 1;\n if (state.nodes > state.limits.maxNodes) {\n throw new WorkerValueCodecError(\n `value-${state.mode}-limit`,\n `value exceeds ${state.limits.maxNodes} nodes`,\n path,\n );\n }\n if (depth > state.limits.maxDepth) {\n throw new WorkerValueCodecError(\n `value-${state.mode}-limit`,\n `value exceeds depth ${state.limits.maxDepth}`,\n path,\n );\n }\n}\n\nfunction collectionLength(state, length, path) {\n if (length > state.limits.maxCollectionLength) {\n throw new WorkerValueCodecError(\n `value-${state.mode}-limit`,\n `collection exceeds ${state.limits.maxCollectionLength} values`,\n path,\n );\n }\n}\n\nfunction withActive(state, value, path, operation) {\n if (state.active.has(value)) {\n throw new WorkerValueCodecError(\n \"value-encoding-cycle\",\n \"cyclic values are not transportable\",\n path,\n );\n }\n state.active.add(value);\n try {\n return operation();\n } finally {\n state.active.delete(value);\n }\n}\n\nfunction encodedMetadata(value, state, depth, path) {\n const metadata = meta(value);\n return metadata === null\n ? null\n : encodeValue(metadata, state, depth + 1, `${path}.metadata`);\n}\n\nfunction encodeSequence(tag, value, state, depth, path) {\n return withActive(state, value, path, () => {\n collectionLength(state, value.count, path);\n const values = [];\n let index = 0;\n for (const item of value) {\n values.push(encodeValue(item, state, depth + 1, `${path}[${index}]`));\n index += 1;\n }\n return [tag, values, encodedMetadata(value, state, depth, path)];\n });\n}\n\nfunction wireKey(value) {\n return wireEncoder.encode(JSON.stringify(value));\n}\n\nfunction compareWireKeys(left, right) {\n const length = Math.min(left.length, right.length);\n for (let index = 0; index < length; index += 1) {\n if (left[index] !== right[index]) return left[index] - right[index];\n }\n return left.length - right.length;\n}\n\nfunction compareWireValues(left, right) {\n return compareWireKeys(wireKey(left), wireKey(right));\n}\n\nfunction compareText(left, right) {\n return compareWireKeys(wireEncoder.encode(left), wireEncoder.encode(right));\n}\n\nfunction encodeMap(value, state, depth, path) {\n return withActive(state, value, path, () => {\n collectionLength(state, value.count, path);\n const entries = [];\n let index = 0;\n for (const [key, item] of value) {\n entries.push([\n encodeValue(key, state, depth + 1, `${path}.keys[${index}]`),\n encodeValue(item, state, depth + 1, `${path}.values[${index}]`),\n ]);\n index += 1;\n }\n entries.sort(compareWireValues);\n return [\"map\", entries, encodedMetadata(value, state, depth, path)];\n });\n}\n\nfunction encodeSet(value, state, depth, path) {\n return withActive(state, value, path, () => {\n collectionLength(state, value.count, path);\n const values = [];\n let index = 0;\n for (const item of value) {\n values.push(encodeValue(item, state, depth + 1, `${path}[${index}]`));\n index += 1;\n }\n values.sort(compareWireValues);\n return [\"set\", values, encodedMetadata(value, state, depth, path)];\n });\n}\n\nfunction encodeArray(value, state, depth, path) {\n return withActive(state, value, path, () => {\n collectionLength(state, value.length, path);\n const values = [];\n for (let index = 0; index < value.length; index += 1) {\n values.push(encodeValue(\n value[index],\n state,\n depth + 1,\n `${path}[${index}]`,\n ));\n }\n return [\n \"array\",\n values,\n ];\n });\n}\n\nfunction encodeObject(value, state, depth, path) {\n return withActive(state, value, path, () => {\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new WorkerValueCodecError(\n \"value-encoding-unsupported\",\n `unsupported object ${Object.prototype.toString.call(value)}`,\n path,\n );\n }\n const symbolKeys = Object.getOwnPropertySymbols(value).filter(\n (key) => Object.prototype.propertyIsEnumerable.call(value, key),\n );\n if (symbolKeys.length > 0) {\n throw new WorkerValueCodecError(\n \"value-encoding-unsupported\",\n \"host objects with enumerable Symbol keys are not transportable\",\n path,\n );\n }\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const keys = Object.keys(descriptors)\n .filter((key) => descriptors[key].enumerable)\n .sort(compareText);\n collectionLength(state, keys.length, path);\n const entries = keys.map((key) => {\n const descriptor = descriptors[key];\n if (!(\"value\" in descriptor)) {\n throw new WorkerValueCodecError(\n \"value-encoding-unsupported\",\n \"host object accessors are not transportable\",\n `${path}.${key}`,\n );\n }\n return [\n key,\n encodeValue(descriptor.value, state, depth + 1, `${path}.${key}`),\n ];\n });\n return [\"object\", entries];\n });\n}\n\nfunction encodeValue(value, state, depth, path) {\n visit(state, depth, path);\n if (value === null || typeof value === \"string\" ||\n typeof value === \"boolean\") {\n return value;\n }\n if (value === undefined) return [\"undefined\"];\n if (typeof value === \"number\") {\n if (Number.isNaN(value)) return [\"number\", \"nan\"];\n if (value === Number.POSITIVE_INFINITY) {\n return [\"number\", \"positive-infinity\"];\n }\n if (value === Number.NEGATIVE_INFINITY) {\n return [\"number\", \"negative-infinity\"];\n }\n if (Object.is(value, -0)) return [\"number\", \"negative-zero\"];\n return value;\n }\n if (isKeyword(value)) {\n return [\"keyword\", value.namespace, value.name];\n }\n if (isEliscriptSymbol(value)) {\n return withActive(state, value, path, () => [\n \"symbol\",\n value.namespace,\n value.name,\n encodedMetadata(value, state, depth, path),\n ]);\n }\n if (isPersistentList(value)) {\n return encodeSequence(\"list\", value, state, depth, path);\n }\n if (isPersistentVector(value)) {\n return encodeSequence(\"vector\", value, state, depth, path);\n }\n if (isPersistentHashMap(value)) {\n return encodeMap(value, state, depth, path);\n }\n if (isPersistentHashSet(value)) {\n return encodeSet(value, state, depth, path);\n }\n if (Array.isArray(value)) return encodeArray(value, state, depth, path);\n if (typeof value === \"object\") {\n return encodeObject(value, state, depth, path);\n }\n throw new WorkerValueCodecError(\n \"value-encoding-unsupported\",\n `unsupported ${typeof value} value`,\n path,\n );\n}\n\nfunction requireArray(value, message, path) {\n if (!Array.isArray(value)) {\n throw new WorkerValueCodecError(\"value-decoding-invalid\", message, path);\n }\n return value;\n}\n\nfunction requireTuple(node, length, tag, path) {\n if (node.length !== length) {\n throw new WorkerValueCodecError(\n \"value-decoding-invalid\",\n `${tag} node must contain ${length} fields`,\n path,\n );\n }\n}\n\nfunction requireName(value, label, path, allowNull = false) {\n if (allowNull && value === null) return null;\n if (typeof value !== \"string\" || value.length === 0) {\n throw new WorkerValueCodecError(\n \"value-decoding-invalid\",\n `${label} must be a non-empty string${allowNull ? \" or null\" : \"\"}`,\n path,\n );\n }\n return value;\n}\n\nfunction decodedMetadata(node, state, depth, path) {\n if (node === null) return null;\n const metadata = decodeValue(node, state, depth + 1, path);\n if (!isPersistentHashMap(metadata)) {\n throw new WorkerValueCodecError(\n \"value-decoding-invalid\",\n \"metadata must decode to a persistent Map\",\n path,\n );\n }\n return metadata;\n}\n\nfunction decodeSequence(node, state, depth, path, constructor) {\n requireTuple(node, 3, node[0], path);\n const values = requireArray(node[1], `${node[0]} values must be an array`, path);\n collectionLength(state, values.length, path);\n const decoded = values.map((value, index) =>\n decodeValue(value, state, depth + 1, `${path}[${index}]`));\n const result = constructor(...decoded);\n const metadata = decodedMetadata(\n node[2],\n state,\n depth,\n `${path}.metadata`,\n );\n return metadata === null ? result : withMeta(result, metadata);\n}\n\nfunction decodeMap(node, state, depth, path) {\n requireTuple(node, 3, \"map\", path);\n const entries = requireArray(node[1], \"map entries must be an array\", path);\n collectionLength(state, entries.length, path);\n let result = persistentHashMap();\n for (let index = 0; index < entries.length; index += 1) {\n const entry = requireArray(\n entries[index],\n \"map entry must be a two-field array\",\n `${path}[${index}]`,\n );\n requireTuple(entry, 2, \"map entry\", `${path}[${index}]`);\n const key = decodeValue(entry[0], state, depth + 1, `${path}.keys[${index}]`);\n if (result.has(key)) {\n throw new WorkerValueCodecError(\n \"value-decoding-invalid\",\n \"map contains an equivalent duplicate key\",\n `${path}.keys[${index}]`,\n );\n }\n const value = decodeValue(\n entry[1],\n state,\n depth + 1,\n `${path}.values[${index}]`,\n );\n result = result.assoc(key, value);\n }\n const metadata = decodedMetadata(\n node[2],\n state,\n depth,\n `${path}.metadata`,\n );\n return metadata === null ? result : withMeta(result, metadata);\n}\n\nfunction decodeSet(node, state, depth, path) {\n requireTuple(node, 3, \"set\", path);\n const values = requireArray(node[1], \"set values must be an array\", path);\n collectionLength(state, values.length, path);\n let result = persistentHashSet();\n for (let index = 0; index < values.length; index += 1) {\n const value = decodeValue(values[index], state, depth + 1, `${path}[${index}]`);\n if (result.has(value)) {\n throw new WorkerValueCodecError(\n \"value-decoding-invalid\",\n \"set contains an equivalent duplicate value\",\n `${path}[${index}]`,\n );\n }\n result = result.conj(value);\n }\n const metadata = decodedMetadata(\n node[2],\n state,\n depth,\n `${path}.metadata`,\n );\n return metadata === null ? result : withMeta(result, metadata);\n}\n\nfunction decodeArray(node, state, depth, path) {\n requireTuple(node, 2, \"array\", path);\n const values = requireArray(node[1], \"array values must be an array\", path);\n collectionLength(state, values.length, path);\n return values.map((value, index) =>\n decodeValue(value, state, depth + 1, `${path}[${index}]`));\n}\n\nfunction decodeObject(node, state, depth, path) {\n requireTuple(node, 2, \"object\", path);\n const entries = requireArray(node[1], \"object entries must be an array\", path);\n collectionLength(state, entries.length, path);\n const result = {};\n const keys = new Set();\n for (let index = 0; index < entries.length; index += 1) {\n const entry = requireArray(\n entries[index],\n \"object entry must be a two-field array\",\n `${path}[${index}]`,\n );\n requireTuple(entry, 2, \"object entry\", `${path}[${index}]`);\n const key = requireName(entry[0], \"object key\", `${path}.keys[${index}]`);\n if (keys.has(key)) {\n throw new WorkerValueCodecError(\n \"value-decoding-invalid\",\n `object contains duplicate key ${key}`,\n `${path}.keys[${index}]`,\n );\n }\n keys.add(key);\n Object.defineProperty(result, key, {\n configurable: true,\n enumerable: true,\n value: decodeValue(\n entry[1],\n state,\n depth + 1,\n `${path}.${key}`,\n ),\n writable: true,\n });\n }\n return result;\n}\n\nfunction decodeValue(node, state, depth, path) {\n visit(state, depth, path);\n if (node === null || typeof node === \"string\" ||\n typeof node === \"boolean\") {\n return node;\n }\n if (typeof node === \"number\") return node;\n requireArray(node, \"encoded value must be a scalar or tagged array\", path);\n if (node.length === 0 || typeof node[0] !== \"string\") {\n throw new WorkerValueCodecError(\n \"value-decoding-invalid\",\n \"encoded value tag must be a non-empty string\",\n path,\n );\n }\n switch (node[0]) {\n case \"undefined\":\n requireTuple(node, 1, \"undefined\", path);\n return undefined;\n case \"number\": {\n requireTuple(node, 2, \"number\", path);\n if (!SPECIAL_NUMBERS.has(node[1])) {\n throw new WorkerValueCodecError(\n \"value-decoding-invalid\",\n `unknown special number ${String(node[1])}`,\n path,\n );\n }\n return SPECIAL_NUMBERS.get(node[1]);\n }\n case \"keyword\": {\n requireTuple(node, 3, \"keyword\", path);\n const namespace = requireName(node[1], \"keyword namespace\", path, true);\n const name = requireName(node[2], \"keyword name\", path);\n return namespace === null ? keyword(name) : keyword(namespace, name);\n }\n case \"symbol\": {\n requireTuple(node, 4, \"symbol\", path);\n const namespace = requireName(node[1], \"symbol namespace\", path, true);\n const name = requireName(node[2], \"symbol name\", path);\n const result = namespace === null\n ? eliscriptSymbol(name)\n : eliscriptSymbol(namespace, name);\n const metadata = decodedMetadata(\n node[3],\n state,\n depth,\n `${path}.metadata`,\n );\n return metadata === null ? result : withMeta(result, metadata);\n }\n case \"list\":\n return decodeSequence(node, state, depth, path, persistentList);\n case \"vector\":\n return decodeSequence(node, state, depth, path, persistentVector);\n case \"map\":\n return decodeMap(node, state, depth, path);\n case \"set\":\n return decodeSet(node, state, depth, path);\n case \"array\":\n return decodeArray(node, state, depth, path);\n case \"object\":\n return decodeObject(node, state, depth, path);\n default:\n throw new WorkerValueCodecError(\n \"value-decoding-invalid\",\n `unknown value tag ${node[0]}`,\n path,\n );\n }\n}\n\nexport function encodeWorkerValue(value, options) {\n return encodeValue(value, createState(\"encoding\", options), 0, \"$\");\n}\n\nexport function encodeWorkerValues(values, options) {\n if (!Array.isArray(values)) {\n throw new TypeError(\"values must be an array\");\n }\n const state = createState(\"encoding\", options);\n collectionLength(state, values.length, \"$arguments\");\n return values.map((value, index) =>\n encodeValue(value, state, 0, `$arguments[${index}]`));\n}\n\nexport function decodeWorkerValue(value, options) {\n return decodeValue(value, createState(\"decoding\", options), 0, \"$\");\n}\n\nexport function decodeWorkerValues(values, options) {\n if (!Array.isArray(values)) {\n throw new WorkerValueCodecError(\n \"value-decoding-invalid\",\n \"encoded values must be an array\",\n \"$arguments\",\n );\n }\n const state = createState(\"decoding\", options);\n collectionLength(state, values.length, \"$arguments\");\n return values.map((value, index) =>\n decodeValue(value, state, 0, `$arguments[${index}]`));\n}\n"))
@@ -0,0 +1,2 @@
1
+ (module capsules.runtime.worker-value-stream
2
+ (js* "import { setImmediate as yieldToEventLoop } from \"node:timers/promises\";\n\nimport {\n eliscriptSymbol,\n isEliscriptSymbol,\n isKeyword,\n keyword,\n} from \"./core/identifier.mjs\";\nimport { EMPTY_LIST, isPersistentList } from \"./core/list.mjs\";\nimport {\n isPersistentHashMap,\n persistentHashMap,\n} from \"./core/map.mjs\";\nimport { meta, withMeta } from \"./core/metadata.mjs\";\nimport {\n isPersistentHashSet,\n persistentHashSet,\n} from \"./core/set.mjs\";\nimport {\n assocBang,\n conjBang,\n persistentBang,\n transient,\n} from \"./core/transient.mjs\";\nimport {\n isPersistentVector,\n persistentVector,\n} from \"./core/vector.mjs\";\n\nexport const workerValueFraming = \"eliscript-value-chunks-v1\";\n\nexport const workerValueStreamLimits = Object.freeze({\n maxDepth: 64,\n maxNodes: 8_000_000,\n maxCollectionLength: 4_000_000,\n maxStringUnits: 268_435_456,\n maxTotalStringUnits: 536_870_912,\n maxChunkBytes: 256 * 1024,\n maxEventsPerChunk: 512,\n maxTextPartUnits: 8_192,\n});\n\nconst SPECIAL_NUMBERS = new Map([\n [\"nan\", Number.NaN],\n [\"positive-infinity\", Number.POSITIVE_INFINITY],\n [\"negative-infinity\", Number.NEGATIVE_INFINITY],\n [\"negative-zero\", -0],\n]);\n\nexport class WorkerValueStreamError extends TypeError {\n constructor(code, message, path = \"$\") {\n super(`${message} at ${path}`);\n this.name = \"WorkerValueStreamError\";\n this.code = code;\n this.path = path;\n }\n}\n\nfunction normalizedLimits(options = {}) {\n const limits = { ...workerValueStreamLimits, ...options };\n for (const name of Object.keys(workerValueStreamLimits)) {\n if (!Number.isSafeInteger(limits[name]) || limits[name] < 1) {\n throw new TypeError(`${name} must be a positive safe integer`);\n }\n }\n if (limits.maxTextPartUnits < 2) {\n throw new TypeError(\"maxTextPartUnits must be at least 2\");\n }\n if (limits.maxTextPartUnits > limits.maxStringUnits) {\n throw new TypeError(\"maxTextPartUnits cannot exceed maxStringUnits\");\n }\n return limits;\n}\n\nfunction createState(mode, options) {\n return {\n active: new WeakSet(),\n limits: normalizedLimits(options),\n mode,\n nodes: 0,\n stringUnits: 0,\n };\n}\n\nfunction streamError(state, suffix, message, path) {\n throw new WorkerValueStreamError(\n `value-stream-${state.mode}-${suffix}`,\n message,\n path,\n );\n}\n\nfunction checkAbort(signal, path) {\n if (signal?.aborted) {\n throw new WorkerValueStreamError(\n \"value-stream-cancelled\",\n \"value stream traversal was cancelled\",\n path,\n );\n }\n}\n\nfunction visit(state, depth, path) {\n state.nodes += 1;\n if (state.nodes > state.limits.maxNodes) {\n streamError(\n state,\n \"limit\",\n `value stream exceeds ${state.limits.maxNodes} nodes`,\n path,\n );\n }\n if (depth > state.limits.maxDepth) {\n streamError(\n state,\n \"limit\",\n `value stream exceeds depth ${state.limits.maxDepth}`,\n path,\n );\n }\n}\n\nfunction collectionLength(state, length, path) {\n if (!Number.isSafeInteger(length) || length < 0) {\n streamError(state, \"invalid\", \"collection length must be a safe integer\", path);\n }\n if (length > state.limits.maxCollectionLength) {\n streamError(\n state,\n \"limit\",\n `collection exceeds ${state.limits.maxCollectionLength} values`,\n path,\n );\n }\n}\n\nfunction stringLength(state, length, path) {\n if (!Number.isSafeInteger(length) || length < 0) {\n streamError(state, \"invalid\", \"string length must be a safe integer\", path);\n }\n if (length > state.limits.maxStringUnits) {\n streamError(\n state,\n \"limit\",\n `string exceeds ${state.limits.maxStringUnits} UTF-16 units`,\n path,\n );\n }\n state.stringUnits += length;\n if (state.stringUnits > state.limits.maxTotalStringUnits) {\n streamError(\n state,\n \"limit\",\n `value stream exceeds ${state.limits.maxTotalStringUnits} string units`,\n path,\n );\n }\n}\n\nfunction activate(state, value, path) {\n if (state.active.has(value)) {\n streamError(state, \"cycle\", \"cyclic values are not transportable\", path);\n }\n state.active.add(value);\n}\n\nfunction textPartEnd(value, start, maximumUnits) {\n let end = Math.min(value.length, start + maximumUnits);\n if (end < value.length && end > start) {\n const previous = value.charCodeAt(end - 1);\n const next = value.charCodeAt(end);\n if (previous >= 0xd800 && previous <= 0xdbff &&\n next >= 0xdc00 && next <= 0xdfff) {\n end -= 1;\n }\n }\n return end === start ? Math.min(value.length, start + 1) : end;\n}\n\nasync function* encodeText(value, state, path, signal) {\n stringLength(state, value.length, path);\n yield [\"text\", value.length];\n for (let start = 0; start < value.length;) {\n checkAbort(signal, path);\n const end = textPartEnd(value, start, state.limits.maxTextPartUnits);\n yield [\"text-part\", value.slice(start, end)];\n start = end;\n }\n}\n\nfunction plainObjectEntries(value, state, path) {\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n streamError(\n state,\n \"unsupported\",\n `unsupported object ${Object.prototype.toString.call(value)}`,\n path,\n );\n }\n const symbolKeys = Object.getOwnPropertySymbols(value).filter(\n (key) => Object.prototype.propertyIsEnumerable.call(value, key),\n );\n if (symbolKeys.length > 0) {\n streamError(\n state,\n \"unsupported\",\n \"host objects with enumerable Symbol keys are not transportable\",\n path,\n );\n }\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const keys = Object.keys(descriptors).filter((key) => descriptors[key].enumerable);\n collectionLength(state, keys.length, path);\n return keys.map((key) => {\n const descriptor = descriptors[key];\n if (!(\"value\" in descriptor)) {\n streamError(\n state,\n \"unsupported\",\n \"host object accessors are not transportable\",\n `${path}.${key}`,\n );\n }\n return [key, descriptor.value];\n });\n}\n\nasync function* encodeValue(value, state, depth, path, signal) {\n checkAbort(signal, path);\n visit(state, depth, path);\n if (value === null || typeof value === \"boolean\") {\n yield [\"value\", value];\n return;\n }\n if (typeof value === \"string\") {\n yield* encodeText(value, state, path, signal);\n return;\n }\n if (value === undefined) {\n yield [\"undefined\"];\n return;\n }\n if (typeof value === \"number\") {\n if (Number.isNaN(value)) yield [\"number\", \"nan\"];\n else if (value === Number.POSITIVE_INFINITY) {\n yield [\"number\", \"positive-infinity\"];\n } else if (value === Number.NEGATIVE_INFINITY) {\n yield [\"number\", \"negative-infinity\"];\n } else if (Object.is(value, -0)) yield [\"number\", \"negative-zero\"];\n else yield [\"value\", value];\n return;\n }\n if (isKeyword(value)) {\n yield [\"open\", \"keyword\", 2];\n yield* encodeValue(value.namespace, state, depth + 1, `${path}.namespace`, signal);\n yield* encodeValue(value.name, state, depth + 1, `${path}.name`, signal);\n return;\n }\n if (isEliscriptSymbol(value)) {\n activate(state, value, path);\n try {\n yield [\"open\", \"symbol\", 3];\n yield* encodeValue(value.namespace, state, depth + 1, `${path}.namespace`, signal);\n yield* encodeValue(value.name, state, depth + 1, `${path}.name`, signal);\n yield* encodeValue(meta(value), state, depth + 1, `${path}.metadata`, signal);\n } finally {\n state.active.delete(value);\n }\n return;\n }\n if (isPersistentList(value) || isPersistentVector(value)) {\n activate(state, value, path);\n try {\n collectionLength(state, value.count, path);\n yield [\"open\", isPersistentList(value) ? \"list\" : \"vector\", value.count];\n let index = 0;\n for (const item of value) {\n yield* encodeValue(item, state, depth + 1, `${path}[${index}]`, signal);\n index += 1;\n }\n yield* encodeValue(meta(value), state, depth + 1, `${path}.metadata`, signal);\n } finally {\n state.active.delete(value);\n }\n return;\n }\n if (isPersistentHashMap(value)) {\n activate(state, value, path);\n try {\n collectionLength(state, value.count, path);\n yield [\"open\", \"map\", value.count];\n let index = 0;\n for (const [key, item] of value) {\n yield* encodeValue(key, state, depth + 1, `${path}.keys[${index}]`, signal);\n yield* encodeValue(item, state, depth + 1, `${path}.values[${index}]`, signal);\n index += 1;\n }\n yield* encodeValue(meta(value), state, depth + 1, `${path}.metadata`, signal);\n } finally {\n state.active.delete(value);\n }\n return;\n }\n if (isPersistentHashSet(value)) {\n activate(state, value, path);\n try {\n collectionLength(state, value.count, path);\n yield [\"open\", \"set\", value.count];\n let index = 0;\n for (const item of value) {\n yield* encodeValue(item, state, depth + 1, `${path}[${index}]`, signal);\n index += 1;\n }\n yield* encodeValue(meta(value), state, depth + 1, `${path}.metadata`, signal);\n } finally {\n state.active.delete(value);\n }\n return;\n }\n if (Array.isArray(value)) {\n activate(state, value, path);\n try {\n collectionLength(state, value.length, path);\n yield [\"open\", \"array\", value.length];\n for (let index = 0; index < value.length; index += 1) {\n yield* encodeValue(value[index], state, depth + 1, `${path}[${index}]`, signal);\n }\n } finally {\n state.active.delete(value);\n }\n return;\n }\n if (typeof value === \"object\") {\n activate(state, value, path);\n try {\n const entries = plainObjectEntries(value, state, path);\n yield [\"open\", \"object\", entries.length];\n for (let index = 0; index < entries.length; index += 1) {\n const [key, item] = entries[index];\n yield* encodeValue(key, state, depth + 1, `${path}.keys[${index}]`, signal);\n yield* encodeValue(item, state, depth + 1, `${path}.${key}`, signal);\n }\n } finally {\n state.active.delete(value);\n }\n return;\n }\n streamError(state, \"unsupported\", `unsupported ${typeof value} value`, path);\n}\n\nexport async function* encodeWorkerValueEvents(value, options = {}) {\n const { signal, ...limitOptions } = options;\n const state = createState(\"encoding\", limitOptions);\n yield* encodeValue(value, state, 0, \"$\", signal);\n}\n\nfunction eventBytes(event) {\n return Buffer.byteLength(JSON.stringify(event), \"utf8\");\n}\n\nexport async function* encodeWorkerValueChunks(value, options = {}) {\n const limits = normalizedLimits(options);\n let events = [];\n let bytes = 2;\n for await (const event of encodeWorkerValueEvents(value, options)) {\n const size = eventBytes(event);\n if (size + 2 > limits.maxChunkBytes) {\n throw new WorkerValueStreamError(\n \"value-stream-encoding-limit\",\n `one value event exceeds ${limits.maxChunkBytes} bytes`,\n );\n }\n const added = size + (events.length === 0 ? 0 : 1);\n if (events.length > 0 &&\n (bytes + added > limits.maxChunkBytes ||\n events.length >= limits.maxEventsPerChunk)) {\n yield events;\n await yieldToEventLoop();\n events = [];\n bytes = 2;\n }\n events.push(event);\n bytes += size + (events.length === 1 ? 0 : 1);\n }\n if (events.length > 0) yield events;\n}\n\nfunction requireEvent(event, length, tag, path) {\n if (!Array.isArray(event) || event.length !== length || event[0] !== tag) {\n throw new WorkerValueStreamError(\n \"value-stream-decoding-invalid\",\n `${tag} event must contain ${length} fields`,\n path,\n );\n }\n}\n\nfunction requireName(value, label, path, nullable = false) {\n if (nullable && value === null) return null;\n if (typeof value !== \"string\" || value.length === 0) {\n throw new WorkerValueStreamError(\n \"value-stream-decoding-invalid\",\n `${label} must be a non-empty string${nullable ? \" or null\" : \"\"}`,\n path,\n );\n }\n return value;\n}\n\nfunction metadata(value, path) {\n if (value === null) return null;\n if (!isPersistentHashMap(value)) {\n throw new WorkerValueStreamError(\n \"value-stream-decoding-invalid\",\n \"metadata must decode to a persistent Map\",\n path,\n );\n }\n return value;\n}\n\nfunction childPath(frame) {\n const index = frame.received;\n switch (frame.tag) {\n case \"keyword\":\n case \"symbol\":\n return `${frame.path}.${[\"namespace\", \"name\", \"metadata\"][index]}`;\n case \"list\":\n case \"vector\":\n case \"set\":\n return index < frame.length\n ? `${frame.path}[${index}]`\n : `${frame.path}.metadata`;\n case \"array\":\n return `${frame.path}[${index}]`;\n case \"map\":\n if (index === frame.length * 2) return `${frame.path}.metadata`;\n return index % 2 === 0\n ? `${frame.path}.keys[${index / 2}]`\n : `${frame.path}.values[${(index - 1) / 2}]`;\n case \"object\":\n return index % 2 === 0\n ? `${frame.path}.keys[${index / 2}]`\n : `${frame.path}.values[${(index - 1) / 2}]`;\n default:\n return frame.path;\n }\n}\n\nfunction makeFrame(tag, length, path, state) {\n if (typeof tag !== \"string\" || !Number.isSafeInteger(length) || length < 0) {\n streamError(state, \"invalid\", \"open event tag and length are invalid\", path);\n }\n if (tag === \"keyword\" && length !== 2) {\n streamError(state, \"invalid\", \"keyword open event must declare arity 2\", path);\n }\n if (tag === \"symbol\" && length !== 3) {\n streamError(state, \"invalid\", \"symbol open event must declare arity 3\", path);\n }\n if (![\"keyword\", \"symbol\", \"list\", \"vector\", \"map\", \"set\", \"array\", \"object\"].includes(tag)) {\n streamError(state, \"invalid\", `unknown open event tag ${tag}`, path);\n }\n if (![\"keyword\", \"symbol\"].includes(tag)) collectionLength(state, length, path);\n const expected = tag === \"keyword\" || tag === \"symbol\"\n ? length\n : tag === \"map\" || tag === \"object\"\n ? length * 2 + (tag === \"map\" ? 1 : 0)\n : length + ([\"list\", \"vector\", \"set\"].includes(tag) ? 1 : 0);\n const frame = { tag, length, path, expected, received: 0 };\n if ([\"keyword\", \"symbol\"].includes(tag)) frame.values = [];\n else if (tag === \"list\" || tag === \"array\") frame.values = [];\n else if (tag === \"vector\") frame.builder = transient(persistentVector());\n else if (tag === \"map\") frame.builder = transient(persistentHashMap());\n else if (tag === \"set\") frame.builder = transient(persistentHashSet());\n else if (tag === \"object\") {\n frame.value = {};\n frame.keys = new Set();\n }\n return frame;\n}\n\nfunction consumeFrame(frame, value) {\n const index = frame.received;\n switch (frame.tag) {\n case \"keyword\":\n case \"symbol\":\n frame.values.push(value);\n break;\n case \"list\":\n case \"array\":\n if (index < frame.length) frame.values.push(value);\n else frame.metadata = value;\n break;\n case \"vector\":\n if (index < frame.length) frame.builder = conjBang(frame.builder, value);\n else frame.metadata = value;\n break;\n case \"map\":\n if (index === frame.length * 2) frame.metadata = value;\n else if (index % 2 === 0) frame.key = value;\n else frame.builder = assocBang(frame.builder, frame.key, value);\n break;\n case \"set\":\n if (index < frame.length) frame.builder = conjBang(frame.builder, value);\n else frame.metadata = value;\n break;\n case \"object\":\n if (index % 2 === 0) {\n const key = requireName(value, \"object key\", childPath(frame));\n if (frame.keys.has(key)) {\n throw new WorkerValueStreamError(\n \"value-stream-decoding-invalid\",\n `object contains duplicate key ${key}`,\n childPath(frame),\n );\n }\n frame.keys.add(key);\n frame.key = key;\n } else {\n Object.defineProperty(frame.value, frame.key, {\n configurable: true,\n enumerable: true,\n value,\n writable: true,\n });\n }\n break;\n }\n frame.received += 1;\n}\n\nfunction finalizeFrame(frame) {\n switch (frame.tag) {\n case \"keyword\": {\n const namespace = requireName(\n frame.values[0],\n \"keyword namespace\",\n `${frame.path}.namespace`,\n true,\n );\n const name = requireName(frame.values[1], \"keyword name\", `${frame.path}.name`);\n return namespace === null ? keyword(name) : keyword(namespace, name);\n }\n case \"symbol\": {\n const namespace = requireName(\n frame.values[0],\n \"symbol namespace\",\n `${frame.path}.namespace`,\n true,\n );\n const name = requireName(frame.values[1], \"symbol name\", `${frame.path}.name`);\n const result = namespace === null\n ? eliscriptSymbol(name)\n : eliscriptSymbol(namespace, name);\n const valueMetadata = metadata(frame.values[2], `${frame.path}.metadata`);\n return valueMetadata === null ? result : withMeta(result, valueMetadata);\n }\n case \"list\": {\n let result = EMPTY_LIST;\n for (let index = frame.values.length - 1; index >= 0; index -= 1) {\n result = result.conj(frame.values[index]);\n }\n const valueMetadata = metadata(frame.metadata, `${frame.path}.metadata`);\n return valueMetadata === null ? result : withMeta(result, valueMetadata);\n }\n case \"vector\": {\n const result = persistentBang(frame.builder);\n const valueMetadata = metadata(frame.metadata, `${frame.path}.metadata`);\n return valueMetadata === null ? result : withMeta(result, valueMetadata);\n }\n case \"map\": {\n const result = persistentBang(frame.builder);\n if (result.count !== frame.length) {\n throw new WorkerValueStreamError(\n \"value-stream-decoding-invalid\",\n \"map contains an equivalent duplicate key\",\n frame.path,\n );\n }\n const valueMetadata = metadata(frame.metadata, `${frame.path}.metadata`);\n return valueMetadata === null ? result : withMeta(result, valueMetadata);\n }\n case \"set\": {\n const result = persistentBang(frame.builder);\n if (result.count !== frame.length) {\n throw new WorkerValueStreamError(\n \"value-stream-decoding-invalid\",\n \"set contains an equivalent duplicate value\",\n frame.path,\n );\n }\n const valueMetadata = metadata(frame.metadata, `${frame.path}.metadata`);\n return valueMetadata === null ? result : withMeta(result, valueMetadata);\n }\n case \"array\":\n return frame.values;\n case \"object\":\n return frame.value;\n default:\n throw new WorkerValueStreamError(\n \"value-stream-decoding-invalid\",\n `cannot finalize unknown container ${frame.tag}`,\n frame.path,\n );\n }\n}\n\nexport class WorkerValueStreamDecoder {\n constructor(options = {}) {\n this.state = createState(\"decoding\", options);\n this.signal = options.signal;\n this.stack = [];\n this.text = undefined;\n this.hasRoot = false;\n this.root = undefined;\n this.finished = false;\n }\n\n currentPath() {\n const frame = this.stack.at(-1);\n return frame ? childPath(frame) : \"$\";\n }\n\n accept(value) {\n let completed = value;\n while (true) {\n const frame = this.stack.at(-1);\n if (!frame) {\n if (this.hasRoot) {\n streamError(this.state, \"invalid\", \"value stream contains multiple roots\", \"$\");\n }\n this.root = completed;\n this.hasRoot = true;\n return;\n }\n consumeFrame(frame, completed);\n if (frame.received < frame.expected) return;\n this.stack.pop();\n completed = finalizeFrame(frame);\n }\n }\n\n startText(length, path) {\n stringLength(this.state, length, path);\n if (length === 0) {\n this.accept(\"\");\n return;\n }\n this.text = { path, remaining: length, parts: [] };\n }\n\n writeTextPart(event) {\n requireEvent(event, 2, \"text-part\", this.text.path);\n const part = event[1];\n if (typeof part !== \"string\" || part.length === 0) {\n streamError(this.state, \"invalid\", \"text-part payload must be non-empty\", this.text.path);\n }\n if (part.length > this.text.remaining) {\n streamError(this.state, \"invalid\", \"text parts exceed declared string length\", this.text.path);\n }\n this.text.parts.push(part);\n this.text.remaining -= part.length;\n if (this.text.remaining === 0) {\n const value = this.text.parts.join(\"\");\n this.text = undefined;\n this.accept(value);\n }\n }\n\n writeEvent(event) {\n checkAbort(this.signal, this.currentPath());\n if (this.finished) {\n streamError(this.state, \"invalid\", \"cannot write after stream completion\", \"$\");\n }\n if (this.text) {\n this.writeTextPart(event);\n return;\n }\n if (!Array.isArray(event) || event.length === 0 || typeof event[0] !== \"string\") {\n streamError(this.state, \"invalid\", \"value event must be a tagged array\", this.currentPath());\n }\n const path = this.currentPath();\n switch (event[0]) {\n case \"value\":\n requireEvent(event, 2, \"value\", path);\n if (!(event[1] === null || typeof event[1] === \"boolean\" ||\n (typeof event[1] === \"number\" && Number.isFinite(event[1])))) {\n streamError(this.state, \"invalid\", \"value event contains an invalid scalar\", path);\n }\n visit(this.state, this.stack.length, path);\n this.accept(event[1]);\n break;\n case \"undefined\":\n requireEvent(event, 1, \"undefined\", path);\n visit(this.state, this.stack.length, path);\n this.accept(undefined);\n break;\n case \"number\":\n requireEvent(event, 2, \"number\", path);\n if (!SPECIAL_NUMBERS.has(event[1])) {\n streamError(this.state, \"invalid\", `unknown special number ${String(event[1])}`, path);\n }\n visit(this.state, this.stack.length, path);\n this.accept(SPECIAL_NUMBERS.get(event[1]));\n break;\n case \"text\":\n requireEvent(event, 2, \"text\", path);\n visit(this.state, this.stack.length, path);\n this.startText(event[1], path);\n break;\n case \"open\": {\n requireEvent(event, 3, \"open\", path);\n visit(this.state, this.stack.length, path);\n const frame = makeFrame(event[1], event[2], path, this.state);\n this.stack.push(frame);\n if (frame.expected === 0) {\n this.stack.pop();\n this.accept(finalizeFrame(frame));\n }\n break;\n }\n default:\n streamError(this.state, \"invalid\", `unknown value event ${event[0]}`, path);\n }\n }\n\n write(events) {\n if (!Array.isArray(events)) {\n streamError(this.state, \"invalid\", \"value chunk events must be an array\", this.currentPath());\n }\n let bytes;\n try {\n bytes = Buffer.byteLength(JSON.stringify(events), \"utf8\");\n } catch (error) {\n streamError(\n this.state,\n \"invalid\",\n `value chunk is not JSON-serializable: ${error.message}`,\n this.currentPath(),\n );\n }\n if (bytes > this.state.limits.maxChunkBytes) {\n streamError(\n this.state,\n \"limit\",\n `value chunk exceeds ${this.state.limits.maxChunkBytes} bytes`,\n this.currentPath(),\n );\n }\n if (events.length > this.state.limits.maxEventsPerChunk) {\n streamError(\n this.state,\n \"limit\",\n `value chunk exceeds ${this.state.limits.maxEventsPerChunk} events`,\n this.currentPath(),\n );\n }\n for (const event of events) this.writeEvent(event);\n return this;\n }\n\n finish() {\n checkAbort(this.signal, this.currentPath());\n if (this.finished) {\n streamError(this.state, \"invalid\", \"value stream was already completed\", \"$\");\n }\n if (this.text) {\n streamError(this.state, \"truncated\", \"value stream ended inside a string\", this.text.path);\n }\n if (this.stack.length > 0) {\n streamError(this.state, \"truncated\", \"value stream ended inside a container\", this.currentPath());\n }\n if (!this.hasRoot) {\n streamError(this.state, \"truncated\", \"value stream did not contain a root\", \"$\");\n }\n this.finished = true;\n return this.root;\n }\n}\n\nexport async function decodeWorkerValueChunks(chunks, options = {}) {\n const decoder = new WorkerValueStreamDecoder(options);\n for await (const events of chunks) decoder.write(events);\n return decoder.finish();\n}\n"))
@@ -0,0 +1,2 @@
1
+ (module capsules.runtime.worker
2
+ (js* "#!/usr/bin/env bun\n\nimport { createHash } from \"node:crypto\";\nimport { once } from \"node:events\";\nimport { readFile, realpath, stat } from \"node:fs/promises\";\nimport { dirname, isAbsolute, relative, resolve, sep } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { workerCapabilities } from \"../platform/worker.mjs\";\nimport {\n decodeWorkerValues,\n encodeWorkerValue,\n workerValueEncoding,\n} from \"./worker-value-codec.mjs\";\nimport {\n WorkerValueStreamDecoder,\n encodeWorkerValueChunks,\n workerValueFraming,\n workerValueStreamLimits,\n} from \"./worker-value-stream.mjs\";\nimport {\n decodeSourceMappings,\n mapSourceFrames,\n parseJavaScriptStack,\n} from \"./source-mapping.mjs\";\n\nexport const protocolVersion = 1;\nconst runtimeDirectory = dirname(fileURLToPath(import.meta.url));\nconst packageDirectories = new Map([\n [\"eliscript/platform/\", resolve(runtimeDirectory, \"../platform\")],\n [\"eliscript/runtime/\", runtimeDirectory],\n]);\n\nfunction installPackageResolver() {\n Bun.plugin({\n name: \"eliscript-worker-package\",\n setup(build) {\n build.onResolve(\n { filter: /^eliscript\\/(?:platform|runtime)\\// },\n ({ path: specifier }) => {\n const [prefix, directory] = [...packageDirectories].find(\n ([candidate]) => specifier.startsWith(candidate),\n );\n const suffix = specifier.slice(prefix.length);\n const target = resolve(directory, suffix);\n const local = relative(directory, target);\n if (suffix.length === 0 || isAbsolute(local) ||\n local === \"..\" || local.startsWith(`..${sep}`)) {\n const area = prefix.split(\"/\")[1];\n throw new Error(\n `worker ${area} import escapes package ${area}: ${specifier}`,\n );\n }\n return { namespace: \"file\", path: target };\n },\n );\n },\n });\n}\n\ninstallPackageResolver();\n\nexport const capabilities = Object.freeze([\n \"request\",\n \"progress\",\n \"cancel\",\n \"timeout\",\n \"shutdown\",\n \"module-cache\",\n \"module-version\",\n \"operation-capabilities-v1\",\n \"project-manifest\",\n \"portable-manifest\",\n \"runtime-resolution\",\n \"value-codec-v1\",\n \"value-chunks-v1\",\n]);\n\nconst maximumLineBytes = 16 * 1024 * 1024;\nconst maximumValueChunkLineBytes = workerValueStreamLimits.maxChunkBytes + 4096;\nconst maximumValueStreamBytes = 768 * 1024 * 1024;\nconst moduleCache = new Map();\nconst pending = new Map();\nconst protocolOutput = process.stdout;\nlet shuttingDown = false;\n\nfor (const method of [\"log\", \"info\", \"debug\"]) {\n console[method] = (...values) => console.error(...values);\n}\n\nfunction normalizeWorkerStackFile(file) {\n if (!file.startsWith(\"file:\")) return file;\n try {\n return fileURLToPath(file);\n } catch {\n return file;\n }\n}\n\nfunction errorPayload(code, message, error, sourceMaps) {\n const payload = { code, message };\n if (error?.name) payload.name = error.name;\n if (error?.path) payload.path = error.path;\n if (error?.stack) {\n payload.stack = error.stack;\n const frames = mapSourceFrames(\n parseJavaScriptStack(error.stack, { normalizeFile: normalizeWorkerStackFile }),\n sourceMaps ?? [],\n );\n if (frames.length > 0) {\n payload.frames = frames;\n payload.location = frames.find((frame) => frame.file.endsWith(\".eli\")) ??\n frames[0];\n }\n }\n return payload;\n}\n\nfunction encodeMessage(message) {\n let encoded;\n try {\n encoded = JSON.stringify(message);\n } catch (error) {\n encoded = JSON.stringify({\n version: protocolVersion,\n type: \"protocol-error\",\n error: errorPayload(\n \"serialization\",\n `worker could not serialize a protocol message: ${error.message}`,\n error,\n ),\n });\n }\n return `${encoded}\\n`;\n}\n\nfunction writeMessage(message) {\n protocolOutput.write(encodeMessage(message));\n}\n\nasync function writeMessageAsync(message) {\n if (!protocolOutput.write(encodeMessage(message))) {\n await once(protocolOutput, \"drain\");\n }\n}\n\nfunction jsonValue(value, label) {\n let encoded;\n try {\n encoded = JSON.stringify(value);\n } catch (error) {\n const wrapped = new Error(`${label} is not JSON-serializable: ${error.message}`);\n wrapped.code = \"serialization\";\n throw wrapped;\n }\n if (encoded === undefined) {\n const error = new Error(`${label} is not JSON-serializable`);\n error.code = \"serialization\";\n throw error;\n }\n return JSON.parse(encoded);\n}\n\nfunction requestError(id, code, message, error, timing, sourceMaps) {\n const response = {\n version: protocolVersion,\n type: \"response\",\n id,\n ok: false,\n error: errorPayload(code, message, error, sourceMaps),\n };\n if (timing) response.timing = timing;\n writeMessage(response);\n}\n\nfunction protocolError(code, message, id) {\n const response = {\n version: protocolVersion,\n type: \"protocol-error\",\n error: errorPayload(code, message),\n };\n if (id !== undefined) response.id = id;\n writeMessage(response);\n}\n\nfunction moduleUrl(identity) {\n let url;\n try {\n url = new URL(identity);\n } catch {\n url = pathToFileURL(resolve(identity));\n }\n if (url.protocol !== \"file:\") {\n throw new Error(`worker modules must use local file URLs: ${identity}`);\n }\n return url.href;\n}\n\nexport async function loadSourceMap(moduleUrl_) {\n try {\n const cleanUrl = new URL(moduleUrl_);\n cleanUrl.search = \"\";\n cleanUrl.hash = \"\";\n const javascript = await readFile(fileURLToPath(cleanUrl), \"utf8\");\n const match = javascript.match(/\\/\\/# sourceMappingURL=([^\\s]+)\\s*$/);\n if (!match || match[1].startsWith(\"data:\")) return undefined;\n const mapUrl = new URL(match[1], cleanUrl);\n const map = JSON.parse(await readFile(fileURLToPath(mapUrl), \"utf8\"));\n if (map.version !== 3 || typeof map.mappings !== \"string\" ||\n !Array.isArray(map.sources)) return undefined;\n return {\n generatedFile: resolve(await realpath(fileURLToPath(cleanUrl))),\n sources: map.sources.map((source) => {\n const sourceUrl = new URL(source, mapUrl);\n return sourceUrl.protocol === \"file:\"\n ? resolve(fileURLToPath(sourceUrl))\n : sourceUrl.href;\n }),\n lines: decodeSourceMappings(map.mappings),\n };\n } catch (error) {\n console.error(`could not load source map for ${moduleUrl_}: ${error.message}`);\n return undefined;\n }\n}\n\nasync function moduleFingerprint(url) {\n const fileUrl = new URL(url);\n fileUrl.search = \"\";\n fileUrl.hash = \"\";\n const metadata = await stat(fileURLToPath(fileUrl), { bigint: true });\n return `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeNs}`;\n}\n\nfunction projectManifestError(message) {\n const error = new Error(message);\n error.code = \"invalid-project-manifest\";\n return error;\n}\n\nfunction projectFile(root, value, label) {\n if (typeof value !== \"string\" || value.length === 0 || isAbsolute(value)) {\n throw projectManifestError(`${label} must be a non-empty relative path`);\n }\n const path = resolve(root, value);\n const fromRoot = relative(root, path);\n if (fromRoot === \"..\" || fromRoot.startsWith(`..${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`) ||\n isAbsolute(fromRoot)) {\n throw projectManifestError(`${label} escapes the project output directory`);\n }\n return path;\n}\n\nasync function fileDigest(path) {\n return createHash(\"sha256\").update(await readFile(path)).digest(\"hex\");\n}\n\nfunction textDigest(value) {\n return createHash(\"sha256\").update(value, \"utf8\").digest(\"hex\");\n}\n\nasync function readProjectManifest(identity, entryUrl) {\n const url = moduleUrl(identity);\n let path;\n try {\n path = await realpath(fileURLToPath(url));\n } catch (error) {\n throw projectManifestError(`could not resolve project manifest: ${error.message}`);\n }\n const root = dirname(path);\n let manifest;\n try {\n manifest = JSON.parse(await readFile(path, \"utf8\"));\n } catch (error) {\n throw projectManifestError(`could not read project manifest: ${error.message}`);\n }\n if (manifest.format !== \"eliscript-project\" ||\n (manifest.version !== 1 && manifest.version !== 2) ||\n typeof manifest.digest !== \"string\" ||\n !/^[0-9a-f]{64}$/.test(manifest.digest) ||\n !Array.isArray(manifest.modules)) {\n throw projectManifestError(\"project manifest has an unsupported shape\");\n }\n const manifestEntries = manifest.version === 1\n ? [manifest.entry]\n : manifest.entries;\n if (!Array.isArray(manifestEntries) || manifestEntries.length === 0 ||\n new Set(manifestEntries).size !== manifestEntries.length ||\n [...manifestEntries].sort().some((entry, index) =>\n entry !== manifestEntries[index])) {\n throw projectManifestError(\"project manifest entries have an unsupported shape\");\n }\n const entries = manifestEntries.map((entry, index) =>\n projectFile(root, entry, `manifest entry ${index}`));\n let canonicalEntries;\n let canonicalModule;\n try {\n [canonicalEntries, canonicalModule] = await Promise.all([\n Promise.all(entries.map((entry) => realpath(entry))),\n realpath(fileURLToPath(entryUrl)),\n ]);\n } catch (error) {\n throw projectManifestError(`could not resolve project entry: ${error.message}`);\n }\n if (!canonicalEntries.includes(canonicalModule)) {\n throw projectManifestError(\"project manifest entry does not match request module\");\n }\n const identityModules = [];\n const modules = manifest.modules.map((module, index) => {\n if (!module || typeof module !== \"object\" ||\n typeof module.source !== \"string\" || module.source.length === 0 ||\n isAbsolute(module.source) ||\n module.source.split(/[\\\\/]/).includes(\"..\") ||\n !/^[0-9a-f]{64}$/.test(module.sourceDigest ?? \"\") ||\n !/^[0-9a-f]{64}$/.test(module.outputDigest ?? \"\") ||\n !/^[0-9a-f]{64}$/.test(module.sourceMapDigest ?? \"\")) {\n throw projectManifestError(`manifest module ${index} has an unsupported shape`);\n }\n identityModules.push({\n source: module.source,\n output: module.output,\n sourceMap: module.sourceMap,\n sourceDigest: module.sourceDigest,\n outputDigest: module.outputDigest,\n sourceMapDigest: module.sourceMapDigest,\n });\n return {\n output: projectFile(root, module.output, `manifest module ${index} output`),\n sourceMap: projectFile(\n root,\n module.sourceMap,\n `manifest module ${index} source map`,\n ),\n outputDigest: module.outputDigest,\n sourceMapDigest: module.sourceMapDigest,\n };\n });\n const declaredOutputs = new Set(identityModules.map((module) => module.output));\n if (manifestEntries.some((entry) => !declaredOutputs.has(entry))) {\n throw projectManifestError(\"project manifest does not describe every entry artifact\");\n }\n const graphIdentity = manifest.version === 1\n ? {\n format: manifest.format,\n version: manifest.version,\n entry: manifest.entry,\n modules: identityModules,\n }\n : {\n format: manifest.format,\n version: manifest.version,\n entries: manifest.entries,\n modules: identityModules,\n };\n if (textDigest(JSON.stringify(graphIdentity)) !== manifest.digest) {\n throw projectManifestError(\"project manifest graph digest does not match its records\");\n }\n return { digest: manifest.digest, modules };\n}\n\nasync function loadProjectArtifacts(project) {\n const sourceMaps = await Promise.all(project.modules.map(async (module) => {\n let outputDigest;\n let sourceMapDigest;\n try {\n [outputDigest, sourceMapDigest] = await Promise.all([\n fileDigest(module.output),\n fileDigest(module.sourceMap),\n ]);\n } catch (error) {\n throw projectManifestError(\n `could not verify generated module ${module.output}: ${error.message}`,\n );\n }\n if (outputDigest !== module.outputDigest ||\n sourceMapDigest !== module.sourceMapDigest) {\n throw projectManifestError(\n `generated module does not match project manifest: ${module.output}`,\n );\n }\n return loadSourceMap(pathToFileURL(module.output).href);\n }));\n return sourceMaps.filter(Boolean);\n}\n\nasync function loadModule(identity, requestedVersion, projectManifest) {\n const url = moduleUrl(identity);\n const projectPromise = projectManifest === undefined\n ? Promise.resolve(undefined)\n : readProjectManifest(projectManifest, url);\n const discoveredProject = projectManifest !== undefined &&\n requestedVersion === undefined\n ? await projectPromise\n : undefined;\n const version = discoveredProject?.digest ?? requestedVersion ??\n await moduleFingerprint(url);\n const cacheKey = `${url}\\n${projectManifest === undefined ? \"\" : moduleUrl(projectManifest)}`;\n const cached = moduleCache.get(cacheKey);\n if (cached?.version === version) {\n const loaded = await cached.promise;\n return { ...loaded, cacheHit: true, version };\n }\n if (cached) {\n const error = new Error(\n `module version changed from ${cached.version} to ${version}; restart the worker before loading it`,\n );\n error.code = \"module-version-changed\";\n throw error;\n }\n const importUrl = new URL(url);\n importUrl.searchParams.set(\"__eliscript_worker_version\", version);\n const entry = {\n version,\n promise: (async () => {\n const project = discoveredProject ?? await projectPromise;\n if (project && version !== project.digest) {\n const error = new Error(\n `requested module version ${version} does not match project manifest ${project.digest}`,\n );\n error.code = \"module-version-mismatch\";\n throw error;\n }\n const [module, sourceMaps] = await Promise.all([\n import(importUrl.href),\n project\n ? loadProjectArtifacts(project)\n : loadSourceMap(url).then((sourceMap) => sourceMap ? [sourceMap] : []),\n ]);\n return { module, sourceMaps };\n })(),\n };\n moduleCache.set(cacheKey, entry);\n try {\n const loaded = await entry.promise;\n return { ...loaded, cacheHit: false, version };\n } catch (error) {\n if (moduleCache.get(cacheKey) === entry) moduleCache.delete(cacheKey);\n throw error;\n }\n}\n\nfunction validateRequest(message) {\n if (typeof message.id !== \"string\" || message.id.length === 0) {\n throw new Error(\"request id must be a non-empty string\");\n }\n if (typeof message.module !== \"string\" || message.module.length === 0) {\n throw new Error(\"request module must be a non-empty string\");\n }\n const hasExport = typeof message.export === \"string\" && message.export.length > 0;\n const hasOperation = typeof message.operation === \"string\" &&\n message.operation.length > 0;\n if (hasExport === hasOperation) {\n throw new Error(\n \"request must contain exactly one non-empty export or operation\",\n );\n }\n const usesValueChunks = message.valueFraming === workerValueFraming;\n if (message.valueFraming !== undefined && !usesValueChunks) {\n throw new Error(`request valueFraming must be ${workerValueFraming}`);\n }\n if (usesValueChunks) {\n if (message.valueEncoding !== workerValueEncoding) {\n throw new Error(\n `chunked requests require valueEncoding ${workerValueEncoding}`,\n );\n }\n if (message.arguments !== undefined) {\n throw new Error(\"chunked requests must stream arguments after the request header\");\n }\n } else if (!Array.isArray(message.arguments)) {\n throw new Error(\"request arguments must be an array\");\n }\n if (message.valueEncoding !== undefined &&\n message.valueEncoding !== workerValueEncoding) {\n throw new Error(\n `request valueEncoding must be ${workerValueEncoding}`,\n );\n }\n if (message.moduleVersion !== undefined &&\n (typeof message.moduleVersion !== \"string\" ||\n message.moduleVersion.length === 0 || message.moduleVersion.length > 512)) {\n throw new Error(\"request moduleVersion must be a non-empty string up to 512 characters\");\n }\n if (message.projectManifest !== undefined &&\n (typeof message.projectManifest !== \"string\" ||\n message.projectManifest.length === 0)) {\n throw new Error(\"request projectManifest must be a non-empty string\");\n }\n if (message.timeoutMs !== undefined &&\n (!Number.isInteger(message.timeoutMs) || message.timeoutMs <= 0 ||\n message.timeoutMs > 2_147_483_647)) {\n throw new Error(\"request timeoutMs must be a positive 32-bit integer\");\n }\n}\n\nfunction closeEntry(id, entry) {\n if (entry.timer !== undefined) clearTimeout(entry.timer);\n if (pending.get(id) === entry) pending.delete(id);\n}\n\nfunction receivingError(entry, code, message, error = undefined) {\n requestError(entry.message.id, code, message, error);\n closeEntry(entry.message.id, entry);\n}\n\nfunction createEntry(message, phase) {\n const entry = {\n controller: new AbortController(),\n abortCode: \"cancelled\",\n timer: undefined,\n phase,\n message,\n startedAt: performance.now(),\n progressIndex: 0,\n progressQueue: Promise.resolve(),\n progressError: undefined,\n };\n pending.set(message.id, entry);\n if (message.timeoutMs !== undefined) {\n entry.timer = setTimeout(() => {\n entry.abortCode = \"timeout\";\n entry.controller.abort();\n if (entry.phase === \"receiving\") {\n const error = new Error(\"request timed out while receiving value chunks\");\n error.code = \"timeout\";\n receivingError(entry, \"timeout\", error.message, error);\n }\n }, message.timeoutMs);\n }\n return entry;\n}\n\nfunction abortPromise(entry) {\n return new Promise((_, reject) => {\n entry.controller.signal.addEventListener(\"abort\", () => {\n const error = new Error(\n entry.abortCode === \"timeout\" ? \"request timed out\" : \"request cancelled\",\n );\n error.code = entry.abortCode;\n reject(error);\n }, { once: true });\n });\n}\n\nasync function writeValueStream({\n id,\n channel,\n stream,\n value,\n signal,\n finalFields,\n}) {\n const iterator = encodeWorkerValueChunks(value, { signal })[Symbol.asyncIterator]();\n let sequence = 0;\n let current = await iterator.next();\n if (current.done) {\n throw new Error(\"value stream encoder produced no events\");\n }\n while (!current.done) {\n const next = await iterator.next();\n const final = next.done;\n const message = {\n version: protocolVersion,\n type: \"value-chunk\",\n id,\n channel,\n sequence,\n final,\n valueEncoding: workerValueEncoding,\n valueFraming: workerValueFraming,\n events: current.value,\n };\n if (stream !== undefined) message.stream = stream;\n if (final && finalFields) {\n Object.assign(message, finalFields({\n sequence,\n chunkCount: sequence + 1,\n }));\n }\n await writeMessageAsync(message);\n current = next;\n sequence += 1;\n }\n}\n\nfunction queueProgress(entry, value) {\n const stream = String(++entry.progressIndex);\n const task = entry.progressQueue.then(() => writeValueStream({\n id: entry.message.id,\n channel: \"progress\",\n stream,\n value,\n signal: entry.controller.signal,\n }));\n entry.progressQueue = task.catch((error) => {\n if (entry.progressError === undefined) entry.progressError = error;\n });\n return task;\n}\n\nasync function executeRequest(message, entry, streamedArguments = undefined) {\n const startedAt = entry.startedAt;\n let moduleLoadMs = 0;\n let executionMs = 0;\n let serializationMs = 0;\n let moduleCacheHit = false;\n let moduleVersion;\n let sourceMaps = [];\n let executionStartedAt;\n entry.phase = \"executing\";\n\n try {\n const moduleLoadStartedAt = performance.now();\n const loaded = await loadModule(\n message.module,\n message.moduleVersion,\n message.projectManifest,\n );\n const module = loaded.module;\n sourceMaps = loaded.sourceMaps;\n moduleCacheHit = loaded.cacheHit;\n moduleVersion = loaded.version;\n moduleLoadMs = performance.now() - moduleLoadStartedAt;\n const manifest = module.__eliscript_portable__;\n const operation = message.operation === undefined\n ? module[message.export]\n : manifest && Object.hasOwn(manifest, message.operation)\n ? manifest[message.operation]\n : undefined;\n if (typeof operation !== \"function\") {\n const operationName = message.operation ?? message.export;\n const error = new Error(\n message.operation === undefined\n ? `module does not export a function named ${operationName}`\n : `module does not declare a portable function named ${operationName}`,\n );\n error.code = message.operation === undefined\n ? \"missing-export\"\n : \"missing-portable\";\n throw error;\n }\n const usesValueCodec = message.valueEncoding === workerValueEncoding;\n const usesValueChunks = message.valueFraming === workerValueFraming;\n const arguments_ = streamedArguments !== undefined\n ? streamedArguments\n : usesValueCodec\n ? decodeWorkerValues(message.arguments)\n : message.arguments;\n const progress = (value) => {\n if (entry.controller.signal.aborted) return;\n if (usesValueChunks) return queueProgress(entry, value);\n const response = {\n version: protocolVersion,\n type: \"progress\",\n id: message.id,\n value: usesValueCodec\n ? encodeWorkerValue(value)\n : jsonValue(value, \"progress value\"),\n };\n if (usesValueCodec) response.valueEncoding = workerValueEncoding;\n writeMessage(response);\n };\n const context = Object.freeze({\n signal: entry.controller.signal,\n progress,\n capabilities: workerCapabilities(\n { signal: entry.controller.signal, progress },\n [\"cancellation\", \"progress\"],\n ),\n });\n executionStartedAt = performance.now();\n const operationPromise = Promise.resolve(\n operation(...arguments_, context),\n );\n const value = await Promise.race([operationPromise, abortPromise(entry)]);\n executionMs = performance.now() - executionStartedAt;\n await entry.progressQueue;\n if (entry.progressError !== undefined) throw entry.progressError;\n const serializationStartedAt = performance.now();\n if (usesValueChunks) {\n await writeValueStream({\n id: message.id,\n channel: \"response\",\n value,\n signal: entry.controller.signal,\n finalFields({ chunkCount }) {\n serializationMs = performance.now() - serializationStartedAt;\n return {\n timing: {\n moduleLoadMs,\n moduleCacheHit,\n moduleVersion,\n sourceMapLoaded: sourceMaps.length > 0,\n sourceMapCount: sourceMaps.length,\n executionMs,\n serializationMs,\n workerMs: performance.now() - startedAt,\n valueStream: {\n framing: workerValueFraming,\n argumentChunks: entry.sequence,\n responseChunks: chunkCount,\n maxChunkBytes: workerValueStreamLimits.maxChunkBytes,\n maxEventsPerChunk: workerValueStreamLimits.maxEventsPerChunk,\n maxTextPartUnits: workerValueStreamLimits.maxTextPartUnits,\n },\n },\n };\n },\n });\n return;\n }\n const serializedValue = usesValueCodec\n ? encodeWorkerValue(value)\n : jsonValue(value, \"response value\");\n serializationMs = performance.now() - serializationStartedAt;\n const response = {\n version: protocolVersion,\n type: \"response\",\n id: message.id,\n ok: true,\n value: serializedValue,\n timing: {\n moduleLoadMs,\n moduleCacheHit,\n moduleVersion,\n sourceMapLoaded: sourceMaps.length > 0,\n sourceMapCount: sourceMaps.length,\n executionMs,\n serializationMs,\n workerMs: performance.now() - startedAt,\n },\n };\n if (usesValueCodec) response.valueEncoding = workerValueEncoding;\n writeMessage(response);\n } catch (error) {\n if (executionStartedAt !== undefined && executionMs === 0) {\n executionMs = performance.now() - executionStartedAt;\n }\n const code = entry.controller.signal.aborted\n ? entry.abortCode\n : error.code ?? \"runtime\";\n requestError(\n message.id,\n code,\n error.message,\n error,\n {\n moduleLoadMs,\n moduleCacheHit,\n moduleVersion,\n sourceMapLoaded: sourceMaps.length > 0,\n sourceMapCount: sourceMaps.length,\n executionMs,\n serializationMs,\n workerMs: performance.now() - startedAt,\n },\n sourceMaps,\n );\n } finally {\n closeEntry(message.id, entry);\n }\n}\n\nfunction valueAck(id, sequence, final = false) {\n writeMessage({\n version: protocolVersion,\n type: \"value-ack\",\n id,\n channel: \"arguments\",\n sequence,\n final,\n valueEncoding: workerValueEncoding,\n valueFraming: workerValueFraming,\n });\n}\n\nfunction startRequest(message) {\n validateRequest(message);\n if (pending.has(message.id)) {\n throw new Error(`request id is already pending: ${message.id}`);\n }\n if (message.valueFraming === workerValueFraming) {\n const entry = createEntry(message, \"receiving\");\n entry.decoder = new WorkerValueStreamDecoder({\n signal: entry.controller.signal,\n });\n entry.sequence = 0;\n entry.framedBytes = 0;\n valueAck(message.id, -1);\n return;\n }\n const entry = createEntry(message, \"executing\");\n void executeRequest(message, entry);\n}\n\nfunction receiveValueChunk(message, lineBytes) {\n if (typeof message.id !== \"string\" || message.id.length === 0) {\n protocolError(\"invalid-message\", \"value chunk id must be a non-empty string\");\n return;\n }\n const entry = pending.get(message.id);\n if (!entry || entry.phase !== \"receiving\") {\n protocolError(\n \"invalid-message\",\n `no request is receiving value chunks for id ${message.id}`,\n message.id,\n );\n return;\n }\n try {\n if (lineBytes > maximumValueChunkLineBytes) {\n throw new Error(\n `value chunk exceeds ${maximumValueChunkLineBytes} framed bytes`,\n );\n }\n if (message.channel !== \"arguments\") {\n throw new Error(\"incoming value chunk channel must be arguments\");\n }\n if (message.valueEncoding !== workerValueEncoding ||\n message.valueFraming !== workerValueFraming) {\n throw new Error(\"incoming value chunk encoding or framing mismatch\");\n }\n if (!Number.isSafeInteger(message.sequence) || message.sequence < 0 ||\n message.sequence !== entry.sequence) {\n throw new Error(\n `value chunk sequence ${String(message.sequence)} does not match ${entry.sequence}`,\n );\n }\n if (typeof message.final !== \"boolean\") {\n throw new Error(\"value chunk final must be a boolean\");\n }\n if (!Array.isArray(message.events)) {\n throw new Error(\"value chunk events must be an array\");\n }\n entry.framedBytes += lineBytes;\n if (entry.framedBytes > maximumValueStreamBytes) {\n throw new Error(\n `value stream exceeds ${maximumValueStreamBytes} framed bytes`,\n );\n }\n entry.decoder.write(message.events);\n const sequence = entry.sequence;\n entry.sequence += 1;\n if (!message.final) {\n valueAck(message.id, sequence);\n return;\n }\n const arguments_ = entry.decoder.finish();\n if (!Array.isArray(arguments_)) {\n throw new Error(\"chunked request root must decode to an argument array\");\n }\n entry.decoder = undefined;\n entry.phase = \"executing\";\n valueAck(message.id, sequence, true);\n void executeRequest(entry.message, entry, arguments_);\n } catch (error) {\n entry.controller.abort();\n receivingError(\n entry,\n error.code ?? \"invalid-value-chunk\",\n error.message,\n error,\n );\n }\n}\n\nfunction cancelRequest(message) {\n if (typeof message.id !== \"string\" || message.id.length === 0) {\n protocolError(\"invalid-message\", \"cancel id must be a non-empty string\");\n return;\n }\n const entry = pending.get(message.id);\n const accepted = Boolean(entry);\n if (entry) {\n entry.abortCode = \"cancelled\";\n entry.controller.abort();\n }\n writeMessage({\n version: protocolVersion,\n type: \"cancel\",\n id: message.id,\n accepted,\n });\n if (entry?.phase === \"receiving\") {\n const error = new Error(\"request cancelled while receiving value chunks\");\n error.code = \"cancelled\";\n receivingError(entry, \"cancelled\", error.message, error);\n }\n}\n\nfunction shutdown(lines) {\n shuttingDown = true;\n for (const entry of pending.values()) {\n entry.abortCode = \"shutdown\";\n entry.controller.abort();\n }\n writeMessage({\n version: protocolVersion,\n type: \"shutdown\",\n ok: true,\n });\n lines.close();\n setTimeout(() => process.exit(0), 0);\n}\n\nfunction handleMessage(message, lines, lineBytes) {\n if (!message || typeof message !== \"object\" || Array.isArray(message)) {\n protocolError(\"invalid-message\", \"protocol message must be an object\");\n return;\n }\n if (message.version !== protocolVersion) {\n protocolError(\n \"version-mismatch\",\n `worker protocol version ${protocolVersion} required`,\n message.id,\n );\n return;\n }\n if (message.type === \"request\") {\n try {\n startRequest(message);\n } catch (error) {\n requestError(message.id, \"invalid-request\", error.message, error);\n }\n } else if (message.type === \"value-chunk\") {\n receiveValueChunk(message, lineBytes);\n } else if (message.type === \"cancel\") {\n cancelRequest(message);\n } else if (message.type === \"shutdown\") {\n shutdown(lines);\n } else {\n protocolError(\n \"invalid-message\",\n `unknown protocol message type: ${message.type}`,\n message.id,\n );\n }\n}\n\nexport async function runWorker() {\n const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });\n writeMessage({\n version: protocolVersion,\n type: \"ready\",\n capabilities,\n pid: process.pid,\n });\n lines.on(\"close\", () => {\n if (shuttingDown) return;\n for (const entry of pending.values()) {\n entry.abortCode = \"shutdown\";\n entry.controller.abort();\n }\n });\n for await (const line of lines) {\n const lineBytes = Buffer.byteLength(line, \"utf8\");\n if (lineBytes > maximumLineBytes) {\n protocolError(\"line-too-large\", \"protocol line exceeds 16 MiB\");\n continue;\n }\n if (line.trim().length === 0) continue;\n try {\n handleMessage(JSON.parse(line), lines, lineBytes);\n } catch (error) {\n protocolError(\"invalid-json\", `invalid JSON: ${error.message}`);\n }\n }\n}\n\nif (import.meta.main) {\n runWorker().catch((error) => {\n console.error(error.stack ?? error.message);\n process.exitCode = 1;\n });\n}\n"))
package/stdlib/README.md CHANGED
@@ -374,8 +374,8 @@ protocols to ordinary Eliscript source:
374
374
  ```elisp
375
375
  (import "../../stdlib/core/metadata.eli"
376
376
  meta supports-metadata? vary-meta with-meta)
377
- (import "../../runtime/core/map.mjs" persistentHashMap)
378
- (import "../../runtime/core/vector.mjs" persistentVector)
377
+ (import "eliscript/runtime/core/map" persistentHashMap)
378
+ (import "eliscript/runtime/core/vector" persistentVector)
379
379
 
380
380
  (let ((value (with-meta
381
381
  (persistentVector 1 2 3)
@@ -1,7 +1,7 @@
1
1
  (module eliscript.core.order
2
2
  (import "../../runtime/core/collection.mjs" reduce)
3
3
  (import "../../runtime/core/order.mjs" :as Runtime)
4
- (import "../../runtime/core/transducer.mjs" into)
4
+ (import "../../runtime/core/transient.mjs" conjBang persistentBang transient)
5
5
  (import "../../runtime/core/truth.mjs" isTruthy)
6
6
  (import "../../runtime/core/vector.mjs" EMPTY_VECTOR)
7
7
  (defconst IComparable Runtime/IComparable)
@@ -22,12 +22,14 @@
22
22
  (defun comparator
23
23
  (comparison)
24
24
  (require-function comparison "comparator comparison")
25
- (lambda
26
- (left right)
27
- (let ((result (funcall comparison left right)))
28
- (if (= (value-type result) "number")
29
- (normalize-comparison-result result "comparator comparison")
30
- (if (isTruthy result) -1 (if (isTruthy (funcall comparison right left)) 1 0))))))
25
+ (if (or (eq comparison compare-values) (eq comparison Runtime/compareValues))
26
+ Runtime/compareValues
27
+ (lambda
28
+ (left right)
29
+ (let ((result (funcall comparison left right)))
30
+ (if (= (value-type result) "number")
31
+ (normalize-comparison-result result "comparator comparison")
32
+ (if (isTruthy result) -1 (if (isTruthy (funcall comparison right left)) 1 0)))))))
31
33
  (defun reverse-comparator
32
34
  (&rest arguments)
33
35
  (let ((length (js-length arguments)))
@@ -66,7 +68,31 @@
66
68
  (left right)
67
69
  (let ((result (funcall comparison (get left :key) (get right :key))))
68
70
  (if (= result 0) (- (get left :index) (get right :index)) result))))
69
- (into EMPTY_VECTOR (js-call values :map (lambda (entry) (get entry :value)))))
71
+ (let ((builder (transient EMPTY_VECTOR)) (index 0) (limit (js-length values)))
72
+ (while (< index limit)
73
+ (conjBang builder (get (js-nth index values) :value))
74
+ (setq index (1+ index)))
75
+ (persistentBang builder)))
76
+ (defun collect-values
77
+ (collection)
78
+ (reduce
79
+ collection
80
+ (lambda
81
+ (result value)
82
+ (js-call result :push value)
83
+ result)
84
+ (js-array)))
85
+ (defun sort-values
86
+ (values comparison)
87
+ (js-call values :sort comparison)
88
+ (let ((from-fn (get (get EMPTY_VECTOR :constructor) :from)))
89
+ (if (not (undefined? from-fn))
90
+ (js-call (get EMPTY_VECTOR :constructor) :from values)
91
+ (let ((builder (transient EMPTY_VECTOR)) (index 0) (limit (js-length values)))
92
+ (while (< index limit)
93
+ (conjBang builder (js-nth index values))
94
+ (setq index (1+ index)))
95
+ (persistentBang builder)))))
70
96
  (defun sort
71
97
  (&rest arguments)
72
98
  (let ((length (js-length arguments)))
@@ -78,8 +104,8 @@
78
104
  (let
79
105
  ((comparison (if (= length 1) compare-values (js-nth 0 arguments)))
80
106
  (collection (js-nth (1- length) arguments)))
81
- (sort-decorated
82
- (collect-decorated collection (lambda (value) value))
107
+ (sort-values
108
+ (collect-values collection)
83
109
  (comparator comparison))))))
84
110
  (defun sort-by
85
111
  (key-function &rest arguments)