"use strict";
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 __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all2) => {
  for (var name in all2)
    __defProp(target, name, { get: all2[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
var __runInitializers = (array, flags, self, value) => {
  for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
  return value;
};
var __decorateElement = (array, flags, name, decorators, target, extra) => {
  var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
  var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
  var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
  var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
    return __privateGet(this, extra);
  }, set [name](x) {
    return __privateSet(this, extra, x);
  } }, name));
  k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
  for (var i = decorators.length - 1; i >= 0; i--) {
    ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
    if (k) {
      ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
      if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
      if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
    }
    it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
    if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
    else if (typeof it !== "object" || it === null) __typeError("Object expected");
    else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
  }
  return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
};
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);

// src/core/utils/index.ts
var index_exports = {};
__export(index_exports, {
  Buckets: () => Buckets,
  Defer: () => Defer,
  Graph: () => Graph,
  LINK_KEYS: () => LINK_KEYS,
  LINK_KEYS_LEADING_CONFIG: () => LINK_KEYS_LEADING_CONFIG,
  LINK_KEYS_PAGE_CONSTRUCTOR_CONFIG: () => LINK_KEYS_PAGE_CONSTRUCTOR_CONFIG,
  MEDIA_FORMATS: () => MEDIA_FORMATS,
  VFile: () => VFile,
  all: () => all,
  bounded: () => bounded,
  bucket: () => bucket,
  compareJson: () => compareJson,
  console: () => _console,
  copyJson: () => copyJson,
  errorMessage: () => errorMessage,
  evaluateWhen: () => evaluateWhen,
  fallbackLang: () => fallbackLang,
  filterBlocksByConditions: () => filterBlocksByConditions,
  filterTokens: () => filterTokens,
  freezeJson: () => freezeJson,
  fs: () => fs,
  fullPath: () => fullPath,
  generateHooksAccess: () => generateHooksAccess,
  get: () => get,
  getDepth: () => getDepth,
  getDepthPath: () => getDepthPath,
  hasWhenConditions: () => hasWhenConditions,
  intercept: () => intercept,
  isExternalHref: () => isExternalHref2,
  isMediaLink: () => isMediaLink,
  isRelativePath: () => isRelativePath,
  langFromPath: () => langFromPath,
  longLink: () => longLink,
  memoize: () => memoize,
  noop: () => noop,
  normalizePath: () => normalizePath,
  own: () => own,
  parseLocalUrl: () => parseLocalUrl,
  race: () => race,
  rebasePath: () => rebasePath,
  replaceAll: () => replaceAll,
  setExt: () => setExt,
  shortLink: () => shortLink,
  wait: () => wait,
  walkLinks: () => walkLinks,
  zip: () => zip
});
module.exports = __toCommonJS(index_exports);

// src/core/utils/common.ts
var import_lodash = require("lodash");

// src/core/utils/decorators.ts
function bounded(_originalMethod, context) {
  const methodName = context.name;
  context.addInitializer(function() {
    this[methodName] = this[methodName].bind(this);
  });
}
var Release = /* @__PURE__ */ Symbol("Cache");
function memoize(...props) {
  return function(_originalMethod, context) {
    const methodName = context.name;
    const hash = typeof props[0] === "function" ? props[0] : function(...args) {
      const mem = args.slice(0, props.length);
      if (!mem.every(isPrimitive)) {
        return null;
      }
      return props.map((prop, index) => `${prop}=${mem[index]}`).join("&");
    };
    context.addInitializer(function() {
      const cache = /* @__PURE__ */ new Map();
      const method = this[methodName];
      this[methodName] = function(...args) {
        const key = hash.call(this, ...args);
        if (key === null) {
          return method.call(this, ...args);
        }
        if (!cache.has(key)) {
          cache.set(key, method.call(this, ...args));
        }
        return cache.get(key);
      };
      this[methodName][Release] = (args) => {
        const key = hash.call(this, ...args);
        cache.delete(key);
      };
    });
  };
}
memoize.release = (method, ...args) => {
  if (Release in method) {
    method[Release](args);
  }
};
var PRIMITIVE_TYPES = ["string", "number", "symbol", "boolean", "undefined"];
function isPrimitive(value) {
  return !value || PRIMITIVE_TYPES.includes(typeof value);
}

// src/core/utils/common.ts
var all = Promise.all.bind(Promise);
var race = Promise.race.bind(Promise);
function noop() {
}
function get(key) {
  return function(object) {
    return object[key];
  };
}
function zip(keys, values) {
  return keys.reduce((acc, key, index) => {
    acc[key] = values[index];
    return acc;
  }, {});
}
function own(box, field) {
  return Boolean(box && typeof box === "object") && Object.prototype.hasOwnProperty.call(box, field);
}
function copyJson(json) {
  return json ? JSON.parse(JSON.stringify(json)) : json;
}
function freezeJson(target, visited = /* @__PURE__ */ new Set()) {
  if (!visited.has(target)) {
    visited.add(target);
    if (Array.isArray(target)) {
      target.forEach((item) => freezeJson(item, visited));
    }
    if ((0, import_lodash.isObject)(target) && !Object.isSealed(target)) {
      Object.freeze(target);
      Object.keys(target).forEach(
        (key) => freezeJson(target[key], visited)
      );
    }
  }
  return target;
}
function errorMessage(error) {
  if (typeof error === "string") {
    return error;
  }
  if (own(error, "message")) {
    return error.message;
  }
  return String(error);
}
function fallbackLang(lang) {
  if (["kz", "ua", "be", "ru"].includes(lang)) {
    return "ru";
  }
  return "en";
}
var Defer = class {
  constructor() {
    this.promise = new Promise((resolve, reject) => {
      this.resolve = resolve;
      this.reject = reject;
    });
  }
};
function wait(delay, action = () => {
}) {
  let timeout;
  const promise = new Promise((resolve) => {
    timeout = setTimeout(resolve, delay);
  }).then(() => action());
  Object.assign(promise, {
    cancel: () => clearTimeout(timeout),
    skip: () => {
      action = () => {
      };
    }
  });
  return promise;
}
function bucket() {
  let _value;
  return {
    get: () => _value,
    set: (value) => {
      _value = value;
    }
  };
}
var _delete_dec, _get_dec, _set_dec, _bind_dec, _init;
_bind_dec = [bounded], _set_dec = [bounded], _get_dec = [bounded], _delete_dec = [bounded];
var Buckets = class {
  constructor() {
    __runInitializers(_init, 5, this);
    this.scope = /* @__PURE__ */ new Map();
  }
  bind(key) {
    return {
      get: () => this.get(key),
      set: (value) => this.set(key, value)
    };
  }
  set(key, value) {
    this.scope.set(key, value);
  }
  get(key) {
    return this.scope.get(key);
  }
  delete(key) {
    this.scope.delete(key);
  }
};
_init = __decoratorStart(null);
__decorateElement(_init, 1, "bind", _bind_dec, Buckets);
__decorateElement(_init, 1, "set", _set_dec, Buckets);
__decorateElement(_init, 1, "get", _get_dec, Buckets);
__decorateElement(_init, 1, "delete", _delete_dec, Buckets);
__decoratorMetadata(_init, Buckets);

// src/core/utils/console.ts
var import_node_console = require("node:console");
var MutableConsole = class extends import_node_console.Console {
  log(...args) {
    this.write("log", args);
  }
  time(label) {
    if (process.env.NODE_ENV !== "test") {
      super.time(label);
    }
  }
  timeEnd(label) {
    if (process.env.NODE_ENV !== "test") {
      super.timeEnd(label);
    }
  }
  write(level, args) {
    if (process.env.NODE_ENV !== "test") {
      super[level](...args);
    }
  }
};
var _console = new MutableConsole(process.stdout, process.stderr, false);

// src/core/utils/extension.ts
function generateHooksAccess(name, hooks) {
  const Hooks = /* @__PURE__ */ Symbol(`${name}Hooks`);
  function getHooks(program) {
    return program && program[Hooks] || hooks("Unknown");
  }
  function withHooks(Target, { kind }) {
    var _a, _b;
    if (kind !== "class") {
      throw new TypeError(`Decorator 'withHooks' is not applicable to '${kind}'.`);
    }
    return class extends (_b = Target, _a = Hooks, _b) {
      constructor() {
        super(...arguments);
        this[_a] = intercept(this.name, hooks(this.name || name));
      }
    };
  }
  return [getHooks, withHooks, Hooks];
}
function intercept(service, hooks) {
  for (const [hook, handler] of Object.entries(hooks)) {
    handler.intercept({
      register: (info) => {
        const { type, name, fn } = info;
        const meta = { service, hook, name, type };
        if (type === "promise") {
          info.fn = async (...args) => {
            try {
              return await fn(...args);
            } catch (error) {
              if (error instanceof Error) {
                Object.assign(error, { hook: meta });
              }
              throw error;
            }
          };
        } else if (type === "sync") {
          info.fn = (...args) => {
            try {
              return fn(...args);
            } catch (error) {
              if (error instanceof Error) {
                Object.assign(error, { hook: meta });
              }
              throw error;
            }
          };
        } else {
          throw new TypeError("Unexpected hook tap type - " + type);
        }
        return info;
      }
    });
  }
  return hooks;
}

// src/core/utils/path.ts
var import_node_path = require("node:path");
var import_normalize_path = __toESM(require("normalize-path"));
var import_utils = require("@diplodoc/cli/lib/utils");
function normalizePath(path) {
  return (0, import_normalize_path.default)((0, import_node_path.normalize)((0, import_normalize_path.default)(path, false)), false);
}
function isRelativePath(path) {
  return !(0, import_utils.isExternalHref)(path) && !(0, import_node_path.isAbsolute)(path);
}
function langFromPath(path, config) {
  const { lang, langs } = config;
  const pathBaseLang = normalizePath(path).split("/")[0];
  const pathLang = langs.some((l) => typeof l === "string" ? l === pathBaseLang : l.lang === pathBaseLang) && pathBaseLang;
  const result = pathLang || lang || langs[0];
  return typeof result === "string" ? result : result.lang;
}
function rebasePath(root, path) {
  return normalizePath((0, import_node_path.join)((0, import_node_path.dirname)(root), path));
}
function fullPath(path, root) {
  if (path.match(/^(\/|\\)/)) {
    return normalizePath(path.slice(1));
  } else {
    return normalizePath((0, import_node_path.join)((0, import_node_path.dirname)(root), path));
  }
}
function getDepth(path) {
  return path.replace(/\\/g, "/").replace(/^\.\/|\/$/g, "").split("/").length;
}
function getDepthPath(depth) {
  return Array(depth).fill("../").join("") || "./";
}
function setExt(path, newext) {
  newext = newext.startsWith(".") ? newext.slice(1) : newext;
  return path.slice(0, -(0, import_node_path.extname)(path).length) + (newext ? "." + newext : "");
}

// src/core/utils/string.ts
function replaceAll(string, match, replace) {
  if (!string) {
    return string;
  }
  const matches = [];
  let index = -1;
  while ((index = string.indexOf(match, index + 1)) > -1) {
    matches.push([index, index + match.length]);
  }
  return matches.reduceRight((string2, match2) => {
    return string2.slice(0, match2[0]) + replace + string2.slice(match2[1]);
  }, string);
}

// src/core/utils/url.ts
var import_node_url = require("node:url");
var import_lodash2 = require("lodash");
function isExternalHref2(href) {
  return /^(\w{1,10}:)?\/\//.test(href) || /^([+\w]{1,10}:)/.test(href);
}
function longLink(href) {
  if (isExternalHref2(href)) {
    return href;
  }
  const [pathWithoutHash, hash] = href.split("#", 2);
  const [path, query] = pathWithoutHash.split("?", 2);
  let result = path;
  if (result.endsWith("/")) {
    result += "index.html";
  }
  if (result.match(/\.[^/\\]+$/)) {
    result += ".html";
  }
  if (query) {
    result += "?" + query;
  }
  if (hash) {
    result += "#" + hash;
  }
  return result;
}
function shortLink(href) {
  if (isExternalHref2(href)) {
    return href;
  }
  const [pathWithoutHash, hash] = href.split("#", 2);
  const [path, query] = pathWithoutHash.split("?", 2);
  let result = path.replace(/\\/g, "/").replace(/\/index\.html$/, "/").replace(/\/index$/, "/").replace(/^index\.html$/, ".").replace(/^index$/, ".").replace(/\.html$/, "");
  if (result === "" || result === "./") {
    result = ".";
  }
  if (query) {
    result += "?" + query;
  }
  if (hash) {
    result += "#" + hash;
  }
  return result;
}
var MEDIA_FORMATS = /\.(svg|png|gif|jpe?g|bmp|webp|ico)$/i;
var DOC_FORMATS = /\.(txt|ya?ml|docx|xlsx|pptx|pdf|csv)$/i;
function isMediaLink(link2) {
  return MEDIA_FORMATS.test(link2) || DOC_FORMATS.test(link2);
}
var UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g;
function unescapeAll(str) {
  if (str.indexOf("\\") < 0 && str.indexOf("&") < 0) {
    return str;
  }
  return str.replace(UNESCAPE_MD_RE, (_match, escaped) => escaped);
}
function parseLocalUrl(url) {
  if (!url || isExternalHref2(url) || url.startsWith("/")) {
    return null;
  }
  try {
    const parsed = (0, import_node_url.parse)(unescapeAll(url));
    if (parsed.host || parsed.protocol) {
      return null;
    }
    if (parsed.path) {
      parsed.path = normalizePath(parsed.path);
    }
    return (0, import_lodash2.pick)(parsed, ["path", "search", "hash"]);
  } catch {
    return null;
  }
}
var LINK_KEYS_LEADING_CONFIG = ["href"];
var LINK_KEYS_PAGE_CONSTRUCTOR_CONFIG = [
  "src",
  "url",
  "href",
  "icon",
  "image",
  "desktop",
  "mobile",
  "tablet",
  "previewImg",
  "image",
  "avatar",
  "logo",
  "light",
  "dark"
];
var LINK_KEYS = [
  .../* @__PURE__ */ new Set([...LINK_KEYS_LEADING_CONFIG, ...LINK_KEYS_PAGE_CONSTRUCTOR_CONFIG])
];
function walkLinks(object, modify) {
  return (0, import_lodash2.cloneDeepWith)(object, (value, key) => {
    if (LINK_KEYS.includes(key) && (0, import_lodash2.isString)(value)) {
      return modify(value);
    }
    return void 0;
  });
}

// src/core/utils/markdown.ts
function filterTokens(tokens, type, handler) {
  let commented = false;
  if (!tokens || !tokens.length) {
    return;
  }
  for (let index = 0; index < tokens.length; index++) {
    const token = tokens[index];
    if (token.type === "html_block") {
      const commentStart = token.content.match("<!--");
      const commentEnd = token.content.match("-->");
      if (commentStart && !commentEnd) {
        commented = true;
      }
      if (!commentStart && commentEnd) {
        commented = false;
      }
    }
    if (token.type === type) {
      const result = handler(token, { commented, index });
      if (result?.skip) {
        index += result?.skip - 1;
      }
    }
  }
}

// src/core/utils/file.ts
var toString = (data) => {
  if (typeof data === "string") {
    return data;
  }
  return JSON.stringify(data);
};
var VFile = class _VFile {
  constructor(path, data, formatter = toString) {
    this._info = {};
    this._path = normalizePath(path);
    this._data = data;
    this._format = formatter;
  }
  get path() {
    return this._path;
  }
  set path(value) {
    this._path = normalizePath(value);
  }
  get data() {
    return this._data;
  }
  set data(value) {
    this._data = value;
  }
  get info() {
    return this._info;
  }
  set info(value) {
    this._info = value;
  }
  copy(path) {
    const data = typeof this._data === "string" ? this._data : copyJson(this._data);
    return new _VFile(path || this._path, data, this._format);
  }
  format(formatter) {
    this._format = formatter;
  }
  toString() {
    return this._format(this._data);
  }
};

// src/core/utils/graph/index.ts
var import_dependency_graph = require("dependency-graph");
var Graph = class _Graph extends import_dependency_graph.DepGraph {
  static is(data) {
    if (data instanceof _Graph) {
      return true;
    }
    return Boolean(
      data && typeof data === "object" && "__type" in data && data.__type === "$$Graph"
    );
  }
  static deserialize(message) {
    return new _Graph().consume(message);
  }
  constructor() {
    super({ circular: true });
  }
  /**
   * Extracts a subgraph related to the specified node
   * @param nodeName - name of the node for which to extract the subgraph
   * @returns new Graph instance with the extracted subgraph
   */
  extract(nodeName) {
    const extractedGraph = new _Graph();
    if (!this.hasNode(nodeName)) {
      return extractedGraph;
    }
    this.copyDependenciesRecursively(nodeName, extractedGraph, /* @__PURE__ */ new Set());
    this.copyDependentsRecursively(nodeName, extractedGraph, /* @__PURE__ */ new Set());
    return extractedGraph;
  }
  /**
   * Consumes a serialized graph
   */
  consume(graph) {
    if (!graph) {
      return this;
    }
    if (graph instanceof _Graph) {
      graph = graph.serialize();
    }
    for (const node of graph.nodes) {
      this.addNode(node.name);
      if (node.data) {
        this.setNodeData(node.name, node.data);
      }
    }
    for (const dep of graph.dependencies) {
      this.addDependency(dep.from, dep.to);
    }
    return this;
  }
  /**
   * Removes node from graph
   * If node dependencies has no other dependants, they will be removed too
   * @param nodeName - node name to remove
   */
  release(nodeName) {
    if (!this.hasNode(nodeName)) {
      return this;
    }
    const directParents = this.directDependenciesOf(nodeName);
    for (const parent of directParents) {
      this.removeDependency(nodeName, parent);
    }
    const directDependents = this.directDependentsOf(nodeName);
    for (const dependent of directDependents) {
      this.removeDependency(dependent, nodeName);
    }
    this.removeNode(nodeName);
    for (const parent of directParents) {
      if (this.hasNode(parent) && this.directDependentsOf(parent).length === 0) {
        this.release(parent);
      }
    }
    return this;
  }
  /**
   * Serializes the graph to a format for transfer between threads
   * @returns serialized representation of the graph
   */
  serialize() {
    const nodes = [];
    const dependencies = [];
    const allNodes = this.overallOrder();
    for (const nodeName of allNodes) {
      const nodeData = this.getNodeData(nodeName);
      nodes.push({
        name: nodeName,
        // Some data srtuctures can be Proxy objects,
        // which can't be serialized by threads defaultSerializer.
        // So, read data from this Proxy objects and write it as raw json.
        data: JSON.parse(JSON.stringify(nodeData))
      });
    }
    for (const nodeName of allNodes) {
      const directDeps = this.directDependenciesOf(nodeName);
      for (const dep of directDeps) {
        dependencies.push({
          from: nodeName,
          to: dep
        });
      }
    }
    nodes.sort((a, b) => a.name > b.name ? 1 : -1);
    dependencies.sort((a, b) => {
      if (a.from === b.from) {
        return a.to > b.to ? 1 : -1;
      }
      return a.from > b.from ? 1 : -1;
    });
    return { nodes, dependencies, __type: "$$Graph" };
  }
  /**
   * Recursively copies node dependencies
   */
  copyDependenciesRecursively(nodeName, targetGraph, processed) {
    if (processed.has(nodeName)) {
      return;
    }
    processed.add(nodeName);
    if (!targetGraph.hasNode(nodeName)) {
      targetGraph.addNode(nodeName);
      const nodeData = this.getNodeData(nodeName);
      if (nodeData) {
        targetGraph.setNodeData(nodeName, nodeData);
      }
    }
    const dependencies = this.directDependenciesOf(nodeName);
    for (const dep of dependencies) {
      this.copyDependenciesRecursively(dep, targetGraph, processed);
      targetGraph.addDependency(nodeName, dep);
    }
  }
  /**
   * Recursively copies dependent nodes
   */
  copyDependentsRecursively(nodeName, targetGraph, processed) {
    if (processed.has(nodeName)) {
      return;
    }
    processed.add(nodeName);
    if (!targetGraph.hasNode(nodeName)) {
      targetGraph.addNode(nodeName);
      const nodeData = this.getNodeData(nodeName);
      if (nodeData) {
        targetGraph.setNodeData(nodeName, nodeData);
      }
    }
    const dependents = this.directDependentsOf(nodeName);
    for (const dep of dependents) {
      this.copyDependentsRecursively(dep, targetGraph, processed);
      targetGraph.addDependency(dep, nodeName);
    }
  }
};

// src/core/utils/json/index.ts
function compareJson(oldObj, newObj) {
  const added = [];
  const changed = [];
  const removed = [];
  compareObjects(oldObj, newObj, "", added, changed, removed);
  return {
    added: added.sort(),
    changed: changed.sort(),
    removed: removed.sort()
  };
}
function compareObjects(oldObj, newObj, path, added, changed, removed) {
  if (isNullable(oldObj) && isNullable(newObj)) {
    return;
  }
  compareEntity(oldObj, newObj, path, added, changed, removed);
}
function addAllPaths(obj, path, arr) {
  if (path) {
    arr.push(path);
  }
  if (typeof obj !== "object" || obj === null) {
    return;
  }
  if (Array.isArray(obj)) {
    for (let i = 0; i < obj.length; i++) {
      const currentPath = path ? `${path}[${i}]` : `[${i}]`;
      addAllPaths(obj[i], currentPath, arr);
    }
    return;
  }
  for (const key of Object.keys(obj)) {
    const currentPath = path ? `${path}.${key}` : key;
    addAllPaths(obj[key], currentPath, arr);
  }
}
function compareArrays(oldArr, newArr, path, added, changed, removed) {
  const maxLength = Math.max(oldArr.length, newArr.length);
  for (let i = 0; i < maxLength; i++) {
    const currentPath = path ? `${path}[${i}]` : `[${i}]`;
    const oldItem = oldArr[i];
    const newItem = newArr[i];
    if (i >= oldArr.length) {
      added.push(currentPath);
    } else if (i >= newArr.length) {
      removed.push(currentPath);
    } else {
      compareObjects(oldItem, newItem, currentPath, added, changed, removed);
    }
  }
}
function compareObjectProperties(oldObj, newObj, path, added, changed, removed) {
  const allKeys = /* @__PURE__ */ new Set([...Object.keys(oldObj), ...Object.keys(newObj)]);
  for (const key of allKeys) {
    const currentPath = path ? `${path}.${key}` : key;
    const oldValue = oldObj[key];
    const newValue = newObj[key];
    const isOldMember = key in oldObj;
    const isNewMember = key in newObj;
    if (isOldMember && isNewMember) {
      compareEntity(oldValue, newValue, currentPath, added, changed, removed);
    } else if (isNewMember) {
      addAllPaths(newValue, currentPath, added);
    } else if (isOldMember) {
      addAllPaths(oldValue, currentPath, removed);
    }
  }
}
function compareEntity(oldValue, newValue, path, added, changed, removed) {
  if ((isNullable(oldValue) || isNullable(newValue)) && !(isNullable(oldValue) && isNullable(newValue))) {
    changed.push(path);
  } else if (typeof oldValue !== typeof newValue) {
    changed.push(path);
  } else if (typeof oldValue !== "object" || typeof newValue !== "object") {
    if (oldValue !== newValue) {
      changed.push(path);
    }
  } else if (Array.isArray(oldValue) && Array.isArray(newValue)) {
    compareArrays(oldValue, newValue, path, added, changed, removed);
  } else if (!Array.isArray(oldValue) && !Array.isArray(newValue)) {
    compareObjectProperties(oldValue, newValue, path, added, changed, removed);
  } else {
    changed.push(path);
  }
}
function isNullable(value) {
  return value === null || value === void 0;
}

// src/core/utils/fs.ts
var import_promises = require("node:fs/promises");
var import_node_fs = require("node:fs");
var fs = {
  stat: import_promises.stat,
  statSync: import_node_fs.statSync,
  realpathSync: import_node_fs.realpathSync,
  realpath: import_promises.realpath,
  rm: import_promises.rm,
  link: import_promises.link,
  unlink: import_promises.unlink,
  copyFile: import_promises.copyFile,
  mkdir: import_promises.mkdir,
  readFile: import_promises.readFile,
  writeFile: import_promises.writeFile
};

// src/core/utils/conditions.ts
var import_liquid = require("@diplodoc/liquid");
function evaluateWhen(whenValue, vars, skipMissingVars) {
  if (typeof whenValue === "boolean") {
    return whenValue;
  }
  if (typeof whenValue === "string") {
    const evalResult = (0, import_liquid.evaluate)(whenValue, vars, skipMissingVars);
    if (evalResult === import_liquid.NoValue && skipMissingVars) {
      return true;
    }
    return Boolean(evalResult);
  }
  return true;
}
function isBlockWithWhen(item) {
  return typeof item === "object" && item !== null && "when" in item;
}
function filterBlocksByConditions(obj, vars, skipMissingVars) {
  if (Array.isArray(obj)) {
    return obj.filter((item) => {
      if (isBlockWithWhen(item)) {
        if (item.when === null || item.when === void 0) {
          return true;
        }
        return evaluateWhen(item.when, vars, skipMissingVars);
      }
      return true;
    }).map((item) => {
      if (isBlockWithWhen(item)) {
        const { when: _, ...rest } = item;
        return filterBlocksByConditions(rest, vars, skipMissingVars);
      }
      return filterBlocksByConditions(item, vars, skipMissingVars);
    });
  }
  if (obj && typeof obj === "object" && obj !== null) {
    const result = {};
    for (const [key, value] of Object.entries(obj)) {
      result[key] = filterBlocksByConditions(value, vars, skipMissingVars);
    }
    return result;
  }
  return obj;
}
function hasWhenConditions(obj) {
  if (Array.isArray(obj)) {
    return obj.some((item) => hasWhenConditions(item));
  }
  if (obj && typeof obj === "object" && obj !== null) {
    if ("when" in obj) {
      return true;
    }
    return Object.values(obj).some((value) => hasWhenConditions(value));
  }
  return false;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  Buckets,
  Defer,
  Graph,
  LINK_KEYS,
  LINK_KEYS_LEADING_CONFIG,
  LINK_KEYS_PAGE_CONSTRUCTOR_CONFIG,
  MEDIA_FORMATS,
  VFile,
  all,
  bounded,
  bucket,
  compareJson,
  console,
  copyJson,
  errorMessage,
  evaluateWhen,
  fallbackLang,
  filterBlocksByConditions,
  filterTokens,
  freezeJson,
  fs,
  fullPath,
  generateHooksAccess,
  get,
  getDepth,
  getDepthPath,
  hasWhenConditions,
  intercept,
  isExternalHref,
  isMediaLink,
  isRelativePath,
  langFromPath,
  longLink,
  memoize,
  noop,
  normalizePath,
  own,
  parseLocalUrl,
  race,
  rebasePath,
  replaceAll,
  setExt,
  shortLink,
  wait,
  walkLinks,
  zip
});
//# sourceMappingURL=index.js.map
