recital / exporters / ink / dist / cli.js
cli.js
Raw
#!/usr/bin/env node
var __getOwnPropNames2 = Object.getOwnPropertyNames;
var __commonJS2 = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};

// ../../core/dist/stage-parser.js
var require_stage_parser = __commonJS2({
  "../../core/dist/stage-parser.js"(exports, module) {
    "use strict";
    var __create = Object.create;
    var __defProp = Object.defineProperty;
    var __defProps = Object.defineProperties;
    var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
    var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
    var __getOwnPropNames = Object.getOwnPropertyNames;
    var __getOwnPropSymbols = Object.getOwnPropertySymbols;
    var __getProtoOf = Object.getPrototypeOf;
    var __hasOwnProp = Object.prototype.hasOwnProperty;
    var __propIsEnum = Object.prototype.propertyIsEnumerable;
    var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
    var __spreadValues = (a, b) => {
      for (var prop in b || (b = {}))
        if (__hasOwnProp.call(b, prop))
          __defNormalProp(a, prop, b[prop]);
      if (__getOwnPropSymbols)
        for (var prop of __getOwnPropSymbols(b)) {
          if (__propIsEnum.call(b, prop))
            __defNormalProp(a, prop, b[prop]);
        }
      return a;
    };
    var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
    var __commonJS = (cb, mod) => function __require() {
      return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
    };
    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(
      isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
      mod
    ));
    var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
    var require_moo = __commonJS({
      "../node_modules/.pnpm/moo@0.5.2/node_modules/moo/moo.js"(exports2, module2) {
        (function(root, factory) {
          if (typeof define === "function" && define.amd) {
            define([], factory);
          } else if (typeof module2 === "object" && module2.exports) {
            module2.exports = factory();
          } else {
            root.moo = factory();
          }
        })(exports2, function() {
          "use strict";
          var hasOwnProperty2 = Object.prototype.hasOwnProperty;
          var toString = Object.prototype.toString;
          var hasSticky = typeof new RegExp().sticky === "boolean";
          function isRegExp(o) {
            return o && toString.call(o) === "[object RegExp]";
          }
          function isObject(o) {
            return o && typeof o === "object" && !isRegExp(o) && !Array.isArray(o);
          }
          function reEscape(s) {
            return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
          }
          function reGroups(s) {
            var re = new RegExp("|" + s);
            return re.exec("").length - 1;
          }
          function reCapture(s) {
            return "(" + s + ")";
          }
          function reUnion(regexps) {
            if (!regexps.length)
              return "(?!)";
            var source = regexps.map(function(s) {
              return "(?:" + s + ")";
            }).join("|");
            return "(?:" + source + ")";
          }
          function regexpOrLiteral(obj) {
            if (typeof obj === "string") {
              return "(?:" + reEscape(obj) + ")";
            } else if (isRegExp(obj)) {
              if (obj.ignoreCase)
                throw new Error("RegExp /i flag not allowed");
              if (obj.global)
                throw new Error("RegExp /g flag is implied");
              if (obj.sticky)
                throw new Error("RegExp /y flag is implied");
              if (obj.multiline)
                throw new Error("RegExp /m flag is implied");
              return obj.source;
            } else {
              throw new Error("Not a pattern: " + obj);
            }
          }
          function pad(s, length) {
            if (s.length > length) {
              return s;
            }
            return Array(length - s.length + 1).join(" ") + s;
          }
          function lastNLines(string, numLines) {
            var position = string.length;
            var lineBreaks = 0;
            while (true) {
              var idx = string.lastIndexOf("\n", position - 1);
              if (idx === -1) {
                break;
              } else {
                lineBreaks++;
              }
              position = idx;
              if (lineBreaks === numLines) {
                break;
              }
              if (position === 0) {
                break;
              }
            }
            var startPosition = lineBreaks < numLines ? 0 : position + 1;
            return string.substring(startPosition).split("\n");
          }
          function objectToRules(object) {
            var keys = Object.getOwnPropertyNames(object);
            var result = [];
            for (var i = 0; i < keys.length; i++) {
              var key = keys[i];
              var thing = object[key];
              var rules = [].concat(thing);
              if (key === "include") {
                for (var j = 0; j < rules.length; j++) {
                  result.push({ include: rules[j] });
                }
                continue;
              }
              var match = [];
              rules.forEach(function(rule) {
                if (isObject(rule)) {
                  if (match.length)
                    result.push(ruleOptions(key, match));
                  result.push(ruleOptions(key, rule));
                  match = [];
                } else {
                  match.push(rule);
                }
              });
              if (match.length)
                result.push(ruleOptions(key, match));
            }
            return result;
          }
          function arrayToRules(array) {
            var result = [];
            for (var i = 0; i < array.length; i++) {
              var obj = array[i];
              if (obj.include) {
                var include = [].concat(obj.include);
                for (var j = 0; j < include.length; j++) {
                  result.push({ include: include[j] });
                }
                continue;
              }
              if (!obj.type) {
                throw new Error("Rule has no type: " + JSON.stringify(obj));
              }
              result.push(ruleOptions(obj.type, obj));
            }
            return result;
          }
          function ruleOptions(type, obj) {
            if (!isObject(obj)) {
              obj = { match: obj };
            }
            if (obj.include) {
              throw new Error("Matching rules cannot also include states");
            }
            var options = {
              defaultType: type,
              lineBreaks: !!obj.error || !!obj.fallback,
              pop: false,
              next: null,
              push: null,
              error: false,
              fallback: false,
              value: null,
              type: null,
              shouldThrow: false
            };
            for (var key in obj) {
              if (hasOwnProperty2.call(obj, key)) {
                options[key] = obj[key];
              }
            }
            if (typeof options.type === "string" && type !== options.type) {
              throw new Error("Type transform cannot be a string (type '" + options.type + "' for token '" + type + "')");
            }
            var match = options.match;
            options.match = Array.isArray(match) ? match : match ? [match] : [];
            options.match.sort(function(a, b) {
              return isRegExp(a) && isRegExp(b) ? 0 : isRegExp(b) ? -1 : isRegExp(a) ? 1 : b.length - a.length;
            });
            return options;
          }
          function toRules(spec) {
            return Array.isArray(spec) ? arrayToRules(spec) : objectToRules(spec);
          }
          var defaultErrorRule = ruleOptions("error", { lineBreaks: true, shouldThrow: true });
          function compileRules(rules, hasStates) {
            var errorRule = null;
            var fast = /* @__PURE__ */ Object.create(null);
            var fastAllowed = true;
            var unicodeFlag = null;
            var groups = [];
            var parts = [];
            for (var i = 0; i < rules.length; i++) {
              if (rules[i].fallback) {
                fastAllowed = false;
              }
            }
            for (var i = 0; i < rules.length; i++) {
              var options = rules[i];
              if (options.include) {
                throw new Error("Inheritance is not allowed in stateless lexers");
              }
              if (options.error || options.fallback) {
                if (errorRule) {
                  if (!options.fallback === !errorRule.fallback) {
                    throw new Error("Multiple " + (options.fallback ? "fallback" : "error") + " rules not allowed (for token '" + options.defaultType + "')");
                  } else {
                    throw new Error("fallback and error are mutually exclusive (for token '" + options.defaultType + "')");
                  }
                }
                errorRule = options;
              }
              var match = options.match.slice();
              if (fastAllowed) {
                while (match.length && typeof match[0] === "string" && match[0].length === 1) {
                  var word = match.shift();
                  fast[word.charCodeAt(0)] = options;
                }
              }
              if (options.pop || options.push || options.next) {
                if (!hasStates) {
                  throw new Error("State-switching options are not allowed in stateless lexers (for token '" + options.defaultType + "')");
                }
                if (options.fallback) {
                  throw new Error("State-switching options are not allowed on fallback tokens (for token '" + options.defaultType + "')");
                }
              }
              if (match.length === 0) {
                continue;
              }
              fastAllowed = false;
              groups.push(options);
              for (var j = 0; j < match.length; j++) {
                var obj = match[j];
                if (!isRegExp(obj)) {
                  continue;
                }
                if (unicodeFlag === null) {
                  unicodeFlag = obj.unicode;
                } else if (unicodeFlag !== obj.unicode && options.fallback === false) {
                  throw new Error("If one rule is /u then all must be");
                }
              }
              var pat = reUnion(match.map(regexpOrLiteral));
              var regexp = new RegExp(pat);
              if (regexp.test("")) {
                throw new Error("RegExp matches empty string: " + regexp);
              }
              var groupCount = reGroups(pat);
              if (groupCount > 0) {
                throw new Error("RegExp has capture groups: " + regexp + "\nUse (?: \u2026 ) instead");
              }
              if (!options.lineBreaks && regexp.test("\n")) {
                throw new Error("Rule should declare lineBreaks: " + regexp);
              }
              parts.push(reCapture(pat));
            }
            var fallbackRule = errorRule && errorRule.fallback;
            var flags = hasSticky && !fallbackRule ? "ym" : "gm";
            var suffix = hasSticky || fallbackRule ? "" : "|";
            if (unicodeFlag === true)
              flags += "u";
            var combined = new RegExp(reUnion(parts) + suffix, flags);
            return { regexp: combined, groups, fast, error: errorRule || defaultErrorRule };
          }
          function compile(rules) {
            var result = compileRules(toRules(rules));
            return new Lexer({ start: result }, "start");
          }
          function checkStateGroup(g, name, map) {
            var state = g && (g.push || g.next);
            if (state && !map[state]) {
              throw new Error("Missing state '" + state + "' (in token '" + g.defaultType + "' of state '" + name + "')");
            }
            if (g && g.pop && +g.pop !== 1) {
              throw new Error("pop must be 1 (in token '" + g.defaultType + "' of state '" + name + "')");
            }
          }
          function compileStates(states, start) {
            var all = states.$all ? toRules(states.$all) : [];
            delete states.$all;
            var keys = Object.getOwnPropertyNames(states);
            if (!start)
              start = keys[0];
            var ruleMap = /* @__PURE__ */ Object.create(null);
            for (var i = 0; i < keys.length; i++) {
              var key = keys[i];
              ruleMap[key] = toRules(states[key]).concat(all);
            }
            for (var i = 0; i < keys.length; i++) {
              var key = keys[i];
              var rules = ruleMap[key];
              var included = /* @__PURE__ */ Object.create(null);
              for (var j = 0; j < rules.length; j++) {
                var rule = rules[j];
                if (!rule.include)
                  continue;
                var splice = [j, 1];
                if (rule.include !== key && !included[rule.include]) {
                  included[rule.include] = true;
                  var newRules = ruleMap[rule.include];
                  if (!newRules) {
                    throw new Error("Cannot include nonexistent state '" + rule.include + "' (in state '" + key + "')");
                  }
                  for (var k = 0; k < newRules.length; k++) {
                    var newRule = newRules[k];
                    if (rules.indexOf(newRule) !== -1)
                      continue;
                    splice.push(newRule);
                  }
                }
                rules.splice.apply(rules, splice);
                j--;
              }
            }
            var map = /* @__PURE__ */ Object.create(null);
            for (var i = 0; i < keys.length; i++) {
              var key = keys[i];
              map[key] = compileRules(ruleMap[key], true);
            }
            for (var i = 0; i < keys.length; i++) {
              var name = keys[i];
              var state = map[name];
              var groups = state.groups;
              for (var j = 0; j < groups.length; j++) {
                checkStateGroup(groups[j], name, map);
              }
              var fastKeys = Object.getOwnPropertyNames(state.fast);
              for (var j = 0; j < fastKeys.length; j++) {
                checkStateGroup(state.fast[fastKeys[j]], name, map);
              }
            }
            return new Lexer(map, start);
          }
          function keywordTransform(map) {
            var isMap = typeof Map !== "undefined";
            var reverseMap = isMap ? /* @__PURE__ */ new Map() : /* @__PURE__ */ Object.create(null);
            var types = Object.getOwnPropertyNames(map);
            for (var i = 0; i < types.length; i++) {
              var tokenType = types[i];
              var item = map[tokenType];
              var keywordList = Array.isArray(item) ? item : [item];
              keywordList.forEach(function(keyword) {
                if (typeof keyword !== "string") {
                  throw new Error("keyword must be string (in keyword '" + tokenType + "')");
                }
                if (isMap) {
                  reverseMap.set(keyword, tokenType);
                } else {
                  reverseMap[keyword] = tokenType;
                }
              });
            }
            return function(k) {
              return isMap ? reverseMap.get(k) : reverseMap[k];
            };
          }
          var Lexer = function(states, state) {
            this.startState = state;
            this.states = states;
            this.buffer = "";
            this.stack = [];
            this.reset();
          };
          Lexer.prototype.reset = function(data, info) {
            this.buffer = data || "";
            this.index = 0;
            this.line = info ? info.line : 1;
            this.col = info ? info.col : 1;
            this.queuedToken = info ? info.queuedToken : null;
            this.queuedText = info ? info.queuedText : "";
            this.queuedThrow = info ? info.queuedThrow : null;
            this.setState(info ? info.state : this.startState);
            this.stack = info && info.stack ? info.stack.slice() : [];
            return this;
          };
          Lexer.prototype.save = function() {
            return {
              line: this.line,
              col: this.col,
              state: this.state,
              stack: this.stack.slice(),
              queuedToken: this.queuedToken,
              queuedText: this.queuedText,
              queuedThrow: this.queuedThrow
            };
          };
          Lexer.prototype.setState = function(state) {
            if (!state || this.state === state)
              return;
            this.state = state;
            var info = this.states[state];
            this.groups = info.groups;
            this.error = info.error;
            this.re = info.regexp;
            this.fast = info.fast;
          };
          Lexer.prototype.popState = function() {
            this.setState(this.stack.pop());
          };
          Lexer.prototype.pushState = function(state) {
            this.stack.push(this.state);
            this.setState(state);
          };
          var eat = hasSticky ? function(re, buffer) {
            return re.exec(buffer);
          } : function(re, buffer) {
            var match = re.exec(buffer);
            if (match[0].length === 0) {
              return null;
            }
            return match;
          };
          Lexer.prototype._getGroup = function(match) {
            var groupCount = this.groups.length;
            for (var i = 0; i < groupCount; i++) {
              if (match[i + 1] !== void 0) {
                return this.groups[i];
              }
            }
            throw new Error("Cannot find token type for matched text");
          };
          function tokenToString() {
            return this.value;
          }
          Lexer.prototype.next = function() {
            var index = this.index;
            if (this.queuedGroup) {
              var token = this._token(this.queuedGroup, this.queuedText, index);
              this.queuedGroup = null;
              this.queuedText = "";
              return token;
            }
            var buffer = this.buffer;
            if (index === buffer.length) {
              return;
            }
            var group = this.fast[buffer.charCodeAt(index)];
            if (group) {
              return this._token(group, buffer.charAt(index), index);
            }
            var re = this.re;
            re.lastIndex = index;
            var match = eat(re, buffer);
            var error = this.error;
            if (match == null) {
              return this._token(error, buffer.slice(index, buffer.length), index);
            }
            var group = this._getGroup(match);
            var text = match[0];
            if (error.fallback && match.index !== index) {
              this.queuedGroup = group;
              this.queuedText = text;
              return this._token(error, buffer.slice(index, match.index), index);
            }
            return this._token(group, text, index);
          };
          Lexer.prototype._token = function(group, text, offset) {
            var lineBreaks = 0;
            if (group.lineBreaks) {
              var matchNL = /\n/g;
              var nl = 1;
              if (text === "\n") {
                lineBreaks = 1;
              } else {
                while (matchNL.exec(text)) {
                  lineBreaks++;
                  nl = matchNL.lastIndex;
                }
              }
            }
            var token = {
              type: typeof group.type === "function" && group.type(text) || group.defaultType,
              value: typeof group.value === "function" ? group.value(text) : text,
              text,
              toString: tokenToString,
              offset,
              lineBreaks,
              line: this.line,
              col: this.col
            };
            var size = text.length;
            this.index += size;
            this.line += lineBreaks;
            if (lineBreaks !== 0) {
              this.col = size - nl + 1;
            } else {
              this.col += size;
            }
            if (group.shouldThrow) {
              var err = new Error(this.formatError(token, "invalid syntax"));
              throw err;
            }
            if (group.pop)
              this.popState();
            else if (group.push)
              this.pushState(group.push);
            else if (group.next)
              this.setState(group.next);
            return token;
          };
          if (typeof Symbol !== "undefined" && Symbol.iterator) {
            var LexerIterator = function(lexer) {
              this.lexer = lexer;
            };
            LexerIterator.prototype.next = function() {
              var token = this.lexer.next();
              return { value: token, done: !token };
            };
            LexerIterator.prototype[Symbol.iterator] = function() {
              return this;
            };
            Lexer.prototype[Symbol.iterator] = function() {
              return new LexerIterator(this);
            };
          }
          Lexer.prototype.formatError = function(token, message) {
            if (token == null) {
              var text = this.buffer.slice(this.index);
              var token = {
                text,
                offset: this.index,
                lineBreaks: text.indexOf("\n") === -1 ? 0 : 1,
                line: this.line,
                col: this.col
              };
            }
            var numLinesAround = 2;
            var firstDisplayedLine = Math.max(token.line - numLinesAround, 1);
            var lastDisplayedLine = token.line + numLinesAround;
            var lastLineDigits = String(lastDisplayedLine).length;
            var displayedLines = lastNLines(
              this.buffer,
              this.line - token.line + numLinesAround + 1
            ).slice(0, 5);
            var errorLines = [];
            errorLines.push(message + " at line " + token.line + " col " + token.col + ":");
            errorLines.push("");
            for (var i = 0; i < displayedLines.length; i++) {
              var line = displayedLines[i];
              var lineNo = firstDisplayedLine + i;
              errorLines.push(pad(String(lineNo), lastLineDigits) + "  " + line);
              if (lineNo === token.line) {
                errorLines.push(pad("", lastLineDigits + token.col + 1) + "^");
              }
            }
            return errorLines.join("\n");
          };
          Lexer.prototype.clone = function() {
            return new Lexer(this.states, this.state);
          };
          Lexer.prototype.has = function(tokenType) {
            return true;
          };
          return {
            compile,
            states: compileStates,
            error: Object.freeze({ error: true }),
            fallback: Object.freeze({ fallback: true }),
            keywords: keywordTransform
          };
        });
      }
    });
    var require_eol = __commonJS({
      "../node_modules/.pnpm/eol@0.9.1/node_modules/eol/eol.js"(exports2, module2) {
        !function(root, name, make) {
          if (typeof module2 != "undefined" && module2.exports)
            module2.exports = make();
          else
            root[name] = make();
        }(exports2, "eol", function() {
          var api = {};
          var isWindows = typeof process != "undefined" && "win32" === process.platform;
          var linebreak = isWindows ? "\r\n" : "\n";
          var newline = /\r\n|\r|\n/g;
          function before(text) {
            return linebreak + text;
          }
          function after(text) {
            return text + linebreak;
          }
          function converts(to) {
            function convert(text) {
              return text.replace(newline, to);
            }
            convert.toString = function() {
              return to;
            };
            return convert;
          }
          function split(text) {
            return text.split(newline);
          }
          api["lf"] = converts("\n");
          api["cr"] = converts("\r");
          api["crlf"] = converts("\r\n");
          api["auto"] = converts(linebreak);
          api["before"] = before;
          api["after"] = after;
          api["split"] = split;
          return api;
        });
      }
    });
    var require_parser = __commonJS({
      "../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/parser.js"(exports2, module2) {
        "use strict";
        var ParserEND = 1114112;
        var ParserError = class extends Error {
          constructor(msg, filename, linenumber) {
            super("[ParserError] " + msg, filename, linenumber);
            this.name = "ParserError";
            this.code = "ParserError";
            if (Error.captureStackTrace)
              Error.captureStackTrace(this, ParserError);
          }
        };
        var State = class {
          constructor(parser) {
            this.parser = parser;
            this.buf = "";
            this.returned = null;
            this.result = null;
            this.resultTable = null;
            this.resultArr = null;
          }
        };
        var Parser = class {
          constructor() {
            this.pos = 0;
            this.col = 0;
            this.line = 0;
            this.obj = {};
            this.ctx = this.obj;
            this.stack = [];
            this._buf = "";
            this.char = null;
            this.ii = 0;
            this.state = new State(this.parseStart);
          }
          parse(str) {
            if (str.length === 0 || str.length == null)
              return;
            this._buf = String(str);
            this.ii = -1;
            this.char = -1;
            let getNext;
            while (getNext === false || this.nextChar()) {
              getNext = this.runOne();
            }
            this._buf = null;
          }
          nextChar() {
            if (this.char === 10) {
              ++this.line;
              this.col = -1;
            }
            ++this.ii;
            this.char = this._buf.codePointAt(this.ii);
            ++this.pos;
            ++this.col;
            return this.haveBuffer();
          }
          haveBuffer() {
            return this.ii < this._buf.length;
          }
          runOne() {
            return this.state.parser.call(this, this.state.returned);
          }
          finish() {
            this.char = ParserEND;
            let last;
            do {
              last = this.state.parser;
              this.runOne();
            } while (this.state.parser !== last);
            this.ctx = null;
            this.state = null;
            this._buf = null;
            return this.obj;
          }
          next(fn) {
            if (typeof fn !== "function")
              throw new ParserError("Tried to set state to non-existent state: " + JSON.stringify(fn));
            this.state.parser = fn;
          }
          goto(fn) {
            this.next(fn);
            return this.runOne();
          }
          call(fn, returnWith) {
            if (returnWith)
              this.next(returnWith);
            this.stack.push(this.state);
            this.state = new State(fn);
          }
          callNow(fn, returnWith) {
            this.call(fn, returnWith);
            return this.runOne();
          }
          return(value) {
            if (this.stack.length === 0)
              throw this.error(new ParserError("Stack underflow"));
            if (value === void 0)
              value = this.state.buf;
            this.state = this.stack.pop();
            this.state.returned = value;
          }
          returnNow(value) {
            this.return(value);
            return this.runOne();
          }
          consume() {
            if (this.char === ParserEND)
              throw this.error(new ParserError("Unexpected end-of-buffer"));
            this.state.buf += this._buf[this.ii];
          }
          error(err) {
            err.line = this.line;
            err.col = this.col;
            err.pos = this.pos;
            return err;
          }
          parseStart() {
            throw new ParserError("Must declare a parseStart method");
          }
        };
        Parser.END = ParserEND;
        Parser.Error = ParserError;
        module2.exports = Parser;
      }
    });
    var require_create_datetime = __commonJS({
      "../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime.js"(exports2, module2) {
        "use strict";
        module2.exports = (value) => {
          const date = new Date(value);
          if (isNaN(date)) {
            throw new TypeError("Invalid Datetime");
          } else {
            return date;
          }
        };
      }
    });
    var require_format_num = __commonJS({
      "../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/format-num.js"(exports2, module2) {
        "use strict";
        module2.exports = (d, num) => {
          num = String(num);
          while (num.length < d)
            num = "0" + num;
          return num;
        };
      }
    });
    var require_create_datetime_float = __commonJS({
      "../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime-float.js"(exports2, module2) {
        "use strict";
        var f = require_format_num();
        var FloatingDateTime = class extends Date {
          constructor(value) {
            super(value + "Z");
            this.isFloating = true;
          }
          toISOString() {
            const date = `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`;
            const time = `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`;
            return `${date}T${time}`;
          }
        };
        module2.exports = (value) => {
          const date = new FloatingDateTime(value);
          if (isNaN(date)) {
            throw new TypeError("Invalid Datetime");
          } else {
            return date;
          }
        };
      }
    });
    var require_create_date = __commonJS({
      "../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-date.js"(exports2, module2) {
        "use strict";
        var f = require_format_num();
        var DateTime = global.Date;
        var Date2 = class extends DateTime {
          constructor(value) {
            super(value);
            this.isDate = true;
          }
          toISOString() {
            return `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`;
          }
        };
        module2.exports = (value) => {
          const date = new Date2(value);
          if (isNaN(date)) {
            throw new TypeError("Invalid Datetime");
          } else {
            return date;
          }
        };
      }
    });
    var require_create_time = __commonJS({
      "../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-time.js"(exports2, module2) {
        "use strict";
        var f = require_format_num();
        var Time = class extends Date {
          constructor(value) {
            super(`0000-01-01T${value}Z`);
            this.isTime = true;
          }
          toISOString() {
            return `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`;
          }
        };
        module2.exports = (value) => {
          const date = new Time(value);
          if (isNaN(date)) {
            throw new TypeError("Invalid Datetime");
          } else {
            return date;
          }
        };
      }
    });
    var require_toml_parser = __commonJS({
      "../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/toml-parser.js"(exports, module) {
        "use strict";
        module.exports = makeParserClass(require_parser());
        module.exports.makeParserClass = makeParserClass;
        var TomlError = class extends Error {
          constructor(msg) {
            super(msg);
            this.name = "TomlError";
            if (Error.captureStackTrace)
              Error.captureStackTrace(this, TomlError);
            this.fromTOML = true;
            this.wrapped = null;
          }
        };
        TomlError.wrap = (err) => {
          const terr = new TomlError(err.message);
          terr.code = err.code;
          terr.wrapped = err;
          return terr;
        };
        module.exports.TomlError = TomlError;
        var createDateTime = require_create_datetime();
        var createDateTimeFloat = require_create_datetime_float();
        var createDate = require_create_date();
        var createTime = require_create_time();
        var CTRL_I = 9;
        var CTRL_J = 10;
        var CTRL_M = 13;
        var CTRL_CHAR_BOUNDARY = 31;
        var CHAR_SP = 32;
        var CHAR_QUOT = 34;
        var CHAR_NUM = 35;
        var CHAR_APOS = 39;
        var CHAR_PLUS = 43;
        var CHAR_COMMA = 44;
        var CHAR_HYPHEN = 45;
        var CHAR_PERIOD = 46;
        var CHAR_0 = 48;
        var CHAR_1 = 49;
        var CHAR_7 = 55;
        var CHAR_9 = 57;
        var CHAR_COLON = 58;
        var CHAR_EQUALS = 61;
        var CHAR_A = 65;
        var CHAR_E = 69;
        var CHAR_F = 70;
        var CHAR_T = 84;
        var CHAR_U = 85;
        var CHAR_Z = 90;
        var CHAR_LOWBAR = 95;
        var CHAR_a = 97;
        var CHAR_b = 98;
        var CHAR_e = 101;
        var CHAR_f = 102;
        var CHAR_i = 105;
        var CHAR_l = 108;
        var CHAR_n = 110;
        var CHAR_o = 111;
        var CHAR_r = 114;
        var CHAR_s = 115;
        var CHAR_t = 116;
        var CHAR_u = 117;
        var CHAR_x = 120;
        var CHAR_z = 122;
        var CHAR_LCUB = 123;
        var CHAR_RCUB = 125;
        var CHAR_LSQB = 91;
        var CHAR_BSOL = 92;
        var CHAR_RSQB = 93;
        var CHAR_DEL = 127;
        var SURROGATE_FIRST = 55296;
        var SURROGATE_LAST = 57343;
        var escapes = {
          [CHAR_b]: "\b",
          [CHAR_t]: "	",
          [CHAR_n]: "\n",
          [CHAR_f]: "\f",
          [CHAR_r]: "\r",
          [CHAR_QUOT]: '"',
          [CHAR_BSOL]: "\\"
        };
        function isDigit(cp) {
          return cp >= CHAR_0 && cp <= CHAR_9;
        }
        function isHexit(cp) {
          return cp >= CHAR_A && cp <= CHAR_F || cp >= CHAR_a && cp <= CHAR_f || cp >= CHAR_0 && cp <= CHAR_9;
        }
        function isBit(cp) {
          return cp === CHAR_1 || cp === CHAR_0;
        }
        function isOctit(cp) {
          return cp >= CHAR_0 && cp <= CHAR_7;
        }
        function isAlphaNumQuoteHyphen(cp) {
          return cp >= CHAR_A && cp <= CHAR_Z || cp >= CHAR_a && cp <= CHAR_z || cp >= CHAR_0 && cp <= CHAR_9 || cp === CHAR_APOS || cp === CHAR_QUOT || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN;
        }
        function isAlphaNumHyphen(cp) {
          return cp >= CHAR_A && cp <= CHAR_Z || cp >= CHAR_a && cp <= CHAR_z || cp >= CHAR_0 && cp <= CHAR_9 || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN;
        }
        var _type = Symbol("type");
        var _declared = Symbol("declared");
        var hasOwnProperty = Object.prototype.hasOwnProperty;
        var defineProperty = Object.defineProperty;
        var descriptor = { configurable: true, enumerable: true, writable: true, value: void 0 };
        function hasKey(obj, key) {
          if (hasOwnProperty.call(obj, key))
            return true;
          if (key === "__proto__")
            defineProperty(obj, "__proto__", descriptor);
          return false;
        }
        var INLINE_TABLE = Symbol("inline-table");
        function InlineTable() {
          return Object.defineProperties({}, {
            [_type]: { value: INLINE_TABLE }
          });
        }
        function isInlineTable(obj) {
          if (obj === null || typeof obj !== "object")
            return false;
          return obj[_type] === INLINE_TABLE;
        }
        var TABLE = Symbol("table");
        function Table() {
          return Object.defineProperties({}, {
            [_type]: { value: TABLE },
            [_declared]: { value: false, writable: true }
          });
        }
        function isTable(obj) {
          if (obj === null || typeof obj !== "object")
            return false;
          return obj[_type] === TABLE;
        }
        var _contentType = Symbol("content-type");
        var INLINE_LIST = Symbol("inline-list");
        function InlineList(type) {
          return Object.defineProperties([], {
            [_type]: { value: INLINE_LIST },
            [_contentType]: { value: type }
          });
        }
        function isInlineList(obj) {
          if (obj === null || typeof obj !== "object")
            return false;
          return obj[_type] === INLINE_LIST;
        }
        var LIST = Symbol("list");
        function List() {
          return Object.defineProperties([], {
            [_type]: { value: LIST }
          });
        }
        function isList(obj) {
          if (obj === null || typeof obj !== "object")
            return false;
          return obj[_type] === LIST;
        }
        var _custom;
        try {
          const utilInspect = eval("require('util').inspect");
          _custom = utilInspect.custom;
        } catch (_) {
        }
        var _inspect = _custom || "inspect";
        var BoxedBigInt = class {
          constructor(value) {
            try {
              this.value = global.BigInt.asIntN(64, value);
            } catch (_) {
              this.value = null;
            }
            Object.defineProperty(this, _type, { value: INTEGER });
          }
          isNaN() {
            return this.value === null;
          }
          toString() {
            return String(this.value);
          }
          [_inspect]() {
            return `[BigInt: ${this.toString()}]}`;
          }
          valueOf() {
            return this.value;
          }
        };
        var INTEGER = Symbol("integer");
        function Integer(value) {
          let num = Number(value);
          if (Object.is(num, -0))
            num = 0;
          if (global.BigInt && !Number.isSafeInteger(num)) {
            return new BoxedBigInt(value);
          } else {
            return Object.defineProperties(new Number(num), {
              isNaN: { value: function() {
                return isNaN(this);
              } },
              [_type]: { value: INTEGER },
              [_inspect]: { value: () => `[Integer: ${value}]` }
            });
          }
        }
        function isInteger(obj) {
          if (obj === null || typeof obj !== "object")
            return false;
          return obj[_type] === INTEGER;
        }
        var FLOAT = Symbol("float");
        function Float(value) {
          return Object.defineProperties(new Number(value), {
            [_type]: { value: FLOAT },
            [_inspect]: { value: () => `[Float: ${value}]` }
          });
        }
        function isFloat(obj) {
          if (obj === null || typeof obj !== "object")
            return false;
          return obj[_type] === FLOAT;
        }
        function tomlType(value) {
          const type = typeof value;
          if (type === "object") {
            if (value === null)
              return "null";
            if (value instanceof Date)
              return "datetime";
            if (_type in value) {
              switch (value[_type]) {
                case INLINE_TABLE:
                  return "inline-table";
                case INLINE_LIST:
                  return "inline-list";
                case TABLE:
                  return "table";
                case LIST:
                  return "list";
                case FLOAT:
                  return "float";
                case INTEGER:
                  return "integer";
              }
            }
          }
          return type;
        }
        function makeParserClass(Parser) {
          class TOMLParser extends Parser {
            constructor() {
              super();
              this.ctx = this.obj = Table();
            }
            atEndOfWord() {
              return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine();
            }
            atEndOfLine() {
              return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M;
            }
            parseStart() {
              if (this.char === Parser.END) {
                return null;
              } else if (this.char === CHAR_LSQB) {
                return this.call(this.parseTableOrList);
              } else if (this.char === CHAR_NUM) {
                return this.call(this.parseComment);
              } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
                return null;
              } else if (isAlphaNumQuoteHyphen(this.char)) {
                return this.callNow(this.parseAssignStatement);
              } else {
                throw this.error(new TomlError(`Unknown character "${this.char}"`));
              }
            }
            parseWhitespaceToEOL() {
              if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
                return null;
              } else if (this.char === CHAR_NUM) {
                return this.goto(this.parseComment);
              } else if (this.char === Parser.END || this.char === CTRL_J) {
                return this.return();
              } else {
                throw this.error(new TomlError("Unexpected character, expected only whitespace or comments till end of line"));
              }
            }
            parseAssignStatement() {
              return this.callNow(this.parseAssign, this.recordAssignStatement);
            }
            recordAssignStatement(kv) {
              let target = this.ctx;
              let finalKey = kv.key.pop();
              for (let kw of kv.key) {
                if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
                  throw this.error(new TomlError("Can't redefine existing key"));
                }
                target = target[kw] = target[kw] || Table();
              }
              if (hasKey(target, finalKey)) {
                throw this.error(new TomlError("Can't redefine existing key"));
              }
              if (isInteger(kv.value) || isFloat(kv.value)) {
                target[finalKey] = kv.value.valueOf();
              } else {
                target[finalKey] = kv.value;
              }
              return this.goto(this.parseWhitespaceToEOL);
            }
            parseAssign() {
              return this.callNow(this.parseKeyword, this.recordAssignKeyword);
            }
            recordAssignKeyword(key) {
              if (this.state.resultTable) {
                this.state.resultTable.push(key);
              } else {
                this.state.resultTable = [key];
              }
              return this.goto(this.parseAssignKeywordPreDot);
            }
            parseAssignKeywordPreDot() {
              if (this.char === CHAR_PERIOD) {
                return this.next(this.parseAssignKeywordPostDot);
              } else if (this.char !== CHAR_SP && this.char !== CTRL_I) {
                return this.goto(this.parseAssignEqual);
              }
            }
            parseAssignKeywordPostDot() {
              if (this.char !== CHAR_SP && this.char !== CTRL_I) {
                return this.callNow(this.parseKeyword, this.recordAssignKeyword);
              }
            }
            parseAssignEqual() {
              if (this.char === CHAR_EQUALS) {
                return this.next(this.parseAssignPreValue);
              } else {
                throw this.error(new TomlError('Invalid character, expected "="'));
              }
            }
            parseAssignPreValue() {
              if (this.char === CHAR_SP || this.char === CTRL_I) {
                return null;
              } else {
                return this.callNow(this.parseValue, this.recordAssignValue);
              }
            }
            recordAssignValue(value) {
              return this.returnNow({ key: this.state.resultTable, value });
            }
            parseComment() {
              do {
                if (this.char === Parser.END || this.char === CTRL_J) {
                  return this.return();
                }
              } while (this.nextChar());
            }
            parseTableOrList() {
              if (this.char === CHAR_LSQB) {
                this.next(this.parseList);
              } else {
                return this.goto(this.parseTable);
              }
            }
            parseTable() {
              this.ctx = this.obj;
              return this.goto(this.parseTableNext);
            }
            parseTableNext() {
              if (this.char === CHAR_SP || this.char === CTRL_I) {
                return null;
              } else {
                return this.callNow(this.parseKeyword, this.parseTableMore);
              }
            }
            parseTableMore(keyword) {
              if (this.char === CHAR_SP || this.char === CTRL_I) {
                return null;
              } else if (this.char === CHAR_RSQB) {
                if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {
                  throw this.error(new TomlError("Can't redefine existing key"));
                } else {
                  this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table();
                  this.ctx[_declared] = true;
                }
                return this.next(this.parseWhitespaceToEOL);
              } else if (this.char === CHAR_PERIOD) {
                if (!hasKey(this.ctx, keyword)) {
                  this.ctx = this.ctx[keyword] = Table();
                } else if (isTable(this.ctx[keyword])) {
                  this.ctx = this.ctx[keyword];
                } else if (isList(this.ctx[keyword])) {
                  this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
                } else {
                  throw this.error(new TomlError("Can't redefine existing key"));
                }
                return this.next(this.parseTableNext);
              } else {
                throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"));
              }
            }
            parseList() {
              this.ctx = this.obj;
              return this.goto(this.parseListNext);
            }
            parseListNext() {
              if (this.char === CHAR_SP || this.char === CTRL_I) {
                return null;
              } else {
                return this.callNow(this.parseKeyword, this.parseListMore);
              }
            }
            parseListMore(keyword) {
              if (this.char === CHAR_SP || this.char === CTRL_I) {
                return null;
              } else if (this.char === CHAR_RSQB) {
                if (!hasKey(this.ctx, keyword)) {
                  this.ctx[keyword] = List();
                }
                if (isInlineList(this.ctx[keyword])) {
                  throw this.error(new TomlError("Can't extend an inline array"));
                } else if (isList(this.ctx[keyword])) {
                  const next = Table();
                  this.ctx[keyword].push(next);
                  this.ctx = next;
                } else {
                  throw this.error(new TomlError("Can't redefine an existing key"));
                }
                return this.next(this.parseListEnd);
              } else if (this.char === CHAR_PERIOD) {
                if (!hasKey(this.ctx, keyword)) {
                  this.ctx = this.ctx[keyword] = Table();
                } else if (isInlineList(this.ctx[keyword])) {
                  throw this.error(new TomlError("Can't extend an inline array"));
                } else if (isInlineTable(this.ctx[keyword])) {
                  throw this.error(new TomlError("Can't extend an inline table"));
                } else if (isList(this.ctx[keyword])) {
                  this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
                } else if (isTable(this.ctx[keyword])) {
                  this.ctx = this.ctx[keyword];
                } else {
                  throw this.error(new TomlError("Can't redefine an existing key"));
                }
                return this.next(this.parseListNext);
              } else {
                throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"));
              }
            }
            parseListEnd(keyword) {
              if (this.char === CHAR_RSQB) {
                return this.next(this.parseWhitespaceToEOL);
              } else {
                throw this.error(new TomlError("Unexpected character, expected whitespace, . or ]"));
              }
            }
            parseValue() {
              if (this.char === Parser.END) {
                throw this.error(new TomlError("Key without value"));
              } else if (this.char === CHAR_QUOT) {
                return this.next(this.parseDoubleString);
              }
              if (this.char === CHAR_APOS) {
                return this.next(this.parseSingleString);
              } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
                return this.goto(this.parseNumberSign);
              } else if (this.char === CHAR_i) {
                return this.next(this.parseInf);
              } else if (this.char === CHAR_n) {
                return this.next(this.parseNan);
              } else if (isDigit(this.char)) {
                return this.goto(this.parseNumberOrDateTime);
              } else if (this.char === CHAR_t || this.char === CHAR_f) {
                return this.goto(this.parseBoolean);
              } else if (this.char === CHAR_LSQB) {
                return this.call(this.parseInlineList, this.recordValue);
              } else if (this.char === CHAR_LCUB) {
                return this.call(this.parseInlineTable, this.recordValue);
              } else {
                throw this.error(new TomlError("Unexpected character, expecting string, number, datetime, boolean, inline array or inline table"));
              }
            }
            recordValue(value) {
              return this.returnNow(value);
            }
            parseInf() {
              if (this.char === CHAR_n) {
                return this.next(this.parseInf2);
              } else {
                throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
              }
            }
            parseInf2() {
              if (this.char === CHAR_f) {
                if (this.state.buf === "-") {
                  return this.return(-Infinity);
                } else {
                  return this.return(Infinity);
                }
              } else {
                throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
              }
            }
            parseNan() {
              if (this.char === CHAR_a) {
                return this.next(this.parseNan2);
              } else {
                throw this.error(new TomlError('Unexpected character, expected "nan"'));
              }
            }
            parseNan2() {
              if (this.char === CHAR_n) {
                return this.return(NaN);
              } else {
                throw this.error(new TomlError('Unexpected character, expected "nan"'));
              }
            }
            parseKeyword() {
              if (this.char === CHAR_QUOT) {
                return this.next(this.parseBasicString);
              } else if (this.char === CHAR_APOS) {
                return this.next(this.parseLiteralString);
              } else {
                return this.goto(this.parseBareKey);
              }
            }
            parseBareKey() {
              do {
                if (this.char === Parser.END) {
                  throw this.error(new TomlError("Key ended without value"));
                } else if (isAlphaNumHyphen(this.char)) {
                  this.consume();
                } else if (this.state.buf.length === 0) {
                  throw this.error(new TomlError("Empty bare keys are not allowed"));
                } else {
                  return this.returnNow();
                }
              } while (this.nextChar());
            }
            parseSingleString() {
              if (this.char === CHAR_APOS) {
                return this.next(this.parseLiteralMultiStringMaybe);
              } else {
                return this.goto(this.parseLiteralString);
              }
            }
            parseLiteralString() {
              do {
                if (this.char === CHAR_APOS) {
                  return this.return();
                } else if (this.atEndOfLine()) {
                  throw this.error(new TomlError("Unterminated string"));
                } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
                  throw this.errorControlCharInString();
                } else {
                  this.consume();
                }
              } while (this.nextChar());
            }
            parseLiteralMultiStringMaybe() {
              if (this.char === CHAR_APOS) {
                return this.next(this.parseLiteralMultiString);
              } else {
                return this.returnNow();
              }
            }
            parseLiteralMultiString() {
              if (this.char === CTRL_M) {
                return null;
              } else if (this.char === CTRL_J) {
                return this.next(this.parseLiteralMultiStringContent);
              } else {
                return this.goto(this.parseLiteralMultiStringContent);
              }
            }
            parseLiteralMultiStringContent() {
              do {
                if (this.char === CHAR_APOS) {
                  return this.next(this.parseLiteralMultiEnd);
                } else if (this.char === Parser.END) {
                  throw this.error(new TomlError("Unterminated multi-line string"));
                } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
                  throw this.errorControlCharInString();
                } else {
                  this.consume();
                }
              } while (this.nextChar());
            }
            parseLiteralMultiEnd() {
              if (this.char === CHAR_APOS) {
                return this.next(this.parseLiteralMultiEnd2);
              } else {
                this.state.buf += "'";
                return this.goto(this.parseLiteralMultiStringContent);
              }
            }
            parseLiteralMultiEnd2() {
              if (this.char === CHAR_APOS) {
                return this.return();
              } else {
                this.state.buf += "''";
                return this.goto(this.parseLiteralMultiStringContent);
              }
            }
            parseDoubleString() {
              if (this.char === CHAR_QUOT) {
                return this.next(this.parseMultiStringMaybe);
              } else {
                return this.goto(this.parseBasicString);
              }
            }
            parseBasicString() {
              do {
                if (this.char === CHAR_BSOL) {
                  return this.call(this.parseEscape, this.recordEscapeReplacement);
                } else if (this.char === CHAR_QUOT) {
                  return this.return();
                } else if (this.atEndOfLine()) {
                  throw this.error(new TomlError("Unterminated string"));
                } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
                  throw this.errorControlCharInString();
                } else {
                  this.consume();
                }
              } while (this.nextChar());
            }
            recordEscapeReplacement(replacement) {
              this.state.buf += replacement;
              return this.goto(this.parseBasicString);
            }
            parseMultiStringMaybe() {
              if (this.char === CHAR_QUOT) {
                return this.next(this.parseMultiString);
              } else {
                return this.returnNow();
              }
            }
            parseMultiString() {
              if (this.char === CTRL_M) {
                return null;
              } else if (this.char === CTRL_J) {
                return this.next(this.parseMultiStringContent);
              } else {
                return this.goto(this.parseMultiStringContent);
              }
            }
            parseMultiStringContent() {
              do {
                if (this.char === CHAR_BSOL) {
                  return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement);
                } else if (this.char === CHAR_QUOT) {
                  return this.next(this.parseMultiEnd);
                } else if (this.char === Parser.END) {
                  throw this.error(new TomlError("Unterminated multi-line string"));
                } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
                  throw this.errorControlCharInString();
                } else {
                  this.consume();
                }
              } while (this.nextChar());
            }
            errorControlCharInString() {
              let displayCode = "\\u00";
              if (this.char < 16) {
                displayCode += "0";
              }
              displayCode += this.char.toString(16);
              return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`));
            }
            recordMultiEscapeReplacement(replacement) {
              this.state.buf += replacement;
              return this.goto(this.parseMultiStringContent);
            }
            parseMultiEnd() {
              if (this.char === CHAR_QUOT) {
                return this.next(this.parseMultiEnd2);
              } else {
                this.state.buf += '"';
                return this.goto(this.parseMultiStringContent);
              }
            }
            parseMultiEnd2() {
              if (this.char === CHAR_QUOT) {
                return this.return();
              } else {
                this.state.buf += '""';
                return this.goto(this.parseMultiStringContent);
              }
            }
            parseMultiEscape() {
              if (this.char === CTRL_M || this.char === CTRL_J) {
                return this.next(this.parseMultiTrim);
              } else if (this.char === CHAR_SP || this.char === CTRL_I) {
                return this.next(this.parsePreMultiTrim);
              } else {
                return this.goto(this.parseEscape);
              }
            }
            parsePreMultiTrim() {
              if (this.char === CHAR_SP || this.char === CTRL_I) {
                return null;
              } else if (this.char === CTRL_M || this.char === CTRL_J) {
                return this.next(this.parseMultiTrim);
              } else {
                throw this.error(new TomlError("Can't escape whitespace"));
              }
            }
            parseMultiTrim() {
              if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
                return null;
              } else {
                return this.returnNow();
              }
            }
            parseEscape() {
              if (this.char in escapes) {
                return this.return(escapes[this.char]);
              } else if (this.char === CHAR_u) {
                return this.call(this.parseSmallUnicode, this.parseUnicodeReturn);
              } else if (this.char === CHAR_U) {
                return this.call(this.parseLargeUnicode, this.parseUnicodeReturn);
              } else {
                throw this.error(new TomlError("Unknown escape character: " + this.char));
              }
            }
            parseUnicodeReturn(char) {
              try {
                const codePoint = parseInt(char, 16);
                if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {
                  throw this.error(new TomlError("Invalid unicode, character in range 0xD800 - 0xDFFF is reserved"));
                }
                return this.returnNow(String.fromCodePoint(codePoint));
              } catch (err) {
                throw this.error(TomlError.wrap(err));
              }
            }
            parseSmallUnicode() {
              if (!isHexit(this.char)) {
                throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"));
              } else {
                this.consume();
                if (this.state.buf.length >= 4)
                  return this.return();
              }
            }
            parseLargeUnicode() {
              if (!isHexit(this.char)) {
                throw this.error(new TomlError("Invalid character in unicode sequence, expected hex"));
              } else {
                this.consume();
                if (this.state.buf.length >= 8)
                  return this.return();
              }
            }
            parseNumberSign() {
              this.consume();
              return this.next(this.parseMaybeSignedInfOrNan);
            }
            parseMaybeSignedInfOrNan() {
              if (this.char === CHAR_i) {
                return this.next(this.parseInf);
              } else if (this.char === CHAR_n) {
                return this.next(this.parseNan);
              } else {
                return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart);
              }
            }
            parseNumberIntegerStart() {
              if (this.char === CHAR_0) {
                this.consume();
                return this.next(this.parseNumberIntegerExponentOrDecimal);
              } else {
                return this.goto(this.parseNumberInteger);
              }
            }
            parseNumberIntegerExponentOrDecimal() {
              if (this.char === CHAR_PERIOD) {
                this.consume();
                return this.call(this.parseNoUnder, this.parseNumberFloat);
              } else if (this.char === CHAR_E || this.char === CHAR_e) {
                this.consume();
                return this.next(this.parseNumberExponentSign);
              } else {
                return this.returnNow(Integer(this.state.buf));
              }
            }
            parseNumberInteger() {
              if (isDigit(this.char)) {
                this.consume();
              } else if (this.char === CHAR_LOWBAR) {
                return this.call(this.parseNoUnder);
              } else if (this.char === CHAR_E || this.char === CHAR_e) {
                this.consume();
                return this.next(this.parseNumberExponentSign);
              } else if (this.char === CHAR_PERIOD) {
                this.consume();
                return this.call(this.parseNoUnder, this.parseNumberFloat);
              } else {
                const result = Integer(this.state.buf);
                if (result.isNaN()) {
                  throw this.error(new TomlError("Invalid number"));
                } else {
                  return this.returnNow(result);
                }
              }
            }
            parseNoUnder() {
              if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) {
                throw this.error(new TomlError("Unexpected character, expected digit"));
              } else if (this.atEndOfWord()) {
                throw this.error(new TomlError("Incomplete number"));
              }
              return this.returnNow();
            }
            parseNoUnderHexOctBinLiteral() {
              if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD) {
                throw this.error(new TomlError("Unexpected character, expected digit"));
              } else if (this.atEndOfWord()) {
                throw this.error(new TomlError("Incomplete number"));
              }
              return this.returnNow();
            }
            parseNumberFloat() {
              if (this.char === CHAR_LOWBAR) {
                return this.call(this.parseNoUnder, this.parseNumberFloat);
              } else if (isDigit(this.char)) {
                this.consume();
              } else if (this.char === CHAR_E || this.char === CHAR_e) {
                this.consume();
                return this.next(this.parseNumberExponentSign);
              } else {
                return this.returnNow(Float(this.state.buf));
              }
            }
            parseNumberExponentSign() {
              if (isDigit(this.char)) {
                return this.goto(this.parseNumberExponent);
              } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
                this.consume();
                this.call(this.parseNoUnder, this.parseNumberExponent);
              } else {
                throw this.error(new TomlError("Unexpected character, expected -, + or digit"));
              }
            }
            parseNumberExponent() {
              if (isDigit(this.char)) {
                this.consume();
              } else if (this.char === CHAR_LOWBAR) {
                return this.call(this.parseNoUnder);
              } else {
                return this.returnNow(Float(this.state.buf));
              }
            }
            parseNumberOrDateTime() {
              if (this.char === CHAR_0) {
                this.consume();
                return this.next(this.parseNumberBaseOrDateTime);
              } else {
                return this.goto(this.parseNumberOrDateTimeOnly);
              }
            }
            parseNumberOrDateTimeOnly() {
              if (this.char === CHAR_LOWBAR) {
                return this.call(this.parseNoUnder, this.parseNumberInteger);
              } else if (isDigit(this.char)) {
                this.consume();
                if (this.state.buf.length > 4)
                  this.next(this.parseNumberInteger);
              } else if (this.char === CHAR_E || this.char === CHAR_e) {
                this.consume();
                return this.next(this.parseNumberExponentSign);
              } else if (this.char === CHAR_PERIOD) {
                this.consume();
                return this.call(this.parseNoUnder, this.parseNumberFloat);
              } else if (this.char === CHAR_HYPHEN) {
                return this.goto(this.parseDateTime);
              } else if (this.char === CHAR_COLON) {
                return this.goto(this.parseOnlyTimeHour);
              } else {
                return this.returnNow(Integer(this.state.buf));
              }
            }
            parseDateTimeOnly() {
              if (this.state.buf.length < 4) {
                if (isDigit(this.char)) {
                  return this.consume();
                } else if (this.char === CHAR_COLON) {
                  return this.goto(this.parseOnlyTimeHour);
                } else {
                  throw this.error(new TomlError("Expected digit while parsing year part of a date"));
                }
              } else {
                if (this.char === CHAR_HYPHEN) {
                  return this.goto(this.parseDateTime);
                } else {
                  throw this.error(new TomlError("Expected hyphen (-) while parsing year part of date"));
                }
              }
            }
            parseNumberBaseOrDateTime() {
              if (this.char === CHAR_b) {
                this.consume();
                return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerBin);
              } else if (this.char === CHAR_o) {
                this.consume();
                return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerOct);
              } else if (this.char === CHAR_x) {
                this.consume();
                return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerHex);
              } else if (this.char === CHAR_PERIOD) {
                return this.goto(this.parseNumberInteger);
              } else if (isDigit(this.char)) {
                return this.goto(this.parseDateTimeOnly);
              } else {
                return this.returnNow(Integer(this.state.buf));
              }
            }
            parseIntegerHex() {
              if (isHexit(this.char)) {
                this.consume();
              } else if (this.char === CHAR_LOWBAR) {
                return this.call(this.parseNoUnderHexOctBinLiteral);
              } else {
                const result = Integer(this.state.buf);
                if (result.isNaN()) {
                  throw this.error(new TomlError("Invalid number"));
                } else {
                  return this.returnNow(result);
                }
              }
            }
            parseIntegerOct() {
              if (isOctit(this.char)) {
                this.consume();
              } else if (this.char === CHAR_LOWBAR) {
                return this.call(this.parseNoUnderHexOctBinLiteral);
              } else {
                const result = Integer(this.state.buf);
                if (result.isNaN()) {
                  throw this.error(new TomlError("Invalid number"));
                } else {
                  return this.returnNow(result);
                }
              }
            }
            parseIntegerBin() {
              if (isBit(this.char)) {
                this.consume();
              } else if (this.char === CHAR_LOWBAR) {
                return this.call(this.parseNoUnderHexOctBinLiteral);
              } else {
                const result = Integer(this.state.buf);
                if (result.isNaN()) {
                  throw this.error(new TomlError("Invalid number"));
                } else {
                  return this.returnNow(result);
                }
              }
            }
            parseDateTime() {
              if (this.state.buf.length < 4) {
                throw this.error(new TomlError("Years less than 1000 must be zero padded to four characters"));
              }
              this.state.result = this.state.buf;
              this.state.buf = "";
              return this.next(this.parseDateMonth);
            }
            parseDateMonth() {
              if (this.char === CHAR_HYPHEN) {
                if (this.state.buf.length < 2) {
                  throw this.error(new TomlError("Months less than 10 must be zero padded to two characters"));
                }
                this.state.result += "-" + this.state.buf;
                this.state.buf = "";
                return this.next(this.parseDateDay);
              } else if (isDigit(this.char)) {
                this.consume();
              } else {
                throw this.error(new TomlError("Incomplete datetime"));
              }
            }
            parseDateDay() {
              if (this.char === CHAR_T || this.char === CHAR_SP) {
                if (this.state.buf.length < 2) {
                  throw this.error(new TomlError("Days less than 10 must be zero padded to two characters"));
                }
                this.state.result += "-" + this.state.buf;
                this.state.buf = "";
                return this.next(this.parseStartTimeHour);
              } else if (this.atEndOfWord()) {
                return this.returnNow(createDate(this.state.result + "-" + this.state.buf));
              } else if (isDigit(this.char)) {
                this.consume();
              } else {
                throw this.error(new TomlError("Incomplete datetime"));
              }
            }
            parseStartTimeHour() {
              if (this.atEndOfWord()) {
                return this.returnNow(createDate(this.state.result));
              } else {
                return this.goto(this.parseTimeHour);
              }
            }
            parseTimeHour() {
              if (this.char === CHAR_COLON) {
                if (this.state.buf.length < 2) {
                  throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"));
                }
                this.state.result += "T" + this.state.buf;
                this.state.buf = "";
                return this.next(this.parseTimeMin);
              } else if (isDigit(this.char)) {
                this.consume();
              } else {
                throw this.error(new TomlError("Incomplete datetime"));
              }
            }
            parseTimeMin() {
              if (this.state.buf.length < 2 && isDigit(this.char)) {
                this.consume();
              } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
                this.state.result += ":" + this.state.buf;
                this.state.buf = "";
                return this.next(this.parseTimeSec);
              } else {
                throw this.error(new TomlError("Incomplete datetime"));
              }
            }
            parseTimeSec() {
              if (isDigit(this.char)) {
                this.consume();
                if (this.state.buf.length === 2) {
                  this.state.result += ":" + this.state.buf;
                  this.state.buf = "";
                  return this.next(this.parseTimeZoneOrFraction);
                }
              } else {
                throw this.error(new TomlError("Incomplete datetime"));
              }
            }
            parseOnlyTimeHour() {
              if (this.char === CHAR_COLON) {
                if (this.state.buf.length < 2) {
                  throw this.error(new TomlError("Hours less than 10 must be zero padded to two characters"));
                }
                this.state.result = this.state.buf;
                this.state.buf = "";
                return this.next(this.parseOnlyTimeMin);
              } else {
                throw this.error(new TomlError("Incomplete time"));
              }
            }
            parseOnlyTimeMin() {
              if (this.state.buf.length < 2 && isDigit(this.char)) {
                this.consume();
              } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
                this.state.result += ":" + this.state.buf;
                this.state.buf = "";
                return this.next(this.parseOnlyTimeSec);
              } else {
                throw this.error(new TomlError("Incomplete time"));
              }
            }
            parseOnlyTimeSec() {
              if (isDigit(this.char)) {
                this.consume();
                if (this.state.buf.length === 2) {
                  return this.next(this.parseOnlyTimeFractionMaybe);
                }
              } else {
                throw this.error(new TomlError("Incomplete time"));
              }
            }
            parseOnlyTimeFractionMaybe() {
              this.state.result += ":" + this.state.buf;
              if (this.char === CHAR_PERIOD) {
                this.state.buf = "";
                this.next(this.parseOnlyTimeFraction);
              } else {
                return this.return(createTime(this.state.result));
              }
            }
            parseOnlyTimeFraction() {
              if (isDigit(this.char)) {
                this.consume();
              } else if (this.atEndOfWord()) {
                if (this.state.buf.length === 0)
                  throw this.error(new TomlError("Expected digit in milliseconds"));
                return this.returnNow(createTime(this.state.result + "." + this.state.buf));
              } else {
                throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"));
              }
            }
            parseTimeZoneOrFraction() {
              if (this.char === CHAR_PERIOD) {
                this.consume();
                this.next(this.parseDateTimeFraction);
              } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
                this.consume();
                this.next(this.parseTimeZoneHour);
              } else if (this.char === CHAR_Z) {
                this.consume();
                return this.return(createDateTime(this.state.result + this.state.buf));
              } else if (this.atEndOfWord()) {
                return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf));
              } else {
                throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"));
              }
            }
            parseDateTimeFraction() {
              if (isDigit(this.char)) {
                this.consume();
              } else if (this.state.buf.length === 1) {
                throw this.error(new TomlError("Expected digit in milliseconds"));
              } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
                this.consume();
                this.next(this.parseTimeZoneHour);
              } else if (this.char === CHAR_Z) {
                this.consume();
                return this.return(createDateTime(this.state.result + this.state.buf));
              } else if (this.atEndOfWord()) {
                return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf));
              } else {
                throw this.error(new TomlError("Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z"));
              }
            }
            parseTimeZoneHour() {
              if (isDigit(this.char)) {
                this.consume();
                if (/\d\d$/.test(this.state.buf))
                  return this.next(this.parseTimeZoneSep);
              } else {
                throw this.error(new TomlError("Unexpected character in datetime, expected digit"));
              }
            }
            parseTimeZoneSep() {
              if (this.char === CHAR_COLON) {
                this.consume();
                this.next(this.parseTimeZoneMin);
              } else {
                throw this.error(new TomlError("Unexpected character in datetime, expected colon"));
              }
            }
            parseTimeZoneMin() {
              if (isDigit(this.char)) {
                this.consume();
                if (/\d\d$/.test(this.state.buf))
                  return this.return(createDateTime(this.state.result + this.state.buf));
              } else {
                throw this.error(new TomlError("Unexpected character in datetime, expected digit"));
              }
            }
            parseBoolean() {
              if (this.char === CHAR_t) {
                this.consume();
                return this.next(this.parseTrue_r);
              } else if (this.char === CHAR_f) {
                this.consume();
                return this.next(this.parseFalse_a);
              }
            }
            parseTrue_r() {
              if (this.char === CHAR_r) {
                this.consume();
                return this.next(this.parseTrue_u);
              } else {
                throw this.error(new TomlError("Invalid boolean, expected true or false"));
              }
            }
            parseTrue_u() {
              if (this.char === CHAR_u) {
                this.consume();
                return this.next(this.parseTrue_e);
              } else {
                throw this.error(new TomlError("Invalid boolean, expected true or false"));
              }
            }
            parseTrue_e() {
              if (this.char === CHAR_e) {
                return this.return(true);
              } else {
                throw this.error(new TomlError("Invalid boolean, expected true or false"));
              }
            }
            parseFalse_a() {
              if (this.char === CHAR_a) {
                this.consume();
                return this.next(this.parseFalse_l);
              } else {
                throw this.error(new TomlError("Invalid boolean, expected true or false"));
              }
            }
            parseFalse_l() {
              if (this.char === CHAR_l) {
                this.consume();
                return this.next(this.parseFalse_s);
              } else {
                throw this.error(new TomlError("Invalid boolean, expected true or false"));
              }
            }
            parseFalse_s() {
              if (this.char === CHAR_s) {
                this.consume();
                return this.next(this.parseFalse_e);
              } else {
                throw this.error(new TomlError("Invalid boolean, expected true or false"));
              }
            }
            parseFalse_e() {
              if (this.char === CHAR_e) {
                return this.return(false);
              } else {
                throw this.error(new TomlError("Invalid boolean, expected true or false"));
              }
            }
            parseInlineList() {
              if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
                return null;
              } else if (this.char === Parser.END) {
                throw this.error(new TomlError("Unterminated inline array"));
              } else if (this.char === CHAR_NUM) {
                return this.call(this.parseComment);
              } else if (this.char === CHAR_RSQB) {
                return this.return(this.state.resultArr || InlineList());
              } else {
                return this.callNow(this.parseValue, this.recordInlineListValue);
              }
            }
            recordInlineListValue(value) {
              if (this.state.resultArr) {
                const listType = this.state.resultArr[_contentType];
                const valueType = tomlType(value);
                if (listType !== valueType) {
                  throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`));
                }
              } else {
                this.state.resultArr = InlineList(tomlType(value));
              }
              if (isFloat(value) || isInteger(value)) {
                this.state.resultArr.push(value.valueOf());
              } else {
                this.state.resultArr.push(value);
              }
              return this.goto(this.parseInlineListNext);
            }
            parseInlineListNext() {
              if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
                return null;
              } else if (this.char === CHAR_NUM) {
                return this.call(this.parseComment);
              } else if (this.char === CHAR_COMMA) {
                return this.next(this.parseInlineList);
              } else if (this.char === CHAR_RSQB) {
                return this.goto(this.parseInlineList);
              } else {
                throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"));
              }
            }
            parseInlineTable() {
              if (this.char === CHAR_SP || this.char === CTRL_I) {
                return null;
              } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
                throw this.error(new TomlError("Unterminated inline array"));
              } else if (this.char === CHAR_RCUB) {
                return this.return(this.state.resultTable || InlineTable());
              } else {
                if (!this.state.resultTable)
                  this.state.resultTable = InlineTable();
                return this.callNow(this.parseAssign, this.recordInlineTableValue);
              }
            }
            recordInlineTableValue(kv) {
              let target = this.state.resultTable;
              let finalKey = kv.key.pop();
              for (let kw of kv.key) {
                if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
                  throw this.error(new TomlError("Can't redefine existing key"));
                }
                target = target[kw] = target[kw] || Table();
              }
              if (hasKey(target, finalKey)) {
                throw this.error(new TomlError("Can't redefine existing key"));
              }
              if (isInteger(kv.value) || isFloat(kv.value)) {
                target[finalKey] = kv.value.valueOf();
              } else {
                target[finalKey] = kv.value;
              }
              return this.goto(this.parseInlineTableNext);
            }
            parseInlineTableNext() {
              if (this.char === CHAR_SP || this.char === CTRL_I) {
                return null;
              } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
                throw this.error(new TomlError("Unterminated inline array"));
              } else if (this.char === CHAR_COMMA) {
                return this.next(this.parseInlineTable);
              } else if (this.char === CHAR_RCUB) {
                return this.goto(this.parseInlineTable);
              } else {
                throw this.error(new TomlError("Invalid character, expected whitespace, comma (,) or close bracket (])"));
              }
            }
          }
          return TOMLParser;
        }
      }
    });
    var require_parse_pretty_error = __commonJS({
      "../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-pretty-error.js"(exports2, module2) {
        "use strict";
        module2.exports = prettyError;
        function prettyError(err, buf) {
          if (err.pos == null || err.line == null)
            return err;
          let msg = err.message;
          msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:
`;
          if (buf && buf.split) {
            const lines = buf.split(/\n/);
            const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length;
            let linePadding = " ";
            while (linePadding.length < lineNumWidth)
              linePadding += " ";
            for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {
              let lineNum = String(ii + 1);
              if (lineNum.length < lineNumWidth)
                lineNum = " " + lineNum;
              if (err.line === ii) {
                msg += lineNum + "> " + lines[ii] + "\n";
                msg += linePadding + "  ";
                for (let hh = 0; hh < err.col; ++hh) {
                  msg += " ";
                }
                msg += "^\n";
              } else {
                msg += lineNum + ": " + lines[ii] + "\n";
              }
            }
          }
          err.message = msg + "\n";
          return err;
        }
      }
    });
    var require_parse_string = __commonJS({
      "../node_modules/.pnpm/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-string.js"(exports2, module2) {
        "use strict";
        module2.exports = parseString2;
        var TOMLParser = require_toml_parser();
        var prettyError = require_parse_pretty_error();
        function parseString2(str) {
          if (global.Buffer && global.Buffer.isBuffer(str)) {
            str = str.toString("utf8");
          }
          const parser = new TOMLParser();
          try {
            parser.parse(str);
            return parser.finish();
          } catch (err) {
            throw prettyError(err, str);
          }
        }
      }
    });
    var stage_parser_exports = {};
    __export(stage_parser_exports, {
      default: () => stage_parser_default,
      genFlattenedObject: () => genFlattenedObject,
      genFragmentsForScenes: () => genFragmentsForScenes,
      genSceneObjects: () => genSceneObjects,
      genTokensForScene: () => genTokensForScene,
      parse: () => parse,
      parseFlat: () => parseFlat,
      preprocessString: () => preprocessString
    });
    module.exports = __toCommonJS(stage_parser_exports);
    var pipe = (raw, plugins) => {
      let intermediate = raw;
      for (let plugin of plugins) {
        intermediate = plugin(intermediate);
      }
      return intermediate;
    };
    var import_moo = __toESM(require_moo());
    var import_eol = __toESM(require_eol());
    var parseComments = (raw) => {
      const lexer = import_moo.default.compile({
        comment: { match: /^=.*\n?/, lineBreaks: true },
        comment2: /^=.*?$/,
        text: { match: /[^]+?/, lineBreaks: true }
      });
      lexer.reset(import_eol.default.lf(raw));
      let finalString = "";
      for (let token of Array.from(lexer)) {
        if (token.type === "text") {
          finalString += token.value;
        }
      }
      return finalString;
    };
    var import_eol3 = __toESM(require_eol());
    var import_eol2 = __toESM(require_eol());
    var preserveWhitespaceTags = [
      {
        start: /^```$/gm,
        end: /^```$/gm,
        startTag: "```",
        endTag: "```",
        type: "code"
      },
      {
        start: /\<pre\>/gm,
        end: /\<\/pre\>/gm,
        startTag: "<pre>",
        endTag: "</pre>",
        type: "pre"
      },
      {
        start: /^\!==$/gm,
        end: /^\!==$/gm,
        type: "custom"
      }
    ];
    var createTrimWhitespaceTokens = (raw) => {
      const lines = import_eol2.default.split(raw);
      const tokens = [];
      let currentString = "";
      let currentTag = null;
      for (let line of lines) {
        if (currentTag === null) {
          let matched = false;
          for (let tag of preserveWhitespaceTags) {
            if (line.match(tag.start)) {
              currentTag = tag;
              tokens.push({ text: currentString, type: "none" });
              currentString = "";
              matched = true;
              break;
            }
          }
          if (!matched) {
            currentString += line + "\n";
          }
          continue;
        }
        if (line.match(currentTag.end)) {
          tokens.push({
            text: currentString,
            type: currentTag.type,
            startTag: currentTag.startTag,
            endTag: currentTag.endTag
          });
          currentTag = null;
          currentString = "";
          continue;
        }
        currentString += line + "\n";
      }
      if (currentString.length > 0) {
        if (currentTag === null) {
          tokens.push({ text: currentString, type: "none" });
        } else {
          tokens.push({
            text: currentString,
            type: currentTag.type,
            startTag: currentTag.startTag,
            endTag: currentTag.endTag
          });
        }
      }
      return tokens;
    };
    var parseTrimLines = (raw) => {
      const trimmedContentTokens = createTrimWhitespaceTokens(raw);
      let finalString = "";
      for (let token of trimmedContentTokens) {
        switch (token.type) {
          case "none":
            finalString += trimLinesOfSection(token.text).trim() + "\n\n";
            break;
          default:
            if (token.startTag) {
              finalString += token.startTag + "\n";
            }
            finalString += token.text;
            if (token.endTag) {
              finalString += token.endTag + "\n";
            }
        }
      }
      return finalString.trim();
    };
    var trimLinesOfSection = (text) => {
      const lines = import_eol3.default.split(text);
      let finalString = "";
      for (let line of lines) {
        finalString += line.trim() + "\n";
      }
      return finalString;
    };
    var preprocessString = (raw) => {
      return pipe(raw, [parseTrimLines, parseComments]);
    };
    var import_moo2 = __toESM(require_moo());
    var import_eol4 = __toESM(require_eol());
    var exposeMeta = (obj) => {
      if (!obj.meta) {
        return;
      }
      if (obj.meta.id) {
        obj.id = obj.meta.id;
      }
      if (obj.meta.classes) {
        obj.classes = obj.meta.classes;
      }
      if (obj.id) {
        obj.primary = obj.id;
      } else if (obj.classes && obj.classes.length) {
        obj.primary = obj.classes[0];
      }
      if (obj.meta.title) {
        obj.title = obj.meta.title;
      }
    };
    var import_parse_string = __toESM(require_parse_string());
    var parseTOMLMeta = (tomlString) => {
      try {
        const tomlObj = (0, import_parse_string.default)(tomlString);
        return tomlObj;
      } catch (err) {
        console.warn(
          "TOML parser failed. String is instead being saved as one unit in the '_unparsed' field, where it can be processed later",
          err
        );
        return {
          _unparsed: tomlString
        };
      }
    };
    var separateAtShorthand = (string) => {
      if (!string.startsWith("@")) {
        throw new Error("@ shorthand must begin with an @ symbol");
      }
      const stringWithoutPrefix = string.slice(1);
      const divElements = stringWithoutPrefix.split(".");
      const div = {
        classes: []
      };
      for (let str of divElements) {
        if (str.startsWith("#")) {
          div.id = str.slice(1);
          continue;
        }
        if (!div.classes) {
          div.classes = [];
        }
        div.classes.push(str);
      }
      return div;
    };
    var splitLineBySpacesWithQuotes = (line) => {
      return line.match(/(\S*'.*?'|\S*".*?"|\S+)/gm) || [];
    };
    var parseInlineMeta = (inlineMeta) => {
      let inlineMetaObject = {};
      let autoTitleAvailable = true;
      let autoTitle = "";
      const inlineMetaTokens = splitLineBySpacesWithQuotes(inlineMeta);
      for (let token of inlineMetaTokens) {
        if (token.startsWith("@")) {
          autoTitleAvailable = false;
          const tokenMeta = separateAtShorthand(token);
          inlineMetaObject = __spreadValues(__spreadValues({}, inlineMetaObject), tokenMeta);
          continue;
        }
        if (token.indexOf("=") >= 0) {
          autoTitleAvailable = false;
          const tokenMeta = parseTOMLMeta(token);
          inlineMetaObject = __spreadValues(__spreadValues({}, inlineMetaObject), tokenMeta);
          continue;
        }
        if (autoTitleAvailable) {
          autoTitle += token + " ";
          continue;
        }
        inlineMetaObject[token] = true;
      }
      autoTitle = autoTitle.trim();
      if (autoTitle) {
        inlineMetaObject.title = autoTitle;
      }
      return inlineMetaObject;
    };
    var genSceneObjects = (preprocessedString) => {
      const scenes = [];
      const lexer = import_moo2.default.states({
        main: {
          sceneDefStart: { match: /\#[ \t]*\n/, lineBreaks: true, push: "sceneDefinition" },
          sceneWithTitleStart: { match: /\#:[ \t]*.*\n/, lineBreaks: true, push: "sceneDefinition" },
          text: { match: /[^]+?/, lineBreaks: true }
        },
        sceneDefinition: {
          tomlStartDash: { match: "---", push: "sceneTomlDash" },
          tomlStartPlus: { match: "+++", push: "sceneTomlPlus" },
          sceneDefEnd: { match: /\n/, lineBreaks: true, push: "main" }
        },
        sceneTomlDash: {
          tomlEnd: { match: "---", push: "sceneDefinition" },
          toml: { match: /[^]+?(?=---)/, lineBreaks: true }
        },
        sceneTomlPlus: {
          tomlEnd: { match: "+++", push: "sceneDefinition" },
          toml: { match: /[^]+?(?=\+\+\+)/, lineBreaks: true }
        }
      });
      let lexerRaw = import_eol4.default.lf(preprocessedString);
      if (lexerRaw.startsWith("---\n") || lexerRaw.startsWith("+++\n")) {
        lexerRaw = "#\n" + lexerRaw;
      }
      lexer.reset(import_eol4.default.lf(lexerRaw));
      let currentScene = {
        type: "scene",
        raw: ""
      };
      for (let token of Array.from(lexer)) {
        switch (token.type) {
          case "sceneDefStart":
            if (!currentScene.raw.length) {
              continue;
            }
            scenes.push(currentScene);
            currentScene = {
              type: "scene",
              raw: ""
            };
            break;
          case "sceneWithTitleStart":
            if (currentScene.raw.length) {
              scenes.push(currentScene);
            }
            const inlineMeta = token.value.substring(2).trim();
            const inlineMetaObject = inlineMeta ? parseInlineMeta(inlineMeta.trim()) : void 0;
            currentScene = {
              type: "scene",
              raw: "",
              meta: inlineMetaObject
            };
            break;
          case "toml":
            const tomlObj = parseTOMLMeta(token.value);
            if (tomlObj === void 0) {
              throw new Error(lexer.formatError(token, "empty TOML frontmatter in scene."));
            }
            if (currentScene.meta) {
              currentScene.meta = __spreadValues(__spreadValues({}, currentScene.meta), tomlObj);
            } else {
              currentScene.meta = tomlObj;
            }
            exposeMeta(currentScene);
            break;
          case "text":
            currentScene.raw += token.value;
            break;
        }
      }
      if (currentScene.raw.length) {
        scenes.push(currentScene);
      }
      return scenes;
    };
    var import_moo3 = __toESM(require_moo());
    var import_eol5 = __toESM(require_eol());
    var FRAGMENT_START_TOKEN = "<>";
    var FRAGMENT_END_TOKEN = "</>";
    var genFragmentsForScenes = (scenes) => {
      const newScenes = [];
      for (let scene of scenes) {
        const fragments = genFragmentObjects(scene.raw);
        const newScene = {
          type: "scene",
          meta: scene.meta,
          id: scene.id,
          classes: scene.classes,
          primary: scene.primary,
          title: scene.title,
          fragments
        };
        newScenes.push(newScene);
      }
      return newScenes;
    };
    var genFragmentObjects = (raw) => {
      const fragments = [];
      let currentFragment = "";
      const lines = import_eol5.default.split(raw);
      for (let line of lines) {
        if (line.trim().startsWith(FRAGMENT_START_TOKEN)) {
          let trimmedFragment2 = currentFragment.trim();
          if (trimmedFragment2.length) {
            fragments.push(genFragmentObject(currentFragment));
          }
          currentFragment = line + "\n";
          continue;
        }
        if (line.trim() === FRAGMENT_END_TOKEN) {
          currentFragment += line + "\n";
          fragments.push(genFragmentObject(currentFragment));
          currentFragment = "";
          continue;
        }
        currentFragment += line + "\n";
      }
      let trimmedFragment = currentFragment.trim();
      if (trimmedFragment.length) {
        fragments.push(genFragmentObject(currentFragment));
      }
      return fragments;
    };
    var genFragmentObject = (text) => {
      if (!text.startsWith(FRAGMENT_START_TOKEN)) {
        return {
          type: "empty",
          raw: text
        };
      }
      const fragmentObject = {
        type: "fragment",
        raw: ""
      };
      const lexer = import_moo3.default.states({
        start: {
          fragDefStart: { match: FRAGMENT_START_TOKEN, push: "fragInlineMeta" }
        },
        fragInlineMeta: {
          fragInlineEnd: { match: /\n/, lineBreaks: true, push: "fragDefinition" },
          inlineMeta: { match: /[^]+?/, lineBreaks: true }
        },
        fragDefinition: {
          tomlStart: { match: "---", push: "fragToml" },
          tomlStartPlus: { match: "+++", push: "fragTomlPlus" },
          fragDefEnd: { match: /\n/, lineBreaks: true, push: "main" },
          text: { match: /[^]+?/, lineBreaks: true }
        },
        fragToml: {
          tomlEnd: { match: "---", push: "fragDefinition" },
          toml: { match: /[^]+?(?=---)/, lineBreaks: true }
        },
        fragTomlPlus: {
          tomlEnd: { match: "+++", push: "fragDefinition" },
          toml: { match: /[^]+?(?=\+\+\+)/, lineBreaks: true }
        },
        main: {
          fragTagEnd: { match: new RegExp(`^s*${FRAGMENT_END_TOKEN.replace("/", "\\/")}s*$`), push: "endFragTag" },
          text: { match: /[^]+?/, lineBreaks: true }
        },
        endFragTag: {
          misc: { match: /[^]+?/, lineBreaks: true }
        }
      });
      lexer.reset(import_eol5.default.lf(text));
      let inlineMeta = "";
      for (let token of Array.from(lexer)) {
        switch (token.type) {
          case "toml":
            const tomlObj = parseTOMLMeta(token.value);
            if (tomlObj === void 0) {
              throw new Error(lexer.formatError(token, "empty TOML frontmatter in scene."));
            }
            if (!fragmentObject.meta) {
              fragmentObject.meta = {};
            }
            fragmentObject.meta = __spreadValues(__spreadValues({}, fragmentObject.meta), tomlObj);
            exposeMeta(fragmentObject);
            break;
          case "text":
            fragmentObject.raw += token.value;
            break;
          case "inlineMeta":
            inlineMeta += token.value;
        }
      }
      inlineMeta = inlineMeta.trim();
      if (inlineMeta.length) {
        let inlineMetaObject = parseInlineMeta(inlineMeta);
        fragmentObject.meta = __spreadValues(__spreadValues({}, inlineMetaObject), fragmentObject.meta);
        exposeMeta(fragmentObject);
      }
      return fragmentObject;
    };
    var import_eol7 = __toESM(require_eol());
    var import_moo4 = __toESM(require_moo());
    var import_eol6 = __toESM(require_eol());
    var SOFTLINE_PLACEHOLDER = "%LINE%";
    var preprocessSoftLines = (raw) => {
      const lfRaw = import_eol6.default.lf(raw);
      return lfRaw.replace(new RegExp("(?<!\\\\)\\\\\\n", "gm"), SOFTLINE_PLACEHOLDER);
    };
    var createCommandObject = (line) => {
      if (!line.startsWith("$")) {
        throw new Error("$ shorthand must begin with an $ symbol");
      }
      let trimmedCommand = line.substring(1).trim();
      const commandParts = splitLineBySpacesWithQuotes(trimmedCommand).map((arg) => {
        if (arg.startsWith('"') && arg.endsWith('"')) {
          return arg.slice(1, arg.length - 1);
        }
        if (arg.startsWith("'") && arg.endsWith("'")) {
          return arg.slice(1, arg.length - 1);
        }
        return arg;
      });
      let [command, ...params] = commandParts;
      return {
        type: "command",
        text: trimmedCommand,
        name: command,
        args: params
      };
    };
    var genTokensForScene = (scene) => {
      const newFragments = [];
      for (let fragment of scene.fragments) {
        const newFragment = genTokenizedFragment(fragment);
        newFragments.push(newFragment);
      }
      return __spreadProps(__spreadValues({}, scene), { fragments: newFragments });
    };
    var genTokenizedFragment = (fragment) => {
      const trimmedLineSections = createTrimWhitespaceTokens(fragment.raw);
      const tokens = [];
      for (let section of trimmedLineSections) {
        if (section.type === "none") {
          const newTokens = createTokensForTextSection(section.text);
          for (let t of newTokens) {
            tokens.push(t);
          }
          continue;
        }
        const newToken = {
          type: "rawText",
          text: section.text,
          startTag: section.startTag,
          endTag: section.endTag
        };
        tokens.push(newToken);
      }
      const newFragmentObject = __spreadProps(__spreadValues({}, fragment), {
        tokens
      });
      return newFragmentObject;
    };
    var createTokensForTextSection = (text) => {
      const preprocessedString = pipe(text, [preprocessSoftLines]);
      const tokens = [];
      const lexer = import_moo4.default.states({
        main: {
          startCommand: { match: /^\$/, next: "command" },
          startAt: { match: /^@/, next: "at" },
          startMetaTag: {
            match: new RegExp("(?<!\\n)\\n<!"),
            lineBreaks: true,
            push: "meta"
          },
          emptyLine: { match: /\n/, lineBreaks: true },
          text: { match: /[^]+?/, lineBreaks: true }
        },
        command: {
          endCommand: { match: /\n/, lineBreaks: true, next: "main" },
          commandText: { match: /[^]+?/, lineBreaks: true }
        },
        meta: {
          endMetaTag: {
            match: />/,
            pop: 1
          },
          meta: {
            match: /[^]+?/,
            lineBreaks: true
          }
        },
        at: {
          colonWithWS: { match: /: /, next: "main" },
          colon: { match: /:/, next: "main" },
          ws: { match: /[ \t]/, next: "main" },
          shorthandText: { match: /.+?/ }
        }
      });
      lexer.reset(import_eol7.default.lf(preprocessedString));
      let currentBuffer = "";
      let existingToken = null;
      const createParagraphToken = () => {
        if (existingToken) {
          existingToken.text = currentBuffer;
          tokens.push(existingToken);
          existingToken = null;
        } else {
          const newToken = {
            type: "paragraph",
            text: currentBuffer
          };
          tokens.push(newToken);
        }
      };
      for (let token of Array.from(lexer)) {
        switch (token.type) {
          case "text":
            currentBuffer += token.value;
            break;
          case "emptyLine":
            if (currentBuffer.length) {
              createParagraphToken();
              currentBuffer = "";
            }
            break;
          case "startAt":
            currentBuffer = "@";
            break;
          case "shorthandText":
            currentBuffer += token.value;
            break;
          case "colonWithWS":
          case "colon":
          case "ws":
            const meta = separateAtShorthand(currentBuffer);
            currentBuffer = "";
            existingToken = {
              type: "paragraph",
              meta,
              text: ""
            };
            exposeMeta(existingToken);
            break;
          case "startCommand":
            currentBuffer = "$";
            break;
          case "commandText":
            currentBuffer += token.value;
            break;
          case "endCommand":
            const commandToken = createCommandObject(currentBuffer);
            tokens.push(commandToken);
            currentBuffer = "";
            break;
          case "startMetaTag":
            if (currentBuffer.length) {
              createParagraphToken();
            }
            currentBuffer = "";
            break;
          case "meta":
            currentBuffer += token.value;
            break;
          case "endMetaTag":
            if (tokens.length === 0) {
              throw new Error("Created a post-paragraph meta tag that doesn't modify a paragraph");
            }
            let modifiedToken = tokens[tokens.length - 1];
            if (!modifiedToken.meta) {
              modifiedToken.meta = {};
            }
            modifiedToken.meta._ = currentBuffer;
            currentBuffer = "";
            break;
        }
      }
      if (currentBuffer.length) {
        createParagraphToken();
      }
      return tokens;
    };
    var concatInPlace = (arrayToModify, arrayToSplice) => {
      for (let item of arrayToSplice) {
        arrayToModify.push(item);
      }
    };
    var genFlattenedObject = (scenes) => {
      const array = [];
      for (let scene of scenes) {
        const newScene = {
          type: "scene"
        };
        if (scene.meta) {
          newScene.meta = scene.meta;
        }
        exposeMeta(newScene);
        array.push(newScene);
        for (let fragment of scene.fragments) {
          if (fragment.type === "empty") {
            concatInPlace(array, fragment.tokens);
          } else {
            const newFrag = {
              type: "fragment"
            };
            if (fragment.meta) {
              newFrag.meta = fragment.meta;
            }
            exposeMeta(newFrag);
            array.push(newFrag);
            concatInPlace(array, fragment.tokens);
            array.push({
              type: "endFragment"
            });
          }
        }
        array.push({
          type: "endScene"
        });
      }
      return array;
    };
    var parse = (text) => {
      const preprocessedText = preprocessString(text);
      const rawScenes = genSceneObjects(preprocessedText);
      const fragmentedScenes = genFragmentsForScenes(rawScenes);
      const tokenizedScenes = [];
      for (let scene of fragmentedScenes) {
        tokenizedScenes.push(genTokensForScene(scene));
      }
      return tokenizedScenes;
    };
    var parseFlat = (text) => {
      return genFlattenedObject(parse(text));
    };
    var stage_parser_default = parse;
  }
});

// ../../core/dist/lib/tools/split-line-by-spaces-with-quotes.js
var require_split_line_by_spaces_with_quotes = __commonJS2({
  "../../core/dist/lib/tools/split-line-by-spaces-with-quotes.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.splitLineBySpacesWithQuotes = void 0;
    var splitLineBySpacesWithQuotes2 = (line) => {
      return line.match(/(\S*'.*?'|\S*".*?"|\S+)/gm) || [];
    };
    exports2.splitLineBySpacesWithQuotes = splitLineBySpacesWithQuotes2;
  }
});

// ../../core/dist/lib/tools/command-shorthand.js
var require_command_shorthand = __commonJS2({
  "../../core/dist/lib/tools/command-shorthand.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createCommandObject = void 0;
    var split_line_by_spaces_with_quotes_1 = require_split_line_by_spaces_with_quotes();
    var createCommandObject2 = (line) => {
      if (!line.startsWith("$")) {
        throw new Error("$ shorthand must begin with an $ symbol");
      }
      let trimmedCommand = line.substring(1).trim();
      const commandParts = (0, split_line_by_spaces_with_quotes_1.splitLineBySpacesWithQuotes)(trimmedCommand).map((arg) => {
        if (arg.startsWith('"') && arg.endsWith('"')) {
          return arg.slice(1, arg.length - 1);
        }
        if (arg.startsWith("'") && arg.endsWith("'")) {
          return arg.slice(1, arg.length - 1);
        }
        return arg;
      });
      let [command, ...params] = commandParts;
      return {
        type: "command",
        text: trimmedCommand,
        name: command,
        args: params
      };
    };
    exports2.createCommandObject = createCommandObject2;
  }
});

// ../../packages/ext-common-commands/dist/common-commands-ext.js
var require_common_commands_ext = __commonJS2({
  "../../packages/ext-common-commands/dist/common-commands-ext.js"(exports2) {
    var __create2 = Object.create;
    var __defProp2 = Object.defineProperty;
    var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __getProtoOf2 = Object.getPrototypeOf;
    var __hasOwnProp2 = Object.prototype.hasOwnProperty;
    var __markAsModule = (target) => __defProp2(target, "__esModule", { value: true });
    var __commonJS3 = (cb, mod) => function __require() {
      return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
    };
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp2(target, name, { get: all[name], enumerable: true });
    };
    var __reExport = (target, module22, desc) => {
      if (module22 && typeof module22 === "object" || typeof module22 === "function") {
        for (let key of __getOwnPropNames3(module22))
          if (!__hasOwnProp2.call(target, key) && key !== "default")
            __defProp2(target, key, { get: () => module22[key], enumerable: !(desc = __getOwnPropDesc2(module22, key)) || desc.enumerable });
      }
      return target;
    };
    var __toModule = (module22) => {
      return __reExport(__markAsModule(__defProp2(module22 != null ? __create2(__getProtoOf2(module22)) : {}, "default", module22 && module22.__esModule && "default" in module22 ? { get: () => module22.default, enumerable: true } : { value: module22, enumerable: true })), module22);
    };
    var require_eol2 = __commonJS3({
      "../../node_modules/.pnpm/eol@0.9.1/node_modules/eol/eol.js"(exports3, module22) {
        !function(root, name, make) {
          if (typeof module22 != "undefined" && module22.exports)
            module22.exports = make();
          else
            root[name] = make();
        }(exports3, "eol", function() {
          var api = {};
          var isWindows = typeof process != "undefined" && process.platform === "win32";
          var linebreak = isWindows ? "\r\n" : "\n";
          var newline = /\r\n|\r|\n/g;
          function before(text) {
            return linebreak + text;
          }
          function after(text) {
            return text + linebreak;
          }
          function converts(to) {
            function convert(text) {
              return text.replace(newline, to);
            }
            convert.toString = function() {
              return to;
            };
            return convert;
          }
          function split(text) {
            return text.split(newline);
          }
          api["lf"] = converts("\n");
          api["cr"] = converts("\r");
          api["crlf"] = converts("\r\n");
          api["auto"] = converts(linebreak);
          api["before"] = before;
          api["after"] = after;
          api["split"] = split;
          return api;
        });
      }
    });
    __markAsModule(exports2);
    __export2(exports2, {
      convertWikiLinkToMd: () => convertWikiLinkToMd,
      enforceIds: () => enforceIds,
      findFragment: () => findFragment,
      findObjectViaLink: () => findObjectViaLink,
      findScene: () => findScene,
      getSceneThatFragmentBelongsTo: () => getSceneThatFragmentBelongsTo,
      parseWikiLink: () => parseWikiLink,
      resolveIncludes: () => resolveIncludes,
      slugify: () => slugify
    });
    var import_command_shorthand = __toModule(require_command_shorthand());
    var import_eol8 = __toModule(require_eol2());
    var resolveIncludes = (fs2, path, filePath, stageString, layer = 0) => {
      if (layer > 20) {
        throw new Error("Include command recursed more than 20 layers deep. This is a lot. Is there an infinite loop somewhere?");
      }
      const tokens = import_eol8.default.split(stageString);
      let finalString = "";
      for (let token of tokens) {
        if (!token.startsWith("$include")) {
          finalString += token + "\n";
          continue;
        }
        let commandObj = (0, import_command_shorthand.createCommandObject)(token);
        if (!commandObj.args) {
          console.warn("empty $include command found.");
          continue;
        }
        let givenFilepath = commandObj.args[0].toString();
        let targetFilepath = path.resolve(path.dirname(filePath), givenFilepath);
        if (!fs2.existsSync(targetFilepath)) {
          console.log(targetFilepath);
          console.warn("File '" + givenFilepath + "' used in $include command does not exist");
          continue;
        }
        const newFileContents = fs2.readFileSync(targetFilepath, { encoding: "utf-8" });
        let shouldProcessInclude = true;
        if (shouldProcessInclude == true && commandObj.args.length > 1 && commandObj.args[1] === "raw") {
          shouldProcessInclude = false;
        }
        if (shouldProcessInclude) {
          const processedContents = resolveIncludes(fs2, path, targetFilepath, newFileContents, layer + 1);
          finalString += processedContents + "\n";
          continue;
        }
        finalString += newFileContents + "\n";
      }
      return finalString.trim();
    };
    var getSceneThatFragmentBelongsTo = (stageObjects, fragment) => {
      const index = stageObjects.indexOf(fragment);
      if (index === -1) {
        return void 0;
      }
      for (let i = index; i >= 0; i--) {
        const pointer = stageObjects[i];
        if (pointer.type === "scene") {
          return pointer;
        }
      }
      return void 0;
    };
    var findFragment = (stageObjects, primary, title) => {
      if (!primary && !title) {
        return void 0;
      }
      if (primary && title) {
        return stageObjects.find((val) => {
          return val.type === "fragment" && val.primary === primary && val.title === title;
        });
      }
      if (primary) {
        return stageObjects.find((val) => {
          return val.type === "fragment" && val.primary === primary;
        });
      }
      if (title) {
        return stageObjects.find((val) => {
          return val.type === "fragment" && val.title === title;
        });
      }
    };
    var findScene = (stageObjects, primary, title) => {
      if (!primary && !title) {
        return void 0;
      }
      if (primary && title) {
        return stageObjects.find((val) => {
          return val.type === "scene" && val.primary === primary && val.title === title;
        });
      }
      if (primary) {
        return stageObjects.find((val) => {
          return val.type === "scene" && val.primary === primary;
        });
      }
      if (title) {
        return stageObjects.find((val) => {
          return val.type === "scene" && val.title === title;
        });
      }
    };
    var slugify = (...args) => {
      const value = args.join(" ");
      return value.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim().replace(/[-_]/g, " ").replace(/[^a-z0-9 ]/g, "").replace(/\s+/g, "-");
    };
    var parseWikiLink = (wikiLink) => {
      let label = wikiLink;
      let target = wikiLink;
      const barIndex = wikiLink.indexOf("|");
      if (barIndex !== -1) {
        label = wikiLink.substring(0, barIndex);
        target = wikiLink.substring(barIndex + 1);
      } else {
        const rightArrIndex = wikiLink.indexOf("->");
        if (rightArrIndex !== -1) {
          label = wikiLink.substring(0, rightArrIndex);
          target = wikiLink.substring(rightArrIndex + 2);
        } else {
          const leftArrIndex = wikiLink.indexOf("<-");
          if (leftArrIndex !== -1) {
            label = wikiLink.substring(leftArrIndex + 2);
            target = wikiLink.substring(0, leftArrIndex);
          }
        }
      }
      return {
        label,
        target
      };
    };
    var enforceIds = (stageObjects) => {
      let currentId = 0;
      const genWikiId = () => {
        const id = `__recital-id-${currentId.toString().padStart(4, "0")}`;
        currentId += 1;
        return id;
      };
      const newObjs = [];
      for (let obj of stageObjects) {
        if (obj.type !== "scene" && obj.type !== "fragment") {
          newObjs.push(obj);
          continue;
        }
        if (obj.id) {
          newObjs.push(obj);
          continue;
        }
        if (obj.title) {
          let newObj2 = { ...obj };
          newObj2.id = slugify(obj.title);
          newObjs.push(newObj2);
          continue;
        }
        let newObj = { ...obj };
        newObj.id = genWikiId();
        newObjs.push(newObj);
      }
      for (let obj of newObjs) {
        if (obj.type !== "scene" && obj.type !== "fragment") {
          continue;
        }
        if (!obj.primary) {
          obj.primary = obj.id;
        }
      }
      return newObjs;
    };
    var findObjectViaLink = (stageObjects, target) => {
      if (target.startsWith("#")) {
        let possibleTarget2 = findFragment(stageObjects, target.substring(1));
        if (!possibleTarget2) {
          possibleTarget2 = findScene(stageObjects, target.substring(1));
        }
        return possibleTarget2;
      }
      let possibleTarget = findFragment(stageObjects, target);
      if (!possibleTarget) {
        possibleTarget = findFragment(stageObjects, void 0, target);
      }
      if (!possibleTarget) {
        possibleTarget = findScene(stageObjects, target);
      }
      if (!possibleTarget) {
        possibleTarget = findScene(stageObjects, void 0, target);
      }
      if (!possibleTarget) {
        return void 0;
      }
      return possibleTarget;
    };
    var convertWikiLinkToMd = (stageObjects) => {
      const newFlatObjects = [];
      const stageObjectsWithId = enforceIds(stageObjects);
      for (let obj of stageObjectsWithId) {
        if (obj.type !== "paragraph") {
          newFlatObjects.push(obj);
          continue;
        }
        const newText = renderWikilinks(stageObjectsWithId, obj.text);
        newFlatObjects.push({
          ...obj,
          text: newText
        });
      }
      return newFlatObjects;
    };
    var renderWikilinks = (stageObjects, source) => {
      return source.replace(/\[\[(.*?)\]\]/g, (_, target) => {
        const parsedLink = parseWikiLink(target);
        return renderLink(stageObjects, parsedLink.target, parsedLink.label || parsedLink.target);
      });
    };
    var renderLink = (stageObjects, target, label) => {
      if (/^\w+:\/\/\/?\w/i.test(target)) {
        return `[${label}](${target})`;
      }
      const linkTarget = findObjectViaLink(stageObjects, target);
      if (!linkTarget) {
        console.warn("link to " + target + " did not produce a valid link, and may not resolve correctly in editor.");
        return `[${label}](${target})`;
      }
      return `[${label}](${getHrefForObject(linkTarget)})`;
    };
    var getHrefForObject = (object) => {
      if (!object.id) {
        throw new Error("Cannot create a link to an object without an id");
      }
      return `#${object.id}`;
    };
  }
});

// dist/stage-ink.js
var require_stage_ink = __commonJS2({
  "dist/stage-ink.js"(exports2, module2) {
    var __defProp2 = Object.defineProperty;
    var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
    var __getOwnPropNames3 = Object.getOwnPropertyNames;
    var __hasOwnProp2 = Object.prototype.hasOwnProperty;
    var __export2 = (target, all) => {
      for (var name in all)
        __defProp2(target, name, { get: all[name], enumerable: true });
    };
    var __copyProps2 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames3(from))
          if (!__hasOwnProp2.call(to, key) && key !== except)
            __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
      }
      return to;
    };
    var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
    var src_exports = {};
    __export2(src_exports, {
      stageToInk: () => stageToInk2
    });
    module2.exports = __toCommonJS2(src_exports);
    var import_recital = require_stage_parser();
    var import_recital_ext_common_commands3 = require_common_commands_ext();
    var convertMetaIntoInkTags = (token, config) => {
      let tagsString = "";
      if (!token.meta) {
        return "";
      }
      for (let key in token.meta) {
        if (key === "title" && !config?.addStats) {
          continue;
        }
        const value = JSON.stringify(token.meta[key]);
        const splits = value.split("\n");
        for (let split of splits) {
          tagsString += `# ${key.toLocaleUpperCase()}: ${split}
`;
        }
      }
      return tagsString;
    };
    var tags_to_skip = /<(\/?)(?:pre|code|kbd|script|math)[^>]*>/i;
    var SmartyPants = (text = "", attr = "1") => {
      var do_quotes;
      var do_backticks;
      var do_dashes;
      var do_ellipses;
      var do_stupefy;
      var convert_quot = 0;
      if (typeof attr === "number") {
        attr = attr.toString();
      } else {
        attr = attr.replace(/\s/g, "");
      }
      if (attr === "0") {
        return text;
      } else if (attr === "1") {
        do_quotes = 1;
        do_backticks = 1;
        do_dashes = 1;
        do_ellipses = 1;
      } else if (attr === "2") {
        do_quotes = 1;
        do_backticks = 1;
        do_dashes = 2;
        do_ellipses = 1;
      } else if (attr === "3") {
        do_quotes = 1;
        do_backticks = 1;
        do_dashes = 3;
        do_ellipses = 1;
      } else if (attr === "-1") {
        do_stupefy = 1;
      } else {
        for (let i = 0; i < attr.length; i++) {
          let c = attr[i];
          if (c === "q") {
            do_quotes = 1;
          }
          if (c === "b") {
            do_backticks = 1;
          }
          if (c === "B") {
            do_backticks = 2;
          }
          if (c === "d") {
            do_dashes = 1;
          }
          if (c === "D") {
            do_dashes = 2;
          }
          if (c === "i") {
            do_dashes = 3;
          }
          if (c === "e") {
            do_ellipses = 1;
          }
          if (c === "w") {
            convert_quot = 1;
          }
        }
      }
      var tokens = _tokenize(text);
      var result = "";
      var in_pre = 0;
      var prev_token_last_char = "";
      for (let i = 0; i < tokens.length; i++) {
        let cur_token = tokens[i];
        if (cur_token[0] === "tag") {
          result = result + cur_token[1];
          let matched = tags_to_skip.exec(cur_token[1]);
          if (matched) {
            if (matched[1] === "/") {
              in_pre = 0;
            } else {
              in_pre = 1;
            }
          }
        } else {
          let t = cur_token[1];
          let last_char = t.substring(t.length - 1, t.length);
          if (!in_pre) {
            t = ProcessEscapes(t);
            if (convert_quot) {
              t = t.replace(/$quot;/g, '"');
            }
            if (do_dashes) {
              if (do_dashes === 1) {
                t = EducateDashes(t);
              }
              if (do_dashes === 2) {
                t = EducateDashesOldSchool(t);
              }
              if (do_dashes === 3) {
                t = EducateDashesOldSchoolInverted(t);
              }
            }
            if (do_ellipses) {
              t = EducateEllipses(t);
            }
            if (do_backticks) {
              t = EducateBackticks(t);
              if (do_backticks === 2) {
                t = EducateSingleBackticks(t);
              }
            }
            if (do_quotes) {
              if (t === "'") {
                if (/\S/.test(prev_token_last_char)) {
                  t = "&#8217;";
                } else {
                  t = "&#8216;";
                }
              } else if (t === '"') {
                if (/\S/.test(prev_token_last_char)) {
                  t = "&#8221;";
                } else {
                  t = "&#8220;";
                }
              } else {
                t = EducateQuotes(t);
              }
            }
            if (do_stupefy) {
              t = StupefyEntities(t);
            }
          }
          prev_token_last_char = last_char;
          result = result + t;
        }
      }
      return result;
    };
    var EducateQuotes = (str) => {
      var punct_class = "[!\"#$%'()*+,-./:;<=>?@[\\]^_`{|}~]";
      str = str.replace(new RegExp(`^'(?=${punct_class}\\B)`), "&#8217;");
      str = str.replace(new RegExp(`^"(?=${punct_class}\\B)`), "&#8221;");
      str = str.replace(/"'(?=\w)/, "&#8220;&#8216;");
      str = str.replace(/'"(?=\w)/, "&#8216;&#8220;");
      str = str.replace(/'(?=\d\d)/, "&#8217;");
      var close_class = "[^\\ \\t\\r\\n\\[\\{\\(\\-]";
      var not_close_class = "[\\ \\t\\r\\n\\[\\{\\(\\-]";
      var dec_dashes = "&#8211;|&#8212;";
      str = str.replace(new RegExp(`(\\s|&nbsp;|--|&[mn]dash;|${dec_dashes}|&#x201[34])'(?=\\w)`, "g"), "$1&#8216;");
      str = str.replace(new RegExp(`(${close_class})'`, "g"), "$1&#8217;");
      str = str.replace(new RegExp(`(${not_close_class}?)'(?=\\s|s\\b)`, "g"), "$1&#8217;");
      str = str.replace(/'/g, "&#8216;");
      str = str.replace(new RegExp(`(\\s|&nbsp;|--|&[mn]dash;|${dec_dashes}|&#x201[34])"(?=\\w)`, "g"), "$1&#8220;");
      str = str.replace(new RegExp(`(${close_class})"`, "g"), "$1&#8221;");
      str = str.replace(new RegExp(`(${not_close_class}?)"(?=\\s)`, "g"), "$1&#8221;");
      str = str.replace(/"/g, "&#8220;");
      return str;
    };
    var EducateBackticks = (str) => {
      str = str.replace(/``/g, "&#8220;");
      str = str.replace(/''/g, "&#8221;");
      return str;
    };
    var EducateSingleBackticks = (str) => {
      str = str.replace(/`/g, "&#8216;");
      str = str.replace(/'/g, "&#8217;");
      return str;
    };
    var EducateDashes = (str) => {
      str = str.replace(/--/g, "&#8212;");
      return str;
    };
    var EducateDashesOldSchool = (str) => {
      str = str.replace(/---/g, "&#8212;");
      str = str.replace(/--/g, "&#8211;");
      return str;
    };
    var EducateDashesOldSchoolInverted = (str) => {
      str = str.replace(/---/g, "&#8211;");
      str = str.replace(/--/g, "&#8212;");
      return str;
    };
    var EducateEllipses = (str) => {
      str = str.replace(/\.\.\./g, "&#8230;");
      str = str.replace(/\. \. \./g, "&#8230;");
      return str;
    };
    var StupefyEntities = (str) => {
      str = str.replace(/&#8211;/g, "-");
      str = str.replace(/&#8212;/g, "--");
      str = str.replace(/&#8216;/g, "'");
      str = str.replace(/&#8217;/g, "'");
      str = str.replace(/&#8220;/g, '"');
      str = str.replace(/&#8221;/g, '"');
      str = str.replace(/&#8230;/g, "...");
      return str;
    };
    var EducateEntities = (text, attr = "1") => {
      var do_quotes;
      var do_backticks;
      var do_dashes;
      var do_ellipses;
      if (typeof attr === "number") {
        attr = attr.toString();
      } else {
        attr = attr.replace(/\s/g, "");
      }
      if (attr === "0") {
        return text;
      } else if (attr === "1") {
        do_quotes = 1;
        do_backticks = 1;
        do_dashes = 1;
        do_ellipses = 1;
      } else if (attr === "2") {
        do_quotes = 1;
        do_backticks = 1;
        do_dashes = 3;
        do_ellipses = 1;
      } else if (attr === "3") {
        do_quotes = 1;
        do_backticks = 1;
        do_dashes = 3;
        do_ellipses = 1;
      } else {
        for (let i = 0; i < attr.length; i++) {
          let c = attr[i];
          if (c === "q") {
            do_quotes = 1;
          }
          if (c === "b") {
            do_backticks = 1;
          }
          if (c === "B") {
            do_backticks = 2;
          }
          if (c === "d") {
            do_dashes = 1;
          }
          if (c === "D") {
            do_dashes = 2;
          }
          if (c === "i") {
            do_dashes = 3;
          }
          if (c === "e") {
            do_ellipses = 1;
          }
        }
      }
      if (do_dashes) {
        text = text.replace(/&#8211;/g, "\u2013");
        text = text.replace(/&#8212;/g, "\u2014");
      }
      if (do_quotes || do_backticks) {
        text = text.replace(/&#8216;/g, "\u2018");
        text = text.replace(/&#8217;/g, "\u2019");
        text = text.replace(/&#8220;/g, "\u201C");
        text = text.replace(/&#8221;/g, "\u201D");
      }
      if (do_ellipses) {
        text = text.replace(/&#8230;/g, "\u2026");
      }
      return text;
    };
    var StupifyUTF8Char = (str) => {
      str = str.replace(/\u2013/g, "-");
      str = str.replace(/\u2014/g, "--");
      str = str.replace(/\u2018/g, "'");
      str = str.replace(/\u2019/g, "'");
      str = str.replace(/\u201c/g, '"');
      str = str.replace(/\u201d/g, '"');
      str = str.replace(/\u2026/g, "...");
      return str;
    };
    var ProcessEscapes = (str) => {
      str = str.replace(/\\\\/g, "&#92;");
      str = str.replace(/\\"/g, "&#34;");
      str = str.replace(/\\'/g, "&#39;");
      str = str.replace(/\\\./g, "&#46;");
      str = str.replace(/\\-/g, "&#45;");
      str = str.replace(/\\`/g, "&#96;");
      return str;
    };
    var _tokenize = (str) => {
      var pos = 0;
      var len = str.length;
      var tokens = [];
      var match = /<!--[\s\S]*?-->|<\?.*?\?>|<[^>]*>/g;
      var matched = null;
      while (matched = match.exec(str)) {
        if (pos < matched.index) {
          let t2 = ["text", str.substring(pos, matched.index)];
          tokens.push(t2);
        }
        let t = ["tag", matched.toString()];
        tokens.push(t);
        pos = match.lastIndex;
      }
      if (pos < len) {
        let t = ["text", str.substring(pos, len)];
        tokens.push(t);
      }
      return tokens;
    };
    var smartypantsu = (text = "", attr = "1") => {
      var str = SmartyPants(text, attr);
      if (typeof attr === "number") {
        attr = attr.toString();
      } else {
        attr = attr.replace(/\s/g, "");
      }
      if (attr === "-1") {
        return StupifyUTF8Char(str);
      } else {
        return EducateEntities(str, attr);
      }
    };
    var import_recital_ext_common_commands2 = require_common_commands_ext();
    var getNextScene = (currentTokenIndex, flats, allowFragment) => {
      for (let i = currentTokenIndex + 1; i < flats.length; i++) {
        const target = flats[i];
        if (target.type === "scene" || target.type === "fragment" && allowFragment) {
          return target;
        }
      }
    };
    var import_recital_ext_common_commands = require_common_commands_ext();
    var inkSlugify = (inputText) => {
      if (!inputText) {
        return "";
      }
      if (inputText.startsWith("$")) {
        return inputText.substring(1);
      }
      if (["END", "DONE"].includes(inputText.toLocaleUpperCase())) {
        return inputText.toLocaleUpperCase();
      }
      return (0, import_recital_ext_common_commands.slugify)(inputText).replace(/-/g, "_");
    };
    var parseChoice = (line) => {
      const choiceRegex = /^(?<nesting>>*)(?<modifier>[!+.]*) ?(?<logic>{.+})? ?\[\[(?<link>.+)\]\]/g;
      const matches = choiceRegex.exec(line);
      if (!matches || !matches.groups) {
        return void 0;
      }
      const link = (0, import_recital_ext_common_commands2.parseWikiLink)(matches.groups.link);
      return {
        nestedCount: matches.groups.nesting ? matches.groups.nesting.length : 1,
        modifiers: matches.groups.modifier ?? "",
        logic: matches.groups.logic ?? "",
        ...link
      };
    };
    var parseGather = (line) => {
      const singleRegex = /^(?<nesting><+)$/g;
      const singleMatch = singleRegex.exec(line);
      if (singleMatch && singleMatch.groups) {
        return {
          nestedCount: singleMatch.groups.nesting.length,
          text: ""
        };
      }
      const regex = /^(?<nesting><+) +(?<text>.*)/g;
      const matches = regex.exec(line);
      if (!matches || !matches.groups) {
        return void 0;
      }
      return {
        nestedCount: matches.groups.nesting.length,
        text: matches.groups.text.trim()
      };
    };
    var parseGlue = (line) => {
      return line.replace(/\$\<\>/g, "<>");
    };
    var parseRedirect = (line) => {
      const regex = /(^|= *|- *)(?<redirect>->) *(?<link>.+)/g;
      const matches = regex.exec(line);
      if (!matches || !matches.groups) {
        return void 0;
      }
      return {
        beforeLink: line.split("->")[0] ?? "",
        link: matches.groups.link
      };
    };
    var parseParagraph = (token, flats, state = { lastIndent: 0, withinLogicBlock: false }) => {
      if (token.text.trim() === "END") {
        return `${"	".repeat(state.lastIndent)}->END
`;
      }
      let paragraphString = "";
      if (token.text.trim().startsWith("{")) {
        state.withinLogicBlock = true;
      }
      if (token.text.trim().startsWith("}") || token.text.trim().endsWith("}")) {
        state.withinLogicBlock = false;
      }
      let shouldSmartText = true;
      if (/^(VAR |~).*/.test(token.text.trim())) {
        shouldSmartText = false;
      }
      if (state.withinLogicBlock) {
        if (token.text.trim().startsWith("-")) {
          shouldSmartText = false;
        }
        if (token.text.trim().startsWith("{")) {
          shouldSmartText = false;
        }
      }
      const smartText = shouldSmartText ? smartypantsu(token.text, "qie") : token.text;
      const choice = parseChoice(smartText);
      if (choice) {
        state.lastIndent = choice.nestedCount;
        let bulletPoint = choice.modifiers.includes("+") ? "+ " : "* ";
        paragraphString += `${"	".repeat(choice.nestedCount - 1)}${bulletPoint.repeat(
          choice.nestedCount
        )}`;
        if (choice.modifiers.includes(".")) {
          paragraphString += `->
${"	".repeat(state.lastIndent)}${choice.label}
`;
          return paragraphString;
        }
        if (choice.logic) {
          paragraphString += `${choice.logic} `;
        }
        if (choice.modifiers.includes("!")) {
          paragraphString += choice.label;
        } else {
          paragraphString += `[${choice.label}]`;
        }
        if (choice.target !== choice.label) {
          paragraphString += ` -> ${inkSlugify(choice.target)}
`;
        } else {
          paragraphString += "\n";
        }
        return paragraphString;
      }
      let workingText = smartText;
      workingText = parseGlue(workingText);
      const gather = parseGather(workingText);
      if (gather) {
        state.lastIndent = gather.nestedCount - 1;
        workingText = `${"- ".repeat(gather.nestedCount)}${gather.text}
`;
      }
      const redirect = parseRedirect(workingText);
      if (redirect) {
        workingText = `${redirect.beforeLink.trim()} -> ${inkSlugify(redirect.link)}
`;
      }
      if (workingText.trim().endsWith("->")) {
        const i = flats.indexOf(token);
        const targetToken = i > -1 ? getNextScene(i, flats, true) : void 0;
        if (!targetToken) {
          workingText = workingText.trimEnd().replace("->", "-> END");
        } else {
          workingText = workingText.trimEnd().replace("->", `-> ${inkSlugify(targetToken.title ?? targetToken.primary ?? "ERROR")}
`);
        }
      }
      let shorthand = "";
      if (token.primary) {
        shorthand = "@";
        if (token.id) {
          shorthand += "#" + token.id;
        }
        if (token.classes && token.classes.length) {
          if (token.id) {
            shorthand += ".";
          }
          shorthand += `${token.classes.join(".")}`;
        }
        shorthand += " ";
      }
      paragraphString += "	".repeat(state.lastIndent) + shorthand + workingText + "\n";
      return paragraphString;
    };
    var handleRegularInkToken = (token, flats, state, config = { _globals: {} }) => {
      let finalString = "";
      switch (token.type) {
        case "fragment":
          finalString += `= ${inkSlugify(token.title ?? token.primary ?? "ERROR")}
`;
          state.lastIndent = 0;
          finalString += convertMetaIntoInkTags(token, config);
          break;
        case "command":
          if (token.text.startsWith("<>")) {
            finalString += token.text + "\n";
            break;
          }
          finalString += "$" + token.text + "\n";
          break;
        case "paragraph":
          if (token.text.trimStart().startsWith("VAR")) {
            if (!config._globals) {
              config._globals = {};
            }
            if (!config._globals.variables) {
              config._globals.variables = /* @__PURE__ */ new Set();
            }
            const variableName = token.text.split("=")[0].replace("VAR", "").trim();
            config._globals.variables.add(variableName);
          }
          finalString += parseParagraph(token, flats, state);
      }
      return finalString;
    };
    var HUB_REPLACEMENT = "HUB_REPLACEMENT";
    var handleStoryletSection = (startToken, flats, state, config = { _globals: {} }) => {
      const index = flats.indexOf(startToken);
      let storyletString = "";
      let endIndex;
      for (let i2 = index; i2 < flats.length; i2++) {
        if (flats[i2].type === "endScene") {
          endIndex = i2;
          break;
        }
      }
      let isInHub = false;
      let hubText = "";
      let beforeFirstStorylet = true;
      for (let i2 = index; i2 < endIndex; i2++) {
        const token = flats[i2];
        switch (token.type) {
          case "scene":
            break;
          case "fragment":
            if (token.title && token.title.toLocaleLowerCase() === "hub") {
              isInHub = true;
              break;
            }
            if (beforeFirstStorylet) {
              beforeFirstStorylet = false;
              storyletString += "-> _hub\n\n" + HUB_REPLACEMENT + "\n";
            }
            isInHub = false;
            storyletString += `= ${inkSlugify(token.title ?? token.primary ?? "ERROR")}
`;
            state.lastIndent = 0;
            storyletString += convertMetaIntoInkTags(token, config);
            if (token.meta?.enter) {
              const operations = token.meta.enter;
              for (let operation of operations) {
                const variableName = operation.split(/(\+|\-|\*|\/|%|)?=/g)[0]?.trim();
                if (config._globals.variables && config._globals.variables.has(variableName)) {
                  continue;
                }
                if (!config._globals.storyletVariables) {
                  config._globals.storyletVariables = /* @__PURE__ */ new Set();
                }
                config._globals.storyletVariables.add(variableName);
              }
            }
            break;
          case "endFragment":
            if (isInHub) {
              isInHub = false;
              break;
            }
            storyletString += "-> _hub\n\n";
            break;
          case "command":
            if (isInHub) {
              hubText += token.text + "\n";
              break;
            }
            storyletString += token.text + "\n";
            break;
          case "paragraph":
            if (isInHub) {
              hubText += parseParagraph(token, flats, state);
              break;
            }
            storyletString += parseParagraph(token, flats, state);
        }
      }
      let hubString = "";
      const sceneTitle = inkSlugify(startToken.title ?? startToken.primary ?? "ERROR");
      hubString += "= _hub\n";
      hubString += hubText + "\n";
      hubString += `$HUB ${sceneTitle}
`;
      const i = flats.indexOf(startToken);
      const targetToken = i > -1 ? getNextScene(i, flats) : void 0;
      if (!targetToken) {
        hubString += `-> END
`;
      } else {
        hubString += `-> ${inkSlugify(targetToken.title ?? targetToken.primary ?? "ERROR")}
`;
      }
      let finalString = storyletString.replace(HUB_REPLACEMENT, hubString);
      return {
        inkText: finalString,
        newIndex: endIndex
      };
    };
    var stageToInk2 = (recitalText, config = {}) => {
      const flats = (0, import_recital_ext_common_commands3.enforceIds)((0, import_recital.parseFlat)(recitalText));
      let finalString = "";
      const statefulConfig = { ...config, _globals: {} };
      let state = {
        lastIndent: 0
      };
      let firstScene = inkSlugify(statefulConfig.sceneToStartOn ?? "");
      let totalNumScenes = 0;
      for (let i = 0; i < flats.length; i++) {
        const token = flats[i];
        if (token.type === "scene") {
          totalNumScenes += 1;
        }
      }
      let currentScene = 0;
      for (let i = 0; i < flats.length; i++) {
        const token = flats[i];
        switch (token.type) {
          case "scene":
            const sceneTitle = inkSlugify(token.title ?? token.primary ?? "ERROR");
            finalString += `=== ${sceneTitle} ===
`;
            state.lastIndent = 0;
            if (!firstScene) {
              firstScene = sceneTitle;
            }
            const additionalToken = { ...token };
            if (statefulConfig.addStats) {
              if (!additionalToken.meta) {
                additionalToken.meta = {};
              }
              additionalToken.meta.__sceneNumber = currentScene;
              additionalToken.meta.__totalScenes = totalNumScenes;
              currentScene += 1;
            }
            finalString += convertMetaIntoInkTags(additionalToken, statefulConfig);
            if (token.meta?.storylet) {
              const storyletData = handleStoryletSection(token, flats, state, statefulConfig);
              i = storyletData.newIndex;
              finalString += storyletData.inkText;
            }
            break;
        }
        finalString += handleRegularInkToken(token, flats, state, statefulConfig);
      }
      let varString = "";
      if (statefulConfig._globals.storyletVariables) {
        statefulConfig._globals.storyletVariables.forEach((variableName) => {
          varString += `VAR ${variableName} = false
`;
        });
      }
      finalString = `${varString}
-> ${firstScene}
${finalString}`;
      return finalString.trim() + "\n";
    };
  }
});

// ../../node_modules/.pnpm/minimist@1.2.6/node_modules/minimist/index.js
var require_minimist = __commonJS2({
  "../../node_modules/.pnpm/minimist@1.2.6/node_modules/minimist/index.js"(exports2, module2) {
    module2.exports = function(args, opts) {
      if (!opts)
        opts = {};
      var flags = { bools: {}, strings: {}, unknownFn: null };
      if (typeof opts["unknown"] === "function") {
        flags.unknownFn = opts["unknown"];
      }
      if (typeof opts["boolean"] === "boolean" && opts["boolean"]) {
        flags.allBools = true;
      } else {
        [].concat(opts["boolean"]).filter(Boolean).forEach(function(key2) {
          flags.bools[key2] = true;
        });
      }
      var aliases = {};
      Object.keys(opts.alias || {}).forEach(function(key2) {
        aliases[key2] = [].concat(opts.alias[key2]);
        aliases[key2].forEach(function(x) {
          aliases[x] = [key2].concat(aliases[key2].filter(function(y) {
            return x !== y;
          }));
        });
      });
      [].concat(opts.string).filter(Boolean).forEach(function(key2) {
        flags.strings[key2] = true;
        if (aliases[key2]) {
          flags.strings[aliases[key2]] = true;
        }
      });
      var defaults = opts["default"] || {};
      var argv2 = { _: [] };
      Object.keys(flags.bools).forEach(function(key2) {
        setArg(key2, defaults[key2] === void 0 ? false : defaults[key2]);
      });
      var notFlags = [];
      if (args.indexOf("--") !== -1) {
        notFlags = args.slice(args.indexOf("--") + 1);
        args = args.slice(0, args.indexOf("--"));
      }
      function argDefined(key2, arg2) {
        return flags.allBools && /^--[^=]+$/.test(arg2) || flags.strings[key2] || flags.bools[key2] || aliases[key2];
      }
      function setArg(key2, val, arg2) {
        if (arg2 && flags.unknownFn && !argDefined(key2, arg2)) {
          if (flags.unknownFn(arg2) === false)
            return;
        }
        var value2 = !flags.strings[key2] && isNumber(val) ? Number(val) : val;
        setKey(argv2, key2.split("."), value2);
        (aliases[key2] || []).forEach(function(x) {
          setKey(argv2, x.split("."), value2);
        });
      }
      function setKey(obj, keys, value2) {
        var o = obj;
        for (var i2 = 0; i2 < keys.length - 1; i2++) {
          var key2 = keys[i2];
          if (isConstructorOrProto(o, key2))
            return;
          if (o[key2] === void 0)
            o[key2] = {};
          if (o[key2] === Object.prototype || o[key2] === Number.prototype || o[key2] === String.prototype)
            o[key2] = {};
          if (o[key2] === Array.prototype)
            o[key2] = [];
          o = o[key2];
        }
        var key2 = keys[keys.length - 1];
        if (isConstructorOrProto(o, key2))
          return;
        if (o === Object.prototype || o === Number.prototype || o === String.prototype)
          o = {};
        if (o === Array.prototype)
          o = [];
        if (o[key2] === void 0 || flags.bools[key2] || typeof o[key2] === "boolean") {
          o[key2] = value2;
        } else if (Array.isArray(o[key2])) {
          o[key2].push(value2);
        } else {
          o[key2] = [o[key2], value2];
        }
      }
      function aliasIsBoolean(key2) {
        return aliases[key2].some(function(x) {
          return flags.bools[x];
        });
      }
      for (var i = 0; i < args.length; i++) {
        var arg = args[i];
        if (/^--.+=/.test(arg)) {
          var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
          var key = m[1];
          var value = m[2];
          if (flags.bools[key]) {
            value = value !== "false";
          }
          setArg(key, value, arg);
        } else if (/^--no-.+/.test(arg)) {
          var key = arg.match(/^--no-(.+)/)[1];
          setArg(key, false, arg);
        } else if (/^--.+/.test(arg)) {
          var key = arg.match(/^--(.+)/)[1];
          var next = args[i + 1];
          if (next !== void 0 && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
            setArg(key, next, arg);
            i++;
          } else if (/^(true|false)$/.test(next)) {
            setArg(key, next === "true", arg);
            i++;
          } else {
            setArg(key, flags.strings[key] ? "" : true, arg);
          }
        } else if (/^-[^-]+/.test(arg)) {
          var letters = arg.slice(1, -1).split("");
          var broken = false;
          for (var j = 0; j < letters.length; j++) {
            var next = arg.slice(j + 2);
            if (next === "-") {
              setArg(letters[j], next, arg);
              continue;
            }
            if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
              setArg(letters[j], next.split("=")[1], arg);
              broken = true;
              break;
            }
            if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
              setArg(letters[j], next, arg);
              broken = true;
              break;
            }
            if (letters[j + 1] && letters[j + 1].match(/\W/)) {
              setArg(letters[j], arg.slice(j + 2), arg);
              broken = true;
              break;
            } else {
              setArg(letters[j], flags.strings[letters[j]] ? "" : true, arg);
            }
          }
          var key = arg.slice(-1)[0];
          if (!broken && key !== "-") {
            if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
              setArg(key, args[i + 1], arg);
              i++;
            } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) {
              setArg(key, args[i + 1] === "true", arg);
              i++;
            } else {
              setArg(key, flags.strings[key] ? "" : true, arg);
            }
          }
        } else {
          if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
            argv2._.push(
              flags.strings["_"] || !isNumber(arg) ? arg : Number(arg)
            );
          }
          if (opts.stopEarly) {
            argv2._.push.apply(argv2._, args.slice(i + 1));
            break;
          }
        }
      }
      Object.keys(defaults).forEach(function(key2) {
        if (!hasKey2(argv2, key2.split("."))) {
          setKey(argv2, key2.split("."), defaults[key2]);
          (aliases[key2] || []).forEach(function(x) {
            setKey(argv2, x.split("."), defaults[key2]);
          });
        }
      });
      if (opts["--"]) {
        argv2["--"] = new Array();
        notFlags.forEach(function(key2) {
          argv2["--"].push(key2);
        });
      } else {
        notFlags.forEach(function(key2) {
          argv2._.push(key2);
        });
      }
      return argv2;
    };
    function hasKey2(obj, keys) {
      var o = obj;
      keys.slice(0, -1).forEach(function(key2) {
        o = o[key2] || {};
      });
      var key = keys[keys.length - 1];
      return key in o;
    }
    function isNumber(x) {
      if (typeof x === "number")
        return true;
      if (/^0x[0-9a-f]+$/i.test(x))
        return true;
      return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
    }
    function isConstructorOrProto(obj, key) {
      return key === "constructor" && typeof obj[key] === "function" || key === "__proto__";
    }
  }
});

// package.json
var require_package = __commonJS2({
  "package.json"(exports2, module2) {
    module2.exports = {
      name: "@a-morphous/recital-stage-ink",
      version: "1.4.8",
      description: "Parses a recital *.stage file into an ink story.",
      main: "dist/stage-ink.js",
      module: "dist/stage-ink.module.js",
      scripts: {
        test: "node_modules/.bin/test test/*.js"
      },
      author: "Amorphous",
      bin: {
        "stage-ink": "./dist/cli.js"
      },
      license: "MPL 2.0",
      dependencies: {
        "@a-morphous/recital": "^1.2.0",
        "@a-morphous/recital-ext-common-commands": "^1.1.0",
        minimist: "^1.2.6",
        smartypants: "^0.1.6"
      },
      devDependencies: {
        "@a-morphous/test": "workspace:^1.0.0",
        esbuild: "^0.14.32"
      }
    };
  }
});

// cli.js
var stageToInk = require_stage_ink().stageToInk;
var argv = require_minimist()(process.argv.slice(2));
var fs = require("fs");
var pkg = require_package();
var main = () => {
  if (argv.v || argv.version) {
    console.log(pkg.version);
    return;
  }
  if (!argv._ || argv._.length === 0) {
    console.log(`Usage: stage-ink input-file.stage -o outputfile.ink
	`);
    return;
  }
  const config = {};
  if (argv.stats || argv.s) {
    config.addStats = true;
  }
  const results = [];
  for (let i = 0; i < argv._.length; i++) {
    const file = argv._[i];
    const fileString = fs.readFileSync(file, "utf-8");
    const inkString = stageToInk(fileString, config);
    results.push(inkString);
  }
  const str = results.join("\n");
  if (argv.o) {
    fs.writeFileSync(argv.o, str);
  } else {
    console.log(str);
  }
};
main();