@nodaro/shared 3.64.0 → 3.65.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.
Files changed (205) hide show
  1. package/dist/{chunk-PJJAZQVZ.js → chunk-222QM7CO.js} +3 -3
  2. package/dist/{chunk-PJJAZQVZ.js.map → chunk-222QM7CO.js.map} +1 -1
  3. package/dist/chunk-27HA6YOL.cjs +377 -0
  4. package/dist/chunk-27HA6YOL.cjs.map +1 -0
  5. package/dist/{chunk-TTGZ2L3O.js → chunk-2NKF476Z.js} +3 -3
  6. package/dist/{chunk-TTGZ2L3O.js.map → chunk-2NKF476Z.js.map} +1 -1
  7. package/dist/chunk-3AU52TSW.js +143 -0
  8. package/dist/chunk-3AU52TSW.js.map +1 -0
  9. package/dist/{chunk-7AJGUI7L.cjs → chunk-5NVGKXJV.cjs} +34 -17
  10. package/dist/chunk-5NVGKXJV.cjs.map +1 -0
  11. package/dist/{chunk-3AYM47GW.js → chunk-5SSMPYE5.js} +99 -9
  12. package/dist/chunk-5SSMPYE5.js.map +1 -0
  13. package/dist/{chunk-KHH54GRP.cjs → chunk-6ET3KDO4.cjs} +15 -338
  14. package/dist/chunk-6ET3KDO4.cjs.map +1 -0
  15. package/dist/{chunk-ACZZHHFZ.cjs → chunk-6OSIOVF7.cjs} +44 -22
  16. package/dist/chunk-6OSIOVF7.cjs.map +1 -0
  17. package/dist/{chunk-OBOOHG3N.js → chunk-6X5PBAC4.js} +3 -3
  18. package/dist/{chunk-OBOOHG3N.js.map → chunk-6X5PBAC4.js.map} +1 -1
  19. package/dist/chunk-7BN4EDIC.cjs +185 -0
  20. package/dist/chunk-7BN4EDIC.cjs.map +1 -0
  21. package/dist/{chunk-IYSOVS7O.js → chunk-7OWXHW7Z.js} +31 -13
  22. package/dist/chunk-7OWXHW7Z.js.map +1 -0
  23. package/dist/{chunk-ZI3QDUHO.js → chunk-AT53ZQUC.js} +3 -3
  24. package/dist/{chunk-ZI3QDUHO.js.map → chunk-AT53ZQUC.js.map} +1 -1
  25. package/dist/{chunk-SHH2T4CR.js → chunk-BSTAAGLY.js} +3 -3
  26. package/dist/{chunk-SHH2T4CR.js.map → chunk-BSTAAGLY.js.map} +1 -1
  27. package/dist/{chunk-DZ4IOP3Q.js → chunk-CW6MMQNO.js} +277 -3
  28. package/dist/chunk-CW6MMQNO.js.map +1 -0
  29. package/dist/{chunk-Q2Y4JHF7.js → chunk-D5Y3EYRM.js} +5 -5
  30. package/dist/{chunk-Q2Y4JHF7.js.map → chunk-D5Y3EYRM.js.map} +1 -1
  31. package/dist/{chunk-EXEVT6D2.cjs → chunk-DQ2PARNH.cjs} +5 -5
  32. package/dist/{chunk-EXEVT6D2.cjs.map → chunk-DQ2PARNH.cjs.map} +1 -1
  33. package/dist/{chunk-OOZW2MM6.cjs → chunk-E66HSC2E.cjs} +9 -9
  34. package/dist/{chunk-OOZW2MM6.cjs.map → chunk-E66HSC2E.cjs.map} +1 -1
  35. package/dist/{chunk-NIAFR5EE.js → chunk-FGBGKBML.js} +32 -3
  36. package/dist/chunk-FGBGKBML.js.map +1 -0
  37. package/dist/{chunk-5OBTGNUQ.cjs → chunk-FI3HJZWM.cjs} +294 -2
  38. package/dist/chunk-FI3HJZWM.cjs.map +1 -0
  39. package/dist/{chunk-SPAHI7DY.cjs → chunk-FJZTQTF4.cjs} +4 -4
  40. package/dist/{chunk-SPAHI7DY.cjs.map → chunk-FJZTQTF4.cjs.map} +1 -1
  41. package/dist/{chunk-J6B7J73J.cjs → chunk-GJ3D5X4X.cjs} +49 -49
  42. package/dist/{chunk-J6B7J73J.cjs.map → chunk-GJ3D5X4X.cjs.map} +1 -1
  43. package/dist/{chunk-KB2SQAR3.js → chunk-H745DQ6V.js} +3 -3
  44. package/dist/{chunk-KB2SQAR3.js.map → chunk-H745DQ6V.js.map} +1 -1
  45. package/dist/{chunk-7KQ6W5DS.js → chunk-HAH2F7LT.js} +4 -4
  46. package/dist/{chunk-7KQ6W5DS.js.map → chunk-HAH2F7LT.js.map} +1 -1
  47. package/dist/{chunk-HDPJNNMF.cjs → chunk-JQMFJAYU.cjs} +21 -21
  48. package/dist/{chunk-HDPJNNMF.cjs.map → chunk-JQMFJAYU.cjs.map} +1 -1
  49. package/dist/{chunk-D4KWNDPH.cjs → chunk-JYU5EIRM.cjs} +12 -12
  50. package/dist/{chunk-D4KWNDPH.cjs.map → chunk-JYU5EIRM.cjs.map} +1 -1
  51. package/dist/{chunk-AZNZ5WNZ.cjs → chunk-K6RIN3LW.cjs} +142 -45
  52. package/dist/chunk-K6RIN3LW.cjs.map +1 -0
  53. package/dist/{chunk-YQV53HRR.cjs → chunk-KTCEKGBJ.cjs} +7 -7
  54. package/dist/{chunk-YQV53HRR.cjs.map → chunk-KTCEKGBJ.cjs.map} +1 -1
  55. package/dist/{chunk-W6VJAUGM.cjs → chunk-KWYS4IIM.cjs} +83 -37
  56. package/dist/chunk-KWYS4IIM.cjs.map +1 -0
  57. package/dist/{chunk-GTWUS6MQ.cjs → chunk-MIT2USTS.cjs} +61 -61
  58. package/dist/{chunk-GTWUS6MQ.cjs.map → chunk-MIT2USTS.cjs.map} +1 -1
  59. package/dist/{chunk-Y4GCJJPF.cjs → chunk-NYZQOIXJ.cjs} +35 -2
  60. package/dist/chunk-NYZQOIXJ.cjs.map +1 -0
  61. package/dist/{chunk-FHGRKQVZ.cjs → chunk-PGDR7CO3.cjs} +8 -8
  62. package/dist/{chunk-FHGRKQVZ.cjs.map → chunk-PGDR7CO3.cjs.map} +1 -1
  63. package/dist/{chunk-W7KHHNZR.js → chunk-PL7AQQV7.js} +53 -9
  64. package/dist/chunk-PL7AQQV7.js.map +1 -0
  65. package/dist/chunk-Q4YOLT4M.js +164 -0
  66. package/dist/chunk-Q4YOLT4M.js.map +1 -0
  67. package/dist/{chunk-CHS2SIP6.cjs → chunk-R5ILCNCC.cjs} +90 -76
  68. package/dist/chunk-R5ILCNCC.cjs.map +1 -0
  69. package/dist/chunk-RP4KQUNU.cjs +168 -0
  70. package/dist/chunk-RP4KQUNU.cjs.map +1 -0
  71. package/dist/{chunk-CHTZZRAL.cjs → chunk-SPU7MUWE.cjs} +6 -6
  72. package/dist/{chunk-CHTZZRAL.cjs.map → chunk-SPU7MUWE.cjs.map} +1 -1
  73. package/dist/{chunk-VPTA4Z7G.js → chunk-ST7OBB5J.js} +5 -5
  74. package/dist/{chunk-VPTA4Z7G.js.map → chunk-ST7OBB5J.js.map} +1 -1
  75. package/dist/{chunk-TPQJKS7D.js → chunk-V5NLQ4L5.js} +21 -7
  76. package/dist/{chunk-CHS2SIP6.cjs.map → chunk-V5NLQ4L5.js.map} +1 -1
  77. package/dist/{chunk-QYU7J5EQ.js → chunk-V6OXSXIX.js} +29 -18
  78. package/dist/chunk-V6OXSXIX.js.map +1 -0
  79. package/dist/{chunk-T2OVDF2M.cjs → chunk-WQMPIURW.cjs} +6 -6
  80. package/dist/{chunk-T2OVDF2M.cjs.map → chunk-WQMPIURW.cjs.map} +1 -1
  81. package/dist/{chunk-67CMMTLN.cjs → chunk-WZG6GZIL.cjs} +4 -4
  82. package/dist/{chunk-67CMMTLN.cjs.map → chunk-WZG6GZIL.cjs.map} +1 -1
  83. package/dist/{chunk-36VWLB4J.js → chunk-XJANKTIL.js} +3 -3
  84. package/dist/{chunk-36VWLB4J.js.map → chunk-XJANKTIL.js.map} +1 -1
  85. package/dist/{chunk-O7RZRUMZ.js → chunk-XJWED257.js} +14 -309
  86. package/dist/chunk-XJWED257.js.map +1 -0
  87. package/dist/chunk-XSSLNINL.js +346 -0
  88. package/dist/chunk-XSSLNINL.js.map +1 -0
  89. package/dist/{chunk-O4RPXBDZ.cjs → chunk-YD4XY74W.cjs} +8 -8
  90. package/dist/{chunk-O4RPXBDZ.cjs.map → chunk-YD4XY74W.cjs.map} +1 -1
  91. package/dist/{chunk-SXHHLZ22.js → chunk-YMZUE2IX.js} +9 -9
  92. package/dist/{chunk-SXHHLZ22.js.map → chunk-YMZUE2IX.js.map} +1 -1
  93. package/dist/{chunk-4IUE2JB7.js → chunk-Z77M7Q2R.js} +3 -3
  94. package/dist/{chunk-4IUE2JB7.js.map → chunk-Z77M7Q2R.js.map} +1 -1
  95. package/dist/{chunk-3KTWYYCN.js → chunk-ZSRXY5YT.js} +3 -3
  96. package/dist/{chunk-3KTWYYCN.js.map → chunk-ZSRXY5YT.js.map} +1 -1
  97. package/dist/entries/apps.cjs +42 -42
  98. package/dist/entries/apps.js +7 -7
  99. package/dist/entries/captions.d.cts +1 -1
  100. package/dist/entries/captions.d.ts +1 -1
  101. package/dist/entries/credits.cjs +230 -214
  102. package/dist/entries/credits.d.cts +51 -14
  103. package/dist/entries/credits.d.ts +51 -14
  104. package/dist/entries/credits.js +10 -10
  105. package/dist/entries/entities.cjs +202 -193
  106. package/dist/entries/entities.d.cts +44 -9
  107. package/dist/entries/entities.d.ts +44 -9
  108. package/dist/entries/entities.js +2 -1
  109. package/dist/entries/llm-models.cjs +86 -62
  110. package/dist/entries/llm-models.d.cts +46 -15
  111. package/dist/entries/llm-models.d.ts +46 -15
  112. package/dist/entries/llm-models.js +2 -2
  113. package/dist/entries/media.cjs +79 -63
  114. package/dist/entries/media.d.cts +154 -1
  115. package/dist/entries/media.d.ts +154 -1
  116. package/dist/entries/media.js +1 -1
  117. package/dist/entries/model-catalog.cjs +175 -119
  118. package/dist/entries/model-catalog.d.cts +4 -54
  119. package/dist/entries/model-catalog.d.ts +4 -54
  120. package/dist/entries/model-catalog.js +4 -4
  121. package/dist/entries/models.cjs +491 -358
  122. package/dist/entries/models.d.cts +86 -7
  123. package/dist/entries/models.d.ts +86 -7
  124. package/dist/entries/models.js +6 -5
  125. package/dist/entries/nodes.cjs +212 -212
  126. package/dist/entries/nodes.d.cts +1 -1
  127. package/dist/entries/nodes.d.ts +1 -1
  128. package/dist/entries/nodes.js +8 -8
  129. package/dist/entries/pipeline.cjs +153 -153
  130. package/dist/entries/pipeline.d.cts +3 -3
  131. package/dist/entries/pipeline.d.ts +3 -3
  132. package/dist/entries/pipeline.js +3 -3
  133. package/dist/entries/social.cjs +177 -177
  134. package/dist/entries/social.js +2 -2
  135. package/dist/entries/ugc.cjs +71 -71
  136. package/dist/entries/ugc.js +4 -4
  137. package/dist/entries/video.cjs +174 -145
  138. package/dist/entries/video.d.cts +114 -2
  139. package/dist/entries/video.d.ts +114 -2
  140. package/dist/entries/video.js +7 -6
  141. package/dist/entries/workflow.d.cts +1 -1
  142. package/dist/entries/workflow.d.ts +1 -1
  143. package/dist/index.cjs +2074 -1793
  144. package/dist/index.d.cts +10 -9
  145. package/dist/index.d.ts +10 -9
  146. package/dist/index.js +24 -23
  147. package/dist/{model-catalog-Cf9fkEUp.d.ts → model-catalog-BoUKGFNl.d.cts} +167 -1
  148. package/dist/{model-catalog-Cf9fkEUp.d.cts → model-catalog-BoUKGFNl.d.ts} +167 -1
  149. package/dist/{model-constants-BxjiWVQ9.d.ts → model-constants-BElS3AeE.d.ts} +55 -6
  150. package/dist/{model-constants-C_Nyft_i.d.cts → model-constants-CpQz1bGa.d.cts} +55 -6
  151. package/dist/tts-capabilities-BtnDWK9K.d.ts +133 -0
  152. package/dist/tts-capabilities-C52UccTI.d.cts +133 -0
  153. package/package.json +1 -1
  154. package/src/__tests__/dialogue-capabilities.test.ts +167 -6
  155. package/src/__tests__/extend-providers.test.ts +87 -0
  156. package/src/__tests__/kling4-catalog.test.ts +1 -1
  157. package/src/__tests__/llm-models.test.ts +41 -4
  158. package/src/__tests__/speech-pricing.test.ts +62 -1
  159. package/src/__tests__/tts-capabilities.test.ts +160 -4
  160. package/src/__tests__/video-analysis-pricing.test.ts +13 -1
  161. package/src/__tests__/video-subjects.test.ts +192 -0
  162. package/src/__tests__/wired-character-names.test.ts +142 -0
  163. package/src/credit-estimators/index.ts +4 -0
  164. package/src/credit-estimators/speech.ts +57 -9
  165. package/src/credit-identifiers.ts +48 -13
  166. package/src/dialogue-capabilities.ts +220 -3
  167. package/src/dubbing-structure.ts +186 -0
  168. package/src/entries/entities.ts +2 -0
  169. package/src/entries/llm-models.ts +7 -0
  170. package/src/entries/media.ts +3 -1
  171. package/src/entries/model-catalog.ts +17 -0
  172. package/src/entries/models.ts +39 -0
  173. package/src/entries/video.ts +8 -1
  174. package/src/gemini-tts.ts +144 -0
  175. package/src/llm-models.ts +71 -21
  176. package/src/model-catalog.ts +259 -0
  177. package/src/model-constants.ts +101 -8
  178. package/src/tts-capabilities.ts +193 -1
  179. package/src/video-analysis-pricing.ts +11 -0
  180. package/src/video-character-refs.ts +160 -3
  181. package/src/wired-character-names.ts +134 -18
  182. package/src/wired-character-video-subjects.ts +63 -0
  183. package/dist/chunk-3AYM47GW.js.map +0 -1
  184. package/dist/chunk-5OBTGNUQ.cjs.map +0 -1
  185. package/dist/chunk-6YIV37V7.js +0 -31
  186. package/dist/chunk-6YIV37V7.js.map +0 -1
  187. package/dist/chunk-7AJGUI7L.cjs.map +0 -1
  188. package/dist/chunk-ACZZHHFZ.cjs.map +0 -1
  189. package/dist/chunk-AZNZ5WNZ.cjs.map +0 -1
  190. package/dist/chunk-DZ4IOP3Q.js.map +0 -1
  191. package/dist/chunk-IYSOVS7O.js.map +0 -1
  192. package/dist/chunk-KHH54GRP.cjs.map +0 -1
  193. package/dist/chunk-NIAFR5EE.js.map +0 -1
  194. package/dist/chunk-O7RZRUMZ.js.map +0 -1
  195. package/dist/chunk-QYU7J5EQ.js.map +0 -1
  196. package/dist/chunk-S3UGLZSF.js +0 -42
  197. package/dist/chunk-S3UGLZSF.js.map +0 -1
  198. package/dist/chunk-TPQJKS7D.js.map +0 -1
  199. package/dist/chunk-TQW3R44P.cjs +0 -38
  200. package/dist/chunk-TQW3R44P.cjs.map +0 -1
  201. package/dist/chunk-VZ6TE23U.cjs +0 -54
  202. package/dist/chunk-VZ6TE23U.cjs.map +0 -1
  203. package/dist/chunk-W6VJAUGM.cjs.map +0 -1
  204. package/dist/chunk-W7KHHNZR.js.map +0 -1
  205. package/dist/chunk-Y4GCJJPF.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/video-character-refs.ts","../src/wired-character-video-subjects.ts","../src/video-overlay-geometry.ts","../src/video-overlay-layout-ids.ts","../src/video-overlay-validate.ts","../src/video-overlay-layouts.ts","../src/video-analysis.ts","../src/video-output-canvas.ts","../src/video-frame-fit.ts"],"names":["used","evenFloor","even"],"mappings":";;;;;;;;AA+DO,IAAM,gCAAgC,IAAA,CAAK,GAAA;AAAA,EAChD,CAAA;AAAA,EACA,GAAG,MAAA,CAAO,MAAA,CAAO,4BAA4B,CAAA,CAAE,IAAI,CAAC,CAAA,KAAM,CAAA,EAAG,UAAA,IAAc,CAAC;AAC9E;AAGO,IAAM,gCAAA,GAAmC;AAGzC,IAAM,+BAAA,GAAkC;AACxC,IAAM,wBAAA,GAA2B;AAIjC,IAAM,qCAAA,GAAwC;AAC9C,IAAM,iCAAA,GAAoC;AAG1C,SAAS,qBAAqB,QAAA,EAAsC;AACzE,EAAA,OAAO,QAAA,GAAY,4BAAA,CAA6B,QAAQ,CAAA,EAAG,cAAc,CAAA,GAAK,CAAA;AAChF;AAGO,SAAS,uBAAuB,QAAA,EAAsC;AAC3E,EAAA,OAAO,QAAA,GAAY,4BAAA,CAA6B,QAAQ,CAAA,EAAG,mBAAmB,CAAA,GAAK,CAAA;AACrF;AAGO,SAAS,4BAAA,GAAyC;AACvD,EAAA,OAAO,MAAA,CAAO,QAAQ,4BAA4B,CAAA,CAC/C,OAAO,CAAC,GAAG,CAAC,CAAA,KAAA,CAAO,GAAG,eAAA,IAAmB,CAAA,IAAK,CAAC,CAAA,CAC/C,GAAA,CAAI,CAAC,CAAC,EAAE,MAAM,EAAE,CAAA;AACrB;AAGO,SAAS,mBACd,mBAAA,EACU;AACV,EAAA,MAAM,MAAgB,EAAC;AACvB,EAAA,KAAA,MAAW,CAAA,IAAK,mBAAA,IAAuB,EAAC,EAAG;AACzC,IAAA,MAAM,MAAO,CAAA,EAAiD,QAAA;AAC9D,IAAA,IAAI,OAAO,GAAA,K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AAO,KAAA;AAAA,IACd,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,GAAI,IAAA,GAAO,EAAE,IAAA,KAAS,EAAC;AAAA,IACvB,MAAA,EAAQ,SAAS,YAAA,GAAe;AAAA,GAClC;AACF;AAQO,SAAS,qBAAqB,IAAA,EAIF;AACjC,EAAA,MAAM,SAAA,GAAY,KAAK,SAAA,IAAa,sBAAA;AACpC,EAAA,MAAM,MAAA,GAAS,SAAA,KAAc,MAAA,GACxB,IAAA,CAAK,QAAA,GAAW,2BAA2B,IAAA,CAAK,QAAQ,CAAA,IAAK,OAAA,GAAU,OAAA,GACxE,SAAA;AACJ,EAAA,IAAI,MAAA,KAAW,WAAA,IAAe,CAAC,IAAA,CAAK,yBAAyB,OAAO,OAAA;AACpE,EAAA,OAAO,MAAA;AACT","file":"chunk-5SSMPYE5.js","sourcesContent":["import { VIDEO_REF_LIMITS_BY_PROVIDER } from \"./model-constants.js\"\nimport type { ConnectedReference } from \"./types.js\"\nimport type { GeminiOmniVoicePresetId } from \"./gemini-omni-voices.js\"\n\n/**\n * Character references — the dedicated IDENTITY input of a video model, as\n * opposed to a loose reference image.\n *\n * Gemini Omni treats `image_urls` as \"reference images for characters, scenes,\n * styles, or storyboard guidance\": a portrait sent there steers the clip but\n * the face drifts. Its separate `character_ids` input is the one that keeps a\n * real person's face, and it takes ids minted from a portrait by a create\n * call. The PUBLIC shape below is provider-neutral — a portrait and a\n * description — and the provider layer mints (and caches) whatever ids its\n * upstream needs. Nothing upstream-shaped ever appears in the API.\n *\n * WHICH models take them is data, never a name list: a positive `characters`\n * cap on `VIDEO_REF_LIMITS_BY_PROVIDER`.\n */\nexport interface VideoCharacterVoice {\n /** The base voice — one of `GEMINI_OMNI_VOICE_PRESETS`. */\n preset: GeminiOmniVoicePresetId\n /** Free-text timbre / pace / emotion for the persona. Optional. */\n description?: string\n /** One example line the persona says (≤ 120 chars). Optional. */\n exampleLine?: string\n}\n\nexport interface VideoCharacterReference {\n /** Portrait of the person (public URL). Index 0 of the upstream image set. */\n imageUrl: string\n /** Optional full-body image; costs a second input unit. */\n bodyImageUrl?: string\n /**\n * More views of the same person, after the portrait and body image. Read by\n * models whose subject takes several images (Kling 4.0: 2-4 per subject, the\n * portrait first); ignored elsewhere. At most\n * {@link VIDEO_CHARACTER_EXTRA_IMAGES_MAX}.\n */\n extraImageUrls?: string[]\n /** Who this is: appearance, identity, style, clothing. Required by the upstream. */\n description: string\n /** Optional display name. */\n name?: string\n /**\n * Pin a voice persona to this character so it keeps ONE voice across clips\n * (the model otherwise improvises a voice per generation). Only models with a\n * positive `voices` cap take it.\n */\n voice?: VideoCharacterVoice\n /**\n * A short single-shot clip of this character (public URL). On a model with a\n * positive `videoCharacters` cap (Kling 4.0, Kling 4.0 Flash) the character\n * becomes a VIDEO subject made from this clip instead of an image subject.\n * The clip rides as one more reference video ({@link seatCharacterVideos}),\n * so it is measured, capped and priced exactly as a reference video is; its\n * own length must fit `VIDEO_CHARACTER_CLIP_DURATION_LIMITS`. Any other model\n * refuses it.\n */\n videoUrl?: string\n}\n\n/** Zod `.max()` ceiling for the wire field — the widest cap any provider declares. */\nexport const VIDEO_CHARACTER_REFS_WIRE_MAX = Math.max(\n 0,\n ...Object.values(VIDEO_REF_LIMITS_BY_PROVIDER).map((l) => l?.characters ?? 0),\n)\n\n/** Most `extraImageUrls` a character reference may carry (Kling 4.0's subject takes 4 images: the portrait + 3). */\nexport const VIDEO_CHARACTER_EXTRA_IMAGES_MAX = 3\n\n/** Longest `description` / `name` a client may send (route Zod reads these). */\nexport const VIDEO_CHARACTER_DESCRIPTION_MAX = 2000\nexport const VIDEO_CHARACTER_NAME_MAX = 100\n/** Longest voice `description` / `exampleLine` a client may send. The upstream\n * allows far more description (20000); we cap the PUBLIC field at the same\n * ceiling as a character description so policy text and prompts stay bounded. */\nexport const VIDEO_CHARACTER_VOICE_DESCRIPTION_MAX = 2000\nexport const VIDEO_CHARACTER_VOICE_EXAMPLE_MAX = 120\n\n/** How many character references the provider takes; 0 = none (or unknown). */\nexport function videoCharacterRefCap(provider: string | undefined): number {\n return provider ? (VIDEO_REF_LIMITS_BY_PROVIDER[provider]?.characters ?? 0) : 0\n}\n\n/** How many characters may be VIDEO subjects (a `videoUrl` clip) on the provider; 0 = none. */\nexport function videoCharacterVideoCap(provider: string | undefined): number {\n return provider ? (VIDEO_REF_LIMITS_BY_PROVIDER[provider]?.videoCharacters ?? 0) : 0\n}\n\n/** Every provider that takes video subjects, in declaration order. */\nexport function videoCharacterVideoProviders(): string[] {\n return Object.entries(VIDEO_REF_LIMITS_BY_PROVIDER)\n .filter(([, l]) => (l?.videoCharacters ?? 0) > 0)\n .map(([id]) => id)\n}\n\n/** The clips a set of character references carries (`videoUrl`, trimmed, non-empty), in order. */\nexport function characterVideoUrls(\n characterReferences: readonly unknown[] | undefined,\n): string[] {\n const out: string[] = []\n for (const c of characterReferences ?? []) {\n const url = (c as { videoUrl?: unknown } | null | undefined)?.videoUrl\n if (typeof url === \"string\" && url.trim()) out.push(url.trim())\n }\n return out\n}\n\n/**\n * Whether the provider bills a character's video subject as reference-video\n * seconds (`videoCharactersBillAsReferenceVideo`: Kling 4.0). On any other\n * model that takes video subjects (Kling 4.0 Flash, measured, decided\n * 2026-11-14) the subject is priced like an image subject.\n */\nexport function videoCharacterClipsBilledAsReferenceVideo(provider: string | undefined): boolean {\n return provider ? VIDEO_REF_LIMITS_BY_PROVIDER[provider]?.videoCharactersBillAsReferenceVideo === true : false\n}\n\n/**\n * The reference videos a run is PRICED on: `referenceVideoUrls` as sent, less\n * — on a model that does not bill video subjects as reference video\n * ({@link videoCharacterClipsBilledAsReferenceVideo}) — the seats that are a\n * character's clip. Those seats still count toward the model's video cap and\n * the reference videos' total length (`seatCharacterVideos`, the duration\n * check); they only leave the price. The same value when nothing leaves it.\n * Every price path reads it: the routes' credit guard and `POST /v1/quote`,\n * the workflow reservation, the estimates and the completion settlement.\n */\nexport function pricedReferenceVideoUrls(args: {\n provider: string | undefined\n referenceVideoUrls: readonly unknown[] | undefined\n characterReferences: readonly unknown[] | undefined\n}): readonly unknown[] | undefined {\n if (videoCharacterClipsBilledAsReferenceVideo(args.provider)) return args.referenceVideoUrls\n const clips = new Set(characterVideoUrls(args.characterReferences))\n if (clips.size === 0 || !args.referenceVideoUrls?.some((u) => typeof u === \"string\" && clips.has(u))) return args.referenceVideoUrls\n return args.referenceVideoUrls.filter((u) => !(typeof u === \"string\" && clips.has(u)))\n}\n\n/** A refusal from {@link seatCharacterVideos}: a finished, user-facing sentence. */\nexport interface CharacterVideoSeatProblem {\n code: \"character_video_unsupported\" | \"character_videos_over_limit\" | \"character_video_shared\" | \"reference_videos_over_limit\"\n message: string\n}\n\n/**\n * The reference-video list a run sends once its characters' clips are seated\n * in it — the ONE rule both video routes (a precheck, before the duration\n * check, the quote and any reservation) and the workflow run (the payload\n * builder) apply, so a video subject's clip is measured, capped, priced, held\n * and settled exactly as a reference video is (KIE bills video subjects as\n * reference-video seconds, summed). The provider runner then takes the seat\n * back out of the reference videos and sends it as the character's subject.\n *\n * - No clip: the list as it came (the same value).\n * - A clip already in the list (also wired as a plain reference video) keeps\n * its seat, and becomes the subject only; any other is appended, in\n * character order, after the reference videos.\n * - Refused: a model that takes no video subjects; more clips than its\n * `videoCharacters` cap; two characters with the same clip; reference\n * videos plus clips over its `videos` cap (the provider counts both in one\n * cap, and a clip past it would be neither measured nor sent).\n * - On a model that takes video subjects (one shared cap), plain reference\n * videos alone over that cap are refused too, instead of the extra ones\n * being left out without a word (decided 2026-11-13). Any other model's\n * list is not judged here.\n */\nexport function seatCharacterVideos(args: {\n provider: string | undefined\n referenceVideoUrls: readonly unknown[] | undefined\n characterReferences: readonly unknown[] | undefined\n}):\n | { ok: true; referenceVideoUrls: readonly unknown[] | undefined }\n | ({ ok: false } & CharacterVideoSeatProblem) {\n const clips = characterVideoUrls(args.characterReferences)\n const provider = args.provider ?? \"the selected model\"\n const cap = videoCharacterVideoCap(args.provider)\n const videosCap = VIDEO_REF_LIMITS_BY_PROVIDER[args.provider as string]?.videos ?? 0\n const overVideos = (count: number): { ok: false } & CharacterVideoSeatProblem => ({\n ok: false,\n code: \"reference_videos_over_limit\",\n message:\n `${provider} takes at most ${videosCap} videos in all — reference videos and characters made from a video together. ` +\n `This run has ${count}. Remove a reference video${clips.length > 0 ? \", or the video from a character\" : \"\"}.`,\n })\n if (clips.length === 0) {\n const sent = (args.referenceVideoUrls ?? []).length\n if (cap > 0 && sent > videosCap) return overVideos(sent)\n return { ok: true, referenceVideoUrls: args.referenceVideoUrls }\n }\n if (cap === 0) {\n const takers = videoCharacterVideoProviders()\n return {\n ok: false,\n code: \"character_video_unsupported\",\n message:\n `A character video (characterReferences[].videoUrl) is not supported by ${provider}. ` +\n `Models that take one: ${takers.join(\", \")}. Otherwise drop the video and keep the character's images.`,\n }\n }\n if (clips.length > cap) {\n return {\n ok: false,\n code: \"character_videos_over_limit\",\n message: `${provider} takes at most ${cap} characters made from a video; ${clips.length} characters carry one. Remove the video from some of them.`,\n }\n }\n if (new Set(clips).size < clips.length) {\n return {\n ok: false,\n code: \"character_video_shared\",\n message: \"Two characters carry the same video. Each character made from a video needs a clip of its own.\",\n }\n }\n // The list as sent stays as it is (an entry the route's schema would refuse\n // is still there for it to refuse); the clips follow it.\n const raw = args.referenceVideoUrls ?? []\n const seated: unknown[] = [...raw, ...clips.filter((c) => !raw.includes(c))]\n if (seated.length > videosCap) return overVideos(seated.length)\n return { ok: true, referenceVideoUrls: seated }\n}\n\n/** How many DISTINCT voice personas the provider takes per request; 0 = none. */\nexport function videoCharacterVoiceCap(provider: string | undefined): number {\n return provider ? (VIDEO_REF_LIMITS_BY_PROVIDER[provider]?.voices ?? 0) : 0\n}\n\n/**\n * Identity of a voice persona — what makes two voices \"the same voice\". The\n * persona is minted per (preset, description, example line) AND the character's\n * name (the label it is created under), so the name is part of the identity:\n * this count must equal the number of personas the provider will actually mint,\n * or the cap would be checked against a different number than what ships.\n */\nexport function videoCharacterVoiceKey(ref: Pick<VideoCharacterReference, \"voice\" | \"name\">): string | null {\n const voice = ref.voice\n if (!voice) return null\n return JSON.stringify([voice.preset, voice.description?.trim() ?? \"\", voice.exampleLine?.trim() ?? \"\", ref.name?.trim() ?? \"\"])\n}\n\n/** How many distinct voice personas a set of references asks for. */\nexport function videoCharacterDistinctVoices(\n characterReferences: readonly Pick<VideoCharacterReference, \"voice\" | \"name\">[] | undefined,\n): number {\n const keys = new Set<string>()\n for (const c of characterReferences ?? []) {\n const key = videoCharacterVoiceKey(c)\n if (key) keys.add(key)\n }\n return keys.size\n}\n\n/** Every provider that declares a character-reference cap, in declaration order. */\nexport function videoCharacterRefProviders(): string[] {\n return Object.entries(VIDEO_REF_LIMITS_BY_PROVIDER)\n .filter(([, l]) => (l?.characters ?? 0) > 0)\n .map(([id]) => id)\n}\n\n/**\n * Input units a set of character references draws from the provider's shared\n * input budget: 1 per character, 2 when a body image is supplied (the upstream\n * counts a dual-image character as two slots).\n */\nexport function videoCharacterRefUnits(\n characterReferences: readonly Pick<VideoCharacterReference, \"bodyImageUrl\">[] | undefined,\n): number {\n let units = 0\n for (const c of characterReferences ?? []) units += c.bodyImageUrl ? 2 : 1\n return units\n}\n\nexport interface VideoCharacterRefProblem {\n code:\n | \"character_references_unsupported\"\n | \"character_references_over_limit\"\n | \"character_references_with_start_frame\"\n | \"character_references_with_end_frame\"\n | \"character_references_quota\"\n | \"character_voice_unsupported\"\n | \"character_voices_over_limit\"\n message: string\n}\n\n/**\n * Voice-persona rule: the provider must take voices at all, and the DISTINCT\n * voices must fit its cap (Gemini Omni: 3 `audio_ids` per task). Two characters\n * with an identical voice AND name count once. `cap` overrides the provider's declared cap\n * (tests; a future model with a different limit declares it as data instead).\n */\nexport function videoCharacterVoiceProblem(args: {\n provider: string | undefined\n characterReferences: readonly VideoCharacterReference[] | undefined\n cap?: number\n}): VideoCharacterRefProblem | null {\n const distinct = videoCharacterDistinctVoices(args.characterReferences)\n if (distinct === 0) return null\n const cap = args.cap ?? videoCharacterVoiceCap(args.provider)\n if (cap === 0) {\n return {\n code: \"character_voice_unsupported\",\n message:\n `A character voice is not supported by ${args.provider ?? \"the selected model\"}. ` +\n \"Drop the voice, or pick a model that takes characterReferences.\",\n }\n }\n if (distinct > cap) {\n return {\n code: \"character_voices_over_limit\",\n message: `${args.provider} accepts at most ${cap} distinct character voices per video; got ${distinct}. Give some characters the same voice, or drop some.`,\n }\n }\n return null\n}\n\n/**\n * The one validation both video routes (and the provider backstop) run. Returns\n * the first problem as a friendly 400 body, or null when the request is fine.\n *\n * The shared budget: for a model that declares `characters`, its `images` cap\n * IS the total input budget (images + 2×videos + character units ≤ images cap —\n * 7 for Gemini Omni). Callers pass the ASSEMBLED image count, after any\n * `connectedReferences` expansion, so the budget is measured on what ships.\n */\nexport function videoCharacterRefProblem(args: {\n provider: string | undefined\n characterReferences: readonly VideoCharacterReference[] | undefined\n /** Reference images that will ship (assembled, flat). */\n imageCount: number\n /** Source / reference videos that will ship. */\n videoCount: number\n /** True when the request carries a start frame (`imageUrl`). */\n hasStartFrame: boolean\n /** True when the request carries an end frame (`endFrameUrl`). */\n hasEndFrame?: boolean\n /** Reference audio clips that will ship (counted by a `materials` budget). */\n audioCount?: number\n}): VideoCharacterRefProblem | null {\n const { provider, characterReferences } = args\n if (!characterReferences || characterReferences.length === 0) return null\n\n const cap = videoCharacterRefCap(provider)\n if (cap === 0) {\n return {\n code: \"character_references_unsupported\",\n message:\n `characterReferences is not supported by ${provider ?? \"the selected model\"}. ` +\n `Models that take them: ${videoCharacterRefProviders().join(\", \")}. ` +\n \"Otherwise send the portrait as a reference image instead.\",\n }\n }\n if (characterReferences.length > cap) {\n return {\n code: \"character_references_over_limit\",\n message: `${provider} accepts at most ${cap} character references; got ${characterReferences.length}.`,\n }\n }\n // A provider that counts every material against ONE budget (Kling 4.0: 15\n // images + videos + subjects + voices) takes characters beside a start frame\n // (the frame joins the reference images) — the Gemini Omni unit rules below\n // do not apply to it. Where audio rides on the characters as their voices\n // (`audioBindsToCharacters`, Kling 4.0 Flash), a clip takes no seat.\n const limits = VIDEO_REF_LIMITS_BY_PROVIDER[provider as string]\n const materials = limits?.materials\n if (materials !== undefined) {\n const audioSeats = limits?.audioBindsToCharacters ? 0 : (args.audioCount ?? 0)\n const used =\n args.imageCount + (args.hasStartFrame ? 1 : 0) + args.videoCount + characterReferences.length + audioSeats\n if (used > materials) {\n return {\n code: \"character_references_quota\",\n message:\n `${provider} takes at most ${materials} materials in all — reference images (a start frame counts as one), ` +\n `reference videos, characters${limits?.audioBindsToCharacters ? \"\" : \" and voices\"}. This request uses ${used}. Remove some.`,\n }\n }\n return videoCharacterVoiceProblem({ provider, characterReferences })\n }\n // A NODARO limit, not an upstream exclusivity: Gemini Omni's start frame is\n // sent as the first entry of `image_urls` (never as `first_frame_url`), so\n // the upstream would take it beside `character_ids`. We reject the pair\n // because the frame / identity roles are not yet bound in the prompt\n // (and the frame would need to be budgeted against the shared input quota).\n if (args.hasStartFrame) {\n return {\n code: \"character_references_with_start_frame\",\n message:\n `${provider} does not yet support combining characterReferences with a start frame (imageUrl) — ` +\n \"the frame and the characters would compete for the same input slots without a defined role. \" +\n \"Drop the start frame (the character's portrait carries the face), or drop characterReferences.\",\n }\n }\n // Gemini Omni has no end-frame input; without this the frame would be dropped\n // silently once characters make a frame-less request look \"referenced\".\n if (args.hasEndFrame) {\n return {\n code: \"character_references_with_end_frame\",\n message:\n `${provider} does not use an end frame (endFrameUrl) together with characterReferences. ` +\n \"Drop the end frame, or drop characterReferences.\",\n }\n }\n const budget = VIDEO_REF_LIMITS_BY_PROVIDER[provider as string]?.images ?? 7\n const used = args.imageCount + args.videoCount * 2 + videoCharacterRefUnits(characterReferences)\n if (used > budget) {\n return {\n code: \"character_references_quota\",\n message:\n `${provider} takes at most ${budget} input units: reference images count 1, each reference video 2, ` +\n `each character 1 (2 with a body image). This request uses ${used}. Remove some reference images or characters.`,\n }\n }\n return videoCharacterVoiceProblem({ provider, characterReferences })\n}\n\n/**\n * One provider-neutral character reference per wired Character node, for a\n * model that takes wired characters as NAMED SUBJECTS (catalog feature\n * `character-subjects`, Kling 4.0). Input: the wired-character entries both\n * engines already expand (`expandWiredCharacterRefs` server-side, the editor's\n * twin) — the canonical portrait and every variant, grouped here by character.\n * The portrait leads; up to {@link VIDEO_CHARACTER_EXTRA_IMAGES_MAX} more views\n * follow in expansion order. The name is the character's own; the description\n * its canonical description, else its description. A character with a single\n * image still yields a reference — the provider decides (Kling keeps it a\n * reference image).\n */\nexport function characterReferencesFromWired(\n refs: readonly ConnectedReference[],\n /**\n * The clip each wired character carries, by its slug (`wiredCharacterVideoUrls`):\n * pass it only for a model that takes video subjects. Absent = none.\n */\n videoBySlug?: ReadonlyMap<string, string>,\n): VideoCharacterReference[] {\n const bySlug = new Map<string, { name: string; description?: string; urls: string[]; videoUrl?: string }>()\n for (const r of refs) {\n if (r.source !== \"wired-character\" || !r.characterSlug || !r.url) continue\n let entry = bySlug.get(r.characterSlug)\n if (!entry) {\n const videoUrl = videoBySlug?.get(r.characterSlug)\n entry = { name: r.defaultName.split(\" / \")[0]!.trim() || r.characterSlug, urls: [], ...(videoUrl ? { videoUrl } : {}) }\n bySlug.set(r.characterSlug, entry)\n }\n const description = (r.characterCanonicalDescription ?? r.description)?.trim()\n if (!entry.description && description) entry.description = description\n if (entry.urls.includes(r.url)) continue\n // The canonical portrait leads whatever order the variants arrived in.\n if (!r.variantSlug) entry.urls.unshift(r.url)\n else entry.urls.push(r.url)\n }\n return [...bySlug.values()].map((c) => ({\n imageUrl: c.urls[0]!,\n ...(c.urls.length > 1 ? { extraImageUrls: c.urls.slice(1, 1 + VIDEO_CHARACTER_EXTRA_IMAGES_MAX) } : {}),\n description: (c.description ?? c.name).slice(0, VIDEO_CHARACTER_DESCRIPTION_MAX),\n name: c.name.slice(0, VIDEO_CHARACTER_NAME_MAX),\n ...(c.videoUrl ? { videoUrl: c.videoUrl } : {}),\n }))\n}\n","import { hasFeature } from \"./model-catalog.js\"\nimport { characterMentionSlug } from \"./character-mention-slug.js\"\nimport { characterMentionableAssetArrays } from \"./character-variant-assets.js\"\nimport { entityImageUrl } from \"./entity-image-url.js\"\nimport { videoCharacterRefCap, videoCharacterVideoCap } from \"./video-character-refs.js\"\nimport { wiredCharacterNamesOf, wiredCharacterVideoUrls } from \"./wired-character-names.js\"\n\ntype GraphNode = { readonly id: string; readonly type?: string | null; readonly data?: unknown }\ntype GraphEdge = { readonly source: string; readonly target: string; readonly sourceHandle?: string | null }\n\n/**\n * Whether a Character node gives its wired character a reference image: its\n * portrait (`entityImageUrl`), or any named image of its mentionable asset\n * buckets. The rule a run's character expansion follows (`expandWiredCharacterRefs`\n * in the workflow payload builder, its editor twin): a node with none yields\n * no reference, so `characterReferencesFromWired` makes no character of it.\n */\nfunction characterGivesAnImage(data: unknown): boolean {\n if (entityImageUrl(data)) return true\n const arrays = characterMentionableAssetArrays((data ?? {}) as Record<string, unknown>)\n return Object.values(arrays).some((items) => items.some((item) => !!item?.url && !!characterMentionSlug(item.name ?? \"\")))\n}\n\n/**\n * The clips a Generate Video run on `provider` sends as its characters' video\n * subjects (decided 2026-11-13), in the order the run seats them — read off the\n * graph without building the run, for an estimate that must price exactly what\n * the run sends:\n *\n * - none on a model that takes no video subjects (or no named subjects at all);\n * - the characters as the run groups them (`characterReferencesFromWired`): one\n * per wired character by the slug it goes by, in wire order of its first node\n * that gives an image — a node with no image at all makes no character, so\n * its clip is not sent;\n * - only the first `videoCharacterRefCap(provider)` characters (the run's slice);\n * - each character's clip as `wiredCharacterVideoUrls` gives it (its first\n * node's, in wire order).\n *\n * The workflow run itself builds the same list through\n * `characterReferencesFromWired(expandWiredCharacterRefs(…), clips).slice(…)`;\n * a parity test holds the two together. Only Generate Video carries video\n * subjects — the older Image to Video / Text to Video nodes never do.\n */\nexport function wiredCharacterSubjectClips(\n consumerId: string,\n nodes: ReadonlyArray<GraphNode>,\n edges: ReadonlyArray<GraphEdge>,\n provider: string,\n): string[] {\n if (videoCharacterVideoCap(provider) === 0 || !hasFeature(provider, \"character-subjects\")) return []\n const clips = wiredCharacterVideoUrls(consumerId, nodes, edges)\n if (clips.size === 0) return []\n const byId = new Map(nodes.map((n) => [n.id, n] as const))\n const subjects: string[] = []\n for (const [id, named] of wiredCharacterNamesOf(consumerId, nodes, edges)) {\n if (subjects.includes(named.slug)) continue\n if (characterGivesAnImage(byId.get(id)?.data)) subjects.push(named.slug)\n }\n return subjects.slice(0, videoCharacterRefCap(provider)).flatMap((slug) => {\n const clip = clips.get(slug)\n return clip ? [clip] : []\n })\n}\n","/**\n * Video Overlay — placement: the output canvas and where a layer's box lands\n * on it. `resolveVideoOverlayGeometry` is the one placement function the\n * canvas preview and the ffmpeg worker both call. A sibling of\n * `video-overlay.ts`, which it imports from; nothing there imports this file.\n * Wire contract only — no I/O.\n */\nimport type { OverlayAnchor } from \"./image-overlay-layers.js\"\nimport { ASPECT_RATIO_DIMENSIONS } from \"./model-constants.js\"\nimport { isVideoOverlayOutputAspect, type VideoOverlayLayer } from \"./video-overlay.js\"\n\nexport interface VideoOverlayRect {\n readonly left: number\n readonly top: number\n readonly width: number\n readonly height: number\n}\nexport interface VideoOverlayCanvas {\n readonly w: number\n readonly h: number\n}\nexport interface VideoOverlayGeometry {\n readonly box: VideoOverlayRect\n readonly drawn: VideoOverlayRect\n}\n\nconst evenFloor = (n: number): number => Math.max(2, Math.floor(n / 2) * 2)\n\n/**\n * The output canvas: `ASPECT_RATIO_DIMENSIONS[outputAspect]` when a target\n * aspect is set; otherwise the base's DISPLAY size (rotation already applied by\n * the caller's probe) with the sample aspect ratio resolved and both sides\n * rounded down to even — `trunc(iw*sar/2)*2 × trunc(ih/2)*2`, what the ffmpeg\n * base chain produces. null when neither is known.\n */\nexport function videoOverlayCanvas(\n display: { readonly width: number; readonly height: number; readonly sar?: number } | null | undefined,\n outputAspect?: string | null,\n): VideoOverlayCanvas | null {\n if (isVideoOverlayOutputAspect(outputAspect)) {\n const d = ASPECT_RATIO_DIMENSIONS[outputAspect]!\n return { w: d.width, h: d.height }\n }\n if (!display || !(display.width > 0) || !(display.height > 0)) return null\n const sar = typeof display.sar === \"number\" && Number.isFinite(display.sar) && display.sar > 0 ? display.sar : 1\n return { w: evenFloor(display.width * sar), h: evenFloor(display.height) }\n}\n\nfunction anchorFactors(anchor: OverlayAnchor): readonly [number, number] {\n const h = anchor.endsWith(\"left\") ? 0 : anchor.endsWith(\"right\") ? 1 : 0.5\n const v = anchor.startsWith(\"top\") ? 0 : anchor.startsWith(\"bottom\") ? 1 : 0.5\n return [h, v]\n}\n\n/**\n * Spec §3.4. `width%` → px of the canvas width; height follows the image's\n * aspect unless `height%` is set; nine anchors; x/y are additive offsets in %\n * of the canvas. An aspect-following box taller than the canvas is fitted\n * inside it (both sides scaled, aspect kept) — so `drawn` never exceeds the\n * canvas, which is what bounds the sharp pre-fit at one canvas of RGBA. `fit`:\n * contain → the image scaled inside the box, centred; cover → the box itself.\n * The only post-processing is rounding `drawn` DOWN to even, floored at 2 × 2.\n * Differences from Image Overlay's copies (on purpose): no 8192 edge shrink,\n * the canvas clamp, the even rounding.\n */\nexport function resolveVideoOverlayGeometry(\n canvas: VideoOverlayCanvas,\n layer: Pick<VideoOverlayLayer, \"anchor\" | \"x\" | \"y\" | \"width\" | \"height\" | \"fit\">,\n imageAspect: number,\n): VideoOverlayGeometry {\n const aspect = Number.isFinite(imageAspect) && imageAspect > 0 ? imageAspect : 1\n let bw = Math.max(1, Math.round((layer.width / 100) * canvas.w))\n let bh = layer.height !== undefined ? Math.max(1, Math.round((layer.height / 100) * canvas.h)) : Math.max(1, Math.round(bw / aspect))\n if (layer.height === undefined && bh > canvas.h) {\n bw = Math.max(1, Math.round(bw * (canvas.h / bh)))\n bh = canvas.h\n }\n const [ax, ay] = anchorFactors(layer.anchor)\n const left = Math.round(ax * (canvas.w - bw) + (layer.x / 100) * canvas.w)\n const top = Math.round(ay * (canvas.h - bh) + (layer.y / 100) * canvas.h)\n let dw: number\n let dh: number\n if (layer.fit === \"cover\") {\n dw = bw\n dh = bh\n } else if (bw / bh > aspect) {\n dh = bh\n dw = bh * aspect\n } else {\n dw = bw\n dh = bw / aspect\n }\n const width = evenFloor(dw)\n const height = evenFloor(dh)\n return {\n box: { left, top, width: bw, height: bh },\n drawn: { left: left + Math.floor((bw - width) / 2), top: top + Math.floor((bh - height) / 2), width, height },\n }\n}\n","/**\n * Video Overlay layouts — the ids, and what each one needs. A layout is a\n * named shortcut that writes the boxes (`expandVideoOverlayLayout` in\n * `video-overlay-layouts.ts`); like a placement preset, it is a TAG and the\n * boxes are the truth, except for the two stacks, whose boxes depend on the\n * sources' shapes and are resolved where those are known.\n *\n * Dependency-free on purpose: the validator in `video-overlay-validate.ts`\n * reads these, and `video-overlay-layouts.ts` imports the contract in\n * `video-overlay.ts`, so they cannot live in either without a cycle. Wire contract only — no I/O.\n */\n\n/**\n * - `video-bottom` / `video-top`: the base whole, full width, against that edge.\n * - `stack-whole`: the base directly above the first video layer, both whole,\n * the same width, the pair centred.\n * - `stack-filled`: the base fills the top half, the first video layer the\n * bottom half, both cropped (`cover`).\n * - `pip`: the base fills the frame, the first video layer sits in a corner.\n */\nexport const VIDEO_OVERLAY_LAYOUT_IDS = [\"video-bottom\", \"video-top\", \"stack-whole\", \"stack-filled\", \"pip\"] as const\nexport type VideoOverlayLayoutId = (typeof VIDEO_OVERLAY_LAYOUT_IDS)[number]\n\nexport function isVideoOverlayLayoutId(v: unknown): v is VideoOverlayLayoutId {\n return typeof v === \"string\" && (VIDEO_OVERLAY_LAYOUT_IDS as readonly string[]).includes(v)\n}\n\n/** Layouts placed against the output canvas's edges or halves: every one but `pip`. */\nconst NEEDS_ASPECT: ReadonlySet<VideoOverlayLayoutId> = new Set([\"video-bottom\", \"video-top\", \"stack-whole\", \"stack-filled\"])\n/** Layouts that place the first video layer. */\nconst NEEDS_VIDEO_LAYER: ReadonlySet<VideoOverlayLayoutId> = new Set([\"stack-whole\", \"stack-filled\", \"pip\"])\n/** Layouts that place the base themselves, so take no `baseBox`. */\nconst PLACES_BASE: ReadonlySet<VideoOverlayLayoutId> = new Set([\"stack-whole\", \"stack-filled\"])\n\n/** True when the layout is refused without an `outputAspect` (`layout_needs_aspect`). */\nexport function videoOverlayLayoutNeedsAspect(id: VideoOverlayLayoutId): boolean {\n return NEEDS_ASPECT.has(id)\n}\n\n/** True when the layout is refused without a video layer (`layout_needs_video_layer`). */\nexport function videoOverlayLayoutNeedsVideoLayer(id: VideoOverlayLayoutId): boolean {\n return NEEDS_VIDEO_LAYER.has(id)\n}\n\n/** True when the layout places the base itself and is refused with a `baseBox` (`layout_conflicts_base_box`): the two stacks. */\nexport function videoOverlayLayoutPlacesBase(id: VideoOverlayLayoutId): boolean {\n return PLACES_BASE.has(id)\n}\n","/**\n * Video Overlay — the request validator: what a schema cannot express, run at\n * every engine entry. It returns a CODE, never English: `formatVideoOverlayError`\n * renders the route / worker text, the canvas renders the code through its\n * dictionaries. A sibling of `video-overlay.ts`, which it imports from; nothing\n * there imports this file.\n * Wire contract only — no prompt content, no I/O.\n */\nimport { OVERLAY_ANCHORS } from \"./image-overlay-layers.js\"\nimport {\n VIDEO_OVERLAY_BOUNDS, VIDEO_OVERLAY_BOX_FIELDS, VIDEO_OVERLAY_FITS, VIDEO_OVERLAY_MAX_LAYERS, VIDEO_OVERLAY_MAX_TIME_SEC,\n VIDEO_OVERLAY_MAX_VIDEO_LAYERS, VIDEO_OVERLAY_VOLUME_BOUNDS, isVideoOverlayOutputAspect, isVideoOverlayPresetId,\n type VideoOverlayBoxInput, type VideoOverlayErrorCode, type VideoOverlayLayerInput,\n} from \"./video-overlay.js\"\nimport { asLayer, isFit, nonEmpty, storedLayout } from \"./video-overlay-input.js\"\nimport { isVideoOverlayVideoLayer } from \"./video-overlay-video-layers.js\"\nimport {\n VIDEO_OVERLAY_LAYOUT_IDS, isVideoOverlayLayoutId, videoOverlayLayoutNeedsAspect, videoOverlayLayoutNeedsVideoLayer, videoOverlayLayoutPlacesBase,\n type VideoOverlayLayoutId,\n} from \"./video-overlay-layout-ids.js\"\n\nexport interface VideoOverlayIssue {\n readonly ok: false\n readonly code: VideoOverlayErrorCode\n /** 0-based index into the validated `layers[]`. */\n readonly layer?: number\n readonly slot?: number\n readonly planLayer?: number\n readonly params: Readonly<Record<string, string | number>>\n}\nexport type VideoOverlayValidation = { readonly ok: true } | VideoOverlayIssue\n\nexport interface VideoOverlayValidationInput {\n readonly layers?: ReadonlyArray<VideoOverlayLayerInput | null | undefined> | null\n readonly outputAspect?: string | null\n readonly baseFit?: string | null\n readonly backgroundColor?: string | null\n readonly baseBox?: VideoOverlayBoxInput | null\n readonly layout?: string | null\n /** From `assembleVideoOverlayRequest`: the wired layer plan was unreadable. */\n readonly planError?: \"invalid_layer_plan\"\n}\n\nconst inTimeRange = (v: unknown): v is number =>\n typeof v === \"number\" && Number.isFinite(v) && v >= 0 && v <= VIDEO_OVERLAY_MAX_TIME_SEC\n\ntype BoundedField = keyof typeof VIDEO_OVERLAY_BOUNDS\nconst BOUNDED_FIELDS = Object.keys(VIDEO_OVERLAY_BOUNDS) as BoundedField[]\n\n/**\n * The first present (non-null) box / look field outside its domain, with the\n * domain as a symbolic `allowed` string; null when every present field is in\n * range. Only PRESENT fields are checked, so the verdict is the same before and\n * after the expansion (it fills in-range defaults only). This is what keeps a\n * JSON-written layer (MCP `update_workflow_json`, copilot, templates) from\n * reaching the geometry with an unbounded box — `drawn ≤ canvas` (§3.4) holds\n * only for boxes inside these bounds.\n */\nfunction outOfBounds(l: VideoOverlayLayerInput): { field: string; allowed: string } | null {\n for (const f of BOUNDED_FIELDS) {\n const v = l[f]\n if (v === undefined || v === null) continue\n const [min, max] = VIDEO_OVERLAY_BOUNDS[f]\n const integer = f === \"zIndex\"\n if (typeof v !== \"number\" || !Number.isFinite(v) || v < min || v > max || (integer && !Number.isInteger(v))) {\n return { field: f, allowed: `${integer ? \"integers \" : \"\"}${min}..${max}` }\n }\n }\n if (l.anchor != null && !(OVERLAY_ANCHORS as readonly unknown[]).includes(l.anchor)) {\n return { field: \"anchor\", allowed: OVERLAY_ANCHORS.join(\", \") }\n }\n if (l.fit != null && !isFit(l.fit)) return { field: \"fit\", allowed: VIDEO_OVERLAY_FITS.join(\", \") }\n if (l.animate != null && typeof l.animate !== \"boolean\") return { field: \"animate\", allowed: \"true, false\" }\n return null\n}\n\n/**\n * A present `sound` that is not `{ volume }` with the volume inside\n * `VIDEO_OVERLAY_VOLUME_BOUNDS`. Kept out of `outOfBounds`: a bad volume is\n * refused, but it does not stop the stage from drawing the layer.\n */\nfunction soundOutOfBounds(sound: unknown): { field: string; allowed: string } | null {\n if (sound === undefined || sound === null) return null\n const [min, max] = VIDEO_OVERLAY_VOLUME_BOUNDS\n const v = typeof sound === \"object\" && !Array.isArray(sound) ? (sound as { volume?: unknown }).volume : undefined\n return typeof v === \"number\" && Number.isFinite(v) && v >= min && v <= max ? null : { field: \"sound.volume\", allowed: `${min}..${max}` }\n}\n\n/** A present base box under the layer rule: anchor and width (a non-object reads as an empty box), every present box field in range. */\nfunction baseBoxIssue(raw: unknown): VideoOverlayIssue | null {\n const own = asLayer(raw) ?? {}\n const box = Object.fromEntries(VIDEO_OVERLAY_BOX_FIELDS.map((f) => [f, own[f]])) as VideoOverlayLayerInput\n if (box.anchor == null || box.width == null) return { ok: false, code: \"incomplete_box\", params: { field: \"baseBox\" } }\n const bad = outOfBounds(box)\n return bad ? { ok: false, code: \"field_out_of_bounds\", params: { ...bad, field: `baseBox.${bad.field}` } } : null\n}\n\n/**\n * Can `resolveVideoOverlayGeometry` place this layer? True when its box is what\n * the validator's box checks require: `anchor` one of the nine anchors, `width`\n * a finite number, and every present box / look field in range\n * (`VIDEO_OVERLAY_BOUNDS`, enums). A partial box saved from workflow JSON\n * (`{ imageUrl, start, width }`, `anchor: null`) is stored as written — the\n * expansion leaves it for the validator's `incomplete_box` — so any reader\n * that DRAWS a stored layer (the canvas stage) must skip one that fails this;\n * the geometry would throw on it.\n */\nexport function hasDrawableVideoOverlayBox(layer: unknown): boolean {\n const l = asLayer(layer)\n if (!l) return false\n if (!(OVERLAY_ANCHORS as readonly unknown[]).includes(l.anchor)) return false\n if (typeof l.width !== \"number\" || !Number.isFinite(l.width)) return false\n return outOfBounds(l) === null\n}\n\n/**\n * Spec §3.5 — what a schema cannot express, and what the DAG path skips. Run\n * at every engine entry: the route (`.superRefine`, before the expansion), the\n * canvas single-node run, payload-builder and the worker (after it) — the\n * verdict is the same on either side of the expansion (no code reads an\n * expanded field). Also refuses a PRESENT box / look field outside\n * `VIDEO_OVERLAY_BOUNDS` or its enum / type (`field_out_of_bounds`, spec §4.4's\n * \"out-of-bounds box/opacity/zIndex\" row — on the DAG path this validator is\n * the only check). A layer carries an image or a video, never both\n * (`layer_two_sources`), at most `VIDEO_OVERLAY_MAX_VIDEO_LAYERS` are videos,\n * and only a video layer has `sound`. A non-object `layers[]` entry reads as\n * an empty layer. A `layout` (`\"\"` reads as absent) must be known, a stack\n * takes no `baseBox` (`layout_conflicts_base_box`: it places the base\n * itself); a `baseBox` follows the layer rule (`incomplete_box`,\n * `field_out_of_bounds` as `baseBox.<field>`) and needs an `outputAspect`; a\n * layout gets what it needs (an aspect, a video layer) — checked before\n * `base_box_needs_aspect`, so writing a layout's base box does not change the\n * verdict. The FIRST failure, as a code.\n */\nexport function validateVideoOverlayRequest(body: VideoOverlayValidationInput): VideoOverlayValidation {\n if (body.planError) return { ok: false, code: \"invalid_layer_plan\", params: {} }\n const layers = Array.isArray(body.layers) ? body.layers : []\n if (layers.length === 0) return { ok: false, code: \"no_layers\", params: {} }\n if (layers.length > VIDEO_OVERLAY_MAX_LAYERS) {\n return { ok: false, code: \"too_many_layers\", params: { max: VIDEO_OVERLAY_MAX_LAYERS, count: layers.length } }\n }\n const videoCount = layers.filter(isVideoOverlayVideoLayer).length\n if (videoCount > VIDEO_OVERLAY_MAX_VIDEO_LAYERS) {\n return { ok: false, code: \"too_many_video_layers\", params: { max: VIDEO_OVERLAY_MAX_VIDEO_LAYERS, count: videoCount } }\n }\n for (let i = 0; i < layers.length; i++) {\n const l: VideoOverlayLayerInput = asLayer(layers[i]) ?? {}\n const at = (code: VideoOverlayErrorCode, params: Record<string, string | number> = {}): VideoOverlayIssue => ({\n ok: false,\n code,\n layer: i,\n ...(typeof l.slot === \"number\" ? { slot: l.slot } : {}),\n ...(typeof l.planLayer === \"number\" ? { planLayer: l.planLayer } : {}),\n params,\n })\n const boxFields = VIDEO_OVERLAY_BOX_FIELDS.filter((f) => l[f] !== undefined && l[f] !== null)\n if (!isVideoOverlayPresetId(l.preset) && boxFields.length > 0 && (l.anchor == null || l.width == null)) return at(\"incomplete_box\")\n const bad = outOfBounds(l) ?? soundOutOfBounds(l.sound)\n if (bad) return at(\"field_out_of_bounds\", bad)\n const hasVideo = nonEmpty(l.videoUrl)\n if (nonEmpty(l.imageUrl) && hasVideo) return at(\"layer_two_sources\")\n if (!nonEmpty(l.imageUrl) && !hasVideo) return at(\"layer_without_image\")\n if (l.sound != null && !hasVideo) return at(\"sound_without_video\")\n if (!inTimeRange(l.start)) return at(\"time_out_of_range\", { field: \"start\", max: VIDEO_OVERLAY_MAX_TIME_SEC })\n if (l.end !== undefined && l.end !== null) {\n if (!inTimeRange(l.end)) return at(\"time_out_of_range\", { field: \"end\", max: VIDEO_OVERLAY_MAX_TIME_SEC })\n if (!(l.end > l.start)) return at(\"end_before_start\", { start: l.start, end: l.end })\n }\n }\n const hasAspect = isVideoOverlayOutputAspect(body.outputAspect)\n if (!hasAspect && (body.baseFit != null || body.backgroundColor != null)) {\n return { ok: false, code: \"fit_without_aspect\", params: {} }\n }\n const stored = storedLayout(body.layout)\n if (stored !== undefined && !isVideoOverlayLayoutId(stored)) {\n return { ok: false, code: \"field_out_of_bounds\", params: { field: \"layout\", allowed: VIDEO_OVERLAY_LAYOUT_IDS.join(\", \") } }\n }\n const layout = stored as VideoOverlayLayoutId | undefined\n if (layout && body.baseBox != null && videoOverlayLayoutPlacesBase(layout)) return { ok: false, code: \"layout_conflicts_base_box\", params: { layout } }\n const boxIssue = body.baseBox != null ? baseBoxIssue(body.baseBox) : null\n if (boxIssue) return boxIssue\n if (layout && !hasAspect && videoOverlayLayoutNeedsAspect(layout)) return { ok: false, code: \"layout_needs_aspect\", params: { layout } }\n if (layout && videoOverlayLayoutNeedsVideoLayer(layout) && !layers.some(isVideoOverlayVideoLayer)) {\n return { ok: false, code: \"layout_needs_video_layer\", params: { layout } }\n }\n if (body.baseBox != null && !hasAspect) return { ok: false, code: \"base_box_needs_aspect\", params: {} }\n return { ok: true }\n}\n\nconst MESSAGES: { readonly [C in VideoOverlayErrorCode]: (p: Readonly<Record<string, string | number>>) => string } = {\n no_layers: () => \"At least 1 layer is required\",\n too_many_layers: (p) => `At most ${p.max} layers (got ${p.count})`,\n incomplete_box: (p) => (p.field ? `${p.field} needs an anchor and a width` : \"anchor and width are required without a preset\"),\n layer_without_image: () => \"no image or video — connect one to the layer's handle or set imageUrl or videoUrl\",\n time_out_of_range: (p) => `${p.field} must be between 0 and ${p.max} s`,\n end_before_start: (p) => `end (${p.end} s) must be after start (${p.start} s)`,\n fit_without_aspect: () => \"baseFit and backgroundColor need an outputAspect\",\n field_out_of_bounds: (p) => `${p.field} is out of range (allowed: ${p.allowed})`,\n invalid_layer_plan: () => \"the layer plan must be a list of layers\",\n layer_two_sources: () => \"has both an image and a video — keep one (imageUrl or videoUrl)\",\n too_many_video_layers: (p) => `At most ${p.max} video layers (got ${p.count})`,\n sound_without_video: () => \"sound is only for a video layer — remove it or set videoUrl\",\n base_box_needs_aspect: () => \"baseBox needs an outputAspect\",\n layout_needs_aspect: (p) => `layout ${p.layout} needs an outputAspect`,\n layout_needs_video_layer: (p) => `layout ${p.layout} needs a video layer — set videoUrl on a layer or connect a video to a layer's handle`,\n layout_conflicts_base_box: () => \"A stack layout places the base itself — remove baseBox or choose Custom\",\n}\n\nconst PLAN_LAYER_WITHOUT_IMAGE = \"no image or video — set imageUrl or videoUrl on this layer in the plan.\"\n\n/** `Plan layer <n>` for a layer-plan entry, `Layer <slot>` when the layer came from the canvas, else `layers[<index>]`; \"\" for a request-wide failure. */\nexport function videoOverlayLayerLabel(ref: { readonly layer?: number; readonly slot?: number; readonly planLayer?: number }): string {\n if (typeof ref.planLayer === \"number\") return `Plan layer ${ref.planLayer}`\n return typeof ref.slot === \"number\" ? `Layer ${ref.slot}` : typeof ref.layer === \"number\" ? `layers[${ref.layer}]` : \"\"\n}\n\n/** The ONE English rendering of a verdict — the route's 400 text and the worker's error message. */\nexport function formatVideoOverlayError(issue: VideoOverlayIssue): string {\n const label = videoOverlayLayerLabel(issue)\n // A plan layer has no handle to connect — its source can only come from its own imageUrl or videoUrl.\n const text = issue.code === \"layer_without_image\" && typeof issue.planLayer === \"number\" ? PLAN_LAYER_WITHOUT_IMAGE : MESSAGES[issue.code](issue.params)\n return label ? `${label}: ${text}` : text\n}\n","/**\n * Video Overlay layouts and the placed base — the request-level normaliser\n * (`expandVideoOverlayLayout`) and the geometry the canvas preview and the\n * ffmpeg worker both call, so the preview and the render cannot disagree.\n * A sibling of `video-overlay.ts`: it imports from there, nothing there imports\n * from here, and the layout ids live in the dependency-free\n * `video-overlay-layout-ids.ts`.\n *\n * - `video-bottom` / `video-top` write a base box; an explicit one wins.\n * - `pip` writes the first video layer's box in its corner.\n * - The two stacks write no box: their rects depend on the sources' shapes,\n * known only after probing, so the worker and the preview call\n * `resolveVideoOverlayStackRects` with them. A stack places the base\n * itself, so the validator refuses one with a `baseBox` (`layout_conflicts_base_box`).\n * `pip` and the two stacks turn the first video layer's fade off;\n * `video-bottom` / `video-top` touch no layer. \"First video layer\" is the\n * lowest one (`firstVideoLayerIndex`); image layers are left where they are.\n * A probed video's aspect goes through `clampVideoOverlayAspect` before any of\n * this geometry, and a video's rect through `evenVideoOverlayRect` after it —\n * in the worker and the preview alike.\n * Wire contract only — no I/O.\n */\nimport {\n VIDEO_OVERLAY_BOX_FIELDS,\n expandVideoOverlayLayer,\n isVideoOverlayCorner,\n videoOverlayRenderOrder,\n type VideoOverlayBox,\n type VideoOverlayBoxInput,\n type VideoOverlayCorner,\n type VideoOverlayFit,\n type VideoOverlayLayer,\n type VideoOverlayLayerInput,\n type VideoOverlayOrderable,\n} from \"./video-overlay.js\"\nimport { resolveVideoOverlayGeometry, type VideoOverlayCanvas, type VideoOverlayRect } from \"./video-overlay-geometry.js\"\nimport { validateVideoOverlayRequest } from \"./video-overlay-validate.js\"\nimport { isVideoOverlayVideoLayer } from \"./video-overlay-video-layers.js\"\n\n/** Picture in picture: the inset's width and its margin from the corner, % of the output canvas (Speaker View's inset). */\nexport const VIDEO_OVERLAY_PIP_WIDTH = 30\nexport const VIDEO_OVERLAY_PIP_INSET = 4\n\n/** What a layout reads and writes — a request, an assembled request, or node data. */\nexport interface VideoOverlayLayoutFields {\n readonly layout?: string | null\n readonly baseBox?: VideoOverlayBoxInput | null\n readonly layers?: ReadonlyArray<VideoOverlayLayerInput | null | undefined> | null\n}\n\n/** The base box each edge layout writes: the base whole, full width, flush on that edge. */\nconst EDGE_BASE_BOXES: { readonly [L in \"video-bottom\" | \"video-top\"]: VideoOverlayBox } = {\n \"video-bottom\": { anchor: \"bottom\", x: 0, y: 0, width: 100, fit: \"contain\" },\n \"video-top\": { anchor: \"top\", x: 0, y: 0, width: 100, fit: \"contain\" },\n}\n\n/** A base box's trailing defaults, as a layer's (`expandVideoOverlayLayer`). */\nconst BOX_DEFAULTS = { x: 0, y: 0, fit: \"contain\" } as const\n\n/**\n * The narrowest and widest aspect a probed video is placed at. A video's\n * shape is only known from its probe, and nothing bounds a probe, so a stack\n * of a 1:1000 sliver could otherwise place a rect off the canvas. Inside these\n * bounds every stack, base and layer rect stays on it.\n */\nexport const VIDEO_OVERLAY_ASPECT_BOUNDS = [1 / 8, 8] as const\n\n/** Rounded down to even, floored at 2; the epsilon absorbs float error at an exact even size (960.0000 read as 959.9999). */\nconst evenFloor = (n: number): number => Math.max(2, Math.floor(n / 2 + 1e-9) * 2)\nconst usableAspect = (a: number): number => (Number.isFinite(a) && a > 0 ? a : 1)\n\n/**\n * A probed video's display aspect (width ÷ height), held inside\n * `VIDEO_OVERLAY_ASPECT_BOUNDS`; one that is not a positive finite number\n * reads as square, as in the layer geometry. The worker and the preview pass\n * every video's aspect (the base's and each video layer's) through this before\n * any placement, so they place the same rects.\n */\nexport function clampVideoOverlayAspect(aspect: number): number {\n const [min, max] = VIDEO_OVERLAY_ASPECT_BOUNDS\n return Number.isFinite(aspect) && aspect > 0 ? Math.min(max, Math.max(min, aspect)) : 1\n}\n\n/** Rounded down to an even integer, negatives included (−61 → −62). */\nconst floorEven = (n: number): number => Math.floor(n / 2) * 2\n\n/**\n * A video's rect as the render draws it: left and top rounded DOWN to even,\n * and the size down to even. ffmpeg's overlay on yuv420 clears the low bit of\n * an odd x or y (a base placed at top 371 is drawn at 370), so this is where\n * the picture lands anyway; the worker hands the graph these numbers and the\n * preview draws them, so the two agree to the pixel. A stack's two rects move\n * by the same pixel (its heights are even), so its join stays exact. Applied\n * to the base's rect and to video layers only — an image layer's geometry is\n * unchanged. By reference when the rect is already even.\n */\nexport function evenVideoOverlayRect(rect: VideoOverlayRect): VideoOverlayRect {\n const even = { left: floorEven(rect.left), top: floorEven(rect.top), width: evenFloor(rect.width), height: evenFloor(rect.height) }\n return sameShallow(even, rect) ? rect : even\n}\n\nfunction sameShallow(a: object, b: object): boolean {\n const ka = Object.keys(a)\n return ka.length === Object.keys(b).length && ka.every((k) => (a as Record<string, unknown>)[k] === (b as Record<string, unknown>)[k])\n}\n\n/** The lowest video layer by `videoOverlayRenderOrder`, as its index in `layers`; -1 when there is none. */\nexport function firstVideoLayerIndex(\n layers: ReadonlyArray<(VideoOverlayOrderable & { readonly videoUrl?: string | null }) | null | undefined> | null | undefined,\n): number {\n if (!Array.isArray(layers)) return -1\n return videoOverlayRenderOrder(layers).find((i) => isVideoOverlayVideoLayer(layers[i])) ?? -1\n}\n\n/**\n * An explicit base box with `anchor` and `width` gets the layer's trailing\n * defaults (x 0, y 0, fit contain) and loses its `null` fields; anything else\n * (a partial box, a non-object) is returned untouched for the validator. By\n * reference when nothing changes.\n */\nfunction expandBaseBox(raw: VideoOverlayBoxInput): VideoOverlayBoxInput {\n if (typeof raw !== \"object\" || Array.isArray(raw) || raw.anchor == null || raw.width == null) return raw\n const out: Record<string, unknown> = { ...BOX_DEFAULTS }\n for (const [k, v] of Object.entries(raw)) if (v != null) out[k] = v\n return sameShallow(out, raw) ? raw : (out as VideoOverlayBoxInput)\n}\n\nfunction pipBox(corner: VideoOverlayCorner): VideoOverlayBox {\n const sx = corner.endsWith(\"left\") ? 1 : -1\n const sy = corner.startsWith(\"top\") ? 1 : -1\n return { anchor: corner, x: sx * VIDEO_OVERLAY_PIP_INSET, y: sy * VIDEO_OVERLAY_PIP_INSET, width: VIDEO_OVERLAY_PIP_WIDTH, fit: \"contain\" }\n}\n\n/**\n * The validator's per-layer verdict on this layer alone (a one-layer request\n * meets no request-level check). A layout never repairs a layer it refuses — a\n * bad or partial box, a non-boolean `animate`, two sources, a bad time or\n * volume — so the verdict is the same before and after the expansion, as\n * `expandBaseBox` leaves a partial base box for the validator.\n */\nconst acceptedAlone = (layer: VideoOverlayLayerInput): boolean => validateVideoOverlayRequest({ layers: [layer] }).ok\n\n/**\n * The first video layer under `pip` or a stack, the layouts that place it:\n * `pip` replaces its box (as a preset click does: height and tag go), and each\n * of them turns its fade off. A layer the validator would refuse is returned\n * untouched.\n */\nfunction placeFirstVideoLayer(layout: string, layer: VideoOverlayLayerInput): VideoOverlayLayerInput {\n if (!acceptedAlone(layer)) return layer\n if (layout !== \"pip\") return layer.animate === false ? layer : { ...layer, animate: false }\n const rest: Record<string, unknown> = { ...layer }\n for (const f of VIDEO_OVERLAY_BOX_FIELDS) delete rest[f]\n delete rest.preset\n const corner = isVideoOverlayCorner(layer.corner) ? layer.corner : \"bottom-right\"\n const next = expandVideoOverlayLayer({ ...rest, ...pipBox(corner), animate: false } as VideoOverlayLayerInput)\n return sameShallow(next, layer) ? layer : next\n}\n\n/**\n * The request-level normaliser: what a `layout` writes, and an explicit base\n * box's defaults. Called at the write boundaries and by the worker after the\n * validator. An explicit `baseBox` wins over `video-bottom` / `video-top`;\n * `pip` places the first video layer; the stacks write no box. An unknown\n * layout writes nothing (the validator refuses it), and neither does any\n * layout to a first video layer the validator refuses, so the verdict is the\n * same before and after. Never mutates; the request BY REFERENCE when nothing\n * changes; idempotent.\n */\nexport function expandVideoOverlayLayout<T extends VideoOverlayLayoutFields>(req: T): T & { readonly baseBox?: VideoOverlayBox } {\n const { layout } = req\n const baseBox =\n req.baseBox != null ? expandBaseBox(req.baseBox) : layout === \"video-bottom\" || layout === \"video-top\" ? EDGE_BASE_BOXES[layout] : req.baseBox\n let layers = req.layers\n const first = layout === \"pip\" || layout === \"stack-whole\" || layout === \"stack-filled\" ? firstVideoLayerIndex(req.layers) : -1\n if (first >= 0 && Array.isArray(req.layers)) {\n const layer = req.layers[first] as VideoOverlayLayerInput\n const placed = placeFirstVideoLayer(layout as string, layer)\n if (placed !== layer) layers = req.layers.map((l, i) => (i === first ? placed : l))\n }\n if (baseBox === req.baseBox && layers === req.layers) return req as T & { readonly baseBox?: VideoOverlayBox }\n // Only the changed fields: an unset one never becomes an `undefined` key.\n return {\n ...req,\n ...(baseBox !== req.baseBox ? { baseBox } : {}),\n ...(layers !== req.layers ? { layers } : {}),\n } as T & { readonly baseBox?: VideoOverlayBox }\n}\n\n/**\n * The two stacked rects, `top` for the base and `bottom` for the first video\n * layer, in output pixels.\n * - `stack-whole`: both whole, the same even width, touching, the pair centred\n * with equal spare room above and below (±1 px). They shrink together only\n * when both together are taller than the canvas. The join is pixel-exact.\n * - `stack-filled`: the top half (rounded down to even) and the rest, full\n * width; the aspects are not read — both are cropped (`cover`).\n * An aspect that is not a positive finite number reads as square.\n */\nexport function resolveVideoOverlayStackRects(\n layout: \"stack-whole\" | \"stack-filled\",\n canvas: VideoOverlayCanvas,\n topAspect: number,\n bottomAspect: number,\n): { top: VideoOverlayRect; bottom: VideoOverlayRect } {\n if (layout === \"stack-filled\") {\n const half = evenFloor(canvas.h / 2)\n return {\n top: { left: 0, top: 0, width: canvas.w, height: half },\n bottom: { left: 0, top: half, width: canvas.w, height: canvas.h - half },\n }\n }\n const a = usableAspect(topAspect)\n const b = usableAspect(bottomAspect)\n const total = canvas.w / a + canvas.w / b\n const width = evenFloor(total > canvas.h ? (canvas.w * canvas.h) / total : canvas.w)\n const th = evenFloor(width / a)\n const bh = evenFloor(width / b)\n const top = Math.floor((canvas.h - th - bh) / 2)\n const left = Math.floor((canvas.w - width) / 2)\n return {\n top: { left, top, width, height: th },\n bottom: { left, top: top + th, width, height: bh },\n }\n}\n\n/** A picture placed on the output canvas: its even rect and how it fills it (contain = scaled to the rect, cover = cropped to it). */\nexport interface VideoOverlayPlacedRect {\n readonly drawn: VideoOverlayRect\n readonly fit: VideoOverlayFit\n}\n\n/** A video layer to place. */\nexport interface PlacedVideoOverlayVideoInput {\n /** 0-based index in the request's layers[] (what `firstVideo` names). */\n readonly index: number\n readonly layer: Pick<VideoOverlayLayer, \"anchor\" | \"x\" | \"y\" | \"width\" | \"height\" | \"fit\">\n /** Its display aspect (width ÷ height, rotation and sample aspect resolved); held inside the bounds here. */\n readonly aspect: number\n}\n\nexport interface VideoOverlayVideoPlacement {\n /** Present when the base is placed (a stack or a base box); absent = the base as before (its own size, or `outputAspect` with `baseFit`). */\n readonly basePlacement?: VideoOverlayPlacedRect\n /** Each video layer's even drawn rect and fit, by request index. */\n readonly layers: ReadonlyMap<number, VideoOverlayPlacedRect>\n}\n\n/**\n * Where the base and every video layer draw, on the output canvas — the ONE\n * placement the worker renders with and the canvas preview draws with. Every\n * aspect goes through `clampVideoOverlayAspect` and every rect through\n * `evenVideoOverlayRect` here, so neither caller can skip them.\n * - A stack (`stack-whole` / `stack-filled`): both rects from\n * `resolveVideoOverlayStackRects` with the base's and the first video\n * layer's aspects; that layer's stored box is not read. `stack-filled` draws\n * both `cover`, `stack-whole` both `contain`, whatever fit is stored.\n * - Otherwise a base box (written by `video-bottom` / `video-top`, or explicit)\n * places the base with `resolveVideoOverlayBaseRect` at its own fit.\n * - Every other video layer: its box, `resolveVideoOverlayGeometry`, at its\n * aspect (`pip` has already written its box).\n * An image layer is not placed here: its geometry is unchanged. The caller\n * passes a stack's first video layer among `videos` (the worker refuses a\n * stack whose first video layer it does not keep). Pure.\n */\nexport function placeVideoOverlayVideos(input: {\n readonly canvas: VideoOverlayCanvas\n readonly layout?: string | null\n readonly baseBox?: VideoOverlayBox\n readonly baseAspect: number\n /** `firstVideoLayerIndex` of the request's layers: what a stack places under the base. */\n readonly firstVideo: number\n readonly videos: ReadonlyArray<PlacedVideoOverlayVideoInput>\n}): VideoOverlayVideoPlacement {\n const { canvas, layout } = input\n const baseAspect = clampVideoOverlayAspect(input.baseAspect)\n const layers = new Map<number, VideoOverlayPlacedRect>()\n let basePlacement: VideoOverlayPlacedRect | undefined\n if (layout === \"stack-whole\" || layout === \"stack-filled\") {\n const first = input.videos.find((v) => v.index === input.firstVideo)\n if (!first) throw new Error(`placeVideoOverlayVideos: the stacked layer ${input.firstVideo} was not kept`)\n const rects = resolveVideoOverlayStackRects(layout, canvas, baseAspect, clampVideoOverlayAspect(first.aspect))\n const fit: VideoOverlayFit = layout === \"stack-filled\" ? \"cover\" : \"contain\"\n basePlacement = { drawn: evenVideoOverlayRect(rects.top), fit }\n layers.set(first.index, { drawn: evenVideoOverlayRect(rects.bottom), fit })\n } else if (input.baseBox) {\n basePlacement = { drawn: evenVideoOverlayRect(resolveVideoOverlayBaseRect(canvas, input.baseBox, baseAspect)), fit: input.baseBox.fit }\n }\n for (const v of input.videos) {\n if (layers.has(v.index)) continue\n const { drawn } = resolveVideoOverlayGeometry(canvas, v.layer, clampVideoOverlayAspect(v.aspect))\n layers.set(v.index, { drawn: evenVideoOverlayRect(drawn), fit: v.layer.fit })\n }\n return { ...(basePlacement ? { basePlacement } : {}), layers }\n}\n\n/**\n * Where a placed base draws, in output pixels. Its SIZE is the layer\n * geometry's drawn size (`resolveVideoOverlayGeometry`: the same clamp and even\n * rounding as an image layer); it is then placed by that drawn size against the\n * anchor, plus the x / y offsets — so a contained base sits flush on its\n * anchored edge rather than centred in a box rounded to other numbers (a 16:9\n * base at the bottom of 1080x1920 draws at y 1314–1920, with no strip under it).\n */\nexport function resolveVideoOverlayBaseRect(canvas: VideoOverlayCanvas, box: VideoOverlayBox, baseAspect: number): VideoOverlayRect {\n const { drawn } = resolveVideoOverlayGeometry(canvas, box, baseAspect)\n const ax = box.anchor.endsWith(\"left\") ? 0 : box.anchor.endsWith(\"right\") ? 1 : 0.5\n const ay = box.anchor.startsWith(\"top\") ? 0 : box.anchor.startsWith(\"bottom\") ? 1 : 0.5\n return {\n left: Math.round(ax * (canvas.w - drawn.width) + (box.x / 100) * canvas.w),\n top: Math.round(ay * (canvas.h - drawn.height) + (box.y / 100) * canvas.h),\n width: drawn.width,\n height: drawn.height,\n }\n}\n","/**\n * Video-analysis node — shared data contract.\n *\n * Single source of truth for the video-analysis node: the backend worker, the\n * frontend, and a future generator all import from here. Two schema layers:\n * - `windowAnalysisSchema` — what the LLM emits per analysis window\n * (strict-JSON footer). `scenes` has NO min (a quiet window returning zero\n * scenes is a VALID result). Model-emitted `oversized`/`slotRefs` are\n * STRIPPED here — they are validator-computed later (z.object drops unknown\n * keys by default).\n * - `videoAnalysisResultSchema` — the merged, validator-computed result across\n * all windows; requires >=1 scene overall.\n *\n * Entity slots are referenced in scene `visual` text via `{slot:<id>}` tokens\n * (`SLOT_TOKEN_RE`) — a grammar distinct from `NODE_REF_PATTERN` and the\n * `{image:N}` reference tokens. Unresolved tokens UNWRAP to their literal id\n * text, never delete (spec invariant), so a downstream prompt never carries a\n * dangling `{slot:…}` placeholder.\n */\nimport { z } from \"zod\"\n\nexport const VIDEO_ANALYSIS_MAX_SCENE_SEC = 8\n\n/**\n * Camera VIEWPOINT — where the camera is relative to the subject. The axis\n * `shotType` does not carry, and the one the analyzer had been improvising.\n *\n * Two failures this fixes, both from real jobs:\n *\n * 1. `shotType` is framing SIZE (Wide … Extreme Close-Up), so a true angle had\n * nowhere to go and landed in the MOVEMENT field instead:\n * `\"camera\": \"low angle static\"`. That loses the angle to anything reading\n * `camera` and pollutes the movement vocabulary.\n * 2. The relational viewpoints — `Over-the-Shoulder`, `POV` — were conventions\n * inside the `shotType` list, competing with the sizes for one slot. So an\n * over-the-shoulder MEDIUM had to pick one and threw the other away. They\n * belong here, leaving `shotType` free to state the size: an OTS medium is\n * `shotType: \"Medium\"` + `angle: \"over-the-shoulder\"`, which is strictly more\n * than either field could carry alone.\n *\n * A closed enum rather than free text precisely because improvisation is the\n * failure being fixed. Absent means EYE-LEVEL — the overwhelming default, so\n * omitting it costs nothing on most shots (the same \"absence is the default\"\n * shape as `transitionOut` and appearance variations).\n *\n * `from-behind` and `over-the-shoulder` also carry real meaning downstream: a\n * face is not visible in either, which is what auto-cast needs to know before\n * choosing one as an identity reference.\n */\nexport const VIDEO_ANALYSIS_SHOT_ANGLES = [\n // Vertical placement and roll — the classical \"angles\".\n \"eye-level\", \"low\", \"high\", \"overhead\", \"worms-eye\", \"dutch\",\n // Relational viewpoints — where the camera sits with respect to the subject.\n \"over-the-shoulder\", \"pov\", \"profile\", \"from-behind\",\n] as const\nexport type VideoAnalysisShotAngle = (typeof VIDEO_ANALYSIS_SHOT_ANGLES)[number]\n\n/** Viewpoints in which the subject's FACE is not visible — so a frame shot this\n * way is a poor identity reference however good its framing otherwise is. */\nexport const VIDEO_ANALYSIS_FACELESS_ANGLES: ReadonlySet<string> = new Set([\"over-the-shoulder\", \"from-behind\"])\n\n/**\n * Effects applied to the PICTURE of a shot. An array — a shot can be grainy and\n * vignetted at once — and absent when the image is clean, which is most shots.\n *\n * Scoped deliberately to things done to the IMAGE, and NOT to compositing that\n * asserts what is in the shot (picture-in-picture, split screen). That line\n * matters: a real job invented `{slot:creator} overlay talking to camera` across\n * nine scenes for a man who is never seen, so a field for \"there is an inset of a\n * person here\" would hand that fabrication a legitimate home. An effect is\n * verifiable in the pixels; a claim about who is inset is not.\n *\n * `dissolve` and `fade` are NOT here either — they are edits BETWEEN shots and\n * belong to `transitionOut`.\n */\nexport const VIDEO_ANALYSIS_VISUAL_EFFECTS = [\n \"blur\", \"pixelate\", \"glitch\", \"grain\", \"vignette\", \"flash\", \"distortion\", \"double-exposure\",\n] as const\nexport type VideoAnalysisVisualEffect = (typeof VIDEO_ANALYSIS_VISUAL_EFFECTS)[number]\n\n/**\n * Visible edit INTO the next shot.\n *\n * `dissolve` (a cross-fade from one image to the other) is distinct from `fade`\n * (through black or white). Collapsing both onto `fade` — as this enum did — makes\n * a recreation render the wrong edit, and the two look nothing alike.\n *\n * ABSENT means NOTHING ASSERTED (since v2): the analyser emits a value only\n * when it can see the device; an unknown or uncertain edit is left out so the\n * video model chooses. `cut` is itself an assertion (an instant change between\n * two clearly different shots), never a default.\n */\nexport const VIDEO_ANALYSIS_TRANSITIONS = [\n \"cut\", \"fade\", \"dissolve\", \"wipe\", \"whip\",\n // v2 (2026-08-30, recast shot craft rev 1.5 Appendix F): the common edits a\n // creator actually cuts with. `white-flash` / `digital-glitch` are spelled\n // out because `flash` / `glitch` already name in-shot EFFECTS (the axis test\n // below) — a device is the edit BETWEEN two shots, an effect is on one shot.\n \"zoom\", \"slide\", \"white-flash\", \"digital-glitch\", \"morph\", \"match\", \"jump\",\n] as const\nexport type VideoAnalysisTransition = (typeof VIDEO_ANALYSIS_TRANSITIONS)[number]\n\n/**\n * What burned-in text IS (2026-08-28, recast shot craft). Decides render-vs-omit\n * downstream: a `subtitle` is a transcription of the piece's own speech — a\n * recreation re-speaks it and must not render it — while a `title`, `caption`,\n * `lower-third` or `logo` is picture content. Absent when a scene carries no\n * text. A new KEY on the scene: strip-mode readers drop it harmlessly.\n */\nexport const VIDEO_ANALYSIS_TEXT_KINDS = [\"title\", \"caption\", \"lower-third\", \"subtitle\", \"logo\", \"other\"] as const\nexport type VideoAnalysisTextKind = (typeof VIDEO_ANALYSIS_TEXT_KINDS)[number]\n\n/** How the CLIP opens (clip-level, not per scene — a window's first scene is\n * not the clip's). Absent ⇒ a hard open. Only `fade` today. */\nexport const VIDEO_ANALYSIS_CLIP_TRANSITIONS_IN = [\"fade\"] as const\nexport type VideoAnalysisClipTransitionIn = (typeof VIDEO_ANALYSIS_CLIP_TRANSITIONS_IN)[number]\n\n/**\n * Time manipulation — slow motion, ramps, timelapse, freeze, reverse.\n *\n * Previously unrepresentable anywhere in the schema, so a recreation rendered\n * every shot at normal speed no matter what the footage did. It is a first-class\n * lever in every video model and a real editing decision in most action footage.\n *\n * `\"normal\"` is deliberately NOT a member: absence is normal speed, so there is\n * exactly one way to say \"nothing unusual here\" and the field costs nothing on\n * the majority of shots.\n */\nexport const VIDEO_ANALYSIS_SPEED_EFFECTS = [\"slow-motion\", \"ramp-in\", \"ramp-out\", \"timelapse\", \"freeze\", \"reverse\"] as const\n\n/** CHRONICLE TIME (2026-08-17): the STORY clock, per scene, as read from the\n * pictures — light, sky, practicals. \"ambiguous\" is the honest answer for a\n * windowless interior; guessing day is exactly the kind of tidy inference\n * the analysis doctrine forbids. */\nexport const VIDEO_ANALYSIS_TIMES_OF_DAY = [\"dawn\", \"day\", \"dusk\", \"night\", \"ambiguous\"] as const\n\n/** STORY JUMP since the PREVIOUS scene in the list: how much narrative time\n * passed across the cut, judged from evidence (wardrobe change, aged\n * subjects, season, a title card), not from the cut itself. Time outranks\n * location for continuity judgements (same person, new place, continuous\n * time ⇒ same outfit; same place, years later ⇒ anything may differ), which\n * is why this is a structured field and not prose. \"unclear\" is the honest\n * default; the FIRST scene of a clip is \"continuous\" by convention. */\nexport const VIDEO_ANALYSIS_STORY_JUMPS = [\"continuous\", \"same-day\", \"another-day\", \"years-later\", \"unclear\"] as const\nexport type VideoAnalysisSpeedEffect = (typeof VIDEO_ANALYSIS_SPEED_EFFECTS)[number]\n\n/**\n * The CLIP-LEVEL look — one source of truth for the properties that belong to\n * the whole piece rather than any one shot.\n *\n * Colour grade, camera format and lens character were previously only ever prose\n * inside each scene's `visual`, which meant a 43-scene analysis re-decided the\n * grade forty-three independent times with nothing holding them consistent. That\n * is the same drift problem entity slots solve for people: state it once, apply it\n * everywhere. A recreation reads this alongside every scene.\n *\n * Every field optional — an analyzer that cannot read the format should say\n * nothing rather than guess, and a per-scene deviation still belongs in that\n * scene's `visual` prose.\n */\nexport const clipLookSchema = z.object({\n /**\n * The rendering MEDIUM — \"live-action photoreal\", \"2D anime\", \"stop-motion\n * claymation\", \"3D render\", \"oil painting\", \"pixel art\".\n *\n * The most consequential field in this object, and orthogonal to every other\n * one: two shots with identical grade, lens, lighting and framing still look\n * nothing alike when one is live action and the other is an oil painting. Get\n * this wrong and a recreation renders the whole piece in the wrong medium,\n * which no amount of correct grade or lighting can rescue.\n *\n * Mirrors the product's Style picker, whose catalog defines exactly this axis\n * and states its independence from lighting, colour-look, atmosphere and lens.\n * A clip that genuinely changes medium partway (live action with an animated\n * insert) states the deviation in that scene's `visual`, as with `lighting`.\n */\n style: z.string().optional(),\n /**\n * The Style picker CATALOG ID the prose in `style` corresponds to — the\n * analyzer's PICK (\"pixar-3d\" beside \"3D stylized animation\"), not a second\n * description of it.\n *\n * Worth strictly more than the prose it accompanies: an id addresses the\n * catalog, so a recreation renders the same medium the product's own Style\n * picker would render, instead of re-interpreting a sentence. Absent when the\n * analyzer read a medium it could not place in the catalog — `style` then\n * carries the whole answer, as it always did.\n *\n * A free `string` here on purpose. The PRODUCER validates it against the\n * catalog (the analyzer plugin's wire schema is an enum generated from\n * `STYLES`, so an invented id never leaves it), while this package must not\n * carry the catalog itself. A closed enum here would only add a second copy\n * of the vocabulary to drift out of date — and, worse, would REJECT a\n * catalog entry newer than the installed `@nodaro/shared`, which is exactly\n * the analysis a consumer most wants to read.\n */\n styleId: z.string().optional(),\n /** Colour grade / palette — \"muted teal-and-orange, crushed blacks\". */\n grade: z.string().optional(),\n /** Camera or film FORMAT and stock — \"anamorphic digital\", \"16mm film grain\". */\n format: z.string().optional(),\n /** Lens character — \"wide-angle, shallow depth of field throughout\". */\n lens: z.string().optional(),\n /** Overall lighting style — \"hard single-source daylight, deep shadow\". */\n lighting: z.string().optional(),\n /** What KIND of piece this is — \"cinematic trailer\", \"talking-head vlog\". */\n genre: z.string().optional(),\n /**\n * The visual INFLUENCE the piece clearly evokes — a cinematographer, director,\n * photographer or named aesthetic (\"shot like Deakins\", \"Wes Anderson\n * symmetry\", \"80s Kodachrome editorial\").\n *\n * The highest-leverage field here by a distance: a couple of words transfer a\n * whole aesthetic that would otherwise take a paragraph of grade, lens and\n * lighting prose to approximate — which is exactly why the product already\n * exposes it as a curated picker (\"Photographer / Artist\") whose catalog ships\n * `in the style of …` prompt hints. The analyzer had no way to read it back.\n *\n * Deliberately conservative: OMIT unless the footage genuinely evokes a\n * well-known, nameable style. A confident misattribution is worse than silence,\n * because it drags an entire wrong aesthetic into every regenerated shot — so\n * describing the look in `grade`/`lighting` always beats guessing a name.\n */\n influence: z.string().optional(),\n})\nexport type ClipLook = z.infer<typeof clipLookSchema>\nexport const VIDEO_ANALYSIS_ENTITY_SOURCES = [\"wired-character\", \"wired-object\", \"wired-location\", \"wired-creature\"] as const\nexport type VideoAnalysisEntitySource = (typeof VIDEO_ANALYSIS_ENTITY_SOURCES)[number]\n/** Matches {slot:<id>} tokens. Distinct from NODE_REF_PATTERN / {image:N} grammars. */\nexport const SLOT_TOKEN_RE = /\\{slot:([a-z0-9-]+)\\}/g\n\n/**\n * Appearance variations (cast-variations spec, 2026-07-24): a slot's canonical\n * `description` IS its default look; `variations` enumerates NON-default looks\n * only (dream vs reality, flashback, disguise…). `\"default\"` is a reserved\n * variationId — used in scene bindings / ledger keys / routing for unbound\n * scenes, never inside `variations[]`. The closed slug vocabulary is\n * doctrine-enforced (the schema pins only the id charset, like `role`);\n * `alt-1`/`alt-2` are the escape hatches.\n */\nexport const VIDEO_ANALYSIS_VARIATION_SLUGS = [\"dream\", \"flashback\", \"disguise\", \"costume\", \"transformation\", \"era\", \"alt-1\", \"alt-2\"] as const\n/** Max NON-default looks per slot. The window layer REJECTS past the cap (schema-forced retry); the cross-window merge FOLDS at the cap. */\nexport const VIDEO_ANALYSIS_MAX_VARIATIONS = 4\nexport const VIDEO_ANALYSIS_DEFAULT_VARIATION = \"default\"\n\nexport const slotVariationSchema = z.object({\n variationId: z.string().min(1).regex(/^[a-z0-9-]+$/)\n .refine((id) => id !== VIDEO_ANALYSIS_DEFAULT_VARIATION, { message: `\"${VIDEO_ANALYSIS_DEFAULT_VARIATION}\" is reserved for the slot's canonical look` }),\n label: z.string().min(1),\n /** Full STANDALONE casting-sheet look restating the slot's invariant identity\n * core (face, build, age) — the manifest substitutes it wholesale, so a\n * wardrobe-only delta would silently delete identity from the prompt. */\n description: z.string().min(1),\n /** Per-variation identity reference (auto-cast frame or user sheet). In the\n * schema from day one: every strip-mode round-trip must carry it. */\n refImageUrl: z.string().url().optional(),\n})\nexport type SlotVariation = z.infer<typeof slotVariationSchema>\n\nexport const entitySlotSchema = z.object({\n slotId: z.string().min(1).regex(/^[a-z0-9-]+$/),\n label: z.string().min(1),\n source: z.enum(VIDEO_ANALYSIS_ENTITY_SOURCES),\n role: z.string().min(1),\n description: z.string().min(1),\n /** Auto-cast visual reference — a hosted frame from the analyzed footage\n * where this entity is clearly visible. Optional/additive: producers may\n * omit it; consumers use it as an identity reference for recreation. */\n refImageUrl: z.string().url().optional(),\n /**\n * Why `refImageUrl` is ABSENT, when the analyzer's vision pass actively\n * refused every candidate frame rather than merely failing to produce one.\n *\n * Present only alongside a missing `refImageUrl`, and only for a real refusal\n * — never for a technical failure, so its presence always carries meaning. The\n * important case reads like \"the shots bound to this slot show someone else —\n * cast as X, but on screen: Y\", which is the analyzer telling you the casting\n * description and the footage disagree. A consumer should treat that as a\n * reason to review the slot before spending on regeneration, since a wrong\n * identity propagates into every regenerated shot.\n */\n refRejectedReason: z.string().optional(),\n /** NON-default looks only; present only when at least one exists. */\n variations: z.array(slotVariationSchema).max(VIDEO_ANALYSIS_MAX_VARIATIONS).optional(),\n /**\n * WHOSE THIS OBJECT IS (2026-09-17). An object slot that is worn, held,\n * carried, driven or ridden by a cast person or creature names that slot\n * here, with the relation as a short passive phrase ending in \"by\" (\"worn\n * by\", \"held by\", \"driven by\"). The link says the object slot IS the one on\n * that person — not a second one: a recast that saw \"Man in Blue Silk\n * Shirt\" AND \"Blue Silk Shirt\" as unrelated slots rendered two shirts.\n * Object slots only; a free-standing prop, the product on a table, a place\n * or a person never carries it. Optional/additive: producers may omit it.\n */\n owner: z.object({\n slotId: z.string().min(1).regex(/^[a-z0-9-]+$/),\n relation: z.string().min(1),\n }).optional(),\n})\nexport type EntitySlot = z.infer<typeof entitySlotSchema>\nexport type EntitySlotOwner = NonNullable<EntitySlot[\"owner\"]>\n\n/**\n * The sound LAYER vocabulary — what kind of thing this layer is.\n *\n * `ambience` is deliberately its own member rather than a flavour of `sfx`:\n * they are different layers of a real mix and they are recreated by different\n * means — ambience is the continuous bed a scene sits in (room tone, distant\n * traffic, wind), an sfx is a discrete hit (a door slam, a gunshot). Folded\n * together, a scene's bed and its one-off noises arrive indistinguishable and\n * anything recreating the mix has to guess which it was told.\n *\n * Exported so a consumer keying its own document by these modes imports the\n * vocabulary instead of restating it — the same reason every other closed\n * vocabulary in this file is a const.\n */\nexport const VIDEO_ANALYSIS_AUDIO_MODES = [\"speech\", \"music\", \"sfx\", \"ambience\"] as const\nexport type VideoAnalysisAudioMode = (typeof VIDEO_ANALYSIS_AUDIO_MODES)[number]\n\n/**\n * One concurrent sound layer in a scene. Real footage stacks sound (music bed\n * under dialogue over ambient room tone), so a scene carries an ARRAY of these\n * — an empty array means genuine silence. `content`: speech = verbatim words;\n * music/sfx/ambience = gen-ready description. `voice` is speech-only\n * voice-casting.\n */\nconst audioLayerSchema = z.object({\n mode: z.enum(VIDEO_ANALYSIS_AUDIO_MODES),\n content: z.string().min(1),\n voice: z.string().optional(),\n /**\n * SPEECH ONLY — `slotId` of the on-screen speaker saying these words.\n *\n * `voice` casts a voice (\"male, proud triumphant shouting\"); this says WHO it\n * belongs to, so a recreation can route the line to the right character\n * instead of guessing. Usually one person speaks per scene and the guess is\n * right, which is exactly why the cases with two speakers over one cut fail\n * silently without this field.\n *\n * Optional by design and deliberately NOT refined against `mode` here: the\n * window schema is the enforced decode grammar, and rejecting a whole roll\n * because the model tagged a music layer would be a hair-trigger failure. A\n * speaker on a non-speech layer, or one naming a slot that no longer exists,\n * is stripped structurally by `dropUnknownSpeakers` — the same\n * unwrap/drop/sweep philosophy the slot-token and binding channels use.\n *\n * An unseen narrator gets NO speaker: a voice with no body is never a slot\n * (doctrine §5), so attribution here would resurrect the phantom-entity\n * defect that `stripOrphanSlots` exists to kill.\n */\n speakerSlot: z.string().optional(),\n /**\n * SPEECH ONLY — WHO says these words, by NAME.\n *\n * The second of two ways to name a speaker, and the one for documents that\n * have no slots: `speakerSlot` addresses an `EntitySlot` of THIS analysis by\n * id, while `speaker` is the plain cast name a production keys its own cast\n * by (\"Jack Mercer\"). A layer may legitimately carry both — the id for the\n * analysis it came from, the name for the document it is going into — and a\n * consumer that understands only one reads the one it understands.\n *\n * Optional, and not refined against `mode`, for the same reason\n * `speakerSlot` is not: the window schema is the enforced decode grammar and\n * must not throw away a whole roll over one mis-tagged field.\n *\n * NOT swept by `dropUnknownSpeakers`. That function is the SLOT channel's\n * sanitizer — it judges an id against the surviving slot list, and a name has\n * no id space to be unknown in. The asymmetry is deliberate and pinned by\n * test; whoever owns the name's vocabulary sanitizes the name.\n *\n * The residual that leaves: a layer can keep a `speaker` naming someone\n * `stripOrphanSlots` already pruned as a phantom, where the same claim spelled\n * `speakerSlot` would have been dropped — the invented-narrator defect, in the\n * one spelling the sweep cannot see. LATENT today, since nothing in this\n * repo emits `speaker`; the day the analyzer does, that sweep is what has to\n * grow, not this field.\n */\n speaker: z.string().optional(),\n})\nexport type AudioLayer = z.infer<typeof audioLayerSchema>\n\nconst windowSceneBase = z.object({\n startSec: z.number().min(0),\n endSec: z.number().min(0),\n label: z.string().min(1),\n shotType: z.string().min(1),\n camera: z.string(),\n /** Camera VIEWPOINT. Absent ⇒ eye-level. Keeps `camera` to pure MOVEMENT and\n * frees `shotType` to state the SIZE even on an over-the-shoulder or POV. */\n angle: z.enum(VIDEO_ANALYSIS_SHOT_ANGLES).optional(),\n /** Time manipulation. Absent ⇒ normal speed. */\n speed: z.enum(VIDEO_ANALYSIS_SPEED_EFFECTS).optional(),\n /** CHRONICLE TIME (2026-08-17) — see the consts' docstrings. Both optional:\n * absent on every pre-2.6.0 analysis, and legitimately absent when the\n * analyser cannot read the clock. Enum + optional keeps the window decode\n * grammar congruence-safe (no ints, no maxItems). */\n timeOfDay: z.enum(VIDEO_ANALYSIS_TIMES_OF_DAY).optional(),\n storyJump: z.enum(VIDEO_ANALYSIS_STORY_JUMPS).optional(),\n visual: z.string().min(1),\n /**\n * Text burned into the PICTURE of this shot — titles, captions, lower-thirds,\n * subtitles — verbatim, in its original script. Absent when the frame carries\n * none.\n *\n * Doctrine already asks for on-screen text inside `visual` prose, but a\n * recreation needs to know discretely whether to RENDER text at all, and\n * `translateOnScreenTextToEnglish` had no structured field to land in. It is\n * also the signal the auto-cast frame judge reads: picture text belonging to an\n * earlier scene's speech means the shot is replayed footage under a voice-over.\n */\n onScreenText: z.string().optional(),\n /** What the on-screen text IS. Meaningful only when `onScreenText` is non-empty. */\n onScreenTextKind: z.enum(VIDEO_ANALYSIS_TEXT_KINDS).optional(),\n /** Effects on this shot's PICTURE. Absent ⇒ a clean image. */\n effects: z.array(z.enum(VIDEO_ANALYSIS_VISUAL_EFFECTS)).optional(),\n transitionOut: z.enum(VIDEO_ANALYSIS_TRANSITIONS).optional(),\n // Round 4 (2026-08-30, recast shot craft rev 1.5 Appendix F.8): the edit into\n // the next scene in the analyser's OWN WORDS — a few words of what it saw\n // (\"fast blurred pan left\", \"fade to black\", \"zoom-blur warp into the tunnel\")\n // — or absent when the take continues through the change or no edit is seen\n // (nothing asserted: the video model decides from story and refs). The closed\n // `transitionOut` vocabulary above is LEGACY from here on: kept so stored\n // blueprints still parse, never emitted again. Readers take\n // `transition ?? transitionOut`.\n transition: z.string().trim().min(1).max(120).optional(),\n // Array of concurrent layers (music + speech + sfx together); [] = silence.\n audio: z.array(audioLayerSchema),\n /** slotId → variationId for slots wearing a NON-default look in this scene\n * (only slots referenced in the scene; absent key ⇒ the default look).\n * Rides windowSceneBase so BOTH the window layer and analyzedSceneSchema\n * inherit it — the out-of-band binding channel (no in-text markers, D6). */\n slotVariations: z.record(z.string(), z.string()).optional(),\n})\n// .strip() (default) drops model-emitted oversized/slotRefs — validator-computed only.\nconst windowSceneSchema = windowSceneBase.refine((s) => s.endSec > s.startSec, { message: \"endSec must be > startSec\" })\nexport type WindowScene = z.infer<typeof windowSceneSchema>\n\n/** What the MODEL emits per window (strict-JSON footer schema). scenes has NO min. */\nexport const windowAnalysisSchema = z.object({\n language: z.string().optional(),\n /** The clip-level look as read from THIS window. Merge folds the windows\n * field-by-field (first non-empty wins), like `language`. */\n look: clipLookSchema.optional(),\n /** The clip opens with a fade-in. Folded from window 0 only. */\n transitionIn: z.enum(VIDEO_ANALYSIS_CLIP_TRANSITIONS_IN).optional(),\n slots: z.array(entitySlotSchema),\n scenes: z.array(windowSceneSchema),\n})\nexport type WindowAnalysis = z.infer<typeof windowAnalysisSchema>\n\nexport const analyzedSceneSchema = windowSceneBase.extend({\n sceneNumber: z.number().int().min(1),\n visualResolved: z.string().min(1),\n oversized: z.boolean().optional(),\n slotRefs: z.array(z.string()),\n}).refine((s) => s.endSec > s.startSec, { message: \"endSec must be > startSec\" })\nexport type AnalyzedScene = z.infer<typeof analyzedSceneSchema>\n\nexport const videoAnalysisResultSchema = z.object({\n meta: z.object({\n durationSec: z.number().positive(),\n width: z.number().int().positive(),\n height: z.number().int().positive(),\n aspectRatio: z.string(),\n title: z.string().optional(),\n language: z.string().optional(),\n }),\n /** Clip-level look, merged across windows. Deliberately a sibling of `meta`\n * rather than a member: `meta` is probed fact (ffprobe dimensions, probed\n * duration), while this is the model's reading of the photography. */\n look: clipLookSchema.optional(),\n /** The clip opens with a fade-in. Folded from window 0 only. */\n transitionIn: z.enum(VIDEO_ANALYSIS_CLIP_TRANSITIONS_IN).optional(),\n slots: z.array(entitySlotSchema),\n scenes: z.array(analyzedSceneSchema).min(1),\n /** CAST VARIATIONS (§4 cap handling): looks the analyzer's merge FOLDED into\n * the default at VIDEO_ANALYSIS_MAX_VARIATIONS — recorded, never silent. In\n * the wire schema so strip-mode consumers (the recast client's validated\n * blueprint view) keep it: the §6 \"folded into default look\" note is the\n * user's only pre-pay defense against a wrong split. */\n variationFolds: z.array(z.object({\n slotId: z.string(),\n variationId: z.string(),\n label: z.string(),\n })).optional(),\n /**\n * Analyzer diagnostics for THIS result — things the analysis noticed about\n * itself that a reader should know before spending on regeneration.\n *\n * Added because there was previously no channel for them at all: the merge\n * layer has always produced a warnings list and the auto-cast pass has always\n * had findings, and every one of them died in a `console.warn` inside a worker\n * the user cannot see. So a run could quietly drop a duplicated line, fold a\n * cast look, or conclude a character is not the person their own description\n * names, and the result looked indistinguishable from a clean one.\n *\n * Prose, not codes, and deliberately so — these are read by a human deciding\n * whether to re-run, not branched on. Absent when there is nothing to report.\n */\n warnings: z.array(z.string()).optional(),\n})\nexport type VideoAnalysisResult = z.infer<typeof videoAnalysisResultSchema>\n\nexport function deriveSlotRefs(visual: string): string[] {\n const out: string[] = []\n for (const m of visual.matchAll(SLOT_TOKEN_RE)) if (!out.includes(m[1])) out.push(m[1])\n return out\n}\n\nexport function rewriteSlotTokens(visual: string, renames: Record<string, string>): string {\n return visual.replace(SLOT_TOKEN_RE, (whole, id: string) => (renames[id] ? `{slot:${renames[id]}}` : whole))\n}\n\n/** Unresolved tokens unwrap to their literal id text — never deleted (spec invariant). */\nexport function unwrapUnresolvedTokens(text: string, validIds: Set<string>): { text: string; unresolved: string[] } {\n const unresolved: string[] = []\n const out = text.replace(SLOT_TOKEN_RE, (whole, id: string) => {\n if (validIds.has(id)) return whole\n if (!unresolved.includes(id)) unresolved.push(id)\n return id\n })\n return { text: out, unresolved }\n}\n\n/**\n * Rewrite a scene's `slotVariations` after cross-window slot/variation\n * unification: slot keys map through `slotRenames`, then each variation value\n * maps through `variationRenames[<new slotId>]`. Absent renames pass through.\n */\nexport function rewriteSceneBindings(\n sv: Record<string, string> | undefined,\n slotRenames: Record<string, string>,\n variationRenames?: Record<string, Record<string, string>>,\n): Record<string, string> | undefined {\n if (!sv) return undefined\n const out: Record<string, string> = {}\n for (const [slotId, variationId] of Object.entries(sv)) {\n const newSlot = slotRenames[slotId] ?? slotId\n out[newSlot] = variationRenames?.[newSlot]?.[variationId] ?? variationId\n }\n return out\n}\n\n/**\n * Drop bindings whose (slotId, variationId) no longer exists after a merge —\n * the unwrap-rule mirror: never persist a dangling binding, and report what\n * was dropped so the caller can warn. `\"default\"` is always valid for a known\n * slot. `kept` is undefined when nothing survives (no `{}` materialization).\n */\nexport function dropUnknownBindings(\n sv: Record<string, string> | undefined,\n validBySlot: Map<string, Set<string>>,\n): { kept?: Record<string, string>; dropped: Array<{ slotId: string; variationId: string }> } {\n if (!sv) return { dropped: [] }\n const kept: Record<string, string> = {}\n const dropped: Array<{ slotId: string; variationId: string }> = []\n for (const [slotId, variationId] of Object.entries(sv)) {\n const valid = validBySlot.get(slotId)\n if (valid && (variationId === VIDEO_ANALYSIS_DEFAULT_VARIATION || valid.has(variationId))) kept[slotId] = variationId\n else dropped.push({ slotId, variationId })\n }\n return { kept: Object.keys(kept).length > 0 ? kept : undefined, dropped }\n}\n\n/**\n * Rewrite speech attribution after cross-window slot unification — the\n * `rewriteSceneBindings` counterpart for the `audio` channel. Slot unification\n * renames a loser id to its survivor and rewrites `{slot:…}` tokens and\n * variation bindings; an un-rewritten `speakerSlot` would be left pointing at an\n * id that no longer exists. Copy-on-write: returns the input array untouched\n * when no layer names a renamed slot.\n */\nexport function rewriteSpeakerSlots(audio: AudioLayer[], slotRenames: Record<string, string>): AudioLayer[] {\n if (!audio.some((a) => a.speakerSlot !== undefined && slotRenames[a.speakerSlot])) return audio\n return audio.map((a) => {\n const to = a.speakerSlot !== undefined ? slotRenames[a.speakerSlot] : undefined\n return to ? { ...a, speakerSlot: to } : a\n })\n}\n\n/**\n * Strip attribution that no scene can honour — the `dropUnknownBindings` mirror\n * for the `audio` channel. Two cases, both model sloppiness rather than errors\n * worth failing a roll over:\n * - a `speakerSlot` on any non-`speech` layer (nobody is speaking)\n * - a `speakerSlot` naming a slot that is not in the final list\n *\n * MUST run AFTER the orphan-slot sweep, and attribution must NEVER count as a\n * slot reference for that sweep: a slot reachable only as a speaker is a voice\n * with no body — precisely the invented-narrator entity doctrine §5 forbids. The\n * two passes compose to remove both the phantom slot and the dangling\n * attribution pointing at it.\n */\nexport function dropUnknownSpeakers(\n audio: AudioLayer[],\n validSlotIds: Set<string>,\n): { audio: AudioLayer[]; dropped: string[] } {\n const dropped: string[] = []\n const out = audio.map((a) => {\n if (a.speakerSlot === undefined) return a\n if (a.mode === \"speech\" && validSlotIds.has(a.speakerSlot)) return a\n dropped.push(a.speakerSlot)\n const { speakerSlot: _drop, ...rest } = a\n return rest\n })\n return { audio: dropped.length > 0 ? out : audio, dropped }\n}\n\n/**\n * Fold each window's reading of the clip look into one, FIELD BY FIELD: the first\n * window that had something to say about a field wins it.\n *\n * Per-field rather than first-window-wins-everything because the windows see\n * different footage — an opening window may read the grade confidently while only\n * a later one contains the shot that reveals the format. Mirrors how `language` is\n * resolved across windows rather than taken from window 0.\n *\n * Returns undefined when no window said anything, so an analysis with nothing to\n * report omits the field rather than shipping an empty object.\n */\nexport function mergeClipLook(looks: ReadonlyArray<ClipLook | undefined>): ClipLook | undefined {\n const out: Record<string, string> = {}\n for (const look of looks) {\n for (const [k, v] of Object.entries(look ?? {})) {\n if (typeof v === \"string\" && v.trim() && !out[k]) out[k] = v.trim()\n }\n }\n return Object.keys(out).length > 0 ? (out as ClipLook) : undefined\n}\n\n/** Substitute {slot:x}: castMap binding wins, else the slot's description, else literal id. */\nexport function renderAnalyzedScene(scene: { visual: string }, slots: EntitySlot[], castMap?: Record<string, string>): string {\n const byId = new Map(slots.map((s) => [s.slotId, s]))\n return scene.visual.replace(SLOT_TOKEN_RE, (_whole, id: string) => castMap?.[id] ?? byId.get(id)?.description ?? id)\n}\n\n/**\n * Float slack for the oversize comparison.\n *\n * Scene boundaries arrive as decimal seconds and the duration is derived by\n * SUBTRACTING two of them, which does not land on the cap exactly: a real job\n * produced a 12.67 → 20.67 scene whose computed length is 8.000000000000002,\n * so a scene sitting precisely ON the 8s cap was flagged oversized and carried\n * a `oversized: true` defect marker downstream for no reason.\n *\n * A microsecond is orders of magnitude below any boundary precision the\n * analyzer can actually resolve (windows land on ~0.01s at best), so this can\n * never mask a genuinely oversized scene — the smallest real overshoot is\n * still ~10000x larger than the tolerance.\n */\nconst OVERSIZE_TOLERANCE_SEC = 1e-6\n\nexport function isOversizedScene(startSec: number, endSec: number): boolean {\n return endSec - startSec > VIDEO_ANALYSIS_MAX_SCENE_SEC + OVERSIZE_TOLERANCE_SEC\n}\n\nconst STANDARD_RATIOS: Array<[string, number]> = [\n [\"16:9\", 16 / 9], [\"9:16\", 9 / 16], [\"1:1\", 1], [\"4:3\", 4 / 3], [\"3:4\", 3 / 4], [\"21:9\", 21 / 9],\n]\nexport function aspectRatioFromDims(w: number, h: number): string {\n const r = w / h\n for (const [label, v] of STANDARD_RATIOS) if (Math.abs(r - v) / v < 0.03) return label\n const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b))\n const g = gcd(Math.round(w), Math.round(h))\n return `${Math.round(w) / g}:${Math.round(h) / g}`\n}\n\n/** Sung-vocal evidence in a music layer's gen-ready description. Word-bounded\n * and deliberately WITHOUT bare \"song\"/\"music\" (an instrumental bed is\n * routinely described as a \"pop song\"). Quoted text of some length inside a\n * music layer counts too — analysers quote lyrics. */\nconst MUSIC_VOCAL_RE = /\\b(?:lyrics?|sung|sings?|singing|vocals?|chorus|verse|rap(?:ping|ped)?|a cappella)\\b/i\nconst MUSIC_VOCAL_QUOTE_RE = /[\"\\u201c][^\"\\u201d]{6,}[\"\\u201d]/\n/** Negated-vocal phrasing — a layer matching this contributes NO vocal\n * evidence (it does not veto other layers). */\nconst MUSIC_NO_VOCAL_RE = /\\b(?:no|without|non)[- ](?:vocals?|lyrics?|singing)\\b|\\binstrumental\\b|\\bwordless\\b/i\n\n/**\n * MUSIC-VIDEO INFERENCE (2026-08-17): is this clip a music video — one whose\n * soundtrack IS the content, to be taken as-is with no stem separation?\n *\n * Lives in SHARED because two sides must agree BYTE-FOR-BYTE on the answer:\n * the recast route derives `music.mode` from it server-side, and the client\n * both prices the original-audio prep and GUARDS on the server's derived mode\n * at generate time — two hand-written copies of this heuristic would drift\n * into that guard firing on honest runs. Deterministic, throw-proof on any\n * malformed analysis (absent fields ⇒ false).\n *\n * The rule is conservative toward FALSE (a false positive keeps unwanted\n * dialogue in the render; a false negative merely runs the separation, which\n * was yesterday's default): at least 4 scenes, at least 80% of scenes carry a\n * music layer, and at least one music layer carries sung-vocal evidence that\n * is not negated (\"instrumental\", \"no vocals\").\n *\n * An EXPLICIT analyze-time flag always wins — callers use\n * `flag === true || inferMusicVideo(analysis)` and never let a cached false\n * suppress the inference (the flag can only ever be set true; false means\n * \"unset\", not \"denied\").\n */\nexport function inferMusicVideo(analysis: {\n scenes?: ReadonlyArray<{ audio?: ReadonlyArray<{ mode?: string; content?: string }> }>\n} | undefined | null): boolean {\n const scenes = analysis?.scenes ?? []\n if (scenes.length < 4) return false\n const musicLayers = (sc: (typeof scenes)[number]) => (sc.audio ?? []).filter((a) => a?.mode === \"music\")\n const withMusic = scenes.filter((sc) => musicLayers(sc).length > 0).length\n if (withMusic / scenes.length < 0.8) return false\n return scenes.some((sc) =>\n musicLayers(sc).some((a) => {\n const content = typeof a.content === \"string\" ? a.content : \"\"\n if (MUSIC_NO_VOCAL_RE.test(content)) return false\n return MUSIC_VOCAL_RE.test(content) || MUSIC_VOCAL_QUOTE_RE.test(content)\n }),\n )\n}\n\n// ---------------------------------------------------------------------------\n// The analysis as a BRIEF — the compact projection an LLM is handed\n// ---------------------------------------------------------------------------\n\n/** Top-level keys the analyzer derives AFTER the model's pass (merge\n * diagnostics, folded cast looks). A reader drafting FROM the analysis — a\n * production plan, a script — needs none of them. */\nconst DERIVED_ANALYSIS_TOP_KEYS: ReadonlySet<string> = new Set([\"warnings\", \"variationFolds\"])\n\n/** Per-scene keys the validator computes from `visual` and the slot list. */\nconst DERIVED_ANALYSIS_SCENE_KEYS: ReadonlySet<string> = new Set([\"visualResolved\", \"slotRefs\", \"oversized\"])\n\nconst asRecord = (v: unknown): Record<string, unknown> | null =>\n typeof v === \"object\" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : null\n\n/**\n * The analysis with its server-derived fields removed — the form an LLM is\n * handed when the analysis IS the brief (Nodaro Studio's Director and its\n * job-id loader). Drops `warnings` and `variationFolds` at the top and\n * `visualResolved`, `slotRefs`, `oversized` on every scene; keeps\n * `refImageUrl` (a downstream cast image) and everything else. Never mutates;\n * a non-object input comes back as-is.\n *\n * ONE strip list, shared by the worker that composes the brief server-side\n * (`llm-structured` jobs with a `videoUrl`) and the client that loads a\n * finished analysis into a textarea, so the two can never drift.\n */\nexport function stripDerivedAnalysisFields(json: unknown): unknown {\n const doc = asRecord(json)\n if (!doc) return json\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(doc)) {\n if (DERIVED_ANALYSIS_TOP_KEYS.has(key)) continue\n out[key] =\n key === \"scenes\" && Array.isArray(value)\n ? value.map((scene) => {\n const s = asRecord(scene)\n if (!s) return scene\n return Object.fromEntries(Object.entries(s).filter(([k]) => !DERIVED_ANALYSIS_SCENE_KEYS.has(k)))\n })\n : value\n }\n return out\n}\n","/**\n * Real output canvases per (video model, resolution, aspect ratio).\n *\n * Every entry is a pixel size read off a finished render with ffprobe — the\n * geometry a model hands back, never a rate or a price. None of it is\n * arithmetic either, because the providers do not follow arithmetic:\n *\n * - minimax-h3 at 768P returns 768x1344 (0.5714) for a 9:16 request,\n * - seedance-2 at 480p 16:9 returns 864x496 (1.742) while seedance-2-5\n * returns 854x480 (1.778) for the same request,\n * - grok returns 736x400 (1.84), seedance 1.0 at 1080p 1:1 returns 1440x1440.\n *\n * A formula would get all four wrong, which is why `resolveOutputCanvas`\n * answers `undefined` for anything not measured: callers must then leave the\n * frame alone rather than invent geometry (see `computeFrameFitPlan`).\n *\n * HOW TO EXTEND: run `node tools/harvest-output-canvas.mjs` (it pages the admin\n * jobs API, groups completed video jobs by provider/resolution/aspect and probes\n * real outputs) and paste new rows here. Take rows from REFERENCE or\n * TEXT-TO-VIDEO jobs only: in frame mode the adaptive models (the seedance and\n * wan families) size the output from the INPUT image, so those rows describe the\n * input that was sent, not the canvas the model would choose on its own.\n *\n * Seeded 2026-09-16 from 3000 completed production jobs.\n */\n\n/** `[width, height]` in pixels. */\nexport type VideoOutputCanvas = readonly [number, number]\n\n/** provider → resolution (lower-cased) → aspect token → canvas. */\nexport const VIDEO_OUTPUT_CANVAS: Readonly<\n Record<string, Readonly<Record<string, Readonly<Record<string, VideoOutputCanvas>>>>>\n> = {\n \"seedance-2-5\": {\n \"480p\": { \"16:9\": [854, 480], \"9:16\": [480, 854] },\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280], \"1:1\": [960, 960] },\n \"1080p\": { \"16:9\": [1920, 1080] },\n },\n // The 2.0 family is NOT the same as 2.5 at 480p — 864x496 vs 854x480.\n \"seedance-2\": {\n \"480p\": { \"16:9\": [864, 496], \"9:16\": [496, 864] },\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n },\n \"seedance-2-fast\": {\n \"480p\": { \"16:9\": [864, 496], \"9:16\": [496, 864] },\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n },\n \"seedance-2-mini\": {\n \"480p\": { \"16:9\": [864, 496], \"9:16\": [496, 864] },\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n },\n \"gemini-omni-video\": {\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n \"1080p\": { \"16:9\": [1920, 1080] },\n },\n \"gemini-omni-flash\": {\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n },\n \"veo3.1\": {\n \"720p\": { \"9:16\": [720, 1280] },\n \"1080p\": { \"16:9\": [1920, 1080] },\n },\n \"wan-3\": {\n \"480p\": { \"16:9\": [832, 480] },\n \"720p\": { \"16:9\": [1280, 720], \"9:16\": [720, 1280] },\n },\n \"wan-3-prime\": {\n \"720p\": { \"16:9\": [1280, 720] },\n },\n // 768P's \"9:16\" is 0.5714, not 0.5625 — the single clearest reason this table\n // exists.\n \"minimax-h3\": {\n \"768p\": { \"9:16\": [768, 1344] },\n \"2k\": { \"16:9\": [2560, 1440], \"9:16\": [1440, 2560] },\n },\n}\n\n/**\n * The canvas a model renders for this request, or `undefined` when we have never\n * measured that combination. `undefined` means \"leave the frame alone\".\n *\n * Resolution matching is case-insensitive (`768P`, `2K`, `720p` all appear in\n * the wild). An aspect of `adaptive` / `Auto` has no canvas of its own — the\n * caller resolves it to a concrete ratio first (`resolveFrameFitAspect`).\n */\nexport function resolveOutputCanvas(\n provider: string | undefined,\n resolution: string | undefined,\n aspect: string | undefined,\n): VideoOutputCanvas | undefined {\n if (!provider || !resolution || !aspect) return undefined\n return VIDEO_OUTPUT_CANVAS[provider]?.[resolution.toLowerCase()]?.[aspect]\n}\n\n/** Every measured combination, for tests and for the harvest script's diff. */\nexport function measuredCanvasCombinations(): Array<{\n provider: string\n resolution: string\n aspect: string\n canvas: VideoOutputCanvas\n}> {\n const out: Array<{ provider: string; resolution: string; aspect: string; canvas: VideoOutputCanvas }> = []\n for (const [provider, byResolution] of Object.entries(VIDEO_OUTPUT_CANVAS)) {\n for (const [resolution, byAspect] of Object.entries(byResolution)) {\n for (const [aspect, canvas] of Object.entries(byAspect)) {\n out.push({ provider, resolution, aspect, canvas })\n }\n }\n }\n return out\n}\n","/**\n * START/END FRAME FIT — the pure geometry half.\n *\n * WHY THIS EXISTS (measured on ~40 production renders, 2026-09-16):\n * a start frame whose pixel size is not the model's own output canvas gets\n * reshaped by the provider, and Seedance 2.5 does it VISIBLY — frame 0 is the\n * user's image verbatim, then from frame 1 the generated frames are rescaled\n * ~2% on ONE axis (x1.000 y1.02). Five of ten runs with a 940x1672 image\n * snapped; three of three with the same image resized to 720x1280 did not.\n *\n * So: reshape the frame ourselves, to the size the model was going to render\n * anyway. The canvas comes from measurement (`video-output-canvas.ts`), never\n * from arithmetic, and when a combination has never been measured the fit\n * DEGRADES rather than guesses.\n *\n * This module is pure — no I/O, no sharp, no network. `prepareVideoFrames` in\n * the backend does the pixels and the upload.\n */\nimport { getModel } from \"./model-catalog.js\"\nimport { resolveOutputCanvas, type VideoOutputCanvas } from \"./video-output-canvas.js\"\n\n/** How much of the frame we are allowed to reshape. */\nexport const FRAME_FITS = [\"original\", \"ratio\", \"resolution\"] as const\nexport type FrameFit = (typeof FRAME_FITS)[number]\n\n/** `resolution` — the measured canvas — is the default everywhere. */\nexport const DEFAULT_FRAME_FIT: FrameFit = \"resolution\"\n\n/** How the frame is handed to the model. */\nexport const FRAME_DELIVERIES = [\"auto\", \"frame\", \"reference\"] as const\nexport type FrameDelivery = (typeof FRAME_DELIVERIES)[number]\n\nexport const DEFAULT_FRAME_DELIVERY: FrameDelivery = \"auto\"\n\n/**\n * Stretching an image to a ratio it is nowhere near would squash the subject,\n * so past this gap the frame is centre-cropped to the target ratio FIRST and\n * only then resized. 5% covers every \"1K image into a 720p canvas\" case we\n * measured (940x1672 into 9:16 is a 0.05% gap) while refusing to squash a\n * square photo into 9:16 (a 78% gap).\n */\nexport const FRAME_FIT_STRETCH_TOLERANCE = 0.05\n\n/**\n * Models whose frame mode is measurably worse than reference delivery.\n *\n * The Seedance 2.0 family crop-zooms the frame 2% and drifts 11-26% darker\n * within six frames in frame mode; delivered as a reference with the opening-\n * frame sentence, the same models hold a flat look from frame 0 and keep the\n * image's true geometry. Every OTHER model measured (Seedance 2.5, Gemini Omni\n * video + flash, Veo 3.1, Wan 3.0, Minimax H3) reproduces the opening frame\n * better in frame mode, so the default stays `frame` for anything absent here.\n */\nexport const FRAME_DELIVERY_BY_PROVIDER: Readonly<Record<string, Exclude<FrameDelivery, \"auto\">>> = {\n \"seedance-2\": \"reference\",\n \"seedance-2-fast\": \"reference\",\n \"seedance-2-mini\": \"reference\",\n}\n\n/** Aspect tokens that name no concrete shape — the model picks. */\nconst OPEN_ASPECT_TOKENS = new Set([\"adaptive\", \"auto\"])\n\n/** `\"16:9\"` → 1.777…; anything unparseable → `undefined`. */\nexport function parseAspectToken(token: string | undefined): number | undefined {\n if (!token) return undefined\n const m = /^(\\d+(?:\\.\\d+)?)\\s*[:x/]\\s*(\\d+(?:\\.\\d+)?)$/.exec(token.trim())\n if (!m) return undefined\n const w = Number(m[1]); const h = Number(m[2])\n if (!(w > 0) || !(h > 0)) return undefined\n return w / h\n}\n\n/**\n * The aspect the fit should target.\n *\n * An explicit ratio is used as-is. `adaptive` / `Auto` (and an absent value,\n * which the seedance family sends as adaptive whenever a frame is present) has\n * no shape of its own: the provider will follow the IMAGE, so we snap the\n * image's own ratio to the nearest one the model lists and target that. A model\n * with no declared ratio list and an open token gives `undefined` — no fit.\n */\nexport function resolveFrameFitAspect(args: {\n provider: string | undefined\n requestedAspect: string | undefined\n sourceWidth: number\n sourceHeight: number\n}): string | undefined {\n const requested = args.requestedAspect?.trim()\n if (requested && !OPEN_ASPECT_TOKENS.has(requested.toLowerCase())) return requested\n const ratios = args.provider ? getModel(args.provider)?.aspectRatios : undefined\n if (!ratios?.length || !(args.sourceWidth > 0) || !(args.sourceHeight > 0)) return undefined\n const source = args.sourceWidth / args.sourceHeight\n let best: { token: string; gap: number } | undefined\n for (const token of ratios) {\n const value = parseAspectToken(token)\n if (value === undefined) continue // skips \"adaptive\"/\"Auto\" members\n const gap = Math.abs(Math.log(value / source))\n if (!best || gap < best.gap) best = { token, gap }\n }\n return best?.token\n}\n\n/** What `prepareVideoFrames` should do to one frame. `null` = nothing. */\nexport interface FrameFitPlan {\n /** Final pixel size to produce. */\n readonly width: number\n readonly height: number\n /** Centre-crop applied BEFORE the resize (only past the stretch tolerance). */\n readonly crop?: { readonly left: number; readonly top: number; readonly width: number; readonly height: number }\n /** Why the plan exists — carried into logs and job output for traceability. */\n readonly reason: \"resolution\" | \"ratio\"\n}\n\n/** Round to an even number ≥ 2 — odd dimensions break yuv420p encoders. */\nfunction even(value: number): number {\n return Math.max(2, Math.round(value / 2) * 2)\n}\n\n/**\n * The smallest change that makes `width x height` exactly `aspect`: keep the\n * longer side, move the shorter one. Rounding to even can leave a sub-pixel\n * residue, which is why the caller compares ratios with a tolerance rather than\n * for equality.\n */\nexport function minimalRatioDimensions(width: number, height: number, aspect: number): { width: number; height: number } {\n const current = width / height\n if (current > aspect) {\n // too wide → bring the height up (keep the long side, the width)\n return { width: even(width), height: even(width / aspect) }\n }\n return { width: even(height * aspect), height: even(height) }\n}\n\n/**\n * The centre-crop that turns `width x height` into exactly `aspect`, dropping\n * the overhang on the long axis.\n */\nexport function centreCropToAspect(width: number, height: number, aspect: number): { left: number; top: number; width: number; height: number } {\n const current = width / height\n if (current > aspect) {\n const w = even(height * aspect)\n return { left: Math.max(0, Math.round((width - w) / 2)), top: 0, width: Math.min(width, w), height }\n }\n const h = even(width / aspect)\n return { left: 0, top: Math.max(0, Math.round((height - h) / 2)), width, height: Math.min(height, h) }\n}\n\n/**\n * Turn a request into a concrete plan for ONE frame, or `null` when the frame\n * should be sent untouched.\n *\n * Degradation ladder — a missing measurement must never invent geometry:\n * `resolution` with no measured canvas → behaves as `ratio`\n * `ratio` with no resolvable aspect → no fit\n * any fit whose target equals the source (within a pixel) → no fit\n */\nexport function computeFrameFitPlan(args: {\n fit: FrameFit\n provider: string | undefined\n resolution: string | undefined\n /** The aspect as the request carries it: a ratio, `adaptive`/`Auto`, or absent. */\n aspect: string | undefined\n sourceWidth: number\n sourceHeight: number\n /** Overrides the measured table (tests, and a caller that already looked up). */\n canvas?: VideoOutputCanvas\n tolerance?: number\n}): FrameFitPlan | null {\n const { fit, sourceWidth, sourceHeight } = args\n if (fit === \"original\") return null\n if (!(sourceWidth > 0) || !(sourceHeight > 0)) return null\n\n const aspectToken = resolveFrameFitAspect({\n provider: args.provider,\n requestedAspect: args.aspect,\n sourceWidth,\n sourceHeight,\n })\n\n const canvas = fit === \"resolution\"\n ? args.canvas ?? resolveOutputCanvas(args.provider, args.resolution, aspectToken)\n : undefined\n\n const targetAspect = canvas ? canvas[0] / canvas[1] : parseAspectToken(aspectToken)\n if (targetAspect === undefined || !(targetAspect > 0)) return null\n\n const sourceAspect = sourceWidth / sourceHeight\n const gap = Math.abs(sourceAspect - targetAspect) / targetAspect\n const tolerance = args.tolerance ?? FRAME_FIT_STRETCH_TOLERANCE\n const crop = gap > tolerance ? centreCropToAspect(sourceWidth, sourceHeight, targetAspect) : undefined\n\n const target = canvas\n ? { width: canvas[0], height: canvas[1] }\n : minimalRatioDimensions(\n crop ? crop.width : sourceWidth,\n crop ? crop.height : sourceHeight,\n targetAspect,\n )\n\n const unchanged = target.width === sourceWidth && target.height === sourceHeight && !crop\n if (unchanged) return null\n\n return {\n width: target.width,\n height: target.height,\n ...(crop ? { crop } : {}),\n reason: canvas ? \"resolution\" : \"ratio\",\n }\n}\n\n/**\n * Frame or reference? `auto` reads the per-provider default measured above.\n * Reference delivery is only possible on models that accept reference images —\n * on the others `reference` collapses back to `frame` rather than dropping the\n * frame on the floor.\n */\nexport function resolveFrameDelivery(args: {\n provider: string | undefined\n requested: FrameDelivery | undefined\n supportsReferenceImages: boolean\n}): Exclude<FrameDelivery, \"auto\"> {\n const requested = args.requested ?? DEFAULT_FRAME_DELIVERY\n const wanted = requested === \"auto\"\n ? (args.provider ? FRAME_DELIVERY_BY_PROVIDER[args.provider] ?? \"frame\" : \"frame\")\n : requested\n if (wanted === \"reference\" && !args.supportsReferenceImages) return \"frame\"\n return wanted\n}\n"]}