/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

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 __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var key_registry_exports = {};
__export(key_registry_exports, {
  FLOW_SURFACE_DECLARED_KEY_KEY: () => FLOW_SURFACE_DECLARED_KEY_KEY,
  FLOW_SURFACE_INTERNAL_META_KEY: () => FLOW_SURFACE_INTERNAL_META_KEY,
  FLOW_SURFACE_KEY_NOT_PERSISTABLE_CODE: () => FLOW_SURFACE_KEY_NOT_PERSISTABLE_CODE,
  FLOW_SURFACE_RESERVED_KEYS: () => FLOW_SURFACE_RESERVED_KEYS,
  FLOW_SURFACE_SYSTEM_KEY: () => FLOW_SURFACE_SYSTEM_KEY,
  annotateTreeKey: () => annotateTreeKey,
  buildSurfaceFingerprintKeysObject: () => buildSurfaceFingerprintKeysObject,
  buildSurfaceKeysObject: () => buildSurfaceKeysObject,
  collectDeclaredKeysFromTree: () => collectDeclaredKeysFromTree,
  collectRequestKeysToPersist: () => collectRequestKeysToPersist,
  getDeclaredKeyFromNode: () => getDeclaredKeyFromNode,
  getSurfaceSelectorRequestKey: () => getSurfaceSelectorRequestKey,
  normalizeBindKeys: () => normalizeBindKeys
});
module.exports = __toCommonJS(key_registry_exports);
var import_lodash = __toESM(require("lodash"));
var import_errors = require("../errors");
var import_service_utils = require("../service-utils");
const FLOW_SURFACE_SYSTEM_KEY = "surface";
const FLOW_SURFACE_RESERVED_KEYS = /* @__PURE__ */ new Set([FLOW_SURFACE_SYSTEM_KEY]);
const FLOW_SURFACE_INTERNAL_META_KEY = "__flowSurfaceMeta";
const FLOW_SURFACE_DECLARED_KEY_KEY = "declaredKey";
const FLOW_SURFACE_KEY_NOT_PERSISTABLE_CODE = "FLOW_SURFACE_KEY_NOT_PERSISTABLE";
function getDeclaredKeyFromNode(node) {
  const declaredKey = import_lodash.default.get(node, ["stepParams", FLOW_SURFACE_INTERNAL_META_KEY, FLOW_SURFACE_DECLARED_KEY_KEY]);
  return typeof declaredKey === "string" && declaredKey.trim() ? declaredKey.trim() : void 0;
}
function normalizeBindKeys(actionName, bindKeys, deps) {
  if (import_lodash.default.isUndefined(bindKeys)) {
    return [];
  }
  if (!Array.isArray(bindKeys)) {
    (0, import_errors.throwBadRequest)(`flowSurfaces ${actionName} bindKeys must be an array`);
  }
  const seenKeys = /* @__PURE__ */ new Set();
  return bindKeys.map((item, index) => {
    if (!import_lodash.default.isPlainObject(item)) {
      (0, import_errors.throwBadRequest)(`flowSurfaces ${actionName} bindKeys[${index}] must be an object`);
    }
    const key = String(item.key || "").trim();
    if (!key) {
      (0, import_errors.throwBadRequest)(`flowSurfaces ${actionName} bindKeys[${index}].key is required`);
    }
    if (FLOW_SURFACE_RESERVED_KEYS.has(key)) {
      (0, import_errors.throwBadRequest)(`flowSurfaces ${actionName} bindKeys[${index}].key '${key}' is reserved`);
    }
    if (seenKeys.has(key)) {
      (0, import_errors.throwBadRequest)(`flowSurfaces ${actionName} bindKeys[${index}].key '${key}' is duplicated`);
    }
    seenKeys.add(key);
    if (!import_lodash.default.isPlainObject(item.locator)) {
      (0, import_errors.throwBadRequest)(`flowSurfaces ${actionName} bindKeys[${index}].locator is required`);
    }
    return (0, import_service_utils.buildDefinedPayload)({
      key,
      locator: deps.normalizeGetTarget(item.locator),
      expectedKind: typeof item.expectedKind === "string" ? String(item.expectedKind).trim() : void 0,
      rebind: item.rebind === true
    });
  });
}
function collectDeclaredKeysFromTree(node, deps, carry = /* @__PURE__ */ new Map()) {
  if (!node || typeof node !== "object") {
    return carry;
  }
  if (node.uid) {
    const declaredKey = getDeclaredKeyFromNode(node);
    if (declaredKey && !FLOW_SURFACE_RESERVED_KEYS.has(declaredKey)) {
      const existing = carry.get(declaredKey);
      if (existing && existing.uid !== node.uid) {
        (0, import_errors.throwConflict)(
          `flowSurfaces ${deps.actionName || "describeSurface"} declared key '${declaredKey}' is duplicated on '${existing.uid}' and '${node.uid}'`,
          "FLOW_SURFACE_DECLARED_KEY_CONFLICT"
        );
      }
      carry.set(declaredKey, {
        key: declaredKey,
        uid: node.uid,
        source: "declared",
        kind: deps.buildPlanKeyKind(node),
        locator: {
          uid: node.uid
        }
      });
    }
  }
  for (const value of Object.values(node.subModels || {})) {
    import_lodash.default.castArray(value).forEach((child) => collectDeclaredKeysFromTree(child, deps, carry));
  }
  return carry;
}
function annotateTreeKey(tree, keyByUid) {
  const visit = (current) => {
    if (!current || typeof current !== "object") {
      return;
    }
    const currentKey = current.uid ? keyByUid.get(current.uid) : void 0;
    if (currentKey && typeof current.key === "undefined") {
      current.key = currentKey;
    }
    for (const value of Object.values(current.subModels || {})) {
      import_lodash.default.castArray(value).forEach((child) => visit(child));
    }
  };
  visit(tree);
  return tree;
}
function buildSurfaceKeysObject(keyMap) {
  return Object.fromEntries(
    Array.from(keyMap.entries()).map(([key, info]) => [
      key,
      {
        uid: info.uid,
        kind: info.kind,
        source: info.source,
        locator: info.locator
      }
    ])
  );
}
function buildSurfaceFingerprintKeysObject(keyMap) {
  return Object.fromEntries(
    Array.from(keyMap.entries()).map(([key, info]) => [
      key,
      {
        uid: info.uid,
        kind: info.kind
      }
    ])
  );
}
function getSurfaceSelectorRequestKey(context) {
  if (!context.surfaceSelector || !("key" in context.surfaceSelector)) {
    return void 0;
  }
  return context.requestKeyMap.get(context.surfaceSelector.key);
}
function collectRequestKeysToPersist(context, compiledSteps) {
  const keys = /* @__PURE__ */ new Map();
  const surfaceRequestKey = getSurfaceSelectorRequestKey(context);
  if (surfaceRequestKey) {
    keys.set(surfaceRequestKey.key, surfaceRequestKey);
  }
  for (const compiled of compiledSteps) {
    for (const keyInfo of compiled.usedKeys) {
      if (keyInfo.source === "request") {
        keys.set(keyInfo.key, keyInfo);
      }
    }
  }
  return keys;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  FLOW_SURFACE_DECLARED_KEY_KEY,
  FLOW_SURFACE_INTERNAL_META_KEY,
  FLOW_SURFACE_KEY_NOT_PERSISTABLE_CODE,
  FLOW_SURFACE_RESERVED_KEYS,
  FLOW_SURFACE_SYSTEM_KEY,
  annotateTreeKey,
  buildSurfaceFingerprintKeysObject,
  buildSurfaceKeysObject,
  collectDeclaredKeysFromTree,
  collectRequestKeysToPersist,
  getDeclaredKeyFromNode,
  getSurfaceSelectorRequestKey,
  normalizeBindKeys
});
