{"version":3,"file":"FlowBuilderCore.cjs","names":["toBindValue","familySize","instancePortName","ref"],"sources":["../../src/authoring/FlowBuilderCore.ts"],"sourcesContent":["import {\n  type AppliedGuard,\n  type BindValue,\n  type Call,\n  familySize,\n  type Flow,\n  type FlowInput,\n  instancePortName,\n  type Ref,\n  type Resource,\n  type SolType,\n} from '@lifi/compose-spec';\n\nimport type {\n  InputDecl,\n  InputSchema,\n  OutputKind,\n  TypedGuard,\n  TypedLiteral,\n  TypedRef,\n} from '../types.js';\n\nimport type {\n  InputHandle,\n  OutputHandle,\n  ResourceInputHandle,\n} from './handles.js';\nimport { toBindValue } from './handles.js';\nimport { ref } from './raw.js';\n\n/**\n * Arguments for calling an operation node in a flow.\n */\nexport interface CallArgs {\n  /** Maps parameter names to input/output handles or raw `$ref` pointers. */\n  readonly bind: Record<string, AnyBindable>;\n  /** Optional operation-specific configuration. */\n  readonly config?: object;\n  /** Optional guards (e.g. slippage checks) applied to this operation's outputs. */\n  readonly guards?: readonly TypedGuard[];\n}\n\n/**\n * Any value that can be bound to an operation parameter: an input handle, an\n * output handle from a previous operation, a typed `$ref` pointer, a typed\n * literal, or a bare `{ $ref }` pointer.\n *\n * This is the bind type of {@link FlowBuilderInternal.call}, the entry point\n * every generated operation lowers into — not a public authoring surface. A\n * bare `Ref` belongs here because a generated op resolves its own typed binds\n * to wire refs (`toBindRef` in `./signatureArgs.js`) before calling it. Typed\n * operation slots use `Bindable<T>`, which rejects a bare `Ref`; see\n * `RefBindable` in `./handles.js`.\n *\n * Use `raw.ref<T>()` to create a typed ref from a raw path string, and\n * `raw.literal<T>()` to bake in a constant.\n */\nexport type AnyBindable =\n  InputHandle | OutputHandle | TypedRef | TypedLiteral | Ref;\n\n/**\n * Provides references to runtime context values available inside a flow.\n * Access via `builder.context`.\n */\nexport interface ContextAccessor {\n  /** A `$ref` pointing to the transaction sender (signer) address. */\n  readonly sender: TypedRef<'address'>;\n  /** A `$ref` pointing to the on-chain execution (proxy) address. */\n  readonly executionAddress: TypedRef<'address'>;\n}\n\ntype InputHandleOf<D extends InputDecl> = D extends Resource\n  ? ResourceInputHandle\n  : D extends SolType\n    ? InputHandle<D>\n    : InputHandle;\n\n/**\n * A mapped type that converts an input schema into typed handles.\n * Resource inputs produce {@link ResourceInputHandle}; scalar inputs produce {@link InputHandle}.\n *\n * @typeParam T - The flow's input schema.\n */\nexport type InputHandles<T extends InputSchema> = {\n  readonly [K in keyof T]: InputHandleOf<T[K]>;\n};\n\n/**\n * Options for creating a new flow builder.\n *\n * @typeParam T - The flow's input schema.\n */\nexport interface FlowOptions<T extends InputSchema> {\n  /** Optional human-readable name for the flow. Defaults to a random UUID. */\n  readonly name?: string;\n  /** Input declarations mapping names to resource or scalar types. */\n  readonly inputs: T;\n}\n\n/**\n * A Flow document branded with its input schema for type-safe request building.\n *\n * The `__inputs` field is a phantom type — it exists only at compile time for\n * TypeScript inference and is never present at runtime.\n */\nexport type TypedFlow<T extends InputSchema = InputSchema> = Flow & {\n  readonly __inputs?: T;\n};\n\n/**\n * Core flow builder interface providing low-level access to flow construction.\n *\n * For most use cases, prefer the {@link FlowBuilder} type returned by `sdk.flow()`\n * which adds generated operation methods and a `compile` method.\n *\n * @typeParam T - The flow's input schema.\n */\nexport interface FlowBuilderCore<T extends InputSchema = InputSchema> {\n  /** Runtime context references (sender address, execution address). */\n  readonly context: ContextAccessor;\n  /** Typed handles for each declared flow input, used to bind inputs to operations. */\n  readonly inputs: InputHandles<T>;\n  /**\n   * Appends an untyped operation node to the flow. This is an escape hatch\n   * for operations not yet covered by the generated methods.\n   *\n   * Use `raw.ref<T>()` to reference this node's outputs in subsequent typed\n   * operations.\n   *\n   * @param id - Unique node identifier within the flow.\n   * @param op - The operation name (e.g. `\"custom.vaultQuery\"`).\n   * @param args - Bind map, config, and optional guards for the node.\n   * @throws Error if a node with the same `id` already exists in the flow.\n   */\n  readonly untypedOp: (\n    id: string,\n    op: string,\n    args: {\n      readonly bind: Record<string, BindValue>;\n      readonly config: Record<string, unknown>;\n      readonly guards?: readonly AppliedGuard[];\n    },\n  ) => void;\n  /** Serialises the builder state into a {@link TypedFlow} document. */\n  readonly build: () => TypedFlow<T>;\n}\n\n/** Maps output port names to their output kind for compile-time and runtime validation. */\nexport type OutputSpec = Record<string, OutputKind>;\n\n/**\n * Maps each output family's port name to the config key that sizes it: an\n * array (one instance per element) or a non-negative integer count.\n * A family port is also listed in the {@link OutputSpec}, as `'resource'`.\n */\nexport type FamilySpec = Readonly<Record<string, string>>;\n\n/** The handles `call` returns for an {@link OutputSpec} and its families. */\nexport type OutputHandles<O extends OutputSpec, F extends FamilySpec> = {\n  readonly [K in keyof O & string]: K extends keyof F\n    ? readonly OutputHandle<'resource'>[]\n    : OutputHandle<O[K]>;\n};\n\n/** Internal interface exposed to bindGeneratedOps — not part of the public API. */\nexport interface FlowBuilderInternal<\n  T extends InputSchema = InputSchema,\n> extends FlowBuilderCore<T> {\n  readonly call: <\n    O extends OutputSpec,\n    F extends FamilySpec = Record<never, string>,\n  >(\n    nodeId: string,\n    op: string,\n    args: CallArgs,\n    outputs: O,\n    families?: F,\n  ) => OutputHandles<O, F>;\n}\n\nconst isResource = (decl: InputDecl): decl is Resource =>\n  typeof decl === 'object' && decl !== null && 'kind' in decl;\n\n/**\n * Creates a new flow builder targeting the given chain.\n *\n * @param chainId - The EVM chain ID (e.g. `1` for Ethereum mainnet).\n * @param options - Flow configuration including input declarations.\n * @returns A {@link FlowBuilderInternal} instance.\n * @internal\n */\nexport const createFlowBuilderCore = <T extends InputSchema>(\n  chainId: number,\n  options: FlowOptions<T>,\n): FlowBuilderInternal<T> => {\n  const id = options.name ?? crypto.randomUUID();\n  const flowInputs: FlowInput[] = [];\n  const nodes: Call[] = [];\n  const nodeIds = new Set<string>();\n\n  const inputHandles = {} as Record<string, InputHandle | ResourceInputHandle>;\n  for (const [name, decl] of Object.entries(options.inputs)) {\n    if (isResource(decl)) {\n      if (decl.chainId !== chainId) {\n        throw new Error(\n          `Input \"${name}\" has chainId ${decl.chainId} but flow targets chain ${chainId}`,\n        );\n      }\n      flowInputs.push({ name, resource: decl });\n      inputHandles[name] = { _tag: 'input', inputName: name, resource: decl };\n    } else {\n      flowInputs.push({ name, type: decl });\n      inputHandles[name] = { _tag: 'input', inputName: name };\n    }\n  }\n\n  const call = <\n    O extends OutputSpec,\n    F extends FamilySpec = Record<never, string>,\n  >(\n    nodeId: string,\n    op: string,\n    args: CallArgs,\n    outputs: O,\n    families?: F,\n  ): OutputHandles<O, F> => {\n    if (nodeIds.has(nodeId)) throw new Error(`Duplicate node id: \"${nodeId}\"`);\n    nodeIds.add(nodeId);\n\n    const bind: Record<string, BindValue> = {};\n    for (const [key, val] of Object.entries(args.bind)) {\n      bind[key] = toBindValue(val);\n    }\n\n    const config = (args.config ?? {}) as Record<string, unknown>;\n    const node: Call = {\n      id: nodeId,\n      op,\n      bind,\n      config,\n      ...(args.guards && args.guards.length > 0 && { guards: args.guards }),\n    };\n    nodes.push(node);\n\n    const outputHandle = (portName: string): OutputHandle => ({\n      _tag: 'output',\n      nodeId,\n      portName,\n    });\n    return new Proxy({} as OutputHandles<O, F>, {\n      get: (\n        _target,\n        prop,\n      ): OutputHandle | readonly OutputHandle[] | undefined => {\n        if (typeof prop !== 'string' || prop === 'then') return undefined;\n        // Own-key only: the trap sees every property a consumer reads, so `in`\n        // would answer a handle for `toString` or `constructor` instead of the\n        // unknown-port error.\n        if (!Object.hasOwn(outputs, prop)) {\n          throw new Error(\n            `Op \"${op}\" has no output port \"${prop}\". Valid ports: ${Object.keys(\n              outputs,\n            ).join(', ')}`,\n          );\n        }\n        const countFrom = families?.[prop];\n        if (countFrom === undefined) return outputHandle(prop);\n        const size = familySize({ name: prop, countFrom }, config);\n        return Array.from({ length: size }, (_, index) =>\n          outputHandle(instancePortName(prop, index)),\n        );\n      },\n    });\n  };\n\n  const untypedOp = (\n    nodeId: string,\n    op: string,\n    args: {\n      readonly bind: Record<string, BindValue>;\n      readonly config: Record<string, unknown>;\n      readonly guards?: readonly AppliedGuard[];\n    },\n  ): void => {\n    if (nodeIds.has(nodeId)) throw new Error(`Duplicate node id: \"${nodeId}\"`);\n    nodeIds.add(nodeId);\n    const node: Call = {\n      id: nodeId,\n      op,\n      bind: args.bind,\n      config: args.config,\n      ...(args.guards && args.guards.length > 0 && { guards: args.guards }),\n    };\n    nodes.push(node);\n  };\n\n  const build = (): TypedFlow<T> => ({\n    version: 1,\n    id,\n    chainId,\n    inputs: [...flowInputs],\n    nodes: [...nodes],\n  });\n\n  const context: ContextAccessor = {\n    sender: ref<'address'>('context.sender'),\n    executionAddress: ref<'address'>('context.executionAddress'),\n  };\n\n  return {\n    context,\n    inputs: inputHandles as InputHandles<T>,\n    call,\n    untypedOp,\n    build,\n  };\n};\n"],"mappings":";;;;;AAoLA,MAAM,cAAc,SAClB,OAAO,SAAS,YAAY,SAAS,QAAQ,UAAU;;;;;;;;;AAUzD,MAAa,yBACX,SACA,YAC2B;CAC3B,MAAM,KAAK,QAAQ,QAAQ,OAAO,WAAW;CAC7C,MAAM,aAA0B,CAAC;CACjC,MAAM,QAAgB,CAAC;CACvB,MAAM,0BAAU,IAAI,IAAY;CAEhC,MAAM,eAAe,CAAC;CACtB,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,QAAQ,MAAM,GACtD,IAAI,WAAW,IAAI,GAAG;EACpB,IAAI,KAAK,YAAY,SACnB,MAAM,IAAI,MACR,UAAU,KAAK,gBAAgB,KAAK,QAAQ,0BAA0B,SACxE;EAEF,WAAW,KAAK;GAAE;GAAM,UAAU;EAAK,CAAC;EACxC,aAAa,QAAQ;GAAE,MAAM;GAAS,WAAW;GAAM,UAAU;EAAK;CACxE,OAAO;EACL,WAAW,KAAK;GAAE;GAAM,MAAM;EAAK,CAAC;EACpC,aAAa,QAAQ;GAAE,MAAM;GAAS,WAAW;EAAK;CACxD;CAGF,MAAM,QAIJ,QACA,IACA,MACA,SACA,aACwB;EACxB,IAAI,QAAQ,IAAI,MAAM,GAAG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