recital / packages / ext-common-commands / dist / common-commands-ext.mjs
common-commands-ext.mjs
Raw
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __markAsModule = (target) => __defProp(target, "__esModule", {value: true});
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[Object.keys(cb)[0]])((mod = {exports: {}}).exports, mod), mod.exports;
};
var __reExport = (target, module, desc) => {
  if (module && typeof module === "object" || typeof module === "function") {
    for (let key of __getOwnPropNames(module))
      if (!__hasOwnProp.call(target, key) && key !== "default")
        __defProp(target, key, {get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable});
  }
  return target;
};
var __toModule = (module) => {
  return __reExport(__markAsModule(__defProp(module != null ? __create(__getProtoOf(module)) : {}, "default", module && module.__esModule && "default" in module ? {get: () => module.default, enumerable: true} : {value: module, enumerable: true})), module);
};

// ../../node_modules/.pnpm/eol@0.9.1/node_modules/eol/eol.js
var require_eol = __commonJS({
  "../../node_modules/.pnpm/eol@0.9.1/node_modules/eol/eol.js"(exports, module) {
    !function(root, name, make) {
      if (typeof module != "undefined" && module.exports)
        module.exports = make();
      else
        root[name] = make();
    }(exports, "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;
    });
  }
});

// src/lib/include-command.ts
var import_eol = __toModule(require_eol());
import {createCommandObject} from "@a-morphous/recital/dist/lib/tools/command-shorthand";
var resolveIncludes = (fs, 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_eol.default.split(stageString);
  let finalString = "";
  for (let token of tokens) {
    if (!token.startsWith("$include")) {
      finalString += token + "\n";
      continue;
    }
    let commandObj = 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 (!fs.existsSync(targetFilepath)) {
      console.log(targetFilepath);
      console.warn("File '" + givenFilepath + "' used in $include command does not exist");
      continue;
    }
    const newFileContents = fs.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(fs, path, targetFilepath, newFileContents, layer + 1);
      finalString += processedContents + "\n";
      continue;
    }
    finalString += newFileContents + "\n";
  }
  return finalString.trim();
};

// src/tools/fragment-tools.ts
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;
    });
  }
};

// src/tools/scene-tools.ts
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;
    });
  }
};

// src/tools/text-tools.ts
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
  };
};

// src/tools/stage-tools.ts
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;
};

// src/lib/convert-wiki-link-to-md.ts
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}`;
};
export {
  convertWikiLinkToMd,
  enforceIds,
  findFragment,
  findObjectViaLink,
  findScene,
  getSceneThatFragmentBelongsTo,
  parseWikiLink,
  resolveIncludes,
  slugify
};