@nodaro/shared 3.63.0 → 3.64.0
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-AE3AAJ4O.js → chunk-36VWLB4J.js} +3 -3
- package/dist/{chunk-AE3AAJ4O.js.map → chunk-36VWLB4J.js.map} +1 -1
- package/dist/{chunk-HWQ2SYNA.js → chunk-3AYM47GW.js} +5 -5
- package/dist/{chunk-HWQ2SYNA.js.map → chunk-3AYM47GW.js.map} +1 -1
- package/dist/{chunk-CZ5IQB3L.js → chunk-3KTWYYCN.js} +8 -5
- package/dist/chunk-3KTWYYCN.js.map +1 -0
- package/dist/{chunk-4MMZD63H.js → chunk-4IUE2JB7.js} +3 -3
- package/dist/{chunk-4MMZD63H.js.map → chunk-4IUE2JB7.js.map} +1 -1
- package/dist/{chunk-M5OCFGHF.cjs → chunk-5OBTGNUQ.cjs} +296 -25
- package/dist/chunk-5OBTGNUQ.cjs.map +1 -0
- package/dist/{chunk-ZPE2ZTJ4.cjs → chunk-67CMMTLN.cjs} +4 -4
- package/dist/{chunk-ZPE2ZTJ4.cjs.map → chunk-67CMMTLN.cjs.map} +1 -1
- package/dist/{chunk-WRSWH7US.cjs → chunk-6BRWPJPP.cjs} +17 -2
- package/dist/chunk-6BRWPJPP.cjs.map +1 -0
- package/dist/{chunk-HBXF6RUU.js → chunk-6YIV37V7.js} +4 -4
- package/dist/{chunk-HBXF6RUU.js.map → chunk-6YIV37V7.js.map} +1 -1
- package/dist/{chunk-F6WGGYQW.cjs → chunk-7AJGUI7L.cjs} +37 -15
- package/dist/chunk-7AJGUI7L.cjs.map +1 -0
- package/dist/{chunk-KCZHQH2O.js → chunk-7KQ6W5DS.js} +4 -4
- package/dist/{chunk-KCZHQH2O.js.map → chunk-7KQ6W5DS.js.map} +1 -1
- package/dist/{chunk-TM5JYSJF.cjs → chunk-ACZZHHFZ.cjs} +72 -33
- package/dist/chunk-ACZZHHFZ.cjs.map +1 -0
- package/dist/{chunk-Y35JQPT6.cjs → chunk-AZNZ5WNZ.cjs} +42 -42
- package/dist/{chunk-Y35JQPT6.cjs.map → chunk-AZNZ5WNZ.cjs.map} +1 -1
- package/dist/{chunk-HSHCCBIV.js → chunk-BQYCZLMF.js} +16 -3
- package/dist/chunk-BQYCZLMF.js.map +1 -0
- package/dist/{chunk-GMBDLNLD.cjs → chunk-CHS2SIP6.cjs} +183 -60
- package/dist/chunk-CHS2SIP6.cjs.map +1 -0
- package/dist/{chunk-77WU3V3J.cjs → chunk-CHTZZRAL.cjs} +6 -6
- package/dist/{chunk-77WU3V3J.cjs.map → chunk-CHTZZRAL.cjs.map} +1 -1
- package/dist/{chunk-WZVIBAKN.cjs → chunk-D4KWNDPH.cjs} +12 -12
- package/dist/{chunk-WZVIBAKN.cjs.map → chunk-D4KWNDPH.cjs.map} +1 -1
- package/dist/{chunk-PSKZKLDG.js → chunk-DZ4IOP3Q.js} +288 -26
- package/dist/chunk-DZ4IOP3Q.js.map +1 -0
- package/dist/{chunk-XGVJGNZW.cjs → chunk-EXEVT6D2.cjs} +15 -5
- package/dist/chunk-EXEVT6D2.cjs.map +1 -0
- package/dist/{chunk-X5BAFW3Q.cjs → chunk-FHGRKQVZ.cjs} +8 -8
- package/dist/{chunk-X5BAFW3Q.cjs.map → chunk-FHGRKQVZ.cjs.map} +1 -1
- package/dist/{chunk-GSKLPI3J.cjs → chunk-GTWUS6MQ.cjs} +118 -61
- package/dist/chunk-GTWUS6MQ.cjs.map +1 -0
- package/dist/{chunk-Q6IES3U2.js → chunk-H5KHWTAE.js} +5 -2
- package/dist/chunk-H5KHWTAE.js.map +1 -0
- package/dist/{chunk-V5EEQR2U.cjs → chunk-HDPJNNMF.cjs} +21 -21
- package/dist/{chunk-V5EEQR2U.cjs.map → chunk-HDPJNNMF.cjs.map} +1 -1
- package/dist/{chunk-6M563QE6.js → chunk-IYSOVS7O.js} +55 -23
- package/dist/chunk-IYSOVS7O.js.map +1 -0
- package/dist/{chunk-XGGZWA4A.cjs → chunk-J6B7J73J.cjs} +52 -49
- package/dist/chunk-J6B7J73J.cjs.map +1 -0
- package/dist/{chunk-MD4XHED4.js → chunk-KB2SQAR3.js} +3 -3
- package/dist/{chunk-MD4XHED4.js.map → chunk-KB2SQAR3.js.map} +1 -1
- package/dist/{chunk-BLJUCPMV.cjs → chunk-KSHAAPQF.cjs} +5 -2
- package/dist/chunk-KSHAAPQF.cjs.map +1 -0
- package/dist/{chunk-6TGB7ECA.cjs → chunk-O4RPXBDZ.cjs} +12 -8
- package/dist/chunk-O4RPXBDZ.cjs.map +1 -0
- package/dist/{chunk-YUER7TJG.js → chunk-OBOOHG3N.js} +13 -4
- package/dist/chunk-OBOOHG3N.js.map +1 -0
- package/dist/{chunk-6BZC2ZHC.cjs → chunk-OOZW2MM6.cjs} +9 -9
- package/dist/{chunk-6BZC2ZHC.cjs.map → chunk-OOZW2MM6.cjs.map} +1 -1
- package/dist/{chunk-A2PX5IRC.cjs → chunk-PERUFUVH.cjs} +13 -13
- package/dist/{chunk-A2PX5IRC.cjs.map → chunk-PERUFUVH.cjs.map} +1 -1
- package/dist/{chunk-3K24DWOH.js → chunk-PJJAZQVZ.js} +3 -3
- package/dist/{chunk-3K24DWOH.js.map → chunk-PJJAZQVZ.js.map} +1 -1
- package/dist/{chunk-EPXGG27L.js → chunk-Q2Y4JHF7.js} +5 -5
- package/dist/{chunk-EPXGG27L.js.map → chunk-Q2Y4JHF7.js.map} +1 -1
- package/dist/{chunk-KMGCHV6O.js → chunk-QYU7J5EQ.js} +37 -15
- package/dist/chunk-QYU7J5EQ.js.map +1 -0
- package/dist/{chunk-IY3Y462W.js → chunk-S3UGLZSF.js} +3 -3
- package/dist/{chunk-IY3Y462W.js.map → chunk-S3UGLZSF.js.map} +1 -1
- package/dist/{chunk-34QLPTSA.js → chunk-SHH2T4CR.js} +3 -3
- package/dist/{chunk-34QLPTSA.js.map → chunk-SHH2T4CR.js.map} +1 -1
- package/dist/{chunk-L2TVY6XN.cjs → chunk-SPAHI7DY.cjs} +4 -4
- package/dist/{chunk-L2TVY6XN.cjs.map → chunk-SPAHI7DY.cjs.map} +1 -1
- package/dist/{chunk-YX6TFX7H.js → chunk-SXHHLZ22.js} +66 -11
- package/dist/chunk-SXHHLZ22.js.map +1 -0
- package/dist/{chunk-LMAQUR55.cjs → chunk-T2OVDF2M.cjs} +6 -6
- package/dist/{chunk-LMAQUR55.cjs.map → chunk-T2OVDF2M.cjs.map} +1 -1
- package/dist/{chunk-2QKF7M2Z.js → chunk-TAPBDT47.js} +3 -3
- package/dist/{chunk-2QKF7M2Z.js.map → chunk-TAPBDT47.js.map} +1 -1
- package/dist/{chunk-BMJVKYVB.js → chunk-TPQJKS7D.js} +109 -7
- package/dist/chunk-TPQJKS7D.js.map +1 -0
- package/dist/{chunk-63H4C56Q.cjs → chunk-TQW3R44P.cjs} +8 -8
- package/dist/{chunk-63H4C56Q.cjs.map → chunk-TQW3R44P.cjs.map} +1 -1
- package/dist/{chunk-4DVWXEB6.js → chunk-TTGZ2L3O.js} +3 -3
- package/dist/{chunk-4DVWXEB6.js.map → chunk-TTGZ2L3O.js.map} +1 -1
- package/dist/{chunk-XBTYGQ6Z.js → chunk-VPTA4Z7G.js} +8 -5
- package/dist/chunk-VPTA4Z7G.js.map +1 -0
- package/dist/{chunk-6XUG4L7X.cjs → chunk-VZ6TE23U.cjs} +6 -6
- package/dist/{chunk-6XUG4L7X.cjs.map → chunk-VZ6TE23U.cjs.map} +1 -1
- package/dist/{chunk-LH72PQO2.cjs → chunk-W6VJAUGM.cjs} +114 -45
- package/dist/chunk-W6VJAUGM.cjs.map +1 -0
- package/dist/{chunk-OV3JTKBY.js → chunk-W7KHHNZR.js} +74 -17
- package/dist/chunk-W7KHHNZR.js.map +1 -0
- package/dist/{chunk-2PU3AGGS.cjs → chunk-YQV53HRR.cjs} +7 -7
- package/dist/{chunk-2PU3AGGS.cjs.map → chunk-YQV53HRR.cjs.map} +1 -1
- package/dist/{chunk-FXGNRYQQ.js → chunk-ZI3QDUHO.js} +3 -3
- package/dist/{chunk-FXGNRYQQ.js.map → chunk-ZI3QDUHO.js.map} +1 -1
- package/dist/entries/apps.cjs +43 -42
- package/dist/entries/apps.js +8 -7
- package/dist/entries/captions.cjs +38 -30
- package/dist/entries/captions.d.cts +47 -1
- package/dist/entries/captions.d.ts +47 -1
- package/dist/entries/captions.js +1 -1
- package/dist/entries/credits.cjs +303 -191
- package/dist/entries/credits.d.cts +219 -15
- package/dist/entries/credits.d.ts +219 -15
- package/dist/entries/credits.js +11 -11
- package/dist/entries/llm-models.cjs +62 -62
- package/dist/entries/llm-models.d.cts +29 -7
- package/dist/entries/llm-models.d.ts +29 -7
- package/dist/entries/llm-models.js +2 -2
- package/dist/entries/model-catalog.cjs +149 -109
- package/dist/entries/model-catalog.d.cts +64 -7
- package/dist/entries/model-catalog.d.ts +64 -7
- package/dist/entries/model-catalog.js +4 -4
- package/dist/entries/models.cjs +394 -346
- package/dist/entries/models.d.cts +4 -4
- package/dist/entries/models.d.ts +4 -4
- package/dist/entries/models.js +5 -5
- package/dist/entries/nodes.cjs +220 -211
- package/dist/entries/nodes.d.cts +46 -3
- package/dist/entries/nodes.d.ts +46 -3
- package/dist/entries/nodes.js +10 -9
- package/dist/entries/pipeline.cjs +156 -152
- package/dist/entries/pipeline.d.cts +13 -3
- package/dist/entries/pipeline.d.ts +13 -3
- package/dist/entries/pipeline.js +3 -3
- package/dist/entries/social.cjs +177 -177
- package/dist/entries/social.js +2 -2
- package/dist/entries/ugc.cjs +71 -71
- package/dist/entries/ugc.js +4 -4
- package/dist/entries/video.cjs +145 -145
- package/dist/entries/video.js +6 -6
- package/dist/entries/workflow.cjs +150 -150
- package/dist/entries/workflow.d.cts +1 -1
- package/dist/entries/workflow.d.ts +1 -1
- package/dist/entries/workflow.js +2 -2
- package/dist/index.cjs +1879 -1659
- package/dist/index.d.cts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +25 -25
- package/dist/{model-catalog-C_Eo35tL.d.cts → model-catalog-Cf9fkEUp.d.cts} +15 -2
- package/dist/{model-catalog-C_Eo35tL.d.ts → model-catalog-Cf9fkEUp.d.ts} +15 -2
- package/dist/{model-constants-DWcxOmaY.d.cts → model-constants-BxjiWVQ9.d.ts} +89 -19
- package/dist/{model-constants-Bg4ccSQb.d.ts → model-constants-C_Nyft_i.d.cts} +89 -19
- package/package.json +1 -1
- package/src/__tests__/add-captions-nemotron-pricing.test.ts +111 -0
- package/src/__tests__/extend-providers.test.ts +266 -26
- package/src/__tests__/fixtures/mask-composite-quote-parity.json +1 -1
- package/src/__tests__/fixtures/measured-input-quote-parity.json +1435 -0
- package/src/__tests__/fixtures/planned-length-quote-parity.json +1866 -0
- package/src/__tests__/fixtures/video-utility-quote-parity.json +2343 -0
- package/src/__tests__/flux-3-klein.test.ts +203 -0
- package/src/__tests__/gpt-image-2-6-formats.test.ts +3 -1
- package/src/__tests__/llm-models.test.ts +7 -9
- package/src/__tests__/llm-price-key.test.ts +12 -0
- package/src/__tests__/model-makers.test.ts +3 -0
- package/src/__tests__/node-runtime-keys.test.ts +7 -0
- package/src/__tests__/normalize-node-params.test.ts +147 -1
- package/src/__tests__/retired-lip-sync-providers.test.ts +43 -0
- package/src/__tests__/seedance-extend-source-credit-id.test.ts +89 -0
- package/src/__tests__/sequence-execution.test.ts +22 -1
- package/src/__tests__/suno-credit-type.test.ts +21 -2
- package/src/__tests__/transcribe-capabilities.test.ts +4 -2
- package/src/__tests__/video-analysis-catalog-sync.test.ts +4 -2
- package/src/__tests__/video-analysis-pricing.test.ts +10 -9
- package/src/caption-styles.ts +62 -0
- package/src/credit-estimators/add-captions-nemotron.ts +73 -0
- package/src/credit-estimators/index.ts +10 -0
- package/src/credit-identifiers.ts +249 -13
- package/src/entries/captions.ts +2 -0
- package/src/entries/credits.ts +25 -1
- package/src/entries/model-catalog.ts +13 -0
- package/src/entries/models.ts +15 -0
- package/src/entries/nodes.ts +2 -0
- package/src/entries/pipeline.ts +1 -1
- package/src/flux-3-klein.ts +69 -0
- package/src/input-image-pricing.ts +23 -6
- package/src/llm-models.ts +60 -16
- package/src/model-catalog.ts +280 -25
- package/src/model-constants.ts +146 -17
- package/src/node-default-mappings.ts +3 -0
- package/src/node-runtime-keys.ts +3 -0
- package/src/normalize-node-params.ts +123 -2
- package/src/seedance-extend-rate.ts +116 -0
- package/src/sequence-execution.ts +24 -0
- package/src/transcribe-preflight.ts +23 -0
- package/src/video-analysis-pricing.ts +28 -15
- package/dist/chunk-6M563QE6.js.map +0 -1
- package/dist/chunk-6TGB7ECA.cjs.map +0 -1
- package/dist/chunk-BLJUCPMV.cjs.map +0 -1
- package/dist/chunk-BMJVKYVB.js.map +0 -1
- package/dist/chunk-CZ5IQB3L.js.map +0 -1
- package/dist/chunk-F6WGGYQW.cjs.map +0 -1
- package/dist/chunk-GMBDLNLD.cjs.map +0 -1
- package/dist/chunk-GSKLPI3J.cjs.map +0 -1
- package/dist/chunk-HSHCCBIV.js.map +0 -1
- package/dist/chunk-KMGCHV6O.js.map +0 -1
- package/dist/chunk-LH72PQO2.cjs.map +0 -1
- package/dist/chunk-M5OCFGHF.cjs.map +0 -1
- package/dist/chunk-OV3JTKBY.js.map +0 -1
- package/dist/chunk-PSKZKLDG.js.map +0 -1
- package/dist/chunk-Q6IES3U2.js.map +0 -1
- package/dist/chunk-TM5JYSJF.cjs.map +0 -1
- package/dist/chunk-WRSWH7US.cjs.map +0 -1
- package/dist/chunk-XBTYGQ6Z.js.map +0 -1
- package/dist/chunk-XGGZWA4A.cjs.map +0 -1
- package/dist/chunk-XGVJGNZW.cjs.map +0 -1
- package/dist/chunk-YUER7TJG.js.map +0 -1
- package/dist/chunk-YX6TFX7H.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/credit-conversion.ts","../src/film-pricing.ts","../src/credit-estimators/video-utils.ts","../src/credit-estimators/image-overlay.ts","../src/credit-estimators/video-sfx.ts","../src/credit-estimators/text-to-audio.ts","../src/credit-estimators/ltx-extend.ts","../src/credit-estimators/ltx-retake.ts","../src/credit-estimators/speech.ts","../src/credit-estimators/voice-changer-pro-quote.ts","../src/credit-estimators/pitch-tempo.ts","../src/credit-estimators/nemotron-transcribe.ts","../src/credit-estimators/video-overlay.ts","../src/topaz-upscale.ts","../src/upscale-factors.ts","../src/monetization.ts","../src/lip-sync-pricing.ts","../src/ai-avatar-pricing.ts","../src/switchx-pricing.ts","../src/cinematic-avatar-pricing.ts","../src/avatar-payload-validators.ts","../src/effective-tier.ts","../src/video-analysis-pricing.ts","../src/content-recipe-ideas.ts"],"names":["CREDIT_BASE_USD","known","output","overlayPlatformById","DEFAULT_TEXT_TO_AUDIO_PROVIDER","canonicalTtsProvider","unitQuoteCreditId","findTtsCapabilities","findDialogueCapabilities","VIDEO_OVERLAY_VIDEO_MAX_BASE_SEC","pricedClipSeconds","ALLOWED_RESOLUTIONS","getLlmModel","LLM_FEATURE_DEFAULTS","buildLlmCreditIdentifier"],"mappings":";;;;;;;;;;;;AAoBO,IAAM,0BAAA,GAA6B;AAE1C,SAAS,gBAAgB,GAAA,EAAmB;AAC1C,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,GAAG,CAAA,QAAS,IAAI,KAAA,CAAM,CAAA,uCAAA,EAA0C,GAAG,CAAA,CAAE,CAAA;AAC1F,EAAA,IAAI,MAAM,CAAA,EAAG,MAAM,IAAI,KAAA,CAAM,CAAA,6CAAA,EAAgD,GAAG,CAAA,CAAE,CAAA;AACpF;AAGO,SAAS,aAAa,GAAA,EAAqB;AAChD,EAAA,eAAA,CAAgB,GAAG,CAAA;AACnB,EAAA,MAAM,YAAA,GAAe,IAAA,CAAK,KAAA,CAAO,GAAA,GAAMA,oCAAmB,0BAA0B,CAAA;AACpF,EAAA,OAAO,IAAA,CAAK,IAAA,CAAK,YAAA,GAAe,0BAA0B,CAAA;AAC5D;AAGO,SAAS,aAAa,OAAA,EAAyB;AACpD,EAAA,IAAI,CAAC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AAC,CAAA;AACzD;AAGO,SAAS,0BAA0B,KAAA,EAAqD;AAC7F,EAAA,OAAO,KAAA,GAAQ,2BAA2B,kBAAA,GAAqB,eAAA;AACjE;AAKO,SAAS,qBAAA,CAAsB,SAA6C,QAAA,EAA2B;AAC5G,EAAA,IAAI,OAAO,aAAa,QAAA,IAAYC,6BAAA,CAAY,QAAQ,CAAA,EAAG,oBAAA,IAAwB,MAAM,OAAO,QAAA;AAChG,EAAA,OAAOC,uCAAqB,OAAO,CAAA;AACrC;AAEO,SAAS,qBAAA,CAAsB,UAAoB,eAAA,EAAkC;AAC1F,EAAA,OAAOC,2CAAyB,gBAAA,EAAkB,qBAAA,CAAsB,gBAAA,EAAkB,QAAQ,GAAG,eAAe,CAAA;AACtH;AAEO,SAAS,oBAAA,CAAqB,KAAA,EAAgB,QAAA,EAAoB,eAAA,EAAkC;AACzG,EAAA,OAAOA,0CAAA;AAAA,IACL,yBAAA,CAA0B,sBAAA,CAAuB,KAAK,CAAC,CAAA;AAAA,IACvD,qBAAA,CAAsB,iBAAiB,QAAQ,CAAA;AAAA,IAC/C;AAAA,GACF;AACF;AAGO,IAAM,+BAAA,GAAkC;AAAA,EAC7C,wBAAA;AAAA,EACA,gBAAA;AAAA,EACA,wBAAA;AAAA,EACA,+BAAA;AAAA,EACA,uBAAA;AAAA,EACA,eAAA;AAAA,EACA,uBAAA;AAAA,EACA,8BAAA;AAAA,EACA,0BAAA;AAAA,EACA,kBAAA;AAAA,EACA,0BAAA;AAAA,EACA;AACF","file":"chunk-TM5JYSJF.cjs","sourcesContent":["/**\n * The ONLY place credit⇄USD arithmetic is written.\n *\n * Every credit figure derives from {@link CREDIT_BASE_USD}. Dividing by a\n * hardcoded copy of that number instead makes the base impossible to change\n * without a multi-file hunt, so route conversions through here.\n *\n * MILLI-CREDIT GUARD — do not remove. `usd / base` is IEEE-754 division and\n * lands a hair above an integer for many exact-multiple inputs\n * (0.14 / 0.02 = 7.000000000000001), so a bare `Math.ceil` rounds up a whole\n * credit that was not owed. Rounding to milli-credits first absorbs that noise\n * at 1000x finer resolution than any credit-level decision.\n *\n * The guard matters at every base, not just the current one — a finer base does\n * not make it unnecessary, it only moves which inputs trip it. Do not\n * \"simplify\" it away if {@link CREDIT_BASE_USD} ever changes.\n */\nimport { CREDIT_BASE_USD } from \"./model-constants.js\"\n\n/** Milli-credits per credit — the intermediate rounding resolution. */\nexport const CREDIT_ROUNDING_RESOLUTION = 1000\n\nfunction assertUsableUsd(usd: number): void {\n if (!Number.isFinite(usd)) throw new Error(`usdToCredits: cost must be finite, got ${usd}`)\n if (usd < 0) throw new Error(`usdToCredits: cost must not be negative, got ${usd}`)\n}\n\n/** A USD amount → whole credits at the current base. Rounds up. */\nexport function usdToCredits(usd: number): number {\n assertUsableUsd(usd)\n const milliCredits = Math.round((usd / CREDIT_BASE_USD) * CREDIT_ROUNDING_RESOLUTION)\n return Math.ceil(milliCredits / CREDIT_ROUNDING_RESOLUTION)\n}\n\n/** Whole credits → their USD value at the current base. Display/reporting only. */\nexport function creditsToUsd(credits: number): number {\n if (!Number.isFinite(credits)) throw new Error(`creditsToUsd: credits must be finite, got ${credits}`)\n return credits * CREDIT_BASE_USD\n}\n","/**\n * Film cost ESTIMATION for the studio preview.\n *\n * This is display guidance only — it produces an approximate \"this film will\n * cost ≈ N credits\" number so the user can see cost before committing to a\n * length + model. The ACTUAL charge is still computed at generation time from\n * `STATIC_CREDIT_COSTS` / the `model_pricing` table per job; this module never\n * bills.\n *\n * Numbers are grounded in the KIE-calibrated per-clip credit costs in\n * `backend/src/ee/billing/credits.ts` (each entry there is annotated with its\n * KIE-credit + USD source). A backend test cross-checks `VIDEO_CLIP_CREDITS`\n * against that source so the estimate can't silently drift from reality.\n *\n * Cost structure of a Story→Video film:\n * total = BASE (duration-independent planning + assembly)\n * + perShot × shotCount (the variable, model-driven bulk)\n * where a shot = one keyframe image + one video clip + one video-critic pass,\n * and shotCount ≈ ceil(duration / clipSeconds) for the chosen model.\n */\n\n/**\n * Duration-independent overhead, in credits:\n * script/showrunner LLM chain ~30 · music timeline 4 · editor LLM 3 ·\n * final merge 3 · storyboard-cohesion critic 5 ≈ 45.\n * Mirrors the fixed line items in `estimateUpfrontCredits`\n * (backend/src/ee/pipelines/credits.ts).\n */\nexport const FILM_BASE_CREDITS = 45\n\n/** Per-shot keyframe image (nano-banana class) — see STATIC_CREDIT_COSTS. */\nexport const KEYFRAME_CREDITS_PER_SHOT = 2\n/** Per-shot Video Critic pass (first_last frame mode) — see credits.ts. */\nexport const VIDEO_CRITIC_CREDITS_PER_SHOT = 2\n\nexport interface VideoClipCost {\n /** Representative per-clip credit cost at the studio's default config\n * (720p; for the Seedance 2 family this is the ref-image variant the\n * studio uses for identity). Sourced from STATIC_CREDIT_COSTS. */\n readonly credits: number\n /** Representative clip length in seconds for shot-count estimation. */\n readonly clipSeconds: number\n}\n\n/**\n * Representative per-clip credit cost for each user-pinnable video model.\n * Values are the KIE-calibrated credits from STATIC_CREDIT_COSTS at the\n * studio's typical settings (720p; Seedance 2 = 8s 720p +ref). Keep in sync\n * with that table — the backend cross-check test guards drift.\n */\nexport const VIDEO_CLIP_CREDITS: Record<string, VideoClipCost> = {\n \"kling-turbo\": { credits: 11, clipSeconds: 5 }, // kling-turbo:5s\n \"kling\": { credits: 14, clipSeconds: 5 }, // kling:5s\n \"kling-3.0\": { credits: 31, clipSeconds: 5 },\n \"seedance-2\": { credits: 50, clipSeconds: 8 }, // seedance-2:8s:720p-ref\n \"seedance-2-fast\": { credits: 40, clipSeconds: 8 }, // seedance-2-fast:8s:720p-ref\n \"seedance-2-mini\": { credits: 25, clipSeconds: 8 }, // seedance-2-mini:8s:720p-ref\n \"seedance-2-5\": { credits: 76, clipSeconds: 8 }, // seedance-2-5:8s:720p-ref\n \"veo3\": { credits: 79, clipSeconds: 8 }, // flat per generation (VEO 3.1 Quality)\n \"veo3.1\": { credits: 19, clipSeconds: 6 }, // veo3.1 @ 720p\n \"veo3_lite\": { credits: 10, clipSeconds: 6 }, // veo3_lite @ 720p\n \"minimax\": { credits: 18, clipSeconds: 6 }, // fixed ~6s\n \"hailuo-standard\": { credits: 8, clipSeconds: 6 }, // hailuo-standard:6s\n \"wan-turbo\": { credits: 13, clipSeconds: 5 }, // 5s 480p\n \"bytedance-lite\": { credits: 6, clipSeconds: 5 },\n \"bytedance-pro\": { credits: 18, clipSeconds: 5 },\n}\n\n/**\n * Fallback when no model is pinned (Auto — the Scene Director picks per scene)\n * or the model isn't in the table. kling-turbo is the cheap, common default\n * the engine gravitates to, so it's a reasonable \"≈\" anchor.\n */\nexport const DEFAULT_VIDEO_CLIP_COST: VideoClipCost = VIDEO_CLIP_CREDITS[\"kling-turbo\"]!\n\nexport interface FilmCreditEstimate {\n /** Total estimated credits for the whole film. */\n readonly totalCredits: number\n /** Fixed base portion (planning + assembly). */\n readonly baseCredits: number\n /** Variable portion (shots × per-shot). */\n readonly variableCredits: number\n /** Estimated number of shots (clips) generated. */\n readonly shotCount: number\n /** Average credits per second of film (totalCredits / duration). */\n readonly creditsPerSecond: number\n /** Whether a known model drove the estimate (false = Auto/fallback). */\n readonly modelKnown: boolean\n}\n\n/**\n * Estimate the credit cost of a Story→Video film of `durationSeconds` rendered\n * with `videoModel`. Approximate, for the studio's cost preview only.\n */\nexport function estimateFilmCredits(\n durationSeconds: number,\n videoModel?: string,\n): FilmCreditEstimate {\n const seconds = Math.max(1, Math.round(durationSeconds))\n const known = !!videoModel && videoModel in VIDEO_CLIP_CREDITS\n const clip = known ? VIDEO_CLIP_CREDITS[videoModel!]! : DEFAULT_VIDEO_CLIP_COST\n\n const shotCount = Math.max(1, Math.ceil(seconds / clip.clipSeconds))\n const perShot =\n clip.credits + KEYFRAME_CREDITS_PER_SHOT + VIDEO_CRITIC_CREDITS_PER_SHOT\n const variableCredits = shotCount * perShot\n const totalCredits = FILM_BASE_CREDITS + variableCredits\n\n return {\n totalCredits,\n baseCredits: FILM_BASE_CREDITS,\n variableCredits,\n shotCount,\n creditsPerSecond: Math.round((totalCredits / seconds) * 10) / 10,\n modelKnown: known,\n }\n}\n","/**\n * Pure credit estimators for video-utility nodes (loop-video, trim-video,\n * combine-videos, assemble-narrated-video). Used by frontend (Run-button\n * display + API call) AND backend (creditGuard reservation, the workflow\n * run's reservation, the workflow estimate) so the displayed cost equals\n * what gets debited.\n *\n * Every estimate counts pricing UNITS and returns units × CREDIT_UNIT base\n * credits: a unit is 5 seconds of output, ~24 frames a smart loop cut\n * searches, each combine input beyond two, and each step of Assemble Narrated\n * Video (3 + 1 per 6 blocks).\n */\n\nexport const VIDEO_UTIL_PRICING = {\n /** Base credits per pricing unit. The node's own `model_pricing` row is one unit. */\n CREDIT_UNIT: 10,\n /** Base credits per 5 seconds of output (one unit), ceiling. */\n CREDITS_PER_5_SEC: 10,\n /** Smart-loop-cut work scales at one unit per ~24 frames searched. */\n FRAMES_PER_CREDIT: 24,\n /** Used when an upstream node hasn't produced a measurable duration yet. */\n FALLBACK_DURATION_SECONDS: 8,\n} as const\n\n/** Base credits for a count of pricing units, never below one unit. */\nfunction unitsToCredits(units: number): number {\n return VIDEO_UTIL_PRICING.CREDIT_UNIT * Math.max(1, units)\n}\n\nexport interface LoopVideoEstimatorInput {\n mode?: \"repeat\" | \"duration\"\n repeatCount?: number\n targetDuration?: number\n smartLoopCutBeforeRepeat?: boolean\n smartLoopCutLookback?: number\n}\n\nexport interface TrimVideoEstimatorInput {\n trimMode?: \"time\" | \"seconds\" | \"keep-first-seconds\" | \"keep-last-seconds\" | \"frames\" | \"smart-loop-cut\"\n startTime?: number\n endTime?: number\n /** Seconds-mirror of frames mode: trim N seconds from start AND/OR end. */\n trimStartSeconds?: number\n trimEndSeconds?: number\n /** Keep only the first/last N seconds (probes duration at runtime). */\n keepFirstSeconds?: number\n keepLastSeconds?: number\n trimStartFrames?: number\n trimEndFrames?: number\n smartLoopCutLookback?: number\n}\n\nexport interface CombineVideosEstimatorInput {\n /** Any id from `COMBINE_TRANSITIONS`. The estimator only branches on\n * `cut` vs non-cut, so accepting the full string keeps the catalog as\n * the single source of truth. */\n transition?: string\n transitionDuration?: number\n trimStartFrames?: number\n trimEndFrames?: number\n}\n\nexport function estimateLoopVideoCredits(\n data: LoopVideoEstimatorInput,\n upstreamDuration?: number,\n): number {\n const fallback = VIDEO_UTIL_PRICING.FALLBACK_DURATION_SECONDS\n const inputDuration = upstreamDuration ?? fallback\n\n const output =\n data.mode === \"duration\"\n ? (data.targetDuration ?? fallback)\n : (data.repeatCount ?? 2) * inputDuration\n\n const base = Math.ceil(output / 5)\n const cut = data.smartLoopCutBeforeRepeat\n ? Math.ceil((data.smartLoopCutLookback ?? 16) / VIDEO_UTIL_PRICING.FRAMES_PER_CREDIT)\n : 0\n\n return unitsToCredits(base + cut)\n}\n\nexport function estimateTrimVideoCredits(\n data: TrimVideoEstimatorInput,\n upstreamDuration?: number,\n): number {\n const fallback = VIDEO_UTIL_PRICING.FALLBACK_DURATION_SECONDS\n const inputDuration = upstreamDuration ?? fallback\n\n if (data.trimMode === \"smart-loop-cut\") {\n const base = Math.ceil(inputDuration / 5)\n const cut = Math.ceil((data.smartLoopCutLookback ?? 16) / VIDEO_UTIL_PRICING.FRAMES_PER_CREDIT)\n return unitsToCredits(base + cut)\n }\n\n if (data.trimMode === \"frames\") {\n // Source fps unknown frontend-side; assume 24.\n const startSec = (data.trimStartFrames ?? 0) / VIDEO_UTIL_PRICING.FRAMES_PER_CREDIT\n const endSec = (data.trimEndFrames ?? 0) / VIDEO_UTIL_PRICING.FRAMES_PER_CREDIT\n const output = Math.max(0, inputDuration - startSec - endSec)\n return unitsToCredits(Math.ceil(output / 5))\n }\n\n if (data.trimMode === \"seconds\") {\n const output = Math.max(0, inputDuration - (data.trimStartSeconds ?? 0) - (data.trimEndSeconds ?? 0))\n return unitsToCredits(Math.ceil(output / 5))\n }\n\n if (data.trimMode === \"keep-first-seconds\") {\n const output = Math.min(inputDuration, Math.max(0, data.keepFirstSeconds ?? 0))\n return unitsToCredits(Math.ceil(output / 5))\n }\n\n if (data.trimMode === \"keep-last-seconds\") {\n const output = Math.min(inputDuration, Math.max(0, data.keepLastSeconds ?? 0))\n return unitsToCredits(Math.ceil(output / 5))\n }\n\n // \"time\" mode (default)\n const output = (data.endTime ?? 0) - (data.startTime ?? 0)\n return unitsToCredits(Math.ceil(output / 5))\n}\n\nexport function estimateCombineVideosCredits(\n data: CombineVideosEstimatorInput,\n upstreamDurations: ReadonlyArray<number | undefined>,\n): number {\n if (upstreamDurations.length === 0) return unitsToCredits(1)\n\n const fallback = VIDEO_UTIL_PRICING.FALLBACK_DURATION_SECONDS\n const n = upstreamDurations.length\n\n let total = 0\n for (const d of upstreamDurations) {\n total += typeof d === \"number\" && Number.isFinite(d) && d >= 0 ? d : fallback\n }\n\n if (data.transition && data.transition !== \"cut\" && n > 1) {\n total -= (data.transitionDuration ?? 0.5) * (n - 1)\n }\n\n const trimSecPerClip =\n ((data.trimStartFrames ?? 0) + (data.trimEndFrames ?? 0)) /\n VIDEO_UTIL_PRICING.FRAMES_PER_CREDIT\n total -= trimSecPerClip * n\n\n const base = Math.ceil(Math.max(0, total) / 5)\n const inputAdder = Math.max(0, n - 2)\n return unitsToCredits(base + inputAdder)\n}\n\nexport interface LoopTrimEstimatorInput {\n enabled?: boolean\n framesToTest?: number\n}\n\n/** Add-on credits charged for the smart-loop-cut post-process applied to an\n * image-to-video output. Returns 0 when loopTrim is undefined or disabled.\n * Formula: CREDIT_UNIT × (ceil(duration / 5) + ceil(framesToTest / 24)) —\n * the same units as Trim Video's smart loop cut, so 8 s at 16 frames → 30. */\nexport function estimateLoopTrimAddonCredits(\n loopTrim: LoopTrimEstimatorInput | undefined,\n outputDurationSeconds: number,\n): number {\n if (!loopTrim?.enabled) return 0\n const frames = Math.max(1, Math.min(loopTrim.framesToTest ?? 16, 64))\n return unitsToCredits(\n Math.ceil(outputDurationSeconds / 5) + Math.ceil(frames / VIDEO_UTIL_PRICING.FRAMES_PER_CREDIT),\n )\n}\n\n/** BASE credits for assemble-narrated-video: 3 units flat + 1 per 6\n * blocks. 6→40, 24→70, 60→130. Single source of truth shared by the backend\n * route/creditGuard (`backend/src/providers/video/narrated-block-fit.ts`\n * re-exports this), the workflow run's reservation and the frontend pre-run\n * estimate (`frontend/src/hooks/use-estimated-credits.ts`). */\nexport function assembleNarratedVideoCredits(blockCount: number): number {\n return unitsToCredits(3 + Math.ceil(blockCount / 6))\n}\n","import { overlayPlatformById } from \"../image-overlay-platforms.js\"\n\n/**\n * Image Overlay pricing — one formula shared by the backend route\n * (creditGuard computeCredits), the orchestrator's reservation override, the\n * workflow estimator and the canvas Run button, so every surface quotes and\n * charges the same number.\n *\n * credits = BASE + PER_VARIANT × (number of distinct, valid platform ids)\n *\n * The base covers the composite and its mask; every extra platform render is\n * one more resize + encode + upload. Worked examples (pinned by the tests and\n * repeated in docs/nodes/processing-video/image-overlay.md — keep them equal):\n * 0 variants → 10, 2 → 14, 12 (every platform) → 34.\n */\nexport const IMAGE_OVERLAY_BASE_CREDITS = 10\nexport const IMAGE_OVERLAY_VARIANT_CREDITS = 2\n\n/** Distinct platform ids the registry knows — the count the price is built from. */\nexport function imageOverlayBillableVariants(variants: ReadonlyArray<unknown> | undefined): string[] {\n const seen = new Set<string>()\n for (const v of variants ?? []) {\n if (typeof v === \"string\" && overlayPlatformById(v)) seen.add(v)\n }\n return [...seen]\n}\n\nexport function imageOverlayCredits(variants: ReadonlyArray<unknown> | undefined): number {\n return IMAGE_OVERLAY_BASE_CREDITS + IMAGE_OVERLAY_VARIANT_CREDITS * imageOverlayBillableVariants(variants).length\n}\n","/**\n * Video SFX pricing — which price row a run is charged from, by the length of\n * the input video. One mapping for every place that names the row: the route\n * (`POST /v1/video-sfx`), the workflow run's reservation, the node's Run\n * button and the workflow estimates.\n *\n * Each bucket is a `model_pricing` row (`replicate-mmaudio:<n>s`); the credit\n * amounts live there, never here. Worked examples (repeated in\n * docs/nodes/ai-video/video-sfx.md):\n * 5 s → `:8s`, 12 s → `:15s`, 31 s → `:60s`, 180 s → `:300s`.\n */\n\nexport const VIDEO_SFX_PRICING = {\n /** The longest input video a run accepts, in seconds. */\n MAX_DURATION_SEC: 300,\n /** The length priced (and generated) when the input video cannot be measured. */\n FALLBACK_DURATION_SEC: 8,\n} as const\n\nconst VIDEO_SFX_BUCKETS: ReadonlyArray<{ readonly upToSec: number; readonly creditId: string }> = [\n { upToSec: 8, creditId: \"replicate-mmaudio:8s\" },\n { upToSec: 15, creditId: \"replicate-mmaudio:15s\" },\n { upToSec: 30, creditId: \"replicate-mmaudio:30s\" },\n { upToSec: 60, creditId: \"replicate-mmaudio:60s\" },\n { upToSec: 120, creditId: \"replicate-mmaudio:120s\" },\n { upToSec: 300, creditId: \"replicate-mmaudio:300s\" },\n]\n\n/**\n * The price row for an input video of `durationSec` seconds. An unknown or\n * non-positive length prices the fallback length; anything past the cap prices\n * the last bucket (the route refuses such a video before it gets here).\n */\nexport function videoSfxCreditId(durationSec: number | null | undefined): string {\n const seconds =\n typeof durationSec === \"number\" && Number.isFinite(durationSec) && durationSec > 0\n ? durationSec\n : VIDEO_SFX_PRICING.FALLBACK_DURATION_SEC\n const bucket = VIDEO_SFX_BUCKETS.find((b) => seconds <= b.upToSec) ?? VIDEO_SFX_BUCKETS[VIDEO_SFX_BUCKETS.length - 1]!\n return bucket.creditId\n}\n\n/**\n * The price row a QUOTE names for an input video of `durationSec` seconds —\n * every estimate before a run (the node's Run button, the workflow estimate,\n * the server's run estimate, a listing). A known length is the row its run is\n * charged ({@link videoSfxCreditId}). An UNKNOWN length is the last row, 300\n * seconds (decided 2026-10-13): a run measures the clip before it reserves and\n * refuses one over 300 s, so that row is the most any run can be charged —\n * the quote is never below the charge, as Video Mask and Video Depth quote an\n * unknown clip at their highest row.\n */\nexport function videoSfxQuoteCreditId(durationSec: number | null | undefined): string {\n const known = typeof durationSec === \"number\" && Number.isFinite(durationSec) && durationSec > 0\n return videoSfxCreditId(known ? durationSec : VIDEO_SFX_PRICING.MAX_DURATION_SEC)\n}\n","/**\n * Text to Audio (sound effects) pricing — which price row a run is charged\n * from, by the length of the clip it asks for. One mapping for every place\n * that names the row: the route (`POST /v1/text-to-audio`), the workflow run's\n * reservation, the node's Run button and the workflow estimates.\n *\n * `elevenlabs-sfx` is priced per second: one `model_pricing` row per whole\n * second (`elevenlabs-sfx:1s` … `elevenlabs-sfx:30s`); the credit amounts live\n * there, never here. The requested length is rounded UP to whole seconds, and\n * a request that names no length is priced as 5 seconds. Worked examples\n * (repeated in docs/nodes/ai-audio/text-to-audio.md):\n * 0.5 s → `:1s`, 6 s → `:6s`, 22.3 s → `:23s`, no duration → `:5s`.\n */\n\nimport { DEFAULT_TEXT_TO_AUDIO_PROVIDER } from \"../model-constants.js\"\n\nexport const TEXT_TO_AUDIO_PRICING = {\n /** The engine priced per second of requested audio. */\n PER_SECOND_PROVIDER: \"elevenlabs-sfx\",\n /** The longest clip a request may ask for, in seconds. */\n MAX_DURATION_SEC: 30,\n /** The length priced when a request names none (the model picks the length). */\n DEFAULT_BILLED_SEC: 5,\n} as const\n\n/** Every per-second price row, shortest first: `elevenlabs-sfx:1s` … `:30s`. */\nexport const TEXT_TO_AUDIO_SFX_CREDIT_IDS: readonly string[] = Array.from(\n { length: TEXT_TO_AUDIO_PRICING.MAX_DURATION_SEC },\n (_, i) => `${TEXT_TO_AUDIO_PRICING.PER_SECOND_PROVIDER}:${i + 1}s`,\n)\n\n/**\n * The whole seconds a request of `duration` seconds is billed for: rounded up,\n * at most the 30 s cap. No usable length (absent, empty, non-numeric, zero or\n * negative) bills the 5 s default. A numeric string counts — a field mapping\n * can deliver the length as text.\n */\nexport function textToAudioBilledSeconds(duration: unknown): number {\n const seconds =\n typeof duration === \"number\"\n ? duration\n : typeof duration === \"string\" && duration.trim() !== \"\"\n ? Number(duration)\n : Number.NaN\n if (!Number.isFinite(seconds) || seconds <= 0) return TEXT_TO_AUDIO_PRICING.DEFAULT_BILLED_SEC\n return Math.min(Math.ceil(seconds), TEXT_TO_AUDIO_PRICING.MAX_DURATION_SEC)\n}\n\n/**\n * The price row for a Text to Audio request. A request with no provider runs\n * (and is priced as) the default engine. An engine that is not priced per\n * second keeps its own flat row.\n */\nexport function textToAudioCreditId(provider: string | null | undefined, duration: unknown): string {\n const engine = provider || DEFAULT_TEXT_TO_AUDIO_PROVIDER\n if (engine !== TEXT_TO_AUDIO_PRICING.PER_SECOND_PROVIDER) return engine\n return `${engine}:${textToAudioBilledSeconds(duration)}s`\n}\n","/**\n * LTX 2.3 Pro Extend pricing — a per-second price row times the seconds added.\n *\n * `ltxExtendDurationSec` is the one reading of the requested length, and the\n * value it returns is the one SENT to the model: the route, the workflow run\n * and the worker all pass it on, so the seconds priced are the seconds\n * rendered. An absent length is the model's own default (6 seconds).\n *\n * The per-second amount lives in the `model_pricing` row, never here. Worked\n * examples at the row's listed price of 40 (repeated in\n * docs/nodes/ai-video/extend-video.md):\n * 2 s → 80, 6 s (or no length) → 240, 20 s → 800.\n */\n\nexport const LTX_EXTEND_PER_SECOND_CREDIT_ID = \"ltx-2.3-pro-extend:per-second\"\n\nexport const LTX_EXTEND_DURATION = {\n MIN_SEC: 1,\n MAX_SEC: 20,\n DEFAULT_SEC: 6,\n} as const\n\n/**\n * The seconds an LTX extend adds: a whole number from 1 to 20, the default\n * when none (or nothing readable) was given. Accepts a numeric string, which a\n * workflow field mapping can deliver.\n */\nexport function ltxExtendDurationSec(raw: unknown): number {\n const n =\n typeof raw === \"number\" ? raw : typeof raw === \"string\" && raw.trim() !== \"\" ? Number(raw) : Number.NaN\n if (!Number.isFinite(n)) return LTX_EXTEND_DURATION.DEFAULT_SEC\n return Math.min(LTX_EXTEND_DURATION.MAX_SEC, Math.max(LTX_EXTEND_DURATION.MIN_SEC, Math.round(n)))\n}\n","/**\n * LTX 2.3 Pro Retake pricing — a per-second price row times the seconds of\n * the replaced window.\n *\n * `ltxRetakeDurationSec` is the one reading of the window's length, and the\n * value it returns is the one SENT to the model: the route, the workflow run\n * and the worker all pass it on. The window is at least 2 seconds (the\n * route's own floor) and may be fractional — the editor's range picker sets\n * it to the frame.\n *\n * The per-second amount lives in the `model_pricing` row, never here; a run\n * is the row × these seconds, rounded up to a whole credit.\n */\n\nexport const LTX_RETAKE_PER_SECOND_CREDIT_ID = \"ltx-2.3-pro-retake:per-second\"\n\n/** The shortest window a retake replaces, in seconds. */\nexport const LTX_RETAKE_MIN_DURATION_SEC = 2\n\n/**\n * The seconds a retake replaces: the requested window, never below 2; 2 when\n * none (or nothing readable) was given. Accepts a numeric string, which a\n * workflow field mapping can deliver.\n */\nexport function ltxRetakeDurationSec(raw: unknown): number {\n const n =\n typeof raw === \"number\" ? raw : typeof raw === \"string\" && raw.trim() !== \"\" ? Number(raw) : Number.NaN\n if (!Number.isFinite(n) || n <= 0) return LTX_RETAKE_MIN_DURATION_SEC\n return Math.max(LTX_RETAKE_MIN_DURATION_SEC, n)\n}\n","/**\n * Length-based speech pricing — the shape of the price, not its value.\n *\n * A speech request (Text to Speech, Text to Dialogue, and the voiced-video\n * add-on) is priced per STARTED 100 characters of the text actually sent,\n * with a minimum number of units per request. The amount of one unit is a\n * `model_pricing` row per model — `<model id>:per-100-chars`, admin-editable\n * — and never lives here. `speechCredits(chars, row)` is the list price of a\n * request at a catalog row. An instance prices the WHOLE request and rounds it\n * once, so the price it serves for one unit times the units is only an upper\n * bound of what the request costs there. The exact charge of a\n * request of N units is served under its own id, `speechQuoteCreditId(model,\n * N)` (`<model>:per-100-chars:<N>u`), by the same price lookups that serve the\n * unit row (credits.model-costs, GET /v1/credits/model-cost): a client quotes\n * that answer rather than multiplying.\n *\n * Why 100 and not 1,000: the per-request error is at most one unit, and a\n * whole number of units times a charged unit price never under-quotes the\n * charge (the same property the per-second video rows rely on).\n *\n * Decided 2026-10-06. Every name here is a published contract.\n */\nimport { canonicalTtsProvider, findTtsCapabilities } from \"../tts-capabilities.js\"\nimport { findDialogueCapabilities } from \"../dialogue-capabilities.js\"\nimport { unitQuoteCreditId } from \"./unit-quote.js\"\n\n/** Characters per price unit. */\nexport const SPEECH_PRICE_UNIT_CHARS = 100\n\n/** The minimum units a request is priced at, however short its text. */\nexport const SPEECH_FLOOR_UNITS = 8\n\n/** Appended to a speech model's id to name its per-unit price row. */\nexport const SPEECH_UNIT_CREDIT_SUFFIX = \":per-100-chars\"\n\n/**\n * The price-row id of one unit for the model a request runs as. The legacy\n * `elevenlabs` alias prices on turbo's row, as it runs on turbo; any other id\n * (including the dialogue model) is used as given.\n */\nexport function speechUnitCreditId(modelId: string): string {\n return `${canonicalTtsProvider(modelId)}${SPEECH_UNIT_CREDIT_SUFFIX}`\n}\n\n/**\n * Units a text of `chars` characters is priced at: every started 100, and\n * never fewer than the floor. A count that is not a finite non-negative\n * number (node data written straight into workflow JSON) is the floor.\n */\nexport function speechPriceUnits(chars: number): number {\n const started = Number.isFinite(chars) && chars > 0 ? Math.ceil(chars / SPEECH_PRICE_UNIT_CHARS) : 0\n return Math.max(SPEECH_FLOOR_UNITS, started)\n}\n\n/** Base credits for `chars` characters at `perUnitCredits` per unit (the model's `:per-100-chars` row). */\nexport function speechCredits(chars: number, perUnitCredits: number): number {\n return speechPriceUnits(chars) * perUnitCredits\n}\n\n/**\n * The id of the exact charge of a whole request of `units` units on `modelId`:\n * `<model>:per-100-chars:<N>u`. Never a row of its own — a price lookup prices\n * it from the model's unit row × N as one whole, exactly as a request of that\n * length is reserved. Served only while length pricing is on, like the unit\n * row it is priced from.\n */\nexport function speechQuoteCreditId(modelId: string, units: number): string {\n return unitQuoteCreditId(speechUnitCreditId(modelId), units)\n}\n\n/** A `<model>:per-100-chars:<N>u` id, read back. */\nexport interface SpeechQuoteCreditIdParts {\n /** The speech model (canonical id) the request runs as. */\n model: string\n /** Its `<model>:per-100-chars` unit row. */\n unitId: string\n /** Units priced: at least the floor, at most the model's per-request cap in started hundreds. */\n units: number\n}\n\nconst SPEECH_QUOTE_ID = /^(.+):per-100-chars:(\\d{1,6})u$/\n\n/**\n * The parts of a `<model>:per-100-chars:<N>u` id, or undefined for any other id\n * — including a model that is not a speech model under its canonical id, and a\n * unit count no request on that model can be priced at (below the floor, or\n * above the model's cap in started hundreds).\n */\nexport function parseSpeechQuoteCreditId(id: string): SpeechQuoteCreditIdParts | undefined {\n if (typeof id !== \"string\") return undefined\n const m = SPEECH_QUOTE_ID.exec(id)\n if (!m) return undefined\n const model = m[1]!\n if (canonicalTtsProvider(model) !== model) return undefined\n const caps = findTtsCapabilities(model) ?? findDialogueCapabilities(model)\n if (!caps) return undefined\n const units = Number(m[2])\n if (!Number.isInteger(units) || units < SPEECH_FLOOR_UNITS || units > speechPriceUnits(caps.maxChars)) return undefined\n return { model, unitId: speechUnitCreditId(model), units }\n}\n\n/**\n * Whether an id is a length price of speech — a `<model>:per-100-chars` unit\n * row or a `<model>:per-100-chars:<N>u` request quote — by its shape alone.\n * Both are served only while the server prices speech by length.\n */\nexport function isSpeechLengthPriceId(id: string): boolean {\n return typeof id === \"string\" && /:per-100-chars(?::\\d+u)?$/.test(id)\n}\n\n/**\n * The speech model a length price id is priced for — the id a request of\n * that model is reserved at, so the two are priced under the same id — or\n * undefined for any other id.\n */\nexport function speechLengthPriceModel(id: string): string | undefined {\n if (!isSpeechLengthPriceId(id)) return undefined\n return id.replace(/:per-100-chars(?::\\d+u)?$/, \"\")\n}\n","/**\n * The price of a whole Voice Changer Pro convert, as ONE id.\n *\n * A convert is charged as one whole: every changed speaker's slot is priced in\n * base credits (a recast slot by the length of its stem, a Re-speak slot by\n * its characters on its engine's row), the slots are summed, and the sum is\n * marked up ONCE at `voice-changer-pro`. A client that prices each slot on the\n * served (already marked-up, already rounded) rows and adds them up cannot\n * reach that figure: the rounding happens in a different place.\n *\n * `voiceChangerProQuoteCreditId(slots)` names the whole price:\n * `voice-changer-pro:<slot>,<slot>,…`, one slot per changed speaker, where a\n * slot is\n *\n * - `sts-<seconds>` — a recast (speech-to-speech) slot whose stem is that\n * many seconds long (the speaker's last utterance end); `sts` alone when\n * the length is unknown (priced as one minute, as the convert reserves it);\n * - `respeak-<chars>` — a Re-speak slot on the default engine (v3) that\n * re-speaks that many characters; `respeak` alone when the count is unknown;\n * - `respeak-v4-<chars>` — a Re-speak slot on the v4 engine (`respeak-v4`\n * when the count is unknown); `respeak-v3-<chars>` names v3 explicitly\n * and is the same price as `respeak-<chars>`;\n * - `respeak-v4t-<chars>` — a v4 slot speaking a TRANSLATION of its\n * `<chars>` transcript characters. The convert reserves such a slot for more\n * speech than its transcript holds (a line may be re-rendered once,\n * shorter); the server applies that allowance, so the client sends the\n * transcript's own count and never the arithmetic. Only v4 speaks a\n * translation, so there is no `v3t`.\n *\n * `POST /v1/credits/model-costs` and `GET /v1/credits/model-cost` answer it\n * with the figure the convert reserves; an id the server does not price\n * (a malformed slot, more slots than a convert takes, a count out of range)\n * lands in `missing`. Numbers are written exactly as JavaScript prints them,\n * so the server reads back the value the client priced.\n */\n\n/** The id a convert is reserved (and marked up) at. */\nexport const VOICE_CHANGER_PRO_QUOTE_RATE_ID = \"voice-changer-pro\"\n\n/** A Re-speak engine, as the quote names it. */\nexport type VoiceChangerProQuoteRespeakEngine = \"v3\" | \"v4\"\n\n/** One changed speaker of a convert, as the quote prices it. */\nexport type VoiceChangerProQuoteSlot =\n /** A recast slot: the stem's length in seconds; `null` (or not a positive number) = unknown. */\n | { readonly kind: \"sts\"; readonly seconds: number | null }\n /**\n * A Re-speak slot: the characters of its transcript; `null` (or not a\n * positive number) = unknown. `engine` absent = the default engine (v3).\n * `translated` = the slot speaks the plan's target language — read only on\n * v4, the one engine that speaks a translation (the convert route reads it\n * the same way).\n */\n | {\n readonly kind: \"respeak\"\n readonly chars: number | null\n readonly engine?: VoiceChangerProQuoteRespeakEngine\n readonly translated?: boolean\n }\n\n/** A `voice-changer-pro:<slots>` id, read back into the convert's pricing inputs (slot order kept per kind). */\nexport interface VoiceChangerProQuoteCreditIdParts {\n /** Stem seconds per recast slot; `null` = unknown. */\n readonly stsSlotSeconds: ReadonlyArray<number | null>\n /** Transcript characters per Re-speak slot; `null` = unknown. */\n readonly respeakChars: ReadonlyArray<number | null>\n /** The engine of each Re-speak slot, index-aligned with `respeakChars`; `null` = not named (the default engine). */\n readonly respeakEngines: ReadonlyArray<VoiceChangerProQuoteRespeakEngine | null>\n /** Whether each Re-speak slot speaks a translation, index-aligned with `respeakChars` (only ever true on v4). */\n readonly respeakTranslated: ReadonlyArray<boolean>\n}\n\nconst PREFIX = `${VOICE_CHANGER_PRO_QUOTE_RATE_ID}:`\nconst NUMBER = String.raw`\\d{1,7}(?:\\.\\d{1,20})?`\nconst STS_SLOT = new RegExp(`^sts(?:-(${NUMBER}))?$`)\nconst RESPEAK_SLOT = new RegExp(`^respeak(?:-(v3|v4|v4t))?(?:-(${NUMBER}))?$`)\n\nconst known = (n: number | null): n is number => n !== null && Number.isFinite(n) && n > 0\n\n/** The engine token of a Re-speak slot: none for the default engine (the id every client sent before engines were named). */\nfunction respeakEngineToken(slot: { readonly engine?: VoiceChangerProQuoteRespeakEngine; readonly translated?: boolean }): string {\n if (slot.engine !== \"v4\") return \"\"\n return slot.translated === true ? \"-v4t\" : \"-v4\"\n}\n\n/** `voice-changer-pro:<slot>,…` — the id of the whole price of a convert with these changed speakers. */\nexport function voiceChangerProQuoteCreditId(slots: ReadonlyArray<VoiceChangerProQuoteSlot>): string {\n return (\n PREFIX +\n slots\n .map((slot) => {\n if (slot.kind === \"sts\") return known(slot.seconds) ? `sts-${String(slot.seconds)}` : \"sts\"\n const head = `respeak${respeakEngineToken(slot)}`\n return known(slot.chars) ? `${head}-${String(slot.chars)}` : head\n })\n .join(\",\")\n )\n}\n\nfunction measureOf(text: string | undefined): number | null | undefined {\n if (text === undefined) return null\n const value = Number(text)\n return Number.isFinite(value) && value > 0 ? value : undefined\n}\n\n/**\n * The parts of a `voice-changer-pro:<slots>` id by its shape alone, or\n * undefined (not such an id, an empty or malformed slot). How many slots and\n * what counts the server prices is the server's to say: an id it does not\n * price lands in `missing`.\n */\nexport function parseVoiceChangerProQuoteCreditId(id: string): VoiceChangerProQuoteCreditIdParts | undefined {\n if (typeof id !== \"string\" || !id.startsWith(PREFIX)) return undefined\n const body = id.slice(PREFIX.length)\n if (body.length === 0) return undefined\n const stsSlotSeconds: Array<number | null> = []\n const respeakChars: Array<number | null> = []\n const respeakEngines: Array<VoiceChangerProQuoteRespeakEngine | null> = []\n const respeakTranslated: boolean[] = []\n for (const part of body.split(\",\")) {\n const sts = STS_SLOT.exec(part)\n if (sts) {\n const seconds = measureOf(sts[1])\n if (seconds === undefined) return undefined\n stsSlotSeconds.push(seconds)\n continue\n }\n const respeak = RESPEAK_SLOT.exec(part)\n if (!respeak) return undefined\n const chars = measureOf(respeak[2])\n if (chars === undefined) return undefined\n const token = respeak[1]\n respeakChars.push(chars)\n respeakEngines.push(token === undefined ? null : token === \"v3\" ? \"v3\" : \"v4\")\n respeakTranslated.push(token === \"v4t\")\n }\n return { stsSlotSeconds, respeakChars, respeakEngines, respeakTranslated }\n}\n","/**\n * Pitch & Tempo pricing — per STARTED minute of the input media (decided\n * 2026-10-12), at least one minute, at most 30.\n *\n * One `model_pricing` row, `pitch-tempo`, holds the credits per minute; a run\n * reserves `pitch-tempo:<N>m` (N = started minutes), which billing prices as\n * that row × N — never a row of its own, so a retune of the rate row moves the\n * route, the workflow run, the node's Run button and every estimate together.\n * The same id is built by the route (from the probed length), the workflow run\n * (the same probe) and the editor (the upstream length it knows).\n *\n * Worked examples at the row's listed rate of 20 (repeated in\n * docs/nodes/processing-audio/pitch-tempo.md):\n * 0:45 → 20, 1:00 → 20, 1:01 → 40, 3:10 → 80, 30:00 → 600.\n */\n\nexport const PITCH_TEMPO_PRICING = {\n /** The rate row: credits per started minute. Never reserved by itself. */\n RATE_CREDIT_ID: \"pitch-tempo\",\n /** The longest input a run accepts, in seconds (the route refuses longer). */\n MAX_DURATION_SEC: 1800,\n /** The most minutes a `pitch-tempo:<N>m` id can carry. */\n MAX_MINUTES: 30,\n /** The rate row's launch value (admin-retunable in /admin/models). */\n CREDITS_PER_MINUTE_DEFAULT: 20,\n} as const\n\n/** The control ranges every surface validates against. */\nexport const PITCH_TEMPO_LIMITS = {\n SEMITONES_MIN: -12,\n SEMITONES_MAX: 12,\n TEMPO_MIN: 0.5,\n TEMPO_MAX: 2,\n} as const\n\n/**\n * Started minutes of an input of `durationSec` seconds: ceil(sec / 60), at\n * least 1, at most 30. An unknown or non-positive length counts as one minute\n * here; a quote of an unknown length names 30 instead\n * ({@link pitchTempoQuoteCreditId}), and a run always measures.\n */\nexport function pitchTempoStartedMinutes(durationSec: number | null | undefined): number {\n if (typeof durationSec !== \"number\" || !Number.isFinite(durationSec) || durationSec <= 0) return 1\n return Math.min(PITCH_TEMPO_PRICING.MAX_MINUTES, Math.max(1, Math.ceil(durationSec / 60)))\n}\n\n/** `pitch-tempo:<N>m` — the id a run on an input of `durationSec` seconds reserves. */\nexport function pitchTempoCreditId(durationSec: number | null | undefined): string {\n return `pitch-tempo:${pitchTempoStartedMinutes(durationSec)}m`\n}\n\n/**\n * The id a QUOTE names for an input of `durationSec` seconds — every estimate\n * before a run. A known length is the id its run reserves\n * ({@link pitchTempoCreditId}). An UNKNOWN length is the 30-minute id\n * (decided 2026-10-13): a run measures the file before it reserves and refuses\n * one it cannot measure or one over 30 minutes, so 30 minutes is the most any\n * run can be charged and the quote is never below the charge.\n */\nexport function pitchTempoQuoteCreditId(durationSec: number | null | undefined): string {\n const known = typeof durationSec === \"number\" && Number.isFinite(durationSec) && durationSec > 0\n return pitchTempoCreditId(known ? durationSec : PITCH_TEMPO_PRICING.MAX_DURATION_SEC)\n}\n\n/** The minutes of a `pitch-tempo:<N>m` id (1 ≤ N ≤ 30), or `undefined` for any other id. */\nexport function parsePitchTempoCreditId(id: string): { minutes: number } | undefined {\n const m = /^pitch-tempo:(\\d+)m$/.exec(id)\n if (!m) return undefined\n const minutes = Number(m[1])\n if (!Number.isInteger(minutes) || minutes < 1 || minutes > PITCH_TEMPO_PRICING.MAX_MINUTES) return undefined\n return { minutes }\n}\n\n/** rate × minutes, rounded up, at least 1 credit — what a `pitch-tempo:<N>m` id costs. */\nexport function pitchTempoBaseCredits(ratePerMinute: number, minutes: number): number {\n return Math.max(1, Math.ceil(ratePerMinute * minutes))\n}\n\n/** The frequency ratio for a shift of `semitones` (12 = one octave up = ×2). */\nexport function semitonesToPitchRatio(semitones: number): number {\n return 2 ** (semitones / 12)\n}\n","/**\n * Nemotron 3.5 Transcribe pricing — per STARTED minute of the file (decided\n * 2026-11-12): the same price with word timings or a translation.\n *\n * The base price is 0.75 credits a minute, which no whole-credit row can hold\n * (`model_pricing.credit_cost` is an integer), so the rate row prices FOUR\n * minutes — the same trick as Nodaro Video Upscale's four-second rows. A run\n * reserves `nemotron-3-5-transcribe:<N>m` (N = started minutes, 1..60), which\n * billing prices as that row × N ÷ 4, rounded up once for the whole run, then\n * marked up once — never a row of its own, so a retune of the rate row moves\n * the route, the workflow run, the node's Run button and every estimate\n * together. The same id is built by the route (from the probed length), the\n * workflow run (the same probe) and the editor (the upstream length it knows).\n * That id is the HOLD: a run is then CHARGED for the minutes the provider\n * reports it decoded, up or down (decided 2026-11-12; backend\n * `lib/nemotron-transcribe-settle.ts`).\n *\n * Worked base prices at the row's launch value of 3 (per 4 minutes):\n * 0:45 → 1, 1:00 → 1, 1:01 → 2, 10:00 → 8, 60:00 → 45.\n * The listed (marked-up) price follows from those.\n */\n\n/** The engine's id — the Transcribe node's `provider`, and the bare price id. */\nexport const NEMOTRON_TRANSCRIBE_ID = \"nemotron-3-5-transcribe\"\n\nexport const NEMOTRON_TRANSCRIBE_PRICING = {\n /** The rate row: credits per {@link NEMOTRON_TRANSCRIBE_PRICING.RATE_MINUTES} minutes. Never reserved by itself. */\n RATE_CREDIT_ID: \"nemotron-3-5-transcribe:per-4m\",\n /** The minutes the rate row prices. */\n RATE_MINUTES: 4,\n /** The rate row's launch value (admin-retunable in /admin/models): 0.75 base credits a minute. */\n CREDITS_PER_RATE_DEFAULT: 3,\n /** The longest file a run accepts, in seconds (KIE's 60-minute limit; the route refuses longer). */\n MAX_DURATION_SEC: 3600,\n /** The most minutes a `nemotron-3-5-transcribe:<N>m` id can carry. */\n MAX_MINUTES: 60,\n /** The largest file a run accepts, in bytes (KIE's 200 MB limit). */\n MAX_BYTES: 200 * 1024 * 1024,\n} as const\n\n/**\n * Started minutes of a file of `durationSec` seconds: ceil(sec / 60), at least\n * 1, at most 60. An unknown or non-positive length counts as one minute here; a\n * quote of an unknown length names 60 instead ({@link nemotronTranscribeQuoteCreditId}),\n * as does a run whose file's length cannot be read (it holds 60 minutes and\n * settles at the provider's decoded length).\n */\nexport function nemotronTranscribeStartedMinutes(durationSec: number | null | undefined): number {\n if (typeof durationSec !== \"number\" || !Number.isFinite(durationSec) || durationSec <= 0) return 1\n return Math.min(NEMOTRON_TRANSCRIBE_PRICING.MAX_MINUTES, Math.max(1, Math.ceil(durationSec / 60)))\n}\n\n/** `nemotron-3-5-transcribe:<N>m` — the id a run on a file of `durationSec` seconds reserves. */\nexport function nemotronTranscribeCreditId(durationSec: number | null | undefined): string {\n return `${NEMOTRON_TRANSCRIBE_ID}:${nemotronTranscribeStartedMinutes(durationSec)}m`\n}\n\n/**\n * The id a QUOTE names for a file of `durationSec` seconds — every estimate\n * before a run. A known length is the id its run reserves. An UNKNOWN length is\n * the 60-minute id: a run measures the file before it reserves, holds 60\n * minutes for one whose length cannot be read and refuses one over 60 minutes,\n * and the provider refuses longer audio, so 60 minutes is the most any run can\n * be charged and the quote is never below the charge (Pitch & Tempo's rule).\n */\nexport function nemotronTranscribeQuoteCreditId(durationSec: number | null | undefined): string {\n const known = typeof durationSec === \"number\" && Number.isFinite(durationSec) && durationSec > 0\n return nemotronTranscribeCreditId(known ? durationSec : NEMOTRON_TRANSCRIBE_PRICING.MAX_DURATION_SEC)\n}\n\n/** The minutes of a `nemotron-3-5-transcribe:<N>m` id (1 ≤ N ≤ 60), or `undefined` for any other id. */\nexport function parseNemotronTranscribeCreditId(id: string): { minutes: number } | undefined {\n const m = /^nemotron-3-5-transcribe:(\\d+)m$/.exec(id)\n if (!m) return undefined\n const minutes = Number(m[1])\n if (!Number.isInteger(minutes) || minutes < 1 || minutes > NEMOTRON_TRANSCRIBE_PRICING.MAX_MINUTES) return undefined\n return { minutes }\n}\n\n/**\n * The base of a run of `minutes` started minutes from the rate row's value\n * (`ratePerBlock` credits per {@link NEMOTRON_TRANSCRIBE_PRICING.RATE_MINUTES}\n * minutes): rate × minutes ÷ 4, rounded up once for the whole run, at least 1.\n */\nexport function nemotronTranscribeBaseCredits(ratePerBlock: number, minutes: number): number {\n return Math.max(1, Math.ceil((ratePerBlock * minutes) / NEMOTRON_TRANSCRIBE_PRICING.RATE_MINUTES))\n}\n","/**\n * Video Overlay pricing — which row a run is charged from, and how many units\n * of it. One mapping for every place that names the price: the route\n * (`POST /v1/video-overlay`), the workflow run's reservation, the node's Run\n * button and the workflow estimates.\n *\n * An image-only run is the flat `video-overlay` row, whatever its layers or\n * the base's length; its base is never measured for the price. A run with any\n * video layer is charged the `video-overlay:video` row once per started 5\n * seconds of the output — the base's length, which is the output's — the unit\n * Mask Composite is charged by. The route and the workflow run measure the\n * base before anything is reserved, and refuse one they cannot read or one\n * past {@link VIDEO_OVERLAY_PRICING.MAX_BASE_SEC}. Before a run, a base whose\n * length is not known yet is quoted at that cap, so a quote is never below\n * what the run is charged.\n *\n * Worked examples, in units of the `video-overlay:video` row:\n * 10 s → 2, 23 s → 5, 60 s → 12, unknown → 12, 61 s → refused.\n */\nimport { pricedClipSeconds } from \"../priced-clip-seconds.js\"\nimport { VIDEO_OVERLAY_VIDEO_MAX_BASE_SEC } from \"../video-overlay.js\"\n\nexport const VIDEO_OVERLAY_PRICING = {\n /** An image-only run: one flat row. */\n IMAGE_CREDIT_ID: \"video-overlay\",\n /** A run with a video layer: one row per started {@link VIDEO_OVERLAY_PRICING.UNIT_SEC} seconds of the output. */\n VIDEO_CREDIT_ID: \"video-overlay:video\",\n /** Seconds of output one unit of the video row covers. */\n UNIT_SEC: 5,\n /** The longest base a run with a video layer accepts, in seconds. */\n MAX_BASE_SEC: VIDEO_OVERLAY_VIDEO_MAX_BASE_SEC,\n} as const\n\n/**\n * How much longer, in seconds, the base the worker downloads may run than the\n * base measured before the run was charged, before the worker refuses it as\n * changed: a re-measure can read a hair longer (a re-encode, a container's\n * rounding), and that is not a different file. Applied to the seconds, never\n * to the units: a base billed for 10 s renders at up to 10.5 s.\n */\nexport const VIDEO_OVERLAY_REMEASURE_SLACK_SEC = 0.5\n\n/** The row a run is charged from: the flat image row, or the per-5-second video row when any layer is a video. */\nexport function videoOverlayCreditId(hasVideoLayer: boolean): string {\n return hasVideoLayer ? VIDEO_OVERLAY_PRICING.VIDEO_CREDIT_ID : VIDEO_OVERLAY_PRICING.IMAGE_CREDIT_ID\n}\n\n/**\n * Units of the video row for a base `baseSec` long: one per started 5\n * seconds, at least one, after `pricedClipSeconds` (up to 0.05 s past a whole\n * second is ignored, so a 10.01 s base is 2 units). An unknown length counts\n * the cap — the pre-run quote for a base not measured yet — and so does a\n * length past it (such a base is refused before anything is reserved).\n */\nexport function videoOverlayVideoUnits(baseSec: number | null | undefined): number {\n const sec =\n typeof baseSec === \"number\" && Number.isFinite(baseSec) && baseSec > 0\n ? Math.min(baseSec, VIDEO_OVERLAY_PRICING.MAX_BASE_SEC)\n : VIDEO_OVERLAY_PRICING.MAX_BASE_SEC\n return Math.ceil(pricedClipSeconds(sec) / VIDEO_OVERLAY_PRICING.UNIT_SEC)\n}\n\n/**\n * Whether a measured base is past the cap for a run with a video layer. Read\n * on the priced seconds the units use, so a base the price counts as 60 s\n * (60.04 s, a whole-second cut of a 29.97 fps clip) is accepted at 12 units.\n */\nexport function videoOverlayBaseTooLong(baseSec: number): boolean {\n return pricedClipSeconds(baseSec) > VIDEO_OVERLAY_PRICING.MAX_BASE_SEC\n}\n","/**\n * Topaz image upscale — the single authority for \"which lever did the user\n * pull, what do we send, and what do we charge\".\n *\n * KIE's `topaz/image-upscale` takes exactly ONE quality lever:\n * upscale_factor: \"1\" | \"2\" | \"4\" (default \"2\")\n * There is no target-resolution parameter (docs.kie.ai/market/topaz/image-upscale,\n * verified 2026-09-02). The editor nevertheless shipped TWO controls — an\n * `upscaleFactor` select AND a `targetResolution` select (2K/4K/8K) — and billed\n * on the second one, which never reached the worker. Everyone who bought 4K or\n * 8K got a 2x render at 2x/4x the price (app-reports triage 2026-09-01 §4.3).\n *\n * So: the FACTOR is the lever. `targetResolution` survives only as a legacy\n * input (stored node data, old API/MCP callers) and is mapped forward here.\n * The credit tier is derived from the SAME resolution, which is why callers\n * must pass `creditTier` into `buildCreditModelIdentifier` rather than the raw\n * request value — that is what makes CHECK = DEBIT = SENT.\n *\n * The composite `topaz-image-upscale:4K` is retained as the id of the 4x tier\n * (migration 288 wrote that row; renaming it would need a pricing migration for\n * zero user-visible gain). Read it as \"the top Topaz tier\", not as a promise of\n * 4096 pixels. `topaz-image-upscale:8K` stays priced in STATIC_CREDIT_COSTS so\n * historical usage_logs still resolve, but nothing can reserve it any more.\n *\n * Resolution order (fix round 1, 2026-09-02 review):\n * 1. Resolve the WINNING factor first — a valid `upscaleFactor` always wins;\n * an invalid one falls through to `targetResolution` exactly as if it had\n * never been sent, rather than freezing the default before the legacy\n * tier gets a chance to raise it (an invalid factor + a stored 4K/8K tier\n * must still resolve — and bill — at the tier's factor, not the default).\n * 2. Only THEN build `adjustments`, so every `to` reflects the resolved\n * factor rather than an intermediate guess, and every `from` is the raw,\n * untransformed input string (never the trimmed/uppercased copy used\n * internally to match).\n * 3. A valid `upscaleFactor` alongside a `targetResolution` it disagrees\n * with emits an informational (not corrective) adjustment — the stored\n * legacy choice is being overridden, not silently dropped — with\n * `to: undefined` because nothing was actually sent for that field.\n * Agreement (they resolve to the same factor) is reported as nothing:\n * there is no override to disclose.\n */\n\nexport type TopazUpscaleFactor = \"1\" | \"2\" | \"4\"\n\nexport const TOPAZ_UPSCALE_FACTORS: readonly TopazUpscaleFactor[] = [\"1\", \"2\", \"4\"]\n\n/** KIE's own default when `upscale_factor` is omitted (providers/kie/models.ts). */\nexport const TOPAZ_DEFAULT_UPSCALE_FACTOR: TopazUpscaleFactor = \"2\"\n\nexport interface TopazUpscaleAdjustment {\n field: \"upscaleFactor\" | \"targetResolution\"\n /** The raw, untransformed value as received — never trimmed or case-normalized. */\n from: string\n /**\n * The resolved factor this adjustment corresponds to, or `undefined` for the\n * informational \"your stored targetResolution was overridden\" notice, which\n * names nothing to switch TO — `upscaleFactor` already won.\n */\n to: string | undefined\n reason: string\n}\n\nexport interface TopazUpscaleResolution {\n /** Sent to KIE as `upscale_factor`. Always set — never rely on the model default. */\n upscaleFactor: TopazUpscaleFactor\n /**\n * Passed VERBATIM as `buildCreditModelIdentifier`'s `targetResolution` arg.\n * `undefined` = the bare id (1x / 2x); `\"4K\"` = the 4x tier.\n */\n creditTier: \"4K\" | undefined\n /** Non-empty when a legacy or out-of-enum value was coerced or overridden. */\n adjustments: TopazUpscaleAdjustment[]\n}\n\n/** Legacy 2K/4K/8K tier → the factor the provider can actually deliver. */\nconst LEGACY_TIER_TO_FACTOR: Record<string, TopazUpscaleFactor> = {\n \"2K\": \"2\",\n \"4K\": \"4\",\n \"8K\": \"4\",\n}\n\nfunction isFactor(v: string): v is TopazUpscaleFactor {\n return (TOPAZ_UPSCALE_FACTORS as readonly string[]).includes(v)\n}\n\nexport function resolveTopazUpscale(input: {\n upscaleFactor?: string | null\n targetResolution?: string | null\n}): TopazUpscaleResolution {\n const adjustments: TopazUpscaleAdjustment[] = []\n\n // Raw, untransformed inputs — these are what every adjustment's `from` reports.\n const rawFactor = typeof input.upscaleFactor === \"string\" ? input.upscaleFactor : \"\"\n const rawTier = typeof input.targetResolution === \"string\" ? input.targetResolution : \"\"\n\n // Trimmed/normalized copies used ONLY for matching, never for display.\n const trimmedFactor = rawFactor.trim()\n const normalizedTier = rawTier.trim().toUpperCase()\n\n const factorGiven = trimmedFactor.length > 0\n const factorValid = factorGiven && isFactor(trimmedFactor)\n\n const tierGiven = normalizedTier.length > 0\n const tierMappedFactor = tierGiven ? LEGACY_TIER_TO_FACTOR[normalizedTier] : undefined\n\n // --- 1. Resolve the winning factor FIRST. ---\n // A valid factor always wins. An invalid (or absent) one falls through to\n // whatever the legacy tier maps to; only if that also comes up empty do we\n // land on the provider default.\n const finalFactor: TopazUpscaleFactor = factorValid\n ? (trimmedFactor as TopazUpscaleFactor)\n : (tierMappedFactor ?? TOPAZ_DEFAULT_UPSCALE_FACTOR)\n\n // --- 2. Emit adjustments LAST, against the already-resolved factor. ---\n if (factorGiven && !factorValid) {\n adjustments.push({\n field: \"upscaleFactor\",\n from: rawFactor,\n to: finalFactor,\n reason: `Topaz upscale accepts a factor of 1, 2 or 4 — \"${rawFactor}\" was replaced with ${finalFactor}.`,\n })\n }\n\n if (factorValid && tierGiven) {\n // The factor won outright. Say so if it disagrees with the stored legacy\n // tier — otherwise the tier silently vanishes with no record. Agreement\n // needs no note: nothing was overridden.\n if (tierMappedFactor !== finalFactor) {\n adjustments.push({\n field: \"targetResolution\",\n from: rawTier,\n to: undefined,\n reason: \"upscaleFactor takes precedence over the legacy targetResolution.\",\n })\n }\n } else if (!factorValid && tierGiven) {\n // No valid explicit factor — the legacy tier is the (partial) source of\n // the resolved factor, or was consulted and found unusable.\n if (tierMappedFactor) {\n if (normalizedTier === \"8K\") {\n adjustments.push({\n field: \"targetResolution\",\n from: rawTier,\n to: finalFactor,\n reason: \"Topaz upscale offers factors up to 4x — an 8K target renders and bills at the 4x tier.\",\n })\n }\n } else {\n adjustments.push({\n field: \"targetResolution\",\n from: rawTier,\n to: finalFactor,\n reason: `Unknown Topaz target \"${rawTier}\" — rendering at ${finalFactor}x.`,\n })\n }\n }\n\n return {\n upscaleFactor: finalFactor,\n creditTier: finalFactor === \"4\" ? \"4K\" : undefined,\n adjustments,\n }\n}\n","/**\n * The upscale FACTOR of the image upscalers that take one — which factors each\n * model accepts, and the factor a request renders at. One authority for the\n * route's enum, the editor's dropdown and its fail-safe snap, the workflow\n * payload, the worker, MCP and the SDK.\n *\n * Two models take a factor:\n * - `topaz-image-upscale`: 1, 2 or 4 — resolved by `resolveTopazUpscale`,\n * which also maps its legacy `targetResolution` (unchanged here).\n * - `nodaro-image-upscale`: 1, 2, 4 or 8. A factor multiplies both sides; 1\n * enhances the picture at its own size. Anything else is rendered at the\n * default, 2. It has no `targetResolution`: its price follows the output's\n * size (`@nodaro/render-rules` nodaro-image-upscale-pricing.ts), so a stored\n * tier from another model is never read.\n *\n * Every other model (Recraft, and the edit models) declares no factor list,\n * and a factor stored or mapped onto its node is passed on exactly as it\n * always was — \"1\", \"2\" and \"4\" are the values the route takes for it — except\n * a factor only the house model takes ({@link HOUSE_ONLY_UPSCALE_FACTORS}, \"8\"):\n * no other model takes it, so it is never sent to one, and the editor clears\n * it from a node switched away from Nodaro Image Upscale.\n */\nimport { resolveTopazUpscale, TOPAZ_UPSCALE_FACTORS } from \"./topaz-upscale.js\"\n\n/** Nodaro Image Upscale's model id. */\nexport const NODARO_IMAGE_UPSCALE_MODEL_ID = \"nodaro-image-upscale\"\n\nexport type NodaroImageUpscaleFactor = \"1\" | \"2\" | \"4\" | \"8\"\n\n/** The factors Nodaro Image Upscale renders at, smallest first. */\nexport const NODARO_IMAGE_UPSCALE_FACTORS: readonly NodaroImageUpscaleFactor[] = [\"1\", \"2\", \"4\", \"8\"]\n\n/** The factor a Nodaro Image Upscale request without a valid one renders at. */\nexport const NODARO_IMAGE_UPSCALE_DEFAULT_FACTOR: NodaroImageUpscaleFactor = \"2\"\n\n/** Every factor any image upscaler takes — the vocabulary the request enums carry. Each model's own list is {@link upscaleFactorsFor}. */\nexport const UPSCALE_FACTORS = [\"1\", \"2\", \"4\", \"8\"] as const\nexport type UpscaleFactor = (typeof UPSCALE_FACTORS)[number]\n\n/** The factor Nodaro Image Upscale renders `raw` at: a listed factor as given (trimmed), anything else the default. */\nexport function resolveNodaroImageUpscaleFactor(raw: unknown): NodaroImageUpscaleFactor {\n const trimmed = typeof raw === \"string\" ? raw.trim() : typeof raw === \"number\" ? String(raw) : \"\"\n return (NODARO_IMAGE_UPSCALE_FACTORS as readonly string[]).includes(trimmed)\n ? (trimmed as NodaroImageUpscaleFactor)\n : NODARO_IMAGE_UPSCALE_DEFAULT_FACTOR\n}\n\n/**\n * The factors only Nodaro Image Upscale takes: every other model's request\n * refuses them (Topaz's list, and the 1/2/4 the route takes for a model with\n * no list of its own), so none is ever sent to another model. \"8\".\n */\nexport const HOUSE_ONLY_UPSCALE_FACTORS: readonly UpscaleFactor[] = NODARO_IMAGE_UPSCALE_FACTORS.filter(\n (f) => !(TOPAZ_UPSCALE_FACTORS as readonly string[]).includes(f),\n)\n\n/** True when `value` is a factor only Nodaro Image Upscale takes ({@link HOUSE_ONLY_UPSCALE_FACTORS}). */\nfunction isHouseOnlyUpscaleFactor(value: string): boolean {\n return (HOUSE_ONLY_UPSCALE_FACTORS as readonly string[]).includes(value.trim())\n}\n\n/** The factors `provider` accepts, or undefined for a model that declares no factor list. */\nexport function upscaleFactorsFor(provider: unknown): readonly UpscaleFactor[] | undefined {\n if (provider === NODARO_IMAGE_UPSCALE_MODEL_ID) return NODARO_IMAGE_UPSCALE_FACTORS\n if (provider === \"topaz-image-upscale\") return TOPAZ_UPSCALE_FACTORS\n return undefined\n}\n\n/**\n * The factor a request to `provider` sends: Topaz's through `resolveTopazUpscale`\n * (its legacy `targetResolution` included), Nodaro Image Upscale's through\n * {@link resolveNodaroImageUpscaleFactor}, and any other model's value as\n * given — except a factor only the house model takes (\"8\"), which is not\n * sent. What the editor's panel snaps a stale value to, and what the editor's\n * Run and the workflow payload send.\n */\nexport function resolveUpscaleFactor(\n provider: unknown,\n input: { upscaleFactor?: unknown; targetResolution?: unknown },\n): string | undefined {\n if (provider === NODARO_IMAGE_UPSCALE_MODEL_ID) return resolveNodaroImageUpscaleFactor(input.upscaleFactor)\n if (provider === \"topaz-image-upscale\") {\n return resolveTopazUpscale({\n upscaleFactor: typeof input.upscaleFactor === \"string\" ? input.upscaleFactor : undefined,\n targetResolution: typeof input.targetResolution === \"string\" ? input.targetResolution : undefined,\n }).upscaleFactor\n }\n return typeof input.upscaleFactor === \"string\" && !isHouseOnlyUpscaleFactor(input.upscaleFactor) ? input.upscaleFactor : undefined\n}\n\n/**\n * The factor a node on `provider` must carry instead of its stored one — the\n * one the run would render ({@link resolveUpscaleFactor}) — `null` when it\n * must carry none, or undefined when the stored factor stands. What the editor\n * writes when a stale factor meets a model that does not take it: a Nodaro\n * Image Upscale 8x switched to Topaz runs, and is stored, at 2x; one switched\n * to a model with no factor list (Recraft) keeps no factor. Any other factor\n * on such a model stands exactly as it always did (a saved Recraft node's \"4\"\n * is never rewritten), as does none stored, or one the model takes.\n */\nexport function snappedUpscaleFactor(\n provider: unknown,\n input: { upscaleFactor?: unknown; targetResolution?: unknown },\n): string | null | undefined {\n const stored = typeof input.upscaleFactor === \"string\" ? input.upscaleFactor : undefined\n if (stored === undefined) return undefined\n const factors = upscaleFactorsFor(provider)\n if (!factors) return isHouseOnlyUpscaleFactor(stored) ? null : undefined\n if ((factors as readonly string[]).includes(stored)) return undefined\n return resolveUpscaleFactor(provider, input) ?? null\n}\n","/**\n * Calculate the creator's monetization markup on a base credit cost.\n * Returns the markup amount (not the total).\n */\nexport function calculateMonetizationMarkup(baseCost: number, flatFee: number, percent: number): number {\n if (flatFee <= 0 && percent <= 0) return 0\n return flatFee + Math.ceil(baseCost * percent / 100)\n}\n\n/**\n * Calculate the total cost a runner pays (base + markup).\n */\nexport function calculateMonetizedCost(baseCost: number, flatFee: number, percent: number): number {\n return baseCost + calculateMonetizationMarkup(baseCost, flatFee, percent)\n}\n","/**\n * Lip-sync per-second pricing helpers.\n *\n * KIE.ai Kling AI Avatar 2.0 (May 2026) raised the max input audio from 15s\n * to 5 minutes and bills per-second. We bucket the requested audio duration\n * into discrete tiers and use composite credit identifiers\n * (e.g. `kling-avatar:60s`) so credit reservation scales with input length.\n *\n * InfiniTalk still enforces a 15s upstream cap.\n *\n * A model listed in {@link LIP_SYNC_AUDIO_RATES} is priced differently: at a\n * per-second RATE times the seconds of its audio, never by bucket.\n */\n\nimport { unitQuoteCreditId } from \"./credit-estimators/unit-quote.js\"\n\n/**\n * A lip-sync model charged at a per-second rate: the rate's one-second price\n * row times the seconds of the audio that drives it, rounded up once and marked\n * up once by the pricing chain that charges every per-unit rate.\n */\nexport interface LipSyncAudioRate {\n /** The one-second price row (`model_pricing`, else `STATIC_CREDIT_COSTS`). */\n readonly rateId: string\n /** The fewest seconds a run is charged. Shorter audio is padded with silence to this length before the model sees it. */\n readonly minSeconds: number\n /** The longest audio the model takes. Longer audio is refused before anything is held. */\n readonly maxSeconds: number\n}\n\n/** OmniHuman 2.0's one-second price row. */\nexport const OMNIHUMAN_2_0_PER_SECOND_CREDIT_ID = \"omnihuman-2-0:per-second\"\n\n/**\n * The lip-sync models charged per second of audio at a rate (decided\n * 2026-11-11 for OmniHuman 2.0). Every price of such a run, its quote and its\n * hold are the rate × {@link lipSyncBilledSeconds}.\n */\nexport const LIP_SYNC_AUDIO_RATES: Readonly<Record<string, LipSyncAudioRate>> = {\n // OmniHuman 2.0 (KIE): audio from 4 to 300 seconds; the output is as long as the audio.\n \"omnihuman-2-0\": { rateId: OMNIHUMAN_2_0_PER_SECOND_CREDIT_ID, minSeconds: 4, maxSeconds: 300 },\n}\n\n/** The per-second rate a lip-sync model is charged at, or undefined for every model priced another way. */\nexport function lipSyncAudioRateOf(provider: unknown): LipSyncAudioRate | undefined {\n return typeof provider === \"string\" && Object.prototype.hasOwnProperty.call(LIP_SYNC_AUDIO_RATES, provider)\n ? LIP_SYNC_AUDIO_RATES[provider]\n : undefined\n}\n\n/**\n * The seconds a run of a per-second-rate model is charged for audio measured at\n * `measuredSec`: rounded up to a whole second, and at least the rate's minimum.\n * THE one place this rounding happens — the route, the workflow run, the\n * estimates and the provider's own cost all read it. Pass the length of the\n * audio as it was given, never of a copy padded to the minimum (a padded clip\n * runs a hair past it and would round up a whole second more).\n */\nexport function lipSyncBilledSeconds(rate: LipSyncAudioRate, measuredSec: number): number {\n if (!Number.isFinite(measuredSec) || measuredSec <= 0) return rate.minSeconds\n return Math.max(rate.minSeconds, Math.ceil(measuredSec))\n}\n\n/**\n * The length the editor quotes a lip-sync run on while its audio's length is\n * not known yet — the 15 seconds every model priced by its audio shows then\n * (a bucketed model's `:15s` row), marked as an estimate.\n */\nexport const LIP_SYNC_UNMEASURED_ESTIMATE_SECONDS = 15\n\n/**\n * The seconds an ESTIMATE prices a per-second-rate run at: the billed seconds\n * of the audio when its length is known (at most the model's maximum, the most\n * a run can be charged), else `unknownSec` — by default the maximum, so a\n * server estimate never quotes below what the run may hold; the editor passes\n * {@link LIP_SYNC_UNMEASURED_ESTIMATE_SECONDS} and shows the figure as an estimate.\n */\nexport function lipSyncEstimateSeconds(rate: LipSyncAudioRate, knownSec: number | undefined, unknownSec: number = rate.maxSeconds): number {\n if (knownSec === undefined || !Number.isFinite(knownSec) || knownSec <= 0) return lipSyncBilledSeconds(rate, unknownSec)\n return lipSyncBilledSeconds(rate, Math.min(knownSec, rate.maxSeconds))\n}\n\nexport const LIP_SYNC_DURATION_BUCKETS = [15, 30, 60, 120, 300] as const\n\nexport type LipSyncDurationBucket = typeof LIP_SYNC_DURATION_BUCKETS[number]\n\n/** Round a measured audio duration up to the next supported bucket. */\nexport function pickLipSyncBucket(seconds: number): LipSyncDurationBucket {\n if (!Number.isFinite(seconds) || seconds <= 0) return LIP_SYNC_DURATION_BUCKETS[0]\n for (const b of LIP_SYNC_DURATION_BUCKETS) {\n if (seconds <= b) return b\n }\n return 300\n}\n\n/**\n * Upper audio-duration limit per lip-sync provider, in seconds.\n * Anything longer must be trimmed (server-side) before sending upstream.\n */\nexport const LIP_SYNC_MAX_AUDIO_SECONDS: Record<string, number> = {\n \"kling-avatar\": 300,\n \"kling-avatar-pro\": 300,\n \"infinitalk\": 15,\n // OmniHuman 1.5 — KIE hard limit is < 60s; audio is auto-trimmed to this cap.\n \"omnihuman-1-5\": 60,\n // HeyGen Lipsync Precision + Sync Lipsync 2 Pro — billed per output second.\n // 5-min ceiling for credit bucketing (mirrors kling-avatar). MUST be set:\n // the default fallback below is 15s, which would clamp every request to the\n // 15s bucket and silently under-charge long clips.\n \"heygen-lipsync-precision\": 300,\n \"lipsync-2-pro\": 300,\n // Sync Lipsync v3 (fal.ai) — per-second dubbing, 5-min ceiling for bucketing.\n \"sync-lipsync-v3\": 300,\n // Volcengine (KIE) — video-to-video dubbing, per-second, 5-min ceiling.\n \"volcengine-lipsync\": 300,\n // The per-second-rate models: their own maximum (longer audio is refused, never trimmed).\n ...Object.fromEntries(Object.entries(LIP_SYNC_AUDIO_RATES).map(([provider, rate]) => [provider, rate.maxSeconds])),\n}\n\nexport function getLipSyncMaxAudioSeconds(provider: string): number {\n return LIP_SYNC_MAX_AUDIO_SECONDS[provider] ?? 15\n}\n\n/**\n * The id whose price is a 15-second run of a lip-sync model priced by the\n * length of its audio — the bucket row of a bucketed model (`<provider>:15s`),\n * the 15-second quote of a per-second-rate model — or undefined for a model\n * with one price. A model menu shows a per-second rate from it.\n */\nexport function lipSyncFifteenSecondCreditId(provider: string): string | undefined {\n const rate = lipSyncAudioRateOf(provider)\n if (rate) return unitQuoteCreditId(rate.rateId, LIP_SYNC_UNMEASURED_ESTIMATE_SECONDS)\n return isPerSecondLipSyncProvider(provider) ? `${provider}:${LIP_SYNC_UNMEASURED_ESTIMATE_SECONDS}s` : undefined\n}\n\n/**\n * Providers whose credit cost varies with audio duration, priced by BUCKET\n * (`<provider>:<bucket>s`). A model charged at a per-second rate\n * ({@link LIP_SYNC_AUDIO_RATES}) is never listed here: every caller that\n * branches on this set would bucket it.\n */\nconst PER_SECOND_LIP_SYNC_PROVIDERS = new Set([\n \"kling-avatar\",\n \"kling-avatar-pro\",\n // OmniHuman 1.5 — /sec, bucketed by audio length (60s cap).\n \"omnihuman-1-5\",\n \"heygen-lipsync-precision\",\n \"lipsync-2-pro\",\n // Sync Lipsync v3 (fal.ai) — billed per output second (/min).\n \"sync-lipsync-v3\",\n // Volcengine (KIE) — video-to-video dubbing, billed per output second.\n \"volcengine-lipsync\",\n])\n\nexport function isPerSecondLipSyncProvider(provider: string): boolean {\n return PER_SECOND_LIP_SYNC_PROVIDERS.has(provider)\n}\n\n/**\n * Build the credit identifier for a lip-sync request.\n *\n * For kling-avatar / kling-avatar-pro, returns `<provider>:<bucket>s`.\n * For other providers, returns the bare provider name (caller appends\n * any extra dimensions like resolution).\n *\n * If `audioDurationSec` is missing, defaults to the provider's max cap so\n * credit reservation covers the worst case and any overage is refunded\n * after the worker reconciles the actual KIE cost.\n */\nexport function buildLipSyncCreditId(\n provider: string,\n audioDurationSec: number | undefined,\n): string {\n if (!isPerSecondLipSyncProvider(provider)) return provider\n const cap = getLipSyncMaxAudioSeconds(provider)\n const requested = audioDurationSec === undefined || audioDurationSec <= 0\n ? cap\n : Math.min(audioDurationSec, cap)\n return `${provider}:${pickLipSyncBucket(requested)}s`\n}\n","/**\n * AI Avatar (HeyGen) duration-bucketing + credit-identifier helpers.\n * Single source of truth for the NON-monetary side of ai-avatar billing\n * (duration estimation, bucket selection, composite credit-id construction) —\n * imported by the frontend node UI (to build the id it hands to the\n * `/v1/credits/model-cost` display lookup) AND the backend route/orchestrator\n * (to resolve the credit-guard reservation id pre-Zod).\n *\n * The provider-$ rate table and the USD/credit cost FORMULAS derived from it\n * live in `backend/src/lib/pricing/ai-avatar-cost.ts` (core, not ee/ — the\n * HeyGen provider integration needs them regardless of edition). They were\n * moved out of this package (published Apache-2.0 on npm — an irrevocable\n * grant) per the 2026-07-06 public-flip IP audit, S5.\n */\n\nexport type AiAvatarEngine = \"avatar-v\" | \"avatar-iv\"\nexport type AiAvatarResolution = \"720p\" | \"1080p\" | \"4k\"\n\n/**\n * Worst-case clip duration used as the credit-reserve ceiling.\n * A 5000-character script at voiceSpeed 0.5 ≈ 5000/12/0.5 ≈ 833s → top bucket 900s.\n */\nexport const AI_AVATAR_MAX_DURATION_SEC = 900\n\n/**\n * Duration buckets (seconds) used to pick a reserve ceiling at creditGuard\n * time, when the actual clip length is unknown (text-mode scripts) or only\n * known via a server-side ffprobe (audio mode).\n *\n * The low end is FINE-GRAINED (5/10/15/30/60s) so short clips — the common\n * case — don't over-reserve. A 15s clip lands in the 15s bucket, not the old\n * coarse 30s floor (which doubled the hold). The high end stays coarse because\n * long-form scripts are rare and the bucket-up is a one-time refundable surplus.\n *\n * Bucket selection:\n * - Text mode: bucket = pickAiAvatarBucket(ceil(scriptChars / 12 / voiceSpeed)).\n * - Audio mode: bucket = pickAiAvatarBucket(ceil(probedDurationSec)) when the\n * ffprobe preHandler stashed `__probedDurationSec` on the body; otherwise a\n * MODEST 120s default (NOT the 900s top bucket — that was the bug: it\n * reserved ~4000+ credits for a sub-minute clip).\n *\n * Worst-case derivation: 5000 chars at voiceSpeed=0.5 → ceil(5000/12/0.5) = 834s\n * → fits in 900s bucket. The 900s top bucket covers all legal text inputs.\n *\n * Note: audio >900s (no probe) would undercharge against the 120s default, but\n * the commit-time metered true-up CANNOT charge more than reserved — so a long\n * un-probed audio clip is a (small) revenue leak, not an over-charge. The probe\n * closes it for the normal path. The 900s bucket remains available for the\n * probed long-audio case.\n */\nexport const AI_AVATAR_DURATION_BUCKETS = [5, 10, 15, 30, 60, 120, 240, 360, 600, 900] as const\n\n/**\n * Modest fallback bucket (seconds) for AUDIO mode when the ffprobe preHandler\n * did NOT stash a probed duration. Replaces the old 900s top-bucket fallback\n * that over-reserved ~4000+ credits for short clips. The commit-time metered\n * true-up is refund-only, so this is a reserve ceiling, not a charge.\n */\nexport const AI_AVATAR_AUDIO_FALLBACK_SEC = 120\n\n/**\n * Hard cap (seconds) on AUDIO-mode clip length. HeyGen has no natural length\n * limit on an audio-driven avatar, so a long audio = an expensive / possibly\n * rejected generation and a bounded under-reserve window. We cap it here:\n * - The worker TRIMS incoming audio longer than this down to AI_AVATAR_MAX_AUDIO_SEC\n * (and warns the user, non-fatal).\n * - The credit RESERVE is capped at this bucket too: even a 30-min probed\n * audio buckets at 600s, never the 900s top bucket. Because the worker\n * trims the actual clip to ≤600s, the metered true-up can only refund.\n *\n * Text mode (5000-char script) and cinematic (4–15s) are bounded elsewhere and\n * are NOT affected by this cap.\n */\nexport const AI_AVATAR_MAX_AUDIO_SEC = 600\n\nexport type AiAvatarDurationBucket = (typeof AI_AVATAR_DURATION_BUCKETS)[number]\n\nconst ALLOWED_ENGINES = new Set<AiAvatarEngine>([\"avatar-v\", \"avatar-iv\"])\nconst ALLOWED_RESOLUTIONS = new Set<AiAvatarResolution>([\"720p\", \"1080p\", \"4k\"])\n\n/**\n * Estimate script duration in seconds from character count and voice speed.\n *\n * Uses ~12 chars/sec at normal speed (voiceSpeed=1) — deliberately generous\n * (biased high) so the credit hold covers TTS pacing variations. Slower speech\n * (voiceSpeed < 1) produces a longer clip and thus a higher estimate.\n * Minimum 1s.\n *\n * @param script Script text (undefined treated as empty).\n * @param voiceSpeed HeyGen voice speed parameter, range 0.5–1.5 (default 1).\n * Slower speed → more seconds → higher hold.\n */\nexport function estimateScriptDurationSec(script: string | undefined, voiceSpeed = 1): number {\n const speed = Math.min(1.5, Math.max(0.5, voiceSpeed || 1))\n return Math.max(1, Math.ceil((script?.length ?? 0) / 12 / speed))\n}\n\n/**\n * Pick the smallest duration bucket that is ≥ sec.\n * Falls back to the maximum bucket (900s) when sec exceeds all buckets.\n */\nexport function pickAiAvatarBucket(sec: number): AiAvatarDurationBucket {\n for (const b of AI_AVATAR_DURATION_BUCKETS) {\n if (sec <= b) return b\n }\n return 900\n}\n\n/**\n * Composite credit identifier for a duration-bucketed reserve.\n *\n * Format: `\"heygen-<engine>:<resolution>:<bucketSec>s\"`\n * e.g. `\"heygen-avatar-iv:720p:60s\"`.\n */\nexport function aiAvatarReserveCreditId(\n engine: AiAvatarEngine,\n resolution: AiAvatarResolution,\n bucketSec: number,\n): string {\n return `heygen-${engine}:${resolution}:${bucketSec}s`\n}\n\n/**\n * Resolve the credit identifier from a raw request body BEFORE Zod validation.\n * Called at creditGuard preHandler time — mirrors how `resolveLipSyncIdentifier`\n * reads the raw body in `backend/src/routes/lip-sync.ts`.\n *\n * - `speechMode === \"text\"`: bucket by estimated script duration, accounting for\n * voiceSpeed (slower → longer clip → larger bucket). Surplus is refunded at commit.\n * - Any other speechMode (audio / missing): bucket by `__probedDurationSec` when\n * the ffprobe preHandler stashed it on the raw body; otherwise a MODEST 120s\n * default (AI_AVATAR_AUDIO_FALLBACK_SEC) — NOT the 900s top bucket. Reserving\n * the 900s ceiling for a sub-minute audio clip was the over-reservation bug\n * (~4000+ credits held for a clip that costs ~40). The commit-time metered\n * true-up is refund-only, so a modest reserve never over-charges. The effective\n * seconds are ALSO capped at AI_AVATAR_MAX_AUDIO_SEC (600s) — the worker trims\n * audio longer than that, so a 30-min audio reserves the 600s bucket, never 900s.\n *\n * - `avatarSource === \"image\"`: image-source mode is IV-class (HeyGen's own\n * engine, no avatar_id) — bill at the avatar-iv rate regardless of the\n * (ignored) `engine` field, reusing the existing heygen-avatar-iv:* ids.\n *\n * Falls back to (\"avatar-iv\", \"720p\", 120s) when fields are missing or invalid.\n */\nexport function resolveAiAvatarCreditId(\n body: Record<string, unknown> | undefined,\n): string {\n const rawEngine = body?.engine as string | undefined\n const rawResolution = body?.resolution as string | undefined\n const speechMode = body?.speechMode as string | undefined\n const avatarSource = body?.avatarSource as string | undefined\n\n // Image-source mode is IV-class (its own engine, no IV/V lever) — pin the\n // rate engine to avatar-iv and reuse the existing heygen-avatar-iv:* ids.\n const engine: AiAvatarEngine =\n avatarSource === \"image\"\n ? \"avatar-iv\"\n : rawEngine !== undefined && ALLOWED_ENGINES.has(rawEngine as AiAvatarEngine)\n ? (rawEngine as AiAvatarEngine)\n : \"avatar-iv\"\n\n const resolution: AiAvatarResolution =\n rawResolution !== undefined && ALLOWED_RESOLUTIONS.has(rawResolution as AiAvatarResolution)\n ? (rawResolution as AiAvatarResolution)\n : \"720p\"\n\n let bucketSec: AiAvatarDurationBucket\n if (speechMode === \"text\") {\n // voiceSpeed is a float in [0.5, 1.5]; coerce to number, default 1.\n // Slower speed → more seconds → larger bucket → larger hold (no undercharge).\n const voiceSpeed = Number(body?.voiceSpeed) || 1\n bucketSec = pickAiAvatarBucket(\n estimateScriptDurationSec(body?.script as string | undefined, voiceSpeed),\n )\n } else {\n // Audio/unknown mode. The ffprobe preHandler (video-sfx pattern) stashes\n // the measured clip length on the raw body as `__probedDurationSec` so we\n // can bucket by the ACTUAL audio duration. When present, bucket by it;\n // otherwise fall back to a MODEST 120s default — NOT the 900s top bucket.\n // The old 900s fallback over-reserved ~4000+ credits for sub-minute clips.\n //\n // Effective seconds are capped at AI_AVATAR_MAX_AUDIO_SEC (600s): audio mode\n // has no natural length limit, so the worker TRIMS the actual clip to ≤600s\n // and we cap the RESERVE at the matching 600s bucket. A 30-min probed audio\n // thus reserves the 600s bucket, never the 900s top bucket. Since the worker\n // trims actual to ≤600s, the metered commit can only refund.\n const probed = Number(body?.__probedDurationSec)\n const effectiveSec = Math.min(\n Number.isFinite(probed) && probed > 0\n ? Math.ceil(probed)\n : AI_AVATAR_AUDIO_FALLBACK_SEC,\n AI_AVATAR_MAX_AUDIO_SEC,\n )\n bucketSec = pickAiAvatarBucket(effectiveSec)\n }\n\n return aiAvatarReserveCreditId(engine, resolution, bucketSec)\n}\n\n/**\n * All 60 reserve credit IDs — every (engine × resolution × bucket) combination.\n * 2 engines × 3 resolutions × 10 buckets (5/10/15/30/60/120/240/360/600/900s) = 60.\n * Seeded in STATIC_CREDIT_COSTS and the model_pricing migration so\n * getModelCreditBaseCost never hard-fails (503 price_not_configured) for any\n * legal creditGuard input.\n */\nexport const AI_AVATAR_RESERVE_IDS: string[] = [...ALLOWED_ENGINES].flatMap((engine) =>\n [...ALLOWED_RESOLUTIONS].flatMap((resolution) =>\n AI_AVATAR_DURATION_BUCKETS.map((bucketSec) =>\n aiAvatarReserveCreditId(engine, resolution, bucketSec),\n ),\n ),\n)\n","// Beeble SwitchX — Relight & Switch video node. Non-monetary tier bucketing\n// and credit-identifier helpers. Beeble bills per 30-frame block with no\n// per-job meter returned, so we reserve a block tier (the smallest tier that\n// covers the clip's frame count) and commit it verbatim — tiers are 30-frame\n// multiples, so a clip snaps to the exact number of blocks Beeble bills\n// (ceil(frames/30)); there is no tier over-charge.\n//\n// The $-per-block provider rate and the credits-per-block formula derived\n// from it live in `backend/src/lib/pricing/switchx-cost.ts` (core, not ee/).\n// They were moved out of this package (published Apache-2.0 on npm — an\n// irrevocable grant) per the 2026-07-06 public-flip IP audit, S5.\nexport const SWITCHX_FRAME_TIERS = [30, 60, 90, 120, 150, 180, 210, 240] as const\n\n/** Beeble's metering granularity: frames per billed block. */\nexport const SWITCHX_BLOCK_FRAMES = 30\n\nexport function pickSwitchXFrameTier(frames?: number): number {\n if (frames === undefined || !Number.isFinite(frames) || frames <= 0) return 240\n for (const t of SWITCHX_FRAME_TIERS) if (frames <= t) return t\n return 240\n}\n\nfunction readMaxResolution(body: Record<string, unknown>): 720 | 1080 {\n const r = Number(body.maxResolution ?? body.max_resolution)\n return r === 720 ? 720 : 1080 // default 1080\n}\n\n// Frames are stashed on the raw body by the route's ffprobe preHandler.\nexport function resolveSwitchXCreditId(body: Record<string, unknown>): string {\n const frames = Number(body.__probedFrameCount)\n const tier = pickSwitchXFrameTier(Number.isFinite(frames) ? frames : undefined)\n return `beeble-switchx:${tier}f:${readMaxResolution(body)}p`\n}\n","/**\n * Cinematic Avatar (HeyGen `type:\"cinematic_avatar\"`) duration-clamping +\n * credit-identifier helpers. Single source of truth for the NON-monetary side\n * of cinematic-avatar billing — imported by the frontend node UI and the\n * backend route/orchestrator.\n *\n * The provider-$ rate table and the USD/credit cost FORMULAS derived from it\n * live in `backend/src/lib/pricing/cinematic-avatar-cost.ts` (core, not ee/ —\n * the HeyGen provider integration needs them regardless of edition). They\n * were moved out of this package (published Apache-2.0 on npm — an\n * irrevocable grant) per the 2026-07-06 public-flip IP audit, S5.\n *\n * ─── How this differs from ai-avatar pricing ────────────────────────────────\n * Cinematic Avatar is a generative clip (Seedance-style pipeline) driven by a\n * prompt + 1–3 avatar look ids. Crucially, `duration` is a USER PARAMETER\n * (4–15s, clamped) and is therefore KNOWN at submit time — unlike ai-avatar's\n * text/audio script whose clip length is only estimated. So the reserve here is\n * EXACT (no duration-bucket estimation): the credit id encodes the exact\n * requested duration, and the metered true-up at commit refunds nothing in the\n * common case (provider returns the requested duration).\n * ────────────────────────────────────────────────────────────────────────────\n */\n\nexport type CinematicResolution = \"720p\" | \"1080p\"\n\n/** Minimum / maximum / default user-selectable duration (seconds). */\nexport const CINEMATIC_MIN_DURATION_SEC = 4\nexport const CINEMATIC_MAX_DURATION_SEC = 15\nexport const CINEMATIC_DEFAULT_DURATION_SEC = 10\nexport const CINEMATIC_DEFAULT_RESOLUTION: CinematicResolution = \"720p\"\n\nconst ALLOWED_RESOLUTIONS = new Set<CinematicResolution>([\"720p\", \"1080p\"])\n\n/**\n * Clamp a (possibly invalid) duration to the legal 4–15s range, rounding to a\n * whole second. Falls back to the default (10s) for non-finite input.\n */\nexport function clampCinematicDuration(durationSec: number | undefined): number {\n const n = Number(durationSec)\n if (!Number.isFinite(n)) return CINEMATIC_DEFAULT_DURATION_SEC\n const rounded = Math.round(n)\n return Math.min(\n CINEMATIC_MAX_DURATION_SEC,\n Math.max(CINEMATIC_MIN_DURATION_SEC, rounded),\n )\n}\n\n/**\n * Composite credit identifier for an EXACT-duration reserve.\n *\n * Format: `cinematic-avatar:<resolution>:<durationSec>s`\n * e.g. `cinematic-avatar:720p:10s`.\n */\nexport function cinematicCreditId(\n resolution: CinematicResolution,\n durationSec: number,\n): string {\n return `cinematic-avatar:${resolution}:${durationSec}s`\n}\n\n/**\n * Resolve the credit identifier from a raw request body BEFORE Zod validation.\n * Called at creditGuard preHandler time — mirrors resolveAiAvatarCreditId.\n *\n * Reads `resolution` (default 720p) and `duration` (default 10, clamped 4–15)\n * straight off the raw body. Because duration is a user parameter known at\n * submit time, the reserve id is EXACT — no bucketing.\n *\n * ─── autoDuration → reserve at the MAX-duration ceiling ──────────────────────\n * When `autoDuration` is true, the provider DROPS `duration` and HeyGen picks\n * the clip length itself, so the actual metered length is UNKNOWN at submit\n * time and can exceed the requested/default `duration`. The metered true-up at\n * commit (commit_credits) can ONLY refund a surplus — it never charges more\n * when the actual exceeds the reserved hold. Reserving under the default-10s\n * hold therefore silently undercharges any auto clip longer than 10s (a revenue\n * leak). To preserve the refund-only invariant, reserve under the MAXIMUM\n * possible hold (`cinematic-avatar:<res>:15s`) so the true-up can only refund.\n */\nexport function resolveCinematicCreditId(\n body: Record<string, unknown> | undefined,\n): string {\n const rawResolution = body?.resolution as string | undefined\n const resolution: CinematicResolution =\n rawResolution !== undefined && ALLOWED_RESOLUTIONS.has(rawResolution as CinematicResolution)\n ? (rawResolution as CinematicResolution)\n : CINEMATIC_DEFAULT_RESOLUTION\n\n // autoDuration → HeyGen-chosen length, unknown at submit time → reserve at the\n // 15s ceiling so the metered true-up can only ever refund (never charge more).\n if (body?.autoDuration === true) {\n return cinematicCreditId(resolution, CINEMATIC_MAX_DURATION_SEC)\n }\n\n const durationSec = clampCinematicDuration(body?.duration as number | undefined)\n return cinematicCreditId(resolution, durationSec)\n}\n\n/**\n * All 24 reserve credit IDs — every (resolution × duration) combination.\n * 2 resolutions × 12 durations (4..15s) = 24.\n * Seeded in STATIC_CREDIT_COSTS and the model_pricing migration so\n * getModelCreditBaseCost never hard-fails (503 price_not_configured) for any\n * legal creditGuard input.\n */\nexport const CINEMATIC_RESERVE_IDS: string[] = [...ALLOWED_RESOLUTIONS].flatMap((resolution) => {\n const ids: string[] = []\n for (let d = CINEMATIC_MIN_DURATION_SEC; d <= CINEMATIC_MAX_DURATION_SEC; d++) {\n ids.push(cinematicCreditId(resolution, d))\n }\n return ids\n})\n","/**\n * Shared structural validators for the ai-avatar and cinematic-avatar payloads.\n *\n * ─── Why this exists ─────────────────────────────────────────────────────────\n * The route Zod schemas (`aiAvatarBody` / `cinematicAvatarBody`) only protect the\n * single-node Run path. Workflow runs, published-app runs, MCP run_workflow, and\n * imported/crafted workflow JSON all assemble a payload in\n * `payload-builder.ts` and forward it straight to the worker → provider →\n * HeyGen with NO Zod parse in between. That structural gap is the root cause of\n * the avatar edge-case findings: missing/over-count avatarLooks, reference caps,\n * source/speech-conditional requireds, and voice-param ranges all reach HeyGen\n * unvalidated on those paths.\n *\n * These validators reproduce the route Zod's invariants (minus the userId /\n * workflow wrapper and minus the URL-host allowlist — orchestrated URLs come\n * from trusted upstream R2 outputs). They run inside the `ai-avatar` /\n * `cinematic-avatar` cases of `payload-builder.ts` on the ASSEMBLED payload,\n * throwing `AvatarPayloadError` BEFORE credit reservation + enqueue. The\n * node-executor catches the throw and deletes the orphaned pending job, so both\n * entry points are correct-by-construction rather than relying on the route as\n * the only gate.\n *\n * Keep these in sync with `backend/src/routes/ai-avatar.ts` and\n * `backend/src/routes/cinematic-avatar.ts`.\n */\n\n/** Thrown by the avatar payload validators on a structurally-invalid payload. */\nexport class AvatarPayloadError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"AvatarPayloadError\"\n }\n}\n\nconst AI_AVATAR_SOURCES = new Set([\"avatar\", \"image\"])\nconst AI_AVATAR_ENGINES = new Set([\"avatar-v\", \"avatar-iv\"])\nconst AI_AVATAR_SPEECH_MODES = new Set([\"text\", \"audio\"])\nconst AI_AVATAR_RESOLUTIONS = new Set([\"720p\", \"1080p\", \"4k\"])\nconst AI_AVATAR_ASPECT_RATIOS = new Set([\"16:9\", \"9:16\"])\n\nconst AI_AVATAR_SCRIPT_MAX = 5000\nconst AI_AVATAR_VOICE_SPEED_MIN = 0.5\nconst AI_AVATAR_VOICE_SPEED_MAX = 1.5\nconst AI_AVATAR_PITCH_MIN = -50\nconst AI_AVATAR_PITCH_MAX = 50\nconst AI_AVATAR_VOLUME_MIN = 0\nconst AI_AVATAR_VOLUME_MAX = 1\n\nfunction isNonEmptyString(v: unknown): v is string {\n return typeof v === \"string\" && v.length > 0\n}\n\n/**\n * Validate an assembled ai-avatar payload (post-default-application).\n * Mirrors `aiAvatarBody` (`backend/src/routes/ai-avatar.ts`): enum bounds,\n * source/speech-conditional requireds, script length, and voice-param ranges.\n *\n * @throws AvatarPayloadError on any violation.\n */\nexport function validateAiAvatarPayload(payload: Record<string, unknown>): void {\n const avatarSource = (payload.avatarSource as string | undefined) ?? \"avatar\"\n const speechMode = (payload.speechMode as string | undefined) ?? \"text\"\n const engine = (payload.engine as string | undefined) ?? \"avatar-iv\"\n const resolution = (payload.resolution as string | undefined) ?? \"720p\"\n const aspectRatio = (payload.aspectRatio as string | undefined) ?? \"16:9\"\n\n if (!AI_AVATAR_SOURCES.has(avatarSource)) {\n throw new AvatarPayloadError(`ai-avatar: invalid avatarSource \"${avatarSource}\" (expected avatar | image)`)\n }\n if (!AI_AVATAR_ENGINES.has(engine)) {\n throw new AvatarPayloadError(`ai-avatar: invalid engine \"${engine}\" (expected avatar-v | avatar-iv)`)\n }\n if (!AI_AVATAR_SPEECH_MODES.has(speechMode)) {\n throw new AvatarPayloadError(`ai-avatar: invalid speechMode \"${speechMode}\" (expected text | audio)`)\n }\n if (!AI_AVATAR_RESOLUTIONS.has(resolution)) {\n throw new AvatarPayloadError(`ai-avatar: invalid resolution \"${resolution}\" (expected 720p | 1080p | 4k)`)\n }\n if (!AI_AVATAR_ASPECT_RATIOS.has(aspectRatio)) {\n throw new AvatarPayloadError(`ai-avatar: invalid aspectRatio \"${aspectRatio}\" (expected 16:9 | 9:16)`)\n }\n\n // Source-conditional requireds: avatar mode needs avatarId; image mode needs imageUrl.\n if (avatarSource === \"image\") {\n if (!isNonEmptyString(payload.imageUrl)) {\n throw new AvatarPayloadError(\"ai-avatar: imageUrl is required when avatarSource is image\")\n }\n } else {\n if (!isNonEmptyString(payload.avatarId)) {\n throw new AvatarPayloadError(\"ai-avatar: avatarId is required when avatarSource is avatar\")\n }\n }\n\n // Speech-conditional requireds.\n if (speechMode === \"text\") {\n if (!isNonEmptyString(payload.script)) {\n throw new AvatarPayloadError(\"ai-avatar: script is required when speechMode is text\")\n }\n if ((payload.script as string).length > AI_AVATAR_SCRIPT_MAX) {\n throw new AvatarPayloadError(`ai-avatar: script exceeds ${AI_AVATAR_SCRIPT_MAX} characters`)\n }\n if (!isNonEmptyString(payload.voiceId)) {\n throw new AvatarPayloadError(\"ai-avatar: voiceId is required when speechMode is text\")\n }\n } else {\n if (!isNonEmptyString(payload.audioUrl)) {\n throw new AvatarPayloadError(\"ai-avatar: audioUrl is required when speechMode is audio\")\n }\n }\n\n // Voice-param ranges (optional fields — only checked when present).\n assertNumberInRange(payload.voiceSpeed, AI_AVATAR_VOICE_SPEED_MIN, AI_AVATAR_VOICE_SPEED_MAX, \"ai-avatar: voiceSpeed\")\n assertNumberInRange(payload.pitch, AI_AVATAR_PITCH_MIN, AI_AVATAR_PITCH_MAX, \"ai-avatar: pitch\")\n assertNumberInRange(payload.volume, AI_AVATAR_VOLUME_MIN, AI_AVATAR_VOLUME_MAX, \"ai-avatar: volume\")\n}\n\nfunction assertNumberInRange(v: unknown, min: number, max: number, label: string): void {\n if (v === undefined || v === null) return\n const n = Number(v)\n if (!Number.isFinite(n) || n < min || n > max) {\n throw new AvatarPayloadError(`${label} must be between ${min} and ${max} (got ${String(v)})`)\n }\n}\n\n// ---------------------------------------------------------------------------\n// cinematic-avatar\n// ---------------------------------------------------------------------------\n\nconst CINEMATIC_RESOLUTIONS = new Set([\"720p\", \"1080p\"])\nconst CINEMATIC_ASPECT_RATIOS = new Set([\"16:9\", \"9:16\", \"1:1\"])\nexport const CINEMATIC_PROMPT_MAX = 10000\n\n/** HeyGen combined reference caps: ≤3 videos and ≤9 images across avatar looks + references. */\nexport const CINEMATIC_MAX_REFERENCE_VIDEOS = 3\nexport const CINEMATIC_MAX_REFERENCE_IMAGES = 9\nexport const CINEMATIC_MIN_LOOKS = 1\nexport const CINEMATIC_MAX_LOOKS = 3\n\n/**\n * Validate an assembled cinematic-avatar payload.\n * Mirrors `cinematicAvatarBody` (`backend/src/routes/cinematic-avatar.ts`):\n * prompt presence/length, avatarLooks count (1–3), enum bounds, and the\n * combined reference caps (≤3 videos; avatarLooks + image refs ≤ 9).\n *\n * @throws AvatarPayloadError on any violation.\n */\nexport function validateCinematicAvatarPayload(payload: Record<string, unknown>): void {\n const prompt = payload.prompt\n if (!isNonEmptyString(prompt)) {\n throw new AvatarPayloadError(\"cinematic-avatar: prompt is required\")\n }\n if ((prompt as string).length > CINEMATIC_PROMPT_MAX) {\n throw new AvatarPayloadError(`cinematic-avatar: prompt exceeds ${CINEMATIC_PROMPT_MAX} characters`)\n }\n\n const avatarLooks = payload.avatarLooks\n if (!Array.isArray(avatarLooks)) {\n throw new AvatarPayloadError(\"cinematic-avatar: avatarLooks must be an array of 1–3 look ids\")\n }\n if (avatarLooks.length < CINEMATIC_MIN_LOOKS || avatarLooks.length > CINEMATIC_MAX_LOOKS) {\n throw new AvatarPayloadError(\n `cinematic-avatar: avatarLooks must contain ${CINEMATIC_MIN_LOOKS}–${CINEMATIC_MAX_LOOKS} look ids (got ${avatarLooks.length})`,\n )\n }\n if (!avatarLooks.every((l) => isNonEmptyString(l))) {\n throw new AvatarPayloadError(\"cinematic-avatar: every avatarLooks entry must be a non-empty string\")\n }\n\n const resolution = (payload.resolution as string | undefined) ?? \"720p\"\n const aspectRatio = (payload.aspectRatio as string | undefined) ?? \"16:9\"\n if (!CINEMATIC_RESOLUTIONS.has(resolution)) {\n throw new AvatarPayloadError(`cinematic-avatar: invalid resolution \"${resolution}\" (expected 720p | 1080p)`)\n }\n if (!CINEMATIC_ASPECT_RATIOS.has(aspectRatio)) {\n throw new AvatarPayloadError(`cinematic-avatar: invalid aspectRatio \"${aspectRatio}\" (expected 16:9 | 9:16 | 1:1)`)\n }\n\n // Combined reference caps. avatar looks are image looks → count toward the\n // 9-image budget (matches the route superRefine).\n const references = payload.references\n if (references !== undefined) {\n if (!Array.isArray(references)) {\n throw new AvatarPayloadError(\"cinematic-avatar: references must be an array\")\n }\n let videoCount = 0\n let imageRefCount = 0\n for (const r of references) {\n if (!r || typeof r !== \"object\") {\n throw new AvatarPayloadError(\"cinematic-avatar: each reference must be an object { type, url }\")\n }\n const type = (r as { type?: unknown }).type\n const url = (r as { url?: unknown }).url\n if (type !== \"video\" && type !== \"image\" && type !== \"audio\") {\n throw new AvatarPayloadError(`cinematic-avatar: invalid reference type \"${String(type)}\" (expected video | image | audio)`)\n }\n if (!isNonEmptyString(url)) {\n throw new AvatarPayloadError(\"cinematic-avatar: each reference must carry a non-empty url\")\n }\n if (type === \"video\") videoCount++\n else if (type === \"image\") imageRefCount++\n }\n if (videoCount > CINEMATIC_MAX_REFERENCE_VIDEOS) {\n throw new AvatarPayloadError(\n `cinematic-avatar: at most ${CINEMATIC_MAX_REFERENCE_VIDEOS} video references are allowed (got ${videoCount})`,\n )\n }\n const totalImages = avatarLooks.length + imageRefCount\n if (totalImages > CINEMATIC_MAX_REFERENCE_IMAGES) {\n throw new AvatarPayloadError(\n `cinematic-avatar: at most ${CINEMATIC_MAX_REFERENCE_IMAGES} images are allowed across avatar looks + image references (got ${totalImages})`,\n )\n }\n }\n}\n","/**\n * Effective-tier resolution — the payg derivation.\n *\n * \"payg\" is a DERIVED tier, never stored: a user whose stored tier resolves\n * to \"free\" but who has NET lifetime top-up credits (granted − refunded,\n * clamped ≥ 0 by every SQL writer) is treated as \"payg\" by entitlement\n * checks. Stored tier stays untouched, so subscription webhooks never learn\n * about payg and a cancel→free transition re-derives it automatically.\n *\n * Lives in @nodaro/shared because the pipeline tier maps already do, and\n * both backend (credit gates, workers) and read surfaces need one source.\n *\n * The profile fields are REQUIRED (non-optional) on purpose: a call site\n * whose SELECT forgot to fetch `lifetime_topup_credits` becomes a compile\n * error instead of a silent `?? 0` that quietly deactivates payg — that is\n * the failure mode this shape exists to prevent.\n */\n\n/** Stored-tier resolution — mirrors SQL COALESCE(tier, subscription_tier, 'free'). */\nexport function resolveStoredTier(p: {\n tier: string | null\n subscription_tier: string | null\n}): string {\n return p.tier ?? p.subscription_tier ?? \"free\"\n}\n\n/**\n * Effective tier: stored \"free\" with NET lifetime top-ups > 0 derives \"payg\".\n * Every other stored tier passes through untouched.\n */\nexport function resolveEffectiveTier(p: {\n tier: string | null\n subscription_tier: string | null\n lifetime_topup_credits: number\n}): string {\n const stored = resolveStoredTier(p)\n if (stored === \"free\" && p.lifetime_topup_credits > 0) return \"payg\"\n return stored\n}\n\n/** Media-retention activity window for payg users (design 2026-07-05 §4.6). */\nexport const PAYG_RETENTION_DAYS = 90\n\n/**\n * Is this payg user inside their retention-activity window?\n *\n * Activity = credit SPEND (callers supply MAX(usage_logs.created_at) — never\n * `last_daily_reset`, which read-only balance polls bump) OR a top-up\n * PURCHASE (`last_topup_at`). Within PAYG_RETENTION_DAYS of either → the\n * nightly reaper leaves their media alone; past it, the standard free-tier\n * reaper rules apply. A user with no lifetime purchases is never\n * retention-active (they are not payg).\n */\nexport function isPaygRetentionActive(\n p: {\n lifetimeTopupCredits: number\n lastTopupAt: string | Date | null\n lastSpendAt: string | Date | null\n },\n now: Date\n): boolean {\n if (p.lifetimeTopupCredits <= 0) return false\n const cutoff = now.getTime() - PAYG_RETENTION_DAYS * 24 * 60 * 60 * 1000\n const at = (v: string | Date | null): number | null => {\n if (v === null) return null\n const t = v instanceof Date ? v.getTime() : new Date(v).getTime()\n return Number.isFinite(t) ? t : null\n }\n const topup = at(p.lastTopupAt)\n const spend = at(p.lastSpendAt)\n return (topup !== null && topup >= cutoff) || (spend !== null && spend >= cutoff)\n}\n","/**\n * Video-analysis pricing — shared duration-bucket credit model.\n *\n * Single source of truth for the video-analysis node's NON-monetary credit\n * math: duration bucketing, the window-batching constants (also consumed by\n * the backend workers for real chunking, not just pricing), and the\n * composite credit-id builder. The route (charge at generate-time), the\n * worker (re-check + settle), and the frontend node UI (via\n * `buildVideoAnalysisCreditId` + `/v1/credits/model-cost`) all derive from\n * these.\n *\n * The rate constants and the formula that GENERATE these numbers live\n * PRIVATELY in the `@nodaroai/cloud-plugins` package — never in this public\n * repo. They were first moved out of this package (published Apache-2.0 on\n * npm), then out of the app repo entirely alongside the rest of the\n * video-analysis node. A cross-check test in that private package guards\n * this table so the public numbers can't silently drift from the formula.\n *\n * `VIDEO_ANALYSIS_BUCKET_CREDITS` below is the precomputed OUTPUT of that\n * private formula for every (model × bucket) combination — a plain credit\n * lookup table, not a formula, mirroring the same wire-contract pattern\n * `VIDEO_CLIP_CREDITS` uses in `film-pricing.ts`. It is what the frontend's\n * client-side cost preview (`estimateNodeCredits` in\n * workflow-editor/types.ts) reads instead of calling the formula directly.\n * The formula's own test in `@nodaroai/cloud-plugins` cross-checks this\n * table against it and fails on drift. There is deliberately NO app-side formula to\n * check against — it was moved private in 2026-07 and the old backend test\n * went with it.\n *\n * `VIDEO_AUDIT_BUCKET_CREDITS` further down is the sibling table for the\n * `video-audit` node (\"AI Audit\") — same module, same bucket ladder, same\n * generator-authoritative pattern, its own two credit families.\n */\n\nexport const VIDEO_ANALYSIS_DURATION_BUCKETS = [60, 180, 360, 600] as const\n/** Pricing grace: a clip at most this far past a bucket edge is priced at that\n * bucket. A part chosen as 1:00 in the Video URL chooser downloads at about\n * 1:03 (the cut lands on keyframes), and must cost a minute, not three. Read\n * by pickVideoAnalysisBucket — the ONE bucket picker every price reads (the\n * editor estimate, the orchestrator reserve, the cloud routes). */\nexport const VIDEO_ANALYSIS_BUCKET_GRACE_SEC = 3\n/** Worker re-check grace: route metadata is integer-rounded, provider durations nominal;\n * ffprobe floats run 0.05–2 s over. Zero tolerance fails legit videos at 1:00/3:00/6:00/10:00.\n * It sits ON TOP of the pricing grace: a clip the grace priced into a bucket\n * (probe 63 s → 60 s) must still pass the worker gate (bucket + tolerance) at\n * its float length (63.4 s). The cloud plugin reads this constant from the\n * host app at run time, so its gate moves with it. */\nexport const VIDEO_ANALYSIS_DURATION_TOLERANCE_SEC = VIDEO_ANALYSIS_BUCKET_GRACE_SEC + 3\nexport const VIDEO_ANALYSIS_MAX_DURATION_SEC = 600\nconst WINDOW_LEN = 150, WINDOW_STRIDE = 145, WINDOW_OVERLAP = 5\nexport const VIDEO_ANALYSIS_WINDOW = { LEN: WINDOW_LEN, STRIDE: WINDOW_STRIDE, OVERLAP: WINDOW_OVERLAP, SINGLE_MAX: 180 } as const\n\n/**\n * Precomputed credit cost per (model, bucket) — the OUTPUT of the private\n * `videoAnalysisBucketCredits` formula (in `@nodaroai/cloud-plugins`), not a\n * formula itself. Regenerate by running that function for every\n * `VIDEO_ANALYSIS_LLM_MODELS` × duration bucket combination whenever the\n * underlying rate/token constants change (the plugin's cost test guards drift).\n * Keep in sync with\n * `docs/nodes/processing-video/video-analysis.md`.\n */\n// EVERY row here is RE-DERIVED from the cloud-plugins formula at the current\n// credit base — never a mechanical x10 of an older table. The formula ceils USD\n// into credits, so a 10x finer base rounds LESS: the 60s flash bucket is 23,\n// where x10 of the old 3 would have been 30 (a ~30% over-charge).\n//\n// That applies to the SENTINEL rows (`mixed:*`, `smart:*`) exactly as much as to\n// the per-model rows. They were briefly shipped as a x10 on the reasoning that\n// they sit outside the plugin's cross-check loop — but being outside the loop\n// makes a row UNGUARDED, not exempt: `videoAnalysisBucketCredits` computes them\n// from the same roll plan, so they are formula-derived too (mixed:60s is 104,\n// not 110). The plugin's cost test now covers sentinels as well, so this class\n// of drift fails CI instead of shipping.\n// REGENERATED 2026-07-31 with the smart-tier re-base (formula inputs moved in\n// the plugin: sampling 24→6 fps, which proved equal on content and better on\n// cast stability; system-prompt and per-window output-token constants updated).\n// Net effect: smart drops 27–47% per bucket, and the economy rows tick up 3–6%.\n//\n// REGENERATED 2026-08-03 — V1 hybrid-smart reprice, from the plugin's own\n// generator. This is the V1 true-up of the earlier provisional\n// judge/refine/frame-judge constants (the constants themselves, like the rest\n// of the formula, stay private in the plugin repo — never in this public\n// package). `smart` is now a multi-roll plan that always refines its merged\n// result (`selectionMode` does not apply to it), and every multi-roll tier\n// now carries its own explicit judge/refine terms instead of an implicit\n// share of a single-pass budget.\n// The economy tiers rise too (fast 33->185 @180s).\n// Net effect, per bucket (every row rises):\n//\n// gemini-3-flash 60s 24->180 180s 33->185 360s 86-> 514 600s 143-> 846\n// gemini-3.6-flash 60s 65->203 180s 92->218 360s 237-> 598 600s 395-> 986\n// gemini-3.1-pro 60s 87->215 180s 116->231 360s 305-> 636 600s 509->1050\n// mixed 60s 110->228 180s 149->249 360s 390-> 684 600s 651->1129\n// mixed (2026-08-04) 60s 228->268 180s 249->289 360s 684-> 724 600s 1129->1169 (+40 flat: continuity pass joined the family)\n// smart 60s 333->410 180s 470->500 360s 1135->1259 600s 1868->2064\n//\n// Values are pasted verbatim from the plugin generator's output — never hand\n// computed. The plugin's cost test cross-checks every row, sentinels included.\n// REGENERATED 2026-08-28 — recast shot-craft Stage 1: the analyser's system\n// prompt grew (transition/on-screen-text doctrine + three required wire\n// fields), so the plugin's system-prompt token pin moved 8_203 → 8_482 and\n// 21 of 28 rows tick up by 1–4 credits (~0.1–0.3%). Output of the plugin's\n// `scripts/gen-va-buckets.mjs` on `feat/va-shot-craft`, pasted verbatim.\n//\n// REGENERATED 2026-08-29 — recast shot-craft Stage 1.3: the analyser's system\n// prompt grew again, moving the plugin's system-prompt token pin 8_482 → 8_706\n// (cloud-plugins 0.209.0). 12 of 20 analysis rows and 6 of 8 audit rows tick up\n// by 1–3 credits (~0.1–0.3%); the legacy `gemini-3-flash` family is unchanged.\n// Output of the plugin's `scripts/gen-va-buckets.mjs`, pasted verbatim.\n//\n// REGENERATED 2026-08-30 — transition vocabulary v2: the analyser's doctrine now\n// DEFINES twelve named transition values (and says an absent transition asserts\n// nothing), which grew the analyser's system prompt once more — the plugin's\n// system-prompt token pin moved 8_706 → 9_082 (cloud-plugins 0.212.0). 15 of 20\n// analysis rows and 6 of 8 audit rows tick up by 1–5 credits (~0.1–0.6%); unlike\n// the 8_482 → 8_706 round, the legacy `gemini-3-flash` family moves too.\n// Output of the plugin's `scripts/gen-va-buckets.mjs`, pasted verbatim.\n//\n// RESET 2026-10-14 to the DEPLOYED schedule (migration 357, the 9_082 pin). A\n// 2026-09-06 regeneration (the 9_434 pin) moved these rows up by 1–5 credits\n// but shipped no migration, so for five weeks every estimate, doc and tool\n// description quoted a price no run was charged. This table is what\n// `model_pricing` holds, not the generator's latest output: a regeneration\n// lands TOGETHER with the migration that seeds it —\n// `backend/src/ee/billing/__tests__/static-costs-match-migrations.test.ts`\n// fails the build on any row that differs from its latest migration.\nexport const VIDEO_ANALYSIS_BUCKET_CREDITS: Record<string, number> = {\n // Current fast tier (VIDEO_ANALYSIS_TIERS.fast; it was also the fast model\n // before 2026-07).\n \"video-analysis:gemini-3-flash:60s\": 181,\n \"video-analysis:gemini-3-flash:180s\": 185,\n \"video-analysis:gemini-3-flash:360s\": 515,\n \"video-analysis:gemini-3-flash:600s\": 848,\n // Legacy fast-tier model (backed the fast tier 2026-07 → 2026-07-29) — kept\n // for stored raw-id configs; still ≤ pro per bucket.\n \"video-analysis:gemini-3.6-flash:60s\": 204,\n \"video-analysis:gemini-3.6-flash:180s\": 219,\n \"video-analysis:gemini-3.6-flash:360s\": 602,\n \"video-analysis:gemini-3.6-flash:600s\": 992,\n \"video-analysis:gemini-3.1-pro:60s\": 216,\n \"video-analysis:gemini-3.1-pro:180s\": 232,\n \"video-analysis:gemini-3.1-pro:360s\": 640,\n \"video-analysis:gemini-3.1-pro:600s\": 1056,\n // Mixed tiers (`mixed` + `mixed-fast`) share ONE credit family — they are\n // variants of the same engine plan (plan internals live in the private\n // analysis plugin). Admin-tunable via model_pricing like every other row.\n \"video-analysis:mixed:60s\": 270,\n \"video-analysis:mixed:180s\": 291,\n \"video-analysis:mixed:360s\": 729,\n \"video-analysis:mixed:600s\": 1177,\n // SMART — the accuracy tier, and since the 2026-08-03 re-plan a multi-roll\n // plan like the others, always refined (`selectionMode` does not apply\n // here — smart always refines; it never offers a cheaper \"choose\" path).\n // Priced above the economy tiers because it genuinely costs more to run;\n // the only tier whose accuracy is validated against a hand-counted edit\n // list, re-validated at the current plan before this schedule shipped.\n \"video-analysis:smart:60s\": 413,\n \"video-analysis:smart:180s\": 503,\n \"video-analysis:smart:360s\": 1267,\n \"video-analysis:smart:600s\": 2076,\n}\n\n/**\n * The credit-id MODEL SEGMENT for an engine identifier: both mixed-tier\n * sentinels share the `mixed` price family (same engine plan); everything\n * else prices under its own identifier. Single source of truth — used by\n * `buildVideoAnalysisCreditId` below, so route/orchestrator/UI callers can\n * never diverge on where a sentinel prices.\n */\nexport function videoAnalysisCreditSegment(modelOrSentinel: string): string {\n return modelOrSentinel === \"mixed-fast\" ? \"mixed\" : modelOrSentinel\n}\n\nexport function pickVideoAnalysisBucket(durationSec: number): number {\n for (const b of VIDEO_ANALYSIS_DURATION_BUCKETS) if (durationSec <= b + VIDEO_ANALYSIS_BUCKET_GRACE_SEC) return b\n return VIDEO_ANALYSIS_MAX_DURATION_SEC\n}\n\nexport function buildVideoAnalysisCreditId(model: string, durationSec?: number): string {\n const bucket = durationSec !== undefined && durationSec > 0\n ? pickVideoAnalysisBucket(Math.min(durationSec, VIDEO_ANALYSIS_MAX_DURATION_SEC))\n : VIDEO_ANALYSIS_MAX_DURATION_SEC // unknown → ceiling composite (the ONLY silent-ceiling path)\n return `video-analysis:${videoAnalysisCreditSegment(model)}:${bucket}s`\n}\n\nexport function bucketSecondsFromCreditId(creditId: string): number | null {\n const m = /^video-analysis:.+:(\\d+)s$/.exec(creditId)\n return m ? Number(m[1]) : null\n}\n\nexport function videoAnalysisNumWindows(bucketSec: number): number {\n return bucketSec <= VIDEO_ANALYSIS_WINDOW.SINGLE_MAX ? 1 : 1 + Math.ceil((bucketSec - WINDOW_LEN) / WINDOW_STRIDE)\n}\n\n/**\n * Precomputed credit cost for the `video-audit` node (\"AI Audit\") — the same\n * pattern as `VIDEO_ANALYSIS_BUCKET_CREDITS` above: the OUTPUT of the private\n * `videoAuditBucketCredits` formula in `@nodaroai/cloud-plugins`\n * (in the plugin repo), a plain lookup table never a\n * formula, cross-checked against that package's own cost test. Shares the\n * SAME duration-bucket ladder as video-analysis (`VIDEO_ANALYSIS_DURATION_BUCKETS`\n * / `pickVideoAnalysisBucket`) — the audit re-watches the same clip, so it\n * buckets identically.\n *\n * Two credit families, selected by whether an analysis was wired into the\n * node (see `buildVideoAuditCreditId`):\n * - `video-audit:<bucket>s` — an analysis was provided; the audit re-watches\n * the clip against it directly (native watcher roll + reasoner pass, at a\n * safety margin — internals stay private in the plugin).\n * - `video-audit:auto:<bucket>s` — no analysis wired; the node auto-runs a\n * fast-tier analysis first. Exactly the base family's price PLUS the\n * `gemini-3-flash` (legacy fast tier) row from `VIDEO_ANALYSIS_BUCKET_CREDITS`\n * at the SAME bucket — summed in the plugin's generator/formula, never\n * hand-added here (see the single-source assertion in\n * video-analysis-pricing.test.ts).\n *\n * Bare ids (`video-audit`, `video-audit:auto` — they live in\n * `model-catalog.ts`'s pricing rows, not as keys in this table) equal their\n * family's 600s ceiling, the same \"unknown duration → ceiling\" convention\n * `VIDEO_ANALYSIS_BUCKET_CREDITS`'s bare per-model catalog rows use.\n * `buildVideoAuditCreditId` never returns a bare id itself — an\n * unknown/invalid duration resolves to the bucketed 600s id, matching\n * `buildVideoAnalysisCreditId`.\n *\n * Values pasted verbatim from the plugin generator's output\n * (the plugin repo's bucket generator) —\n * never hand computed. The plugin's cost test cross-checks every row.\n */\nexport const VIDEO_AUDIT_BUCKET_CREDITS: Record<string, number> = {\n \"video-audit:60s\": 215,\n \"video-audit:180s\": 290,\n \"video-audit:360s\": 663,\n \"video-audit:600s\": 1073,\n \"video-audit:auto:60s\": 396,\n \"video-audit:auto:180s\": 475,\n \"video-audit:auto:360s\": 1178,\n \"video-audit:auto:600s\": 1921,\n}\n\n/**\n * Composite credit-id builder for `video-audit`. Mirrors\n * `buildVideoAnalysisCreditId`'s bucket selection and unknown/invalid-duration\n * ceiling fallback exactly (same ladder, same rounding — `durationSec <=\n * bucket`, clamped to the 600s max), but selects the FAMILY by whether an\n * analysis was already provided instead of by model: `analysisProvided:\n * true` prices under the cheaper `video-audit` family (re-audits an existing\n * analysis); `false` prices under `video-audit:auto` (the node auto-runs a\n * fast analysis first, hence that family's built-in fast-tier addition).\n */\nexport function buildVideoAuditCreditId(args: { analysisProvided: boolean; durationSec?: number }): string {\n const { analysisProvided, durationSec } = args\n const bucket = durationSec !== undefined && durationSec > 0\n ? pickVideoAnalysisBucket(Math.min(durationSec, VIDEO_ANALYSIS_MAX_DURATION_SEC))\n : VIDEO_ANALYSIS_MAX_DURATION_SEC // no/invalid duration → ceiling composite, same convention as buildVideoAnalysisCreditId\n const family = analysisProvided ? \"video-audit\" : \"video-audit:auto\"\n return `${family}:${bucket}s`\n}\n\n/**\n * Table lookup for a resolved bucket + family. Snaps `bucketSec` onto the\n * ladder via `pickVideoAnalysisBucket` first, so a raw duration (not just an\n * exact 60/180/360/600) is safe to pass — mirrors `buildVideoAuditCreditId`'s\n * own rounding rather than requiring the caller to pre-round.\n */\nexport function videoAuditCreditsForBucket(bucketSec: number, auto: boolean): number {\n const bucket = pickVideoAnalysisBucket(bucketSec)\n return VIDEO_AUDIT_BUCKET_CREDITS[`video-audit${auto ? \":auto\" : \"\"}:${bucket}s`]!\n}\n\n/**\n * Parses a `video-audit:*` credit id back to its bucket seconds — both\n * families (`video-audit:<n>s` and `video-audit:auto:<n>s`); null on\n * anything else (a bare id with no bucket, a `video-analysis:*` id, or\n * garbage). Deliberately a SEPARATE parser from `bucketSecondsFromCreditId`\n * (anchored to the `video-analysis:` prefix and a mandatory model segment) —\n * mirrors the plugin-local audit parser so app code can never mis-parse an\n * audit id with the VA-anchored parser, or vice versa.\n */\nexport function bucketSecondsFromAuditCreditId(id: string): number | null {\n const m = /^video-audit(?::auto)?:(\\d+)s$/.exec(id)\n return m ? Number(m[1]) : null\n}\n","import { buildLlmCreditIdentifier, getLlmModel, LLM_FEATURE_DEFAULTS } from \"./llm-models.js\"\n\n/**\n * Pricing vocabulary for the \"steal the format\" nodes — Content Recipe and\n * Content Ideas. Public prices only: the credit ids a run is billed under and\n * the count rule that picks between them. One copy for the editor's credit\n * badge, the workflow orchestrator's reservation and the pre-run estimate;\n * the cloud plugin that runs the nodes computes the same ids.\n *\n * Content Ideas is charged per batch of up to five ideas: a run of 1–5 ideas\n * bills `content-ideas[:economy|:premium|:premium-direct]`, a run of 6–10 bills\n * `content-ideas:10[:economy|:premium|:premium-direct]`, priced at two batches.\n */\n\nexport const CONTENT_IDEAS_MAX_COUNT = 10\nexport const CONTENT_IDEAS_DEFAULT_COUNT = 5\nexport const CONTENT_IDEAS_PER_CHARGE = 5\n\n/** Request limits the cloud routes enforce — the orchestrator trims to the\n * same bounds, since its payload never passes the route's validation. */\nexport const CONTENT_RECIPE_SOURCE_MAX = 300_000\nexport const CONTENT_IDEAS_MAX_RECIPE_INPUTS = 20\nexport const CONTENT_IDEAS_BRAND_MAX = 6_000\nexport const CONTENT_IDEAS_LANGUAGE_MAX = 40\n\n/** A whole number of ideas in 1..10; anything but a finite number is the\n * default. (The plugin reads `count` the same way — numbers only.) */\nexport function clampContentIdeasCount(raw: unknown): number {\n const n = typeof raw === \"number\" && Number.isFinite(raw) ? Math.floor(raw) : CONTENT_IDEAS_DEFAULT_COUNT\n return Math.min(CONTENT_IDEAS_MAX_COUNT, Math.max(1, n))\n}\n\n/** The billing feature for a run of `count` ideas. */\nexport function contentIdeasCreditFeature(count: number): \"content-ideas\" | \"content-ideas:10\" {\n return count > CONTENT_IDEAS_PER_CHARGE ? \"content-ideas:10\" : \"content-ideas\"\n}\n\n/** The model a node runs: its own pick when the registry can return\n * structured output, else the feature default. Billing uses THIS — a missing\n * model must never bill the bare (standard) id while running economy. */\nexport function effectiveContentModel(feature: \"content-recipe\" | \"content-ideas\", llmModel: unknown): string {\n if (typeof llmModel === \"string\" && getLlmModel(llmModel)?.structuredOutputMode != null) return llmModel\n return LLM_FEATURE_DEFAULTS[feature]\n}\n\nexport function contentRecipeCreditId(llmModel?: unknown, reasoningEffort?: string): string {\n return buildLlmCreditIdentifier(\"content-recipe\", effectiveContentModel(\"content-recipe\", llmModel), reasoningEffort)\n}\n\nexport function contentIdeasCreditId(count: unknown, llmModel?: unknown, reasoningEffort?: string): string {\n return buildLlmCreditIdentifier(\n contentIdeasCreditFeature(clampContentIdeasCount(count)),\n effectiveContentModel(\"content-ideas\", llmModel),\n reasoningEffort,\n )\n}\n\n/** Every credit id the two nodes can bill — for price tables and guards. */\nexport const CONTENT_RECIPE_IDEAS_CREDIT_IDS = [\n \"content-recipe:economy\",\n \"content-recipe\",\n \"content-recipe:premium\",\n \"content-recipe:premium-direct\",\n \"content-ideas:economy\",\n \"content-ideas\",\n \"content-ideas:premium\",\n \"content-ideas:premium-direct\",\n \"content-ideas:10:economy\",\n \"content-ideas:10\",\n \"content-ideas:10:premium\",\n \"content-ideas:10:premium-direct\",\n] as const\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/caption-styles.ts","../src/caption-plan.ts","../src/supported-fonts.ts","../src/caption-segment-schema.ts","../src/caption-edge-dash.ts","../src/add-captions-plan.ts"],"names":["z"],"mappings":";;;;;AAcO,IAAM,qBAAA,GAAwB,CAAC,UAAU;AACzC,IAAM,sBAAA,GAAyB;AAAA,EACpC,gBAAA;AAAA,EACA,SAAA;AAAA,EACA,cAAA;AAAA,EACA,UAAA;AAAA,EACA;AACF;AACO,IAAM,kBAAA,GAAqB,CAAC,GAAG,qBAAA,EAAuB,GAAG,sBAAsB;AAMtF,IAAM,WAAA,GAAc,IAAI,GAAA,CAAY,sBAAsB,CAAA;AAEnD,SAAS,sBAAsB,KAAA,EAAgE;AACpG,EAAA,OAAO,UAAU,IAAA,IAAQ,KAAA,KAAU,MAAA,IAAa,WAAA,CAAY,IAAI,KAAK,CAAA;AACvE;AAOO,IAAM,gBAAA,GAAmB,CAAC,SAAA,EAAW,OAAO;AAM5C,IAAM,oBAAA,GAAsC;AAO5C,IAAM,qBAAA,GAAuC;AAc7C,IAAM,+BAAA,GAAkC;AAAA,EAC7C,gBAAA;AAAA,EACA;AAC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US.cjs","sourcesContent":["import type { SupportedFontName } from \"./supported-fonts.js\"\n\n/**\n * Caption styles for the add-captions node. Static path uses FFmpeg drawtext;\n * kinetic styles render via Remotion (BurnCaptions composition).\n *\n * Single source of truth — imported by:\n * - backend route Zod (add-captions.ts)\n * - backend worker handler (ffmpeg.ts)\n * - backend MCP tool (verbs-video.ts)\n * - backend plan schema (plan-schemas.ts)\n * - frontend node config + cost helper\n * - packages/remotion overlay dispatcher\n */\nexport const STATIC_CAPTION_STYLES = [\"subtitle\"] as const\nexport const KINETIC_CAPTION_STYLES = [\n \"word-highlight\",\n \"karaoke\",\n \"tiktok-words\",\n \"word-pop\",\n \"bouncy\",\n] as const\nexport const ALL_CAPTION_STYLES = [...STATIC_CAPTION_STYLES, ...KINETIC_CAPTION_STYLES] as const\n\nexport type StaticCaptionStyle = (typeof STATIC_CAPTION_STYLES)[number]\nexport type KineticCaptionStyle = (typeof KINETIC_CAPTION_STYLES)[number]\nexport type CaptionStyle = (typeof ALL_CAPTION_STYLES)[number]\n\nconst KINETIC_SET = new Set<string>(KINETIC_CAPTION_STYLES)\n\nexport function isKineticCaptionStyle(style: string | undefined | null): style is KineticCaptionStyle {\n return style !== null && style !== undefined && KINETIC_SET.has(style)\n}\n\n// ── Named \"looks\" ──────────────────────────────────────────────────────────\n// A look is a bundle of visual levers so a caption reads well with one field\n// instead of eight. Shared because the ids are wire contract (route Zod, MCP\n// schema, SDK type) and the value table is consumed by BOTH the worker (render)\n// and the canvas preview — deliberately given away, not creative doctrine.\nexport const CAPTION_LOOK_IDS = [\"outline\", \"clean\"] as const\nexport type CaptionLookId = (typeof CAPTION_LOOK_IDS)[number]\n\n/** What an unset `look` means on a KINETIC style. ONE-LINE FLIP: set to \"clean\"\n * to make an unset caption render as the pre-look-system lever set (face pinned)\n * instead. */\nexport const DEFAULT_CAPTION_LOOK: CaptionLookId = \"outline\"\n\n/** What an unset `look` means on the static `subtitle` style: the plain read —\n * a pinned neutral sans, no outline, no casing. A subtitle must never be left\n * with NO face: the Remotion render would fall back to headless Chrome's default\n * SERIF, so adding e.g. a stroke to a subtitle would silently flip its font away\n * from the sans the plain FFmpeg subtitle draws. */\nexport const DEFAULT_SUBTITLE_LOOK: CaptionLookId = \"clean\"\n\n/**\n * The lever field names that are MEANINGLESS on a `subtitle` render and so are\n * rejected on it: `highlightColor` (subtitle has no per-word spoken cursor to\n * colour) and `animate` (subtitle has no motion to switch off). The STYLING\n * levers (look/fontFamily/fontWeight/strokeColor/strokeWidth/uppercase/positionY)\n * are NOT here any more — a `subtitle` carrying any of them now routes to the\n * Remotion renderer (see `captionRoutesToRemotion`), which applies them exactly\n * as it does for the kinetic styles. Single source of truth for the route's\n * reject-on-subtitle guard and the frontend's \"don't send a stale lever\" strip.\n * `color`/`backgroundColor` are deliberately absent — FFmpeg subtitle honours\n * those too.\n */\nexport const KINETIC_ONLY_CAPTION_LEVER_KEYS = [\n \"highlightColor\",\n \"animate\",\n] as const\nexport type KineticOnlyCaptionLeverKey = (typeof KINETIC_ONLY_CAPTION_LEVER_KEYS)[number]\n\n/**\n * Does an add-captions request need the Remotion renderer, vs the cheap static\n * FFmpeg drawtext path? A caption routes to Remotion when it needs anything the\n * one-fixed-string drawtext pass cannot do:\n * - per-segment treatments (`segments`),\n * - a kinetic style,\n * - any STYLING lever (look/font/weight/stroke/uppercase/position_y/\n * max_words_per_line) — FFmpeg drawtext can't apply a webfont face, weight,\n * outline, casing, a free vertical position, or line grouping,\n * - TIMED captions (a wired `transcript` or an explicit `captions[]` array),\n * - auto-transcription, i.e. no `text` to burn as one static block.\n * Plain-`text` `subtitle` with no lever stays on FFmpeg (unchanged, cheap).\n *\n * SINGLE SOURCE for BOTH the worker dispatch (handleAddCaptions) AND the credit\n * id (buildAddCaptionsCreditId) so the renderer and the price never drift: a\n * Remotion render bills as `add-captions:kinetic`, a plain drawtext burn as\n * `add-captions`.\n */\nexport function captionRoutesToRemotion(input: {\n style?: string | null\n text?: string | null\n segments?: readonly unknown[] | null\n transcript?: unknown\n captions?: readonly unknown[] | null\n look?: unknown\n fontFamily?: unknown\n fontWeight?: unknown\n strokeColor?: unknown\n strokeWidth?: unknown\n uppercase?: unknown\n positionY?: unknown\n maxWordsPerLine?: unknown\n}): boolean {\n if (input.segments && input.segments.length > 0) return true\n if (isKineticCaptionStyle(input.style)) return true\n // From here the style is `subtitle` (or unset → the subtitle default).\n // `null` is \"not set\", exactly like `undefined`: stored node JSON (an agent's\n // write, an import, a cleared field) carries nulls, and a null lever that\n // counted as a lever would route a plain subtitle to Remotion — and its price\n // — for a lever nobody chose.\n const isSet = (v: unknown): boolean => v !== undefined && v !== null\n const hasStylingLever =\n isSet(input.look) ||\n isSet(input.fontFamily) ||\n isSet(input.fontWeight) ||\n isSet(input.strokeColor) ||\n isSet(input.strokeWidth) ||\n isSet(input.uppercase) ||\n isSet(input.positionY) ||\n isSet(input.maxWordsPerLine)\n if (hasStylingLever) return true\n if (input.transcript !== undefined && input.transcript !== null) return true\n if (input.captions && input.captions.length > 0) return true\n // No `text` to burn as one static block → the only caption source is\n // transcription, which produces TIMED captions the drawtext pass can't show.\n if (!input.text) return true\n return false\n}\n\n/**\n * `maxWordsPerLine` — caps how many words a caption LINE (or tiktok-words page)\n * may hold, on top of the frame-width budget, sentence ends and pauses that\n * already close a line. 1–2 gives the punchy CapCut read; unset = fit the width.\n * Applies to every line/page-grouped render (word-highlight, karaoke, bouncy,\n * tiktok-words, and a Remotion-rendered subtitle); inert on word-pop (always one\n * word). Bounds single-sourced here for the route Zod, the plan schema, the MCP\n * schema, the CLI and the canvas panel.\n */\nexport const CAPTION_MAX_WORDS_PER_LINE_MIN = 1\nexport const CAPTION_MAX_WORDS_PER_LINE_MAX = 20\n\n/**\n * Numeric caption levers and their wire bounds — the SAME limits the route Zod\n * and the render-plan schema enforce. Single-sourced so the coercion below and\n * those schemas cannot disagree (a guard test pins the route to these).\n */\nexport const CAPTION_LEVER_BOUNDS = {\n fontSize: { min: 12, max: 200 },\n strokeWidth: { min: 0, max: 40 },\n positionY: { min: 0, max: 100 },\n fontWeight: { min: 100, max: 900 },\n maxWordsPerLine: { min: CAPTION_MAX_WORDS_PER_LINE_MIN, max: CAPTION_MAX_WORDS_PER_LINE_MAX },\n} as const\n\ntype CaptionNumericLeverKey = keyof typeof CAPTION_LEVER_BOUNDS\nconst CAPTION_NUMERIC_LEVER_KEYS = Object.keys(CAPTION_LEVER_BOUNDS) as CaptionNumericLeverKey[]\n\n/**\n * COERCE, never reject: bring the numeric caption levers of node data that\n * never passed a Zod (a workflow written by an agent, an import, a template, a\n * FieldMapping) into the range the render plan accepts. Without this an\n * out-of-range value only surfaces when the plan schema throws — mid-run, after\n * credits are reserved. A `null` / non-finite / non-numeric value is DROPPED (the\n * render default applies); an out-of-range one is clamped; `fontWeight` snaps to the\n * nearest 100 and `maxWordsPerLine` to a whole number. Pure; returns a copy and\n * leaves every other field untouched. Applied by payload-builder to the node's\n * top level and to each `segments[]` entry.\n */\nexport function normalizeCaptionNumericLevers<T extends Record<string, unknown>>(input: T): T {\n const out: Record<string, unknown> = { ...input }\n for (const key of CAPTION_NUMERIC_LEVER_KEYS) {\n if (!(key in out) || out[key] === undefined) continue\n // `null` is \"not set\": drop it rather than carry it — the render plan's\n // numeric schema rejects a null, mid-run, after credits are reserved.\n if (out[key] === null) {\n delete out[key]\n continue\n }\n const raw = typeof out[key] === \"string\" && (out[key] as string).trim() !== \"\" ? Number(out[key]) : out[key]\n if (typeof raw !== \"number\" || !Number.isFinite(raw)) {\n delete out[key]\n continue\n }\n const { min, max } = CAPTION_LEVER_BOUNDS[key]\n const shaped = key === \"fontWeight\" ? Math.round(raw / 100) * 100 : key === \"maxWordsPerLine\" ? Math.round(raw) : raw\n out[key] = Math.min(max, Math.max(min, shaped))\n }\n return out as T\n}\n\n/** The concrete levers a look (and any explicit override) resolves to. */\nexport interface CaptionLookLevers {\n fontFamily?: SupportedFontName\n fontWeight?: number\n color?: string\n backgroundColor?: string\n strokeColor?: string\n strokeWidth?: number\n highlightColor?: string\n uppercase?: boolean\n}\n\n/** Outline width = 10% of font size (min 2px). `paint-order: stroke fill` puts\n * half the stroke OUTSIDE the glyph, so the visible rim is ~5% of font size. */\nexport function autoStrokeWidth(fontSize: number): number {\n return Math.max(2, Math.round(fontSize * 0.1))\n}\n\n/** Each look is a function of font size (so the outline tracks the text size). */\nexport const CAPTION_LOOKS: Record<CaptionLookId, (fontSize: number) => CaptionLookLevers> = {\n // The TikTok / CapCut read: heavy geometric sans, caps, white on a thick black\n // outline, yellow spoken word.\n outline: (fs) => ({\n fontFamily: \"Montserrat\",\n fontWeight: 900,\n uppercase: true,\n color: \"#ffffff\",\n strokeColor: \"#000000\",\n strokeWidth: autoStrokeWidth(fs),\n highlightColor: \"#FFE600\",\n }),\n // The pre-look lever set with the face pinned (it never was): per-style weight,\n // soft shadow only, no casing, no outline.\n clean: () => ({ fontFamily: \"Inter\", color: \"#ffffff\" }),\n}\n\n/**\n * Resolve a look + explicit overrides into concrete levers. An explicit lever\n * always wins over the look; `strokeWidth: 0` explicitly means \"no outline\".\n * The plan then carries concrete levers only — nothing to resolve at render.\n */\nexport function resolveCaptionLook(\n look: CaptionLookId | undefined,\n explicit: CaptionLookLevers,\n fontSize: number,\n): CaptionLookLevers {\n // COERCE, never throw. The route Zod rejects a bad `look`, but the orchestrator /\n // authored-JSON / import / Copilot paths write `look` straight onto node data with\n // no validation (payload-builder passes `look: data.look` verbatim — the CLAUDE.md\n // pitfall 5b class). An unknown id here would throw AFTER a paid transcription and\n // fail the whole run, so an out-of-vocabulary look falls back to the default preset.\n const preset = CAPTION_LOOKS[look ?? DEFAULT_CAPTION_LOOK] ?? CAPTION_LOOKS[DEFAULT_CAPTION_LOOK]\n const out: CaptionLookLevers = { ...preset(fontSize) }\n for (const k of Object.keys(explicit) as (keyof CaptionLookLevers)[]) {\n if (explicit[k] !== undefined) (out[k] as CaptionLookLevers[typeof k]) = explicit[k]\n }\n return out\n}\n\n/**\n * Resolve the concrete render levers for a caption, applying the DEFAULT look the\n * way each STYLE expects: an unset `look` means `outline` on a kinetic style (the\n * TikTok/CapCut read) and `clean` on the static `subtitle` (the plain read — a\n * pinned neutral sans, no outline, no casing). So a subtitle that routes to\n * Remotion never inherits the outline house-style unless asked, AND is never left\n * with no face at all (which renders as headless Chrome's default serif). A named\n * look always wins; explicit levers override either. SINGLE SOURCE for the worker\n * top-level levers, the per-segment resolver, and the frontend config/preview\n * mirror, so the per-style default can't drift between them.\n */\nexport function resolveCaptionLevers(\n style: string | undefined | null,\n look: CaptionLookId | undefined,\n explicit: CaptionLookLevers,\n fontSize: number,\n): CaptionLookLevers {\n const effective = look ?? (isKineticCaptionStyle(style) ? DEFAULT_CAPTION_LOOK : DEFAULT_SUBTITLE_LOOK)\n return resolveCaptionLook(effective, explicit, fontSize)\n}\n","export interface CaptionWordTiming {\n readonly text: string\n readonly startMs: number\n readonly endMs: number\n}\n\n/**\n * A caption plan: the opening line, where it ends, and the timed words that\n * follow it. Times and words only — no styling travels on a plan; whoever\n * renders it applies the look. Times are milliseconds from the video's start.\n */\n/** The opening line and the body's words, timed. No styling. */\nexport interface CaptionPlan {\n readonly v: 1\n /** The opening line as written; sent as is, never trimmed. */\n readonly hookText: string\n /** Where the opening line ends; the body starts here. */\n readonly hookEndMs: number\n /** Where the body captions end, any tail included (the producer decides it). */\n readonly bodyEndMs: number\n /** The body's words, in milliseconds. */\n readonly captions: readonly CaptionWordTiming[]\n /** When known, the opening line and the body are clamped to it. */\n readonly videoDurationMs?: number\n /** Primary language tag: \"en\", \"he\", … */\n readonly language?: string\n}\n\nconst nonNegative = (v: unknown): v is number => typeof v === \"number\" && Number.isFinite(v) && v >= 0\n\n/**\n * A wired caption plan (object or JSON string) → the plan, or the first problem\n * named as \"Caption plan: <issue>.\" Only the CaptionPlan fields are kept.\n */\nexport function parseCaptionPlan(raw: unknown): { plan: CaptionPlan } | { error: string } {\n let value: unknown = raw\n if (typeof raw === \"string\") {\n try { value = JSON.parse(raw) } catch { return { error: \"Caption plan: not valid JSON.\" } }\n }\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return { error: \"Caption plan: not an object.\" }\n const o = value as Record<string, unknown>\n if (o.v !== 1) return { error: \"Caption plan: v must be 1.\" }\n if (typeof o.hookText !== \"string\") return { error: \"Caption plan: hookText must be text.\" }\n for (const f of [\"hookEndMs\", \"bodyEndMs\"] as const) {\n if (!nonNegative(o[f])) return { error: `Caption plan: ${f} must be a non-negative number.` }\n }\n if (o.videoDurationMs !== undefined && !nonNegative(o.videoDurationMs)) {\n return { error: \"Caption plan: videoDurationMs must be a non-negative number.\" }\n }\n if (o.language !== undefined && typeof o.language !== \"string\") return { error: \"Caption plan: language must be text.\" }\n if (!Array.isArray(o.captions)) return { error: \"Caption plan: captions must be a list.\" }\n const captions: CaptionWordTiming[] = []\n for (let i = 0; i < o.captions.length; i++) {\n const c = o.captions[i] as Record<string, unknown> | null\n if (!c || typeof c !== \"object\" || typeof c.text !== \"string\" || !nonNegative(c.startMs) || !nonNegative(c.endMs)) {\n return { error: `Caption plan: captions[${i}] needs text, startMs and endMs.` }\n }\n if (c.endMs < c.startMs) return { error: `Caption plan: captions[${i}] ends before it starts.` }\n captions.push({ text: c.text, startMs: c.startMs, endMs: c.endMs })\n }\n return {\n plan: {\n v: 1,\n hookText: o.hookText,\n hookEndMs: o.hookEndMs as number,\n bodyEndMs: o.bodyEndMs as number,\n captions,\n ...(o.videoDurationMs !== undefined ? { videoDurationMs: o.videoDurationMs as number } : {}),\n ...(o.language !== undefined ? { language: o.language as string } : {}),\n },\n }\n}\n","/**\n * Canonical list of font display names supported by the Remotion renderer.\n *\n * Single source of truth shared by:\n * - the backend Zod schemas (`z.enum(SUPPORTED_FONT_NAMES)`), which CANNOT\n * import `@nodaro/remotion` (its font-registry pulls the render runtime +\n * `@remotion/google-fonts` side-effects into a validation path), and\n * - `packages/remotion/src/lib/font-registry.ts`, which loads each face and\n * is kept in lock-step with this tuple by a compile-time `satisfies` guard.\n *\n * Order/spelling MUST match the keys of the `fonts` object in font-registry.ts.\n */\nexport const SUPPORTED_FONT_NAMES = [\n \"Inter\",\n \"Roboto\",\n \"Open Sans\",\n \"Montserrat\",\n \"Poppins\",\n \"Raleway\",\n \"Nunito\",\n \"Lato\",\n \"Playfair Display\",\n \"Merriweather\",\n \"Lora\",\n \"EB Garamond\",\n \"Bebas Neue\",\n \"Oswald\",\n \"Anton\",\n \"Dancing Script\",\n \"Pacifico\",\n \"Caveat\",\n \"Roboto Mono\",\n \"Fira Code\",\n \"Rubik\",\n \"Heebo\",\n \"Cairo\",\n \"Tajawal\",\n] as const\n\nexport type SupportedFontName = (typeof SUPPORTED_FONT_NAMES)[number]\n","import { z } from \"zod\"\nimport {\n ALL_CAPTION_STYLES,\n CAPTION_LOOK_IDS,\n CAPTION_MAX_WORDS_PER_LINE_MAX,\n CAPTION_MAX_WORDS_PER_LINE_MIN,\n} from \"./caption-styles.js\"\nimport { SUPPORTED_FONT_NAMES } from \"./supported-fonts.js\"\n\n/**\n * The add-captions SEGMENT contract — one definition for the route's Zod, the\n * provider's overlap check and both workflow engines' pre-reservation check of a\n * caption plan's segments (a DAG payload never passes the route's validation).\n * Moved here from backend/src/routes/add-captions.ts so the copies can never differ.\n */\n\n/** Caption font weight: 100..900 on the 100 grid. */\nexport const captionFontWeightSchema = z.number().int().min(100).max(900).multipleOf(100)\n\n/** A text caption source must carry a visible glyph (whitespace synthesises to zero words). */\nexport const nonBlankCaptionText = z.string().min(1).refine((t) => /\\S/.test(t), { message: \"text must contain a non-whitespace character\" })\n\n/** One word-timed caption entry. */\nexport const captionInputSchema = z.object({\n text: z.string(),\n // startMs/endMs are the visibility window and drive the highlight; timestampMs\n // is the word timestamp used by tiktok-words token timing; confidence is\n // metadata, ignored by rendering. timestampMs/confidence default to null.\n startMs: z.number().min(0),\n endMs: z.number().min(0),\n timestampMs: z.number().min(0).nullable().default(null),\n confidence: z.number().min(0).max(1).nullable().default(null),\n})\n\n/**\n * One caption SEGMENT: a time range, optional levers (each inherits the top-level\n * value when omitted) and optional own words (`text` or `captions[]`; falls back\n * to the shared transcript filtered to the range). A segmented render is entirely\n * Remotion, so any `style` (incl. subtitle) and any look lever is valid on a segment.\n */\nexport const captionSegmentInputSchema = z.object({\n startMs: z.number().min(0),\n endMs: z.number().min(0),\n style: z.enum(ALL_CAPTION_STYLES).optional(),\n position: z.enum([\"bottom\", \"top\", \"center\"]).optional(),\n fontSize: z.number().min(12).max(200).optional(),\n color: z.string().optional(),\n backgroundColor: z.string().optional(),\n // A named look preset (outline/clean); explicit levers below override it.\n look: z.enum(CAPTION_LOOK_IDS).optional(),\n fontFamily: z.enum(SUPPORTED_FONT_NAMES).optional(),\n fontWeight: captionFontWeightSchema.optional(),\n strokeColor: z.string().optional(),\n strokeWidth: z.number().min(0).max(40).optional(),\n highlightColor: z.string().optional(),\n uppercase: z.boolean().optional(),\n positionY: z.number().min(0).max(100).optional(),\n animate: z.boolean().optional(),\n maxWordsPerLine: z.number().int().min(CAPTION_MAX_WORDS_PER_LINE_MIN).max(CAPTION_MAX_WORDS_PER_LINE_MAX).optional(),\n text: nonBlankCaptionText.optional(),\n captions: z.array(captionInputSchema).optional(),\n}).refine((s) => s.endMs > s.startMs, { message: \"segment endMs must be greater than startMs\" })\n\nexport type CaptionSegmentInput = z.infer<typeof captionSegmentInputSchema>\n\n/** Every field a segment may carry, in schema order. */\nexport const CAPTION_SEGMENT_SCHEMA_KEYS: readonly string[] = Object.keys(captionSegmentInputSchema.shape)\n\n/**\n * Segments must be sorted and non-overlapping. Returns the first offending pair\n * as the route's 400 text; null when none overlap (abutting is fine).\n * `startMs < endMs` per segment is enforced by the schema; this is the cross-segment rule.\n */\nexport function findSegmentOverlap(segments: readonly { startMs: number; endMs: number }[]): string | null {\n const sorted = [...segments].sort((a, b) => a.startMs - b.startMs)\n for (let i = 1; i < sorted.length; i++) {\n if (sorted[i]!.startMs < sorted[i - 1]!.endMs) {\n return `segments overlap: [${sorted[i - 1]!.startMs}, ${sorted[i - 1]!.endMs}) and [${sorted[i]!.startMs}, ${sorted[i]!.endMs})`\n }\n }\n return null\n}\n","/**\n * A caption line never starts or ends on a lone dash.\n *\n * A speech engine times a dash written between two spaces (\"Nodaro — every model\")\n * as a token of its own, and forced alignment keeps it. Inside a line the dash\n * reads as written; at a line's edge — the line breaks right after it, or the\n * next line opens with it — it reads as a stray mark. The display drops such a\n * token from the edge of the line it lands on; the words keep their own timings.\n *\n * One rule for every place that breaks captions into lines: the render's line\n * grouping (word-timed captions) and the wrap of a static text block.\n */\n\n/** Dash characters only: hyphen-minus, the Unicode hyphens and dashes (U+2010–U+2015), minus, the Hebrew maqaf, and their small/full-width forms. */\nconst BARE_DASH = /^[-‐-―−־﹘﹣-]+$/u\n\n/** True when the token, trimmed, is nothing but dash characters (\"—\", \"–\", \"-\"). A hyphenated word (\"ה-AI\", \"re-run\") is not. */\nexport function isBareDashToken(text: string): boolean {\n return BARE_DASH.test(text.trim())\n}\n\n/**\n * The items with every lone-dash token at either end removed (a copy; the input\n * is never mutated). A line holding nothing but dashes comes back empty — the\n * caller drops it rather than show it.\n */\nexport function trimEdgeDashTokens<T>(items: readonly T[], textOf: (item: T) => string): T[] {\n let start = 0\n let end = items.length\n while (start < end && isBareDashToken(textOf(items[start]!))) start++\n while (end > start && isBareDashToken(textOf(items[end - 1]!))) end--\n return items.slice(start, end)\n}\n","import { parseCaptionPlan, type CaptionPlan } from \"./caption-plan.js\"\nimport { captionSegmentInputSchema, findSegmentOverlap } from \"./caption-segment-schema.js\"\n\n/** The styling half, injected so this package never imports @nodaro/prompts (each engine passes hookPlateCaptionSegments). */\nexport interface CaptionPlanStyler {\n readonly segmentsFor: (\n plan: CaptionPlan,\n opts?: { bodyLevers?: Readonly<Record<string, unknown>> },\n ) => { segments: Record<string, unknown>[]; dropped: readonly string[] }\n readonly leverKeys: readonly string[]\n}\n\n/** The node's own caption levers (set, non-null) — the body's style. Undefined when it sets none (the helper then applies Body Captions). */\nexport function captionPlanBodyLevers(\n nodeData: Readonly<Record<string, unknown>>,\n leverKeys: readonly string[],\n): Record<string, unknown> | undefined {\n const levers: Record<string, unknown> = {}\n for (const k of leverKeys) {\n const v = nodeData[k]\n if (v !== undefined && v !== null) levers[k] = v\n }\n return Object.keys(levers).length > 0 ? levers : undefined\n}\n\n/**\n * A wired caption plan → the timed segments of ONE add-captions request, checked\n * with the route's own segment schema and overlap rule (a DAG payload never\n * passes the route, so both engines check here, before any reservation). The\n * plate is always Hook Plate plus the plan's language levers; the body is the\n * node's own style (the helper's rules, SP7 §4.6.3). `segments: []` = no\n * captions — the caller passes the video through.\n */\nexport function styleCaptionPlan(\n raw: unknown,\n nodeData: Readonly<Record<string, unknown>>,\n styler: CaptionPlanStyler,\n): { segments: Record<string, unknown>[] } | { error: string } {\n const parsed = parseCaptionPlan(raw)\n if (\"error\" in parsed) return { error: parsed.error }\n const bodyLevers = captionPlanBodyLevers(nodeData, styler.leverKeys)\n const styled = styler.segmentsFor(parsed.plan, bodyLevers ? { bodyLevers } : undefined).segments\n // The PARSED segments go on, never the helper's raw ones: the route's schema\n // fills each word entry's defaults (`timestampMs` / `confidence` → null), and a\n // DAG payload never passes the route, so returning the raw list sent a server\n // run word entries the add-captions route itself would have completed.\n const segments: Record<string, unknown>[] = []\n for (let i = 0; i < styled.length; i++) {\n const r = captionSegmentInputSchema.safeParse(styled[i])\n if (!r.success) return { error: `Caption plan: segment ${i + 1}: ${r.error.issues[0]?.message ?? \"invalid\"}.` }\n segments.push(r.data)\n }\n const overlap = findSegmentOverlap(segments as { startMs: number; endMs: number }[])\n if (overlap) return { error: `Caption plan: ${overlap}.` }\n return { segments }\n}\n"]}
|