UNPKG

@stryke/capnp

Version:

A package to assist in running the Cap'n Proto compiler and creating Cap'n Proto serialization protocol schemas.

1,591 lines (1,557 loc) 238 kB
#!/usr/bin/env node var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // bin/capnpc.ts var capnpc_exports = {}; __export(capnpc_exports, { createProgram: () => createProgram }); module.exports = __toCommonJS(capnpc_exports); var import_console = require("@storm-software/config-tools/logger/console"); var import_utilities = require("@storm-software/config-tools/utilities"); // ../path/src/exists.ts var import_node_fs = require("fs"); var import_promises = require("fs/promises"); var existsSync = /* @__PURE__ */ __name((filePath) => { return (0, import_node_fs.existsSync)(filePath); }, "existsSync"); var exists = /* @__PURE__ */ __name(async (filePath) => { return (0, import_promises.access)(filePath, import_promises.constants.F_OK).then(() => true).catch(() => false); }, "exists"); // ../fs/src/helpers.ts var import_nanotar = require("nanotar"); var import_node_fs2 = require("fs"); var import_promises2 = require("fs/promises"); async function createDirectory(path) { if (await exists(path)) { return; } return (0, import_promises2.mkdir)(path, { recursive: true }); } __name(createDirectory, "createDirectory"); // ../type-checks/src/get-object-tag.ts var getObjectTag = /* @__PURE__ */ __name((value) => { if (value == null) { return value === void 0 ? "[object Undefined]" : "[object Null]"; } return Object.prototype.toString.call(value); }, "getObjectTag"); // ../type-checks/src/is-plain-object.ts var isObjectLike = /* @__PURE__ */ __name((obj) => { return typeof obj === "object" && obj !== null; }, "isObjectLike"); var isPlainObject = /* @__PURE__ */ __name((obj) => { if (!isObjectLike(obj) || getObjectTag(obj) !== "[object Object]") { return false; } if (Object.getPrototypeOf(obj) === null) { return true; } let proto = obj; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(obj) === proto; }, "isPlainObject"); // ../type-checks/src/is-object.ts var isObject = /* @__PURE__ */ __name((value) => { try { return typeof value === "object" || Boolean(value) && value?.constructor === Object || isPlainObject(value); } catch { return false; } }, "isObject"); // ../type-checks/src/is-string.ts var isString = /* @__PURE__ */ __name((value) => { try { return typeof value === "string"; } catch { return false; } }, "isString"); // ../json/src/storm-json.ts var import_jsonc_parser2 = require("jsonc-parser"); var import_node_buffer = require("buffer"); var import_superjson = __toESM(require("superjson"), 1); // ../types/src/base.ts var EMPTY_STRING = ""; var $NestedValue = Symbol("NestedValue"); // ../json/src/utils/strip-comments.ts var singleComment = Symbol("singleComment"); var multiComment = Symbol("multiComment"); function stripWithoutWhitespace() { return ""; } __name(stripWithoutWhitespace, "stripWithoutWhitespace"); function stripWithWhitespace(value, start, end) { return value.slice(start, end).replace(/\S/g, " "); } __name(stripWithWhitespace, "stripWithWhitespace"); function isEscaped(value, quotePosition) { let index = quotePosition - 1; let backslashCount = 0; while (value[index] === "\\") { index -= 1; backslashCount += 1; } return Boolean(backslashCount % 2); } __name(isEscaped, "isEscaped"); function stripComments(value, { whitespace = true, trailingCommas = false } = {}) { if (typeof value !== "string") { throw new TypeError(`Expected argument \`jsonString\` to be a \`string\`, got \`${typeof value}\``); } const strip = whitespace ? stripWithWhitespace : stripWithoutWhitespace; let isInsideString = false; let isInsideComment = false; let offset = 0; let buffer = ""; let result = ""; let commaIndex = -1; for (let index = 0; index < value.length; index++) { const currentCharacter = value[index]; const nextCharacter = value[index + 1]; if (!isInsideComment && currentCharacter === '"') { const escaped = isEscaped(value, index); if (!escaped) { isInsideString = !isInsideString; } } if (isInsideString) { continue; } if (!isInsideComment && currentCharacter + (nextCharacter ?? EMPTY_STRING) === "//") { buffer += value.slice(offset, index); offset = index; isInsideComment = singleComment; index++; } else if (isInsideComment === singleComment && currentCharacter + (nextCharacter ?? EMPTY_STRING) === "\r\n") { index++; isInsideComment = false; buffer += strip(value, offset, index); offset = index; } else if (isInsideComment === singleComment && currentCharacter === "\n") { isInsideComment = false; buffer += strip(value, offset, index); offset = index; } else if (!isInsideComment && currentCharacter + (nextCharacter ?? EMPTY_STRING) === "/*") { buffer += value.slice(offset, index); offset = index; isInsideComment = multiComment; index++; } else if (isInsideComment === multiComment && currentCharacter + (nextCharacter ?? EMPTY_STRING) === "*/") { index++; isInsideComment = false; buffer += strip(value, offset, index + 1); offset = index + 1; } else if (trailingCommas && !isInsideComment) { if (commaIndex !== -1) { if (currentCharacter === "}" || currentCharacter === "]") { buffer += value.slice(offset, index); result += strip(buffer, 0, 1) + buffer.slice(1); buffer = ""; offset = index; commaIndex = -1; } else if (currentCharacter !== " " && currentCharacter !== " " && currentCharacter !== "\r" && currentCharacter !== "\n") { buffer += value.slice(offset, index); offset = index; commaIndex = -1; } } else if (currentCharacter === ",") { result += buffer + value.slice(offset, index); buffer = ""; offset = index; commaIndex = index; } } } return result + buffer + (isInsideComment ? strip(value.slice(offset)) : value.slice(offset)); } __name(stripComments, "stripComments"); // ../json/src/utils/parse.ts var suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; var JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(?:\.\d{1,17})?(?:E[+-]?\d+)?\s*$/i; function jsonParseTransform(key, value) { if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) { console.warn(`Dropping "${key}" key to prevent prototype pollution.`); return; } return value; } __name(jsonParseTransform, "jsonParseTransform"); function parse(value, options = {}) { if (typeof value !== "string") { return value; } let stripped = stripComments(value); if (stripped[0] === '"' && stripped[stripped.length - 1] === '"' && !stripped.includes("\\")) { return stripped.slice(1, -1); } stripped = stripped.trim(); if (stripped.length <= 9) { switch (stripped.toLowerCase()) { case "true": { return true; } case "false": { return false; } case "undefined": { return void 0; } case "null": { return null; } case "nan": { return Number.NaN; } case "infinity": { return Number.POSITIVE_INFINITY; } case "-infinity": { return Number.NEGATIVE_INFINITY; } } } if (!JsonSigRx.test(stripped)) { if (options.strict) { throw new Error("Invalid JSON"); } return stripped; } try { if (suspectProtoRx.test(stripped) || suspectConstructorRx.test(stripped)) { if (options.strict) { throw new Error("Possible prototype pollution"); } return JSON.parse(stripped, jsonParseTransform); } return JSON.parse(stripped); } catch (error) { if (options.strict) { throw error; } return value; } } __name(parse, "parse"); // ../json/src/utils/parse-error.ts var import_jsonc_parser = require("jsonc-parser"); var import_lines_and_columns = require("lines-and-columns"); // ../json/src/utils/code-frames.ts var NEWLINE = /\r\n|[\n\r\u2028\u2029]/; function getMarkerLines(loc, source, opts = {}) { const startLoc = { column: 0, line: -1, ...loc.start }; const endLoc = { ...startLoc, ...loc.end }; const { linesAbove = 2, linesBelow = 3 } = opts || {}; const startLine = startLoc.line; const startColumn = startLoc.column; const endLine = endLoc.line; const endColumn = endLoc.column; let start = Math.max(startLine - (linesAbove + 1), 0); let end = Math.min(source.length, endLine + linesBelow); if (startLine === -1) { start = 0; } if (endLine === -1) { end = source.length; } const lineDiff = endLine - startLine; const markerLines = {}; if (lineDiff) { for (let i = 0; i <= lineDiff; i++) { const lineNumber = i + startLine; if (!startColumn) { markerLines[lineNumber] = true; } else if (i === 0) { const sourceLength = source[lineNumber - 1]?.length ?? 0; markerLines[lineNumber] = [ startColumn, sourceLength - startColumn + 1 ]; } else if (i === lineDiff) { markerLines[lineNumber] = [ 0, endColumn ]; } else { const sourceLength = source[lineNumber - i]?.length ?? 0; markerLines[lineNumber] = [ 0, sourceLength ]; } } } else if (startColumn === endColumn) { markerLines[startLine] = startColumn ? [ startColumn, 0 ] : true; } else { markerLines[startLine] = [ startColumn, endColumn - startColumn ]; } return { start, end, markerLines }; } __name(getMarkerLines, "getMarkerLines"); function codeFrameColumns(rawLines, loc, opts = {}) { const lines = rawLines.split(NEWLINE); const { start, end, markerLines } = getMarkerLines(loc, lines, opts); const numberMaxWidth = String(end).length; const highlightedLines = opts.highlight ? opts.highlight(rawLines) : rawLines; const frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => { const number = start + 1 + index; const paddedNumber = ` ${number}`.slice(-numberMaxWidth); const gutter = ` ${paddedNumber} | `; const hasMarker = Boolean(markerLines[number] ?? false); if (hasMarker) { let markerLine = ""; if (Array.isArray(hasMarker)) { const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); const numberOfMarkers = hasMarker[1] || 1; markerLine = [ "\n ", gutter.replace(/\d/g, " "), markerSpacing, "^".repeat(numberOfMarkers) ].join(""); } return [ ">", gutter, line, markerLine ].join(""); } return ` ${gutter}${line}`; }).join("\n"); return frame; } __name(codeFrameColumns, "codeFrameColumns"); // ../json/src/utils/parse-error.ts function formatParseError(input, parseError) { const { error, offset, length } = parseError; const result = new import_lines_and_columns.LinesAndColumns(input).locationForIndex(offset); let line = result?.line ?? 0; let column = result?.column ?? 0; line++; column++; return `${(0, import_jsonc_parser.printParseErrorCode)(error)} in JSON at ${line}:${column} ${codeFrameColumns(input, { start: { line, column }, end: { line, column: column + length } })} `; } __name(formatParseError, "formatParseError"); // ../type-checks/src/is-number.ts var isNumber = /* @__PURE__ */ __name((value) => { try { return value instanceof Number || typeof value === "number" || Number(value) === value; } catch { return false; } }, "isNumber"); // ../type-checks/src/is-undefined.ts var isUndefined = /* @__PURE__ */ __name((value) => { return value === void 0; }, "isUndefined"); // ../json/src/utils/stringify.ts var invalidKeyChars = [ "@", "/", "#", "$", " ", ":", ";", ",", ".", "!", "?", "&", "=", "+", "-", "*", "%", "^", "~", "|", "\\", '"', "'", "`", "{", "}", "[", "]", "(", ")", "<", ">" ]; var stringify = /* @__PURE__ */ __name((value, spacing = 2) => { const space = isNumber(spacing) ? " ".repeat(spacing) : spacing; switch (value) { case null: { return "null"; } case void 0: { return '"undefined"'; } case true: { return "true"; } case false: { return "false"; } case Number.POSITIVE_INFINITY: { return "infinity"; } case Number.NEGATIVE_INFINITY: { return "-infinity"; } } if (Array.isArray(value)) { return `[${space}${value.map((v) => stringify(v, space)).join(`,${space}`)}${space}]`; } if (value instanceof Uint8Array) { return value.toString(); } switch (typeof value) { case "number": { return `${value}`; } case "string": { return JSON.stringify(value); } case "object": { const keys = Object.keys(value).filter((key) => !isUndefined(value[key])); return `{${space}${keys.map((key) => `${invalidKeyChars.some((invalidKeyChar) => key.includes(invalidKeyChar)) ? `"${key}"` : key}: ${space}${stringify(value[key], space)}`).join(`,${space}`)}${space}}`; } default: return "null"; } }, "stringify"); // ../json/src/storm-json.ts var StormJSON = class _StormJSON extends import_superjson.default { static { __name(this, "StormJSON"); } static #instance; static get instance() { if (!_StormJSON.#instance) { _StormJSON.#instance = new _StormJSON(); } return _StormJSON.#instance; } /** * Deserialize the given value with superjson using the given metadata */ static deserialize(payload) { return _StormJSON.instance.deserialize(payload); } /** * Serialize the given value with superjson */ static serialize(object) { return _StormJSON.instance.serialize(object); } /** * Parse the given string value with superjson using the given metadata * * @param value - The string value to parse * @returns The parsed data */ static parse(value) { return parse(value); } /** * Serializes the given data to a JSON string. * By default the JSON string is formatted with a 2 space indentation to be easy readable. * * @param value - Object which should be serialized to JSON * @param _options - JSON serialize options * @returns the formatted JSON representation of the object */ static stringify(value, _options) { const customTransformer = _StormJSON.instance.customTransformerRegistry.findApplicable(value); let result = value; if (customTransformer && customTransformer.isApplicable(value)) { result = customTransformer.serialize(result); } return stringify(result); } /** * Parses the given JSON string and returns the object the JSON content represents. * By default javascript-style comments and trailing commas are allowed. * * @param strData - JSON content as string * @param options - JSON parse options * @returns Object the JSON content represents */ static parseJson(strData, options) { try { if (options?.expectComments === false) { return _StormJSON.instance.parse(strData); } } catch { } const errors = []; const opts = { allowTrailingComma: true, ...options }; const result = (0, import_jsonc_parser2.parse)(strData, errors, opts); if (errors.length > 0 && errors[0]) { throw new Error(formatParseError(strData, errors[0])); } return result; } /** * Register a custom schema with superjson * * @param name - The name of the schema * @param serialize - The function to serialize the schema * @param deserialize - The function to deserialize the schema * @param isApplicable - The function to check if the schema is applicable */ static register(name, serialize, deserialize, isApplicable) { _StormJSON.instance.registerCustom({ isApplicable, serialize, deserialize }, name); } /** * Register a class with superjson * * @param classConstructor - The class constructor to register */ static registerClass(classConstructor, options) { _StormJSON.instance.registerClass(classConstructor, { identifier: isString(options) ? options : options?.identifier || classConstructor.name, allowProps: options && isObject(options) && options?.allowProps && Array.isArray(options.allowProps) ? options.allowProps : [ "__typename" ] }); } constructor() { super({ dedupe: true }); } }; StormJSON.instance.registerCustom({ isApplicable: /* @__PURE__ */ __name((v) => import_node_buffer.Buffer.isBuffer(v), "isApplicable"), serialize: /* @__PURE__ */ __name((v) => v.toString("base64"), "serialize"), deserialize: /* @__PURE__ */ __name((v) => import_node_buffer.Buffer.from(v, "base64"), "deserialize") }, "Bytes"); // ../type-checks/src/is-error.ts var isError = /* @__PURE__ */ __name((obj) => { if (!isObject(obj)) { return false; } const tag = getObjectTag(obj); return tag === "[object Error]" || tag === "[object DOMException]" || typeof obj?.message === "string" && typeof obj?.name === "string" && !isPlainObject(obj); }, "isError"); // ../fs/src/read-file.ts var import_node_fs3 = require("fs"); var import_promises3 = require("fs/promises"); var readFile2 = /* @__PURE__ */ __name(async (filePath) => { try { if (!filePath) { throw new Error("No file path provided to read data"); } return await (0, import_promises3.readFile)(filePath, { encoding: "utf8" }); } catch { throw new Error("An error occurred writing data to file"); } }, "readFile"); // ../path/src/is-file.ts var import_node_fs4 = require("fs"); // ../path/src/join-paths.ts var _DRIVE_LETTER_START_RE = /^[A-Z]:\//i; function normalizeWindowsPath(input = "") { if (!input) { return input; } return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); } __name(normalizeWindowsPath, "normalizeWindowsPath"); var _UNC_REGEX = /^[/\\]{2}/; var _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Z]:[/\\]/i; var _DRIVE_LETTER_RE = /^[A-Z]:$/i; var isAbsolute = /* @__PURE__ */ __name(function(p) { return _IS_ABSOLUTE_RE.test(p); }, "isAbsolute"); var correctPaths = /* @__PURE__ */ __name(function(path) { if (!path || path.length === 0) { return "."; } path = normalizeWindowsPath(path); const isUNCPath = path.match(_UNC_REGEX); const isPathAbsolute = isAbsolute(path); const trailingSeparator = path[path.length - 1] === "/"; path = normalizeString(path, !isPathAbsolute); if (path.length === 0) { if (isPathAbsolute) { return "/"; } return trailingSeparator ? "./" : "."; } if (trailingSeparator) { path += "/"; } if (_DRIVE_LETTER_RE.test(path)) { path += "/"; } if (isUNCPath) { if (!isPathAbsolute) { return `//./${path}`; } return `//${path}`; } return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; }, "correctPaths"); var joinPaths = /* @__PURE__ */ __name(function(...segments) { let path = ""; for (const seg of segments) { if (!seg) { continue; } if (path.length > 0) { const pathTrailing = path[path.length - 1] === "/"; const segLeading = seg[0] === "/"; const both = pathTrailing && segLeading; if (both) { path += seg.slice(1); } else { path += pathTrailing || segLeading ? seg : `/${seg}`; } } else { path += seg; } } return correctPaths(path); }, "joinPaths"); function normalizeString(path, allowAboveRoot) { let res = ""; let lastSegmentLength = 0; let lastSlash = -1; let dots = 0; let char = null; for (let index = 0; index <= path.length; ++index) { if (index < path.length) { char = path[index]; } else if (char === "/") { break; } else { char = "/"; } if (char === "/") { if (lastSlash === index - 1 || dots === 1) { } else if (dots === 2) { if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { if (res.length > 2) { const lastSlashIndex = res.lastIndexOf("/"); if (lastSlashIndex === -1) { res = ""; lastSegmentLength = 0; } else { res = res.slice(0, lastSlashIndex); lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); } lastSlash = index; dots = 0; continue; } else if (res.length > 0) { res = ""; lastSegmentLength = 0; lastSlash = index; dots = 0; continue; } } if (allowAboveRoot) { res += res.length > 0 ? "/.." : ".."; lastSegmentLength = 2; } } else { if (res.length > 0) { res += `/${path.slice(lastSlash + 1, index)}`; } else { res = path.slice(lastSlash + 1, index); } lastSegmentLength = index - lastSlash - 1; } lastSlash = index; dots = 0; } else if (char === "." && dots !== -1) { ++dots; } else { dots = -1; } } return res; } __name(normalizeString, "normalizeString"); // ../path/src/regex.ts var DRIVE_LETTER_START_REGEX = /^[A-Z]:\//i; // ../path/src/slash.ts function slash(path) { if (path.startsWith("\\\\?\\")) { return path; } return path.replace(/\\/g, "/"); } __name(slash, "slash"); // ../path/src/correct-path.ts function normalizeWindowsPath2(input = "") { if (!input) { return input; } return slash(input).replace(DRIVE_LETTER_START_REGEX, (r) => r.toUpperCase()); } __name(normalizeWindowsPath2, "normalizeWindowsPath"); // ../path/src/file-path-fns.ts var import_node_path = require("path"); // ../path/src/get-workspace-root.ts var import_config_tools = require("@storm-software/config-tools"); // ../path/src/file-path-fns.ts function findFileName(filePath, options = {}) { const { requireExtension = false, withExtension = true } = options; const result = normalizeWindowsPath2(filePath)?.split(filePath?.includes("\\") ? "\\" : "/")?.pop() ?? ""; if (requireExtension === true && !result.includes(".")) { return EMPTY_STRING; } if (withExtension === false && result.includes(".")) { return result.substring(0, result.lastIndexOf(".")) || EMPTY_STRING; } return result; } __name(findFileName, "findFileName"); function findFilePath(filePath) { const normalizedPath = normalizeWindowsPath2(filePath); const result = normalizedPath.replace(findFileName(normalizedPath, { requireExtension: true }), ""); return result === "/" ? result : result.replace(/\/$/, ""); } __name(findFilePath, "findFilePath"); function relativePath(from, to, withEndSlash = false) { return (0, import_node_path.relative)(withEndSlash !== true ? from.replace(/\/$/, "") : from, withEndSlash !== true ? to.replace(/\/$/, "") : to); } __name(relativePath, "relativePath"); // ../fs/src/write-file.ts var import_node_fs5 = require("fs"); var import_promises4 = require("fs/promises"); // ../fs/src/json.ts async function readJsonFile(path, options) { const content = await readFile2(path); if (options) { options.endsWithNewline = content.codePointAt(content.length - 1) === 10; } try { return StormJSON.parseJson(content, options); } catch (error) { if (isError(error)) { error.message = error.message.replace("JSON", path); throw error; } throw new Error(`Failed to parse JSON: ${path}`); } } __name(readJsonFile, "readJsonFile"); // ../fs/src/list-files.ts var import_defu = __toESM(require("defu"), 1); var import_glob = require("glob"); var DEFAULT_OPTIONS = { dot: true }; async function list(filesGlob, options) { return (0, import_glob.glob)(filesGlob, (0, import_defu.default)(options ?? {}, DEFAULT_OPTIONS)); } __name(list, "list"); async function listFiles(filesGlob, options) { const result = (await list(filesGlob, (0, import_defu.default)({ withFileTypes: true }, options ?? {}))).filter((ret) => ret.isFile()); if (!options?.withFileTypes) { return result.map((file) => file.fullpath()); } return result; } __name(listFiles, "listFiles"); // bin/capnpc.ts var import_commander = require("commander"); var import_promises5 = require("fs/promises"); var import_typescript3 = __toESM(require("typescript"), 1); // ../../node_modules/.pnpm/capnp-es@0.0.11_patch_hash=503a440bd2bef41c0cb22819bc4ced5a7f04993fb999f0d944e284220f14916b_typescript@5.9.2/node_modules/capnp-es/dist/shared/capnp-es.CbTQkT9D.mjs var import_typescript = __toESM(require("typescript"), 1); // ../../node_modules/.pnpm/capnp-es@0.0.11_patch_hash=503a440bd2bef41c0cb22819bc4ced5a7f04993fb999f0d944e284220f14916b_typescript@5.9.2/node_modules/capnp-es/dist/shared/capnp-es.0-_cOx6D.mjs var ListElementSize = /* @__PURE__ */ ((ListElementSize2) => { ListElementSize2[ListElementSize2["VOID"] = 0] = "VOID"; ListElementSize2[ListElementSize2["BIT"] = 1] = "BIT"; ListElementSize2[ListElementSize2["BYTE"] = 2] = "BYTE"; ListElementSize2[ListElementSize2["BYTE_2"] = 3] = "BYTE_2"; ListElementSize2[ListElementSize2["BYTE_4"] = 4] = "BYTE_4"; ListElementSize2[ListElementSize2["BYTE_8"] = 5] = "BYTE_8"; ListElementSize2[ListElementSize2["POINTER"] = 6] = "POINTER"; ListElementSize2[ListElementSize2["COMPOSITE"] = 7] = "COMPOSITE"; return ListElementSize2; })(ListElementSize || {}); var tmpWord = new DataView(new ArrayBuffer(8)); new Uint16Array(tmpWord.buffer)[0] = 258; var DEFAULT_BUFFER_SIZE = 4096; var DEFAULT_TRAVERSE_LIMIT = 64 << 20; var LIST_SIZE_MASK = 7; var MAX_BUFFER_DUMP_BYTES = 8192; var MAX_INT32 = 2147483647; var MAX_UINT32 = 4294967295; var MIN_SINGLE_SEGMENT_GROWTH = 4096; var NATIVE_LITTLE_ENDIAN = tmpWord.getUint8(0) === 2; var PACK_SPAN_THRESHOLD = 2; var POINTER_DOUBLE_FAR_MASK = 4; var POINTER_TYPE_MASK = 3; var MAX_DEPTH = MAX_INT32; var MAX_SEGMENT_LENGTH = MAX_UINT32; var INVARIANT_UNREACHABLE_CODE = "CAPNP-TS000 Unreachable code detected."; function assertNever(n) { throw new Error(INVARIANT_UNREACHABLE_CODE + ` (never block hit with: ${n})`); } __name(assertNever, "assertNever"); var MSG_INVALID_FRAME_HEADER = "CAPNP-TS001 Attempted to parse an invalid message frame header; are you sure this is a Cap'n Proto message?"; var MSG_PACK_NOT_WORD_ALIGNED = "CAPNP-TS003 Attempted to pack a message that was not word-aligned."; var MSG_SEGMENT_OUT_OF_BOUNDS = "CAPNP-TS004 Segment ID %X is out of bounds for message %s."; var MSG_SEGMENT_TOO_SMALL = "CAPNP-TS005 First segment must have at least enough room to hold the root pointer (8 bytes)."; var PTR_ADOPT_WRONG_MESSAGE = "CAPNP-TS008 Attempted to adopt %s into a pointer in a different message %s."; var PTR_ALREADY_ADOPTED = "CAPNP-TS009 Attempted to adopt %s more than once."; var PTR_COMPOSITE_SIZE_UNDEFINED = "CAPNP-TS010 Attempted to set a composite list without providing a composite element size."; var PTR_DEPTH_LIMIT_EXCEEDED = "CAPNP-TS011 Nesting depth limit exceeded for %s."; var PTR_INIT_COMPOSITE_STRUCT = "CAPNP-TS013 Attempted to initialize a struct member from a composite list (%s)."; var PTR_INVALID_FAR_TARGET = "CAPNP-TS015 Target of a far pointer (%s) is another far pointer."; var PTR_INVALID_LIST_SIZE = "CAPNP-TS016 Invalid list element size: %x."; var PTR_INVALID_POINTER_TYPE = "CAPNP-TS017 Invalid pointer type: %x."; var PTR_INVALID_UNION_ACCESS = "CAPNP-TS018 Attempted to access getter on %s for union field %s that is not currently set (wanted: %d, found: %d)."; var PTR_OFFSET_OUT_OF_BOUNDS = "CAPNP-TS019 Pointer offset %a is out of bounds for underlying buffer."; var PTR_STRUCT_DATA_OUT_OF_BOUNDS = "CAPNP-TS020 Attempted to access out-of-bounds struct data (struct: %s, %d bytes at %a, data words: %d)."; var PTR_STRUCT_POINTER_OUT_OF_BOUNDS = "CAPNP-TS021 Attempted to access out-of-bounds struct pointer (%s, index: %d, length: %d)."; var PTR_TRAVERSAL_LIMIT_EXCEEDED = "CAPNP-TS022 Traversal limit exceeded! Slow down! %s"; var PTR_WRONG_LIST_TYPE = "CAPNP-TS023 Cannot convert %s to a %s list."; var PTR_WRONG_POINTER_TYPE = "CAPNP-TS024 Attempted to convert pointer %s to a %s type."; var SEG_GET_NON_ZERO_SINGLE = "CAPNP-TS035 Attempted to get a segment other than 0 (%d) from a single segment arena."; var SEG_ID_OUT_OF_BOUNDS = "CAPNP-TS036 Attempted to get an out-of-bounds segment (%d)."; var SEG_NOT_WORD_ALIGNED = "CAPNP-TS037 Segment buffer length %d is not a multiple of 8."; var SEG_REPLACEMENT_BUFFER_TOO_SMALL = "CAPNP-TS038 Attempted to replace a segment buffer with one that is smaller than the allocated space."; var SEG_SIZE_OVERFLOW = `CAPNP-TS039 Requested size %x exceeds maximum value (${MAX_SEGMENT_LENGTH}).`; var TYPE_COMPOSITE_SIZE_UNDEFINED = "CAPNP-TS040 Must provide a composite element size for composite list pointers."; var LIST_NO_MUTABLE = "CAPNP-TS045: Cannot call mutative methods on an immutable list."; var LIST_NO_SEARCH = "CAPNP-TS046: Search is not supported for list."; function bufferToHex(buffer) { const a = new Uint8Array(buffer); const h = []; for (let i = 0; i < a.byteLength; i++) { h.push(pad(a[i].toString(16), 2)); } return `[${h.join(" ")}]`; } __name(bufferToHex, "bufferToHex"); function dumpBuffer(buffer) { const b = buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); const byteLength = Math.min(b.byteLength, MAX_BUFFER_DUMP_BYTES); let r = format("\n=== buffer[%d] ===", byteLength); for (let j = 0; j < byteLength; j += 16) { r += ` ${pad(j.toString(16), 8)}: `; let s = ""; let k; for (k = 0; k < 16 && j + k < b.byteLength; k++) { const v = b[j + k]; r += `${pad(v.toString(16), 2)} `; s += v > 31 && v < 255 ? String.fromCharCode(v) : "\xB7"; if (k === 7) { r += " "; } } r += `${" ".repeat((17 - k) * 3)}${s}`; } r += "\n"; if (byteLength !== b.byteLength) { r += format("=== (truncated %d bytes) ===\n", b.byteLength - byteLength); } return r; } __name(dumpBuffer, "dumpBuffer"); function format(s, ...args) { const n = s.length; let arg; let argIndex = 0; let c; let escaped = false; let i = 0; let leadingZero = false; let precision; let result = ""; function nextArg() { return args[argIndex++]; } __name(nextArg, "nextArg"); function slurpNumber() { let digits = ""; while (/\d/.test(s[i])) { digits += s[i++]; c = s[i]; } return digits.length > 0 ? Number.parseInt(digits, 10) : null; } __name(slurpNumber, "slurpNumber"); for (; i < n; ++i) { c = s[i]; if (escaped) { escaped = false; if (c === ".") { leadingZero = false; c = s[++i]; } else if (c === "0" && s[i + 1] === ".") { leadingZero = true; i += 2; c = s[i]; } else { leadingZero = true; } precision = slurpNumber(); switch (c) { case "a": { result += "0x" + pad(Number.parseInt(String(nextArg()), 10).toString(16), 8); break; } case "b": { result += Number.parseInt(String(nextArg()), 10).toString(2); break; } case "c": { arg = nextArg(); result += typeof arg === "string" || arg instanceof String ? arg : String.fromCharCode(Number.parseInt(String(arg), 10)); break; } case "d": { result += Number.parseInt(String(nextArg()), 10); break; } case "f": { const tmp = Number.parseFloat(String(nextArg())).toFixed( precision || 6 ); result += leadingZero ? tmp : tmp.replace(/^0/, ""); break; } case "j": { result += JSON.stringify(nextArg()); break; } case "o": { result += "0" + Number.parseInt(String(nextArg()), 10).toString(8); break; } case "s": { result += nextArg(); break; } case "x": { result += "0x" + Number.parseInt(String(nextArg()), 10).toString(16); break; } case "X": { result += "0x" + Number.parseInt(String(nextArg()), 10).toString(16).toUpperCase(); break; } default: { result += c; break; } } } else if (c === "%") { escaped = true; } else { result += c; } } return result; } __name(format, "format"); function pad(v, width, pad2 = "0") { return v.length >= width ? v : Array.from({ length: width - v.length + 1 }).join(pad2) + v; } __name(pad, "pad"); function padToWord$1(size) { return size + 7 & -8; } __name(padToWord$1, "padToWord$1"); var ObjectSize = class { static { __name(this, "ObjectSize"); } /** * Creates a new ObjectSize instance. * * @param dataByteLength - The number of bytes in the data section of the struct * @param pointerLength - The number of pointers in the pointer section of the struct */ constructor(dataByteLength, pointerLength) { this.dataByteLength = dataByteLength; this.pointerLength = pointerLength; } toString() { return format( "ObjectSize_dw:%d,pc:%d", getDataWordLength(this), this.pointerLength ); } }; function getByteLength(o) { return o.dataByteLength + o.pointerLength * 8; } __name(getByteLength, "getByteLength"); function getDataWordLength(o) { return o.dataByteLength / 8; } __name(getDataWordLength, "getDataWordLength"); function getWordLength(o) { return o.dataByteLength / 8 + o.pointerLength; } __name(getWordLength, "getWordLength"); function padToWord(o) { return new ObjectSize(padToWord$1(o.dataByteLength), o.pointerLength); } __name(padToWord, "padToWord"); var Orphan = class { static { __name(this, "Orphan"); } /** If this member is not present then the orphan has already been adopted, or something went very wrong. */ _capnp; byteOffset; segment; constructor(src) { const c = getContent(src); this.segment = c.segment; this.byteOffset = c.byteOffset; this._capnp = {}; this._capnp.type = getTargetPointerType(src); switch (this._capnp.type) { case PointerType.STRUCT: { this._capnp.size = getTargetStructSize(src); break; } case PointerType.LIST: { this._capnp.length = getTargetListLength(src); this._capnp.elementSize = getTargetListElementSize(src); if (this._capnp.elementSize === ListElementSize.COMPOSITE) { this._capnp.size = getTargetCompositeListSize(src); } break; } case PointerType.OTHER: { this._capnp.capId = getCapabilityId(src); break; } default: { throw new Error(PTR_INVALID_POINTER_TYPE); } } erasePointer(src); } /** * Adopt (move) this orphan into the target pointer location. This will allocate far pointers in `dst` as needed. * * @param dst The destination pointer. */ _moveTo(dst) { if (this._capnp === void 0) { throw new Error(format(PTR_ALREADY_ADOPTED, this)); } if (this.segment.message !== dst.segment.message) { throw new Error(format(PTR_ADOPT_WRONG_MESSAGE, this, dst)); } erase(dst); const res = initPointer(this.segment, this.byteOffset, dst); switch (this._capnp.type) { case PointerType.STRUCT: { setStructPointer(res.offsetWords, this._capnp.size, res.pointer); break; } case PointerType.LIST: { let { offsetWords } = res; if (this._capnp.elementSize === ListElementSize.COMPOSITE) { offsetWords--; } setListPointer( offsetWords, this._capnp.elementSize, this._capnp.length, res.pointer, this._capnp.size ); break; } case PointerType.OTHER: { setInterfacePointer(this._capnp.capId, res.pointer); break; } /* istanbul ignore next */ default: { throw new Error(PTR_INVALID_POINTER_TYPE); } } this._capnp = void 0; } dispose() { if (this._capnp === void 0) { return; } switch (this._capnp.type) { case PointerType.STRUCT: { this.segment.fillZeroWords( this.byteOffset, getWordLength(this._capnp.size) ); break; } case PointerType.LIST: { const byteLength = getListByteLength( this._capnp.elementSize, this._capnp.length, this._capnp.size ); this.segment.fillZeroWords(this.byteOffset, byteLength); break; } } this._capnp = void 0; } [Symbol.for("nodejs.util.inspect.custom")]() { return format( "Orphan_%d@%a,type:%s", this.segment.id, this.byteOffset, this._capnp && this._capnp.type ); } }; function adopt(src, p) { src._moveTo(p); } __name(adopt, "adopt"); function disown(p) { return new Orphan(p); } __name(disown, "disown"); function dump(p) { return bufferToHex(p.segment.buffer.slice(p.byteOffset, p.byteOffset + 8)); } __name(dump, "dump"); function getListByteLength(elementSize, length, compositeSize) { switch (elementSize) { case ListElementSize.BIT: { return padToWord$1(length + 7 >>> 3); } case ListElementSize.BYTE: case ListElementSize.BYTE_2: case ListElementSize.BYTE_4: case ListElementSize.BYTE_8: case ListElementSize.POINTER: case ListElementSize.VOID: { return padToWord$1(getListElementByteLength(elementSize) * length); } /* istanbul ignore next */ case ListElementSize.COMPOSITE: { if (compositeSize === void 0) { throw new Error(format(PTR_INVALID_LIST_SIZE, Number.NaN)); } return length * padToWord$1(getByteLength(compositeSize)); } /* istanbul ignore next */ default: { throw new Error(PTR_INVALID_LIST_SIZE); } } } __name(getListByteLength, "getListByteLength"); function getListElementByteLength(elementSize) { switch (elementSize) { /* istanbul ignore next */ case ListElementSize.BIT: { return Number.NaN; } case ListElementSize.BYTE: { return 1; } case ListElementSize.BYTE_2: { return 2; } case ListElementSize.BYTE_4: { return 4; } case ListElementSize.BYTE_8: case ListElementSize.POINTER: { return 8; } /* istanbul ignore next */ case ListElementSize.COMPOSITE: { return Number.NaN; } /* istanbul ignore next */ case ListElementSize.VOID: { return 0; } /* istanbul ignore next */ default: { throw new Error(format(PTR_INVALID_LIST_SIZE, elementSize)); } } } __name(getListElementByteLength, "getListElementByteLength"); function add(offset, p) { return new Pointer(p.segment, p.byteOffset + offset, p._capnp.depthLimit); } __name(add, "add"); function copyFrom(src, p) { if (p.segment === src.segment && p.byteOffset === src.byteOffset) { return; } erase(p); if (isNull(src)) return; switch (getTargetPointerType(src)) { case PointerType.STRUCT: { copyFromStruct(src, p); break; } case PointerType.LIST: { copyFromList(src, p); break; } case PointerType.OTHER: { copyFromInterface(src, p); break; } /* istanbul ignore next */ default: { throw new Error( format(PTR_INVALID_POINTER_TYPE, getTargetPointerType(p)) ); } } } __name(copyFrom, "copyFrom"); function erase(p) { if (isNull(p)) return; let c; switch (getTargetPointerType(p)) { case PointerType.STRUCT: { const size = getTargetStructSize(p); c = getContent(p); c.segment.fillZeroWords(c.byteOffset, size.dataByteLength / 8); for (let i = 0; i < size.pointerLength; i++) { erase(add(i * 8, c)); } break; } case PointerType.LIST: { const elementSize = getTargetListElementSize(p); const length = getTargetListLength(p); let contentWords = padToWord$1( length * getListElementByteLength(elementSize) ); c = getContent(p); if (elementSize === ListElementSize.POINTER) { for (let i = 0; i < length; i++) { erase( new Pointer( c.segment, c.byteOffset + i * 8, p._capnp.depthLimit - 1 ) ); } break; } else if (elementSize === ListElementSize.COMPOSITE) { const tag = add(-8, c); const compositeSize = getStructSize(tag); const compositeByteLength = getByteLength(compositeSize); contentWords = getOffsetWords(tag); c.segment.setWordZero(c.byteOffset - 8); for (let i = 0; i < length; i++) { for (let j = 0; j < compositeSize.pointerLength; j++) { erase( new Pointer( c.segment, c.byteOffset + i * compositeByteLength + j * 8, p._capnp.depthLimit - 1 ) ); } } } c.segment.fillZeroWords(c.byteOffset, contentWords); break; } case PointerType.OTHER: { break; } default: { throw new Error( format(PTR_INVALID_POINTER_TYPE, getTargetPointerType(p)) ); } } erasePointer(p); } __name(erase, "erase"); function erasePointer(p) { if (getPointerType(p) === PointerType.FAR) { const landingPad = followFar(p); if (isDoubleFar(p)) { landingPad.segment.setWordZero(landingPad.byteOffset + 8); } landingPad.segment.setWordZero(landingPad.byteOffset); } p.segment.setWordZero(p.byteOffset); } __name(erasePointer, "erasePointer"); function followFar(p) { const targetSegment = p.segment.message.getSegment( p.segment.getUint32(p.byteOffset + 4) ); const targetWordOffset = p.segment.getUint32(p.byteOffset) >>> 3; return new Pointer( targetSegment, targetWordOffset * 8, p._capnp.depthLimit - 1 ); } __name(followFar, "followFar"); function followFars(p) { if (getPointerType(p) === PointerType.FAR) { const landingPad = followFar(p); if (isDoubleFar(p)) { landingPad.byteOffset += 8; } return landingPad; } return p; } __name(followFars, "followFars"); function getCapabilityId(p) { return p.segment.getUint32(p.byteOffset + 4); } __name(getCapabilityId, "getCapabilityId"); function isCompositeList(p) { return getTargetPointerType(p) === PointerType.LIST && getTargetListElementSize(p) === ListElementSize.COMPOSITE; } __name(isCompositeList, "isCompositeList"); function getContent(p, ignoreCompositeIndex) { let c; if (isDoubleFar(p)) { const landingPad = followFar(p); c = new Pointer( p.segment.message.getSegment(getFarSegmentId(landingPad)), getOffsetWords(landingPad) * 8 ); } else { const target = followFars(p); c = new Pointer( target.segment, target.byteOffset + 8 + getOffsetWords(target) * 8 ); } if (isCompositeList(p)) { c.byteOffset += 8; } if (!ignoreCompositeIndex && p._capnp.compositeIndex !== void 0) { c.byteOffset -= 8; c.byteOffset += 8 + p._capnp.compositeIndex * getByteLength(padToWord(getStructSize(c))); } return c; } __name(getContent, "getContent"); function getFarSegmentId(p) { return p.segment.getUint32(p.byteOffset + 4); } __name(getFarSegmentId, "getFarSegmentId"); function getListElementSize(p) { return p.segment.getUint32(p.byteOffset + 4) & LIST_SIZE_MASK; } __name(getListElementSize, "getListElementSize"); function getListLength(p) { return p.segment.getUint32(p.byteOffset + 4) >>> 3; } __name(getListLength, "getListLength"); function getOffsetWords(p) { const o = p.segment.getInt32(p.byteOffset); return o & 2 ? o >> 3 : o >> 2; } __name(getOffsetWords, "getOffsetWords"); function getPointerType(p) { return p.segment.getUint32(p.byteOffset) & POINTER_TYPE_MASK; } __name(getPointerType, "getPointerType"); function getStructDataWords(p) { return p.segment.getUint16(p.byteOffset + 4); } __name(getStructDataWords, "getStructDataWords"); function getStructPointerLength(p) { return p.segment.getUint16(p.byteOffset + 6); } __name(getStructPointerLength, "getStructPointerLength"); function getStructSize(p) { return new ObjectSize(getStructDataWords(p) * 8, getStructPointerLength(p)); } __name(getStructSize, "getStructSize"); function getTargetCompositeListTag(p) { const c = getContent(p); c.byteOffset -= 8; return c; } __name(getTargetCompositeListTag, "getTargetCompositeListTag"); function getTargetCompositeListSize(p) { return getStructSize(getTargetCompositeListTag(p)); } __name(getTargetCompositeListSize, "getTargetCompositeListSize"); function getTargetListElementSize(p) { return getListElementSize(followFars(p)); } __name(getTargetListElementSize, "getTargetListElementSize"); function getTargetListLength(p) { const t = followFars(p); if (getListElementSize(t) === ListElementSize.COMPOSITE) { return getOffsetWords(getTargetCompositeListTag(p)); } return getListLength(t); } __name(getTargetListLength, "getTargetListLength"); function getTargetPointerType(p) { const t = getPointerType(followFars(p)); if (t === PointerType.FAR) { throw new Error(format(PTR_INVALID_FAR_TARGET, p)); } return t; } __name(getTargetPointerType, "getTargetPointerType"); function getTargetStructSize(p) { return getStructSize(followFars(p)); } __name(getTargetStructSize, "getTargetStructSize"); function initPointer(contentSegment, contentOffset, p) { if (p.segment !== contentSegment) { if (!contentSegment.hasCapacity(8)) { const landingPad2 = p.segment.allocate(16); setFarPointer(true, landingPad2.byteOffset / 8, landingPad2.segment.id, p); setFarPointer(false, contentOffset / 8, contentSegment.id, landingPad2); landingPad2.byteOffset += 8; return new PointerAllocationResult(landingPad2, 0); } const landingPad = contentSegment.allocate(8); if (landingPad.segment.id !== contentSegment.id) { throw new Error(INVARIANT_UNREACHABLE_CODE); } setFarPointer(false, landingPad.byteOffset / 8, landingPad.segment.id, p); return new PointerAllocationResult( landingPad, (contentOffset - landingPad.byteOffset - 8) / 8 ); } return new PointerAllocationResult(p, (contentOffset - p.byteOffset - 8) / 8); } __name(initPointer, "initPointer"); function isDoubleFar(p) { return getPointerType(p) === PointerType.FAR && (p.segment.getUint32(p.byteOffset) & POINTER_DOUBLE_FAR_MASK) !== 0; } __name(isDoubleFar, "isDoubleFar"); function isNull(p) { return p.segment.isWordZero(p.byteOffset); } __name(isNull, "isNull"); function setFarPointer(doubleFar, offsetWords, segmentId, p) { const A = PointerType.FAR; const B = doubleFar ? 1 : 0; const C = offsetWords; const D = segmentId; p.segment.setUint32(p.byteOffset, A | B << 2 | C << 3); p.segment.setUint32(p.byteOffset + 4, D); } __name(setFarPointer, "setFarPointer"); function setInterfacePointer(capId, p) { p.segment.setUint32(p.byteOffset, PointerType.OTHER); p.segment.setUint32(p.byteOffset + 4, capId); } __name(setInterfacePointer, "setInterfacePointer"); function getInterfacePointer(p) { return p.segment.getUint32(p.byteOffset + 4); } __name(getInterfacePointer, "getInterfacePointer"); function setListPointer(offsetWords, size, length, p, compositeSize) { const A = PointerType.LIST; const B = offsetWords; const C = size; let D = length; if (size === ListElementSize.COMPOSITE) { if (compositeSize === void 0) { throw new TypeError(TYPE_COMPOSITE_SIZE_UNDEFINED); } D *= getWordLength(compositeSize); } p.segment.setUint32(p.byteOffset, A | B << 2); p.segment.setUint32(p.byt