@nodaro/shared 3.59.0 → 3.60.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-QE7W4YIK.cjs → chunk-5G23AJBU.cjs} +6 -6
- package/dist/{chunk-QE7W4YIK.cjs.map → chunk-5G23AJBU.cjs.map} +1 -1
- package/dist/{chunk-DKZGLIFW.cjs → chunk-5HK5Z5OB.cjs} +4 -4
- package/dist/{chunk-DKZGLIFW.cjs.map → chunk-5HK5Z5OB.cjs.map} +1 -1
- package/dist/{chunk-RSXQOFM7.cjs → chunk-5Y42RIGY.cjs} +8 -8
- package/dist/{chunk-RSXQOFM7.cjs.map → chunk-5Y42RIGY.cjs.map} +1 -1
- package/dist/{chunk-FHCMYGBV.js → chunk-6AJOTEVC.js} +3 -3
- package/dist/{chunk-FHCMYGBV.js.map → chunk-6AJOTEVC.js.map} +1 -1
- package/dist/{chunk-ZVUVSD5X.js → chunk-6Q6SI7AG.js} +3 -3
- package/dist/{chunk-ZVUVSD5X.js.map → chunk-6Q6SI7AG.js.map} +1 -1
- package/dist/{chunk-V3NONYLA.cjs → chunk-A6HRY3WF.cjs} +269 -18
- package/dist/chunk-A6HRY3WF.cjs.map +1 -0
- package/dist/{chunk-D574HZ35.cjs → chunk-AXT7YNOR.cjs} +51 -51
- package/dist/{chunk-D574HZ35.cjs.map → chunk-AXT7YNOR.cjs.map} +1 -1
- package/dist/{chunk-TA7ODVYJ.js → chunk-AZGONXWV.js} +4 -4
- package/dist/{chunk-TA7ODVYJ.js.map → chunk-AZGONXWV.js.map} +1 -1
- package/dist/{chunk-OFL4UH6L.cjs → chunk-BDXXOEBZ.cjs} +80 -57
- package/dist/chunk-BDXXOEBZ.cjs.map +1 -0
- package/dist/{chunk-NZRG5CXQ.cjs → chunk-BLJUCPMV.cjs} +5 -2
- package/dist/chunk-BLJUCPMV.cjs.map +1 -0
- package/dist/{chunk-NHZWVKGV.cjs → chunk-BXNPO3PL.cjs} +8 -8
- package/dist/{chunk-NHZWVKGV.cjs.map → chunk-BXNPO3PL.cjs.map} +1 -1
- package/dist/{chunk-UPD7W2KJ.cjs → chunk-CIOXUPCJ.cjs} +12 -12
- package/dist/{chunk-UPD7W2KJ.cjs.map → chunk-CIOXUPCJ.cjs.map} +1 -1
- package/dist/{chunk-YE4EDT57.cjs → chunk-DQIJPDHC.cjs} +11 -11
- package/dist/{chunk-YE4EDT57.cjs.map → chunk-DQIJPDHC.cjs.map} +1 -1
- package/dist/{chunk-UMPZR56R.js → chunk-DS2TOM32.js} +3 -3
- package/dist/{chunk-UMPZR56R.js.map → chunk-DS2TOM32.js.map} +1 -1
- package/dist/{chunk-YSEJOJNQ.js → chunk-EN2YI5TV.js} +3 -3
- package/dist/{chunk-YSEJOJNQ.js.map → chunk-EN2YI5TV.js.map} +1 -1
- package/dist/{chunk-ZU56AMFK.js → chunk-G6GMY5BC.js} +20 -4
- package/dist/chunk-G6GMY5BC.js.map +1 -0
- package/dist/chunk-G7ZYZQKO.cjs +27 -0
- package/dist/{chunk-6VXDW2U3.cjs.map → chunk-G7ZYZQKO.cjs.map} +1 -1
- package/dist/{chunk-PEATSEAD.cjs → chunk-GNPJ2JLE.cjs} +6 -6
- package/dist/{chunk-PEATSEAD.cjs.map → chunk-GNPJ2JLE.cjs.map} +1 -1
- package/dist/{chunk-VLQW4CVW.cjs → chunk-GWBQ3GPO.cjs} +41 -21
- package/dist/chunk-GWBQ3GPO.cjs.map +1 -0
- package/dist/{chunk-P7KSB5T6.cjs → chunk-HDHLZK7C.cjs} +5 -5
- package/dist/{chunk-P7KSB5T6.cjs.map → chunk-HDHLZK7C.cjs.map} +1 -1
- package/dist/{chunk-QLLR7GUY.cjs → chunk-HNEF2N5C.cjs} +5 -5
- package/dist/{chunk-QLLR7GUY.cjs.map → chunk-HNEF2N5C.cjs.map} +1 -1
- package/dist/{chunk-7JM5EZF3.cjs → chunk-HOKWJXHA.cjs} +13 -13
- package/dist/{chunk-7JM5EZF3.cjs.map → chunk-HOKWJXHA.cjs.map} +1 -1
- package/dist/{chunk-2S7YYCRT.js → chunk-HYBACFYW.js} +4 -4
- package/dist/chunk-HYBACFYW.js.map +1 -0
- package/dist/{chunk-RGBNOCIO.js → chunk-ICDLYU4I.js} +9 -9
- package/dist/{chunk-RGBNOCIO.js.map → chunk-ICDLYU4I.js.map} +1 -1
- package/dist/{chunk-FJCRWDU5.js → chunk-IV6IDECY.js} +4 -4
- package/dist/{chunk-FJCRWDU5.js.map → chunk-IV6IDECY.js.map} +1 -1
- package/dist/{chunk-PIX4OCCQ.js → chunk-JKZVRKN3.js} +36 -14
- package/dist/chunk-JKZVRKN3.js.map +1 -0
- package/dist/{chunk-MTXVODG3.js → chunk-KJZVQIN4.js} +3 -3
- package/dist/{chunk-MTXVODG3.js.map → chunk-KJZVQIN4.js.map} +1 -1
- package/dist/{chunk-2VQHPILW.js → chunk-KOLC7AF2.js} +262 -19
- package/dist/chunk-KOLC7AF2.js.map +1 -0
- package/dist/{chunk-IP7QOHWQ.js → chunk-LN3EVFRS.js} +5 -5
- package/dist/{chunk-IP7QOHWQ.js.map → chunk-LN3EVFRS.js.map} +1 -1
- package/dist/{chunk-EO4W4MA3.js → chunk-MHY47BLL.js} +4 -4
- package/dist/{chunk-EO4W4MA3.js.map → chunk-MHY47BLL.js.map} +1 -1
- package/dist/{chunk-AWS4BWEC.js → chunk-Q6IES3U2.js} +5 -2
- package/dist/chunk-Q6IES3U2.js.map +1 -0
- package/dist/{chunk-62RC6K62.cjs → chunk-RRPPXZ36.cjs} +4 -4
- package/dist/{chunk-62RC6K62.cjs.map → chunk-RRPPXZ36.cjs.map} +1 -1
- package/dist/{chunk-3R2KVYXN.js → chunk-SCYBGTX6.js} +3 -3
- package/dist/{chunk-3R2KVYXN.js.map → chunk-SCYBGTX6.js.map} +1 -1
- package/dist/{chunk-K4L4G76I.cjs → chunk-SKFJIFEV.cjs} +21 -21
- package/dist/{chunk-K4L4G76I.cjs.map → chunk-SKFJIFEV.cjs.map} +1 -1
- package/dist/{chunk-PIEMWFSJ.js → chunk-URLDVK67.js} +3 -3
- package/dist/{chunk-PIEMWFSJ.js.map → chunk-URLDVK67.js.map} +1 -1
- package/dist/{chunk-IOET54EV.js → chunk-VB2ARGQ6.js} +35 -3
- package/dist/chunk-VB2ARGQ6.js.map +1 -0
- package/dist/{chunk-VOZI5F7V.js → chunk-VYQ25YQF.js} +3 -3
- package/dist/{chunk-VOZI5F7V.js.map → chunk-VYQ25YQF.js.map} +1 -1
- package/dist/{chunk-NSZTHJZJ.cjs → chunk-W4M7TNXG.cjs} +39 -39
- package/dist/chunk-W4M7TNXG.cjs.map +1 -0
- package/dist/{chunk-QSWUSXRL.cjs → chunk-WGKAOUEQ.cjs} +41 -2
- package/dist/chunk-WGKAOUEQ.cjs.map +1 -0
- package/dist/{chunk-ORJ5HQAB.js → chunk-YHVEZVAO.js} +4 -4
- package/dist/{chunk-ORJ5HQAB.js.map → chunk-YHVEZVAO.js.map} +1 -1
- package/dist/entries/apps.cjs +43 -43
- package/dist/entries/apps.js +8 -8
- package/dist/entries/credits.cjs +155 -151
- package/dist/entries/credits.d.cts +32 -3
- package/dist/entries/credits.d.ts +32 -3
- package/dist/entries/credits.js +8 -8
- package/dist/entries/llm-models.d.cts +1 -1
- package/dist/entries/llm-models.d.ts +1 -1
- package/dist/entries/model-catalog.cjs +144 -84
- package/dist/entries/model-catalog.d.cts +4 -47
- package/dist/entries/model-catalog.d.ts +4 -47
- package/dist/entries/model-catalog.js +5 -5
- package/dist/entries/models.cjs +305 -289
- package/dist/entries/models.d.cts +5 -4
- package/dist/entries/models.d.ts +5 -4
- package/dist/entries/models.js +4 -4
- package/dist/entries/nodes.cjs +208 -208
- package/dist/entries/nodes.d.cts +1 -1
- package/dist/entries/nodes.d.ts +1 -1
- package/dist/entries/nodes.js +10 -10
- package/dist/entries/pipeline.cjs +152 -152
- package/dist/entries/pipeline.d.cts +1 -1
- package/dist/entries/pipeline.d.ts +1 -1
- package/dist/entries/pipeline.js +3 -3
- package/dist/entries/ugc.cjs +71 -71
- package/dist/entries/ugc.js +4 -4
- package/dist/entries/video.cjs +117 -117
- package/dist/entries/video.js +4 -4
- package/dist/entries/workflow.cjs +147 -147
- package/dist/entries/workflow.d.cts +8 -0
- package/dist/entries/workflow.d.ts +8 -0
- package/dist/entries/workflow.js +2 -2
- package/dist/gpt-image-2-6-BeZdT-pW.d.cts +98 -0
- package/dist/gpt-image-2-6-BeZdT-pW.d.ts +98 -0
- package/dist/index.cjs +1314 -1234
- package/dist/index.d.cts +5 -4
- package/dist/index.d.ts +5 -4
- package/dist/index.js +20 -20
- package/dist/{model-catalog-QJ_AO9l0.d.cts → model-catalog-D6Es7VG-.d.cts} +56 -2
- package/dist/{model-catalog-QJ_AO9l0.d.ts → model-catalog-D6Es7VG-.d.ts} +56 -2
- package/dist/{model-constants-BwBdh6Rn.d.ts → model-constants-22k3fjp1.d.cts} +16 -1
- package/dist/{model-constants-BwBdh6Rn.d.cts → model-constants-22k3fjp1.d.ts} +16 -1
- package/package.json +1 -1
- package/src/__tests__/gpt-image-2-6-formats.test.ts +171 -0
- package/src/cast-swap-limits.ts +2 -1
- package/src/credit-identifiers.ts +63 -3
- package/src/entries/credits.ts +1 -0
- package/src/entries/model-catalog.ts +17 -0
- package/src/entries/models.ts +6 -0
- package/src/gpt-image-2-6.ts +72 -0
- package/src/model-catalog.ts +336 -13
- package/src/model-constants.ts +33 -0
- package/src/node-execution-state.ts +8 -0
- package/src/node-runtime-keys.ts +3 -0
- package/dist/chunk-2S7YYCRT.js.map +0 -1
- package/dist/chunk-2VQHPILW.js.map +0 -1
- package/dist/chunk-6VXDW2U3.cjs +0 -27
- package/dist/chunk-AWS4BWEC.js.map +0 -1
- package/dist/chunk-IOET54EV.js.map +0 -1
- package/dist/chunk-NSZTHJZJ.cjs.map +0 -1
- package/dist/chunk-NZRG5CXQ.cjs.map +0 -1
- package/dist/chunk-OFL4UH6L.cjs.map +0 -1
- package/dist/chunk-PIX4OCCQ.js.map +0 -1
- package/dist/chunk-QSWUSXRL.cjs.map +0 -1
- package/dist/chunk-V3NONYLA.cjs.map +0 -1
- package/dist/chunk-VLQW4CVW.cjs.map +0 -1
- package/dist/chunk-ZU56AMFK.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/node-refs.ts","../src/trigger-feeds.ts","../src/node-runtime-keys.ts","../src/json-path.ts","../src/filter-condition.ts","../src/selector.ts"],"names":["SUNO_SEPARATE_RESULT_FIELDS","SUNO_SEPARATE_META_FIELDS"],"mappings":";;;;;AAMO,IAAM,gBAAA,GAAmB;AAGzB,IAAM,sBAAA,uBAA6B,GAAA,CAAI;AAAA,EAC5C,MAAA;AAAA,EACA,aAAA;AAAA,EACA,YAAA;AAAA,EACA,mBAAA;AAAA,EACA;AACF,CAAC;AAUM,SAAS,aAAa,GAAA,EAAwD;AACnF,EAAA,MAAM,CAAA,GAAI,GAAA,CAAI,OAAA,CAAQ,IAAI,CAAA;AAC1B,EAAA,IAAI,CAAA,KAAM,IAAI,OAAO,EAAE,MAAM,GAAA,CAAI,IAAA,EAAK,EAAG,QAAA,EAAU,IAAA,EAAK;AACxD,EAAA,OAAO,EAAE,IAAA,EAAM,GAAA,CAAI,KAAA,CAAM,CAAA,EAAG,CAAC,CAAA,CAAE,IAAA,EAAK,EAAG,QAAA,EAAU,IAAI,KAAA,CAAM,CAAA,GAAI,CAAC,CAAA,CAAE,MAAK,EAAE;AAC3E;AAYO,SAAS,iBAAiB,KAAA,EAAuB;AACtD,EAAA,OAAO,KAAA,CAAM,IAAA,EAAK,CAAE,WAAA,EAAY;AAClC;AAcO,SAAS,2BACX,KAAA,EACU;AACb,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,IAAA,CAAK,WAAW,CAAA,EAAG;AACnD,IAAA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O,uBAAA,CAAwB,cAAc,WAAW,CAAA;AAAA,EAC1D,CAAA;AACA,EAAA,OAAO;AAAA,IACL,GAAG,MAAA;AAAA,IACH,aAAA,EAAe,OAAA,CAAQ,MAAA,CAAO,aAAa,CAAA;AAAA,IAC3C,cAAA,EAAgB,OAAA,CAAQ,MAAA,CAAO,cAAc,CAAA;AAAA,IAC7C,aAAA,EAAe,OAAA,CAAQ,MAAA,CAAO,aAAa,CAAA;AAAA,IAC3C,IAAA,EAAM,OAAA,CAAQ,MAAA,CAAO,IAAI;AAAA,GAC3B;AACF","file":"chunk-NZRG5CXQ.cjs","sourcesContent":["/**\n * Node reference pattern and resolution for {Node Label} template syntax.\n * Shared between frontend and backend.\n */\n\n/** Matches {Node Label} references in text. */\nexport const NODE_REF_PATTERN = /\\{([^}]+)\\}/g\n\n/** Reserved template variable names that should NOT be resolved as node refs */\nexport const RESERVED_TEMPLATE_VARS = new Set([\n \"name\",\n \"description\",\n \"userPrompt\",\n \"assetDescriptions\",\n \"outputCount\",\n])\n\n/**\n * Split a `{...}` token body into its node name and optional fallback. Splits on the FIRST `||`\n * (a fallback may itself contain `||`); both sides are trimmed. `fallback` is null when there is\n * no `||`, preserving the legacy \"leave the literal token\" behavior.\n * \"person || man\" -> { name: \"person\", fallback: \"man\" }\n * \"person || \" -> { name: \"person\", fallback: \"\" } (resolves to empty when absent)\n * \"person\" -> { name: \"person\", fallback: null } (literal {person} when absent)\n */\nexport function parseNodeRef(raw: string): { name: string; fallback: string | null } {\n const i = raw.indexOf(\"||\")\n if (i === -1) return { name: raw.trim(), fallback: null }\n return { name: raw.slice(0, i).trim(), fallback: raw.slice(i + 2).trim() }\n}\n\n/**\n * Canonical form of a node-name variable: trimmed + lowercased. Node-name\n * variables are CASE-INSENSITIVE with lowercase as canonical, so nodes labeled\n * `TEXt`, `TEXT`, `text` all feed the one `{text}` variable and `{TEXT}` /\n * `{Text}` / `{text}` in a prompt all resolve to it.\n *\n * Reserved template vars (RESERVED_TEMPLATE_VARS, e.g. `userPrompt`) are matched\n * case-sensitively on the ORIGINAL token BEFORE canonicalization, so `{userPrompt}`\n * stays a reserved token rather than becoming a `userprompt` node ref.\n */\nexport function canonicalVarName(label: string): string {\n return label.trim().toLowerCase()\n}\n\n/**\n * The distinct `{label}` names referenced across the given texts. Mirrors the\n * canvas-side `referencedRefs`: strips the `|| fallback`, and ignores empty\n * tokens, image-ref tokens (`{image:N}`), and RESERVED_TEMPLATE_VARS. Used to\n * SUPPRESS auto-injection of a connected node the author already placed\n * explicitly via `{label}` (so it isn't injected twice). `matchAll` over the\n * global pattern does not mutate its lastIndex, so sharing the constant is safe.\n *\n * Deliberately NOT `REF_TOKEN_NAMESPACE_PREFIXES`: widening this changes\n * run-time auto-injection on BOTH engines (follow-up ticket), not just the\n * editor.\n */\nexport function extractReferencedLabels(\n ...texts: ReadonlyArray<string | undefined | null>\n): Set<string> {\n const refs = new Set<string>()\n for (const text of texts) {\n if (typeof text !== \"string\" || text.length === 0) continue\n for (const m of text.matchAll(NODE_REF_PATTERN)) {\n const { name } = parseNodeRef(m[1] ?? \"\")\n if (name === \"\" || name.startsWith(\"image:\") || RESERVED_TEMPLATE_VARS.has(name)) continue\n refs.add(canonicalVarName(name)) // case-insensitive: {Foo} suppresses a `foo` node\n }\n }\n return refs\n}\n\n/** Handle → combine-order category for same-label `{label}` merging. Lower wins\n * first: prompt (0) → elements (1) → look family (2). Other handles are -1\n * (not combinable — they keep the per-engine last-wins/suffix behavior). */\nexport const REF_HANDLE_CATEGORY: Readonly<Record<string, number>> = {\n prompt: 0,\n elements: 1,\n look: 2,\n cinematography: 2,\n style: 2,\n}\n\n/** Combine-order category for a direct-parent edge's `targetHandle`; -1 when the\n * handle isn't one of the combinable prompt/elements/look handles. */\nexport function refHandleCategory(targetHandle: string | null | undefined): number {\n if (targetHandle != null && Object.prototype.hasOwnProperty.call(REF_HANDLE_CATEGORY, targetHandle)) {\n return REF_HANDLE_CATEGORY[targetHandle]\n }\n return -1\n}\n\n/**\n * Reference-handle id → resolved-input key. The SINGLE SOURCE OF TRUTH for which\n * `targetHandle` ids carry image / video / audio reference inputs. Shared by the\n * backend input-resolver (routes the wired URL into the matching\n * `referenceImageUrls` / `referenceVideoUrls` / `referenceAudioUrls` slot) AND\n * the positional `{image:N}` / `{video:N}` / `{audio:N}` body-token COUNTS in the\n * FE preview (`video-prompt-assembly.ts`), FE run (`execute-node.ts`), and BE\n * payload-builder.\n *\n * Two handle families map to the same keys:\n * - Legacy / i2v single-name ids (`references` / `reference-videos` /\n * `reference-audio`) — kept for un-migrated workflows.\n * - Canonical typed-handle ids the modern Generate Video node exposes\n * (`imageReferences` / `videoReferences` / `audioReferences`) — share the\n * resolved-input keys with the legacy ids so consumer code never forks.\n */\nexport const REFERENCE_HANDLE_MAP: Record<string, \"referenceImageUrls\" | \"referenceVideoUrls\" | \"referenceAudioUrls\"> = {\n // Legacy / i2v single-name handle ids (kept for un-migrated workflows)\n \"references\": \"referenceImageUrls\",\n \"reference-videos\": \"referenceVideoUrls\",\n \"reference-audio\": \"referenceAudioUrls\",\n // New canonical typed-handle ids (Generate Video) — share the resolved-input\n // keys with the legacy ids so payload-builder code doesn't fork.\n \"imageReferences\": \"referenceImageUrls\",\n \"videoReferences\": \"referenceVideoUrls\",\n \"audioReferences\": \"referenceAudioUrls\",\n}\n\n/** The three reference modalities a reference handle can carry. */\nexport type ReferenceModality = \"image\" | \"video\" | \"audio\"\n\n/**\n * The reference MODALITY a `targetHandle` carries, or null when the handle is\n * not a reference handle. Resolves BOTH the legacy single-name ids and the\n * canonical Generate Video ids (via REFERENCE_HANDLE_MAP), so positional\n * `{image:N}` / `{video:N}` / `{audio:N}` token counts cover every handle alias\n * — without this, the generate-video `imageReferences` handle was silently\n * uncounted and `{image:N}` tokens dropped to bare labels on the only creatable\n * video node.\n */\nexport function referenceModalityForHandle(targetHandle: string | null | undefined): ReferenceModality | null {\n if (targetHandle == null) return null\n const key = REFERENCE_HANDLE_MAP[targetHandle]\n return key === \"referenceImageUrls\" ? \"image\" : key === \"referenceVideoUrls\" ? \"video\" : key === \"referenceAudioUrls\" ? \"audio\" : null\n}\n\n/**\n * Frame target handles (start / end keyframes). An image wired into one of these\n * is a KEYFRAME, not an `{image:N}` reference: the backend appends frames at the\n * TAIL of `reference_image_urls` (`resolveSeedance2Inputs`), never numbered. The\n * editor MUST therefore exclude them from `{image:N}` numbering so editor token N\n * equals the worker reference slot N.\n *\n * The SINGLE source of truth for \"is this a frame handle,\" shared by the\n * config-panel autocomplete (`video-configs.tsx`) AND the inline/modal builder\n * (`connected-references.ts`) — without ONE definition those two surfaces drifted\n * and the inline editor numbered the frame as `{image:1}` (the C1 bug). Frames\n * are deliberately NOT in `REFERENCE_HANDLE_MAP`: they carry no reference\n * modality, so `referenceModalityForHandle` already returns `null` for them on\n * the count side — this set is the exclusion lever for the EDITOR-numbering side.\n */\nexport const FRAME_TARGET_HANDLES: ReadonlySet<string> = new Set([\"startFrame\", \"endFrame\"])\n\n/**\n * Minimal structural edge shape {@link countRefModalityEdges} reads — only the\n * two fields the count needs. Both the FE `WorkflowEdge` (xyflow `Edge`, whose\n * `target` is a non-null string) and the BE `SimpleEdge` satisfy it.\n */\nexport interface RefModalityEdge {\n target?: string | null\n targetHandle?: string | null\n}\n\n/**\n * Count the reference-handle edges of a given reference MODALITY wired into a\n * node — the ONE positional `{image:N}` / `{video:N}` / `{audio:N}` counter\n * shared by the FE preview (`video-prompt-assembly.ts`), the FE run\n * (`execute-node.ts`), and the BE orchestrator (`payload-builder.ts`). Counting\n * via `referenceModalityForHandle` (not a single handle string) covers BOTH the\n * legacy single-name ids (`references` / `reference-videos` / `reference-audio`)\n * AND the canonical Generate Video ids (`imageReferences` / `videoReferences` /\n * `audioReferences`), so editor token N maps 1:1 to the worker\n * `referenceImageUrls` / `referenceVideoUrls` / `referenceAudioUrls` slot N on\n * every handle alias. This is the EDGE count (not the resolved/list-expanded URL\n * count) so all three paths stay byte-identical; the edge-vs-resolved divergence\n * for a reference edge that fans out to >1 URL (a List producer) is a shared,\n * documented v1 limitation.\n */\nexport function countRefModalityEdges(\n edges: ReadonlyArray<RefModalityEdge>,\n nodeId: string,\n modality: ReferenceModality,\n): number {\n let n = 0\n for (const e of edges) {\n if (e.target === nodeId && referenceModalityForHandle(e.targetHandle) === modality) n += 1\n }\n return n\n}\n\n/**\n * The wires that bring a node the images a run sends, besides its own source:\n * its reference images, each identity node on the `assets` handle (one image at\n * least), and every `image` wire after the first (the first is the source, which\n * an edit's estimate counts itself). For a model priced per input image.\n */\nexport function countImageInputEdges(edges: ReadonlyArray<RefModalityEdge>, nodeId: string): number {\n const onHandle = (handle: string) => edges.filter((e) => e.target === nodeId && e.targetHandle === handle).length\n return countRefModalityEdges(edges, nodeId, \"image\") + onHandle(\"assets\") + Math.max(0, onHandle(\"image\") - 1)\n}\n\n/** A candidate contribution to the `{label}` map: the node's label, its resolved\n * output, and its direct-parent handle category (-1 = not combinable / deeper). */\nexport interface RefCandidate {\n label: string\n output: string\n category: number\n}\n\n/**\n * Same-label COMBINE: when ≥2 direct-parent candidates (category ≥ 0) share a\n * label, `{label}` resolves to their values joined by \", \" ordered prompt →\n * elements → look, and within a category by candidate (edge) order. Returns a\n * Map of ONLY the combined labels; the caller fills the rest with its own\n * (FE suffix / BE last-wins) logic, skipping any label present here. Shared so\n * the frontend executor and backend orchestrator never drift.\n */\nexport function combineSameLabelRefs(candidates: ReadonlyArray<RefCandidate>): Map<string, string> {\n const byLabel = new Map<string, RefCandidate[]>()\n for (const c of candidates) {\n if (c.category < 0) continue\n const key = canonicalVarName(c.label) // TEXt + TEXT + text collapse into one {text}\n const arr = byLabel.get(key)\n if (arr) arr.push(c)\n else byLabel.set(key, [c])\n }\n const combined = new Map<string, string>()\n for (const [label, group] of byLabel) {\n if (group.length < 2) continue\n const ordered = group\n .map((c, i) => ({ c, i }))\n .sort((a, b) => a.c.category - b.c.category || a.i - b.i)\n .map((x) => x.c.output)\n combined.set(label, ordered.join(\", \"))\n }\n return combined\n}\n\n/**\n * Resolve {Node Label} references in text by replacing them with actual node outputs.\n * Skips reserved template variables used by applyTemplate().\n * Iterates until stable to handle nested refs (e.g. {List} → {Animal1} → \"dog\").\n */\nexport function resolveNodeRefs(\n text: string,\n labelToOutput: ReadonlyMap<string, string>,\n): string {\n const MAX_PASSES = 10\n let result = text\n for (let i = 0; i < MAX_PASSES; i++) {\n const next = result.replace(NODE_REF_PATTERN, (match, raw: string) => {\n const { name, fallback } = parseNodeRef(raw)\n if (RESERVED_TEMPLATE_VARS.has(name)) return match\n // Node-name vars are case-insensitive: try the literal key first (keeps\n // original-cased maps like condition-variables working), then the\n // lowercase-canonical key (node-ref maps are canonical-keyed).\n const output = labelToOutput.get(name) ?? labelToOutput.get(canonicalVarName(name))\n if (output !== undefined) return output // connected, non-empty output → its value\n if (fallback !== null) return fallback // absent/empty + fallback → default (\"\" for {name || })\n return match // absent + no || → literal {name}\n })\n if (next === result) break\n result = next\n }\n return result\n}\n\n/**\n * Token namespaces that are NOT node-label references. `{image:1:face}` is the\n * unified-reference grammar, `{slot:x}` is recast's, `{video:N}`/`{audio:N}`\n * are reference handles, and `{ref:<id>}` is the id-addressed reference form —\n * all five are substituted by their own resolvers (`resolveReferenceTokens`,\n * `resolveRefIdTokens`, the recast slot pass), not by resolveNodeRefs. Before\n * this list existed, only `image:` was excluded, so `{video:1}` classified as a\n * MISSING node ref.\n *\n * Compared against the LOWERCASED token name: `REFERENCE_TOKEN_RE` is `/gi` and\n * `REF_ID_TOKEN_RE` spells `[rR][eE][fF]`, so `{Image:1}` / `{Ref:x}` really do\n * resolve downstream and must never read as a missing node ref.\n */\nexport const REF_TOKEN_NAMESPACE_PREFIXES: readonly string[] = [\n \"image:\", \"video:\", \"audio:\", \"slot:\", \"ref:\",\n]\n\nexport type RefTokenKind = \"wired\" | \"reserved\" | \"missing\" | \"skip\" | \"unknown\"\n\n/**\n * Classify a parsed `{...}` token name against the resolvable label set.\n * `resolvable === null` means the caller has no ref data at all — such tokens\n * classify `unknown` and must render like wired, so \"no data\" never\n * masquerades as \"nothing wired\".\n *\n * Single source of truth for the editor decoration, the missing-refs chip\n * (frontend/src/lib/prompt-ref-scan.ts delegates here) and the execution\n * engine's dispatch guard.\n */\nexport function classifyRefToken(\n name: string,\n resolvable: ReadonlySet<string> | null,\n): RefTokenKind {\n const lower = name.toLowerCase()\n if (name === \"\" || REF_TOKEN_NAMESPACE_PREFIXES.some((p) => lower.startsWith(p))) return \"skip\"\n if (RESERVED_TEMPLATE_VARS.has(name)) return \"reserved\"\n if (resolvable === null) return \"unknown\"\n return resolvable.has(canonicalVarName(name)) ? \"wired\" : \"missing\"\n}\n\n/**\n * The `{Label}` tokens in `text` that `resolveNodeRefs` would leave LITERAL and\n * that no upstream node can explain — i.e. exactly what would reach a provider\n * as the characters `{Label}`. Evidence for why this matters: `{Describe Image}`\n * ×2 (gpt-image-2) and `{gravity flip}` / `{rewind}` (seedance-2-5) in the\n * 2026-09-01 app-reports export.\n *\n * `resolvable` — labels with a value in the ref map (canonical/lowercase).\n * `known` — canonical labels of the nodes the caller considers to EXIST\n * (no state requirement; the backend passes every node in the\n * run's graph).\n *\n * A token whose label is in `known` but not `resolvable` PASSES: the node\n * exists and simply produced nothing, which is the caller's to substitute (the\n * backend resolves it to empty text), not this function's to refuse. A token\n * with an explicit `|| fallback` passes too — the fallback is substituted.\n * Returns original-cased names, de-duplicated by canonical form, for the\n * user-facing message.\n */\nexport function unresolvedRefTokens(\n text: string,\n opts: { resolvable: ReadonlySet<string>; known: ReadonlySet<string> },\n): string[] {\n if (typeof text !== \"string\" || text.length === 0) return []\n const seen = new Set<string>()\n const out: string[] = []\n for (const m of text.matchAll(NODE_REF_PATTERN)) {\n const { name, fallback } = parseNodeRef(m[1] ?? \"\")\n if (fallback !== null) continue\n if (classifyRefToken(name, opts.resolvable) !== \"missing\") continue\n const canon = canonicalVarName(name)\n if (opts.known.has(canon) || seen.has(canon)) continue\n seen.add(canon)\n out.push(name)\n }\n return out\n}\n","/**\n * Every way one node FEEDS another — the ONE definition the server's run\n * scope (`triggerRunScope`) and the editor's \"is this trigger wired?\" read\n * from, so the card can never say \"the branch\" while the server runs the\n * whole workflow, or the other way round:\n *\n * - a drawn edge whose two ends are both on the graph (a delta that deleted a\n * node leaves its edges behind; those feed nothing);\n * - Group membership: a node inside a Group feeds the group (`parentId`),\n * the way the engine orders a group after its members;\n * - a field mapping: `data.fieldMappings[field].sourceNodeId` feeds the node\n * that carries the mapping, even after the edge it was made from is gone.\n */\n\nexport interface FeedNode {\n readonly id: string\n readonly parentId?: string | null\n readonly data?: unknown\n}\n\nexport interface FeedEdge {\n readonly source: string\n readonly target: string\n}\n\nexport interface FeedMaps {\n /** node id → the ids it feeds */\n readonly children: ReadonlyMap<string, ReadonlyArray<string>>\n /** node id → the ids that feed it */\n readonly parents: ReadonlyMap<string, ReadonlyArray<string>>\n}\n\nexport function buildFeedMaps(nodes: ReadonlyArray<FeedNode>, edges: ReadonlyArray<FeedEdge>): FeedMaps {\n const live = new Set(nodes.map((n) => n.id))\n const children = new Map<string, string[]>()\n const parents = new Map<string, string[]>()\n const feeds = (source: string, target: string) => {\n if (!live.has(source) || !live.has(target) || source === target) return\n children.set(source, [...(children.get(source) ?? []), target])\n parents.set(target, [...(parents.get(target) ?? []), source])\n }\n for (const edge of edges) feeds(edge.source, edge.target)\n for (const n of nodes) {\n if (typeof n.parentId === \"string\" && n.parentId) feeds(n.id, n.parentId)\n const mappings = (n.data as { fieldMappings?: unknown } | null | undefined)?.fieldMappings\n if (mappings && typeof mappings === \"object\") {\n for (const mapping of Object.values(mappings as Record<string, unknown>)) {\n const sourceNodeId = (mapping as { sourceNodeId?: unknown } | null)?.sourceNodeId\n if (typeof sourceNodeId === \"string\" && sourceNodeId) feeds(sourceNodeId, n.id)\n }\n }\n }\n return { children, parents }\n}\n\n/** Does this node feed anything? A trigger that does not runs the whole workflow. */\nexport function nodeFeedsAnything(nodes: ReadonlyArray<FeedNode>, edges: ReadonlyArray<FeedEdge>, nodeId: string): boolean {\n return (buildFeedMaps(nodes, edges).children.get(nodeId) ?? []).length > 0\n}\n","import { SUNO_SEPARATE_META_FIELDS, SUNO_SEPARATE_RESULT_FIELDS } from \"./suno-separate.js\"\n\n/**\n * Field names on a node's `data` that hold runtime / result / transient execution\n * state (job ids, progress, generated outputs, fan-out bookkeeping). These are NEVER\n * part of a node's reusable configuration.\n *\n * Single source of truth, consumed by:\n * - the workflow store's undo logic (execution-only updates skip undo capture, so job\n * polling does not pollute undo history or flip `isDirty`)\n * - the node-preset extractor (presets must never capture runtime state)\n * - the backend defensive strip on preset writes\n *\n * When adding a new runtime/result field to a node's data, add its key here — or, when it is a\n * generic name only one node type writes as a result, to that type's row of\n * NODE_TYPE_EXECUTION_DATA_KEYS (read through `isExecutionDataKey` / `executionDataKeysOf`).\n */\nexport const EXECUTION_DATA_KEYS: ReadonlySet<string> = new Set([\n \"executionStatus\",\n \"currentJobId\",\n \"currentJobProgress\",\n \"errorMessage\",\n // Structured detail alongside errorMessage for a safety-filter block\n // (see `JobErrorHint` in the app's frontend/src/types/nodes.ts). Same\n // lifecycle as errorMessage: a RESULT the user expects to survive reload,\n // never user-edited config.\n \"errorHint\",\n // A job policy registered by the deployment held this node's result for a\n // human reviewer (`jobs.status = \"pending_review\"`). Pure run state, like\n // executionStatus: the node is still \"running\" and the flag disappears the\n // moment the review resolves — so it is ALSO in TRANSIENT_RUNTIME_KEYS\n // below. Without the transient half, a flip into review marks a passive tab\n // dirty and a preset captures \"awaiting review\".\n \"jobAwaitingReview\",\n // The editor cannot reach the server to read this node's job. The job keeps\n // running and the watch keeps polling. Pure run state, cleared by the next\n // check that gets through, so it is ALSO in TRANSIENT_RUNTIME_KEYS below.\n \"jobConnectionLost\",\n // Where this node's job stands in line while it waits for a free slot\n // (the job read's `queue` field), shown by the editor's queue badge. Pure run\n // state, replaced on each read and cleared once the job leaves `queued`, so\n // it is ALSO in TRANSIENT_RUNTIME_KEYS below: a badge never marks the\n // workflow dirty and is never saved.\n \"queueInfo\",\n \"isStreaming\",\n \"generatedImageUrl\",\n \"generatedVideoUrl\",\n \"generatedAudioUrl\",\n \"generatedText\",\n \"generatedScript\",\n \"generatedItems\",\n \"generatedResults\",\n \"activeResultIndex\",\n \"sourceImageUrl\",\n \"__listTotal\",\n \"__listCompleted\",\n \"__listResults\",\n // Row-aligned twin of __listResults (Extract Field, List output) — read only\n // by the fan-out so two lists cut from one array pair by row.\n \"__alignedListResults\",\n // A render's fan-out row stamps, row-aligned with __listResults: each row's\n // take identity, and the clip every row was sent for (a failed row too).\n \"__listResultStamps\",\n // List fan-out window flag (abandon-guard exemption). Set/cleared by\n // executeNodeForList — purely execution-related, never user-edited.\n \"__listRunning\",\n // Why the last server run skipped this node (`empty_input`): a chip on the\n // card for the run that just ended, never a saved result — also in\n // TRANSIENT_RUNTIME_KEYS below.\n \"__runSkipReason\",\n // One token per paid run still out on this node that no executor mark\n // covers (the editor's `withRunInFlight`, around each paid call outside the\n // executors). Purely execution-related, never user-edited; also in\n // TRANSIENT_RUNTIME_KEYS.\n \"__runsInFlight\",\n // Selector node dual-channel outputs (picked + rest). Server-side execution\n // output, not user-edited config.\n \"pickedResults\",\n \"restResults\",\n \"__pickedResults\",\n \"__restResults\",\n \"__pickedTotal\",\n \"__restTotal\",\n \"generatedJson\",\n // A render's remapped transcript on its own pip (Speaker View's\n // `transcript`, RENDER_NODE_TYPES transcriptOutput) — run-result data.\n \"generatedTranscript\",\n // Edit Plan: a person's review of the plan (`EditedEdl`, edit-plan-review.ts),\n // kept beside `generatedJson` and fingerprinted against it. Run-result data\n // (TA14, decided 2026-10-04): out of undo, presets, templates and exports,\n // and Clear results wipes it. Persisted — never transient.\n \"editedEdl\",\n \"subWorkflowProgress\",\n \"outputResults\",\n \"shots\",\n \"result\",\n \"processedResult\",\n \"activeRoutes\",\n \"routeOutputs\",\n \"_upstreamRefresh\",\n \"zoom\",\n // Character LoRA training status fields — written every 8s while training.\n \"loraReplicateVersion\",\n \"loraTriggerWord\",\n \"loraTrainingStatus\",\n // Collect (fan-in) execution snapshot.\n \"lastInputs\",\n \"lastMeta\",\n \"__upstreamCount\",\n // Video URL node — the download's live percent/phase, written on every\n // progress tick (~2/s). Pure run-state; also in TRANSIENT_RUNTIME_KEYS below.\n \"downloadPercent\",\n \"downloadPhase\",\n // Webhook Output's delivery receipt. A webhook target may reflect the\n // request back (httpbin, RequestBin, an API that 400s with \"headers\n // received: …\"), so `webhookResponseBody` can carry whatever the request\n // carried — with an attached credential, the secret itself. Listing the three\n // here is what keeps the receipt out of template exports (GENERATED_FIELDS\n // derives from this set), out of node presets, and out of undo history.\n \"webhookSuccess\",\n \"webhookStatusCode\",\n \"webhookResponseBody\",\n // Content Ideas: one creative brief per idea (the node's list output — kept\n // out of __listResults, which would clone the node). And the non-fatal notes\n // a Content Recipe / Content Ideas run returns (\"read the first of 3 posts\").\n // Both are RESULTS: they persist, and a preset, a template or a run-only\n // patch must never treat them as config.\n \"ideaBriefs\",\n \"runWarnings\",\n // Content Ideas: the own brand whose results the last run leaned on — a\n // RESULT naming the runner's brand, so a template or a preset never carries it.\n \"brandLessons\",\n // Social Search: every post the last search found (the picker's grid), the\n // ids a person picked from them, and the run's non-fatal notes (\"only part\n // of the results loaded\"). All RESULTS: a template, a preset or a run-only\n // patch must never carry yesterday's posts or picks as configuration.\n \"searchResults\",\n \"pickedIds\",\n \"searchWarnings\",\n // Save to Collection: how the last run ended for this node (inserted /\n // duplicate / replayed) and how many old records the cap evicted. RESULTS of\n // a run — Clear results wipes them, and a template, a preset or a run-only\n // patch never carries them as configuration.\n \"lastOutcome\",\n \"lastEvicted\",\n // When the editor's \"Clear results\" last emptied this node (ISO time). Not a\n // result and not config: bookkeeping that tells the load-time recovery lanes\n // \"this node is empty ON PURPOSE\" — without it, every reload reads an empty\n // node as \"ran while the editor was closed\" and paints the last run back.\n // Persisted (never transient): the reload is exactly when it is read.\n \"resultsClearedAt\",\n // The id of the trigger-started run whose results this node shows (the\n // editor paints a Telegram run onto the canvas). Bookkeeping, not a result\n // and not config: it stops a reload from painting the same run again over\n // edits made since. Persisted for the same reason as resultsClearedAt.\n \"resultsRunId\",\n // When that run ended the node (beside resultsRunId): the editor's reopen\n // keeps a result a NEWER run left even when its own run listing cannot see\n // that run. Bookkeeping, persisted for the same reason.\n \"resultsRunEndedAt\",\n // A trigger's last run values (also in TRANSIENT_RUNTIME_KEYS: never saved).\n \"__triggerData\",\n // A fan-out's notes rows, every fan-out's (row-aligned with __listResults):\n // a row's warnings and length. A RESULT: persisted.\n \"__listResultMeta\",\n // A use-case node's continuation of one of its runs (Tighten Episode): set\n // for ONE run only, as that run's input override (an app's or the editor's\n // Render final, the canvas Continue's run option). Never saved — also in\n // TRANSIENT_RUNTIME_KEYS — so a saved one can never turn a later plain run\n // into a continuation of an old run.\n \"useCaseContinue\",\n // The content rights confirmation a run fetches a Video URL node's link\n // under: that run's input override alone, never saved (also transient).\n \"rightsConfirmationId\",\n])\n\n/**\n * Run results a node type writes under a GENERIC name — `quote`, `durationSec`,\n * `candidates` — that are execution data on THAT type only. Another node may\n * keep a setting under the same name; filing these globally would misfile it\n * (out of undo, presets, templates and the copilot's view). Same lifecycle as\n * the global results: persisted, and a run writing them is never an undo step.\n *\n * UGC video (Nodaro Cloud): the outputs a node hands on (`ugcOutputs`), UGC\n * Creator's options of a draw and their note, UGC Clips' quote, and UGC Clip's\n * warnings, length and Re-render marks (`rerenderPending`: the clips pressed for\n * Re-render that no run has rendered yet — run bookkeeping; the press itself,\n * `rerender`, is a choice).\n *\n * Suno Separate: every stem / take URL a run writes and the run's facts (its\n * engine, a Demucs fallback's refusal and reason, its mode) — not `stemName`,\n * the node's instrument setting that the run only echoes back.\n */\nexport const NODE_TYPE_EXECUTION_DATA_KEYS: Readonly<Record<string, readonly string[]>> = {\n \"ugc-creator\": [\"ugcOutputs\", \"candidates\", \"optionFailed\"],\n \"ugc-script\": [\"ugcOutputs\"],\n \"ugc-clips\": [\"ugcOutputs\", \"quote\"],\n \"ugc-clip\": [\"ugcOutputs\", \"clipWarnings\", \"durationSec\", \"rerenderPending\"],\n \"ugc-cards\": [\"ugcOutputs\"],\n \"suno-separate\": [...SUNO_SEPARATE_RESULT_FIELDS, ...SUNO_SEPARATE_META_FIELDS.filter((key) => key !== \"stemName\")],\n}\n\n/** Is `key` execution data (run state or a run's result) on a node of `type`: global, or that type's own? */\nexport function isExecutionDataKey(key: string, type: string | null | undefined): boolean {\n if (EXECUTION_DATA_KEYS.has(key)) return true\n return typeof type === \"string\" && Object.hasOwn(NODE_TYPE_EXECUTION_DATA_KEYS, type) && NODE_TYPE_EXECUTION_DATA_KEYS[type]!.includes(key)\n}\n\nconst EXECUTION_DATA_KEYS_BY_TYPE = new Map<string, ReadonlySet<string>>(\n Object.entries(NODE_TYPE_EXECUTION_DATA_KEYS).map(([type, keys]) => [type, new Set([...EXECUTION_DATA_KEYS, ...keys])]),\n)\n\n/** Every execution-data key on a node of `type`, as one set: the global ones, plus the type's own. */\nexport function executionDataKeysOf(type: string | null | undefined): ReadonlySet<string> {\n return (typeof type === \"string\" ? EXECUTION_DATA_KEYS_BY_TYPE.get(type) : undefined) ?? EXECUTION_DATA_KEYS\n}\n\n/**\n * The PURE RUN-STATE subset of EXECUTION_DATA_KEYS: per-tick values (status\n * flips, job ids, progress counters, fan-out bookkeeping) that must NEITHER\n * mark the workflow dirty NOR be persisted in the save payload. Everything\n * else in EXECUTION_DATA_KEYS is a RESULT the user expects to survive reload\n * (generated URLs/results, errorMessage, LoRA outputs, collect snapshots).\n *\n * Why this split exists: writing these keys used to set `isDirty`, so job\n * polling phantom-dirtied passive tabs → spurious autosaves → false\n * \"changed in another tab\" banners → the remote-ahead latch froze autosave\n * (the \"not saved for a long time\" report). Consumed by the workflow\n * store's dirty decision and the save-payload sanitizer below.\n *\n * Invariant (guarded by node-runtime-keys.test.ts): subset of\n * EXECUTION_DATA_KEYS — anything transient is also undo-exempt.\n */\nexport const TRANSIENT_RUNTIME_KEYS: ReadonlySet<string> = new Set([\n \"executionStatus\",\n \"currentJobId\",\n \"currentJobProgress\",\n \"jobAwaitingReview\",\n \"jobConnectionLost\",\n \"queueInfo\",\n \"isStreaming\",\n \"subWorkflowProgress\",\n \"__listTotal\",\n \"__listCompleted\",\n \"__listRunning\",\n \"__runSkipReason\",\n // A paid run still out, held by the editor tab that started it. Never\n // saved, so a reload, which has no such run, starts without one.\n \"__runsInFlight\",\n \"_upstreamRefresh\",\n \"__upstreamCount\",\n // Video URL node download ticks. They used to dirty the workflow twice a\n // second for the length of the download — the same phantom-save chain the\n // job-progress keys above were moved here to stop. What SURVIVES a reload is\n // `downloadStatus` + `downloadId`; the percent is re-read from the server.\n \"downloadPercent\",\n \"downloadPhase\",\n // A trigger's last run values, shown in the editor after a run (a webhook's\n // body, a Telegram message and its post). Never saved: the workflow is not\n // where a message's content is kept — runs are, under their retention.\n \"__triggerData\",\n // A use-case node's continuation: one run's override, never config (above).\n \"useCaseContinue\",\n // The content rights confirmation a run fetches a Video URL node's link\n // under: one run's override (RUN_ONLY_NODE_FIELDS), never config.\n \"rightsConfirmationId\",\n])\n\n/**\n * Pure save-payload sanitizer: returns new node objects with the transient\n * run-state keys removed from `data`. Nodes without transient keys (or\n * without `data`) are returned by reference — cheap for the common case.\n */\nexport function stripTransientRuntimeData<\n T extends { data?: Record<string, unknown> | undefined },\n>(nodes: readonly T[]): T[] {\n return nodes.map((node) => {\n const data = node.data\n if (!data) return node\n let hasTransient = false\n for (const key of TRANSIENT_RUNTIME_KEYS) {\n if (key in data) {\n hasTransient = true\n break\n }\n }\n if (!hasTransient) return node\n const cleaned: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(data)) {\n if (!TRANSIENT_RUNTIME_KEYS.has(key)) cleaned[key] = value\n }\n return { ...node, data: cleaned }\n })\n}\n","/**\n * Evaluate a dot-notation path against a JSON value.\n *\n * Auto-iterates arrays at any depth: if the current value is an array,\n * the evaluator iterates and applies the remaining path to each element,\n * flattening results. This lets simple paths like \"caption\" work on a\n * top-level array and \"pages.markdown\" work on a nested array without\n * any wildcard syntax.\n *\n * Returns an array of values. Missing properties are skipped (empty for\n * that branch). Null/undefined leaf values are included — callers coerce.\n * Empty path returns `[value]` (a single-element array wrapping the\n * value) when the value is scalar/object, or the array elements flat\n * when the root is an array.\n */\nexport function evaluateJsonPath(value: unknown, path: string): unknown[] {\n const segments = path.length === 0 ? [] : path.split(\".\")\n return walk(value, segments, 0)\n}\n\n/**\n * Coerce an array of unknown values (typically from evaluateJsonPath) to\n * strings, skipping null/undefined. Primitives are stringified; objects\n * are JSON-encoded.\n */\nexport function stringifyPathResults(raw: unknown[]): string[] {\n const out: string[] = []\n for (const v of raw) {\n if (v === null || v === undefined) continue\n if (typeof v === \"string\") out.push(v)\n else if (typeof v === \"number\" || typeof v === \"boolean\") out.push(String(v))\n else out.push(JSON.stringify(v))\n }\n return out\n}\n\nfunction walk(value: unknown, segments: string[], offset: number): unknown[] {\n if (Array.isArray(value)) {\n const results: unknown[] = []\n for (const item of value) {\n for (const v of walk(item, segments, offset)) results.push(v)\n }\n return results\n }\n if (offset >= segments.length) return [value]\n if (value !== null && typeof value === \"object\") {\n const head = segments[offset]\n if (!Object.hasOwn(value as object, head)) return []\n return walk((value as Record<string, unknown>)[head], segments, offset + 1)\n }\n return []\n}\n","/** Pure condition evaluator shared by filter-list and router (conditional mode). */\n\nimport { evaluateJsonPath } from \"./json-path.js\"\nimport { resolveNodeRefs } from \"./node-refs.js\"\n\nexport type FilterListOperator =\n | \">\" | \"<\" | \">=\" | \"<=\"\n | \"=\" | \"!=\"\n | \"contains\" | \"not_contains\"\n | \"starts_with\" | \"ends_with\" | \"regex\"\n | \"exists\" | \"not_exists\"\n\nexport interface FilterListCondition {\n id?: string\n field?: string\n operator: FilterListOperator\n value?: string\n valueType?: \"static\" | \"variable\"\n /** UI-only hint on the config panel — irrelevant to evaluation. */\n mode?: \"dropdown\" | \"custom\"\n}\n\n/** AND/OR condition bundle used by the router's conditional mode. When a\n * group matches, every routeId is added to activeRoutes. Multiple groups\n * union (deduped). */\nexport interface RouterConditionGroup {\n id?: string\n conditions?: FilterListCondition[]\n conditionLogic?: \"AND\" | \"OR\"\n routeIds?: string[]\n}\n\n/**\n * Options for `evaluateCondition` / `evaluateConditionGroup`.\n */\nexport interface EvaluateConditionOptions {\n /** When `false`, text operators (`contains`, `not_contains`, `starts_with`,\n * `ends_with`, `=`, `!=`) compare case-insensitively using case-folded\n * string equality.\n *\n * Note: `=` and `!=` lose their default numeric-coercion semantics under\n * `caseSensitive: false`. Under the default (case-sensitive), `1 == \"1.0\"`\n * via `valuesEqual`; under `caseSensitive: false`, comparison is pure\n * case-folded string equality, so `\"1\" !== \"1.0\"`.\n *\n * Default (when undefined): `true` (case-sensitive) — preserves existing\n * behavior for all callers.\n *\n * Non-text operators (`>`, `<`, `>=`, `<=`, `exists`, `not_exists`,\n * `regex`) are unaffected by this flag. */\n caseSensitive?: boolean\n /** Label→output map for `{Node Label}` refs inside condition values.\n * Populated from a filter-list / router node's `\"variables\"` target\n * handle. Resolved via `resolveNodeRefs` — unknown labels preserve\n * the original `{...}` text, so JSON-literal values stay intact. */\n variables?: ReadonlyMap<string, string>\n}\n\nexport function tryParseJson(item: unknown): unknown {\n if (typeof item !== \"string\") return item\n const trimmed = item.trim()\n if (!trimmed) return item\n const first = trimmed[0]\n if (first !== \"{\" && first !== \"[\" && first !== \"\\\"\" && !/^-?\\d/.test(trimmed) && trimmed !== \"true\" && trimmed !== \"false\" && trimmed !== \"null\") {\n return item\n }\n try { return JSON.parse(trimmed) } catch { return item }\n}\n\nconst HOUR_MS = 60 * 60 * 1000\nconst DAY_MS = 24 * HOUR_MS\nconst WEEK_MS = 7 * DAY_MS\n\n/** Resolve a relative-window token like `last_N_hours:3` to an ISO timestamp\n * N units before `Date.now()`. Returns undefined for malformed tokens. */\nexport function resolveRelativeWindowToken(key: string): string | undefined {\n const m = /^last_N_(hours|days|weeks):(-?\\d+)$/.exec(key)\n if (!m) return undefined\n const n = parseInt(m[2], 10)\n if (!Number.isFinite(n)) return undefined\n const unitMs = m[1] === \"hours\" ? HOUR_MS : m[1] === \"days\" ? DAY_MS : WEEK_MS\n return new Date(Date.now() - n * unitMs).toISOString()\n}\n\n/**\n * Substitute `{{...}}` template tokens — `{{now}}`, `{{trigger.<path>}}`,\n * and relative-window tokens (`{{last_N_hours:N}}` / days / weeks). Reused\n * by `resolveConditionValue` (filter-list / router) and `resolveSelectorRefs`\n * (selector node) so token semantics stay identical across the workflow-engine\n * ref-resolution surface.\n *\n * Pure: returns a new string. Strings with no `{{...}}` tokens pass through\n * unchanged.\n */\nexport function substituteTriggerTokens(\n raw: string,\n triggerData?: Record<string, unknown>,\n): string {\n if (!/\\{\\{/.test(raw)) return raw\n return raw.replace(/\\{\\{\\s*([^}]+?)\\s*\\}\\}/g, (_m, expr) => {\n const key = String(expr).trim()\n if (key === \"now\") return new Date().toISOString()\n if (key === \"trigger.last_triggered_at\") {\n const v = triggerData?.last_triggered_at\n return v == null ? \"\" : String(v)\n }\n if (key.startsWith(\"trigger.\")) {\n const path = key.slice(\"trigger.\".length)\n const v = triggerData?.[path]\n return v == null ? \"\" : String(v)\n }\n const relative = resolveRelativeWindowToken(key)\n if (relative !== undefined) return relative\n return \"\"\n })\n}\n\nexport function resolveConditionValue(\n raw: string,\n valueType: string | undefined,\n triggerData?: Record<string, unknown>,\n variables?: ReadonlyMap<string, string>,\n): string {\n let value = raw\n if (variables && variables.size > 0) {\n value = resolveNodeRefs(value, variables)\n }\n const hasTemplate = /\\{\\{/.test(value)\n if (valueType !== \"variable\" && !hasTemplate) return value\n return substituteTriggerTokens(value, triggerData)\n}\n\nfunction asComparableNumber(v: unknown): number {\n if (typeof v === \"number\") return v\n if (typeof v === \"boolean\") return v ? 1 : 0\n if (typeof v === \"string\") {\n const trimmed = v.trim()\n if (trimmed === \"\") return NaN\n const n = Number(trimmed)\n if (!isNaN(n)) return n\n const d = Date.parse(trimmed)\n if (!isNaN(d)) return d\n }\n return NaN\n}\n\n// Numeric-first ordering compare used by >, <, >=, <=. Falls back to\n// localeCompare when either side can't be parsed as a number.\nfunction compareValues(a: unknown, b: unknown): number {\n const na = asComparableNumber(a)\n const nb = asComparableNumber(b)\n if (!isNaN(na) && !isNaN(nb)) return na - nb\n return String(a ?? \"\").localeCompare(String(b ?? \"\"))\n}\n\n// Numeric-first equality used by = and !=. So \"432\" == 432, and 432 == \"432\".\n// Falls back to strict string equality (null/undefined coerced to \"\") so\n// alpha values still work.\nfunction valuesEqual(a: unknown, b: unknown): boolean {\n const na = asComparableNumber(a)\n const nb = asComparableNumber(b)\n if (!isNaN(na) && !isNaN(nb)) return na === nb\n return String(a ?? \"\") === String(b ?? \"\")\n}\n\nfunction applyCase(s: string, caseSensitive: boolean): string {\n return caseSensitive ? s : s.toLowerCase()\n}\n\nexport function evaluateCondition(\n parsedItem: unknown,\n rawItem: string,\n condition: FilterListCondition,\n triggerData?: Record<string, unknown>,\n options?: EvaluateConditionOptions,\n): boolean {\n const path = (condition.field ?? \"\").trim()\n let fieldValue: unknown\n if (path === \"\") {\n fieldValue = parsedItem ?? rawItem\n } else {\n const matches = evaluateJsonPath(parsedItem ?? rawItem, path)\n fieldValue = matches.length > 0 ? matches[0] : undefined\n }\n\n const targetStr = resolveConditionValue(condition.value ?? \"\", condition.valueType, triggerData, options?.variables)\n // Default to case-sensitive when the flag is not explicitly set. This\n // preserves existing behavior for Router conditional mode and legacy\n // Filter List nodes that don't carry the new `caseSensitive` field.\n const cs = options?.caseSensitive ?? true\n const fieldStr = String(fieldValue ?? \"\")\n\n switch (condition.operator) {\n case \"exists\":\n return fieldValue !== undefined && fieldValue !== null\n case \"not_exists\":\n return fieldValue === undefined || fieldValue === null\n case \"contains\":\n return applyCase(fieldStr, cs).includes(applyCase(targetStr, cs))\n case \"not_contains\":\n return !applyCase(fieldStr, cs).includes(applyCase(targetStr, cs))\n case \"starts_with\":\n return applyCase(fieldStr, cs).startsWith(applyCase(targetStr, cs))\n case \"ends_with\":\n return applyCase(fieldStr, cs).endsWith(applyCase(targetStr, cs))\n case \"regex\": {\n if (!targetStr) return false\n try {\n return new RegExp(targetStr).test(fieldStr)\n } catch {\n return false\n }\n }\n case \"=\":\n return cs\n ? valuesEqual(fieldValue, targetStr)\n : applyCase(fieldStr, false) === applyCase(targetStr, false)\n case \"!=\":\n return cs\n ? !valuesEqual(fieldValue, targetStr)\n : applyCase(fieldStr, false) !== applyCase(targetStr, false)\n case \">\":\n return compareValues(fieldValue, targetStr) > 0\n case \"<\":\n return compareValues(fieldValue, targetStr) < 0\n case \">=\":\n return compareValues(fieldValue, targetStr) >= 0\n case \"<=\":\n return compareValues(fieldValue, targetStr) <= 0\n default:\n return false\n }\n}\n\n/** Evaluate a single AND/OR-joined group against one item. Empty condition\n * list evaluates to `true` — typical when the user has just added a group\n * and hasn't configured any conditions yet. */\nexport function evaluateConditionGroup(\n parsedItem: unknown,\n rawItem: string,\n conditions: readonly FilterListCondition[],\n logic: \"AND\" | \"OR\",\n triggerData?: Record<string, unknown>,\n options?: EvaluateConditionOptions,\n): boolean {\n const effective = conditions.filter((c) => c && c.operator)\n if (effective.length === 0) return true\n const results = effective.map((c) => evaluateCondition(parsedItem, rawItem, c, triggerData, options))\n return logic === \"OR\" ? results.some(Boolean) : results.every(Boolean)\n}\n","/**\n * Edge range utilities for resolving 1-based index expressions\n * and applying range/step slicing to output lists.\n *\n * Used by both frontend DAG executor and backend orchestrator\n * to support edge-level range, step, and item selection.\n */\n\nimport { evaluateCondition, substituteTriggerTokens, tryParseJson } from \"./filter-condition.js\"\nimport { resolveNodeRefs } from \"./node-refs.js\"\n\n/** Selector tab on an edge — \"range\" (from/to/step) or \"list\" (expression). */\nexport type SelectorMode = \"range\" | \"list\"\n\n/** Per-edge output mode controlling how upstream results reach downstream. */\nexport type OutputMode = \"last\" | \"each\" | \"all\" | \"item\"\n\n/** Edge-data fields consumed by selectListItems / isDefaultSelectorConfig. */\nexport type SelectorFields = {\n selectorMode?: SelectorMode\n listExpression?: string\n rangeFrom?: string\n rangeTo?: string\n rangeStep?: number\n}\n\n/** Full selector mode set — extends the edge-selector modes with new operators. */\nexport type FullSelectorMode =\n | \"item\"\n | \"range\"\n | \"list\"\n | \"random\"\n | \"modulo\"\n | \"predicate\"\n | \"named-key\"\n\n/** Operator set for predicate mode — reused from filter-list. */\nexport type SelectorPredicateOp =\n | \">\" | \"<\" | \">=\" | \"<=\"\n | \"=\" | \"!=\"\n | \"contains\" | \"not_contains\"\n | \"starts_with\" | \"ends_with\"\n | \"regex\"\n | \"exists\" | \"not_exists\"\n\n/** Config consumed by `runSelector` and `resolveSelectorRefs`. */\nexport type SelectorConfig = {\n mode: FullSelectorMode\n // item\n itemIndex?: string\n // range\n rangeFrom?: string\n rangeTo?: string\n rangeStep?: number\n // list\n listExpression?: string\n // random\n seed?: string\n randomCount?: number\n // modulo\n moduloDivisor?: string\n // predicate\n predicateField?: string\n predicateOp?: SelectorPredicateOp\n predicateValue?: string\n predicateMatch?: \"first\" | \"all\"\n predicateCaseSensitive?: boolean\n // named-key\n namedKeyField?: string\n namedKeyValue?: string\n}\n\n/** Result of a selector run. `picked ∪ rest = items`, `picked ∩ rest = ∅`. */\nexport type SelectorResult = { picked: string[]; rest: string[] }\n\n/**\n * Resolves a 1-based index expression to a 0-based array index.\n *\n * Supported expressions:\n * - \"1\", \"2\", ... — absolute 1-based index\n * - \"last\" — last element\n * - \"last-1\", \"last-2\", ... — relative from end\n *\n * Out-of-bounds values are clamped. Malformed input falls back to `defaultExpr`.\n */\nexport function resolveIndex(\n expr: string,\n listLength: number,\n defaultExpr: string = \"1\",\n): number {\n if (listLength <= 0) return 0\n\n const trimmed = expr.trim()\n let index: number\n\n if (trimmed === \"last\") {\n index = listLength - 1\n } else if (trimmed.startsWith(\"last-\")) {\n const offset = parseInt(trimmed.slice(5), 10)\n if (isNaN(offset) || offset < 0) return resolveIndex(defaultExpr === expr ? \"1\" : defaultExpr, listLength)\n index = listLength - 1 - offset\n } else {\n const n = parseInt(trimmed, 10)\n if (isNaN(n)) return resolveIndex(defaultExpr === expr ? \"1\" : defaultExpr, listLength)\n index = n - 1\n }\n\n return Math.max(0, Math.min(index, listLength - 1))\n}\n\n/**\n * Applies range and step slicing to a list of strings.\n *\n * `from` and `to` are 1-based index expressions (see `resolveIndex`).\n * `step` controls iteration direction and stride:\n * - positive step: forward iteration (from must be <= to)\n * - negative step: reverse iteration (from must be >= to)\n * - step 0 is treated as step 1\n *\n * Returns empty array if direction mismatches (e.g., from < to with negative step).\n */\nexport function applyRange(\n list: string[],\n from?: string,\n to?: string,\n step?: number,\n): string[] {\n if (list.length === 0) return []\n\n const fromIdx = resolveIndex(from ?? \"1\", list.length, \"1\")\n const toIdx = resolveIndex(to ?? \"last\", list.length, \"last\")\n const effectiveStep = step === 0 || step === undefined ? 1 : step\n\n if (effectiveStep > 0 && fromIdx > toIdx) return []\n if (effectiveStep < 0 && fromIdx < toIdx) return []\n\n const result: string[] = []\n if (effectiveStep > 0) {\n for (let i = fromIdx; i <= toIdx; i += effectiveStep) result.push(list[i])\n } else {\n for (let i = fromIdx; i >= toIdx; i += effectiveStep) result.push(list[i])\n }\n return result\n}\n\n/**\n * Migrates legacy `item:N` (0-based) outputMode to structured format.\n *\n * Legacy: `{ outputMode: \"item:0\" }` — 0-based index baked into mode string\n * New: `{ outputMode: \"item\", itemIndex: \"1\" }` — 1-based expression\n *\n * Returns the data unchanged if not a legacy item mode.\n */\nexport function migrateEdgeOutputMode(\n data: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (!data) return data\n\n const mode = data.outputMode as string | undefined\n if (!mode || !mode.startsWith(\"item:\")) return data\n\n const idx = parseInt(mode.split(\":\")[1], 10)\n return {\n ...data,\n outputMode: \"item\",\n itemIndex: String(isNaN(idx) ? 1 : idx + 1),\n }\n}\n\n/**\n * Builds the edge range label shown as a pill on the edge.\n * Examples:\n * - \"2..last-1 +2\" — range with step 2\n * - \"last..1 -1\" — reversed\n * - \"3\" — item mode, index 3\n * - undefined — \"last\" mode has no label\n */\nexport function buildRangeLabel(\n mode: string,\n rangeFrom?: string,\n rangeTo?: string,\n rangeStep?: number,\n itemIndex?: string,\n selectorMode?: SelectorMode,\n listExpression?: string,\n): string | undefined {\n return buildItemLabel(mode, rangeFrom, rangeTo, rangeStep, itemIndex, selectorMode, listExpression)\n}\n\n/** Internal: builds the item-side label (range / list / item / each). Mode \"last\" returns undefined. */\nfunction buildItemLabel(\n mode: string,\n rangeFrom?: string,\n rangeTo?: string,\n rangeStep?: number,\n itemIndex?: string,\n selectorMode?: SelectorMode,\n listExpression?: string,\n): string | undefined {\n if (mode === \"last\") return undefined\n\n if ((mode === \"each\" || mode === \"all\") && selectorMode === \"list\") {\n const trimmed = (listExpression ?? \"\").trim()\n if (trimmed === \"\") return undefined\n return truncateLabel(trimmed, 18)\n }\n\n if (mode === \"item\") return itemIndex || undefined\n\n const from = rangeFrom ?? \"1\"\n const to = rangeTo ?? \"last\"\n const step = rangeStep ?? 1\n const isDefaultRange = from === \"1\" && to === \"last\"\n const isDefaultStep = step === 1\n if (isDefaultRange && isDefaultStep) return undefined\n\n let label = `${from}..${to}`\n if ((mode === \"each\" || mode === \"all\") && !isDefaultStep) {\n label += step > 0 ? ` +${step}` : ` ${step}`\n }\n return label\n}\n\nfunction truncateLabel(s: string, maxLen: number): string {\n if (s.length <= maxLen) return s\n return s.slice(0, maxLen) + \"…\"\n}\n\n/**\n * Validates a list expression without resolving indices.\n * Used for live UI validation in the List tab input.\n *\n * Returns { ok: true } for empty/whitespace input — matches the\n * \"empty = all items\" runtime semantics.\n */\nexport function parseListExpression(\n expr: string,\n): { ok: true } | { ok: false; error: string } {\n const result = parseListTerms(expr.trim())\n return result.ok ? { ok: true } : { ok: false, error: result.error }\n}\n\n/** Internal: validates a single index token (\"1\", \"last\", \"last-3\"). */\nfunction isValidIndexToken(token: string): boolean {\n if (token === \"last\") return true\n if (/^[1-9]\\d*$/.test(token)) return true\n const m = /^last-(\\d+)$/.exec(token)\n if (m) return !isNaN(parseInt(m[1], 10))\n return false\n}\n\n/**\n * Parses a list expression and returns 0-based indices into the list,\n * in user-specified order. Preserves duplicates.\n *\n * Supported syntax:\n * <expr> := <term> (\",\" <term>)*\n * <term> := <index> | <index> \"..\" <index> (\":\" <step>)?\n * <index> := <number> | \"last\" | \"last-\" <number>\n * <step> := integer (0 coerced to 1)\n *\n * Clamps out-of-bounds indices. Malformed input logs a warning and\n * returns [0..listLength-1] (matches applyRange leniency).\n */\nexport function resolveListExpression(expr: string, listLength: number): number[] {\n if (listLength <= 0) return []\n const result = parseListTerms(expr.trim())\n if (!result.ok) {\n console.warn(\"[edge-range] invalid list expression:\", expr, \"—\", result.error)\n return indexRange(0, listLength - 1, 1)\n }\n if (result.terms.length === 0) return indexRange(0, listLength - 1, 1)\n\n const out: number[] = []\n for (const term of result.terms) {\n if (term.kind === \"index\") {\n out.push(resolveIndex(term.token, listLength))\n } else {\n const from = resolveIndex(term.from, listLength)\n const to = resolveIndex(term.to, listLength)\n for (const idx of indexRange(from, to, term.step)) out.push(idx)\n }\n }\n return out\n}\n\n/** Internal: inclusive index range with step. Returns [] if direction mismatches. */\nfunction indexRange(from: number, to: number, step: number): number[] {\n const out: number[] = []\n if (step > 0) {\n if (from > to) return []\n for (let i = from; i <= to; i += step) out.push(i)\n } else {\n if (from < to) return []\n for (let i = from; i >= to; i += step) out.push(i)\n }\n return out\n}\n\n/**\n * Dispatches to either applyRange() or resolveListExpression() based on\n * edgeData.selectorMode. Returns a new string[] containing the selected\n * subset of items — or `items` unchanged when the edge has no filter.\n */\nexport function selectListItems(\n items: string[],\n edgeData: SelectorFields | undefined,\n): string[] {\n if (items.length === 0) return []\n if (isDefaultSelectorConfig(edgeData)) return items\n if (edgeData?.selectorMode === \"list\") {\n const indices = resolveListExpression(edgeData.listExpression ?? \"\", items.length)\n return indices.map((i) => items[i])\n }\n return applyRange(items, edgeData?.rangeFrom, edgeData?.rangeTo, edgeData?.rangeStep)\n}\n\n/**\n * Returns true when edge data carries no active filter — empty/whitespace list\n * expression in list mode, or defaults (1..last, step 1) in range mode.\n * Callers can skip filtering entirely when this returns true.\n */\nexport function isDefaultSelectorConfig(edgeData: SelectorFields | undefined): boolean {\n if (!edgeData) return true\n if (edgeData.selectorMode === \"list\") {\n return ((edgeData.listExpression ?? \"\").trim()) === \"\"\n }\n const { from, to, step } = canonicalRange(edgeData)\n return from === \"1\" && to === \"last\" && step === 1\n}\n\nexport function describeEdgeBehavior(\n edgeData:\n | {\n outputMode?: string\n selectorMode?: SelectorMode\n listExpression?: string\n rangeFrom?: string\n rangeTo?: string\n rangeStep?: number\n itemIndex?: string\n }\n | undefined,\n): string {\n const mode = edgeData?.outputMode\n return buildBaseSentence(edgeData, mode)\n}\n\nfunction buildBaseSentence(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n mode: string | undefined,\n): string {\n if (mode === \"last\") return \"Passes the selected result.\"\n if (mode === \"item\") return buildItemSentence(edgeData)\n if (mode === \"each\") return buildEachSentence(edgeData)\n if (mode === \"all\") return buildAllSentence(edgeData)\n return \"Passes all items at once.\"\n}\n\nfunction buildItemSentence(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n): string {\n const canonical = canonicalItemIndex(edgeData?.itemIndex)\n return `Passes only ${itemModeForm(canonical)}.`\n}\n\nfunction buildEachSentence(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n): string {\n if (isDefaultSelectorConfig(edgeData)) return \"Runs the next node one by one, per item.\"\n if (edgeData?.selectorMode === \"list\") {\n const result = parseListTerms((edgeData.listExpression ?? \"\").trim())\n if (!result.ok) return \"Runs the next node one by one, per item.\"\n }\n const phrase = buildSelectionPhrase(edgeData)\n if (phrase.kind === \"empty-result\") {\n return \"Nothing selected — the next node won't run.\"\n }\n if (phrase.kind === \"single-index\") {\n return `Runs the next node only on ${phrase.itemModeForm}.`\n }\n return `Runs the next node once for ${phrase.text}.`\n}\n\nfunction buildAllSentence(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n): string {\n if (isDefaultSelectorConfig(edgeData)) return \"Passes all items at once.\"\n if (edgeData?.selectorMode === \"list\") {\n const result = parseListTerms((edgeData.listExpression ?? \"\").trim())\n if (!result.ok) return \"Passes all items at once.\"\n }\n const phrase = buildSelectionPhrase(edgeData)\n if (phrase.kind === \"empty-result\") {\n return \"Nothing selected — the next node will get an empty bundle.\"\n }\n if (phrase.kind === \"single-index\") {\n return `Passes only ${phrase.itemModeForm}.`\n }\n return `Passes ${phrase.text} at once.`\n}\n\ntype CanonicalRange = { from: string; to: string; step: number }\n\nfunction canonicalItemIndex(raw: string | undefined): string {\n const trimmed = (raw ?? \"\").trim()\n if (trimmed === \"\") return \"1\"\n if (!isValidIndexToken(trimmed)) return \"1\"\n return trimmed\n}\n\nfunction canonicalRange(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n): CanonicalRange {\n const from = ((edgeData?.rangeFrom ?? \"\").trim() || \"1\")\n const to = ((edgeData?.rangeTo ?? \"\").trim() || \"last\")\n const rawStep = edgeData?.rangeStep\n const step = rawStep === undefined || rawStep === 0 ? 1 : rawStep\n return { from, to, step }\n}\n\n\nfunction itemModeForm(canonical: string): string {\n if (canonical === \"1\") return \"the first item\"\n if (/^\\d+$/.test(canonical)) return `item ${canonical}`\n if (canonical === \"last\" || canonical === \"last-0\") return \"the last item\"\n const m = /^last-(\\d+)$/.exec(canonical)\n if (m) {\n const n = parseInt(m[1], 10)\n if (n === 1) return \"the second-to-last item\"\n if (n === 2) return \"the third-to-last item\"\n if (n === 3) return \"the fourth-to-last item\"\n return `the ${ordinal(n + 1)}-from-last item`\n }\n return \"the first item\"\n}\n\nfunction compactForm(canonical: string): string {\n if (/^\\d+$/.test(canonical)) return canonical\n if (canonical === \"last\" || canonical === \"last-0\") return \"the last one\"\n const m = /^last-(\\d+)$/.exec(canonical)\n if (m) {\n const n = parseInt(m[1], 10)\n if (n === 1) return \"the second-to-last\"\n if (n === 2) return \"the third-to-last\"\n if (n === 3) return \"the fourth-to-last\"\n return `the ${ordinal(n + 1)}-from-last`\n }\n return canonical\n}\n\nfunction ordinal(n: number): string {\n const absN = Math.abs(n)\n const lastTwo = absN % 100\n if (lastTwo >= 11 && lastTwo <= 13) return `${n}th`\n switch (absN % 10) {\n case 1: return `${n}st`\n case 2: return `${n}nd`\n case 3: return `${n}rd`\n default: return `${n}th`\n }\n}\n\ntype SelectionPhrase =\n | { kind: \"items\"; text: string }\n | { kind: \"single-index\"; itemModeForm: string }\n | { kind: \"empty-result\" }\n\nfunction buildSelectionPhrase(\n edgeData: Parameters<typeof describeEdgeBehavior>[0],\n): SelectionPhrase {\n if (edgeData?.selectorMode === \"list\") {\n return buildListSelectionPhrase((edgeData.listExpression ?? \"\").trim())\n }\n return buildRangeSelectionPhrase(canonicalRange(edgeData))\n}\n\nfunction indexKind(token: string): \"concrete\" | \"relative\" | \"invalid\" {\n if (/^[1-9]\\d*$/.test(token)) return \"concrete\"\n if (token === \"last\" || /^last-\\d+$/.test(token)) return \"relative\"\n return \"invalid\"\n}\n\nfunction relativeOffset(token: string): number {\n if (token === \"last\") return 0\n const m = /^last-(\\d+)$/.exec(token)\n return m ? parseInt(m[1], 10) : 0\n}\n\nfunction compareTokens(a: string, b: string): -1 | 0 | 1 | \"indeterminate\" {\n const ka = indexKind(a)\n const kb = indexKind(b)\n if (ka !== kb) return \"indeterminate\"\n if (ka === \"concrete\") {\n const na = parseInt(a, 10)\n const nb = parseInt(b, 10)\n return na < nb ? -1 : na > nb ? 1 : 0\n }\n if (ka === \"relative\") {\n const oa = relativeOffset(a)\n const ob = relativeOffset(b)\n return oa < ob ? 1 : oa > ob ? -1 : 0\n }\n return \"indeterminate\"\n}\n\nfunction buildRangeSelectionPhrase(r: CanonicalRange): SelectionPhrase {\n const { from, to, step } = r\n\n const cmp = compareTokens(from, to)\n if (cmp !== \"indeterminate\") {\n if (step > 0 && cmp === 1) return { kind: \"empty-result\" }\n if (step < 0 && cmp === -1) return { kind: \"empty-result\" }\n }\n\n if (cmp === 0) {\n return { kind: \"single-index\", itemModeForm: itemModeForm(from) }\n }\n\n const absStep = Math.abs(step)\n if (step === -1 && from === \"last\" && to === \"1\") {\n return { kind: \"items\", text: \"all items in reverse order\" }\n }\n\n let text = `items ${compactForm(from)} through ${compactForm(to)}`\n if (absStep === 1 && step < 0) {\n text += \" in reverse order\"\n } else if (absStep > 1 && step > 0) {\n text += ` (every ${ordinal(absStep)} item)`\n } else if (absStep > 1 && step < 0) {\n text += ` (every ${ordinal(absStep)} item, in reverse)`\n }\n return { kind: \"items\", text }\n}\n\ntype ListTerm =\n | { kind: \"index\"; token: string }\n | { kind: \"range\"; from: string; to: string; step: number }\n\ntype ParseResult =\n | { ok: true; terms: ListTerm[] }\n | { ok: false; error: string }\n\n/**\n * Core list-expression parser. Returns structured terms on success or a\n * specific error message on failure. Empty input → zero terms (not an error).\n * Error messages are surfaced unchanged in the edge-config tooltip, so they\n * must stay stable:\n * - \"Empty item between commas\"\n * - \"Invalid index: <token>\"\n * - \"Range missing endpoint: <term>\"\n * - \"Step must be an integer\"\n */\nfunction parseListTerms(expr: string): ParseResult {\n if (expr === \"\") return { ok: true, terms: [] }\n const terms: ListTerm[] = []\n const raw = expr.split(\",\")\n for (const rawTerm of raw) {\n const term = rawTerm.trim()\n if (term === \"\") return { ok: false, error: \"Empty item between commas\" }\n const rangeIdx = term.indexOf(\"..\")\n if (rangeIdx === -1) {\n if (!isValidIndexToken(term)) return { ok: false, error: `Invalid index: ${term}` }\n terms.push({ kind: \"index\", token: term })\n continue\n }\n const left = term.slice(0, rangeIdx).trim()\n const rightWithStep = term.slice(rangeIdx + 2).trim()\n if (left === \"\" || rightWithStep === \"\") {\n return { ok: false, error: `Range missing endpoint: ${term}` }\n }\n const colonIdx = rightWithStep.indexOf(\":\")\n const right = colonIdx === -1 ? rightWithStep : rightWithStep.slice(0, colonIdx).trim()\n const stepStr = colonIdx === -1 ? null : rightWithStep.slice(colonIdx + 1).trim()\n if (right === \"\") return { ok: false, error: `Range missing endpoint: ${term}` }\n if (!isValidIndexToken(left)) return { ok: false, error: `Invalid index: ${left}` }\n if (!isValidIndexToken(right)) return { ok: false, error: `Invalid index: ${right}` }\n let step = 1\n if (stepStr !== null) {\n if (!/^-?\\d+$/.test(stepStr)) return { ok: false, error: \"Step must be an integer\" }\n const parsed = parseInt(stepStr, 10)\n step = parsed === 0 ? 1 : parsed\n }\n terms.push({ kind: \"range\", from: left, to: right, step })\n }\n return { ok: true, terms }\n}\n\nfunction buildListSelectionPhrase(expr: string): SelectionPhrase {\n const result = parseListTerms(expr)\n if (!result.ok) return { kind: \"empty-result\" }\n if (result.terms.length === 0) return { kind: \"items\", text: \"items\" } // unreachable via callers; default-config catches empty\n\n const normalized = result.terms.map<ListTerm>((t) => {\n if (t.kind === \"range\") {\n const cmp = compareTokens(t.from, t.to)\n if (cmp === 0) return { kind: \"index\", token: t.from }\n }\n return t\n })\n\n if (normalized.length === 1 && normalized[0].kind === \"index\") {\n return { kind: \"single-index\", itemModeForm: itemModeForm(normalized[0].token) }\n }\n\n const rendered = normalized.map((t) => {\n if (t.kind === \"index\") return compactForm(t.token)\n let text = `${compactForm(t.from)} through ${compactForm(t.to)}`\n const absStep = Math.abs(t.step)\n if (absStep === 1 && t.step < 0) {\n if (t.from === \"last\" && t.to === \"1\") return \"all items in reverse\"\n text += \" in reverse\"\n } else if (absStep > 1 && t.step > 0) {\n text += ` (every ${ordinal(absStep)})`\n } else if (absStep > 1 && t.step < 0) {\n text += ` (every ${ordinal(absStep)}, in reverse)`\n }\n return text\n })\n\n let joined: string\n if (rendered.length === 1) {\n joined = rendered[0]\n } else if (rendered.length === 2) {\n joined = `${rendered[0]} and ${rendered[1]}`\n } else {\n const head = rendered.slice(0, -1).join(\", \")\n joined = `${head}, and ${rendered[rendered.length - 1]}`\n }\n return { kind: \"items\", text: `items ${joined}` }\n}\n\n/**\n * Run the selector against `items`. Returns the picked subset plus the\n * complement (`rest`). For modes that pick by index, `rest` is computed by\n * index exclusion (not value) so duplicate items are handled correctly.\n */\nexport function runSelector(items: string[], config: SelectorConfig): SelectorResult {\n if (items.length === 0) return { picked: [], rest: [] }\n\n switch (config.mode) {\n case \"item\": {\n const idx = resolveIndex(config.itemIndex ?? \"1\", items.length, \"1\")\n return splitByIndices(items, [idx])\n }\n case \"range\": {\n const indices = applyRangeIndices(items.length, config.rangeFrom, config.rangeTo, config.rangeStep)\n return splitByIndices(items, indices)\n }\n case \"list\": {\n const indices = resolveListExpression(config.listExpression ?? \"\", items.length)\n return splitByIndices(items, indices)\n }\n case \"random\":\n return selectRandom(items, config.randomCount ?? 1, config.seed)\n case \"modulo\":\n return selectByModulo(items, config.moduloDivisor)\n case \"predicate\":\n return selectByPredicate(items, config)\n case \"named-key\":\n return selectByNamedKey(items, config.namedKeyField, config.namedKeyValue)\n default:\n return { picked: [], rest: items.slice() }\n }\n}\n\n/**\n * Partition `items` into picked (indices ∈ pickedIndices, in their original\n * order in the source list) and rest (everything else). Deduplicates\n * `pickedIndices` so passing the same index twice doesn't double-count.\n */\nfunction splitByIndices(items: string[], pickedIndices: number[]): SelectorResult {\n const pickedSet = new Set(pickedIndices.filter((i) => i >= 0 && i < items.length))\n const picked: string[] = []\n const rest: string[] = []\n for (let i = 0; i < items.length; i++) {\n if (pickedSet.has(i)) picked.push(items[i])\n else rest.push(items[i])\n }\n return { picked, rest }\n}\n\n/**\n * Returns the indices that `applyRange` would pick. Extracted so `runSelector`\n * range mode can compute the exact picked-index set (`items.indexOf(value)`\n * would return the wrong duplicate when the list contains repeated values).\n */\nexport function applyRangeIndices(\n length: number,\n from?: string,\n to?: string,\n step?: number,\n): number[] {\n if (length === 0) return []\n const fromIdx = resolveIndex(from ?? \"1\", length, \"1\")\n const toIdx = resolveIndex(to ?? \"last\", length, \"last\")\n const effectiveStep = step === 0 || step === undefined ? 1 : step\n if (effectiveStep > 0 && fromIdx > toIdx) return []\n if (effectiveStep < 0 && fromIdx < toIdx) return []\n const result: number[] = []\n if (effectiveStep > 0) {\n for (let i = fromIdx; i <= toIdx; i += effectiveStep) result.push(i)\n } else {\n for (let i = fromIdx; i >= toIdx; i += effectiveStep) result.push(i)\n }\n return result\n}\n\n/** mulberry32 PRNG — deterministic given a seed (any 32-bit signed integer).\n *\n * TWIN WARNING: backend/src/providers/video/audio-fx.ts carries its own\n * private mulberry32 (cosmetically different — `>>> 0` seed masking — but the\n * same sequence). The two are deliberately INDEPENDENT and both frozen: the\n * audio-fx copy seeds every reverb impulse response that the committed\n * characterization goldens (and every customer's rendered reverb waveform)\n * are pinned to. Do NOT \"deduplicate\" them into one shared export or \"sync\"\n * one to match the other — a change to either sequence is a silent behavior\n * change in its domain. */\nfunction mulberry32(seed: number): () => number {\n let a = seed | 0\n return () => {\n a = (a + 0x6D2B79F5) | 0\n let t = a\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n}\n\n/** Hash a seed string to a 32-bit integer (FNV-1a variant). */\nfunction hashSeed(s: string): number {\n let h = 2166136261 | 0\n for (let i = 0; i < s.length; i++) {\n h ^= s.charCodeAt(i)\n h = Math.imul(h, 16777619)\n }\n return h\n}\n\n/**\n * Pick `count` items uniformly at random without replacement.\n * If `seed` is non-empty, the PRNG is seeded deterministically.\n * Otherwise `Math.random` is used (fresh randomness per call).\n */\nexport function selectRandom(items: string[], count: number, seed?: string): SelectorResult {\n if (items.length === 0) return { picked: [], rest: [] }\n const k = Math.max(0, Math.min(count, items.length))\n const rand = seed && seed.length > 0 ? mulberry32(hashSeed(seed)) : Math.random\n // Partial Fisher-Yates: shuffle the first k positions, pick those indices.\n const indices = items.map((_, i) => i)\n for (let i = 0; i < k; i++) {\n const j = i + Math.floor(rand() * (indices.length - i))\n ;[indices[i], indices[j]] = [indices[j], indices[i]]\n }\n return splitByIndices(items, indices.slice(0, k))\n}\n\n/**\n * Pick a single item at `divisor % items.length`. Non-numeric `divisor`\n * falls back to index 0. Caller is responsible for resolving any\n * `{NodeLabel}` template refs in `divisor` BEFORE calling this — see\n * `resolveSelectorRefs`.\n */\nexport function selectByModulo(items: string[], divisor: string | undefined): SelectorResult {\n if (items.length === 0) return { picked: [], rest: [] }\n const n = divisor ? Number.parseInt(divisor.trim(), 10) : NaN\n const safeN = Number.isFinite(n) ? n : 0\n const idx = ((safeN % items.length) + items.length) % items.length\n return splitByIndices(items, [idx])\n}\n\n/**\n * Pick items whose parsed JSON satisfies the predicate. `match: \"first\"`\n * (default) stops at the first hit; `\"all\"` collects every hit.\n *\n * Reuses the filter-list condition evaluator so operator semantics\n * (numeric coercion on `=`/`!=`, locale-aware ordering, case-sensitive\n * text ops) stay identical to the Filter List node.\n */\nexport function selectByPredicate(\n items: string[],\n config: SelectorConfig,\n): SelectorResult {\n if (items.length === 0) return { picked: [], rest: [] }\n // Default operator to \"=\" so the UI's visual default (selector-config.tsx\n // shows `op={config.predicateOp ?? \"=\"}`) matches runtime; first-time\n // predicate use without explicitly setting an operator used to silently\n // return picked=[].\n // predicateField is intentionally allowed to be empty/undefined —\n // evaluateCondition treats an empty path as \"compare against the whole\n // item\" (filter-condition.ts:161), matching the UI placeholder hint\n // \"blank = whole item\" on the field input.\n const op = config.predicateOp ?? \"=\"\n // Pass caseSensitive explicitly. evaluateCondition defaults undefined to\n // `true` (case-sensitive) to preserve legacy callers, but the selector\n // UI checkbox shows unchecked by default — so undefined config must map\n // to case-INsensitive at runtime to match what the user sees.\n const opts = { caseSensitive: config.predicateCaseSensitive ?? false }\n const matchAll = config.predicateMatch === \"all\"\n const cond = {\n id: \"selector-predicate\",\n field: config.predicateField ?? \"\",\n operator: op,\n value: config.predicateValue ?? \"\",\n valueType: \"static\" as const,\n }\n const matchedIndices: number[] = []\n for (let i = 0; i < items.length; i++) {\n const parsed = tryParseJson(items[i])\n const hit = evaluateCondition(parsed, items[i], cond, undefined, opts)\n if (hit) {\n matchedIndices.push(i)\n if (!matchAll) break\n }\n }\n return splitByIndices(items, matchedIndices)\n}\n\n/**\n * Shortcut for `predicate(op=\"=\", match=\"first\")` — pick the first item\n * whose `field` strictly equals `value`. Implemented as a thin wrapper\n * so the UI can offer a 2-field form (\"look up by name\") instead of the\n * full 4-field predicate form.\n */\nexport function selectByNamedKey(\n items: string[],\n field: string | undefined,\n value: string | undefined,\n): SelectorResult {\n return selectByPredicate(items, {\n mode: \"predicate\",\n predicateField: field,\n predicateOp: \"=\",\n predicateValue: value,\n predicateMatch: \"first\",\n })\n}\n\n/**\n * Returns a new SelectorConfig with `{NodeLabel}` refs and `{{trigger.*}}` /\n * `{{now}}` / `{{last_N_*:N}}` template tokens resolved in the four\n * template-aware fields: moduloDivisor, predicateValue, namedKeyValue, seed.\n * All other fields are passed through unchanged. Callers must build\n * `variables` via `buildConditionVariables` (or equivalent) BEFORE calling.\n *\n * Other selector fields (itemIndex, range/list expressions, randomCount, etc.)\n * are treated as literals — they have their own selector-lib syntax and are\n * not resolved against the variable space.\n *\n * Token resolution matches `resolveConditionValue` exactly (both reuse\n * `substituteTriggerTokens`) so the selector's `{{trigger.foo}}` semantics\n * stay in lockstep with filter-list / router conditions.\n *\n * Pure: returns a new object; the input config is not mutated.\n */\nexport function resolveSelectorRefs(\n config: SelectorConfig,\n triggerData: Record<string, unknown> | undefined,\n variables: ReadonlyMap<string, string>,\n): SelectorConfig {\n const resolve = (v: string | undefined): string | undefined => {\n if (v == null) return v\n const refsResolved = resolveNodeRefs(v, variables)\n return substituteTriggerTokens(refsResolved, triggerData)\n }\n return {\n ...config,\n moduloDivisor: resolve(config.moduloDivisor),\n predicateValue: resolve(config.predicateValue),\n namedKeyValue: resolve(config.namedKeyValue),\n seed: resolve(config.seed),\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/credit-identifiers.ts"],"names":["FLUX2_RES_MP","defaultResolutionFor","GPT_IMAGE_2_6_QUALITIES","GPT_IMAGE_2_6_DEFAULT_QUALITY","GPT_IMAGE_2_6_RESOLUTIONS","GPT_IMAGE_2_6_DEFAULT_RESOLUTION","isGptImage26I2i","T2I_TO_I2I_VARIANT","GPT_IMAGE_2_6_MAX_INPUT_IMAGES","isFlux2Model","isGptImage26Tiered","HIGH_QUALITY_PROVIDERS","TWO_K_RESOLUTION_PROVIDERS","RESOLUTION_2K_4K_TIERED_PROVIDERS","IDEOGRAM_PROVIDERS","autoAspectNeedsSourceImage","normalizeModelInput","snapToNearestDuration","pricedOutputDurationSec","isWan3Provider","normalizeWan3Resolution","isViduQ4Provider","normalizeViduQ4Resolution","isKling4Provider","normalizeKling4Resolution","canonicalVideoProvider","DURATION_PRICED_PROVIDERS","isVeoProvider","VEO_RESOLUTION_TIERED_PROVIDERS","isGeminiOmniProvider","isGeminiOmniPerSecondProvider","VIDEO_DURATION_TIERS","getVideoAudioCapability","AUDIO_ADDON_PROVIDERS","MODE_ADDON_PROVIDERS","RESOLUTION_VIDEO_REF_PRICING","MODEL_CATALOG","PRICING_DEFAULT_RESOLUTION","RESOLUTION_DURATION_PRICING","VIDEO_REF_RATE_PROVIDERS","isMinimaxH3Provider","normalizeMinimaxH3Resolution","normalizeVideoRequestParams","uiResolutionFill","VIDEO_DURATION_AUTO","MOTION_DURATION_TIERS"],"mappings":";;;;;;;;AA6EA,SAAS,kBAAA,CAAmB,OAAmB,UAAA,EAA6B;AAC1E,EAAA,MAAM,IAAA,GAAO,CAAC,CAAA,KAAc,CAAA,CAAE,QAAQ,SAAA,EAAW,EAAE,EAAE,IAAA,EAAK;AAC1D,EAAA,MAAM,MAAM,OAAO,UAAA,KAAe,QAAA,GAAW,IAAA,CAAK,UAAU,CAAA,GAAI,EAAA;AAChE,EAAA,IAAI,GAAA,KAAQ,IAAI,OAAO,GAAA;AAIvB,EAAA,MAAM,IAAA,GAAOA,8BAAA,CAAa,IAAA,CAAK,CAAC,CAAA,KAAM,OAAO,CAAC,CAAA,KAAM,MAAA,CAAO,GAAG,CAAC,CAAA;AAC/D,EAAA,OAAO,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ACJ,OAAA,EAAS,cAAA;AAAA,EACT,OAAA,EAAS,cAAA;AAAA,EACT,IAAA,EAAM,WAAA;AAAA,EACN,EAAA,EAAI;AACN","file":"chunk-OFL4UH6L.cjs","sourcesContent":["/**\n * Build composite credit model identifiers for variable pricing.\n * Shared between frontend and backend.\n */\n\nimport {\n HIGH_QUALITY_PROVIDERS,\n TWO_K_RESOLUTION_PROVIDERS,\n RESOLUTION_2K_4K_TIERED_PROVIDERS,\n IDEOGRAM_PROVIDERS,\n DURATION_PRICED_PROVIDERS,\n AUDIO_ADDON_PROVIDERS,\n MODE_ADDON_PROVIDERS,\n RESOLUTION_VIDEO_REF_PRICING,\n RESOLUTION_DURATION_PRICING,\n VEO_RESOLUTION_TIERED_PROVIDERS,\n VIDEO_DURATION_TIERS,\n pricedOutputDurationSec,\n snapToNearestDuration,\n PRICING_DEFAULT_RESOLUTION,\n MOTION_DURATION_TIERS,\n T2I_TO_I2I_VARIANT,\n isVeoProvider,\n isMinimaxH3Provider,\n isGeminiOmniProvider,\n isGeminiOmniPerSecondProvider,\n isWan3Provider,\n isViduQ4Provider,\n isKling4Provider,\n normalizeKling4Resolution,\n VIDEO_REF_RATE_PROVIDERS,\n normalizeMinimaxH3Resolution,\n normalizeWan3Resolution,\n normalizeViduQ4Resolution,\n getVideoAudioCapability,\n canonicalVideoProvider,\n} from \"./model-constants.js\"\nimport { isFlux2Model, FLUX2_RES_MP, type Flux2Model } from \"./flux2-pricing.js\"\nimport {\n GPT_IMAGE_2_6_DEFAULT_QUALITY,\n GPT_IMAGE_2_6_DEFAULT_RESOLUTION,\n GPT_IMAGE_2_6_MAX_INPUT_IMAGES,\n GPT_IMAGE_2_6_QUALITIES,\n GPT_IMAGE_2_6_RESOLUTIONS,\n isGptImage26I2i,\n isGptImage26Tiered,\n type GptImage26TieredModel,\n} from \"./gpt-image-2-6.js\"\nimport { VIDEO_DURATION_AUTO } from \"./video-duration-auto.js\"\nimport { uiResolutionFill } from \"./video-ui-defaults.js\"\nimport { MODEL_CATALOG, autoAspectNeedsSourceImage, normalizeModelInput, normalizeVideoRequestParams, defaultResolutionFor, type ModelInputAdjustment, type SourceImageSize } from \"./model-catalog.js\"\n\n/**\n * The megapixel tier a Flux 2 credit identifier is keyed on, for ANY incoming\n * `resolution` value.\n *\n * Flux 2 is the only family whose identifier INTERPOLATES the resolution\n * instead of matching it against a known set, and its callers are not\n * guaranteed to hand it a Flux 2 value:\n * - the multi-provider cost preview prices one node's data against EVERY\n * selected provider (`frontend/src/ee/hooks/use-providers-credits-sum.ts`),\n * so a node whose `resolution` is \"2K\" (the flux / nano-banana-pro value\n * space) reaches this branch verbatim;\n * - node data written straight into workflow JSON by an agent, an import or\n * a template never ran the config panel's provider-change fail-safe.\n * Interpolating that produced the off-grid id `flux-2-pro:2KMP:0ref`, which no\n * pricing row can answer — every cost badge 503'd `price_not_configured`\n * (18 production app-reports, 2026-09-07..14).\n *\n * A value off the grid snaps to the model's DEFAULT tier — the same `preferred`\n * value `normalizeModelInput` uses — so the preview asks for exactly the id the\n * route will reserve (both routes and the orchestrator normalize through\n * `resolveNormalizedImageGen` first, which makes this snap a no-op for them).\n * An ABSENT resolution keeps its long-standing meaning (\"this caller has no\n * resolution dimension at all\") and stays on 1 MP rather than moving to the\n * model default, which would silently re-price every resolution-less node.\n */\nfunction flux2MegapixelTier(model: Flux2Model, resolution?: string): string {\n const bare = (v: string) => v.replace(/\\s*MP$/i, \"\").trim()\n const raw = typeof resolution === \"string\" ? bare(resolution) : \"\"\n if (raw === \"\") return \"1\"\n // Numeric match so \"2.0\"/\" 2 MP\" land on the same grid point as \"2\", and the\n // GRID's own spelling is what gets emitted — returning the caller's \"2.0\"\n // would build \":2.0MP:\", another id no pricing row carries.\n const tier = FLUX2_RES_MP.find((t) => Number(t) === Number(raw))\n return tier ?? bare(defaultResolutionFor(model) ?? \"1 MP\")\n}\n\n/**\n * The price id of a GPT Image 2.6 Flare or Sunburst run: `<id>:<quality>:<size>`,\n * and on an edit `<id>:<quality>:<size>:<N>ref`, N being the input images.\n *\n * A value off the grid (a stored node, the multi-provider preview pricing one\n * node's data against every model) lands on the default rather than building\n * an id no row answers. A text-to-image id sent input images runs on the edit\n * endpoint, so a caller that does not swap the model first (the entity routes,\n * a pipeline pin) is priced there too. An edit always has at least its source.\n */\nfunction gptImage26CreditId(\n provider: GptImage26TieredModel,\n quality: string | undefined,\n resolution: string | undefined,\n referenceImageCount: number | undefined,\n): string {\n const q = (GPT_IMAGE_2_6_QUALITIES as readonly string[]).includes(quality ?? \"\") ? quality : GPT_IMAGE_2_6_DEFAULT_QUALITY\n const r = (GPT_IMAGE_2_6_RESOLUTIONS as readonly string[]).includes(resolution ?? \"\") ? resolution : GPT_IMAGE_2_6_DEFAULT_RESOLUTION\n const images = Math.trunc(referenceImageCount ?? 0)\n const model = !isGptImage26I2i(provider) && images > 0 ? T2I_TO_I2I_VARIANT[provider]! : provider\n if (!isGptImage26I2i(model)) return `${model}:${q}:${r}`\n return `${model}:${q}:${r}:${Math.min(Math.max(1, images), GPT_IMAGE_2_6_MAX_INPUT_IMAGES)}ref`\n}\n\n/**\n * Compute composite model identifier for variable credit pricing.\n * Examples: \"gpt-image:high\", \"flux:2K\", \"nano-banana-pro:4K\", \"ideogram:TURBO\",\n * \"flux-2-pro:2MP\", \"flux-2-max:2MP:1ref\" (Flux 2 — billed per megapixel).\n *\n * For image models, uses quality/resolution/renderingSpeed and (Flux 2) the output\n * megapixel count plus (Flux 2 Max) the number of reference images attached at request time.\n * For video models, uses duration/sound params when the model has variable pricing.\n */\nexport function buildCreditModelIdentifier(\n provider: string,\n quality?: string,\n resolution?: string,\n renderingSpeed?: string,\n targetResolution?: string,\n referenceImageCount?: number,\n): string {\n // Flux 2 family: billed per output megapixel AND per reference image (each\n // ref counts as input megapixels). Resolution arrives as \"N MP\" strings (the\n // UI value space); strip the unit. ALL three models encode the ref count\n // (capped at 8): Pro/Klein i2i always carry the source image as a ref and\n // their cost formula charges per input MP, so the reserved identifier must\n // reflect refs (there is no metered true-up to correct an under-reserved tier).\n if (isFlux2Model(provider)) {\n return `${provider}:${flux2MegapixelTier(provider, resolution)}MP:${Math.min(referenceImageCount ?? 0, 8)}ref`\n }\n if (isGptImage26Tiered(provider)) {\n return gptImage26CreditId(provider, quality, resolution, referenceImageCount)\n }\n if (HIGH_QUALITY_PROVIDERS.has(provider) && quality === \"high\") {\n return `${provider}:high`\n }\n if (TWO_K_RESOLUTION_PROVIDERS.has(provider) && resolution === \"2K\") {\n return `${provider}:2K`\n }\n if (provider === \"nano-banana-pro\" && resolution === \"4K\") {\n return `${provider}:4K`\n }\n if (RESOLUTION_2K_4K_TIERED_PROVIDERS.has(provider) && (resolution === \"2K\" || resolution === \"4K\")) {\n return `${provider}:${resolution}`\n }\n // Topaz Image Upscale: 2K is default (no suffix), 4K/8K get composite identifiers\n if (provider === \"topaz-image-upscale\" && targetResolution && targetResolution !== \"2K\") {\n return `${provider}:${targetResolution}`\n }\n if (IDEOGRAM_PROVIDERS.has(provider)) {\n if (renderingSpeed === \"TURBO\") return `${provider}:TURBO`\n if (renderingSpeed === \"QUALITY\") return `${provider}:QUALITY`\n }\n return provider\n}\n\n/**\n * An image request's catalog-snapped parameters PLUS the credit identifier\n * priced off them.\n *\n * `adjustments` is the disclosure channel: every lever this changed, why, and\n * to what. Routes return it in the 200 body so a caller learns their value was\n * corrected instead of silently getting something else.\n */\nexport interface NormalizedImageGen {\n /** Credit identifier, priced off the SNAPPED `resolution` / `quality`. */\n identifier: string\n /** The catalog model id the params were snapped against (post T2I→I2I swap). */\n modelId: string\n aspectRatio?: string\n resolution?: string\n quality?: string\n background?: string\n /** Empty when the caller's values were already valid for `modelId`. */\n adjustments: ModelInputAdjustment[]\n}\n\n/**\n * The catalog model `resolveNormalizedImageGen` snaps against: the provider\n * (Nano Banana when none is named), or — with `swapToI2i` and references\n * attached — its i2i sibling, the model the generate-image route and the\n * workflow payload builder then send. That sibling has its OWN catalog entry\n * and lever lists. Exported so a caller that has to decide something about\n * those lists before the snap (whether a photo's size is worth reading) asks\n * about the same model the snap will use.\n */\nexport function normalizedImageGenModelId(opts: {\n provider: unknown\n refCount: number\n swapToI2i?: boolean\n}): string {\n const provider = typeof opts.provider === \"string\" && opts.provider.length > 0 ? opts.provider : \"nano-banana\"\n return opts.swapToI2i && opts.refCount > 0 ? (T2I_TO_I2I_VARIANT[provider] ?? provider) : provider\n}\n\n/**\n * Whether \"auto\" on a Generate Image request can need its photo's size: the\n * model the snap runs against (`normalizedImageGenModelId` with the swap on)\n * has no native auto. Given the ASSEMBLED reference count, it asks about exactly\n * that model; without one — a write boundary, or a run before its references\n * assemble — about both the provider and its i2i sibling, since references may\n * yet attach.\n */\nexport function imageGenAutoAspectNeedsSourceImage(opts: {\n provider: unknown\n aspectRatio: unknown\n refCount?: number\n}): boolean {\n const asks = (refCount: number) =>\n autoAspectNeedsSourceImage(normalizedImageGenModelId({ provider: opts.provider, refCount, swapToI2i: true }), opts.aspectRatio)\n return opts.refCount === undefined ? asks(0) || asks(1) : asks(opts.refCount)\n}\n\n/**\n * Snap an image request's catalog-governed levers to a combination the model\n * actually accepts, and price the credit identifier off the SNAPPED values.\n *\n * WHY THE SNAP LIVES HERE and not at the call site. Both image routes compute\n * their credit identifier TWICE — once in the `creditGuard` preHandler (the\n * CHECK) and once at the handler's `reserveCreditsForJob` (the DEBIT) — and a\n * dedicated test asserts the two stay byte-identical (see\n * `backend/src/routes/__tests__/generate-image.test.ts`, \"CHECK === DEBIT\").\n * `resolution` and `quality` are pricing dimensions, so a snap applied at only\n * one of those sites breaks that invariant, and `commit_credits` never collects\n * an upward delta — the reserve IS the charge. Putting the snap inside the\n * primitive makes CHECK, DEBIT and the workflow orchestrator agree by\n * construction rather than by everyone remembering to call a normalizer.\n *\n * Inputs are typed `unknown` on purpose: the preHandler runs BEFORE Zod, so a\n * caller can put a number or an object in `resolution`. Non-strings become\n * `undefined` rather than reaching `normalizeModelInput` as a lie.\n *\n * Unknown model ids pass through untouched (same contract as\n * `normalizeModelInput`) — the route's provider enum is the gate for those.\n *\n * `sourceImage` is the size of the photo the request transforms or is drawn\n * from (an image-to-image / edit source, or Generate Image's first wired\n * reference). It only decides \"auto\" on a model without a native auto, and the\n * ratio is not a pricing dimension on any such model (pinned across the catalog\n * by `auto-aspect-source.test.ts`), so a CHECK that runs before the size is\n * known prices the same identifier as the DEBIT that knows it.\n */\nexport function resolveNormalizedImageGen(opts: {\n provider: string | undefined\n aspectRatio?: unknown\n quality?: unknown\n resolution?: unknown\n renderingSpeed?: unknown\n /** Does not price on its own, but a transparent background can move the size. */\n background?: unknown\n refCount: number\n swapToI2i?: boolean\n sourceImage?: SourceImageSize\n}): NormalizedImageGen {\n const str = (v: unknown): string | undefined =>\n typeof v === \"string\" && v.length > 0 ? v : undefined\n\n const modelId = normalizedImageGenModelId(opts)\n\n const n = normalizeModelInput(\n modelId,\n {\n aspectRatio: str(opts.aspectRatio),\n resolution: str(opts.resolution),\n quality: str(opts.quality),\n background: str(opts.background),\n },\n { sourceImage: opts.sourceImage },\n )\n\n return {\n identifier: buildCreditModelIdentifier(\n modelId,\n n.quality,\n n.resolution,\n str(opts.renderingSpeed),\n undefined,\n opts.refCount,\n ),\n modelId,\n aspectRatio: n.aspectRatio,\n resolution: n.resolution,\n quality: n.quality,\n background: n.background,\n adjustments: n.adjustments,\n }\n}\n\n/**\n * Reference-aware image-generation credit identifier — the SINGLE source of\n * truth shared by the single-node routes (`/v1/generate-image`,\n * `/v1/image-to-image`) and the workflow orchestrator\n * (`payload-builder.ts`). It centralises the two pricing dimensions that must\n * match across both paths or a Flux 2 generation is billed the wrong tier\n * (Flux 2 commits non-metered / has no upward true-up, so the reserved\n * identifier IS the final charge):\n * - `refCount`: the number of reference images sent to the provider (Flux 2\n * bills per ref). generate-image passes the assembled count (0 for pure\n * text-to-image); image-to-image passes 1 (the primary `imageUrl`) + extras.\n * - `swapToI2i`: generate-image auto-swaps a bare T2I provider to its i2i\n * sibling (`T2I_TO_I2I_VARIANT`) when refs are attached, so the credit id\n * matches the variant actually invoked. image-to-image is already an i2i\n * provider → pass `false`.\n *\n * The LoRA short-circuit (`flux-lora-character`) stays at the call site because\n * the routing decision needs a DB lookup the routes/orchestrator own.\n */\nexport function resolveImageGenCreditIdentifier(opts: {\n provider: string | undefined\n quality?: string\n resolution?: string\n renderingSpeed?: string\n refCount: number\n swapToI2i?: boolean\n}): string {\n return resolveNormalizedImageGen(opts).identifier\n}\n\n// T2V-specific credit overrides: some providers have different costs for T2V\n// vs I2V/V2V due to different default resolutions or colliding with image model names.\nconst T2V_CREDIT_OVERRIDES: Record<string, string> = {\n \"grok\": \"grok-i2v\", // T2V grok, same as I2V grok (not image grok = 4 cr)\n \"wan\": \"wan-t2v\", // T2V wan 1080p = (V2V wan 720p = 70 cr)\n \"wan-turbo\": \"wan-turbo-t2v\", // T2V wan-turbo 720p = (I2V wan-turbo 480p = 40 cr)\n}\n\n/**\n * Compute composite model identifier for video models with duration/audio-based pricing.\n * Examples: \"kling-3.0:5s\", \"kling-3.0:10s:audio\", \"seedance-2:8s:720p-ref\"\n *\n * @param provider - Video model key (e.g., \"kling-3.0\")\n * @param duration - Video duration in seconds\n * @param sound - Whether audio/sound is enabled\n * @param nodeType - Node type for T2V-specific cost overrides\n * @param mode - Quality variant that affects pricing\n * @param resolution - Output resolution (used by Seedance 2 for 480p/720p pricing)\n * @param hasVideoRef - Whether a reference video is connected (Seedance 2 uses a lower per-second rate when true)\n */\n/**\n * LTX 2.3 (Lightricks via Replicate) credit tiers: priced by\n * (resolution-band × duration-seconds). Keys mirror STATIC_CREDIT_COSTS /\n * model_pricing EXACTLY (lowercase band + raw seconds + \"s\"), e.g.\n * \"ltx-2.3-pro:1080p:6s\". This map is the source of truth for the nearest-tier\n * snap below, so an off-catalog (resolution, duration) from a direct API/SDK\n * call maps to a SEEDED price instead of hard-failing (price_not_configured\n * 503). Pro: 6/8/10s at every band. Fast: up to 20s at 1080p, 6/8/10s at 2k/4k.\n */\nconst LTX_DURATION_TIERS: Record<string, Record<string, number[]>> = {\n \"ltx-2.3-pro\": { \"1080p\": [6, 8, 10], \"2k\": [6, 8, 10], \"4k\": [6, 8, 10] },\n \"ltx-2.3-fast\": { \"1080p\": [6, 8, 10, 12, 14, 16, 18, 20], \"2k\": [6, 8, 10], \"4k\": [6, 8, 10] },\n}\n\n/**\n * The (band, duration) tier the LTX pricing ladder charges for a request, or\n * `undefined` for a non-LTX provider. Extracted so\n * `buildVideoCreditModelIdentifier` and `pricedVideoSelection` read the ladder\n * ONCE — the routes must send the tier they reserved, and a second copy of this\n * math is exactly how the two drift apart.\n *\n * An unknown/absent band falls back to 1080p (LTX's own default, and the band\n * `snapLtxInput` snaps to at the Replicate call), and an off-tier duration\n * snaps to the NEAREST seeded one so the emitted composite always prices.\n */\nfunction ltxPricedTier(\n provider: string,\n resolution?: string,\n duration?: number | string,\n): { band: string; duration: number } | undefined {\n const bands = LTX_DURATION_TIERS[provider]\n if (!bands) return undefined\n const band = bands[String(resolution)] ? String(resolution) : \"1080p\"\n const allowed = bands[band]!\n // The model's own default (catalog `defaultDuration`) when unset, then the\n // nearest rung of THIS band's ladder — the length LTX renders.\n const dur = snapToNearestDuration(pricedOutputDurationSec(provider, duration), allowed)\n return { band, duration: dur }\n}\n\n/**\n * The resolution a provider whose runner NORMALIZES the lever actually renders,\n * in the lowercase spelling of its credit composites — billing collapses\n * through the very normalizer the runner sends, so render == billed for every\n * spelling. `undefined` passes through untouched for every other provider.\n */\nfunction wireNormalizedResolution(provider: string, resolution: string | undefined): string | undefined {\n if (isWan3Provider(provider)) return normalizeWan3Resolution(resolution).toLowerCase()\n if (isViduQ4Provider(provider)) return normalizeViduQ4Resolution(resolution)\n if (isKling4Provider(provider)) return normalizeKling4Resolution(resolution)\n return resolution\n}\n\nexport function buildVideoCreditModelIdentifier(\n rawProvider: string,\n duration?: number | string,\n sound?: boolean,\n nodeType?: \"image-to-video\" | \"text-to-video\",\n mode?: string,\n resolution?: string,\n hasVideoRef?: boolean,\n): string {\n // A retired model (RETIRED_VIDEO_PROVIDERS) is priced as the model it runs as.\n const provider = canonicalVideoProvider(rawProvider) as string\n // T2V overrides: some providers have different base costs for text-to-video\n let effectiveProvider = provider\n if (nodeType === \"text-to-video\") {\n const override = T2V_CREDIT_OVERRIDES[provider]\n if (override) {\n // If override target also has duration pricing, use it as effective provider\n if (DURATION_PRICED_PROVIDERS.has(override)) {\n effectiveProvider = override\n } else {\n return override\n }\n }\n }\n\n // VEO 3.x resolution-tiered pricing: 720p is the base (no suffix), 1080p gets\n // \":1080p\" (Fast/Lite only), and 4K gets \":4k\" for ALL three tiers — direct-4K\n // generation chains KIE's get-4k-video off the base generation (the base runs\n // at 1080p). Duration is fixed at 8s for VEO so the duration-tier path below\n // does not apply.\n if (isVeoProvider(effectiveProvider)) {\n if (resolution === \"4k\") return `${effectiveProvider}:4k`\n // 1080p tier is Fast/Lite only (Quality has no 1080p surcharge).\n if (resolution === \"1080p\" && VEO_RESOLUTION_TIERED_PROVIDERS.has(effectiveProvider)) return `${effectiveProvider}:1080p`\n return effectiveProvider\n }\n\n // Gemini Omni family (gemini-omni-video + gemini-omni-flash): priced by\n // (resolution-band × duration), with a flat per-generation rate when a source\n // video is supplied (V2V). Lowercase \"4k\". The prefix is TEMPLATED from the\n // provider id, so a further Omni SKU needs no edit here — it only has to join\n // GEMINI_OMNI_PROVIDERS and seed its rows. These models are deliberately NOT\n // in DURATION_PRICED_PROVIDERS; this branch early-returns before that gate.\n // A per-second SKU (Omni Flash 1.2) prices on the `:<N>s:<res>` ladder below.\n if (isGeminiOmniProvider(effectiveProvider) && !isGeminiOmniPerSecondProvider(effectiveProvider)) {\n if (hasVideoRef) {\n return resolution === \"4k\" ? `${effectiveProvider}:4k:vref` : `${effectiveProvider}:vref`\n }\n // The rendered length through the catalog funnel (nearest legal tier, the\n // model's own default when unset) so the composite is always a SEEDED one.\n const d = pricedOutputDurationSec(effectiveProvider, duration)\n return resolution === \"4k\" ? `${effectiveProvider}:4k:${d}` : `${effectiveProvider}:${d}`\n }\n\n // LTX 2.3: priced by (resolution-band × duration-seconds). The RESERVE must be\n // the correct composite — commit_credits (migration 176) only refunds a surplus\n // (actual < reserved) and NEVER collects an upward delta, so an under-reserved\n // LTX run (the bare-id default = cheapest 1080p:6s tier) stays under-charged\n // even with meteredCost:true. Snap to a seeded tier so the id always prices.\n const ltxTier = ltxPricedTier(effectiveProvider, resolution, duration)\n if (ltxTier) {\n return `${effectiveProvider}:${ltxTier.band}:${ltxTier.duration}s`\n }\n\n if (!DURATION_PRICED_PROVIDERS.has(effectiveProvider)) {\n return effectiveProvider\n }\n\n // A named-provider request with NO duration renders the model's own default\n // (kie/models.ts extraParams), so price that default — not the global 5s —\n // for providers whose per-second tiers wouldn't snap 5 up to it\n // (minimax-h3, seedance-2-5). One helper, shared with the dynamic\n // reference-video reservations, so the tier and the scaled reserve agree.\n const durationSec = pricedOutputDurationSec(effectiveProvider, duration)\n const tiers = VIDEO_DURATION_TIERS[effectiveProvider]\n if (!tiers) return effectiveProvider\n\n // Find the matching duration tier\n const tier = tiers.find(t => durationSec <= t.maxSeconds) ?? tiers[tiers.length - 1]\n let identifier = `${effectiveProvider}:${tier.suffix}`\n\n // Append audio suffix if applicable. When the caller expressed no intent\n // (sound === undefined), fall back to the model's own default (capability\n // `defaultOn` — kling-3.0 generates audio unless explicitly disabled), so an\n // intent-less request is billed for the audio it actually produces instead\n // of reserving the cheaper no-audio tier against an audio-on generation.\n const soundOn = sound ?? (getVideoAudioCapability(effectiveProvider).defaultOn === true)\n if (AUDIO_ADDON_PROVIDERS.has(effectiveProvider) && soundOn) {\n identifier += \":audio\"\n }\n\n // Append mode suffix for providers with quality-tiered pricing\n // \"high\" comes from I2V videoSize field, \"pro\" comes from T2V mode field\n if (MODE_ADDON_PROVIDERS.has(effectiveProvider) && (mode === \"high\" || mode === \"pro\")) {\n identifier += \":high\"\n }\n\n // Seedance 2.0 family: per-second billing with resolution + video-ref dimensions.\n // KIE accepts 480p / 720p / 1080p natively; per-second rates rise non-linearly\n // so each tier gets its own composite identifier.\n if (RESOLUTION_VIDEO_REF_PRICING.has(effectiveProvider)) {\n // Clamp to the model's catalog resolutions (single source of truth): e.g.\n // seedance-2-mini exposes only 480p/720p, so a stale/explicit 1080p (or 4k)\n // maps to its top priced tier instead of emitting an unpriced composite\n // (which the hard-fail credit guard would 503 on at runtime).\n const supported = MODEL_CATALOG[effectiveProvider]?.resolutions ?? [\"480p\", \"720p\", \"1080p\"]\n // An OMITTED resolution renders the model's KIE-side default, so price that\n // default rather than the cheapest tier — otherwise an intent-less request\n // reserves 480p against a 720p render and commit_credits (refund-only) can\n // never collect the delta. Providers without an entry keep the historical\n // 480p fallback, so this cannot reprice anything already live.\n const requested = resolution ?? PRICING_DEFAULT_RESOLUTION[effectiveProvider]\n const want = requested === \"4k\" ? \"4k\" : requested === \"1080p\" ? \"1080p\" : requested === \"720p\" ? \"720p\" : \"480p\"\n // Unsupported (e.g. a stale 1080p on seedance-2-mini) clamps to the model's\n // top priced tier so the emitted composite is always seeded.\n const res = supported.includes(want) ? want : (supported[supported.length - 1] ?? \"480p\")\n identifier += `:${res}`\n if (hasVideoRef) identifier += \"-ref\"\n }\n\n // Duration × resolution pricing without a -ref dimension. Resolutions\n // outside the provider's priced tiers (or undefined) collapse to the first\n // (default) tier so the emitted composite is always seeded — the hard-fail\n // guard fuzzes the whole resolution space.\n const resTiers = RESOLUTION_DURATION_PRICING[effectiveProvider]\n if (resTiers) {\n // The \"default tier\" is the provider's DECLARED default when it has one\n // (PRICING_DEFAULT_RESOLUTION — wan-3 renders 720p, not the cheapest tier),\n // otherwise the first listed tier. Declaring it explicitly means a cosmetic\n // reorder of the tier list can never reprice a live model, and an OMITTED\n // *or* unsupported resolution both land on what actually renders instead of\n // on the cheapest row (commit_credits refunds a surplus but can never\n // collect a shortfall). Behaviour-neutral for every member without a\n // declared default.\n const declaredDefault = PRICING_DEFAULT_RESOLUTION[effectiveProvider]\n const fallback = declaredDefault && resTiers.includes(declaredDefault) ? declaredDefault : resTiers[0]!\n // Wan 3.0 renders through `normalizeWan3Resolution`, which is CASE-INSENSITIVE\n // (\"1080P\" — KIE's own OpenAPI enum spelling, and the natural value for an\n // integrator reading the provider docs — renders 1080P). The tier list here is\n // lowercase and `Array.includes` is case-sensitive, so without this the render\n // path and the billing path disagree: \"1080P\" rendered the top tier and billed\n // the 720p row, a shortfall `commit_credits` (refund-only) can never collect.\n // Collapsing through the SAME normalizer the runner uses makes render == billed\n // by construction for every spelling, including garbage (→ the declared 720p).\n // Scoped to the families whose runner normalizes on purpose (Wan 3.0, Vidu\n // Q4): the other RESOLUTION_DURATION_PRICING members pass `resolution` to\n // their wire verbatim, so case-folding their billing without probing their\n // wire would reprice live models.\n const requested = wireNormalizedResolution(effectiveProvider, resolution)\n const res = requested && resTiers.includes(requested) ? requested : fallback\n identifier += `:${res}`\n // A reference VIDEO bills at its own per-second rate (Kling 4.0).\n if (hasVideoRef && VIDEO_REF_RATE_PROVIDERS.has(effectiveProvider)) identifier += \"-ref\"\n }\n\n // MiniMax Hailuo 3 (768P lever, 2026-08-03): bare duration composites stay\n // the 2K (default) rate — byte-identical to the pre-lever seeded rows, so\n // existing workflows and admin overrides keep their ids — and only a\n // verified 768P selection appends \":768p\". normalizeMinimaxH3Resolution\n // collapses anything else to 2K, matching what KIE renders for an\n // omitted/unknown value, so billing can never undercut the render.\n if (isMinimaxH3Provider(effectiveProvider) && normalizeMinimaxH3Resolution(resolution) === \"768P\") {\n identifier += \":768p\"\n }\n\n return identifier\n}\n\n/**\n * The credit identifier a video GENERATION node is quoted at — Generate Video\n * (and the legacy Image/Text to Video nodes) and the Video to Video Seedance\n * edit lane, on every surface that quotes one: the node's cost pill, the\n * editor's run estimate, the prompt modal and the backend pre-run estimator.\n *\n * It applies the request levers the run applies BEFORE it prices\n * (payload-builder's `resolveVideoRequestNorm`): the model's UI resolution fill\n * when the node names none (`uiResolutionFill` — what the run sends), then the\n * catalog normalizer `normalizeVideoRequestParams`, which also owns the Seedance\n * Draft rule (a draft is priced AND sent at 480p whatever resolution came with\n * it). Without that, a node with no resolution was quoted at the identifier's\n * own default band (720p on Seedance 2.5) while the run sent and reserved 480p.\n *\n * `hasVideoRef` must come from the GRAPH (a wired reference-video edge, e.g.\n * `countRefModalityEdges(edges, id, \"video\") > 0`), never node data: nothing\n * writes `referenceVideoUrls` into a video node, so reading it there always\n * quoted the plain ladder for a run that reserves on the `-ref` one.\n */\nexport function videoGenerationCreditId(args: {\n provider: string\n duration?: number | string\n sound?: boolean\n nodeType?: \"image-to-video\" | \"text-to-video\"\n mode?: string\n resolution?: string\n draft?: boolean\n hasVideoRef?: boolean\n}): string {\n const { resolution } = normalizeVideoRequestParams(args.provider, {\n resolution: args.resolution ?? uiResolutionFill(args.provider),\n draft: args.draft === true,\n })\n return buildVideoCreditModelIdentifier(\n args.provider,\n args.duration,\n args.sound,\n args.nodeType ?? \"image-to-video\",\n args.mode,\n resolution,\n args.hasVideoRef === true,\n )\n}\n\n/**\n * The credit identifier a Video to Video node's Seedance EDIT lane reserves\n * under. Seedance has no v2v endpoint — the lane is a text-to-video job in edit\n * shape with the source clip as reference video 1 — so it prices on the\n * REFERENCE-VIDEO ladder at the model's LONGEST clip (Auto duration), and the\n * measured settlement refunds down to what was actually delivered.\n *\n * A thin call into {@link videoGenerationCreditId}, so a Generate Video node\n * making the same KIE call (Seedance, Auto, a wired reference video) is quoted\n * the same id. FOUR surfaces must agree on it exactly: the orchestrator's\n * reservation (payload-builder.ts), the backend pre-run estimator\n * (ee/billing/credits.ts), the node's cost pill, and the frontend run-level\n * estimate (config-panels/helpers.ts). A quote that disagrees with the reserve\n * is the documented `price_not_configured` / blank-pill trap.\n *\n * `resolution` is the node's one `v2vResolution` field; when unset the model's\n * own UI fill is priced, which is what the lane will send. `draft` is the\n * node's Seedance Draft toggle (priced at 480p).\n */\nexport function seedanceVideoEditCreditId(provider: string, resolution?: string, draft?: boolean): string {\n return videoGenerationCreditId({\n provider,\n duration: VIDEO_DURATION_AUTO,\n nodeType: \"text-to-video\",\n resolution,\n draft,\n hasVideoRef: true,\n })\n}\n\n/** What the video credit identifier PRICES for a request, for the levers whose\n * priced value must also be the value we SEND. */\nexport interface PricedVideoSelection {\n /** The resolution band the reservation is priced at when the request omitted\n * one — and only where the platform DECLARES that band as the provider's own\n * default. `undefined` means \"leave `resolution` exactly as the request had\n * it\": either the caller supplied one, or the provider's real default is not\n * known to be the band the identifier assumes. */\n resolution?: string\n /** The length the reservation is priced at and the wire carries, for a\n * provider whose price follows the clip length (LTX's seeded tier, the KIE\n * ladders, Gemini Omni). `undefined` for every other provider, and for Auto:\n * their duration passes through. */\n duration?: number\n /** Non-empty only for a lever the caller ASKED for and did not get (a 7s\n * request snapped to the 6s tier). Filling an omitted lever is a disclosure of\n * the price already being charged, not a correction, so it reports nothing. */\n adjustments: ModelInputAdjustment[]\n}\n\n/**\n * The other half of the video money path: `normalizeVideoRequestParams` snaps a\n * value the CATALOG governs; this returns the value the PRICE ladder governs.\n *\n * Two defects it closes, both of the same shape — the identifier prices one\n * thing and the wire carries another, and `commit_credits` (migration 176) only\n * ever refunds a surplus, so the reservation is the final charge:\n *\n * 1. **Absent resolution.** `buildVideoCreditModelIdentifier` prices an omitted\n * `resolution` as a concrete band (LTX → 1080p; a\n * {@link PRICING_DEFAULT_RESOLUTION} member → its declared default). Leaving\n * the key unset then lets the provider pick — documented for the KIE members\n * (their `extraParams` pin the same band) but UNDOCUMENTED for LTX on\n * Replicate. Sending the band we priced makes the two agree by construction.\n *\n * The fill is deliberately limited to providers with a DECLARED default.\n * `buildVideoCreditModelIdentifier` also has un-declared fallbacks — the\n * cheapest tier for a resolution-priced provider with no\n * `PRICING_DEFAULT_RESOLUTION` row — and those are a HEDGE, not a verified\n * provider default: seedance-2 / -fast / -mini pin `resolution: \"720p\"`\n * KIE-side while the identifier prices 480p, so filling 480p would downgrade\n * the render to match a price we already know is wrong. That mismatch is a\n * pre-existing identifier bug and is fixed by seeding the row, not here.\n *\n * 2. **Duration.** Every provider whose price follows the clip length is\n * charged at the length it RENDERS: its own default when the request named\n * none (catalog `defaultDuration`), the nearest length it offers otherwise\n * (`pricedOutputDurationSec` — the runners' own snap rule). The LTX ladder is\n * seeded per (band × seconds), so a 7s request snaps onto the 6s tier;\n * sending 7s would bill six and render seven. The same value is returned for\n * the other length-priced providers (the KIE ladders, Gemini Omni), so what\n * is priced is what is sent. Auto (-1) is the model's call and is untouched.\n *\n * Pure, and IDEMPOTENT against the identifier: feeding its output back in\n * cannot move the reserved tier. `video-request-normalize.test.ts` proves that\n * over every provider × resolution × duration.\n */\nexport function pricedVideoSelection(opts: {\n provider: string\n resolution?: string\n duration?: number | string\n}): PricedVideoSelection {\n const adjustments: ModelInputAdjustment[] = []\n const ltx = ltxPricedTier(opts.provider, opts.resolution, opts.duration)\n\n // The band the request will be priced AND rendered at. An explicit value\n // always wins — this only ever fills an omission.\n const resolution = opts.resolution\n ?? (ltx ? ltx.band : PRICING_DEFAULT_RESOLUTION[opts.provider])\n\n const requested = typeof opts.duration === \"string\" ? parseInt(opts.duration, 10) : opts.duration\n const asked = requested !== undefined && !Number.isNaN(requested)\n\n // Every provider whose price follows the clip length sends the length it is\n // CHARGED at (the catalog funnel: its own default when unset, the nearest\n // legal length otherwise). Auto (-1) is the model's call and is left alone.\n const lengthPriced = !!ltx || DURATION_PRICED_PROVIDERS.has(opts.provider) || isGeminiOmniProvider(opts.provider)\n if (!lengthPriced || (!ltx && asked && requested! <= 0)) return { resolution, adjustments }\n\n const duration = ltx ? ltx.duration : pricedOutputDurationSec(opts.provider, opts.duration)\n if (asked && requested !== duration) {\n adjustments.push({\n field: \"duration\",\n from: requested!,\n to: duration,\n reason: ltx\n ? `LTX renders ${ltx.band} in ${ltx.duration}s steps — using ${ltx.duration}s instead of ${requested}s.`\n : `${opts.provider} renders ${duration}s clips at the nearest length it offers — using ${duration}s instead of ${requested}s.`,\n })\n }\n return { resolution, duration, adjustments }\n}\n\n/**\n * Compute composite model identifier for motion control with duration-tiered pricing.\n * Examples: \"kling-3.0-motion:10s\", \"kling-3.0-motion:1080p:15s\", \"motion-transfer:5s\"\n *\n * Wan Animate providers use resolution-tiered pricing (not per-second):\n * \"wan-animate-move\" (480p default), \"wan-animate-move:580p\", \"wan-animate-move:720p\"\n *\n * @param provider - Motion control provider key (\"kling\" for 2.6, \"kling-3.0\", \"wan-animate-move\", \"wan-animate-replace\")\n * @param resolution - \"720p\" or \"1080p\" (Kling), \"480p\" or \"580p\" or \"720p\" (Wan Animate)\n * @param videoDuration - Reference video duration in seconds (defaults to 10s, unused for Wan Animate)\n */\nexport function buildMotionCreditModelIdentifier(\n provider: string,\n resolution: string,\n videoDuration?: number,\n): string {\n // Wan Animate providers use resolution-tiered pricing (not duration-based)\n if (provider === \"wan-animate-move\" || provider === \"wan-animate-replace\") {\n // 480p is the default (base identifier), 580p and 720p get composite suffix\n if (resolution === \"580p\" || resolution === \"720p\") {\n return `${provider}:${resolution}`\n }\n return provider\n }\n\n const raw = videoDuration ?? 10\n const durationSec = Math.floor(Number.isNaN(raw) ? 10 : raw) // default 10s; floor to match KIE per-second billing\n const tier = MOTION_DURATION_TIERS.find(t => durationSec <= t.maxSeconds)\n ?? MOTION_DURATION_TIERS[MOTION_DURATION_TIERS.length - 1]\n\n const base = provider === \"kling-3.0\" ? \"kling-3.0-motion\" : \"motion-transfer\"\n const resSuffix = resolution === \"1080p\" ? \":1080p\" : \"\"\n return `${base}${resSuffix}:${tier.suffix}`\n}\n\n/**\n * The Suno operations whose credit key depends on the model VERSION.\n *\n * `/v1/suno/generate`, `/cover` and `/extend` resolve their creditGuard\n * identifier through `sunoCreditType(model, <operation>)` (routes/suno.ts\n * :247-249, :335-337, :407-409). EVERY other Suno route charges a flat\n * per-operation key and ignores the version the node carries — mashup (:648),\n * add-instrumental (:852), add-vocals (:907), upload-extend (:1016),\n * replace-section (:710), style-boost (:771), convert-wav (:962),\n * lyrics (:482), music-video (:594), voice (:1218).\n *\n * Anything that QUOTES a Suno price — a dropdown row, a node badge, the\n * workflow-credit estimator — must follow the same split, or it displays a\n * credit key the route never charges.\n */\nexport const SUNO_VERSION_PRICED_OPERATIONS = [\n \"suno-generate\",\n \"suno-cover\",\n \"suno-extend\",\n] as const\n\n/**\n * The seven Suno operations that appear behind a select/dropdown UI (model\n * pickers, node badges, the credit estimator) — the three version-priced\n * operations above, plus the four flat-key operations exercised by\n * `sunoCreditType`'s own test suite. A readonly tuple so later tasks (the\n * model dropdowns, node badges) can iterate or count it without redeclaring\n * the list and drifting from this one.\n */\nexport const SUNO_SELECT_OPERATIONS = [\n \"suno-generate\",\n \"suno-cover\",\n \"suno-extend\",\n \"suno-mashup\",\n \"suno-add-instrumental\",\n \"suno-add-vocals\",\n \"suno-upload-extend\",\n] as const\n\n/**\n * Adjust Speed's price id: motion-compensated (\"smooth\") interpolation is its\n * own, dearer tier. The route, the workflow run, and the editor's badge and\n * run estimate all price through this, so none of them can quote the fast tier\n * for a smooth run.\n */\nexport function speedRampCreditId(quality: unknown): \"speed-ramp\" | \"speed-ramp:smooth\" {\n return quality === \"smooth\" ? \"speed-ramp:smooth\" : \"speed-ramp\"\n}\n\n/**\n * Apply EDL's price id: a `proxy` render (the 720p preview) is its own,\n * cheaper per-output-minute row; a `final` render keeps the bare id. One id per\n * QUALITY, for a video and an audio output alike (decided 2026-10-04). Anything\n * that is not exactly \"proxy\" is the final, as the route and the node default\n * it. The route, the workflow run, and the editor's badge and run estimate all\n * price through this; the job itself is always named `apply-edl`.\n */\nexport function applyEdlCreditId(quality: unknown): \"apply-edl\" | \"apply-edl:proxy\" {\n return quality === \"proxy\" ? \"apply-edl:proxy\" : \"apply-edl\"\n}\n\n/**\n * Speaker View's price tiers (decided 2026-10-10, C4): a render is priced by\n * how many speakers it composites at once. `standard` — at most two tiles on\n * any segment and no zoom; `complex` — three to six tiles, or any zoom. Which\n * tier a render is in is the render rule's to say (the app's\n * `@nodaro/render-rules`), never this vocabulary's.\n */\nexport const SPEAKER_VIEW_PRICE_TIERS = [\"standard\", \"complex\"] as const\nexport type SpeakerViewPriceTier = (typeof SPEAKER_VIEW_PRICE_TIERS)[number]\n\nexport type SpeakerViewCreditId = \"speaker-view\" | \"speaker-view:proxy\" | \"speaker-view:complex\" | \"speaker-view:complex:proxy\"\n\n/** Every id `speakerViewCreditId` can name. */\nexport const SPEAKER_VIEW_CREDIT_IDS: readonly SpeakerViewCreditId[] = Object.freeze([\n \"speaker-view\",\n \"speaker-view:proxy\",\n \"speaker-view:complex\",\n \"speaker-view:complex:proxy\",\n] as const)\n\n/**\n * The credit id of a Speaker View render (F4, decided 2026-09-23; tiers\n * decided 2026-10-10): a Preview (`quality` \"proxy\") reserves on its own row,\n * anything else on the final's, and each in its price tier — `standard` on\n * `speaker-view` / `speaker-view:proxy`, `complex` on `speaker-view:complex` /\n * `speaker-view:complex:proxy`. A tier that is not exactly `standard` (absent\n * included) names the `complex` row: a caller that cannot tell quotes high,\n * never low. The job is always named `speaker-view`; only its credit id\n * follows the quality and the tier.\n */\nexport function speakerViewCreditId(quality: unknown, tier?: unknown): SpeakerViewCreditId {\n const proxy = quality === \"proxy\"\n if (tier === \"standard\") return proxy ? \"speaker-view:proxy\" : \"speaker-view\"\n return proxy ? \"speaker-view:complex:proxy\" : \"speaker-view:complex\"\n}\n\n/**\n * OUR Nodaro credit key for a Suno operation, given the model version and the\n * operation (which is also the node type and the BullMQ job name).\n *\n * This is the single source of truth for the Suno pricing contract, shared by\n * the reservation path (routes/suno.ts creditGuard), the egress seam\n * (workers/handlers/suno.ts `modelKey`, which must match what was reserved),\n * both workflow-credit estimators (ee/billing/credits.ts and the frontend\n * config-panels/helpers.ts), the seven Suno model dropdowns and the three Suno\n * node badges. It is a billing key — NEVER a KIE provider id — which is what\n * satisfies the B3 egress invariant.\n *\n * The version → key map is {@link SUNO_VERSION_CREDIT_KEYS}; a version with no\n * entry (V4 / V4_5 / V4_5ALL / V4_5PLUS) falls back to the operation key, and a\n * non-version-priced operation is returned unchanged.\n */\nexport function sunoCreditType(model: string | undefined, operation: string): string {\n if (!(SUNO_VERSION_PRICED_OPERATIONS as readonly string[]).includes(operation)) {\n return operation\n }\n return (model && SUNO_VERSION_CREDIT_KEYS[model]) || operation\n}\n\n/**\n * Suno version → Nodaro credit key for the version-priced operations. One row\n * per version that has its own `model_pricing` row / `STATIC_CREDIT_COSTS`\n * entry / `MODEL_CATALOG` pricing row, so an admin can reprice one version\n * without touching code. Every ACTIVE version MUST have a row here — guarded\n * by `__tests__/suno-credit-type.test.ts` (a new active version with no key\n * would silently bill at the operation key).\n */\nexport const SUNO_VERSION_CREDIT_KEYS: Readonly<Record<string, string>> = {\n V6: \"suno-v6\",\n V6_WILD: \"suno-v6_wild\",\n V6_MINI: \"suno-v6_mini\",\n V5_5: \"suno-v5_5\",\n V5: \"suno-v5\",\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/credit-identifiers.ts"],"names":[],"mappings":";;;;;;AA6EA,SAAS,kBAAA,CAAmB,OAAmB,UAAA,EAA6B;AAC1E,EAAA,MAAM,IAAA,GAAO,CAAC,CAAA,KAAc,CAAA,CAAE,QAAQ,SAAA,EAAW,EAAE,EAAE,IAAA,EAAK;AAC1D,EAAA,MAAM,MAAM,OAAO,UAAA,KAAe,QAAA,GAAW,IAAA,CAAK,UAAU,CAAA,GAAI,EAAA;AAChE,EAAA,IAAI,GAAA,KAAQ,IAAI,OAAO,GAAA;AAIvB,EAAA,MAAM,IAAA,GAAO,YAAA,CAAa,IAAA,CAAK,CAAC,CAAA,KAAM,OAAO,CAAC,CAAA,KAAM,MAAA,CAAO,GAAG,CAAC,CAAA;AAC/D,EAAA,OAAO,IAAA,IAAQ,IAAA,CAAK,oBAAA,CAAqB,KAAK,KAAK,MAAM,CAAA;AAC3D;AAYA,SAAS,kBAAA,CACP,QAAA,EACA,OAAA,EACA,UAAA,EACA,mBAAA,EACQ;AACR,EAAA,MAAM,IAAK,uBAAA,CAA8C,QAAA,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ACA,YAAA;AAAA,EACA,aAAA;AAAA,EACA,aAAA;AAAA,EACA,uBAAA;AAAA,EACA,iBAAA;AAAA,EACA;AACF;AAQO,SAAS,kBAAkB,OAAA,EAAsD;AACtF,EAAA,OAAO,OAAA,KAAY,WAAW,mBAAA,GAAsB,YAAA;AACtD;AAUO,SAAS,iBAAiB,OAAA,EAAmD;AAClF,EAAA,OAAO,OAAA,KAAY,UAAU,iBAAA,GAAoB,WAAA;AACnD;AASO,IAAM,wBAAA,GAA2B,CAAC,UAAA,EAAY,SAAS;AAMvD,IAAM,uBAAA,GAA0D,OAAO,MAAA,CAAO;AAAA,EACnF,cAAA;AAAA,EACA,oBAAA;AAAA,EACA,sBAAA;AAAA,EACA;AACF,CAAU;AAYH,SAAS,mBAAA,CAAoB,SAAkB,IAAA,EAAqC;AACzF,EAAA,MAAM,QAAQ,OAAA,KAAY,OAAA;AAC1B,EAAA,IAAI,IAAA,KAAS,UAAA,EAAY,OAAO,KAAA,GAAQ,oBAAA,GAAuB,cAAA;AAC/D,EAAA,OAAO,QAAQ,4BAAA,GAA+B,sBAAA;AAChD;AAkBO,SAAS,cAAA,CAAe,OAA2B,SAAA,EAA2B;AACnF,EAAA,IAAI,CAAE,8BAAA,CAAqD,QAAA,CAAS,SAAS,CAAA,EAAG;AAC9E,IAAA,OAAO,SAAA;AAAA,EACT;AACA,EAAA,OAAQ,KAAA,IAAS,wBAAA,CAAyB,KAAK,CAAA,IAAM,SAAA;AACvD;AAUO,IAAM,wBAAA,GAA6D;AAAA,EACxE,EAAA,EAAI,SAAA;AAAA,EACJ,OAAA,EAAS,cAAA;AAAA,EACT,OAAA,EAAS,cAAA;AAAA,EACT,IAAA,EAAM,WAAA;AAAA,EACN,EAAA,EAAI;AACN","file":"chunk-PIX4OCCQ.js","sourcesContent":["/**\n * Build composite credit model identifiers for variable pricing.\n * Shared between frontend and backend.\n */\n\nimport {\n HIGH_QUALITY_PROVIDERS,\n TWO_K_RESOLUTION_PROVIDERS,\n RESOLUTION_2K_4K_TIERED_PROVIDERS,\n IDEOGRAM_PROVIDERS,\n DURATION_PRICED_PROVIDERS,\n AUDIO_ADDON_PROVIDERS,\n MODE_ADDON_PROVIDERS,\n RESOLUTION_VIDEO_REF_PRICING,\n RESOLUTION_DURATION_PRICING,\n VEO_RESOLUTION_TIERED_PROVIDERS,\n VIDEO_DURATION_TIERS,\n pricedOutputDurationSec,\n snapToNearestDuration,\n PRICING_DEFAULT_RESOLUTION,\n MOTION_DURATION_TIERS,\n T2I_TO_I2I_VARIANT,\n isVeoProvider,\n isMinimaxH3Provider,\n isGeminiOmniProvider,\n isGeminiOmniPerSecondProvider,\n isWan3Provider,\n isViduQ4Provider,\n isKling4Provider,\n normalizeKling4Resolution,\n VIDEO_REF_RATE_PROVIDERS,\n normalizeMinimaxH3Resolution,\n normalizeWan3Resolution,\n normalizeViduQ4Resolution,\n getVideoAudioCapability,\n canonicalVideoProvider,\n} from \"./model-constants.js\"\nimport { isFlux2Model, FLUX2_RES_MP, type Flux2Model } from \"./flux2-pricing.js\"\nimport {\n GPT_IMAGE_2_6_DEFAULT_QUALITY,\n GPT_IMAGE_2_6_DEFAULT_RESOLUTION,\n GPT_IMAGE_2_6_MAX_INPUT_IMAGES,\n GPT_IMAGE_2_6_QUALITIES,\n GPT_IMAGE_2_6_RESOLUTIONS,\n isGptImage26I2i,\n isGptImage26Tiered,\n type GptImage26TieredModel,\n} from \"./gpt-image-2-6.js\"\nimport { VIDEO_DURATION_AUTO } from \"./video-duration-auto.js\"\nimport { uiResolutionFill } from \"./video-ui-defaults.js\"\nimport { MODEL_CATALOG, autoAspectNeedsSourceImage, normalizeModelInput, normalizeVideoRequestParams, defaultResolutionFor, type ModelInputAdjustment, type SourceImageSize } from \"./model-catalog.js\"\n\n/**\n * The megapixel tier a Flux 2 credit identifier is keyed on, for ANY incoming\n * `resolution` value.\n *\n * Flux 2 is the only family whose identifier INTERPOLATES the resolution\n * instead of matching it against a known set, and its callers are not\n * guaranteed to hand it a Flux 2 value:\n * - the multi-provider cost preview prices one node's data against EVERY\n * selected provider (`frontend/src/ee/hooks/use-providers-credits-sum.ts`),\n * so a node whose `resolution` is \"2K\" (the flux / nano-banana-pro value\n * space) reaches this branch verbatim;\n * - node data written straight into workflow JSON by an agent, an import or\n * a template never ran the config panel's provider-change fail-safe.\n * Interpolating that produced the off-grid id `flux-2-pro:2KMP:0ref`, which no\n * pricing row can answer — every cost badge 503'd `price_not_configured`\n * (18 production app-reports, 2026-09-07..14).\n *\n * A value off the grid snaps to the model's DEFAULT tier — the same `preferred`\n * value `normalizeModelInput` uses — so the preview asks for exactly the id the\n * route will reserve (both routes and the orchestrator normalize through\n * `resolveNormalizedImageGen` first, which makes this snap a no-op for them).\n * An ABSENT resolution keeps its long-standing meaning (\"this caller has no\n * resolution dimension at all\") and stays on 1 MP rather than moving to the\n * model default, which would silently re-price every resolution-less node.\n */\nfunction flux2MegapixelTier(model: Flux2Model, resolution?: string): string {\n const bare = (v: string) => v.replace(/\\s*MP$/i, \"\").trim()\n const raw = typeof resolution === \"string\" ? bare(resolution) : \"\"\n if (raw === \"\") return \"1\"\n // Numeric match so \"2.0\"/\" 2 MP\" land on the same grid point as \"2\", and the\n // GRID's own spelling is what gets emitted — returning the caller's \"2.0\"\n // would build \":2.0MP:\", another id no pricing row carries.\n const tier = FLUX2_RES_MP.find((t) => Number(t) === Number(raw))\n return tier ?? bare(defaultResolutionFor(model) ?? \"1 MP\")\n}\n\n/**\n * The price id of a GPT Image 2.6 Flare or Sunburst run: `<id>:<quality>:<size>`,\n * and on an edit `<id>:<quality>:<size>:<N>ref`, N being the input images.\n *\n * A value off the grid (a stored node, the multi-provider preview pricing one\n * node's data against every model) lands on the default rather than building\n * an id no row answers. A text-to-image id sent input images runs on the edit\n * endpoint, so a caller that does not swap the model first (the entity routes,\n * a pipeline pin) is priced there too. An edit always has at least its source.\n */\nfunction gptImage26CreditId(\n provider: GptImage26TieredModel,\n quality: string | undefined,\n resolution: string | undefined,\n referenceImageCount: number | undefined,\n): string {\n const q = (GPT_IMAGE_2_6_QUALITIES as readonly string[]).includes(quality ?? \"\") ? quality : GPT_IMAGE_2_6_DEFAULT_QUALITY\n const r = (GPT_IMAGE_2_6_RESOLUTIONS as readonly string[]).includes(resolution ?? \"\") ? resolution : GPT_IMAGE_2_6_DEFAULT_RESOLUTION\n const images = Math.trunc(referenceImageCount ?? 0)\n const model = !isGptImage26I2i(provider) && images > 0 ? T2I_TO_I2I_VARIANT[provider]! : provider\n if (!isGptImage26I2i(model)) return `${model}:${q}:${r}`\n return `${model}:${q}:${r}:${Math.min(Math.max(1, images), GPT_IMAGE_2_6_MAX_INPUT_IMAGES)}ref`\n}\n\n/**\n * Compute composite model identifier for variable credit pricing.\n * Examples: \"gpt-image:high\", \"flux:2K\", \"nano-banana-pro:4K\", \"ideogram:TURBO\",\n * \"flux-2-pro:2MP\", \"flux-2-max:2MP:1ref\" (Flux 2 — billed per megapixel).\n *\n * For image models, uses quality/resolution/renderingSpeed and (Flux 2) the output\n * megapixel count plus (Flux 2 Max) the number of reference images attached at request time.\n * For video models, uses duration/sound params when the model has variable pricing.\n */\nexport function buildCreditModelIdentifier(\n provider: string,\n quality?: string,\n resolution?: string,\n renderingSpeed?: string,\n targetResolution?: string,\n referenceImageCount?: number,\n): string {\n // Flux 2 family: billed per output megapixel AND per reference image (each\n // ref counts as input megapixels). Resolution arrives as \"N MP\" strings (the\n // UI value space); strip the unit. ALL three models encode the ref count\n // (capped at 8): Pro/Klein i2i always carry the source image as a ref and\n // their cost formula charges per input MP, so the reserved identifier must\n // reflect refs (there is no metered true-up to correct an under-reserved tier).\n if (isFlux2Model(provider)) {\n return `${provider}:${flux2MegapixelTier(provider, resolution)}MP:${Math.min(referenceImageCount ?? 0, 8)}ref`\n }\n if (isGptImage26Tiered(provider)) {\n return gptImage26CreditId(provider, quality, resolution, referenceImageCount)\n }\n if (HIGH_QUALITY_PROVIDERS.has(provider) && quality === \"high\") {\n return `${provider}:high`\n }\n if (TWO_K_RESOLUTION_PROVIDERS.has(provider) && resolution === \"2K\") {\n return `${provider}:2K`\n }\n if (provider === \"nano-banana-pro\" && resolution === \"4K\") {\n return `${provider}:4K`\n }\n if (RESOLUTION_2K_4K_TIERED_PROVIDERS.has(provider) && (resolution === \"2K\" || resolution === \"4K\")) {\n return `${provider}:${resolution}`\n }\n // Topaz Image Upscale: 2K is default (no suffix), 4K/8K get composite identifiers\n if (provider === \"topaz-image-upscale\" && targetResolution && targetResolution !== \"2K\") {\n return `${provider}:${targetResolution}`\n }\n if (IDEOGRAM_PROVIDERS.has(provider)) {\n if (renderingSpeed === \"TURBO\") return `${provider}:TURBO`\n if (renderingSpeed === \"QUALITY\") return `${provider}:QUALITY`\n }\n return provider\n}\n\n/**\n * An image request's catalog-snapped parameters PLUS the credit identifier\n * priced off them.\n *\n * `adjustments` is the disclosure channel: every lever this changed, why, and\n * to what. Routes return it in the 200 body so a caller learns their value was\n * corrected instead of silently getting something else.\n */\nexport interface NormalizedImageGen {\n /** Credit identifier, priced off the SNAPPED `resolution` / `quality`. */\n identifier: string\n /** The catalog model id the params were snapped against (post T2I→I2I swap). */\n modelId: string\n aspectRatio?: string\n resolution?: string\n quality?: string\n background?: string\n /** Empty when the caller's values were already valid for `modelId`. */\n adjustments: ModelInputAdjustment[]\n}\n\n/**\n * The catalog model `resolveNormalizedImageGen` snaps against: the provider\n * (Nano Banana when none is named), or — with `swapToI2i` and references\n * attached — its i2i sibling, the model the generate-image route and the\n * workflow payload builder then send. That sibling has its OWN catalog entry\n * and lever lists. Exported so a caller that has to decide something about\n * those lists before the snap (whether a photo's size is worth reading) asks\n * about the same model the snap will use.\n */\nexport function normalizedImageGenModelId(opts: {\n provider: unknown\n refCount: number\n swapToI2i?: boolean\n}): string {\n const provider = typeof opts.provider === \"string\" && opts.provider.length > 0 ? opts.provider : \"nano-banana\"\n return opts.swapToI2i && opts.refCount > 0 ? (T2I_TO_I2I_VARIANT[provider] ?? provider) : provider\n}\n\n/**\n * Whether \"auto\" on a Generate Image request can need its photo's size: the\n * model the snap runs against (`normalizedImageGenModelId` with the swap on)\n * has no native auto. Given the ASSEMBLED reference count, it asks about exactly\n * that model; without one — a write boundary, or a run before its references\n * assemble — about both the provider and its i2i sibling, since references may\n * yet attach.\n */\nexport function imageGenAutoAspectNeedsSourceImage(opts: {\n provider: unknown\n aspectRatio: unknown\n refCount?: number\n}): boolean {\n const asks = (refCount: number) =>\n autoAspectNeedsSourceImage(normalizedImageGenModelId({ provider: opts.provider, refCount, swapToI2i: true }), opts.aspectRatio)\n return opts.refCount === undefined ? asks(0) || asks(1) : asks(opts.refCount)\n}\n\n/**\n * Snap an image request's catalog-governed levers to a combination the model\n * actually accepts, and price the credit identifier off the SNAPPED values.\n *\n * WHY THE SNAP LIVES HERE and not at the call site. Both image routes compute\n * their credit identifier TWICE — once in the `creditGuard` preHandler (the\n * CHECK) and once at the handler's `reserveCreditsForJob` (the DEBIT) — and a\n * dedicated test asserts the two stay byte-identical (see\n * `backend/src/routes/__tests__/generate-image.test.ts`, \"CHECK === DEBIT\").\n * `resolution` and `quality` are pricing dimensions, so a snap applied at only\n * one of those sites breaks that invariant, and `commit_credits` never collects\n * an upward delta — the reserve IS the charge. Putting the snap inside the\n * primitive makes CHECK, DEBIT and the workflow orchestrator agree by\n * construction rather than by everyone remembering to call a normalizer.\n *\n * Inputs are typed `unknown` on purpose: the preHandler runs BEFORE Zod, so a\n * caller can put a number or an object in `resolution`. Non-strings become\n * `undefined` rather than reaching `normalizeModelInput` as a lie.\n *\n * Unknown model ids pass through untouched (same contract as\n * `normalizeModelInput`) — the route's provider enum is the gate for those.\n *\n * `sourceImage` is the size of the photo the request transforms or is drawn\n * from (an image-to-image / edit source, or Generate Image's first wired\n * reference). It only decides \"auto\" on a model without a native auto, and the\n * ratio is not a pricing dimension on any such model (pinned across the catalog\n * by `auto-aspect-source.test.ts`), so a CHECK that runs before the size is\n * known prices the same identifier as the DEBIT that knows it.\n */\nexport function resolveNormalizedImageGen(opts: {\n provider: string | undefined\n aspectRatio?: unknown\n quality?: unknown\n resolution?: unknown\n renderingSpeed?: unknown\n /** Does not price on its own, but a transparent background can move the size. */\n background?: unknown\n refCount: number\n swapToI2i?: boolean\n sourceImage?: SourceImageSize\n}): NormalizedImageGen {\n const str = (v: unknown): string | undefined =>\n typeof v === \"string\" && v.length > 0 ? v : undefined\n\n const modelId = normalizedImageGenModelId(opts)\n\n const n = normalizeModelInput(\n modelId,\n {\n aspectRatio: str(opts.aspectRatio),\n resolution: str(opts.resolution),\n quality: str(opts.quality),\n background: str(opts.background),\n },\n { sourceImage: opts.sourceImage },\n )\n\n return {\n identifier: buildCreditModelIdentifier(\n modelId,\n n.quality,\n n.resolution,\n str(opts.renderingSpeed),\n undefined,\n opts.refCount,\n ),\n modelId,\n aspectRatio: n.aspectRatio,\n resolution: n.resolution,\n quality: n.quality,\n background: n.background,\n adjustments: n.adjustments,\n }\n}\n\n/**\n * Reference-aware image-generation credit identifier — the SINGLE source of\n * truth shared by the single-node routes (`/v1/generate-image`,\n * `/v1/image-to-image`) and the workflow orchestrator\n * (`payload-builder.ts`). It centralises the two pricing dimensions that must\n * match across both paths or a Flux 2 generation is billed the wrong tier\n * (Flux 2 commits non-metered / has no upward true-up, so the reserved\n * identifier IS the final charge):\n * - `refCount`: the number of reference images sent to the provider (Flux 2\n * bills per ref). generate-image passes the assembled count (0 for pure\n * text-to-image); image-to-image passes 1 (the primary `imageUrl`) + extras.\n * - `swapToI2i`: generate-image auto-swaps a bare T2I provider to its i2i\n * sibling (`T2I_TO_I2I_VARIANT`) when refs are attached, so the credit id\n * matches the variant actually invoked. image-to-image is already an i2i\n * provider → pass `false`.\n *\n * The LoRA short-circuit (`flux-lora-character`) stays at the call site because\n * the routing decision needs a DB lookup the routes/orchestrator own.\n */\nexport function resolveImageGenCreditIdentifier(opts: {\n provider: string | undefined\n quality?: string\n resolution?: string\n renderingSpeed?: string\n refCount: number\n swapToI2i?: boolean\n}): string {\n return resolveNormalizedImageGen(opts).identifier\n}\n\n// T2V-specific credit overrides: some providers have different costs for T2V\n// vs I2V/V2V due to different default resolutions or colliding with image model names.\nconst T2V_CREDIT_OVERRIDES: Record<string, string> = {\n \"grok\": \"grok-i2v\", // T2V grok, same as I2V grok (not image grok = 4 cr)\n \"wan\": \"wan-t2v\", // T2V wan 1080p = (V2V wan 720p = 70 cr)\n \"wan-turbo\": \"wan-turbo-t2v\", // T2V wan-turbo 720p = (I2V wan-turbo 480p = 40 cr)\n}\n\n/**\n * Compute composite model identifier for video models with duration/audio-based pricing.\n * Examples: \"kling-3.0:5s\", \"kling-3.0:10s:audio\", \"seedance-2:8s:720p-ref\"\n *\n * @param provider - Video model key (e.g., \"kling-3.0\")\n * @param duration - Video duration in seconds\n * @param sound - Whether audio/sound is enabled\n * @param nodeType - Node type for T2V-specific cost overrides\n * @param mode - Quality variant that affects pricing\n * @param resolution - Output resolution (used by Seedance 2 for 480p/720p pricing)\n * @param hasVideoRef - Whether a reference video is connected (Seedance 2 uses a lower per-second rate when true)\n */\n/**\n * LTX 2.3 (Lightricks via Replicate) credit tiers: priced by\n * (resolution-band × duration-seconds). Keys mirror STATIC_CREDIT_COSTS /\n * model_pricing EXACTLY (lowercase band + raw seconds + \"s\"), e.g.\n * \"ltx-2.3-pro:1080p:6s\". This map is the source of truth for the nearest-tier\n * snap below, so an off-catalog (resolution, duration) from a direct API/SDK\n * call maps to a SEEDED price instead of hard-failing (price_not_configured\n * 503). Pro: 6/8/10s at every band. Fast: up to 20s at 1080p, 6/8/10s at 2k/4k.\n */\nconst LTX_DURATION_TIERS: Record<string, Record<string, number[]>> = {\n \"ltx-2.3-pro\": { \"1080p\": [6, 8, 10], \"2k\": [6, 8, 10], \"4k\": [6, 8, 10] },\n \"ltx-2.3-fast\": { \"1080p\": [6, 8, 10, 12, 14, 16, 18, 20], \"2k\": [6, 8, 10], \"4k\": [6, 8, 10] },\n}\n\n/**\n * The (band, duration) tier the LTX pricing ladder charges for a request, or\n * `undefined` for a non-LTX provider. Extracted so\n * `buildVideoCreditModelIdentifier` and `pricedVideoSelection` read the ladder\n * ONCE — the routes must send the tier they reserved, and a second copy of this\n * math is exactly how the two drift apart.\n *\n * An unknown/absent band falls back to 1080p (LTX's own default, and the band\n * `snapLtxInput` snaps to at the Replicate call), and an off-tier duration\n * snaps to the NEAREST seeded one so the emitted composite always prices.\n */\nfunction ltxPricedTier(\n provider: string,\n resolution?: string,\n duration?: number | string,\n): { band: string; duration: number } | undefined {\n const bands = LTX_DURATION_TIERS[provider]\n if (!bands) return undefined\n const band = bands[String(resolution)] ? String(resolution) : \"1080p\"\n const allowed = bands[band]!\n // The model's own default (catalog `defaultDuration`) when unset, then the\n // nearest rung of THIS band's ladder — the length LTX renders.\n const dur = snapToNearestDuration(pricedOutputDurationSec(provider, duration), allowed)\n return { band, duration: dur }\n}\n\n/**\n * The resolution a provider whose runner NORMALIZES the lever actually renders,\n * in the lowercase spelling of its credit composites — billing collapses\n * through the very normalizer the runner sends, so render == billed for every\n * spelling. `undefined` passes through untouched for every other provider.\n */\nfunction wireNormalizedResolution(provider: string, resolution: string | undefined): string | undefined {\n if (isWan3Provider(provider)) return normalizeWan3Resolution(resolution).toLowerCase()\n if (isViduQ4Provider(provider)) return normalizeViduQ4Resolution(resolution)\n if (isKling4Provider(provider)) return normalizeKling4Resolution(resolution)\n return resolution\n}\n\nexport function buildVideoCreditModelIdentifier(\n rawProvider: string,\n duration?: number | string,\n sound?: boolean,\n nodeType?: \"image-to-video\" | \"text-to-video\",\n mode?: string,\n resolution?: string,\n hasVideoRef?: boolean,\n): string {\n // A retired model (RETIRED_VIDEO_PROVIDERS) is priced as the model it runs as.\n const provider = canonicalVideoProvider(rawProvider) as string\n // T2V overrides: some providers have different base costs for text-to-video\n let effectiveProvider = provider\n if (nodeType === \"text-to-video\") {\n const override = T2V_CREDIT_OVERRIDES[provider]\n if (override) {\n // If override target also has duration pricing, use it as effective provider\n if (DURATION_PRICED_PROVIDERS.has(override)) {\n effectiveProvider = override\n } else {\n return override\n }\n }\n }\n\n // VEO 3.x resolution-tiered pricing: 720p is the base (no suffix), 1080p gets\n // \":1080p\" (Fast/Lite only), and 4K gets \":4k\" for ALL three tiers — direct-4K\n // generation chains KIE's get-4k-video off the base generation (the base runs\n // at 1080p). Duration is fixed at 8s for VEO so the duration-tier path below\n // does not apply.\n if (isVeoProvider(effectiveProvider)) {\n if (resolution === \"4k\") return `${effectiveProvider}:4k`\n // 1080p tier is Fast/Lite only (Quality has no 1080p surcharge).\n if (resolution === \"1080p\" && VEO_RESOLUTION_TIERED_PROVIDERS.has(effectiveProvider)) return `${effectiveProvider}:1080p`\n return effectiveProvider\n }\n\n // Gemini Omni family (gemini-omni-video + gemini-omni-flash): priced by\n // (resolution-band × duration), with a flat per-generation rate when a source\n // video is supplied (V2V). Lowercase \"4k\". The prefix is TEMPLATED from the\n // provider id, so a further Omni SKU needs no edit here — it only has to join\n // GEMINI_OMNI_PROVIDERS and seed its rows. These models are deliberately NOT\n // in DURATION_PRICED_PROVIDERS; this branch early-returns before that gate.\n // A per-second SKU (Omni Flash 1.2) prices on the `:<N>s:<res>` ladder below.\n if (isGeminiOmniProvider(effectiveProvider) && !isGeminiOmniPerSecondProvider(effectiveProvider)) {\n if (hasVideoRef) {\n return resolution === \"4k\" ? `${effectiveProvider}:4k:vref` : `${effectiveProvider}:vref`\n }\n // The rendered length through the catalog funnel (nearest legal tier, the\n // model's own default when unset) so the composite is always a SEEDED one.\n const d = pricedOutputDurationSec(effectiveProvider, duration)\n return resolution === \"4k\" ? `${effectiveProvider}:4k:${d}` : `${effectiveProvider}:${d}`\n }\n\n // LTX 2.3: priced by (resolution-band × duration-seconds). The RESERVE must be\n // the correct composite — commit_credits (migration 176) only refunds a surplus\n // (actual < reserved) and NEVER collects an upward delta, so an under-reserved\n // LTX run (the bare-id default = cheapest 1080p:6s tier) stays under-charged\n // even with meteredCost:true. Snap to a seeded tier so the id always prices.\n const ltxTier = ltxPricedTier(effectiveProvider, resolution, duration)\n if (ltxTier) {\n return `${effectiveProvider}:${ltxTier.band}:${ltxTier.duration}s`\n }\n\n if (!DURATION_PRICED_PROVIDERS.has(effectiveProvider)) {\n return effectiveProvider\n }\n\n // A named-provider request with NO duration renders the model's own default\n // (kie/models.ts extraParams), so price that default — not the global 5s —\n // for providers whose per-second tiers wouldn't snap 5 up to it\n // (minimax-h3, seedance-2-5). One helper, shared with the dynamic\n // reference-video reservations, so the tier and the scaled reserve agree.\n const durationSec = pricedOutputDurationSec(effectiveProvider, duration)\n const tiers = VIDEO_DURATION_TIERS[effectiveProvider]\n if (!tiers) return effectiveProvider\n\n // Find the matching duration tier\n const tier = tiers.find(t => durationSec <= t.maxSeconds) ?? tiers[tiers.length - 1]\n let identifier = `${effectiveProvider}:${tier.suffix}`\n\n // Append audio suffix if applicable. When the caller expressed no intent\n // (sound === undefined), fall back to the model's own default (capability\n // `defaultOn` — kling-3.0 generates audio unless explicitly disabled), so an\n // intent-less request is billed for the audio it actually produces instead\n // of reserving the cheaper no-audio tier against an audio-on generation.\n const soundOn = sound ?? (getVideoAudioCapability(effectiveProvider).defaultOn === true)\n if (AUDIO_ADDON_PROVIDERS.has(effectiveProvider) && soundOn) {\n identifier += \":audio\"\n }\n\n // Append mode suffix for providers with quality-tiered pricing\n // \"high\" comes from I2V videoSize field, \"pro\" comes from T2V mode field\n if (MODE_ADDON_PROVIDERS.has(effectiveProvider) && (mode === \"high\" || mode === \"pro\")) {\n identifier += \":high\"\n }\n\n // Seedance 2.0 family: per-second billing with resolution + video-ref dimensions.\n // KIE accepts 480p / 720p / 1080p natively; per-second rates rise non-linearly\n // so each tier gets its own composite identifier.\n if (RESOLUTION_VIDEO_REF_PRICING.has(effectiveProvider)) {\n // Clamp to the model's catalog resolutions (single source of truth): e.g.\n // seedance-2-mini exposes only 480p/720p, so a stale/explicit 1080p (or 4k)\n // maps to its top priced tier instead of emitting an unpriced composite\n // (which the hard-fail credit guard would 503 on at runtime).\n const supported = MODEL_CATALOG[effectiveProvider]?.resolutions ?? [\"480p\", \"720p\", \"1080p\"]\n // An OMITTED resolution renders the model's KIE-side default, so price that\n // default rather than the cheapest tier — otherwise an intent-less request\n // reserves 480p against a 720p render and commit_credits (refund-only) can\n // never collect the delta. Providers without an entry keep the historical\n // 480p fallback, so this cannot reprice anything already live.\n const requested = resolution ?? PRICING_DEFAULT_RESOLUTION[effectiveProvider]\n const want = requested === \"4k\" ? \"4k\" : requested === \"1080p\" ? \"1080p\" : requested === \"720p\" ? \"720p\" : \"480p\"\n // Unsupported (e.g. a stale 1080p on seedance-2-mini) clamps to the model's\n // top priced tier so the emitted composite is always seeded.\n const res = supported.includes(want) ? want : (supported[supported.length - 1] ?? \"480p\")\n identifier += `:${res}`\n if (hasVideoRef) identifier += \"-ref\"\n }\n\n // Duration × resolution pricing without a -ref dimension. Resolutions\n // outside the provider's priced tiers (or undefined) collapse to the first\n // (default) tier so the emitted composite is always seeded — the hard-fail\n // guard fuzzes the whole resolution space.\n const resTiers = RESOLUTION_DURATION_PRICING[effectiveProvider]\n if (resTiers) {\n // The \"default tier\" is the provider's DECLARED default when it has one\n // (PRICING_DEFAULT_RESOLUTION — wan-3 renders 720p, not the cheapest tier),\n // otherwise the first listed tier. Declaring it explicitly means a cosmetic\n // reorder of the tier list can never reprice a live model, and an OMITTED\n // *or* unsupported resolution both land on what actually renders instead of\n // on the cheapest row (commit_credits refunds a surplus but can never\n // collect a shortfall). Behaviour-neutral for every member without a\n // declared default.\n const declaredDefault = PRICING_DEFAULT_RESOLUTION[effectiveProvider]\n const fallback = declaredDefault && resTiers.includes(declaredDefault) ? declaredDefault : resTiers[0]!\n // Wan 3.0 renders through `normalizeWan3Resolution`, which is CASE-INSENSITIVE\n // (\"1080P\" — KIE's own OpenAPI enum spelling, and the natural value for an\n // integrator reading the provider docs — renders 1080P). The tier list here is\n // lowercase and `Array.includes` is case-sensitive, so without this the render\n // path and the billing path disagree: \"1080P\" rendered the top tier and billed\n // the 720p row, a shortfall `commit_credits` (refund-only) can never collect.\n // Collapsing through the SAME normalizer the runner uses makes render == billed\n // by construction for every spelling, including garbage (→ the declared 720p).\n // Scoped to the families whose runner normalizes on purpose (Wan 3.0, Vidu\n // Q4): the other RESOLUTION_DURATION_PRICING members pass `resolution` to\n // their wire verbatim, so case-folding their billing without probing their\n // wire would reprice live models.\n const requested = wireNormalizedResolution(effectiveProvider, resolution)\n const res = requested && resTiers.includes(requested) ? requested : fallback\n identifier += `:${res}`\n // A reference VIDEO bills at its own per-second rate (Kling 4.0).\n if (hasVideoRef && VIDEO_REF_RATE_PROVIDERS.has(effectiveProvider)) identifier += \"-ref\"\n }\n\n // MiniMax Hailuo 3 (768P lever, 2026-08-03): bare duration composites stay\n // the 2K (default) rate — byte-identical to the pre-lever seeded rows, so\n // existing workflows and admin overrides keep their ids — and only a\n // verified 768P selection appends \":768p\". normalizeMinimaxH3Resolution\n // collapses anything else to 2K, matching what KIE renders for an\n // omitted/unknown value, so billing can never undercut the render.\n if (isMinimaxH3Provider(effectiveProvider) && normalizeMinimaxH3Resolution(resolution) === \"768P\") {\n identifier += \":768p\"\n }\n\n return identifier\n}\n\n/**\n * The credit identifier a video GENERATION node is quoted at — Generate Video\n * (and the legacy Image/Text to Video nodes) and the Video to Video Seedance\n * edit lane, on every surface that quotes one: the node's cost pill, the\n * editor's run estimate, the prompt modal and the backend pre-run estimator.\n *\n * It applies the request levers the run applies BEFORE it prices\n * (payload-builder's `resolveVideoRequestNorm`): the model's UI resolution fill\n * when the node names none (`uiResolutionFill` — what the run sends), then the\n * catalog normalizer `normalizeVideoRequestParams`, which also owns the Seedance\n * Draft rule (a draft is priced AND sent at 480p whatever resolution came with\n * it). Without that, a node with no resolution was quoted at the identifier's\n * own default band (720p on Seedance 2.5) while the run sent and reserved 480p.\n *\n * `hasVideoRef` must come from the GRAPH (a wired reference-video edge, e.g.\n * `countRefModalityEdges(edges, id, \"video\") > 0`), never node data: nothing\n * writes `referenceVideoUrls` into a video node, so reading it there always\n * quoted the plain ladder for a run that reserves on the `-ref` one.\n */\nexport function videoGenerationCreditId(args: {\n provider: string\n duration?: number | string\n sound?: boolean\n nodeType?: \"image-to-video\" | \"text-to-video\"\n mode?: string\n resolution?: string\n draft?: boolean\n hasVideoRef?: boolean\n}): string {\n const { resolution } = normalizeVideoRequestParams(args.provider, {\n resolution: args.resolution ?? uiResolutionFill(args.provider),\n draft: args.draft === true,\n })\n return buildVideoCreditModelIdentifier(\n args.provider,\n args.duration,\n args.sound,\n args.nodeType ?? \"image-to-video\",\n args.mode,\n resolution,\n args.hasVideoRef === true,\n )\n}\n\n/**\n * The credit identifier a Video to Video node's Seedance EDIT lane reserves\n * under. Seedance has no v2v endpoint — the lane is a text-to-video job in edit\n * shape with the source clip as reference video 1 — so it prices on the\n * REFERENCE-VIDEO ladder at the model's LONGEST clip (Auto duration), and the\n * measured settlement refunds down to what was actually delivered.\n *\n * A thin call into {@link videoGenerationCreditId}, so a Generate Video node\n * making the same KIE call (Seedance, Auto, a wired reference video) is quoted\n * the same id. FOUR surfaces must agree on it exactly: the orchestrator's\n * reservation (payload-builder.ts), the backend pre-run estimator\n * (ee/billing/credits.ts), the node's cost pill, and the frontend run-level\n * estimate (config-panels/helpers.ts). A quote that disagrees with the reserve\n * is the documented `price_not_configured` / blank-pill trap.\n *\n * `resolution` is the node's one `v2vResolution` field; when unset the model's\n * own UI fill is priced, which is what the lane will send. `draft` is the\n * node's Seedance Draft toggle (priced at 480p).\n */\nexport function seedanceVideoEditCreditId(provider: string, resolution?: string, draft?: boolean): string {\n return videoGenerationCreditId({\n provider,\n duration: VIDEO_DURATION_AUTO,\n nodeType: \"text-to-video\",\n resolution,\n draft,\n hasVideoRef: true,\n })\n}\n\n/** What the video credit identifier PRICES for a request, for the levers whose\n * priced value must also be the value we SEND. */\nexport interface PricedVideoSelection {\n /** The resolution band the reservation is priced at when the request omitted\n * one — and only where the platform DECLARES that band as the provider's own\n * default. `undefined` means \"leave `resolution` exactly as the request had\n * it\": either the caller supplied one, or the provider's real default is not\n * known to be the band the identifier assumes. */\n resolution?: string\n /** The length the reservation is priced at and the wire carries, for a\n * provider whose price follows the clip length (LTX's seeded tier, the KIE\n * ladders, Gemini Omni). `undefined` for every other provider, and for Auto:\n * their duration passes through. */\n duration?: number\n /** Non-empty only for a lever the caller ASKED for and did not get (a 7s\n * request snapped to the 6s tier). Filling an omitted lever is a disclosure of\n * the price already being charged, not a correction, so it reports nothing. */\n adjustments: ModelInputAdjustment[]\n}\n\n/**\n * The other half of the video money path: `normalizeVideoRequestParams` snaps a\n * value the CATALOG governs; this returns the value the PRICE ladder governs.\n *\n * Two defects it closes, both of the same shape — the identifier prices one\n * thing and the wire carries another, and `commit_credits` (migration 176) only\n * ever refunds a surplus, so the reservation is the final charge:\n *\n * 1. **Absent resolution.** `buildVideoCreditModelIdentifier` prices an omitted\n * `resolution` as a concrete band (LTX → 1080p; a\n * {@link PRICING_DEFAULT_RESOLUTION} member → its declared default). Leaving\n * the key unset then lets the provider pick — documented for the KIE members\n * (their `extraParams` pin the same band) but UNDOCUMENTED for LTX on\n * Replicate. Sending the band we priced makes the two agree by construction.\n *\n * The fill is deliberately limited to providers with a DECLARED default.\n * `buildVideoCreditModelIdentifier` also has un-declared fallbacks — the\n * cheapest tier for a resolution-priced provider with no\n * `PRICING_DEFAULT_RESOLUTION` row — and those are a HEDGE, not a verified\n * provider default: seedance-2 / -fast / -mini pin `resolution: \"720p\"`\n * KIE-side while the identifier prices 480p, so filling 480p would downgrade\n * the render to match a price we already know is wrong. That mismatch is a\n * pre-existing identifier bug and is fixed by seeding the row, not here.\n *\n * 2. **Duration.** Every provider whose price follows the clip length is\n * charged at the length it RENDERS: its own default when the request named\n * none (catalog `defaultDuration`), the nearest length it offers otherwise\n * (`pricedOutputDurationSec` — the runners' own snap rule). The LTX ladder is\n * seeded per (band × seconds), so a 7s request snaps onto the 6s tier;\n * sending 7s would bill six and render seven. The same value is returned for\n * the other length-priced providers (the KIE ladders, Gemini Omni), so what\n * is priced is what is sent. Auto (-1) is the model's call and is untouched.\n *\n * Pure, and IDEMPOTENT against the identifier: feeding its output back in\n * cannot move the reserved tier. `video-request-normalize.test.ts` proves that\n * over every provider × resolution × duration.\n */\nexport function pricedVideoSelection(opts: {\n provider: string\n resolution?: string\n duration?: number | string\n}): PricedVideoSelection {\n const adjustments: ModelInputAdjustment[] = []\n const ltx = ltxPricedTier(opts.provider, opts.resolution, opts.duration)\n\n // The band the request will be priced AND rendered at. An explicit value\n // always wins — this only ever fills an omission.\n const resolution = opts.resolution\n ?? (ltx ? ltx.band : PRICING_DEFAULT_RESOLUTION[opts.provider])\n\n const requested = typeof opts.duration === \"string\" ? parseInt(opts.duration, 10) : opts.duration\n const asked = requested !== undefined && !Number.isNaN(requested)\n\n // Every provider whose price follows the clip length sends the length it is\n // CHARGED at (the catalog funnel: its own default when unset, the nearest\n // legal length otherwise). Auto (-1) is the model's call and is left alone.\n const lengthPriced = !!ltx || DURATION_PRICED_PROVIDERS.has(opts.provider) || isGeminiOmniProvider(opts.provider)\n if (!lengthPriced || (!ltx && asked && requested! <= 0)) return { resolution, adjustments }\n\n const duration = ltx ? ltx.duration : pricedOutputDurationSec(opts.provider, opts.duration)\n if (asked && requested !== duration) {\n adjustments.push({\n field: \"duration\",\n from: requested!,\n to: duration,\n reason: ltx\n ? `LTX renders ${ltx.band} in ${ltx.duration}s steps — using ${ltx.duration}s instead of ${requested}s.`\n : `${opts.provider} renders ${duration}s clips at the nearest length it offers — using ${duration}s instead of ${requested}s.`,\n })\n }\n return { resolution, duration, adjustments }\n}\n\n/**\n * Compute composite model identifier for motion control with duration-tiered pricing.\n * Examples: \"kling-3.0-motion:10s\", \"kling-3.0-motion:1080p:15s\", \"motion-transfer:5s\"\n *\n * Wan Animate providers use resolution-tiered pricing (not per-second):\n * \"wan-animate-move\" (480p default), \"wan-animate-move:580p\", \"wan-animate-move:720p\"\n *\n * @param provider - Motion control provider key (\"kling\" for 2.6, \"kling-3.0\", \"wan-animate-move\", \"wan-animate-replace\")\n * @param resolution - \"720p\" or \"1080p\" (Kling), \"480p\" or \"580p\" or \"720p\" (Wan Animate)\n * @param videoDuration - Reference video duration in seconds (defaults to 10s, unused for Wan Animate)\n */\nexport function buildMotionCreditModelIdentifier(\n provider: string,\n resolution: string,\n videoDuration?: number,\n): string {\n // Wan Animate providers use resolution-tiered pricing (not duration-based)\n if (provider === \"wan-animate-move\" || provider === \"wan-animate-replace\") {\n // 480p is the default (base identifier), 580p and 720p get composite suffix\n if (resolution === \"580p\" || resolution === \"720p\") {\n return `${provider}:${resolution}`\n }\n return provider\n }\n\n const raw = videoDuration ?? 10\n const durationSec = Math.floor(Number.isNaN(raw) ? 10 : raw) // default 10s; floor to match KIE per-second billing\n const tier = MOTION_DURATION_TIERS.find(t => durationSec <= t.maxSeconds)\n ?? MOTION_DURATION_TIERS[MOTION_DURATION_TIERS.length - 1]\n\n const base = provider === \"kling-3.0\" ? \"kling-3.0-motion\" : \"motion-transfer\"\n const resSuffix = resolution === \"1080p\" ? \":1080p\" : \"\"\n return `${base}${resSuffix}:${tier.suffix}`\n}\n\n/**\n * The Suno operations whose credit key depends on the model VERSION.\n *\n * `/v1/suno/generate`, `/cover` and `/extend` resolve their creditGuard\n * identifier through `sunoCreditType(model, <operation>)` (routes/suno.ts\n * :247-249, :335-337, :407-409). EVERY other Suno route charges a flat\n * per-operation key and ignores the version the node carries — mashup (:648),\n * add-instrumental (:852), add-vocals (:907), upload-extend (:1016),\n * replace-section (:710), style-boost (:771), convert-wav (:962),\n * lyrics (:482), music-video (:594), voice (:1218).\n *\n * Anything that QUOTES a Suno price — a dropdown row, a node badge, the\n * workflow-credit estimator — must follow the same split, or it displays a\n * credit key the route never charges.\n */\nexport const SUNO_VERSION_PRICED_OPERATIONS = [\n \"suno-generate\",\n \"suno-cover\",\n \"suno-extend\",\n] as const\n\n/**\n * The seven Suno operations that appear behind a select/dropdown UI (model\n * pickers, node badges, the credit estimator) — the three version-priced\n * operations above, plus the four flat-key operations exercised by\n * `sunoCreditType`'s own test suite. A readonly tuple so later tasks (the\n * model dropdowns, node badges) can iterate or count it without redeclaring\n * the list and drifting from this one.\n */\nexport const SUNO_SELECT_OPERATIONS = [\n \"suno-generate\",\n \"suno-cover\",\n \"suno-extend\",\n \"suno-mashup\",\n \"suno-add-instrumental\",\n \"suno-add-vocals\",\n \"suno-upload-extend\",\n] as const\n\n/**\n * Adjust Speed's price id: motion-compensated (\"smooth\") interpolation is its\n * own, dearer tier. The route, the workflow run, and the editor's badge and\n * run estimate all price through this, so none of them can quote the fast tier\n * for a smooth run.\n */\nexport function speedRampCreditId(quality: unknown): \"speed-ramp\" | \"speed-ramp:smooth\" {\n return quality === \"smooth\" ? \"speed-ramp:smooth\" : \"speed-ramp\"\n}\n\n/**\n * Apply EDL's price id: a `proxy` render (the 720p preview) is its own,\n * cheaper per-output-minute row; a `final` render keeps the bare id. One id per\n * QUALITY, for a video and an audio output alike (decided 2026-10-04). Anything\n * that is not exactly \"proxy\" is the final, as the route and the node default\n * it. The route, the workflow run, and the editor's badge and run estimate all\n * price through this; the job itself is always named `apply-edl`.\n */\nexport function applyEdlCreditId(quality: unknown): \"apply-edl\" | \"apply-edl:proxy\" {\n return quality === \"proxy\" ? \"apply-edl:proxy\" : \"apply-edl\"\n}\n\n/**\n * Speaker View's price tiers (decided 2026-10-10, C4): a render is priced by\n * how many speakers it composites at once. `standard` — at most two tiles on\n * any segment and no zoom; `complex` — three to six tiles, or any zoom. Which\n * tier a render is in is the render rule's to say (the app's\n * `@nodaro/render-rules`), never this vocabulary's.\n */\nexport const SPEAKER_VIEW_PRICE_TIERS = [\"standard\", \"complex\"] as const\nexport type SpeakerViewPriceTier = (typeof SPEAKER_VIEW_PRICE_TIERS)[number]\n\nexport type SpeakerViewCreditId = \"speaker-view\" | \"speaker-view:proxy\" | \"speaker-view:complex\" | \"speaker-view:complex:proxy\"\n\n/** Every id `speakerViewCreditId` can name. */\nexport const SPEAKER_VIEW_CREDIT_IDS: readonly SpeakerViewCreditId[] = Object.freeze([\n \"speaker-view\",\n \"speaker-view:proxy\",\n \"speaker-view:complex\",\n \"speaker-view:complex:proxy\",\n] as const)\n\n/**\n * The credit id of a Speaker View render (F4, decided 2026-09-23; tiers\n * decided 2026-10-10): a Preview (`quality` \"proxy\") reserves on its own row,\n * anything else on the final's, and each in its price tier — `standard` on\n * `speaker-view` / `speaker-view:proxy`, `complex` on `speaker-view:complex` /\n * `speaker-view:complex:proxy`. A tier that is not exactly `standard` (absent\n * included) names the `complex` row: a caller that cannot tell quotes high,\n * never low. The job is always named `speaker-view`; only its credit id\n * follows the quality and the tier.\n */\nexport function speakerViewCreditId(quality: unknown, tier?: unknown): SpeakerViewCreditId {\n const proxy = quality === \"proxy\"\n if (tier === \"standard\") return proxy ? \"speaker-view:proxy\" : \"speaker-view\"\n return proxy ? \"speaker-view:complex:proxy\" : \"speaker-view:complex\"\n}\n\n/**\n * OUR Nodaro credit key for a Suno operation, given the model version and the\n * operation (which is also the node type and the BullMQ job name).\n *\n * This is the single source of truth for the Suno pricing contract, shared by\n * the reservation path (routes/suno.ts creditGuard), the egress seam\n * (workers/handlers/suno.ts `modelKey`, which must match what was reserved),\n * both workflow-credit estimators (ee/billing/credits.ts and the frontend\n * config-panels/helpers.ts), the seven Suno model dropdowns and the three Suno\n * node badges. It is a billing key — NEVER a KIE provider id — which is what\n * satisfies the B3 egress invariant.\n *\n * The version → key map is {@link SUNO_VERSION_CREDIT_KEYS}; a version with no\n * entry (V4 / V4_5 / V4_5ALL / V4_5PLUS) falls back to the operation key, and a\n * non-version-priced operation is returned unchanged.\n */\nexport function sunoCreditType(model: string | undefined, operation: string): string {\n if (!(SUNO_VERSION_PRICED_OPERATIONS as readonly string[]).includes(operation)) {\n return operation\n }\n return (model && SUNO_VERSION_CREDIT_KEYS[model]) || operation\n}\n\n/**\n * Suno version → Nodaro credit key for the version-priced operations. One row\n * per version that has its own `model_pricing` row / `STATIC_CREDIT_COSTS`\n * entry / `MODEL_CATALOG` pricing row, so an admin can reprice one version\n * without touching code. Every ACTIVE version MUST have a row here — guarded\n * by `__tests__/suno-credit-type.test.ts` (a new active version with no key\n * would silently bill at the operation key).\n */\nexport const SUNO_VERSION_CREDIT_KEYS: Readonly<Record<string, string>> = {\n V6: \"suno-v6\",\n V6_WILD: \"suno-v6_wild\",\n V6_MINI: \"suno-v6_mini\",\n V5_5: \"suno-v5_5\",\n V5: \"suno-v5\",\n}\n"]}
|