/**
 * 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 runtime_exports = {};
__export(runtime_exports, {
  describeSurface: () => describeSurface,
  executeInternalPlan: () => executeInternalPlan
});
module.exports = __toCommonJS(runtime_exports);
var import_lodash = __toESM(require("lodash"));
var import_errors = require("../errors");
var import_executor = require("../executor");
var import_action_specs = require("./action-specs");
var import_context = require("./context");
var import_compiler = require("./compiler");
var import_key_kind = require("./key-kind");
var import_key_registry = require("./key-registry");
var import_created_keys = require("./created-keys");
var import_payload_shape = require("../payload-shape");
async function buildPlanSurfaceContext(surfaceSelectorInput, bindKeysInput, actionName, deps, options = {}) {
  const bindKeys = (0, import_key_registry.normalizeBindKeys)(actionName, bindKeysInput, {
    normalizeGetTarget: deps.normalizeGetTarget
  });
  if (import_lodash.default.isUndefined(surfaceSelectorInput) || import_lodash.default.isNil(surfaceSelectorInput)) {
    return (0, import_context.buildPlanSurfaceContext)(
      {
        actionName,
        bindKeys
      },
      {
        resolveLocator: deps.resolveLocator,
        loadResolvedSurfaceTree: deps.loadResolvedSurfaceTree,
        stripInternalSurfaceMetaFromNodeTree: deps.stripInternalSurfaceMetaFromNodeTree,
        buildReadTargetSummary: deps.buildReadTargetSummary,
        buildSurfaceContextFingerprint: deps.buildSurfaceContextFingerprint,
        buildPlanKeyKind: import_key_kind.buildPlanKeyKind,
        assertBindKeyKind: import_key_kind.assertBindKeyKind,
        collectDeclaredKeysFromTree: (node) => (0, import_key_registry.collectDeclaredKeysFromTree)(
          node,
          {
            actionName,
            buildPlanKeyKind: import_key_kind.buildPlanKeyKind
          },
          /* @__PURE__ */ new Map()
        )
      },
      options
    );
  }
  const normalizedSurfaceSelector = (0, import_compiler.normalizePlanSelector)(
    actionName,
    surfaceSelectorInput,
    {
      normalizeGetTarget: deps.normalizeGetTarget
    },
    "surface",
    {
      allowKey: true
    }
  );
  if ("step" in normalizedSurfaceSelector) {
    (0, import_errors.throwBadRequest)(`flowSurfaces ${actionName} surface only supports { key } or { locator }`);
  }
  return (0, import_context.buildPlanSurfaceContext)(
    {
      actionName,
      surfaceSelector: normalizedSurfaceSelector,
      bindKeys
    },
    {
      resolveLocator: deps.resolveLocator,
      loadResolvedSurfaceTree: deps.loadResolvedSurfaceTree,
      stripInternalSurfaceMetaFromNodeTree: deps.stripInternalSurfaceMetaFromNodeTree,
      buildReadTargetSummary: deps.buildReadTargetSummary,
      buildSurfaceContextFingerprint: deps.buildSurfaceContextFingerprint,
      buildPlanKeyKind: import_key_kind.buildPlanKeyKind,
      assertBindKeyKind: import_key_kind.assertBindKeyKind,
      collectDeclaredKeysFromTree: (node) => (0, import_key_registry.collectDeclaredKeysFromTree)(
        node,
        {
          actionName,
          buildPlanKeyKind: import_key_kind.buildPlanKeyKind
        },
        /* @__PURE__ */ new Map()
      )
    },
    options
  );
}
async function buildDescribeSurfaceResponse(context, deps, options = {}) {
  if (!context.surfaceTarget || !context.surfaceResolved) {
    (0, import_errors.throwBadRequest)(`flowSurfaces describeSurface requires locator`);
  }
  const tree = import_lodash.default.cloneDeep(context.publicTree);
  const keyByUid = /* @__PURE__ */ new Map();
  context.keyMap.forEach((value, key) => {
    if (!keyByUid.has(value.uid)) {
      keyByUid.set(value.uid, key);
    }
  });
  (0, import_key_registry.annotateTreeKey)(tree, keyByUid);
  const result = await deps.buildSurfaceReadPayload(context.surfaceTarget, context.surfaceResolved, tree, options);
  result.fingerprint = context.fingerprint;
  result.keys = (0, import_key_registry.buildSurfaceKeysObject)(context.keyMap);
  return result;
}
function normalizePlanSteps(actionName, values, deps) {
  return (0, import_compiler.normalizePlanSteps)(actionName, values, {
    normalizeGetTarget: deps.normalizeGetTarget,
    validatePayloadShape: import_payload_shape.validateFlowSurfacePayloadShape
  });
}
async function compilePlanStep(actionName, step, index, context, deps, priorStepIds, priorCreatedKeys, options = {}) {
  return (0, import_compiler.compilePlanStep)(
    actionName,
    step,
    index,
    context,
    {
      normalizeGetTarget: deps.normalizeGetTarget,
      resolveLocator: deps.resolveLocator,
      loadResolvedSurfaceTree: deps.loadResolvedSurfaceTree,
      buildPlanKeyKind: import_key_kind.buildPlanKeyKind
    },
    priorStepIds,
    priorCreatedKeys,
    options
  );
}
async function executeCompiledPlanStep(compiled, deps, execCtx, transaction) {
  var _a;
  if (compiled.mutateOp) {
    const mutateResults = await (0, import_executor.executeMutateOps)(
      [compiled.mutateOp],
      execCtx,
      async (op, resolvedValues, currentCtx) => deps.dispatchOp(op, resolvedValues, currentCtx)
    );
    return (_a = mutateResults[0]) == null ? void 0 : _a.result;
  }
  if (!(0, import_action_specs.isFlowSurfacePlanOnlyAction)(compiled.action)) {
    (0, import_errors.throwInternalError)(`flowSurfaces internal plan action '${compiled.action}' is not supported`);
  }
  const result = await deps.dispatchPlanOnlyAction(
    compiled.action,
    (0, import_executor.resolveFlowSurfaceValueKeys)(import_lodash.default.cloneDeep(compiled.payload), execCtx.keys),
    transaction
  );
  if (compiled.id) {
    execCtx.keys.set(compiled.id, result);
  }
  return result;
}
function assertBootstrapPlanConstraints(actionName, compiledSteps) {
  for (const compiled of compiledSteps) {
    for (const selector of Object.values(compiled.resolvedSelectors)) {
      if (!selector) {
        continue;
      }
      if (selector.source !== "step" && selector.source !== "created") {
        (0, import_errors.throwBadRequest)(`flowSurfaces ${actionName} bootstrap plan only supports step or created-key selectors`);
      }
    }
  }
}
async function describeSurface(values, deps, options = {}) {
  if (!import_lodash.default.isPlainObject(values) || !import_lodash.default.isPlainObject(values.locator)) {
    (0, import_errors.throwBadRequest)(`flowSurfaces describeSurface requires locator`);
  }
  const locator = deps.normalizeGetTarget(values.locator);
  const context = await buildPlanSurfaceContext({ locator }, values.bindKeys, "describeSurface", deps, options);
  return buildDescribeSurfaceResponse(context, deps, options);
}
async function executeInternalPlan(values, deps, options = {}) {
  if (!import_lodash.default.isPlainObject(values)) {
    (0, import_errors.throwBadRequest)(`flowSurfaces applyBlueprint requires plan`);
  }
  const context = await buildPlanSurfaceContext(values.surface, void 0, "applyBlueprint", deps, options);
  const steps = normalizePlanSteps("applyBlueprint", values, deps);
  const compiledSteps = [];
  const priorStepIds = /* @__PURE__ */ new Set();
  const priorCreatedKeys = /* @__PURE__ */ new Set();
  for (const [index, step] of steps.entries()) {
    const compiled = await compilePlanStep(
      "applyBlueprint",
      step,
      index,
      context,
      deps,
      priorStepIds,
      priorCreatedKeys,
      options
    );
    compiledSteps.push(compiled);
    if (step.id) {
      priorStepIds.add(step.id);
    }
    for (const createdKey of compiled.createdKeys) {
      priorCreatedKeys.add(createdKey.key);
    }
  }
  if (!context.surfaceSelector) {
    assertBootstrapPlanConstraints("applyBlueprint", compiledSteps);
  }
  const results = [];
  const execCtx = {
    transaction: options.transaction,
    keys: new Map(Array.from(context.keyMap.entries()).map(([key, info]) => [key, info.uid])),
    clientKeyToUid: {}
  };
  for (const compiled of compiledSteps) {
    const result = await executeCompiledPlanStep(compiled, deps, execCtx, options.transaction);
    const createdKeys = (0, import_created_keys.registerFlowSurfaceCreatedKeys)(result, compiled.createdKeys, execCtx.keys);
    results.push({
      index: compiled.index,
      ...compiled.id ? { id: compiled.id } : {},
      action: compiled.action,
      result,
      ...createdKeys.length ? { createdKeys } : {}
    });
  }
  return { results };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  describeSurface,
  executeInternalPlan
});
