/**
 * 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 created_keys_exports = {};
__export(created_keys_exports, {
  assertNoDuplicateFlowSurfaceCreatedKeys: () => assertNoDuplicateFlowSurfaceCreatedKeys,
  collectFlowSurfaceCreatedKeys: () => collectFlowSurfaceCreatedKeys,
  collectPersistableFlowSurfaceCreatedKeys: () => collectPersistableFlowSurfaceCreatedKeys,
  isFlowSurfacePureKeyObject: () => isFlowSurfacePureKeyObject,
  normalizeComposeInlineKeysForPlan: () => normalizeComposeInlineKeysForPlan,
  normalizeFlowSurfaceCreatedKey: () => normalizeFlowSurfaceCreatedKey,
  registerFlowSurfaceCreatedKeys: () => registerFlowSurfaceCreatedKeys
});
module.exports = __toCommonJS(created_keys_exports);
var import_lodash = __toESM(require("lodash"));
var import_errors = require("../errors");
var import_key_registry = require("./key-registry");
function normalizeFlowSurfaceCreatedKey(key, context) {
  const normalized = typeof key === "string" ? key.trim() : String(key || "").trim();
  if (!normalized) {
    (0, import_errors.throwBadRequest)(`${context} key cannot be empty`);
  }
  if (import_key_registry.FLOW_SURFACE_RESERVED_KEYS.has(normalized)) {
    (0, import_errors.throwBadRequest)(`${context} key '${normalized}' is reserved`);
  }
  return normalized;
}
function collectFlowSurfaceCreatedKeys(action, values, options = {}) {
  if (!import_lodash.default.isPlainObject(values)) {
    return [];
  }
  switch (action) {
    case "createPage":
      return collectBaseKey(values.key, `flowSurfaces ${action}`, [
        ["", "pageUid"],
        ["tab", "tabSchemaUid"],
        ["grid", "gridUid"]
      ]);
    case "addTab":
      return collectBaseKey(values.key, `flowSurfaces ${action}`, [
        ["", "tabSchemaUid"],
        ["grid", "gridUid"]
      ]);
    case "addPopupTab":
      return collectBaseKey(values.key, `flowSurfaces ${action}`, [
        ["", "popupTabUid"],
        ["grid", "popupGridUid"]
      ]);
    case "addBlock":
      return collectBaseKey(values.key, `flowSurfaces ${action}`, [
        ["", "uid"],
        ["grid", "blockGridUid"],
        ["item", "itemUid"],
        ["itemGrid", "itemGridUid"],
        ["actionsColumn", "actionsColumnUid"]
      ]);
    case "addField":
      return [
        ...collectBaseKey(values.key, `flowSurfaces ${action}`, [
          ["", "uid"],
          ["field", "fieldUid"],
          ["innerField", "innerFieldUid"]
        ]),
        ...shouldCollectAddFieldPopupKeys(values) ? collectDerivedKey(values.key, `flowSurfaces ${action}`, [
          ["popupPage", "popupPageUid"],
          ["popupTab", "popupTabUid"],
          ["popupGrid", "popupGridUid"]
        ]) : []
      ];
    case "addAction":
    case "addRecordAction":
      return collectBaseKey(values.key, `flowSurfaces ${action}`, [
        ["", "uid"],
        ["assignForm", "assignFormUid"],
        ["assignFormGrid", "assignFormGridUid"],
        ["popupPage", "popupPageUid"],
        ["popupTab", "popupTabUid"],
        ["popupGrid", "popupGridUid"]
      ]);
    case "configure":
      return collectConfigureCreatedKeys(values, options);
    case "compose":
      return collectComposeCreatedKeys(values);
    default:
      return [];
  }
}
function collectBaseKey(keyValue, context, defs) {
  if (import_lodash.default.isUndefined(keyValue)) {
    return [];
  }
  const baseKey = normalizeFlowSurfaceCreatedKey(keyValue, context);
  return defs.map(([suffix, resultPath]) => ({
    key: suffix ? `${baseKey}.${suffix}` : baseKey,
    resultPath
  }));
}
function collectDerivedKey(keyValue, context, defs) {
  if (import_lodash.default.isUndefined(keyValue)) {
    return [];
  }
  const baseKey = normalizeFlowSurfaceCreatedKey(keyValue, context);
  return defs.map(([suffix, resultPath]) => ({
    key: `${baseKey}.${suffix}`,
    resultPath
  }));
}
function shouldCollectAddFieldPopupKeys(values) {
  return !import_lodash.default.isUndefined(values == null ? void 0 : values.popup);
}
function inferConfigureCreatedKeyBase(targetSelectorKey) {
  if (import_lodash.default.isUndefined(targetSelectorKey)) {
    return void 0;
  }
  const normalizedKey = normalizeFlowSurfaceCreatedKey(targetSelectorKey, "flowSurfaces configure target key");
  if (normalizedKey.endsWith(".innerField")) {
    return normalizedKey.slice(0, -".innerField".length);
  }
  if (normalizedKey.endsWith(".field")) {
    return normalizedKey.slice(0, -".field".length);
  }
  return void 0;
}
function collectConfigureCreatedKeys(values, options = {}) {
  var _a;
  if (!import_lodash.default.isPlainObject((_a = values == null ? void 0 : values.changes) == null ? void 0 : _a.openView)) {
    return [];
  }
  const keyBase = !import_lodash.default.isUndefined(values.key) ? values.key : inferConfigureCreatedKeyBase(options.targetSelectorKey);
  if (import_lodash.default.isUndefined(keyBase)) {
    return [];
  }
  return collectDerivedKey(keyBase, "flowSurfaces configure", [
    ["popupPage", "popupPageUid"],
    ["popupTab", "popupTabUid"],
    ["popupGrid", "popupGridUid"]
  ]);
}
function collectComposeCreatedKeys(values) {
  const blocks = import_lodash.default.castArray((values == null ? void 0 : values.blocks) || []);
  const specs = [];
  blocks.forEach((block, blockIndex) => {
    const blockContext = `flowSurfaces compose block #${blockIndex + 1}`;
    if (import_lodash.default.isPlainObject(block) && !import_lodash.default.isUndefined(block.key)) {
      specs.push(
        ...collectBaseKey(block.key, blockContext, [
          ["", `blocks.${blockIndex}.uid`],
          ["grid", `blocks.${blockIndex}.gridUid`],
          ["item", `blocks.${blockIndex}.itemUid`],
          ["itemGrid", `blocks.${blockIndex}.itemGridUid`],
          ["actionsColumn", `blocks.${blockIndex}.actionsColumnUid`]
        ])
      );
    }
    import_lodash.default.castArray((block == null ? void 0 : block.fields) || []).forEach((field, fieldIndex) => {
      const fieldKey = resolveComposeFieldKey(field, `${blockContext} field #${fieldIndex + 1}`);
      if (!fieldKey) {
        return;
      }
      specs.push(
        ...collectBaseKey(fieldKey, `${blockContext} field #${fieldIndex + 1}`, [
          ["", `blocks.${blockIndex}.fields.${fieldIndex}.uid`],
          ["field", `blocks.${blockIndex}.fields.${fieldIndex}.fieldUid`],
          ["innerField", `blocks.${blockIndex}.fields.${fieldIndex}.innerFieldUid`],
          ["popupPage", `blocks.${blockIndex}.fields.${fieldIndex}.popupPageUid`],
          ["popupTab", `blocks.${blockIndex}.fields.${fieldIndex}.popupTabUid`],
          ["popupGrid", `blocks.${blockIndex}.fields.${fieldIndex}.popupGridUid`]
        ])
      );
    });
    import_lodash.default.castArray((block == null ? void 0 : block.actions) || []).forEach((action, actionIndex) => {
      const actionKey = resolveComposeActionKey(action, `${blockContext} action #${actionIndex + 1}`);
      if (!actionKey) {
        return;
      }
      specs.push(
        ...collectBaseKey(actionKey, `${blockContext} action #${actionIndex + 1}`, [
          ["", `blocks.${blockIndex}.actions.${actionIndex}.uid`],
          ["assignForm", `blocks.${blockIndex}.actions.${actionIndex}.assignFormUid`],
          ["assignFormGrid", `blocks.${blockIndex}.actions.${actionIndex}.assignFormGridUid`],
          ["popupPage", `blocks.${blockIndex}.actions.${actionIndex}.popupPageUid`],
          ["popupTab", `blocks.${blockIndex}.actions.${actionIndex}.popupTabUid`],
          ["popupGrid", `blocks.${blockIndex}.actions.${actionIndex}.popupGridUid`]
        ])
      );
    });
    import_lodash.default.castArray((block == null ? void 0 : block.recordActions) || []).forEach((action, actionIndex) => {
      const actionKey = resolveComposeActionKey(action, `${blockContext} recordAction #${actionIndex + 1}`);
      if (!actionKey) {
        return;
      }
      specs.push(
        ...collectBaseKey(actionKey, `${blockContext} recordAction #${actionIndex + 1}`, [
          ["", `blocks.${blockIndex}.recordActions.${actionIndex}.uid`],
          ["assignForm", `blocks.${blockIndex}.recordActions.${actionIndex}.assignFormUid`],
          ["assignFormGrid", `blocks.${blockIndex}.recordActions.${actionIndex}.assignFormGridUid`],
          ["popupPage", `blocks.${blockIndex}.recordActions.${actionIndex}.popupPageUid`],
          ["popupTab", `blocks.${blockIndex}.recordActions.${actionIndex}.popupTabUid`],
          ["popupGrid", `blocks.${blockIndex}.recordActions.${actionIndex}.popupGridUid`]
        ])
      );
    });
  });
  return specs;
}
function resolveComposeFieldKey(field, context) {
  if (typeof field === "string") {
    return normalizeFlowSurfaceCreatedKey(field, context);
  }
  if (!import_lodash.default.isPlainObject(field)) {
    return void 0;
  }
  const semanticType = String(field.type || "").trim();
  const fieldPath = String(field.fieldPath || "").trim();
  const renderer = typeof field.renderer === "undefined" ? void 0 : String(field.renderer || "").trim();
  const rawKey = String(field.key || semanticType || (renderer === "js" ? `js:${fieldPath}` : fieldPath)).trim();
  return rawKey ? normalizeFlowSurfaceCreatedKey(rawKey, context) : void 0;
}
function resolveComposeActionKey(action, context) {
  if (typeof action === "string") {
    return normalizeFlowSurfaceCreatedKey(action, context);
  }
  if (!import_lodash.default.isPlainObject(action)) {
    return void 0;
  }
  const rawKey = String(action.key || action.type || "").trim();
  return rawKey ? normalizeFlowSurfaceCreatedKey(rawKey, context) : void 0;
}
function assertNoDuplicateFlowSurfaceCreatedKeys(specs, context, options = {}) {
  const seen = /* @__PURE__ */ new Map();
  const existing = new Set(options.existingKeys || []);
  const reservedNames = new Set(options.reservedNames || []);
  specs.forEach((spec, index) => {
    if (reservedNames.has(spec.key)) {
      (0, import_errors.throwBadRequest)(`${context} key '${spec.key}' conflicts with an existing step id`);
    }
    if (existing.has(spec.key)) {
      (0, import_errors.throwBadRequest)(`${context} key '${spec.key}' is already defined`);
    }
    const previousIndex = seen.get(spec.key);
    if (typeof previousIndex === "number") {
      (0, import_errors.throwBadRequest)(`${context} key '${spec.key}' is duplicated at #${previousIndex + 1} and #${index + 1}`);
    }
    seen.set(spec.key, index);
  });
}
function registerFlowSurfaceCreatedKeys(result, specs, keys) {
  const registered = resolveFlowSurfaceCreatedKeyResults(result, specs);
  registered.forEach((item) => keys.set(item.key, item.uid));
  return registered;
}
function collectPersistableFlowSurfaceCreatedKeys(result, specs) {
  const persistedUidSet = /* @__PURE__ */ new Set();
  const persisted = [];
  for (const item of resolveFlowSurfaceCreatedKeyResults(result, specs)) {
    if (persistedUidSet.has(item.uid)) {
      continue;
    }
    persistedUidSet.add(item.uid);
    persisted.push(item);
  }
  return persisted;
}
function resolveFlowSurfaceCreatedKeyResults(result, specs) {
  const registered = [];
  for (const spec of specs) {
    const value = import_lodash.default.get(result, spec.resultPath);
    if (typeof value !== "string" || !value.trim()) {
      continue;
    }
    registered.push({
      key: spec.key,
      uid: value.trim()
    });
  }
  return registered;
}
function isFlowSurfacePureKeyObject(input) {
  return import_lodash.default.isPlainObject(input) && Object.keys(input).length === 1 && typeof input.key === "string" && !!input.key.trim();
}
function normalizeComposeInlineKeysForPlan(values, contextPath) {
  var _a;
  if (!import_lodash.default.isPlainObject(values)) {
    return values;
  }
  const cloned = import_lodash.default.cloneDeep(values);
  const blockKeys = new Set(
    import_lodash.default.castArray(cloned.blocks || []).map((block, index) => {
      if (!import_lodash.default.isPlainObject(block) || import_lodash.default.isUndefined(block.key)) {
        return "";
      }
      return normalizeFlowSurfaceCreatedKey(block.key, `${contextPath}.blocks[${index}]`);
    }).filter(Boolean)
  );
  import_lodash.default.castArray(cloned.blocks || []).forEach((block, blockIndex) => {
    import_lodash.default.castArray((block == null ? void 0 : block.fields) || []).forEach((field, fieldIndex) => {
      if (typeof (field == null ? void 0 : field.target) !== "string" || !field.target.trim()) {
        return;
      }
      const targetKey = normalizeFlowSurfaceCreatedKey(
        field.target,
        `${contextPath}.blocks[${blockIndex}].fields[${fieldIndex}].target`
      );
      if (!blockKeys.has(targetKey)) {
        return;
      }
      field.target = targetKey;
    });
  });
  import_lodash.default.castArray(((_a = cloned.layout) == null ? void 0 : _a.rows) || []).forEach((row, rowIndex) => {
    if (!Array.isArray(row)) {
      return;
    }
    row.forEach((cell, cellIndex) => {
      if (typeof cell === "string") {
        return;
      }
      if (!import_lodash.default.isPlainObject(cell) || typeof cell.key !== "string" || !cell.key.trim()) {
        return;
      }
      const key = normalizeFlowSurfaceCreatedKey(cell.key, `${contextPath}.layout.rows[${rowIndex}][${cellIndex}]`);
      if (!blockKeys.has(key)) {
        (0, import_errors.throwBadRequest)(
          `flowSurfaces compose local layout key '${key}' must match a block key in the same compose step`
        );
      }
      delete cell.key;
      cell.composeKey = key;
    });
  });
  return cloned;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  assertNoDuplicateFlowSurfaceCreatedKeys,
  collectFlowSurfaceCreatedKeys,
  collectPersistableFlowSurfaceCreatedKeys,
  isFlowSurfacePureKeyObject,
  normalizeComposeInlineKeysForPlan,
  normalizeFlowSurfaceCreatedKey,
  registerFlowSurfaceCreatedKeys
});
