"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __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/vars/index.ts
var index_exports = {};
__export(index_exports, {
  VarsService: () => VarsService,
  getHooks: () => getHooks
});
module.exports = __toCommonJS(index_exports);

// src/core/vars/hooks.ts
var import_tapable = require("tapable");
var import_utils = require("@diplodoc/cli/lib/utils");
function hooks(name) {
  return {
    /**
     * Async waterfall hook.<br>
     * Called after any presets.yaml was loaded.
     */
    PresetsLoaded: new import_tapable.AsyncSeriesWaterfallHook(
      ["presets", "path"],
      `${name}.PresetsLoaded`
    ),
    /**
     * Async parallel hook.<br>
     * Called after vars was resolved on any level.<br>
     * Vars data is sealed here.
     */
    Resolved: new import_tapable.AsyncParallelHook(
      ["vars", "path"],
      `${name}.Resolved`
    )
  };
}
var [getHooks, withHooks] = (0, import_utils.generateHooksAccess)("Vars", hooks);

// src/core/vars/VarsService.ts
var import_node_path = require("node:path");
var import_lodash2 = require("lodash");
var import_js_yaml = require("js-yaml");
var import_utils2 = require("@diplodoc/cli/lib/utils");

// src/core/vars/utils.ts
var import_lodash = require("lodash");
function proxy(path, resolve, prefix) {
  const proxied = new Proxy(
    {},
    {
      has: (_target, prop) => {
        const { value, scope, track, missed } = resolve(prop);
        if (value === void 0) {
          missed(path, full(prefix, prop));
          return false;
        }
        track(path, scope, full(prefix, prop));
        return true;
      },
      get: (_target, prop) => {
        if (typeof Object.prototype[prop] === "function") {
          return Object.prototype[prop].bind(proxied);
        }
        const { value, scope, track, missed } = resolve(prop);
        if (value === void 0 && typeof prop !== "symbol") {
          missed(path, full(prefix, prop));
          return void 0;
        }
        if (typeof prop === "symbol") {
          return value;
        }
        track(path, scope, full(prefix, prop));
        if (value && typeof value === "object" && !Array.isArray(value)) {
          return proxy(
            path,
            (prop2) => ({
              value: value[prop2],
              scope,
              track,
              missed,
              keys: () => Object.keys(value)
            }),
            full(prefix, prop)
          );
        }
        return value;
      },
      getOwnPropertyDescriptor: (_target, prop) => {
        const { value, scope, track, missed } = resolve(prop);
        if (value === void 0) {
          missed(path, full(prefix, prop));
          return void 0;
        }
        track(path, scope, full(prefix, prop));
        return { configurable: true, enumerable: true, value };
      },
      ownKeys: () => {
        const { keys } = resolve(path);
        return (0, import_lodash.uniq)(keys());
      }
    }
  );
  return proxied;
}
function full(prefix, prop) {
  return prefix ? prefix + "." + prop : prop;
}

// src/core/vars/VarsService.ts
var _trackMissedDependency_dec, _trackDependency_dec, _load_dec, _VarsService_decorators, _init;
_VarsService_decorators = [withHooks], _load_dec = [import_utils2.bounded], _trackDependency_dec = [import_utils2.bounded], _trackMissedDependency_dec = [import_utils2.bounded];
var VarsService = class {
  constructor(run, { usePresets = true } = {}) {
    __runInitializers(_init, 5, this);
    this.name = "Vars";
    this.relations = new import_utils2.Graph();
    this.run = void 0;
    this.logger = void 0;
    this.config = void 0;
    this.presets = {};
    this.usePresets = true;
    this.storeDeps = true;
    this.run = run;
    this.logger = run.logger;
    this.config = run.config;
    this.usePresets = usePresets;
  }
  async init(presets) {
    if (!this.usePresets) {
      return [];
    }
    presets = presets || await this.run.glob("**/presets.yaml", {
      cwd: this.run.input,
      ignore: this.run.config.ignore
    });
    return (0, import_utils2.all)(presets.map(this.load));
  }
  /**
   * @returns preset value by filename
   */
  get(path) {
    if (!this.relations.hasNode(path)) {
      return void 0;
    }
    return this.presets[path];
  }
  for(path, from) {
    const scopes = this.scopes(from || path);
    const keys = () => {
      const keys2 = [];
      for (const { scope } of scopes) {
        keys2.push(...Object.keys(scope));
      }
      return keys2;
    };
    return proxy(path, (prop) => {
      for (let i = 0; i < scopes.length; i++) {
        const { scope, path: path2 } = scopes[i];
        if ((0, import_utils2.own)(scope, prop)) {
          return {
            value: scope[prop],
            scope: path2,
            track: this.trackDependency,
            missed: this.trackMissedDependency,
            keys
          };
        }
      }
      return {
        track: this.trackDependency,
        missed: this.trackMissedDependency,
        keys
      };
    });
  }
  /**
   * Получает файлы, которые зависят от изменённых свойств и (опционально) конкретного scopePath
   */
  getAffectedFiles(scopePath, changedProperties) {
    const affectedFiles = /* @__PURE__ */ new Set();
    for (const property of changedProperties) {
      const dependencyKey = `${scopePath}#${property}`;
      if (this.relations.hasNode(dependencyKey)) {
        const dependents = this.relations.dependentsOf(dependencyKey);
        for (const dependent of dependents) {
          affectedFiles.add(dependent);
        }
      }
    }
    return affectedFiles;
  }
  getSpecifiedFiles(pathA, addedProps, removedProps) {
    const { varsPreset } = this.config;
    const props = [];
    const specified = /* @__PURE__ */ new Set();
    const nodes = this.relations.overallOrder().filter((node) => node.indexOf("#") > -1);
    for (const scopedPropA of addedProps) {
      const [scopeA, propA] = splitProp(scopedPropA);
      props.push(
        ...nodes.filter((node) => {
          const [pathB, scopedPropB] = node.split("#");
          const [scopeB, propB] = splitProp(scopedPropB);
          return propA === propB && isMoreSpecific(pathA, pathB, scopeA, scopeB);
        })
      );
    }
    for (const scopedPropA of removedProps) {
      const [scopeA, propA] = splitProp(scopedPropA);
      props.push(
        ...nodes.filter((pathProp) => {
          const [pathB, scopedPropB] = pathProp.split("#");
          const [scopeB, propB] = splitProp(scopedPropB);
          return propA === propB && !isMoreSpecific(pathA, pathB, scopeA, scopeB);
        })
      );
    }
    for (const prop of props) {
      this.relations.dependantsOf(prop).filter((path) => path !== pathA).filter((path) => canBeUsedByPath(pathA, path)).forEach((path) => specified.add(path));
    }
    return specified;
    function splitProp(scopedProp) {
      const dot = scopedProp.indexOf(".");
      if (dot > -1) {
        return [scopedProp.slice(0, dot), scopedProp.slice(dot)];
      }
      return [scopedProp, ""];
    }
    function canBeUsedByPath(preset, path) {
      const presetParts = (0, import_node_path.dirname)(preset).split("/");
      const pathParts = (0, import_node_path.dirname)(path).split("/");
      while (presetParts.length) {
        if (presetParts[0] !== pathParts[0]) {
          break;
        }
        presetParts.shift();
        pathParts.shift();
      }
      return !presetParts.length;
    }
    function isMoreSpecific(pathA2, pathB, scopeA, scopeB) {
      if (pathB === "config") {
        return false;
      }
      if (pathB === "missed") {
        return true;
      }
      if (pathA2.length === pathB.length) {
        return scopeA !== scopeB && scopeA === varsPreset;
      }
      return pathA2.length > pathB.length;
    }
  }
  dump(presets) {
    return (0, import_js_yaml.dump)(presets, {
      lineWidth: 120
    });
  }
  async load(path) {
    const file = (0, import_utils2.normalizePath)(path);
    this.logger.proc(file);
    this.relations.addNode(file);
    const source = (0, import_utils2.normalizePath)((0, import_node_path.join)(this.run.input, file));
    const data = await getHooks(this).PresetsLoaded.promise(
      (0, import_js_yaml.load)(await this.run.read(source) || "{}"),
      file
    );
    this.relations.setNodeData(file, { type: "preset" });
    this.presets[file] = data;
    return data;
  }
  scopes(path) {
    const paths = this.paths(path);
    const config = { scope: this.config.vars, path: "config" };
    return [config].concat(
      paths.map((path2) => {
        const [preset, scope] = path2.split("#");
        return {
          scope: this.get(preset)[scope],
          path: path2
        };
      })
    );
  }
  paths(path) {
    const varsPreset = this.config.varsPreset || "default";
    const paths = [];
    const dirs = [(0, import_utils2.normalizePath)(path)];
    while (dirs.length) {
      const dir = dirs.pop();
      const path2 = (0, import_utils2.normalizePath)((0, import_node_path.join)(dir, "presets.yaml"));
      const preset = this.get(path2);
      if (preset) {
        const defaults = preset["default"];
        const overrides = preset[varsPreset];
        if (overrides && !(0, import_lodash2.isEmpty)(overrides)) {
          paths.push(`${path2}#${varsPreset}`);
        }
        if (varsPreset !== "default" && defaults && !(0, import_lodash2.isEmpty)(defaults)) {
          paths.push(`${path2}#default`);
        }
      }
      const next = (0, import_utils2.normalizePath)((0, import_node_path.dirname)(dir));
      if (dir !== next) {
        dirs.push(next);
      }
    }
    return paths;
  }
  trackDependency(path, scopePath, propertyPath) {
    if (!this.storeDeps) {
      return;
    }
    if (typeof propertyPath !== "string") {
      return;
    }
    let dependencyKey;
    const file = (0, import_utils2.normalizePath)(path);
    this.relations.addNode(file);
    if (["config", "missed"].includes(scopePath)) {
      dependencyKey = `${scopePath}#${propertyPath}`;
    } else {
      const [preset, scope] = scopePath.split("#");
      dependencyKey = `${preset}#${scope}.${propertyPath}`;
      this.relations.addNode(preset);
      this.relations.addDependency(preset, file);
    }
    if (!this.relations.hasNode(dependencyKey)) {
      this.relations.addNode(dependencyKey);
    }
    this.relations.addDependency(file, dependencyKey);
  }
  trackMissedDependency(path, propertyPath) {
    if (!this.storeDeps) {
      return;
    }
    if (typeof propertyPath !== "string") {
      return;
    }
    const dependencyKeys = [
      `missed#default.${propertyPath}`,
      `missed#${this.config.varsPreset}.${propertyPath}`
    ];
    const file = (0, import_utils2.normalizePath)(path);
    this.relations.addNode(file);
    for (const key of dependencyKeys) {
      if (!this.relations.hasNode(key)) {
        this.relations.addNode(key);
      }
      this.relations.addDependency(file, key);
    }
  }
};
_init = __decoratorStart(null);
__decorateElement(_init, 1, "load", _load_dec, VarsService);
__decorateElement(_init, 1, "trackDependency", _trackDependency_dec, VarsService);
__decorateElement(_init, 1, "trackMissedDependency", _trackMissedDependency_dec, VarsService);
VarsService = __decorateElement(_init, 0, "VarsService", _VarsService_decorators, VarsService);
__runInitializers(_init, 1, VarsService);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  VarsService,
  getHooks
});
//# sourceMappingURL=index.js.map
