@nodaro/shared 3.33.0 → 3.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-2NQLSLSN.cjs → chunk-24ZKPE33.cjs} +5 -5
- package/dist/{chunk-2NQLSLSN.cjs.map → chunk-24ZKPE33.cjs.map} +1 -1
- package/dist/{chunk-CK3GK34R.js → chunk-2HIDE3QV.js} +9 -3
- package/dist/chunk-2HIDE3QV.js.map +1 -0
- package/dist/{chunk-WDIBOWAA.js → chunk-2HVFF5SS.js} +6 -6
- package/dist/chunk-2HVFF5SS.js.map +1 -0
- package/dist/{chunk-FT5CF6IA.js → chunk-2QWNPYDG.js} +3 -3
- package/dist/{chunk-FT5CF6IA.js.map → chunk-2QWNPYDG.js.map} +1 -1
- package/dist/{chunk-M7GQBRZU.cjs → chunk-3YG3MYDE.cjs} +153 -24
- package/dist/chunk-3YG3MYDE.cjs.map +1 -0
- package/dist/{chunk-VNQRI2RO.cjs → chunk-5VNBQ4QK.cjs} +16 -16
- package/dist/{chunk-VNQRI2RO.cjs.map → chunk-5VNBQ4QK.cjs.map} +1 -1
- package/dist/{chunk-K3LLGRK7.cjs → chunk-5ZCXWA7J.cjs} +59 -15
- package/dist/chunk-5ZCXWA7J.cjs.map +1 -0
- package/dist/{chunk-Z2OL5AJD.cjs → chunk-6F6GGX2W.cjs} +4 -3
- package/dist/chunk-6F6GGX2W.cjs.map +1 -0
- package/dist/{chunk-D26ENTN2.cjs → chunk-72IFMNJE.cjs} +80 -52
- package/dist/chunk-72IFMNJE.cjs.map +1 -0
- package/dist/{chunk-SAW5OK36.cjs → chunk-A5Z3IMSJ.cjs} +6 -6
- package/dist/{chunk-SAW5OK36.cjs.map → chunk-A5Z3IMSJ.cjs.map} +1 -1
- package/dist/{chunk-VA42637J.cjs → chunk-AGEZY4LL.cjs} +46 -41
- package/dist/chunk-AGEZY4LL.cjs.map +1 -0
- package/dist/{chunk-BG5D5CZ6.js → chunk-ANOQWAMU.js} +23 -6
- package/dist/chunk-ANOQWAMU.js.map +1 -0
- package/dist/{chunk-PRYE7AZQ.cjs → chunk-AWWOQH46.cjs} +7 -7
- package/dist/chunk-AWWOQH46.cjs.map +1 -0
- package/dist/{chunk-JFS3NWZ5.cjs → chunk-B7WJJHJS.cjs} +7 -4
- package/dist/chunk-B7WJJHJS.cjs.map +1 -0
- package/dist/{chunk-D6GNRSCV.cjs → chunk-BBLE4UTG.cjs} +23 -6
- package/dist/chunk-BBLE4UTG.cjs.map +1 -0
- package/dist/{chunk-HGC5JNVA.cjs → chunk-BVVKMQKR.cjs} +9 -2
- package/dist/chunk-BVVKMQKR.cjs.map +1 -0
- package/dist/{chunk-YYV35XOS.js → chunk-C4R7BTBQ.js} +4 -3
- package/dist/chunk-C4R7BTBQ.js.map +1 -0
- package/dist/{chunk-PXFQVLBX.js → chunk-ETXUOETU.js} +26 -36
- package/dist/chunk-ETXUOETU.js.map +1 -0
- package/dist/{chunk-HKFMXNVQ.cjs → chunk-F4ZT5X2S.cjs} +11 -11
- package/dist/{chunk-HKFMXNVQ.cjs.map → chunk-F4ZT5X2S.cjs.map} +1 -1
- package/dist/{chunk-YBPBK5KI.js → chunk-FKQJYMCO.js} +97 -23
- package/dist/chunk-FKQJYMCO.js.map +1 -0
- package/dist/{chunk-ZDFHA2EC.js → chunk-FVKCNAEQ.js} +51 -7
- package/dist/chunk-FVKCNAEQ.js.map +1 -0
- package/dist/{chunk-ZL7UM6PU.cjs → chunk-GHBXS5RT.cjs} +4 -4
- package/dist/{chunk-ZL7UM6PU.cjs.map → chunk-GHBXS5RT.cjs.map} +1 -1
- package/dist/{chunk-ZO5PBBFX.js → chunk-GKJRNIP4.js} +59 -15
- package/dist/chunk-GKJRNIP4.js.map +1 -0
- package/dist/{chunk-UCFWI6D4.js → chunk-GRIMIJJ3.js} +3 -3
- package/dist/{chunk-UCFWI6D4.js.map → chunk-GRIMIJJ3.js.map} +1 -1
- package/dist/{chunk-5RYLK3MQ.js → chunk-GVHBHUFV.js} +11 -6
- package/dist/chunk-GVHBHUFV.js.map +1 -0
- package/dist/chunk-GZH2SIOF.cjs +99 -0
- package/dist/chunk-GZH2SIOF.cjs.map +1 -0
- package/dist/{chunk-SFW3UB2P.js → chunk-IJNQYMN7.js} +4 -4
- package/dist/{chunk-SFW3UB2P.js.map → chunk-IJNQYMN7.js.map} +1 -1
- package/dist/{chunk-HC7VKIV5.cjs → chunk-IRUPCNW2.cjs} +49 -46
- package/dist/chunk-IRUPCNW2.cjs.map +1 -0
- package/dist/{chunk-JL4C5VJ7.cjs → chunk-J65CAOUV.cjs} +14 -2
- package/dist/chunk-J65CAOUV.cjs.map +1 -0
- package/dist/{chunk-23FJQTEA.js → chunk-LJMNCSDG.js} +38 -15
- package/dist/chunk-LJMNCSDG.js.map +1 -0
- package/dist/{chunk-PVJBAPYJ.js → chunk-MEN7VLQ5.js} +8 -5
- package/dist/chunk-MEN7VLQ5.js.map +1 -0
- package/dist/{chunk-PHZ23DP3.js → chunk-MUA5L25B.js} +125 -12
- package/dist/chunk-MUA5L25B.js.map +1 -0
- package/dist/{chunk-WD6HJRBG.cjs → chunk-NWXB4F6D.cjs} +21 -21
- package/dist/{chunk-WD6HJRBG.cjs.map → chunk-NWXB4F6D.cjs.map} +1 -1
- package/dist/{chunk-PQHS255G.js → chunk-OHSIVNJO.js} +3 -3
- package/dist/chunk-OHSIVNJO.js.map +1 -0
- package/dist/{chunk-XGFTL5XY.js → chunk-PVVO23LZ.js} +3 -3
- package/dist/{chunk-XGFTL5XY.js.map → chunk-PVVO23LZ.js.map} +1 -1
- package/dist/{chunk-CUH22J4D.js → chunk-Q4ZXDDWA.js} +3 -3
- package/dist/{chunk-CUH22J4D.js.map → chunk-Q4ZXDDWA.js.map} +1 -1
- package/dist/{chunk-WKOIGLQX.cjs → chunk-QIIG2QDP.cjs} +8 -8
- package/dist/{chunk-WKOIGLQX.cjs.map → chunk-QIIG2QDP.cjs.map} +1 -1
- package/dist/{chunk-QA3MVQ32.js → chunk-QXW6O56Z.js} +6 -6
- package/dist/chunk-QXW6O56Z.js.map +1 -0
- package/dist/{chunk-5PC6JBGJ.cjs → chunk-R2VF5NQG.cjs} +3 -3
- package/dist/chunk-R2VF5NQG.cjs.map +1 -0
- package/dist/{chunk-7Z5LUTGU.js → chunk-RRI5YBUK.js} +6 -3
- package/dist/{chunk-JFS3NWZ5.cjs.map → chunk-RRI5YBUK.js.map} +1 -1
- package/dist/{chunk-HUR6ZJ7S.cjs → chunk-RUKFN3LJ.cjs} +6 -6
- package/dist/{chunk-HUR6ZJ7S.cjs.map → chunk-RUKFN3LJ.cjs.map} +1 -1
- package/dist/chunk-TCBHVIMD.js +89 -0
- package/dist/chunk-TCBHVIMD.js.map +1 -0
- package/dist/{chunk-SES6GDBQ.cjs → chunk-UJJUX6NW.cjs} +59 -8
- package/dist/chunk-UJJUX6NW.cjs.map +1 -0
- package/dist/{chunk-ZRL2UFTH.cjs → chunk-V3N56Z2S.cjs} +101 -22
- package/dist/chunk-V3N56Z2S.cjs.map +1 -0
- package/dist/{chunk-6WZ2VN7V.js → chunk-W36WCZS2.js} +6 -6
- package/dist/{chunk-6WZ2VN7V.js.map → chunk-W36WCZS2.js.map} +1 -1
- package/dist/{chunk-M36G6SRP.js → chunk-WXNQMJ67.js} +14 -3
- package/dist/chunk-WXNQMJ67.js.map +1 -0
- package/dist/{chunk-VXPLKQWY.cjs → chunk-XE5PE54B.cjs} +30 -40
- package/dist/chunk-XE5PE54B.cjs.map +1 -0
- package/dist/{chunk-OZSACQ2V.js → chunk-XJOBMAWW.js} +3 -3
- package/dist/{chunk-OZSACQ2V.js.map → chunk-XJOBMAWW.js.map} +1 -1
- package/dist/{chunk-OTATNBMD.js → chunk-XS7FI4JA.js} +3 -3
- package/dist/{chunk-OTATNBMD.js.map → chunk-XS7FI4JA.js.map} +1 -1
- package/dist/{chunk-HRXEZ3SX.cjs → chunk-YD3JA36S.cjs} +4 -4
- package/dist/{chunk-HRXEZ3SX.cjs.map → chunk-YD3JA36S.cjs.map} +1 -1
- package/dist/chunk-YYODFQEU.cjs +25 -0
- package/dist/chunk-YYODFQEU.cjs.map +1 -0
- package/dist/{chunk-UTQSSKSG.js → chunk-ZXBSARZX.js} +4 -4
- package/dist/{chunk-UTQSSKSG.js.map → chunk-ZXBSARZX.js.map} +1 -1
- package/dist/entries/apps.cjs +43 -42
- package/dist/entries/apps.d.cts +2 -2
- package/dist/entries/apps.d.ts +2 -2
- package/dist/entries/apps.js +8 -7
- package/dist/entries/catalogs.d.cts +1 -1
- package/dist/entries/catalogs.d.ts +1 -1
- package/dist/entries/credits.cjs +153 -153
- package/dist/entries/credits.d.cts +1 -1
- package/dist/entries/credits.d.ts +1 -1
- package/dist/entries/credits.js +8 -8
- package/dist/entries/edl.cjs +130 -102
- package/dist/entries/edl.d.cts +74 -3
- package/dist/entries/edl.d.ts +74 -3
- package/dist/entries/edl.js +2 -2
- package/dist/entries/entities.cjs +126 -122
- package/dist/entries/entities.d.cts +2 -2
- package/dist/entries/entities.d.ts +2 -2
- package/dist/entries/entities.js +1 -1
- package/dist/entries/i18n.cjs +11 -11
- package/dist/entries/i18n.d.cts +2 -2
- package/dist/entries/i18n.d.ts +2 -2
- package/dist/entries/i18n.js +1 -1
- package/dist/entries/llm-models.cjs +63 -43
- package/dist/entries/llm-models.d.cts +71 -4
- package/dist/entries/llm-models.d.ts +71 -4
- package/dist/entries/llm-models.js +1 -1
- package/dist/entries/media.cjs +45 -41
- package/dist/entries/media.d.cts +39 -1
- package/dist/entries/media.d.ts +39 -1
- package/dist/entries/media.js +1 -1
- package/dist/entries/model-catalog.cjs +66 -66
- package/dist/entries/model-catalog.d.cts +2 -2
- package/dist/entries/model-catalog.d.ts +2 -2
- package/dist/entries/model-catalog.js +4 -4
- package/dist/entries/models.cjs +274 -210
- package/dist/entries/models.d.cts +3 -3
- package/dist/entries/models.d.ts +3 -3
- package/dist/entries/models.js +5 -5
- package/dist/entries/nodes.cjs +222 -201
- package/dist/entries/nodes.d.cts +48 -8
- package/dist/entries/nodes.d.ts +48 -8
- package/dist/entries/nodes.js +10 -9
- package/dist/entries/pipeline.cjs +149 -149
- package/dist/entries/pipeline.d.cts +8 -4
- package/dist/entries/pipeline.d.ts +8 -4
- package/dist/entries/pipeline.js +3 -3
- package/dist/entries/social.cjs +174 -174
- package/dist/entries/social.d.cts +13 -5
- package/dist/entries/social.d.ts +13 -5
- package/dist/entries/social.js +2 -2
- package/dist/entries/types.d.cts +1 -1
- package/dist/entries/types.d.ts +1 -1
- package/dist/entries/ugc.cjs +71 -71
- package/dist/entries/ugc.js +4 -4
- package/dist/entries/video.cjs +115 -115
- package/dist/entries/video.d.cts +4 -3
- package/dist/entries/video.d.ts +4 -3
- package/dist/entries/video.js +4 -4
- package/dist/entries/workflow.cjs +96 -95
- package/dist/entries/workflow.d.cts +7 -18
- package/dist/entries/workflow.d.ts +7 -18
- package/dist/entries/workflow.js +2 -1
- package/dist/index.cjs +1708 -1567
- package/dist/index.d.cts +9 -9
- package/dist/index.d.ts +9 -9
- package/dist/index.js +26 -25
- package/dist/{model-catalog-V-ZNzRSd.d.ts → model-catalog-VIHGmQL2.d.cts} +22 -0
- package/dist/{model-catalog-V-ZNzRSd.d.cts → model-catalog-VIHGmQL2.d.ts} +22 -0
- package/dist/{presentation-utils-D0kxsWf9.d.cts → presentation-utils-A4i92SYo.d.cts} +1 -1
- package/dist/{presentation-utils-pZwlEAzo.d.ts → presentation-utils-DjdPtM9k.d.ts} +1 -1
- package/dist/{scene-node-types-C3kl_zyK.d.ts → scene-node-types-Cvbtf-0a.d.cts} +147 -6
- package/dist/{scene-node-types-C3kl_zyK.d.cts → scene-node-types-Cvbtf-0a.d.ts} +147 -6
- package/dist/{types-DffyGSy5.d.cts → types-CU6SQnMS.d.cts} +0 -5
- package/dist/{types-DffyGSy5.d.ts → types-CU6SQnMS.d.ts} +0 -5
- package/dist/{types-BRlFPEru.d.ts → types-DzUBR7yr.d.cts} +8 -1
- package/dist/{types-BRlFPEru.d.cts → types-DzUBR7yr.d.ts} +8 -1
- package/package.json +1 -1
- package/src/__tests__/camera-switch-contract.test.ts +33 -1
- package/src/__tests__/character-mention-slug.test.ts +0 -8
- package/src/__tests__/effective-tier.test.ts +3 -14
- package/src/__tests__/fixtures/camera-switch-speaker-map-parity.json +178 -0
- package/src/__tests__/fixtures/root-exports.baseline.json +21 -0
- package/src/__tests__/fixtures/speaker-map-camera-ids.json +26 -0
- package/src/__tests__/gvp-supported-providers.test.ts +1 -0
- package/src/__tests__/i18n-locale-completeness.test.ts +38 -3
- package/src/__tests__/llm-models.test.ts +200 -20
- package/src/__tests__/node-preset-extract.test.ts +10 -0
- package/src/__tests__/preview-gate-use-case.test.ts +16 -1
- package/src/__tests__/producer-types.test.ts +19 -0
- package/src/__tests__/run-continuation.test.ts +4 -1
- package/src/__tests__/speaker-map-contract.test.ts +48 -0
- package/src/__tests__/unit-contract-compose.test.ts +129 -0
- package/src/__tests__/unit-contracts.test.ts +134 -0
- package/src/__tests__/use-case-types.test.ts +33 -0
- package/src/__tests__/video-collapse-parity.test.ts +10 -0
- package/src/__tests__/video-frame-slot.test.ts +85 -0
- package/src/__tests__/video-mode-aliases.test.ts +1 -0
- package/src/__tests__/video-reference-only.test.ts +117 -0
- package/src/__tests__/vidu-q4-catalog.test.ts +230 -0
- package/src/camera-switch-contract.ts +36 -2
- package/src/credit-identifiers.ts +19 -6
- package/src/entity-asset-types.ts +13 -0
- package/src/entries/edl.ts +2 -0
- package/src/entries/llm-models.ts +5 -0
- package/src/entries/media.ts +1 -0
- package/src/entries/models.ts +25 -0
- package/src/entries/nodes.ts +5 -1
- package/src/fan-out-rows.ts +36 -3
- package/src/generate-mask.ts +40 -0
- package/src/generated/unit-contracts.ts +58 -0
- package/src/i18n/types.ts +13 -2
- package/src/json-kinds.ts +24 -4
- package/src/llm-models.ts +184 -31
- package/src/meta-ads-scrape.ts +16 -8
- package/src/model-catalog.ts +78 -13
- package/src/model-constants.ts +260 -5
- package/src/node-default-mappings.ts +3 -0
- package/src/node-preset-extract.ts +8 -0
- package/src/pipeline-types.ts +3 -0
- package/src/presentation-utils.ts +12 -12
- package/src/preview-gate.ts +4 -2
- package/src/producer-types.ts +19 -19
- package/src/run-continuation.ts +26 -4
- package/src/speaker-layouts.ts +8 -3
- package/src/speaker-map-contract.ts +77 -0
- package/src/unit-contract-compose.ts +55 -0
- package/src/use-case-types.ts +19 -0
- package/src/video-ui-defaults.ts +7 -5
- package/dist/chunk-23FJQTEA.js.map +0 -1
- package/dist/chunk-5PC6JBGJ.cjs.map +0 -1
- package/dist/chunk-5RYLK3MQ.js.map +0 -1
- package/dist/chunk-7Z5LUTGU.js.map +0 -1
- package/dist/chunk-BG5D5CZ6.js.map +0 -1
- package/dist/chunk-CK3GK34R.js.map +0 -1
- package/dist/chunk-D26ENTN2.cjs.map +0 -1
- package/dist/chunk-D6GNRSCV.cjs.map +0 -1
- package/dist/chunk-HC7VKIV5.cjs.map +0 -1
- package/dist/chunk-HGC5JNVA.cjs.map +0 -1
- package/dist/chunk-JL4C5VJ7.cjs.map +0 -1
- package/dist/chunk-K3LLGRK7.cjs.map +0 -1
- package/dist/chunk-M36G6SRP.js.map +0 -1
- package/dist/chunk-M7GQBRZU.cjs.map +0 -1
- package/dist/chunk-PHZ23DP3.js.map +0 -1
- package/dist/chunk-PQHS255G.js.map +0 -1
- package/dist/chunk-PRYE7AZQ.cjs.map +0 -1
- package/dist/chunk-PVJBAPYJ.js.map +0 -1
- package/dist/chunk-PXFQVLBX.js.map +0 -1
- package/dist/chunk-QA3MVQ32.js.map +0 -1
- package/dist/chunk-SES6GDBQ.cjs.map +0 -1
- package/dist/chunk-TU33KYKW.cjs +0 -25
- package/dist/chunk-TU33KYKW.cjs.map +0 -1
- package/dist/chunk-VA42637J.cjs.map +0 -1
- package/dist/chunk-VXPLKQWY.cjs.map +0 -1
- package/dist/chunk-WDIBOWAA.js.map +0 -1
- package/dist/chunk-YBPBK5KI.js.map +0 -1
- package/dist/chunk-YYV35XOS.js.map +0 -1
- package/dist/chunk-Z2OL5AJD.cjs.map +0 -1
- package/dist/chunk-ZDFHA2EC.js.map +0 -1
- package/dist/chunk-ZO5PBBFX.js.map +0 -1
- package/dist/chunk-ZRL2UFTH.cjs.map +0 -1
- package/src/__tests__/__snapshots__/prompt-builder-segments.test.ts.snap +0 -65
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/producer-types.ts","../src/exposed-field-keys.ts","../src/render-nodes.ts","../src/presentation-utils.ts"],"names":["UGC_PRIMARY_HANDLE","applyEdlCreditId","speakerViewCreditId","SPEAKER_VIEW_CREDIT_IDS","url","text","dropStaleVideoLinkFields"],"mappings":";;;;;;;AAsBO,IAAM,oBAAA,uBAAgD,GAAA,CAAI;AAAA,EAC/D,gBAAA;AAAA,EACA,gBAAA;AAAA,EACA,SAAA;AAAA;AAAA,EACA,eAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,gBAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,oBAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,gBAAA;AAAA,EACA,cAAA;AAAA,EACA,eAAA;AAAA,EACA,gBAAA;AAAA,EACA,UAAA;AAAA,EACA,iBAAA;AAAA,EACA,iBAAA;AAAA,EACA,eAAA;AAAA,EACA,aAAA;AAAA,EACA,cAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAA;AAAA;AAAA;AAAA,EAGA,cAAA;AAAA,EACA,cAAA;AAAA;AAAA;AAAA;AAAA,EAIA,WAAA;AAAA,EACA,kBAAA;AAAA,EACA,mBAAA;AAAA,EACA,cAAA;AAAA,EACA,cAAA;AAAA,EACA,qBAAA;AAAA,EACA,YAAA;AAAA,EACA,cAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA,EACA,YAAA;AAAA;AAAA,EAEA,YAAA;AAAA,EACA,gBAAA;AAAA,EACA,iBAAA;AAAA,EAC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CAAa,IAAA,CAAK,KAAK,CAAC,CAAA;AAAA,IACzC,CAAA,MAAO;AACL,MAAA,MAAA,CAAO,KAAK,IAAI,CAAA;AAAA,IAClB;AAAA,EACF;AACA,EAAA,OAAO,MAAA;AACT;AAGO,SAAS,cAAc,IAAA,EAAgC;AAC5D,EAAA,OAAO,IAAA,CAAK,IAAA,KAAS,MAAA,GAAS,IAAA,CAAK,SAAS,IAAA,CAAK,EAAA;AACnD;AAGO,SAAS,kBAAA,CACd,OACA,OAAA,EACoB;AACpB,EAAA,OAAO,KAAA,CACJ,MAAA,CAAO,CAAC,IAAA,KAAS;AAChB,IAAA,IAAI,IAAA,CAAK,IAAA,KAAS,MAAA,IAAU,IAAA,CAAK,IAAA,KAAS,OAAA,IAAW,IAAA,CAAK,IAAA,KAAS,QAAA,EAAU,OAAO,OAAA,CAAQ,GAAA,CAAI,KAAK,MAAM,CAAA;AAC3G,IAAA,OAAO,IAAA;AAAA,EACT,CAAC,CAAA,CACA,GAAA,CAAI,CAAC,IAAA,KAAS;AACb,IAAA,IAAI,IAAA,CAAK,SAAS,OAAA,EAAS;AACzB,MAAA,OAAO,EAAE,GAAG,IAAA,EAAM,KAAA,EAAO,mBAAmB,IAAA,CAAK,KAAA,EAAO,OAAO,CAAA,EAAE;AAAA,IACnE;AACA,IAAA,OAAO,IAAA;AAAA,EACT,CAAC,CAAA;AACL","file":"chunk-VXPLKQWY.cjs","sourcesContent":["/**\n * Producer-type sets — single source of truth for the node types whose\n * primary output is a video URL, audio URL, etc.\n *\n * Consumed by:\n * - backend/src/services/workflow-engine/execution-graph.ts (orchestrator\n * dispatch + asset-type tagging in payload-builder, output-extractor,\n * inline-executor — re-exported there as VIDEO_SOURCE_TYPES /\n * AUDIO_SOURCE_TYPES for backwards compatibility).\n * - frontend/src/lib/generate-video-handles.ts (handle connection\n * validation on the Generate Video node).\n *\n * Lifting these here ensures the frontend handle validator can never reject\n * a connection from a node type that the backend would happily route at\n * execution time (the prior drift bug, see issue 1 of the Task 4.1 review).\n */\nimport { UGC_PRIMARY_HANDLE } from \"./ugc-node-wires.js\"\n\n/**\n * Source node types whose primary output is a video URL.\n * Mirrors the backend execution-graph VIDEO_SOURCE_TYPES verbatim.\n */\nexport const VIDEO_PRODUCER_TYPES: ReadonlySet<string> = new Set([\n \"image-to-video\",\n \"video-to-video\",\n \"switchx\", // Beeble SwitchX relight/composite\n \"text-to-video\",\n // Unified video node — emits videoUrl identically to i2v/t2v (its payload-builder\n // case dispatches dynamically to \"image-to-video\" or \"text-to-video\" jobName based\n // on whether a start frame is wired). Without this, getPrimaryOutput would fall\n // through to the imageUrl/videoUrl/audioUrl/text default and downstream consumers\n // could silently misroute the output.\n \"generate-video\",\n // Generate Video Pro — Seedance-2-family multi-segment stitch variant of\n // generate-video (same \"emits videoUrl\" contract; a trimmed provider +\n // handle set). Must mirror generate-video here or its output can't connect\n // downstream (the recurring \"cannot connect the outputs\" bug class).\n \"generate-video-pro\",\n // Edit Video Pro — Seedance-2-family span-replace sibling of generate-\n // video-pro (same \"emits videoUrl\" contract; source video + prompt in,\n // ONE video out). Must mirror generate-video-pro here or its output can't\n // connect downstream (the recurring \"cannot connect the outputs\" bug class).\n \"edit-video-pro\",\n \"upload-video\",\n \"youtube-video\",\n \"combine-videos\",\n \"lip-sync\",\n \"speech-to-video\",\n \"motion-transfer\",\n \"video-upscale\",\n \"video-depth\",\n \"extend-video\",\n // face-swap output is video (writes generatedVideoUrl, per-result `url`).\n // Frontend execution-graph already includes it in VIDEO_SOURCE_TYPES; this\n // entry brings the shared set in line so canvas typed-handle validation\n // doesn't reject face-swap → video-consumer edges that the orchestrator\n // would happily route at runtime.\n \"face-swap\",\n // Speaker View (C3.2): an EDL rendered with its speakers framed — one VIDEO\n // out (no audio-only render). Registered in RENDER_NODE_TYPES as well.\n \"speaker-view\",\n \"video-retake\",\n // video-sfx: adds an SFX track to a video → emits a video URL. Belongs here so\n // canvas handle validation accepts video-sfx → video-consumer edges and the\n // backend routes its output as video (it was previously relying on a fallback).\n \"video-sfx\",\n \"suno-music-video\",\n \"merge-video-audio\",\n \"add-captions\",\n \"resize-video\",\n \"social-media-format\",\n \"trim-video\",\n \"render-video\",\n \"speed-ramp\",\n \"loop-video\",\n \"fade-video\",\n // Video Mask emits its mask as a video; Mask Composite its composite.\n \"video-mask\",\n \"mask-composite\",\n \"transcode-video\",\n \"manual-edit\",\n // Remove Audio: strips the audio track, emits a silent video.\n \"remove-audio\",\n // AI Avatar (HeyGen): avatar + voice/audio → video.\n \"ai-avatar\",\n // Cinematic Avatar (HeyGen cinematic_avatar): prompt + 1–3 avatar looks → video.\n \"cinematic-avatar\",\n // Assemble Narrated Video: fits N (clip, voice) blocks into one MP4 → video.\n \"assemble-narrated-video\",\n // Still to Video: one still image + one audio track → MP4 (local FFmpeg,\n // no provider). Emits generatedVideoUrl like every other ffmpeg video node.\n \"still-to-video\",\n // Slideshow: 2-100 stills + one optional audio track → MP4 (local FFmpeg,\n // no provider). Same contract; images arrive via the image-collage lane.\n \"slideshow\",\n // GIF to Video: animated GIF → H.264 MP4 (local FFmpeg, no provider).\n // Emits generatedVideoUrl so it connects to any downstream video consumer\n // (e.g. a Seedance video-reference input) by an ordinary edge.\n \"gif-to-video\",\n // 3D Render Pro: authors a scene AND exports it in one operation, settling\n // with the standard `videoUrl` field. It is a video producer as much as it\n // is a composition producer — omitting it here is the \"cannot connect the\n // outputs\" bug, and its `composition` handle is typed separately.\n \"pro-3d-render\",\n // Video Overlay: timed image layers over a video in one local FFmpeg pass\n // (the base audio copied) — emits a video URL on `video-out`.\n \"video-overlay\",\n // UGC Clip: renders one clip of a UGC video from its ticket — emits a video\n // URL on `video-out` (one per fan-out iteration).\n \"ugc-clip\",\n // UGC Finish: the video's clips, finished, as one ordered list — a registered producer, so a\n // Bundle edge into Combine Videos routes each one as a video, in order.\n \"ugc-finish-clips\",\n])\n\n/**\n * Source node types whose output media-type cannot be classified\n * statically — iterators, dynamic dispatchers, sub-workflow wrappers.\n * The orchestrator decides their actual output type at execution time\n * based on what's wired upstream (loop iterates upstream column type;\n * sub-workflow emits its leaf node's type; adjust-volume passes through\n * video or audio based on its `lastInputType` runtime field;\n * voice-changer emits audio in audio mode, video+audio in video mode).\n *\n * Typed-handle validators (frontend/src/lib/{generate-image,generate-\n * video,ffmpeg}-handles.ts) must include these as acceptors on EVERY\n * media-typed input handle — otherwise the canvas validator hard-\n * rejects edges that the orchestrator would happily route at runtime.\n *\n * Lifted here from `frontend/src/lib/ffmpeg-handles.ts` (where the\n * escape hatch was first added) so the same set drives ALL handle\n * validators uniformly. Adding a new dynamic-output node type means\n * one edit here instead of N across sibling validator files.\n *\n * Intentionally OMITTED:\n * - `webhook-trigger` / `schedule-trigger` — their outputs are\n * user-defined JSON shapes, not media URLs. Accepting them as\n * media producers creates false-positive drops at the canvas\n * that fail at execution. Users wanting trigger → media flows\n * should wire through an upload node.\n */\nexport const DYNAMIC_PRODUCER_TYPES: ReadonlySet<string> = new Set([\n \"list\",\n \"sub-workflow\",\n \"adjust-volume\",\n // Pitch & Tempo: audio in → audio out, video in → video out (picture\n // copied). Dual-mode like adjust-volume; stays in AUDIO_PRODUCER_TYPES as\n // its default.\n \"pitch-tempo\",\n // Dual-mode: audio in → audio out; video in → video out (+ revoiced audio).\n // Listed here so canvas validators accept its output on BOTH audio and video\n // input handles (it also stays in AUDIO_PRODUCER_TYPES as its default).\n \"voice-changer\",\n // voice-changer-pro (renamed from voice-recast in #3581) is a behavioral\n // twin of voice-changer — identical dual-mode output. Must mirror it in\n // EVERY producer set or its outputs can't connect (was the \"cannot connect\n // the outputs of voice-changer-pro\" bug). Guarded by producer-types.test.ts.\n \"voice-changer-pro\",\n // Dubbing joined the dual-mode family with the full-surface upgrade:\n // audio in → dubbed audio; video in (or a video sourceUrl) → dubbed VIDEO\n // (+ audio sidecar). Same wiring contract as voice-changer; stays in\n // AUDIO_PRODUCER_TYPES as its default. Explicitly asserted in\n // producer-types.test.ts (the suite does not fail on omission).\n \"dubbing\",\n \"reduce\",\n // Dual-output time chunker (UI label \"Split into Chunks\"; type id stays\n // \"split-media\"): video in → video chunks, audio in → audio chunks — two\n // independent lanes on two output handles. Like voice-changer, the canvas\n // validator only sees the source NODE type, not which handle a wire leaves,\n // so it lives here to be accepted on BOTH audio and video input handles. The\n // backend routes the correct lane by sourceHandle in getPrimaryOutput\n // (output-extractor.ts); the frontend does so in extractNodeOutput.\n \"split-media\",\n // apply-edl renders an EDL into ONE media output whose type is decided at\n // run time by the node's `output` setting (video OR audio) — so its static\n // medium is genuinely unknown and it belongs here, letting canvas validators\n // accept its default media handle on BOTH audio and video input handles. It\n // ALSO emits a fixed `json` handle (the remapped Transcript); that half lives\n // in JSON_PRODUCER_TYPES (frontend/src/lib/data-handles.ts). The FIRST node\n // with both a dynamic media handle and a fixed json handle. Because\n // getOutputType (presentation-utils.ts) deliberately returns \"data\" for\n // DYNAMIC members, apply-edl is ALSO added to the literal VIDEO_OUTPUT_TYPES\n // there so a published app renders the cut as video, mirroring the\n // voice-changer/dubbing precedent. Asserted in producer-types.test.ts (the\n // suite does not fail on omission).\n \"apply-edl\",\n // Tighten Episode (podcast use-case node): the episode is video OR audio by\n // its `output` setting (an audio recording forces audio) — runtime-decided.\n \"tighten-episode\",\n])\n\n/**\n * Source node types whose primary output is an audio URL.\n * Mirrors the backend execution-graph AUDIO_SOURCE_TYPES verbatim.\n */\nexport const AUDIO_PRODUCER_TYPES: ReadonlySet<string> = new Set([\n \"text-to-speech\",\n \"text-to-audio\",\n \"generate-music\",\n \"upload-audio\",\n \"suno-generate\",\n \"suno-cover\",\n \"suno-extend\",\n \"suno-separate\",\n \"audio-separation\",\n \"suno-mashup\",\n \"suno-replace-section\",\n \"suno-add-instrumental\",\n \"suno-add-vocals\",\n \"suno-convert-wav\",\n \"suno-upload-extend\",\n \"trim-audio\",\n \"mix-audio\",\n \"combine-audio\",\n \"adjust-volume\",\n \"audio-fx\",\n \"pitch-tempo\",\n \"reference-audio\",\n \"audio-isolation\",\n \"text-to-dialogue\",\n \"voice-changer\",\n // Twin of voice-changer (see DYNAMIC_PRODUCER_TYPES note). Audio is its\n // default output mode; video mode is handled via DYNAMIC membership.\n \"voice-changer-pro\",\n \"dubbing\",\n \"voice-remix\",\n \"voice-design\",\n // Extract Audio: demuxes a video's audio track to a standalone MP3.\n \"extract-audio\",\n])\n\n/**\n * Source node types whose output is an IMAGE URL — what feeds a References\n * input. ONE set for the canvas validators (`frontend/src/lib/\n * generate-image-handles.ts` re-exports it), the backend's Generate Image\n * handle migration and the MCP edge normalizer (`llm-chat`'s legacy `in`):\n * they used to keep separate copies, and the backend's lagged by eight types.\n */\nexport const IMAGE_PRODUCER_TYPES: ReadonlySet<string> = new Set([\n \"upload-image\", \"generate-image\", \"edit-image\", \"image-to-image\", \"modify-image\", \"upscale-image\", \"remove-background\",\n // extract-frame produces a single still image extracted from a video source.\n \"extract-frame\",\n // generate-mask emits the source image AND a mask PNG; its `image` source\n // pip is the passthrough (the same image as the input).\n \"generate-mask\",\n // paint-mask emits the hand-painted mask PNG (a plain image at runtime).\n // Membership is what makes mask targets accept it — mask is an advisory\n // color, not a gated type.\n \"paint-mask\",\n // reference-sheet's `sheet` is one composited image and `panels` carries\n // clean reference images; both resolve to image URLs at runtime.\n \"reference-sheet\",\n // reference-board's `image` pip emits a real generated board image.\n \"reference-board\",\n // image-collage composites N images → ONE image.\n \"image-collage\",\n // image-overlay places layers on a base → ONE image.\n \"image-overlay\",\n // 3D Render Pro's `stills` handle carries one PNG per shot of the exported\n // composition (spread into referenceImageUrls like reference-sheet\n // `panels`). A validator sees only the source NODE type, so this also makes\n // its `video` pip droppable on an image input — the handle-blind trade\n // reference-sheet and split-media already make; the input resolvers route\n // by handle, so only `stills` becomes an image at runtime. Deliberately NOT\n // in IMAGE_SOURCE_TYPES on either engine: that set types the node's PRIMARY\n // asset, and 3D Render Pro's is the MP4.\n \"pro-3d-render\",\n])\n\n/**\n * Source node types whose primary output is a LIST that, by default, fans out\n * one downstream execution per element when an edge leaves them WITHOUT an\n * explicit `outputMode` (all other edges default to \"last\"). `selector` is\n * included because its picked/rest channels are lists too.\n *\n * Single source of truth for the fan-out \"each\" default, consumed by:\n * - backend/src/services/workflow-engine/input-resolver.ts (DEFAULT_EACH_TYPES)\n * - frontend/src/components/editor/workflow-editor/types.ts (FAN_OUT_EACH_TYPES)\n * - frontend/src/components/editor/workflow-editor/node-input-resolver.ts\n *\n * These three previously kept independent copies; the backend copy drifted\n * (missing the four list-transform types), so server-side workflow runs\n * silently dropped all-but-the-first item for filter-list / deduplicate /\n * merge-lists / sort-list sources while the canvas fanned out N ways. Lifting\n * the set here makes that drift impossible.\n */\nexport const FAN_OUT_EACH_TYPES: ReadonlySet<string> = new Set([\n \"list\",\n \"split-text\",\n \"filter-list\",\n \"deduplicate\",\n \"merge-lists\",\n \"sort-list\",\n \"selector\",\n // edit-plan `clips` mode emits a bare `Edl[]` on `data.generatedJson`, so an\n // edge leaving it defaults to \"each\" — one downstream execution (typically an\n // apply-edl render) per clip. The `tighten`/`chapters` modes emit an OBJECT,\n // for which the list extractors return undefined, so an \"each\" edge falls back\n // to the scalar `edl` value (no fan-out) — the same graceful degradation\n // web-scrape relies on. See `unwrapEditPlanOutput` in `edit-plan-contract.ts`.\n \"edit-plan\",\n // Content Ideas emits one creative brief per idea on `listResults`, so an\n // edge leaving it defaults to \"each\" — the node after it (typically\n // Generate Script) runs once per idea, on the server too.\n \"content-ideas\",\n])\n\n/**\n * Per-HANDLE \"each\" defaults, for a node whose outputs differ in kind: on the\n * `each` handles an edge without an explicit `outputMode` defaults to \"each\",\n * on its other handles to \"last\". `primary` is the handle an edge with no\n * `sourceHandle` reads (agent-written workflow JSON often omits it).\n *\n * The list an \"each\" edge reads is the node's per-iteration results\n * (`listResults`) — it exists only when the node itself ran once per item, so\n * after a single run the edge degrades to the single value, exactly like a\n * `FAN_OUT_EACH_TYPES` member with one item.\n */\nexport const FAN_OUT_EACH_HANDLES: Readonly<Record<string, { readonly each: readonly string[]; readonly primary: string }>> = {\n // Camera Switch run once per clip (Edit Plan in clips mode): each clip's\n // switched EDL is its own Apply EDL render. Its transcript is the same for\n // every clip (the master clock, renamed), so that handle stays one value\n // (decided 2026-10-04).\n \"camera-switch\": { each: [\"edl\"], primary: \"edl\" },\n // UGC Clips: one ticket per clip on `clips` (each); `plan-out` and\n // `transcript` carry one value. Not a FAN_OUT_EACH_TYPES member — every\n // handle of such a member would fan out. Its one run writes the tickets as\n // its list (`listResults`, the editor's `__listResults`). The pip an edge\n // with no handle reads is the UGC wires' own (UGC_PRIMARY_HANDLE).\n \"ugc-clips\": { each: [\"clips\"], primary: UGC_PRIMARY_HANDLE[\"ugc-clips\"]! },\n}\n\n/**\n * Fan-out nodes whose iterations must ALL succeed: one failed item fails the\n * node (today's rule tolerates a partial list). UGC Clip — a missing clip\n * silently drops a beat from the script (spec R17). Already-started items\n * finish and settle; their jobs are reused on the next run.\n */\nexport const FAN_OUT_ALL_OR_NOTHING_TYPES: ReadonlySet<string> = new Set([\"ugc-clip\"])\n\n/**\n * Nodes whose saved list is the list their last run PRODUCED — `__listResults`\n * (Extract Field's JSON value on `generatedJson`) — and never a history in\n * `generatedResults`: Extract Field, JSON Process and Site Capture. No run of the first two writes\n * one; earlier builds' server runs did (the run's text, the links of a list of\n * links), and both engines' list readers leave it out for these two (decided\n * 2026-10-05). Single source of truth for the backend engine and the editor.\n */\nexport const OWN_LIST_NODE_TYPES: ReadonlySet<string> = new Set([\n \"extract-field\",\n \"json-process\",\n // Site Capture: its stills, in page order — the last capture's, never every capture's (site-capture-node.ts).\n \"site-capture\",\n])\n\n/** Whether a node's saved list is its own `__listResults`, never a history. */\nexport function ownsItsList(nodeType: string | null | undefined): boolean {\n return typeof nodeType === \"string\" && OWN_LIST_NODE_TYPES.has(nodeType)\n}\n\n/** The `outputMode` an edge has when none is set on it — the ONE rule both\n * engines, the credit estimate and the editor read. */\nexport function defaultEdgeOutputMode(\n sourceType: string | null | undefined,\n sourceHandle: string | null | undefined,\n): \"each\" | \"last\" {\n if (typeof sourceType !== \"string\") return \"last\"\n if (FAN_OUT_EACH_TYPES.has(sourceType)) return \"each\"\n const entry = FAN_OUT_EACH_HANDLES[sourceType]\n if (!entry) return \"last\"\n return entry.each.includes(sourceHandle || entry.primary) ? \"each\" : \"last\"\n}\n\n/** Whether an edge from `sourceHandle` reads the node's per-iteration results\n * (`listResults` — each iteration's PRIMARY output). False on the other\n * handles of a `FAN_OUT_EACH_HANDLES` node: Camera Switch's transcript is one\n * value, never the list of switched EDLs, whatever mode its edge is set to. */\nexport function listResultsServeHandle(\n sourceType: string | null | undefined,\n sourceHandle: string | null | undefined,\n): boolean {\n const entry = typeof sourceType === \"string\" ? FAN_OUT_EACH_HANDLES[sourceType] : undefined\n return !entry || entry.each.includes(sourceHandle || entry.primary)\n}\n\n/**\n * FAN-IN targets: nodes that FOLD everything wired into them into ONE run,\n * instead of running once per upstream item. Keyed by node type; the value\n * names the target handles that fold (`\"*\"` = every handle). An edge into any\n * other handle of such a node is routed normally — Content Ideas folds its\n * recipes but reads its brand from a `field-brand` wire like any field.\n *\n * Single source of truth for both engines' input resolvers (the backend and\n * the editor each used to keep a private `new Set([\"reduce\"])`). A fan-in\n * node is never itself fanned out by an upstream list.\n */\nexport const FAN_IN_TARGETS: Readonly<Record<string, \"*\" | readonly string[]>> = {\n // Choose Best — every wire is a candidate.\n reduce: \"*\",\n // Content Ideas — one or more recipes, from several Content Recipe nodes\n // and/or one that ran once per post.\n \"content-ideas\": [\"recipes\"],\n // Telegram Reply — one message per run, whatever is wired into its text\n // input: a list (or a writer that ran once per item) arrives as one\n // message, never as a burst of sends to the owner's chat.\n \"telegram-account-send\": [\"in\"],\n // The list operators — they READ the whole list wired into them (their\n // executors collect every upstream item themselves) and emit a list. Run\n // once per item by an \"each\" wire (a Split Text, a List, a node that ran per\n // item), every iteration saw the same whole list and answered with its\n // first match: a Filter List fed 11 stories handed 11 copies of story one\n // downstream, and every paid stage after it ran 11 times on it\n // (2026-10-06). A list operator is never fanned out, on any wire.\n \"filter-list\": \"*\",\n deduplicate: \"*\",\n \"merge-lists\": \"*\",\n \"sort-list\": \"*\",\n selector: \"*\",\n // Speaker Frames on a clip pack (P3-24 (a), decided 2026-10-06): ONE run over\n // the union of the clips' spans — the pack's EDLs fold onto its `edl` wire\n // instead of running one detection job (and one minimum charge) per clip.\n \"speaker-frames\": [\"edl\"],\n // UGC Finish: ONE run over every clip of the video, in clip order — the finish plans its\n // cut and its sound over all of them at once, so it is never run once per clip.\n \"ugc-finish-clips\": [\"clips\"],\n}\n\nexport function isFanInNodeType(nodeType: string | undefined | null): boolean {\n return typeof nodeType === \"string\" && Object.prototype.hasOwnProperty.call(FAN_IN_TARGETS, nodeType)\n}\n\n/** True when an edge into `targetHandle` of a `targetType` node is folded.\n * An edge with NO target handle (workflow JSON written by an agent often\n * omits it) lands on the node's primary input, which is the folding one. */\nexport function isFanInEdge(targetType: string | undefined | null, targetHandle: string | null | undefined): boolean {\n if (!isFanInNodeType(targetType)) return false\n const spec = FAN_IN_TARGETS[targetType as string]!\n if (spec === \"*\") return true\n return targetHandle == null || targetHandle === \"\" || spec.includes(targetHandle)\n}\n","/**\n * Exposed-field keys that were renamed to the node's real data field.\n *\n * A published app stores which fields it exposes as `{ type: \"field\", nodeId, field }` items in its\n * immutable snapshot settings, and external callers send `inputOverrides[nodeId][field]` with that same\n * string — it is part of the public wire contract (docs/embed-app-guide.md). Renaming a descriptor's key\n * must not strand the apps already published with the old spelling: they keep that string forever, so every\n * place that turns a stored key into a node-data key — or compares it with a descriptor key — goes through\n * `canonicalExposedFieldKey`.\n *\n * CLOSED LIST. A row needs a spelling that was published (a card that existed in apps) and a target the\n * node's descriptor now declares (the frontend guard `exposable-field-keys.test.ts` checks both). Only list a\n * field whose card cannot carry `allowedValues` (slider / toggle / text / color): the server validates\n * `allowedValues` against the stored key (backend routes/app-runner.ts `validateRestrictedFields`). Never list\n * a field of an outbound node type: the run-request override lock (backend lib/input-override-lock.ts) reads\n * the stored key, before this table renames it.\n */\nexport const LEGACY_EXPOSED_FIELD_KEYS: Readonly<Record<string, Readonly<Record<string, string>>>> = {\n // Published as the Text to Speech slider's key. The node's data field, and every runner, route and config\n // panel, has always been `similarityBoost` — so the slider moved nothing.\n \"text-to-speech\": { similarity: \"similarityBoost\" },\n}\n\n/** The node-data key an exposed field's stored key stands for. Unknown node types and keys pass through. */\nexport function canonicalExposedFieldKey(nodeType: string | undefined, key: string): string {\n if (typeof nodeType !== \"string\" || !Object.hasOwn(LEGACY_EXPOSED_FIELD_KEYS, nodeType)) return key\n const renames = LEGACY_EXPOSED_FIELD_KEYS[nodeType]!\n return Object.hasOwn(renames, key) ? renames[key]! : key\n}\n\n/**\n * The override map with every legacy spelling replaced by its current key. When the caller sent both\n * spellings the current one wins (it is their current intent) and the legacy key is dropped — a dead key\n * is never written to node data. Returns the same object when nothing renames; never mutates.\n */\nexport function canonicalizeOverrideKeys(\n nodeType: string | undefined,\n overrides: Record<string, unknown>,\n): Record<string, unknown> {\n let out: Record<string, unknown> | undefined\n for (const key of Object.keys(overrides)) {\n const current = canonicalExposedFieldKey(nodeType, key)\n if (current === key) continue\n out ??= { ...overrides }\n delete out[key]\n if (!Object.hasOwn(overrides, current)) out[current] = overrides[key]\n }\n return out ?? overrides\n}\n","/**\n * The render-node registry (SV18, decided 2026-10-06): every node type that\n * turns an EDL into a finished file, and how each one behaves wherever the\n * platform gives a render its meaning — review and the Preview label, privacy,\n * the latest-batch reader, the owner-only listings, and what its `json` handle\n * carries.\n *\n * ONE registry, read by both engines, the editor, the listings and MCP, so a\n * second render (Speaker View) joins by adding one entry — never by finding\n * every `=== \"apply-edl\"`. The backend census test\n * (`render-node-census.test.ts`) fails a new `apply-edl` literal at any site\n * that is not pure registration of that node.\n *\n * The key is the node type AND the job name: a render's job is never renamed\n * (by quality or otherwise — only its credit id changes), so the same key\n * answers for `node.type` and for `jobs.job_type`.\n */\nimport { applyEdlCreditId, speakerViewCreditId, SPEAKER_VIEW_CREDIT_IDS } from \"./credit-identifiers.js\"\nimport type { RenderMedium } from \"./render-output.js\"\n\n/** Where a render's player maps the output clock back to the master clock\n * from: the EDL it was given (`input_data.edl`), or the EDL it emitted on its\n * `json` output (a render that rewrites its EDL, e.g. by splitting turns). */\nexport type RenderClockSource = \"input\" | \"output-json\"\n\n/** What a render's `json` output handle carries. Only a `transcript` is handed\n * on as one (Add Captions, the word-timing preflight). */\nexport type RenderJsonKind = \"transcript\" | \"edl\"\n\n/** Where a render's wired transcript, remapped through its cut, comes out\n * (Apply EDL's on its `json`; Speaker View's on its own `transcript` pip,\n * decided 2026-10-08). */\nexport interface RenderTranscriptOutput {\n /** The output pip — also the key it rides on the job's `output_data` and on\n * a run's node output. */\n readonly handle: string\n /** The saved node-data field that holds it (the landed take's). */\n readonly dataField: string\n}\n\n/** The pip a render's `json` output (its `jsonKind`) comes out on, and its key\n * on the job's `output_data`. */\nexport const RENDER_JSON_HANDLE = \"json\"\n\nexport interface RenderNodeDescriptor {\n /** The medium the render's order asks for (its node data, or its job's\n * `input_data`) — before any output exists to say. */\n readonly mediumOf: (data: Readonly<Record<string, unknown>>) => RenderMedium\n /** The credit id a render reserves on — a per-OUTPUT-MINUTE row: every\n * render is charged its row × the minutes it renders. Chosen from the\n * render's `quality` and `output` (as its node data or its job's request\n * carries them) and, for a render priced in tiers, the `priceTier` the\n * render rule judged it to be in (Speaker View's, decided 2026-10-10). A\n * tiered render given no tier names its dearer row. */\n readonly creditId: (quality: unknown, output?: unknown, priceTier?: unknown) => string\n /** Every id `creditId` can name (each must have a price row). */\n readonly creditIds: readonly string[]\n readonly clockMapFrom: RenderClockSource\n /** Listed in its owner's own views only, never in a public one (decided\n * 2026-10-06): a Preview is private, and a public final would be exposure\n * nobody decided. */\n readonly ownerOnlyListing: boolean\n /** An `each` wire reads its LATEST batch only, never its accumulated history\n * (TA6, decided 2026-10-04). */\n readonly latestBatch: boolean\n readonly jsonKind: RenderJsonKind\n /** Where its remapped transcript comes out. On the `json` pip exactly when\n * `jsonKind` is `transcript` (a guard test holds the two together). */\n readonly transcriptOutput: RenderTranscriptOutput\n}\n\ntype Data = Readonly<Record<string, unknown>>\n\n/** Its `output` setting, video when absent. */\nconst outputSettingMedium = (data: Data): RenderMedium => (data.output === \"audio\" ? \"audio\" : \"video\")\n\nconst descriptor = (d: RenderNodeDescriptor): RenderNodeDescriptor =>\n Object.freeze({ ...d, creditIds: Object.freeze([...d.creditIds]), transcriptOutput: Object.freeze({ ...d.transcriptOutput }) })\n\nexport const RENDER_NODE_TYPES: Readonly<Record<string, RenderNodeDescriptor>> = Object.freeze({\n \"apply-edl\": descriptor({\n mediumOf: outputSettingMedium,\n creditId: (quality) => applyEdlCreditId(quality),\n creditIds: [\"apply-edl\", \"apply-edl:proxy\"],\n clockMapFrom: \"input\",\n ownerOnlyListing: true,\n latestBatch: true,\n jsonKind: \"transcript\",\n transcriptOutput: { handle: RENDER_JSON_HANDLE, dataField: \"generatedJson\" },\n }),\n // Speaker View (C3.2): video only; its `json` is the EDL as it drew it (the\n // turns split, the layouts written), so a player maps the output clock\n // through THAT, and Add Captions never takes it for a Transcript. The wired\n // transcript, remapped through that same drawn edit, comes out on its own\n // `transcript` pip (decided 2026-10-08) — what a caption step reads.\n \"speaker-view\": descriptor({\n mediumOf: () => \"video\",\n creditId: (quality, _output, priceTier) => speakerViewCreditId(quality, priceTier),\n creditIds: SPEAKER_VIEW_CREDIT_IDS,\n clockMapFrom: \"output-json\",\n ownerOnlyListing: true,\n latestBatch: true,\n jsonKind: \"edl\",\n transcriptOutput: { handle: \"transcript\", dataField: \"generatedTranscript\" },\n }),\n})\n\n/** Every render node type, in registry order. */\nexport const RENDER_NODE_TYPE_IDS: readonly string[] = Object.freeze(Object.keys(RENDER_NODE_TYPES))\n\n/** The descriptor of a render node type (or job name); `undefined` for any\n * other value. Own keys only, so `\"constructor\"` is not a render. */\nexport function renderNodeOf(type: unknown): RenderNodeDescriptor | undefined {\n return typeof type === \"string\" && Object.hasOwn(RENDER_NODE_TYPES, type) ? RENDER_NODE_TYPES[type] : undefined\n}\n\n/** Is this node type (or job name) a render? */\nexport function isRenderNodeType(type: unknown): type is string {\n return renderNodeOf(type) !== undefined\n}\n\n/** Does an `each` wire from this node read its latest batch only? */\nexport function rendersLatestBatch(type: unknown): boolean {\n return renderNodeOf(type)?.latestBatch === true\n}\n\n/** Is this node a render whose `json` output is a Transcript? */\nexport function rendersTranscriptJson(type: unknown): boolean {\n return renderNodeOf(type)?.jsonKind === \"transcript\"\n}\n\n/** Where a render's remapped transcript comes out; `undefined` for any other\n * node type. */\nexport function renderTranscriptOutputOf(type: unknown): RenderTranscriptOutput | undefined {\n return renderNodeOf(type)?.transcriptOutput\n}\n\n/** Is `handle` one of a render's data pips — its `json` or its transcript —\n * rather than its media? Every other pip of a render (the default included)\n * is the rendered media. `false` for any other node type. */\nexport function isRenderDataHandle(type: unknown, handle: unknown): boolean {\n const d = renderNodeOf(type)\n if (!d || typeof handle !== \"string\") return false\n return handle === RENDER_JSON_HANDLE || handle === d.transcriptOutput.handle\n}\n\n/** One json output a render lands on its node: its key on the job's\n * `output_data` (and on a run's node output) and its saved node-data field. */\nexport interface RenderSavedJsonOutput {\n readonly outputKey: string\n readonly dataField: string\n}\n\n/** The json outputs a render lands on its node, `json` first, each once — what\n * every lane that lands a take (or picks one) writes or restores. Empty for\n * any other node type. */\nexport function renderSavedJsonOutputs(type: unknown): readonly RenderSavedJsonOutput[] {\n const d = renderNodeOf(type)\n if (!d) return []\n const json: RenderSavedJsonOutput = { outputKey: RENDER_JSON_HANDLE, dataField: \"generatedJson\" }\n const t = d.transcriptOutput\n return t.handle === RENDER_JSON_HANDLE ? [json] : [json, { outputKey: t.handle, dataField: t.dataField }]\n}\n\n/** The render job types that list in their owner's own views only. */\nexport const OWNER_ONLY_LISTING_RENDER_TYPES: readonly string[] = Object.freeze(\n RENDER_NODE_TYPE_IDS.filter((t) => RENDER_NODE_TYPES[t]!.ownerOnlyListing),\n)\n","/**\n * Presentation / API utilities — pure logic, no React deps.\n * Shared between frontend (presentation mode) and backend (API schema generation).\n */\n\nimport type { GenericNode, GenericEdge } from \"./types.js\"\nimport type { PresentationItem } from \"./presentation-types.js\"\nimport { AUDIO_PRODUCER_TYPES, VIDEO_PRODUCER_TYPES } from \"./producer-types.js\"\nimport { canonicalizeOverrideKeys } from \"./exposed-field-keys.js\"\nimport { RENDER_NODE_TYPE_IDS } from \"./render-nodes.js\"\nimport { dropStaleVideoLinkFields } from \"./video-link.js\"\n\n// ---------------------------------------------------------------------------\n// Node type sets\n// ---------------------------------------------------------------------------\n\nexport const INPUT_NODE_TYPES = new Set([\n \"text-prompt\",\n \"upload-image\",\n \"upload-video\",\n \"upload-audio\",\n \"tone\",\n \"style-guide\",\n \"provider\",\n \"scene-count\",\n \"duration\",\n \"aspect-ratio\",\n \"motion\",\n \"camera-motion\",\n \"framing\",\n \"lens\",\n \"camera-format\",\n \"lighting\",\n \"color-look\",\n \"atmosphere\",\n \"action-fx\",\n \"temporal\",\n \"reference-audio\",\n \"youtube-video\",\n])\n\nconst TRIGGER_NODE_TYPES = new Set([\n \"webhook-trigger\",\n \"schedule-trigger\",\n])\n\nconst ALWAYS_EXCLUDED_TYPES = new Set([\n \"sticky-note\",\n \"webhook-trigger\",\n \"schedule-trigger\",\n \"sub-workflow-input\",\n \"sub-workflow-output\",\n])\n\nconst NON_OUTPUT_TYPES = new Set([\n \"text-prompt\",\n \"list\",\n \"upload-image\",\n \"upload-video\",\n \"upload-audio\",\n \"reference-audio\",\n \"rss-feed\",\n \"youtube-video\",\n \"tone\",\n \"style-guide\",\n \"provider\",\n \"scene-count\",\n \"duration\",\n \"aspect-ratio\",\n \"motion\",\n \"camera-motion\",\n \"framing\",\n \"lens\",\n \"camera-format\",\n \"lighting\",\n \"color-look\",\n \"atmosphere\",\n \"action-fx\",\n \"temporal\",\n \"sticky-note\",\n \"sub-workflow-input\",\n \"sub-workflow-output\",\n \"webhook-trigger\",\n \"schedule-trigger\",\n \"combine-text\",\n \"split-text\",\n \"save-to-storage\",\n \"webhook-output\",\n \"component\",\n])\n\n/**\n * Node types that count as an output even when something is wired to their\n * output handle (the legacy `presentationVisible` rule below).\n *\n * A hand-kept list, and one the platform has outgrown: it is unioned at the use\n * site with the producer vocabularies the canvas validators already maintain\n * (see `isMediaProducingType`), so a new media node is covered by the set it\n * must join anyway rather than by remembering to edit this one.\n */\nconst MEDIA_PRODUCING_TYPES = new Set([\n \"generate-image\",\n \"edit-image\",\n \"image-to-image\",\n \"image-to-video\",\n \"text-to-video\",\n \"video-to-video\",\n \"text-to-speech\",\n \"generate-music\",\n \"text-to-audio\",\n \"generate-script\",\n \"ai-writer\",\n \"llm-chat\",\n \"render-video\",\n \"video-composer\",\n \"after-effects\",\n \"lottie-overlay\",\n \"3d-title\",\n \"motion-graphics\",\n \"composite\",\n \"text-to-dialogue\",\n \"voice-changer\",\n \"dubbing\",\n \"voice-remix\",\n \"voice-design\",\n \"extend-video\",\n \"lip-sync\",\n \"motion-transfer\",\n \"video-upscale\",\n \"video-depth\",\n])\n\n// Output type categorizations\nconst IMAGE_OUTPUT_TYPES = new Set([\n \"generate-image\", \"edit-image\", \"image-to-image\",\n \"upload-image\",\n])\n\n/**\n * Video-output types NOT already declared by `VIDEO_PRODUCER_TYPES` — the two\n * are unioned in `getOutputType`, which is where the reading order (and the\n * reason the literal sets win) is documented.\n */\nconst VIDEO_OUTPUT_TYPES = new Set([\n \"image-to-video\", \"text-to-video\", \"video-to-video\", \"extend-video\",\n \"render-video\", \"video-composer\", \"after-effects\", \"lottie-overlay\",\n \"3d-title\", \"motion-graphics\", \"composite\",\n \"combine-videos\", \"merge-video-audio\", \"resize-video\", \"trim-video\",\n \"speed-ramp\", \"loop-video\", \"fade-video\", \"transcode-video\",\n \"upload-video\",\n \"lip-sync\", \"motion-transfer\", \"video-upscale\", \"video-depth\", \"add-captions\",\n \"social-media-format\",\n // A render (Apply EDL) renders an EDL into video OR audio. Its medium is\n // decided at run time (DYNAMIC_PRODUCER_TYPES), so getOutputType would answer\n // \"data\" and a published app would render the cut as a JSON blob. Declaring\n // every render here — as the voice-changer/dubbing precedent does for their\n // default medium — makes the classifier answer \"video\" (the common case; an\n // audio-only cut still plays in a video element). Asserted in\n // producer-types.test.ts.\n ...RENDER_NODE_TYPE_IDS,\n // Tighten Episode: a published app shows the episode as media, never as data\n // (it is not a render, so RENDER_NODE_TYPE_IDS does not bring it).\n \"tighten-episode\",\n])\n\nconst AUDIO_OUTPUT_TYPES = new Set([\n \"text-to-speech\", \"generate-music\", \"text-to-audio\",\n \"text-to-dialogue\", \"voice-changer\", \"dubbing\", \"voice-remix\",\n \"voice-design\", \"mix-audio\", \"adjust-volume\", \"audio-fx\", \"pitch-tempo\", \"trim-audio\",\n \"audio-isolation\",\n \"audio-separation\",\n \"upload-audio\",\n])\n\nconst TEXT_OUTPUT_TYPES = new Set([\n \"generate-script\", \"ai-writer\", \"llm-chat\", \"transcribe\", \"image-to-text\", \"qa-check\",\n \"text-prompt\",\n // UGC Cards' output card is its Notes: a run hands it on as the node's text\n // (`output.text`, `generatedText` on the canvas).\n \"ugc-cards\",\n])\n\n// ---------------------------------------------------------------------------\n// Output type enum\n// ---------------------------------------------------------------------------\n\nexport type OutputType = \"image\" | \"video\" | \"audio\" | \"text\" | \"data\"\n\n// ---------------------------------------------------------------------------\n// Core functions\n// ---------------------------------------------------------------------------\n\n/** Get nodes that act as user inputs (text prompts, uploads, parameters). */\nexport function getInputNodes<T extends GenericNode>(nodes: T[], curatedOnly = true): T[] {\n return nodes.filter((n) => {\n if (!n.type || ALWAYS_EXCLUDED_TYPES.has(n.type)) return false\n if (n.hidden) return false\n if (curatedOnly) {\n // New explicit flag\n if (n.data.presentationInput === true) return true\n // Backwards compat: old flag on input-type nodes\n if (n.data.presentationVisible === true && INPUT_NODE_TYPES.has(n.type)) return true\n return false\n }\n return true\n })\n}\n\n/** Get leaf/media-producing nodes that represent workflow outputs. */\nexport function getOutputNodes<T extends GenericNode>(\n nodes: T[],\n edges: GenericEdge[],\n curatedOnly = true,\n): T[] {\n const nodesWithOutgoing = new Set(edges.map((e) => e.source))\n\n return nodes.filter((n) => {\n if (!n.type || ALWAYS_EXCLUDED_TYPES.has(n.type)) return false\n if (n.hidden) return false\n if (curatedOnly) {\n // New explicit flag\n if (n.data.presentationOutput === true) return true\n // Backwards compat: old flag on output-eligible nodes\n if (n.data.presentationVisible === true) {\n if (NON_OUTPUT_TYPES.has(n.type)) return false\n return !nodesWithOutgoing.has(n.id) || isMediaProducingType(n.type)\n }\n return false\n }\n return true\n })\n}\n\n/**\n * Map node type to its output media type.\n *\n * The four literal sets above are read FIRST and win: they are the presentation\n * classifier's own opinion, including for dual-mode nodes whose default medium\n * is not their handle set (voice-changer and dubbing are audio here even though\n * they can emit video).\n *\n * Anything they do not name falls through to the producer vocabularies the\n * canvas validators and the orchestrator already maintain\n * (`packages/shared/src/producer-types.ts`). Those sets are what a new media\n * node MUST join for its outputs to connect at all, so deriving the tail from\n * them is what stops this map from silently drifting behind the node catalogue\n * — which it had (3D Render Pro, Generate Video, Generate Video Pro and a dozen\n * ffmpeg nodes all read as `\"data\"`, so a published app rendered them as a JSON\n * blob and `/v1` app schemas declared the wrong output type).\n *\n * `DYNAMIC_PRODUCER_TYPES` is deliberately NOT consulted: a node whose medium\n * is decided at run time has no static answer, and `\"data\"` is the honest one.\n */\nexport function getOutputType(nodeType: string | undefined): OutputType {\n if (!nodeType) return \"data\"\n if (IMAGE_OUTPUT_TYPES.has(nodeType)) return \"image\"\n if (VIDEO_OUTPUT_TYPES.has(nodeType)) return \"video\"\n if (AUDIO_OUTPUT_TYPES.has(nodeType)) return \"audio\"\n if (TEXT_OUTPUT_TYPES.has(nodeType)) return \"text\"\n if (VIDEO_PRODUCER_TYPES.has(nodeType)) return \"video\"\n if (AUDIO_PRODUCER_TYPES.has(nodeType)) return \"audio\"\n return \"data\"\n}\n\n/**\n * Whether a node produces media of its own — the test the legacy\n * `presentationVisible` rule uses to keep a media node as an OUTPUT even when\n * it also feeds something downstream.\n *\n * Same union, same reason as `getOutputType`: the hand-kept list plus the\n * producer vocabularies. Text producers stay where the literal list put them\n * (`generate-script`, `ai-writer`, `llm-chat` are members; `transcribe` and\n * `qa-check` are not) — this is about media, not about every node with a value.\n */\nfunction isMediaProducingType(nodeType: string): boolean {\n if (MEDIA_PRODUCING_TYPES.has(nodeType)) return true\n const output = getOutputType(nodeType)\n return output === \"image\" || output === \"video\" || output === \"audio\"\n}\n\n/** Extract the result URL or text from a node's data. */\nexport function getNodeResult(\n nodeData: Record<string, unknown>,\n): { url?: string; text?: string } {\n // Preview node: extract first visible item from previewItems\n const previewItems = nodeData.previewItems as\n | Array<{ type: string; value: string; visible?: boolean }>\n | undefined\n if (previewItems && previewItems.length > 0) {\n const first = previewItems.find((item) => item.visible !== false) ?? previewItems[0]\n if (first) {\n if (first.type === \"image\" || first.type === \"video\" || first.type === \"audio\") {\n return { url: first.value }\n }\n return { text: first.value }\n }\n }\n\n const results = nodeData.generatedResults as\n | Array<Record<string, unknown>>\n | undefined\n\n if (results && results.length > 0) {\n const idx = (nodeData.activeResultIndex as number) ?? 0\n const active = results[idx] ?? results[0]\n const url = (active?.url ?? active?.imageUrl ?? active?.videoUrl ?? active?.audioUrl) as\n | string\n | undefined\n const text = (active?.text ?? active?.script) as string | undefined\n return { url, text }\n }\n\n // Fallback to individual generated fields\n const url = (nodeData.generatedImageUrl ??\n nodeData.generatedVideoUrl ??\n nodeData.generatedAudioUrl) as string | undefined\n const text = (nodeData.generatedScript ?? nodeData.generatedText) as\n | string\n | undefined\n\n return { url, text }\n}\n\n/** Human-readable label for a node. */\nexport function getNodeLabel(node: GenericNode): string {\n return (\n (node.data.label as string) ||\n node.type?.replace(/-/g, \" \").replace(/\\b\\w/g, (c) => c.toUpperCase()) ||\n \"Node\"\n )\n}\n\n// ---------------------------------------------------------------------------\n// Input field schema (for API schema generation)\n// ---------------------------------------------------------------------------\n\nexport interface InputFieldSchema {\n key: string\n type: \"text\" | \"image-url\" | \"video-url\" | \"audio-url\" | \"select\" | \"number\"\n options?: string[]\n}\n\n// Override field per input-node type. The `key` for a parameter-picker MUST be\n// the field that `getParameterValue()` (parameter-node-value.ts) actually reads\n// — for multi-dimension pickers, its FIRST per-dimension field (the\n// \"representative key\"). A mismatch silently drops the curated app/MCP/SDK input\n// (the override lands on a field nothing reads). This map is the single source\n// of truth for app-input override fields (consumed by extract-app-inputs.ts,\n// api-tokens.ts, and the app-runner). Its parity with getParameterValue is\n// guarded by input-field-map-parity.test.ts so the two can't drift.\nexport const INPUT_FIELD_MAP: Record<string, InputFieldSchema> = {\n // --- Source / upload nodes (not parameter pickers) ---\n \"text-prompt\": { key: \"text\", type: \"text\" },\n \"upload-image\": { key: \"url\", type: \"image-url\" },\n \"upload-video\": { key: \"url\", type: \"video-url\" },\n \"upload-audio\": { key: \"url\", type: \"audio-url\" },\n \"reference-audio\": { key: \"extractedAudioUrl\", type: \"audio-url\" },\n // A LINK, not an upload (rule: `videoLinkInputProblem`, video-link.ts); still a `video-url` media input.\n \"youtube-video\": { key: \"youtubeUrl\", type: \"video-url\" },\n // --- Classic parameters ---\n \"provider\": { key: \"provider\", type: \"select\" },\n \"style-guide\": { key: \"text\", type: \"text\" }, // reads data.text (was wrongly \"styleGuide\")\n \"scene-count\": { key: \"count\", type: \"number\" },\n \"duration\": { key: \"seconds\", type: \"number\" }, // reads data.seconds (was wrongly \"duration\")\n \"aspect-ratio\": { key: \"ratio\", type: \"select\" }, // reads data.ratio (was wrongly \"aspectRatio\")\n // --- Single-field parameter pickers ---\n \"tone\": { key: \"tone\", type: \"select\" },\n \"motion\": { key: \"motion\", type: \"select\" },\n \"camera-motion\": { key: \"cameraMotion\", type: \"select\" },\n \"lens\": { key: \"lens\", type: \"select\" },\n \"camera-format\": { key: \"cameraFormat\", type: \"select\" },\n \"color-look\": { key: \"colorLook\", type: \"select\" },\n \"atmosphere\": { key: \"atmosphere\", type: \"select\" },\n \"style\": { key: \"style\", type: \"select\" },\n \"setting\": { key: \"setting\", type: \"select\" },\n \"mood\": { key: \"mood\", type: \"select\" },\n \"photographer\": { key: \"photographer\", type: \"select\" },\n \"aesthetic\": { key: \"aesthetic\", type: \"select\" },\n \"era\": { key: \"era\", type: \"select\" },\n \"material\": { key: \"material\", type: \"select\" },\n \"animal\": { key: \"animal\", type: \"select\" },\n \"vehicle\": { key: \"vehicle\", type: \"select\" },\n \"weapon\": { key: \"weapon\", type: \"select\" },\n \"furniture\": { key: \"furniture\", type: \"select\" },\n \"photo-genre\": { key: \"photoGenre\", type: \"select\" },\n \"backdrop\": { key: \"backdrop\", type: \"select\" },\n \"held-prop\": { key: \"heldProp\", type: \"select\" },\n \"render-quality\": { key: \"renderQuality\", type: \"select\" },\n \"composition-effects\": { key: \"compositionEffect\", type: \"select\" },\n \"post-process-effects\": { key: \"postProcess\", type: \"select\" },\n \"action-fx\": { key: \"actionFx\", type: \"select\" },\n \"character-fx\": { key: \"characterFx\", type: \"select\" },\n \"character-motion\": { key: \"characterMotion\", type: \"select\" },\n \"transition\": { key: \"transition\", type: \"select\" },\n \"loop-subject\": { key: \"loopSubject\", type: \"select\" },\n // --- Multi-dimension pickers: representative (first) field. Overriding only\n // sets that dimension; full hint composition runs in the executors. ---\n \"framing\": { key: \"shotSize\", type: \"select\" },\n \"lighting\": { key: \"timeOfDay\", type: \"select\" },\n \"temporal\": { key: \"temporalSpeed\", type: \"select\" },\n \"person\": { key: \"type\", type: \"select\" },\n \"pose\": { key: \"pose\", type: \"select\" },\n \"styling\": { key: \"makeup\", type: \"select\" },\n \"exposure-settings\": { key: \"aperture\", type: \"select\" },\n \"music-genre\": { key: \"subgenre\", type: \"select\" },\n \"music-mood\": { key: \"emotion\", type: \"select\" },\n \"instrumentation\": { key: \"production\", type: \"select\" },\n \"voice-character\": { key: \"timbre\", type: \"select\" },\n \"voice-delivery\": { key: \"archetype\", type: \"select\" },\n // --- UGC (Cloud) ---\n \"ugc-creator\": { key: \"source\", type: \"select\" },\n}\n\n/**\n * Extra API-settable keys for node types whose card writes more than one field\n * (INPUT_FIELD_MAP is one key per node type). Read by extract-app-inputs and the\n * app runner; every key here must be in UGC_OVERRIDABLE_FIELDS for a UGC type.\n */\nexport const INPUT_FIELD_EXTRA_KEYS: Readonly<Record<string, readonly InputFieldSchema[]>> = {\n \"ugc-creator\": [{ key: \"gender\", type: \"select\" }, { key: \"photoUrl\", type: \"image-url\" }],\n // The script's language: changes together with UGC_OVERRIDABLE_FIELDS[\"ugc-script\"] and UgcScriptData.language.\n \"ugc-script\": [{ key: \"language\", type: \"select\" }],\n}\n\n/** The extra override fields of a node type (none for most types). */\nexport function getInputFieldExtraKeys(nodeType: string): readonly InputFieldSchema[] {\n return Object.hasOwn(INPUT_FIELD_EXTRA_KEYS, nodeType) ? INPUT_FIELD_EXTRA_KEYS[nodeType]! : []\n}\n\n/** Get the overridable field schema for an input node type. */\nexport function getInputFieldSchema(nodeType: string): InputFieldSchema | undefined {\n return INPUT_FIELD_MAP[nodeType]\n}\n\nconst MEDIA_INPUT_FIELD_TYPES: ReadonlySet<InputFieldSchema[\"type\"]> = new Set([\n \"image-url\",\n \"video-url\",\n \"audio-url\",\n])\n\n/**\n * Shallow-merge run-time input overrides (a published app's inputs, an API-token\n * run, MCP `run_app` / `run_workflow` inputs, a wired component handle) over a\n * node's SAVED data — the one merge every such lane must use.\n *\n * `metadata` holds facts measured FROM the node's media (its length, its\n * dimensions). When an override swaps that media — the node's primary input\n * field is a media url (`INPUT_FIELD_MAP`) and the override changes it — the\n * snapshot's facts describe a file that is no longer there, so they are dropped\n * unless the override supplies its own. Left behind, a publisher's\n * `metadata.durationSeconds` outranks the run's own transcript as Edit Plan's\n * duration basis and under-buckets a caller's longer episode: an estimate that\n * passes the balance precheck for a run the reserve then refuses.\n *\n * Schema-driven on purpose: a new media input node is covered by its\n * `INPUT_FIELD_MAP` row, with no list to remember here.\n *\n * An override sent under a renamed exposed-field key (an app published before\n * the rename) lands on the node's current field — `canonicalizeOverrideKeys`.\n *\n * An override of `null` clears the field: the merged node has no such key.\n */\nexport function mergeNodeInputOverrides(\n nodeType: string | undefined,\n data: Record<string, unknown>,\n overrides: Record<string, unknown>,\n): Record<string, unknown> {\n const incoming = canonicalizeOverrideKeys(nodeType, overrides)\n // A Video URL node on a new link sheds what was fetched for the old one.\n const base = nodeType === \"youtube-video\" ? dropStaleVideoLinkFields(data, incoming) : data\n const merged: Record<string, unknown> = { ...base, ...incoming }\n // A null override CLEARS the field: the run has no value there, neither null nor the saved one. JSON cannot\n // carry `undefined`, so this is how a run says \"unset\" (an app card clearing a lever the chosen model lacks).\n for (const [key, value] of Object.entries(incoming)) {\n if (value === null) delete merged[key]\n }\n const schema = nodeType ? INPUT_FIELD_MAP[nodeType] : undefined\n if (\n schema &&\n MEDIA_INPUT_FIELD_TYPES.has(schema.type) &&\n schema.key in overrides &&\n overrides[schema.key] !== data[schema.key] &&\n !(\"metadata\" in overrides)\n ) {\n delete merged.metadata\n }\n return merged\n}\n\n// ---------------------------------------------------------------------------\n// Migration & validation helpers (PresentationItem)\n// ---------------------------------------------------------------------------\n\n/** Migrate a legacy string[] order to PresentationItem[]. */\nexport function migrateToItems(order: string[] | undefined): PresentationItem[] | undefined {\n if (!order) return undefined\n return order.map((nodeId) => ({ type: \"node\" as const, nodeId }))\n}\n\n/** Strip nested groups — groups may only contain non-group items. */\nexport function validateNoNestedGroups(items: PresentationItem[]): PresentationItem[] {\n return items.map((item) => {\n if (item.type === \"group\") {\n return { ...item, items: item.items.filter((child) => child.type !== \"group\") }\n }\n return item\n })\n}\n\n/** Recursively flatten all items, unwrapping groups. */\nexport function flattenItems(items: PresentationItem[]): PresentationItem[] {\n const result: PresentationItem[] = []\n for (const item of items) {\n if (item.type === \"group\") {\n result.push(...flattenItems(item.items))\n } else {\n result.push(item)\n }\n }\n return result\n}\n\n/** Get the sortable/unique ID for a PresentationItem. */\nexport function getItemSortId(item: PresentationItem): string {\n return item.type === \"node\" ? item.nodeId : item.id\n}\n\n/** Remove items whose nodeId no longer exists in the workflow. */\nexport function cleanOrphanedItems(\n items: PresentationItem[],\n nodeIds: Set<string>\n): PresentationItem[] {\n return items\n .filter((item) => {\n if (item.type === \"node\" || item.type === \"field\" || item.type === \"output\") return nodeIds.has(item.nodeId)\n return true\n })\n .map((item) => {\n if (item.type === \"group\") {\n return { ...item, items: cleanOrphanedItems(item.items, nodeIds) }\n }\n return item\n })\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/pinterest-url.ts","../src/scraper-output-schemas.ts","../src/telegram-account-trigger.ts","../src/telegram-account-send.ts","../src/scraper-actors.ts","../src/meta-ads-scrape.ts","../src/instagram-scrape.ts","../src/social-search.ts","../src/saved-posts.ts","../src/social-post-readers.ts","../src/competitors.ts","../src/social-media-specs.ts","../src/telegram-channel.ts"],"names":["analysisSuffix","urlStrings","isRecord","str","emitted"],"mappings":";;;AAgBO,SAAS,sBAAsB,GAAA,EAAqB;AACzD,EAAA,IAAI;AACF,IAAA,MAAM,CAAA,GAAI,IAAI,GAAA,CAAI,GAAG,CAAA;AACrB,IAAA,IAAI,CAAA,CAAE,QAAA,KAAa,cAAA,EAAgB,OAAO,GAAA;AAC1C,IAAA,MAAM,IAAA,GAAO,CAAA,CAAE,QAAA,CAAS,OAAA,CAAQ,2BAA2B,aAAa,CAAA;AACxE,IAAA,IAAI,IAAA,KAAS,CAAA,CAAE,QAAA,EAAU,OAAO,GAAA;AAChC,IAAA,CAAA,CAAE,QAAA,GAAW,IAAA;AACb,IAAA,OAAO,EAAE,QAAA,EAAS;AAAA,EACpB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,GAAA;AAAA,EACT;AACF;;;AChBO,IAAM,qBAAA,GAAmE;AAAA,EAC9E,iBAAA,EAAmB,CAAC,WAAA,EAAa,gBAAgB,CAAA;AAAA,EACjD,eAAA,EAAmB,CAAC,OAAA,EAAS,KAAA,EAAO,aAAa,CAAA;AAAA,EACjD,WAAA,EAAmB;A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AAI,UAAU,MAAA,EAAW;AACvB,IAAA,MAAMC,QAAAA,GAAU,MAAA,CAAO,KAAA,CAAM,CAAC,GAAG,CAAA;AACjC,IAAA,OAAO,EAAE,OAAA,EAAAA,QAAAA,EAAS,QAAA,EAAU,MAAA,CAAO,MAAA,GAAS,CAAA,GAAI,MAAA,CAAO,MAAA,CAAO,MAAA,GAAS,CAAC,CAAA,CAAG,KAAK,MAAA,EAAU;AAAA,EAC5F;AACA,EAAA,MAAM,QAAQ,MAAA,CAAO,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,KAAK,KAAK,CAAA;AAC/C,EAAA,MAAM,OAAA,GAAU,KAAA,CAAM,KAAA,CAAM,CAAA,EAAG,GAAG,CAAA;AAClC,EAAA,IAAI,OAAA,CAAQ,MAAA,GAAS,CAAA,EAAG,OAAO,EAAE,OAAA,EAAS,QAAA,EAAU,OAAA,CAAQ,OAAA,CAAQ,MAAA,GAAS,CAAC,CAAA,CAAG,EAAA,EAAG;AACpF,EAAA,MAAM,iBAAiB,SAAA,KAAc,MAAA,IAAa,OAAO,QAAA,CAAS,SAAS,KAAK,SAAA,GAAY,KAAA;AAC5F,EAAA,OAAO,EAAE,OAAA,EAAS,QAAA,EAAU,cAAA,GAAiB,YAAY,KAAA,EAAM;AACjE","file":"chunk-WDIBOWAA.js","sourcesContent":["/**\n * Auto-upgrade Pinterest CDN URLs to their highest-resolution variant.\n *\n * `i.pinimg.com` serves the same image at multiple sizes via a path-prefix\n * segment: `/236x/`, `/474x/`, `/564x/`, `/736x/`, `/1200x/`, `/originals/`.\n * The `originals` segment returns the source resolution — much better input\n * for `describe-image`, `image-to-image`, `face-swap`, etc.\n *\n * Returns the input unchanged when:\n * - the URL doesn't parse as a URL\n * - the host isn't `i.pinimg.com`\n * - the path doesn't start with a recognized size segment\n *\n * Used by the upload-image node when a user pastes a Pinterest URL, and by\n * any backend describe-image-style fetch that wants the highest-res input.\n */\nexport function normalizePinterestUrl(url: string): string {\n try {\n const u = new URL(url)\n if (u.hostname !== \"i.pinimg.com\") return url\n const next = u.pathname.replace(/^\\/(?:\\d+x|originals)\\//, \"/originals/\")\n if (next === u.pathname) return url\n u.pathname = next\n return u.toString()\n } catch {\n return url\n }\n}\n","import type { ScraperActorId } from \"./scraper-actors.js\"\n\n/**\n * Scalar fields exposed in the Extract Field dropdown when the direct\n * upstream is a web-scrape node. Nested / non-scalar fields (authorMeta,\n * musicMeta) are intentionally omitted — users access them via the\n * \"Custom path...\" option.\n *\n * content-crawler paths are pre-dotted (`pages.url`, `pages.markdown`)\n * because its root shape is `{ pages: [...] }`, not a top-level array.\n */\nexport const SCRAPER_OUTPUT_FIELDS: Record<ScraperActorId, readonly string[]> = {\n \"content-crawler\": [\"pages.url\", \"pages.markdown\"],\n \"google-search\": [\"title\", \"url\", \"description\"],\n \"instagram\": [\n \"url\", \"shortCode\", \"caption\", \"displayUrl\", \"videoUrl\",\n \"timestamp\", \"likesCount\", \"commentsCount\", \"ownerUsername\", \"type\",\n \"childPosts\",\n ],\n \"tiktok\": [\n \"id\", \"webVideoUrl\", \"videoUrl\", \"text\", \"createTime\",\n \"diggCount\", \"shareCount\", \"playCount\", \"commentCount\",\n ],\n \"rss\": [\"title\", \"url\", \"description\", \"pubDate\", \"guid\"],\n} as const\n","/**\n * The Telegram Account Trigger's named outputs — the wire contract between the\n * Cloud connector that starts a run (it writes these keys into the run's\n * trigger data) and everything that reads them: both workflow engines, the\n * canvas card and the public node registry. A handle id IS the trigger-data\n * key, so the two can never disagree.\n *\n * Structural vocabulary only: the keys and what each one carries. How the\n * connector decides which key a post fills is not part of the contract.\n */\n\n/** The message itself — the card's original output. */\nexport const TELEGRAM_ACCOUNT_TRIGGER_MESSAGE_HANDLE = \"out\"\n\n/**\n * Named outputs, in the order the card shows them. Exactly one of `videoLink`\n * and `postText` carries a value in a run that is about a shared post; both\n * are empty otherwise. Never undefined — an engine reading an empty one gets\n * \"\", never the message text in its place.\n */\nexport const TELEGRAM_ACCOUNT_TRIGGER_POST_FIELDS = [\n /** The post's link, when the post has a video to analyze. */\n \"videoLink\",\n /** The post's words, when it has no video: the message, the link's preview, or the forwarded post. */\n \"postText\",\n /** The link of the post this run is about, whatever its kind. */\n \"postLink\",\n] as const\n\nexport type TelegramAccountTriggerPostField = (typeof TELEGRAM_ACCOUNT_TRIGGER_POST_FIELDS)[number]\n\n/** Message facts carried alongside — read through trigger tokens and JSON-authored wires. */\nexport const TELEGRAM_ACCOUNT_TRIGGER_MESSAGE_FIELDS = [\n \"chatId\",\n \"chatType\",\n \"messageId\",\n \"senderId\",\n] as const\n\n/** Every handle the card renders, `out` first. */\nexport const TELEGRAM_ACCOUNT_TRIGGER_OUTPUT_HANDLES: readonly string[] = [\n TELEGRAM_ACCOUNT_TRIGGER_MESSAGE_HANDLE,\n ...TELEGRAM_ACCOUNT_TRIGGER_POST_FIELDS,\n]\n\nconst NAMED_HANDLES: ReadonlySet<string> = new Set([...TELEGRAM_ACCOUNT_TRIGGER_POST_FIELDS, ...TELEGRAM_ACCOUNT_TRIGGER_MESSAGE_FIELDS])\n\n/**\n * A handle naming one value of the run (a post field or a message fact) —\n * every handle but the message itself. A wire from one carries that value,\n * \"\" when the run has none, never the message in its place.\n */\nexport function isTelegramAccountTriggerNamedHandle(handle: unknown): handle is string {\n return typeof handle === \"string\" && NAMED_HANDLES.has(handle)\n}\n\n/**\n * What an account trigger listens to, and whether it listens: the settings\n * only its owner may set. One canonical string, so the editor that changed a\n * trigger and the server that arms it compare the same thing — the server\n * arms a trigger the owner's editor named only while the stored node still\n * says exactly what that editor set.\n *\n * It states what the trigger hears, not how the node spells it: in inbox mode\n * the owner's own messages are always heard, so `includeOutgoing` reads as on\n * there — a setting the panel does not show in that mode never decides a match.\n * The account id is the one exception: it is read exactly as written, because\n * the server never listens on one that is not written exactly (padded), and\n * the editor shows such an id as no account of the owner's.\n */\nexport function telegramAccountListeningSignature(data: unknown): string {\n const d = (data !== null && typeof data === \"object\" ? data : {}) as Record<string, unknown>\n const list = (value: unknown): string[] =>\n Array.isArray(value)\n ? [...new Set(value.filter((x): x is string => typeof x === \"string\").map((x) => x.trim()).filter((x) => x !== \"\"))].sort()\n : []\n return JSON.stringify({\n accountId: typeof d.accountId === \"string\" ? d.accountId : \"\",\n chatIds: list(d.chatIds),\n senderIds: list(d.senderIds),\n messageTypeFilters: list(d.messageTypeFilters),\n keywords: list(d.keywords),\n includeOutgoing: d.inboxMode === true || d.includeOutgoing === true,\n inboxMode: d.inboxMode === true,\n isActive: d.isActive === true,\n })\n}\n\nfunction stringField(value: unknown): string {\n if (typeof value === \"string\") return value.trim()\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value)\n return \"\"\n}\n\n/**\n * The named outputs of one run, from its trigger data: every post field\n * present (possibly \"\"), each message field only when it has a value.\n */\nexport function telegramAccountTriggerOutputs(triggerData: Record<string, unknown> | null | undefined): Record<string, string> {\n const td = triggerData ?? {}\n const out: Record<string, string> = {}\n for (const key of TELEGRAM_ACCOUNT_TRIGGER_POST_FIELDS) out[key] = stringField(td[key])\n for (const key of TELEGRAM_ACCOUNT_TRIGGER_MESSAGE_FIELDS) {\n const value = stringField(td[key])\n if (value !== \"\") out[key] = value\n }\n return out\n}\n","/**\n * Telegram Reply (`telegram-account-send`) — who writes the message and\n * where it goes, as node data spells it. Structural vocabulary only: every\n * destination is the run's OWNER — the chat of the post they shared, their\n * Saved Messages, or their private chat with their own bot. How the Cloud\n * connector sends is not part of the contract.\n */\n\nexport const TELEGRAM_ACCOUNT_SEND_NODE_TYPE = \"telegram-account-send\"\n\n/** `account`: the owner's connected account writes. `bot`: the owner's own bot writes to them privately. */\nexport const TELEGRAM_SEND_AS = [\"account\", \"bot\"] as const\nexport type TelegramSendAs = (typeof TELEGRAM_SEND_AS)[number]\n\n/**\n * Where an account-written message goes. `reply`: under the post that started\n * the run, in its chat (a run started by the Telegram Account Trigger only).\n * `saved`: the owner's Saved Messages. A bot always writes to the owner's\n * private chat with it, so it has no destination to choose.\n */\nexport const TELEGRAM_SEND_DESTINATIONS = [\"reply\", \"saved\"] as const\nexport type TelegramSendDestination = (typeof TELEGRAM_SEND_DESTINATIONS)[number]\n\n/** The node's `sendAs`, as every reader reads it: anything else is the account. */\nexport function telegramSendAsOf(value: unknown): TelegramSendAs {\n return value === \"bot\" ? \"bot\" : \"account\"\n}\n\n/** The node's `destination`, as every reader reads it: anything else is a reply. */\nexport function telegramSendDestinationOf(value: unknown): TelegramSendDestination {\n return value === \"saved\" ? \"saved\" : \"reply\"\n}\n","export const SCRAPER_ACTOR_IDS = [\n \"content-crawler\",\n \"google-search\",\n \"instagram\",\n \"tiktok\",\n \"rss\",\n] as const\n\nexport type ScraperActorId = (typeof SCRAPER_ACTOR_IDS)[number]\n\nexport const SCRAPER_ACTOR_LABELS: Record<ScraperActorId, string> = {\n \"content-crawler\": \"Website Content (Markdown)\",\n \"google-search\": \"Google Search\",\n \"instagram\": \"Instagram\",\n \"tiktok\": \"TikTok\",\n \"rss\": \"RSS Feed\",\n}\n\n/** Credit costs per composite SKU — must stay in sync with STATIC_CREDIT_COSTS in backend.\n *\n * \"Must stay in sync\" was doing no work: these were left at the pre-2026-07-30\n * credit base while the backend moved, so every SKU here read a tenth of the\n * real price. Values below are copied from `model_pricing`, which is what the\n * user is actually charged. */\nexport const SCRAPER_CREDIT_COSTS: Record<string, number> = {\n \"web-scrape\": 20,\n \"web-scrape:google-search\": 30,\n \"web-scrape:content-crawler\": 10,\n \"web-scrape:content-crawler:site\": 50,\n \"web-scrape:instagram\": 10,\n \"web-scrape:tiktok\": 10,\n \"web-scrape:rss\": 10,\n}\n\nexport function isScraperActor(value: unknown): value is ScraperActorId {\n return typeof value === \"string\" && (SCRAPER_ACTOR_IDS as readonly string[]).includes(value)\n}\n\nexport interface ScraperCreditInput {\n actor: ScraperActorId\n mode?: \"page\" | \"site\"\n}\n\nexport function buildScraperCreditId(input: ScraperCreditInput): string {\n if (input.actor === \"content-crawler\") {\n const mode = input.mode ?? \"page\"\n return mode === \"site\" ? \"web-scrape:content-crawler:site\" : \"web-scrape:content-crawler\"\n }\n return `web-scrape:${input.actor}`\n}\n\n/**\n * Resolve the credit identifier from an unvalidated request body.\n * Falls back to a fixed default SKU (google-search) on missing/invalid actor\n * so misrouted requests reserve a known mid-tier price, not the max-cost tier.\n */\nexport function resolveScraperCreditId(body: unknown): string {\n const raw = body as { actor?: unknown; mode?: unknown } | undefined\n if (!raw || !isScraperActor(raw.actor)) return \"web-scrape:google-search\"\n const mode = raw.mode === \"site\" ? \"site\" : \"page\"\n return buildScraperCreditId({ actor: raw.actor, mode })\n}\n","/**\n * Meta Ads scraper node — shared vocabulary + credit identifiers.\n *\n * The node pulls PUBLIC ads (Facebook + Instagram placements) out of Meta's\n * Ad Library, either by keyword search or by Facebook Page URL, and emits a\n * JSON array of normalized ads. Everything the backend guard/reservation, the\n * frontend credit badge and the docs formula must agree on lives here so the\n * three cannot drift apart.\n *\n * The editor has a third, node-only mode — \"advertiser\": pick advertisers by\n * name (a page lookup) and run as their Page urls. The wire contract stays\n * search / pages; `metaAdsScrapeWireSources` is the ONE mapping both engines\n * call, and `metaAdsScrapeSources` the ONE source count every quote reads.\n *\n * Pricing shape: 1 credit per REQUESTED ad, rounded UP to a fixed tier. The\n * requested total is `count × sources` (search = 1 source; pages = one per\n * URL). The route's Zod bounds `count ≤ 100` and `sources ≤ 5`, so the total\n * can never land outside the tier set — an identifier missing from\n * `model_pricing` is a 503 `price_not_configured`, never a silent fallback.\n */\nimport { LLM_FEATURE_DEFAULTS, getLlmTier } from \"./llm-models.js\"\n\nexport const META_ADS_SCRAPE_NODE_TYPE = \"meta-ads-scrape\" as const\n\n/** The WIRE modes — what `POST /v1/meta-ads-scrape` accepts. */\nexport const META_ADS_SCRAPE_MODES = [\"search\", \"pages\"] as const\nexport type MetaAdsScrapeMode = (typeof META_ADS_SCRAPE_MODES)[number]\n\n/** The NODE modes — the wire modes plus the editor-only advertiser picker (runs as pages). */\nexport const META_ADS_NODE_MODES = [...META_ADS_SCRAPE_MODES, \"advertiser\"] as const\nexport type MetaAdsNodeMode = (typeof META_ADS_NODE_MODES)[number]\n\n/** Coerce stored node data to a node mode; anything unknown is the default keyword search. */\nexport function metaAdsNodeMode(value: unknown): MetaAdsNodeMode {\n return typeof value === \"string\" && (META_ADS_NODE_MODES as readonly string[]).includes(value) ? (value as MetaAdsNodeMode) : \"search\"\n}\n\n/** An advertiser the user picked by name — stored on the node, run as its Page url. */\nexport interface MetaAdsAdvertiser {\n readonly pageId: string\n readonly name: string\n /** The Facebook Page url. The actor resolves it to the Ad Library advertiser itself — the Page id and the advertiser id are NOT the same number. */\n readonly url: string\n readonly imageUrl?: string\n readonly verified?: boolean\n}\n\n/** How many matches an advertiser lookup returns — more than the pick cap, so a same-name brand can be told apart by its badge / avatar. */\nexport const META_ADS_ADVERTISER_MAX_RESULTS = 8\nconst META_ADS_URL_MAX_LENGTH = 2048\n\nfunction httpUrlOnHost(value: unknown, host: RegExp): value is string {\n if (typeof value !== \"string\" || value.length > META_ADS_URL_MAX_LENGTH) return false\n try {\n const url = new URL(value)\n return (url.protocol === \"https:\" || url.protocol === \"http:\") && host.test(url.hostname)\n } catch {\n return false\n }\n}\n\n/** http(s) url on facebook.com (any subdomain) — the ONE predicate for a Page address, on the route's Zod and on stored picks alike. */\nexport function isFacebookPageUrl(value: unknown): value is string {\n return httpUrlOnHost(value, /(^|\\.)facebook\\.com$/i)\n}\n\n/** A Page avatar lives on Meta's CDN; anything else is not stored (it would be fetched by every viewer's browser and our image proxy). */\nexport function isMetaCdnImageUrl(value: unknown): value is string {\n return httpUrlOnHost(value, /(^|\\.)(fbcdn\\.net|facebook\\.com)$/i)\n}\n\n/** Stored / relayed advertisers, sanitized: a page id, a name, a facebook.com url, a Meta-CDN avatar; deduped by page id; at most `limit` (the pick cap by default). */\nexport function metaAdsAdvertisersFrom(raw: unknown, limit: number = META_ADS_SCRAPE_MAX_SOURCES): MetaAdsAdvertiser[] {\n if (!Array.isArray(raw) || limit < 1) return []\n const seen = new Set<string>()\n const out: MetaAdsAdvertiser[] = []\n for (const item of raw) {\n if (!item || typeof item !== \"object\") continue\n const r = item as Record<string, unknown>\n const pageId =\n typeof r.pageId === \"string\" ? r.pageId.trim() : typeof r.pageId === \"number\" && Number.isFinite(r.pageId) ? String(r.pageId) : \"\"\n const name = typeof r.name === \"string\" ? r.name.trim().slice(0, 120) : \"\"\n if (!pageId || !name || !isFacebookPageUrl(r.url) || seen.has(pageId)) continue\n seen.add(pageId)\n out.push({\n pageId,\n name,\n url: r.url,\n ...(isMetaCdnImageUrl(r.imageUrl) ? { imageUrl: r.imageUrl } : {}),\n ...(r.verified === true ? { verified: true } : {}),\n })\n if (out.length >= limit) break\n }\n return out\n}\n\nexport const META_ADS_SCRAPE_PERIODS = [\"24h\", \"7d\", \"30d\", \"all\"] as const\nexport type MetaAdsScrapePeriod = (typeof META_ADS_SCRAPE_PERIODS)[number]\n\nexport const META_ADS_SCRAPE_STATUSES = [\"active\", \"inactive\", \"all\"] as const\nexport type MetaAdsScrapeStatus = (typeof META_ADS_SCRAPE_STATUSES)[number]\n\n/** Meta's `publisher_platform` vocabulary — the values an ad's `platforms` carries and the filter the node accepts. */\nexport const META_ADS_PLATFORMS = [\"FACEBOOK\", \"INSTAGRAM\", \"AUDIENCE_NETWORK\", \"MESSENGER\", \"WHATSAPP\", \"THREADS\"] as const\nexport type MetaAdsPlatform = (typeof META_ADS_PLATFORMS)[number]\n\nexport function isMetaAdsPlatform(value: unknown): value is MetaAdsPlatform {\n return typeof value === \"string\" && (META_ADS_PLATFORMS as readonly string[]).includes(value)\n}\n\n/**\n * Creative format, classified from the creative's measured pixels — the\n * user's \"phone vs web\" question. `vertical` = Stories / Reels / mobile feed\n * (9:16, 4:5), `square` = 1:1 (±5 %), `horizontal` = feed / web / banners\n * (16:9, 1.91:1). One classifier for the route (node setting), the Results\n * chips and the card, so they can never disagree.\n */\nexport const META_ADS_FORMATS = [\"vertical\", \"square\", \"horizontal\"] as const\nexport type MetaAdsFormat = (typeof META_ADS_FORMATS)[number]\nexport type MetaAdsCreativeFormat = MetaAdsFormat | \"unknown\"\n\nexport function isMetaAdsFormat(value: unknown): value is MetaAdsFormat {\n return typeof value === \"string\" && (META_ADS_FORMATS as readonly string[]).includes(value)\n}\n\n/** The featured ad index, clamped so a rerun that returned fewer ads never indexes past the end. */\nexport function clampMetaAdsFeaturedIndex(stored: unknown, count: number): number {\n if (count <= 0) return 0\n const n = typeof stored === \"number\" && Number.isFinite(stored) ? Math.trunc(stored) : 0\n return Math.min(Math.max(n, 0), count - 1)\n}\n\nexport interface FeaturedMetaAdOutputs {\n readonly text?: string\n readonly imageUrl?: string\n readonly videoUrl?: string\n}\n\nfunction urlStrings(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((v): v is string => typeof v === \"string\" && v.trim().length > 0) : []\n}\n\n/**\n * What the node's typed `text` / `image` / `video` handles carry: the\n * FEATURED ad's copy (headline + body), first image (else the video poster)\n * and first video. ONE derivation for the route's output_data, the backend\n * saved-output hydration and the editor's extractNodeOutput, so a thumb pick\n * re-hydrates the handles identically everywhere.\n */\nexport function featuredMetaAdOutputs(json: unknown, featuredIndex: unknown): FeaturedMetaAdOutputs {\n if (!Array.isArray(json) || json.length === 0) return {}\n const ad = json[clampMetaAdsFeaturedIndex(featuredIndex, json.length)]\n if (!ad || typeof ad !== \"object\") return {}\n const a = ad as Record<string, unknown>\n const title = typeof a.title === \"string\" ? a.title.trim() : \"\"\n const body = typeof a.text === \"string\" ? a.text.trim() : \"\"\n const text = [title, body].filter((s) => s.length > 0).join(\"\\n\\n\")\n const imageUrl = urlStrings(a.images)[0] ?? urlStrings(a.videoPreviews)[0]\n const videoUrl = urlStrings(a.videos)[0]\n return {\n ...(text ? { text } : {}),\n ...(imageUrl ? { imageUrl } : {}),\n ...(videoUrl ? { videoUrl } : {}),\n }\n}\n\nexport function classifyCreativeFormat(width: unknown, height: unknown): MetaAdsCreativeFormat {\n if (typeof width !== \"number\" || typeof height !== \"number\" || !Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {\n return \"unknown\"\n }\n const ratio = width / height\n if (ratio < 0.95) return \"vertical\"\n if (ratio <= 1.05) return \"square\"\n return \"horizontal\"\n}\n\n/** Presets the config panel offers; the route accepts any integer 1..MAX_COUNT. */\nexport const META_ADS_SCRAPE_COUNT_OPTIONS = [10, 20, 50, 100] as const\nexport const META_ADS_SCRAPE_DEFAULT_COUNT = 20\nexport const META_ADS_SCRAPE_MAX_COUNT = 100\nexport const META_ADS_SCRAPE_MAX_SOURCES = 5\n/** Meta caps Ad Library search terms at 100 characters. */\nexport const META_ADS_SCRAPE_MAX_QUERY_LENGTH = 100\nexport const META_ADS_SCRAPE_DEFAULT_COUNTRY = \"ALL\"\n\n/** Requested-total buckets. Sorted ascending; the last one is `MAX_COUNT × MAX_SOURCES`. */\nexport const META_ADS_SCRAPE_TIERS = [10, 20, 50, 100, 200, 500] as const\nexport type MetaAdsScrapeTier = (typeof META_ADS_SCRAPE_TIERS)[number]\n\n/**\n * Optional per-ad AI analysis — the \"expert competitor ad analyst\" pass.\n * Priced per REQUESTED ad like the scrape, by the analysing model's tier,\n * and folded into the SAME tiered identifier so every quote (guard,\n * reservation, card badge, run total, backend estimator) stays one SKU:\n *\n * meta-ads-scrape:<tier> tier\n * meta-ads-scrape:<tier>:analysis tier × (1 + 3) standard models\n * meta-ads-scrape:<tier>:analysis:economy tier × (1 + 1)\n * meta-ads-scrape:<tier>:analysis:premium tier × (1 + 4)\n *\n * The per-ad SKUs (`meta-ads-analysis[:economy|:premium]`) price the\n * SETTLEMENT: a run commits tier + per-ad × ads actually analysed and\n * refunds the rest (an ad the model failed on, or one the deadline skipped).\n */\nexport const META_ADS_ANALYSIS_TIERS = [\"economy\", \"standard\", \"premium\"] as const\nexport type MetaAdsAnalysisTier = (typeof META_ADS_ANALYSIS_TIERS)[number]\nexport const META_ADS_ANALYSIS_CREDITS_PER_AD: Record<MetaAdsAnalysisTier, number> = { economy: 1, standard: 3, premium: 4 }\nexport const META_ADS_ANALYSIS_CREDIT_ID = \"meta-ads-analysis\" as const\n/** The user's optional analyst focus, appended to the fixed prompt. */\nexport const META_ADS_ANALYSIS_FOCUS_MAX = 500\n\n/** The per-ad settlement SKU for a tier (the bare id is the standard tier). */\nexport function metaAdsAnalysisCreditId(tier: MetaAdsAnalysisTier): string {\n return tier === \"standard\" ? META_ADS_ANALYSIS_CREDIT_ID : `${META_ADS_ANALYSIS_CREDIT_ID}:${tier}`\n}\n\n/** The analysing model's tier; an absent model is the feature default. */\nexport function metaAdsAnalysisTier(modelId?: unknown): MetaAdsAnalysisTier {\n const id = typeof modelId === \"string\" && modelId ? modelId : LLM_FEATURE_DEFAULTS[\"meta-ads-analysis\"]\n return getLlmTier(id)\n}\n\n/** What one analysed ad carries (`ad.analysis`); fixed fields + string lists only — never a map (Gemini via KIE drops map fields). */\nexport interface AdCreativeAnalysis {\n readonly assetType: \"static\" | \"motion\" | \"carousel\" | \"unknown\"\n readonly format: string\n readonly visualHooks: readonly string[]\n readonly audiences: readonly string[]\n readonly graphicIdentity: string\n readonly copywritingHooks: readonly string[]\n readonly usps: readonly string[]\n readonly cta: string\n readonly summary: string\n}\n\nconst strList = (v: unknown): string[] => (Array.isArray(v) ? v.filter((s): s is string => typeof s === \"string\" && s.trim().length > 0) : [])\nconst str = (v: unknown): string => (typeof v === \"string\" ? v : \"\")\n\n/** Read a stored analysis back defensively (a node's saved JSON is untrusted shape); null when there is none. */\nexport function adCreativeAnalysisFrom(raw: unknown): AdCreativeAnalysis | null {\n if (!raw || typeof raw !== \"object\") return null\n const r = raw as Record<string, unknown>\n if (typeof r.summary !== \"string\" || !r.summary.trim()) return null\n const assetType = r.assetType === \"static\" || r.assetType === \"motion\" || r.assetType === \"carousel\" ? r.assetType : \"unknown\"\n return {\n assetType,\n format: str(r.format),\n visualHooks: strList(r.visualHooks),\n audiences: strList(r.audiences),\n graphicIdentity: str(r.graphicIdentity),\n copywritingHooks: strList(r.copywritingHooks),\n usps: strList(r.usps),\n cta: str(r.cta),\n summary: r.summary,\n }\n}\n\n/** The `:analysis[:tier]` suffix on a scrape SKU for an analysis tier. */\nfunction analysisSuffix(tier: MetaAdsAnalysisTier): string {\n return tier === \"standard\" ? \":analysis\" : `:analysis:${tier}`\n}\n\nfunction buildMetaAdsCreditCostTable(): Record<string, number> {\n const table: Record<string, number> = { [META_ADS_SCRAPE_NODE_TYPE]: 20 }\n for (const tier of META_ADS_ANALYSIS_TIERS) table[metaAdsAnalysisCreditId(tier)] = META_ADS_ANALYSIS_CREDITS_PER_AD[tier]\n // Key by the TIER value directly (not via a count that clamps at MAX_COUNT):\n // the 200 / 500 tiers are reachable through sources > 1, so their analysis\n // rows must exist and be tier-based, not count-based.\n for (const t of META_ADS_SCRAPE_TIERS) {\n table[`${META_ADS_SCRAPE_NODE_TYPE}:${t}`] = t\n for (const tier of META_ADS_ANALYSIS_TIERS) {\n table[`${META_ADS_SCRAPE_NODE_TYPE}:${t}${analysisSuffix(tier)}`] = t * (1 + META_ADS_ANALYSIS_CREDITS_PER_AD[tier])\n }\n }\n return table\n}\n\n/**\n * Credit cost per SKU — mirror of the backend `STATIC_CREDIT_COSTS` rows and\n * migrations 428 / 429, for the frontend badge / estimator. 1 credit per\n * requested ad at every tier, plus the analysis multiples above; the bare\n * identifier is the pre-Zod fallback (mid tier, never the max).\n */\nexport const META_ADS_SCRAPE_CREDIT_COSTS: Record<string, number> = buildMetaAdsCreditCostTable()\n\nexport const META_ADS_SCRAPE_FALLBACK_CREDIT_ID = \"meta-ads-scrape:20\"\n\n/**\n * Page urls are typed one per line in the config panel (a FieldMapping\n * injects the same text); the route wants an array. Tolerates commas and\n * whitespace as separators (a url never contains either) and an array that\n * already went through this once.\n */\nexport function splitMetaAdsPageUrls(value: unknown): string[] {\n if (Array.isArray(value)) {\n return value.filter((v): v is string => typeof v === \"string\").map((v) => v.trim()).filter((v) => v.length > 0)\n }\n if (typeof value !== \"string\") return []\n return value.split(/[\\n,\\s]+/).map((v) => v.trim()).filter((v) => v.length > 0)\n}\n\nexport function isMetaAdsScrapeMode(value: unknown): value is MetaAdsScrapeMode {\n return typeof value === \"string\" && (META_ADS_SCRAPE_MODES as readonly string[]).includes(value)\n}\n\n/**\n * Advertiser NAMES to resolve at run time (advertiser mode driven by the `in`\n * input) — one per line or comma-separated. Unlike page urls, a name contains\n * spaces, so this never splits on whitespace. Trimmed, de-duped, each 2..100\n * chars, capped at `MAX_SOURCES`.\n */\nexport function splitMetaAdsAdvertiserNames(value: unknown): string[] {\n const raw = Array.isArray(value)\n ? value.filter((v): v is string => typeof v === \"string\")\n : typeof value === \"string\"\n ? value.split(/[\\n,]+/)\n : []\n const seen = new Set<string>()\n const out: string[] = []\n for (const item of raw) {\n const name = item.trim()\n if (name.length < 2 || name.length > META_ADS_SCRAPE_MAX_QUERY_LENGTH) continue\n const key = name.toLowerCase()\n if (seen.has(key)) continue\n seen.add(key)\n out.push(name)\n if (out.length >= META_ADS_SCRAPE_MAX_SOURCES) break\n }\n return out\n}\n\n/** The node-data fields that decide what a run scrapes (and therefore what it costs). Index-signature so any node-data bag is accepted as-is. */\nexport interface MetaAdsNodeSourceFields {\n readonly [key: string]: unknown\n readonly mode?: unknown\n readonly query?: unknown\n readonly pageUrls?: unknown\n readonly advertisers?: unknown\n}\n\n/**\n * How many sources a run bills — the number the card badge, the run total,\n * the pre-run estimator and the backend quote must all read, so an advertiser\n * pick can never be quoted as one source while the server reserves five. An\n * empty page list / no picks counts as one (the run then fails validation\n * before anything is reserved).\n */\nexport function metaAdsScrapeSources(data: MetaAdsNodeSourceFields): number {\n switch (metaAdsNodeMode(data.mode)) {\n case \"pages\":\n return Math.max(1, Math.min(splitMetaAdsPageUrls(data.pageUrls).length, META_ADS_SCRAPE_MAX_SOURCES))\n case \"advertiser\":\n return Math.max(1, metaAdsAdvertisersFrom(data.advertisers).length)\n default:\n return 1\n }\n}\n\nexport type MetaAdsWireSources =\n | { readonly mode: \"search\"; readonly query: string | undefined }\n | { readonly mode: \"pages\"; readonly pageUrls: string[]; readonly advertiserNames?: string[] }\n\n/**\n * The wire half of a request from node data — ONE mapping for the editor's\n * executor and the orchestrator's payload builder. The keyword / page list\n * falls back to the upstream text so a Prompt or List node can drive the\n * scrape; advertiser picks are explicit (no upstream fallback) and run as\n * their Page urls, which is why the route never sees \"advertiser\".\n */\nexport function metaAdsScrapeWireSources(data: MetaAdsNodeSourceFields, upstream?: unknown): MetaAdsWireSources {\n const upstreamText = typeof upstream === \"string\" ? upstream : undefined\n switch (metaAdsNodeMode(data.mode)) {\n case \"pages\": {\n const own = splitMetaAdsPageUrls(data.pageUrls)\n return { mode: \"pages\", pageUrls: own.length > 0 ? own : splitMetaAdsPageUrls(upstreamText) }\n }\n case \"advertiser\": {\n // Explicit picks run as their Page urls. With no picks but upstream\n // text, the `in` value is advertiser NAME(s) to resolve at run time\n // (the route looks each up and picks the verified/first Page).\n const picks = metaAdsAdvertisersFrom(data.advertisers)\n if (picks.length > 0) return { mode: \"pages\", pageUrls: picks.map((a) => a.url) }\n const names = splitMetaAdsAdvertiserNames(upstreamText)\n return { mode: \"pages\", pageUrls: [], advertiserNames: names }\n }\n default: {\n const own = typeof data.query === \"string\" ? data.query : \"\"\n return { mode: \"search\", query: own || upstreamText }\n }\n }\n}\n\nexport function isMetaAdsScrapeCount(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 1 && value <= META_ADS_SCRAPE_MAX_COUNT\n}\n\n/** Smallest tier that fits the requested total; clamps to the top tier. */\nexport function metaAdsScrapeTier(requestedTotal: number): MetaAdsScrapeTier {\n for (const tier of META_ADS_SCRAPE_TIERS) {\n if (requestedTotal <= tier) return tier\n }\n return META_ADS_SCRAPE_TIERS[META_ADS_SCRAPE_TIERS.length - 1]\n}\n\nexport interface MetaAdsScrapeCreditInput {\n count: number\n /** Number of input URLs in pages mode; 1 for a keyword search. */\n sources: number\n /** The analysing model's tier when per-ad analysis is on; absent / null = scrape only. */\n analysis?: MetaAdsAnalysisTier | null\n}\n\nexport function buildMetaAdsScrapeCreditId(input: MetaAdsScrapeCreditInput): string {\n const sources = Math.min(Math.max(Math.trunc(input.sources) || 1, 1), META_ADS_SCRAPE_MAX_SOURCES)\n const count = Math.min(Math.max(Math.trunc(input.count) || 1, 1), META_ADS_SCRAPE_MAX_COUNT)\n const base = `${META_ADS_SCRAPE_NODE_TYPE}:${metaAdsScrapeTier(count * sources)}`\n return input.analysis ? `${base}${analysisSuffix(input.analysis)}` : base\n}\n\n/** The analysis tier a request / node asks for, or null when analysis is off. */\nexport function metaAdsAnalysisTierFrom(data: { readonly analyze?: unknown; readonly analysisModel?: unknown }): MetaAdsAnalysisTier | null {\n return data.analyze === true ? metaAdsAnalysisTier(data.analysisModel) : null\n}\n\n/**\n * Resolve the credit identifier from an UNVALIDATED request body (the\n * creditGuard preHandler runs before Zod). It must land on the SAME tier the\n * post-Zod reservation computes, so an OMITTED count is the route's default\n * (Zod fills it in the same way); only a present-but-invalid body reserves\n * the fixed mid tier, and the route then rejects it with a 400 and refunds.\n */\nexport function resolveMetaAdsScrapeCreditId(body: unknown): string {\n const raw = body as { mode?: unknown; count?: unknown; pageUrls?: unknown; advertiserNames?: unknown; analyze?: unknown; analysisModel?: unknown } | null | undefined\n if (!raw || typeof raw !== \"object\") return META_ADS_SCRAPE_FALLBACK_CREDIT_ID\n const count = raw.count === undefined ? META_ADS_SCRAPE_DEFAULT_COUNT : raw.count\n if (!isMetaAdsScrapeCount(count)) return META_ADS_SCRAPE_FALLBACK_CREDIT_ID\n // Pages mode bills per source: the page urls PLUS any advertiser names the\n // route will resolve to page urls at run time. Counting names may over-check\n // when one doesn't resolve — the safe direction (the reservation trues down).\n const sources = raw.mode === \"pages\"\n ? (Array.isArray(raw.pageUrls) ? raw.pageUrls.length : 0) + (Array.isArray(raw.advertiserNames) ? raw.advertiserNames.length : 0)\n : 1\n if (sources < 1 || sources > META_ADS_SCRAPE_MAX_SOURCES) return META_ADS_SCRAPE_FALLBACK_CREDIT_ID\n return buildMetaAdsScrapeCreditId({ count, sources, analysis: metaAdsAnalysisTierFrom(raw) })\n}\n\n/** The node-data fields a quote reads: what a run scrapes, how many, and whether it analyses. */\nexport interface MetaAdsNodeQuoteFields extends MetaAdsNodeSourceFields {\n readonly count?: unknown\n readonly analyze?: unknown\n readonly analysisModel?: unknown\n}\n\n/**\n * The ONE credit identifier for a node's current settings — the card badge,\n * the run total, the pre-run estimator and the backend quote all read this,\n * and it is the same builder the route's guard + reservation use on the wire\n * body, so no surface can quote a different SKU than the one reserved.\n */\nexport function metaAdsScrapeCreditIdFromNode(data: MetaAdsNodeQuoteFields): string {\n const count = typeof data.count === \"number\" ? data.count : META_ADS_SCRAPE_DEFAULT_COUNT\n return buildMetaAdsScrapeCreditId({ count, sources: metaAdsScrapeSources(data), analysis: metaAdsAnalysisTierFrom(data) })\n}\n","/**\n * Instagram scraper node — shared vocabulary + credit identifiers.\n *\n * Pulls PUBLIC Instagram posts (feed images, carousels, reels) by profile, by\n * hashtag or by post link and emits a normalized JSON array. Same shape of contract as the\n * Meta Ads node: everything the backend guard/reservation, the frontend credit\n * badge and the docs formula must agree on lives here.\n *\n * Pricing: 1 credit per REQUESTED post, rounded UP to a fixed tier of\n * `count × sources` (a profile / hashtag / post link is one source, up to 5;\n * a post link is always ONE post — see `instagramRequestedCount`). Optional\n * per-post AI analysis folds into the same identifier, priced by the model's\n * tier — reusing the Meta analysis per-item values so the two nodes stay in\n * lockstep.\n */\nimport {\n META_ADS_ANALYSIS_CREDITS_PER_AD,\n META_ADS_ANALYSIS_TIERS,\n metaAdsAnalysisTier,\n type MetaAdsAnalysisTier,\n} from \"./meta-ads-scrape.js\"\nimport { classifyCreativeFormat, type MetaAdsFormat } from \"./meta-ads-scrape.js\"\n\nexport const INSTAGRAM_SCRAPE_NODE_TYPE = \"instagram-scrape\" as const\n\n/**\n * `profile` = recent posts of an account, `hashtag` = recent posts under a tag,\n * `post` = exactly the posts whose links are given (one post per link — the\n * \"remake this post\" entry point, where a full run must land on THAT post).\n */\nexport const INSTAGRAM_SCRAPE_MODES = [\"profile\", \"hashtag\", \"post\"] as const\nexport type InstagramScrapeMode = (typeof INSTAGRAM_SCRAPE_MODES)[number]\n\nexport function isInstagramScrapeMode(value: unknown): value is InstagramScrapeMode {\n return typeof value === \"string\" && (INSTAGRAM_SCRAPE_MODES as readonly string[]).includes(value)\n}\nexport function instagramScrapeMode(value: unknown): InstagramScrapeMode {\n return isInstagramScrapeMode(value) ? value : \"profile\"\n}\n\n/** Same window vocabulary as Meta Ads; the Instagram actor honours it server-side (`onlyPostsNewerThan`). */\nexport const INSTAGRAM_SCRAPE_PERIODS = [\"24h\", \"7d\", \"30d\", \"all\"] as const\nexport type InstagramScrapePeriod = (typeof INSTAGRAM_SCRAPE_PERIODS)[number]\n\nexport const INSTAGRAM_SCRAPE_DEFAULT_COUNT = 20\nexport const INSTAGRAM_SCRAPE_MAX_COUNT = 100\nexport const INSTAGRAM_SCRAPE_MAX_SOURCES = 5\n/** Instagram usernames / hashtags are short; cap a single target well under a URL. */\nexport const INSTAGRAM_SCRAPE_MAX_TARGET_LENGTH = 200\n\n/** Requested-total buckets — identical shape to Meta (the pricing model is the same). */\nexport const INSTAGRAM_SCRAPE_TIERS = [10, 20, 50, 100, 200, 500] as const\nexport type InstagramScrapeTier = (typeof INSTAGRAM_SCRAPE_TIERS)[number]\n\nexport function instagramScrapeTier(requestedTotal: number): InstagramScrapeTier {\n for (const tier of INSTAGRAM_SCRAPE_TIERS) if (requestedTotal <= tier) return tier\n return INSTAGRAM_SCRAPE_TIERS[INSTAGRAM_SCRAPE_TIERS.length - 1]\n}\n\n/** The analysis tier a request / node asks for, or null when analysis is off. */\nexport function instagramAnalysisTierFrom(data: { readonly analyze?: unknown; readonly analysisModel?: unknown }): MetaAdsAnalysisTier | null {\n return data.analyze === true ? metaAdsAnalysisTier(data.analysisModel) : null\n}\n\nfunction analysisSuffix(tier: MetaAdsAnalysisTier): string {\n return tier === \"standard\" ? \":analysis\" : `:analysis:${tier}`\n}\n\n/** Per-post settlement SKU for a tier (the bare id is the standard tier). */\nexport const INSTAGRAM_ANALYSIS_CREDIT_ID = \"instagram-analysis\" as const\nexport function instagramAnalysisCreditId(tier: MetaAdsAnalysisTier): string {\n return tier === \"standard\" ? INSTAGRAM_ANALYSIS_CREDIT_ID : `${INSTAGRAM_ANALYSIS_CREDIT_ID}:${tier}`\n}\n\nexport interface InstagramScrapeCreditInput {\n count: number\n sources: number\n analysis?: MetaAdsAnalysisTier | null\n}\n\nexport function buildInstagramScrapeCreditId(input: InstagramScrapeCreditInput): string {\n const sources = Math.min(Math.max(Math.trunc(input.sources) || 1, 1), INSTAGRAM_SCRAPE_MAX_SOURCES)\n const count = Math.min(Math.max(Math.trunc(input.count) || 1, 1), INSTAGRAM_SCRAPE_MAX_COUNT)\n const base = `${INSTAGRAM_SCRAPE_NODE_TYPE}:${instagramScrapeTier(count * sources)}`\n return input.analysis ? `${base}${analysisSuffix(input.analysis)}` : base\n}\n\n/**\n * Cost per SKU — mirror of the backend `STATIC_CREDIT_COSTS` rows / migration,\n * for the frontend badge / estimator. 1 credit per requested post at every\n * tier, plus the analysis multiples.\n */\nexport const INSTAGRAM_SCRAPE_CREDIT_COSTS: Record<string, number> = (() => {\n const table: Record<string, number> = { [INSTAGRAM_SCRAPE_NODE_TYPE]: 20 }\n for (const tier of META_ADS_ANALYSIS_TIERS) table[instagramAnalysisCreditId(tier)] = META_ADS_ANALYSIS_CREDITS_PER_AD[tier]\n for (const t of INSTAGRAM_SCRAPE_TIERS) {\n table[`${INSTAGRAM_SCRAPE_NODE_TYPE}:${t}`] = t\n for (const tier of META_ADS_ANALYSIS_TIERS) {\n table[`${INSTAGRAM_SCRAPE_NODE_TYPE}:${t}${analysisSuffix(tier)}`] = t * (1 + META_ADS_ANALYSIS_CREDITS_PER_AD[tier])\n }\n }\n return table\n})()\n\nexport const INSTAGRAM_SCRAPE_FALLBACK_CREDIT_ID = \"instagram-scrape:20\"\n\nexport function isInstagramScrapeCount(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 1 && value <= INSTAGRAM_SCRAPE_MAX_COUNT\n}\n\n/**\n * A post link: instagram.com (any subdomain, an optional username segment\n * before the kind) or instagr.am, `/p/`, `/reel/`, `/reels/` or `/tv/`, with or\n * without scheme, query string or trailing slash. Group 1 = the kind, group 2 =\n * the shortcode. The shortcode is CASE-SENSITIVE — two codes that differ only\n * in case are two different posts — so the `i` flag only relaxes the host and\n * the kind; the captured code keeps its case.\n *\n * Instagram's own path words are never a username: `/share/p/<token>/` (the\n * token of a share redirect, not a shortcode), `/stories/…`, `/explore/…` and\n * the kinds themselves would otherwise turn into a wrong post that still bills.\n * `/reels/audio/<id>/` is an audio page, not a reel.\n */\nconst INSTAGRAM_POST_LINK_RE =\n /^(?:https?:\\/\\/)?(?:[a-z0-9-]+\\.)*(?:instagram\\.com|instagr\\.am)\\/(?:(?!(?:share|stories|explore|accounts|direct|p|reels?|tv)\\/)[A-Za-z0-9._]+\\/)?(p|reels?|tv)\\/(?!audio(?:[/?#]|$))([A-Za-z0-9_-]+)/i\n\nfunction parseInstagramPostLink(value: string): { readonly link: string; readonly shortcode: string } | null {\n const match = INSTAGRAM_POST_LINK_RE.exec(value.trim())\n if (!match) return null\n const kind = match[1].toLowerCase()\n const segment = kind === \"p\" ? \"p\" : kind === \"tv\" ? \"tv\" : \"reel\"\n return { link: `https://www.instagram.com/${segment}/${match[2]}/`, shortcode: match[2] }\n}\n\n/** The canonical link of the post a value points at, or null when it is not an Instagram post link. */\nexport function instagramPostLink(value: string): string | null {\n return parseInstagramPostLink(value)?.link ?? null\n}\n\n/**\n * Post links, canonicalised, deduped by shortcode (`/p/X` and `/reel/X` are\n * one post), capped at MAX_SOURCES. An item holding several links (an API\n * caller's array entry) is split like typed text.\n */\nfunction splitInstagramPostLinks(raw: readonly string[]): string[] {\n const seen = new Set<string>()\n const out: string[] = []\n for (const item of raw.flatMap((entry) => entry.split(/[\\s,]+/))) {\n const parsed = parseInstagramPostLink(item)\n if (!parsed || seen.has(parsed.shortcode)) continue\n seen.add(parsed.shortcode)\n out.push(parsed.link)\n if (out.length >= INSTAGRAM_SCRAPE_MAX_SOURCES) break\n }\n return out\n}\n\n/**\n * Targets are typed one per line; the route wants an array.\n *\n * - `profile` / `hashtag` (the default — the signature predates post mode):\n * a target can be a bare username / `#tag`, so split on lines / commas only\n * (never whitespace), strip a leading `@` or `#`, dedupe, cap at MAX_SOURCES.\n * - `post`: only Instagram post links count; each is canonicalised (see\n * `instagramPostLink`) and anything else is dropped, so the guard, the\n * reservation and the scrape all see the same set of posts.\n */\nexport function splitInstagramTargets(value: unknown, mode: InstagramScrapeMode = \"profile\"): string[] {\n const separator = mode === \"post\" ? /[\\s,]+/ : /[\\n,]+/\n const raw = Array.isArray(value)\n ? value.filter((v): v is string => typeof v === \"string\")\n : typeof value === \"string\"\n ? value.split(separator)\n : []\n if (mode === \"post\") return splitInstagramPostLinks(raw)\n const seen = new Set<string>()\n const out: string[] = []\n for (const item of raw) {\n const t = item.trim().replace(/^[@#]+/, \"\").trim()\n if (t.length < 1 || t.length > INSTAGRAM_SCRAPE_MAX_TARGET_LENGTH) continue\n const key = t.toLowerCase()\n if (seen.has(key)) continue\n seen.add(key)\n out.push(t)\n if (out.length >= INSTAGRAM_SCRAPE_MAX_SOURCES) break\n }\n return out\n}\n\n/** The featured post index, clamped. */\nexport function clampInstagramFeaturedIndex(stored: unknown, count: number): number {\n if (count <= 0) return 0\n const n = typeof stored === \"number\" && Number.isFinite(stored) ? Math.trunc(stored) : 0\n return Math.min(Math.max(n, 0), count - 1)\n}\n\nexport interface FeaturedInstagramOutputs {\n readonly text?: string\n readonly imageUrl?: string\n readonly videoUrl?: string\n}\n\nfunction urlStrings(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((v): v is string => typeof v === \"string\" && v.trim().length > 0) : []\n}\n\n/** The featured post's caption (`text`), first image / cover (`image`), and first video (`video`). */\nexport function featuredInstagramOutputs(json: unknown, featuredIndex: unknown): FeaturedInstagramOutputs {\n if (!Array.isArray(json) || json.length === 0) return {}\n const post = json[clampInstagramFeaturedIndex(featuredIndex, json.length)]\n if (!post || typeof post !== \"object\") return {}\n const p = post as Record<string, unknown>\n const text = typeof p.caption === \"string\" ? p.caption.trim() : \"\"\n const imageUrl = urlStrings(p.images)[0] ?? urlStrings(p.videoPreviews)[0]\n const videoUrl = urlStrings(p.videos)[0]\n return {\n ...(text ? { text } : {}),\n ...(imageUrl ? { imageUrl } : {}),\n ...(videoUrl ? { videoUrl } : {}),\n }\n}\n\n/** The node-data fields a quote reads. */\nexport interface InstagramNodeQuoteFields {\n readonly [key: string]: unknown\n readonly mode?: unknown\n readonly targets?: unknown\n readonly count?: unknown\n readonly analyze?: unknown\n readonly analysisModel?: unknown\n}\n\n/**\n * Posts requested PER SOURCE: the `count` setting, except in post mode, where\n * every source is one link and so one post (the count setting does not apply).\n * Every price computation goes through this, so the guard, the reservation,\n * the settlement and the node's badge cannot disagree on a post-mode run.\n */\nexport function instagramRequestedCount(mode: InstagramScrapeMode, count: number): number {\n return mode === \"post\" ? 1 : count\n}\n\n/** Billable source count: number of targets (min 1). */\nexport function instagramScrapeSources(data: InstagramNodeQuoteFields): number {\n return Math.max(1, Math.min(splitInstagramTargets(data.targets, instagramScrapeMode(data.mode)).length, INSTAGRAM_SCRAPE_MAX_SOURCES))\n}\n\n/** The ONE credit identifier for a node's current settings. */\nexport function instagramScrapeCreditIdFromNode(data: InstagramNodeQuoteFields): string {\n const count = typeof data.count === \"number\" ? data.count : INSTAGRAM_SCRAPE_DEFAULT_COUNT\n return buildInstagramScrapeCreditId({\n count: instagramRequestedCount(instagramScrapeMode(data.mode), count),\n sources: instagramScrapeSources(data),\n analysis: instagramAnalysisTierFrom(data),\n })\n}\n\n/**\n * Resolve the credit identifier from an UNVALIDATED request body (the guard\n * runs before Zod). Lands on the SAME tier the reservation computes.\n */\nexport function resolveInstagramScrapeCreditId(body: unknown): string {\n const raw = body as { mode?: unknown; count?: unknown; targets?: unknown; analyze?: unknown; analysisModel?: unknown } | null | undefined\n if (!raw || typeof raw !== \"object\") return INSTAGRAM_SCRAPE_FALLBACK_CREDIT_ID\n const count = raw.count === undefined ? INSTAGRAM_SCRAPE_DEFAULT_COUNT : raw.count\n if (!isInstagramScrapeCount(count)) return INSTAGRAM_SCRAPE_FALLBACK_CREDIT_ID\n // Same mode resolution as the route's Zod default (absent → profile) and the\n // same splitter the handler uses for `sources` (dedupes, caps at MAX), so the\n // pre-Zod guard and the post-Zod reservation always land on the same tier —\n // a duplicate target bills once, not per copy.\n const mode = instagramScrapeMode(raw.mode)\n const sources = splitInstagramTargets(raw.targets, mode).length\n if (sources < 1) return INSTAGRAM_SCRAPE_FALLBACK_CREDIT_ID\n return buildInstagramScrapeCreditId({ count: instagramRequestedCount(mode, count), sources, analysis: instagramAnalysisTierFrom(raw) })\n}\n\n// Re-export the shared creative-format vocabulary so the node imports one place.\nexport { classifyCreativeFormat }\nexport type InstagramFormat = MetaAdsFormat\n","/**\n * Social Search node — shared vocabulary, the post shape, credit identifiers,\n * and the rule for which posts a run passes on.\n *\n * One node searches one platform (TikTok, Instagram, YouTube, X, Reddit,\n * LinkedIn, Meta's Ad Library) by keyword or by account and returns up to 60\n * posts in one shape. In the editor a person picks the posts to keep; a\n * workflow run without picks passes on the first few. Everything the route\n * reservation, the orchestrator, the editor, the SDK and the docs must agree\n * on lives here.\n *\n * Why public: `SocialPost` is the node's output and the SDK's return type,\n * and `SocialSearchParams` is the `/v1/social-search` request body. The search\n * itself runs in a private plugin (Cloud only).\n */\n\nexport const SOCIAL_SEARCH_NODE_TYPE = \"social-search\" as const\n\nexport const SOCIAL_PLATFORMS = [\"tiktok\", \"instagram\", \"youtube\", \"x\", \"reddit\", \"linkedin\", \"meta_ads\"] as const\nexport type SocialPlatform = (typeof SOCIAL_PLATFORMS)[number]\n\n/** `account` is a creator, a LinkedIn company page or person's profile, or\n * a Meta advertiser; `community` is a subreddit. */\nexport const SOCIAL_SEARCH_MODES = [\"keyword\", \"account\", \"community\"] as const\nexport type SocialSearchMode = (typeof SOCIAL_SEARCH_MODES)[number]\n\nexport const SOCIAL_SEARCH_PLATFORM_MODES: Readonly<Record<SocialPlatform, readonly SocialSearchMode[]>> = {\n tiktok: [\"keyword\", \"account\"],\n instagram: [\"keyword\", \"account\"],\n youtube: [\"keyword\", \"account\"],\n x: [\"keyword\", \"account\"],\n reddit: [\"keyword\", \"community\"],\n linkedin: [\"keyword\", \"account\"],\n meta_ads: [\"keyword\", \"account\"],\n}\n\nexport const SOCIAL_SEARCH_PERIODS = [\"day\", \"week\", \"month\", \"year\", \"all\"] as const\nexport type SocialSearchPeriod = (typeof SOCIAL_SEARCH_PERIODS)[number]\n\nexport const SOCIAL_SEARCH_SORTS = [\"relevance\", \"popular\", \"newest\"] as const\nexport type SocialSearchSort = (typeof SOCIAL_SEARCH_SORTS)[number]\n\n/** Results per search: one page of the platform per 20 posts. */\nexport const SOCIAL_SEARCH_COUNTS = [20, 40, 60] as const\nexport type SocialSearchCount = (typeof SOCIAL_SEARCH_COUNTS)[number]\n\n/**\n * The searches that can fetch more than one page. Every other one (an\n * account's latest posts on TikTok, Instagram, YouTube or LinkedIn, a YouTube\n * keyword search, a Reddit keyword search) returns one page however many\n * results are asked for, so it is capped at 20 — and billed for one page. The\n * plugin applies the same table to what it fetches and reserves.\n */\nexport const SOCIAL_SEARCH_PAGED_MODES: Readonly<Record<SocialPlatform, readonly SocialSearchMode[]>> = {\n tiktok: [\"keyword\"],\n instagram: [\"keyword\"],\n youtube: [],\n x: [\"keyword\", \"account\"],\n reddit: [\"community\"],\n linkedin: [\"keyword\"],\n meta_ads: [\"keyword\", \"account\"],\n}\n\n/** The most results this platform and mode can return in one search. */\nexport function socialSearchMaxCount(platform: SocialPlatform, mode: SocialSearchMode): SocialSearchCount {\n return SOCIAL_SEARCH_PAGED_MODES[platform].includes(mode) ? 60 : 20\n}\n\nexport const SOCIAL_SEARCH_VIDEO_KINDS = [\"all\", \"videos\", \"shorts\"] as const\nexport type SocialSearchVideoKind = (typeof SOCIAL_SEARCH_VIDEO_KINDS)[number]\n\n/** How many posts a run passes on when nobody picked: the first five. */\nexport const SOCIAL_SEARCH_DEFAULT_PICK_TOP = 5\nexport const SOCIAL_SEARCH_MAX_QUERY_LENGTH = 300\n\n// ── The post ───────────────────────────────────────────────────────────────\n\nexport interface SocialPostAuthor {\n readonly handle: string\n readonly name: string\n readonly avatarUrl?: string\n readonly followers?: number\n readonly verified?: boolean\n readonly url?: string\n}\n\n/** Absent means the platform did not report it, never zero. */\nexport interface SocialPostMetrics {\n readonly views?: number\n readonly likes?: number\n readonly comments?: number\n readonly shares?: number\n readonly saves?: number\n /** Reddit's vote score. */\n readonly score?: number\n}\n\nexport interface SocialPostMedia {\n readonly kind: \"video\" | \"image\" | \"text\"\n /** The platform's own still. Signed links expire within days. */\n readonly thumbnailUrl?: string\n /** A direct video file when the platform hands one out. Also short-lived. */\n readonly videoUrl?: string\n readonly durationSec?: number\n readonly aspect?: \"9:16\" | \"16:9\" | \"1:1\"\n}\n\nexport interface SocialPost {\n /** `<platform>:<the platform's own id>`, stable across searches. */\n readonly id: string\n readonly platform: SocialPlatform\n /** The post's page. */\n readonly url: string\n readonly title?: string\n readonly text: string\n readonly author: SocialPostAuthor\n /** Where it was posted: `r/<subreddit>`, a channel, a company page, an advertiser. */\n readonly container?: string\n /** ISO 8601, UTC. */\n readonly publishedAt?: string\n readonly metrics: SocialPostMetrics\n readonly media: SocialPostMedia\n readonly hashtags: readonly string[]\n /** Platform-specific facts: a TikTok `sound`, an ad's `active` / `endedAt` /\n * `variants` / `cta`, a Reddit `subreddit`, an X `reply` flag. */\n readonly extra: Readonly<Record<string, unknown>>\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\n/** Every field the card, the digest and the picker read, with its type. A\n * saved post that fails this is skipped, never rendered half-broken. */\nexport function isSocialPost(value: unknown): value is SocialPost {\n if (!isRecord(value)) return false\n return (\n typeof value.id === \"string\" &&\n typeof value.url === \"string\" &&\n typeof value.text === \"string\" &&\n typeof value.platform === \"string\" &&\n (SOCIAL_PLATFORMS as readonly string[]).includes(value.platform) &&\n isRecord(value.author) &&\n typeof value.author.handle === \"string\" &&\n typeof value.author.name === \"string\" &&\n isRecord(value.metrics) &&\n isRecord(value.media) &&\n Array.isArray(value.hashtags) &&\n isRecord(value.extra)\n )\n}\n\n/** The posts in an unknown value (a job's output, a node's saved data). */\nexport function socialPostsFrom(value: unknown): SocialPost[] {\n return Array.isArray(value) ? value.filter(isSocialPost) : []\n}\n\n// ── The request ────────────────────────────────────────────────────────────\n\n/** The body of `POST /v1/social-search` (and `nodes.run(\"social-search\", …)`).\n * A type alias, not an interface, so it is assignable to a plain record (the\n * SDK's generic `run` body). */\nexport type SocialSearchParams = {\n readonly platform: SocialPlatform\n /** Default `keyword`. */\n readonly mode?: SocialSearchMode\n /** A keyword, or an account: a handle, a profile link, a subreddit, a\n * LinkedIn company page or profile, a Meta advertiser's name or page id. */\n readonly query: string\n /** 20, 40 or 60 results. Default 20. */\n readonly count?: SocialSearchCount\n /** Default `month`. */\n readonly period?: SocialSearchPeriod\n /** Default `relevance` (the platform's own order). */\n readonly sort?: SocialSearchSort\n /** TikTok keyword search: a two-letter region. */\n readonly region?: string\n /** Meta ads: a two-letter country, or `ALL`. */\n readonly country?: string\n /** Meta ads: only ads that are running now. Default true. */\n readonly activeOnly?: boolean\n /** Reddit keyword search inside one subreddit. */\n readonly subreddit?: string\n /** YouTube: long videos, Shorts, or both. Default `all`. */\n readonly videoKind?: SocialSearchVideoKind\n}\n\nfunction oneOf<T extends string>(list: readonly T[], value: unknown, fallback: T): T {\n return typeof value === \"string\" && (list as readonly string[]).includes(value) ? (value as T) : fallback\n}\n\nexport function socialSearchPlatform(value: unknown): SocialPlatform {\n return oneOf(SOCIAL_PLATFORMS, value, \"tiktok\")\n}\n\n/** The mode, or the platform's first one when the stored mode does not apply\n * (a node switched from Reddit \"community\" to TikTok). */\nexport function socialSearchMode(platform: SocialPlatform, value: unknown): SocialSearchMode {\n const allowed = SOCIAL_SEARCH_PLATFORM_MODES[platform]\n return oneOf(allowed, value, allowed[0]!)\n}\n\nexport function socialSearchCount(value: unknown): SocialSearchCount {\n return value === 60 ? 60 : value === 40 ? 40 : 20\n}\n\nexport function socialSearchPages(count: SocialSearchCount): 1 | 2 | 3 {\n return count === 60 ? 3 : count === 40 ? 2 : 1\n}\n\nfunction cleanText(value: unknown, max: number): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim().slice(0, max) : undefined\n}\n\n/** The count a search really runs at: the asked count, capped for a search\n * that returns one page (`socialSearchMaxCount`). */\nexport function socialSearchEffectiveCount(platform: SocialPlatform, mode: SocialSearchMode, value: unknown): SocialSearchCount {\n const asked = socialSearchCount(value)\n const max = socialSearchMaxCount(platform, mode)\n return asked > max ? max : asked\n}\n\n/** A two-letter region (TikTok), upper-cased, or undefined. */\nexport function socialSearchRegion(value: unknown): string | undefined {\n const text = typeof value === \"string\" ? value.trim().toUpperCase() : \"\"\n return /^[A-Z]{2}$/.test(text) ? text : undefined\n}\n\n/** A two-letter country or ALL (Meta ads), upper-cased; anything else is ALL. */\nexport function socialSearchCountry(value: unknown): string {\n const text = typeof value === \"string\" ? value.trim().toUpperCase() : \"\"\n return /^([A-Z]{2}|ALL)$/.test(text) ? text : \"ALL\"\n}\n\n/**\n * The request a Social Search node sends — the ONE builder the editor's run\n * and the workflow orchestrator share. `query` is the wired text when there is\n * one (a Text node, a List item), else the node's own field.\n */\nexport function socialSearchRequestFromNode(\n data: Readonly<Record<string, unknown>>,\n wiredQuery?: string,\n): SocialSearchParams {\n const platform = socialSearchPlatform(data.platform)\n const mode = socialSearchMode(platform, data.mode)\n const query = cleanText(wiredQuery, SOCIAL_SEARCH_MAX_QUERY_LENGTH) ?? cleanText(data.query, SOCIAL_SEARCH_MAX_QUERY_LENGTH) ?? \"\"\n const region = socialSearchRegion(data.region)\n const country = socialSearchCountry(data.country)\n const subreddit = cleanText(data.subreddit, 100)\n return {\n platform,\n mode,\n query,\n count: socialSearchEffectiveCount(platform, mode, data.count),\n period: oneOf(SOCIAL_SEARCH_PERIODS, data.period, \"month\"),\n sort: oneOf(SOCIAL_SEARCH_SORTS, data.sort, \"relevance\"),\n ...(platform === \"tiktok\" && mode === \"keyword\" && region ? { region } : {}),\n ...(platform === \"meta_ads\" ? { country, activeOnly: data.activeOnly !== false } : {}),\n ...(platform === \"reddit\" && mode === \"keyword\" && subreddit ? { subreddit } : {}),\n ...(platform === \"youtube\" ? { videoKind: oneOf(SOCIAL_SEARCH_VIDEO_KINDS, data.videoKind, \"all\") } : {}),\n }\n}\n\n/**\n * The page link of a Social Search post, read from the node's `json` output\n * as a wire hands it on: one post (a wire in Each mode) or the list of posts\n * (any other wire: the first). Undefined when the output holds no post with\n * an http(s) link.\n */\nexport function socialSearchPostLink(output: string): string | undefined {\n let parsed: unknown\n try {\n parsed = JSON.parse(output)\n } catch {\n return undefined\n }\n const post = Array.isArray(parsed) ? parsed[0] : parsed\n const url = typeof post === \"object\" && post !== null ? (post as { url?: unknown }).url : undefined\n return httpLink(url)\n}\n\nfunction httpLink(value: unknown): string | undefined {\n const link = typeof value === \"string\" ? value.trim() : \"\"\n return /^https?:\\/\\/\\S+$/i.test(link) ? link : undefined\n}\n\n// ── A post's video, for Video Analysis ─────────────────────────────────────\n\n/**\n * A signed link counts as expired this long before its stated end, so it\n * still answers when the run reads it: the length check, then the download.\n */\nexport const SOCIAL_POST_VIDEO_LINK_MARGIN_MS = 60 * 60 * 1000\n\n/**\n * When a platform's signed media link stops working, in epoch milliseconds,\n * if the link says: `oe` (hex seconds: Instagram, Facebook and ad videos),\n * `x-expires` (TikTok), `Expires` (S3, CloudFront), `e` (LinkedIn). Undefined\n * for a link that names no end (an X video's link does not expire).\n */\nexport function signedLinkExpiresAt(link: string): number | undefined {\n let url: URL\n try {\n url = new URL(link)\n } catch {\n return undefined\n }\n const params = url.searchParams\n const oe = params.get(\"oe\")\n if (oe !== null && /^[0-9a-f]{6,10}$/i.test(oe)) return parseInt(oe, 16) * 1000\n const linkedin = /(^|\\.)licdn\\.com$/i.test(url.hostname)\n const seconds = params.get(\"x-expires\") ?? params.get(\"Expires\") ?? params.get(\"expires\") ?? (linkedin ? params.get(\"e\") : null)\n return seconds !== null && /^\\d{9,11}$/.test(seconds) ? Number(seconds) * 1000 : undefined\n}\n\n/**\n * A post's video link when it is a FILE the analysis can download whole; a\n * streaming playlist (an HLS `.m3u8`, which some LinkedIn videos are) is not\n * one, so the post is read by its page instead.\n */\nfunction videoFileLink(value: unknown): string | undefined {\n const link = httpLink(value)\n if (!link) return undefined\n try {\n return /\\.m3u8$/i.test(new URL(link).pathname) ? undefined : link\n } catch {\n return undefined\n }\n}\n\n/** What a Social Search post hands Video Analysis. */\nexport type SocialSearchPostVideo =\n /** The post's own video file, while the platform's signed link is valid. */\n | { readonly kind: \"file\"; readonly url: string }\n /** No file came with the post (TikTok, YouTube): its page, which the analysis fetches. */\n | { readonly kind: \"page\"; readonly url: string }\n /** The file's signed link has expired: the search has to run again. */\n | { readonly kind: \"expired\" }\n /** The post is an image or a text post: there is no video to analyze. */\n | { readonly kind: \"none\" }\n\n/**\n * The video Video Analysis reads from a Social Search node's `json` output,\n * as a wire hands it on: one post (a wire in Each mode) or the list (any\n * other wire: the first post). A post that came with its own video file is\n * analyzed from that file, so the platform's page is never read: Instagram's\n * page does not say how long the video is, and a video without a length\n * cannot be priced. A file whose signed link has expired is reported as such\n * rather than swapped for the page. Undefined when the output holds no post.\n * Both engines read it (input-resolver / node-input-resolver).\n */\nexport function socialSearchPostVideo(output: string, now: number = Date.now()): SocialSearchPostVideo | undefined {\n let parsed: unknown\n try {\n parsed = JSON.parse(output)\n } catch {\n return undefined\n }\n const post = Array.isArray(parsed) ? socialPostsFrom(parsed)[0] : isSocialPost(parsed) ? parsed : undefined\n if (!post) return undefined\n if (post.media.kind !== \"video\") return { kind: \"none\" }\n const file = videoFileLink(post.media.videoUrl)\n if (file) {\n const end = signedLinkExpiresAt(file)\n return end !== undefined && end - SOCIAL_POST_VIDEO_LINK_MARGIN_MS <= now ? { kind: \"expired\" } : { kind: \"file\", url: file }\n }\n const page = httpLink(post.url)\n return page ? { kind: \"page\", url: page } : undefined\n}\n\n/**\n * The longest video among the posts, in seconds: what Video Analysis quotes\n * for each post a Social Search wire hands it (each post is charged by its\n * own length when it runs, so the quote is never lower than the charge).\n * Posts without a video are left out: Video Analysis refuses them without a\n * charge. Undefined when no post has a video, or one of them does not say\n * how long it is (the ceiling quotes it).\n */\nexport function socialPostsLongestVideoSec(posts: readonly SocialPost[]): number | undefined {\n const lengths = posts.filter((p) => p.media.kind === \"video\").map((p) => p.media.durationSec)\n if (lengths.length === 0) return undefined\n return lengths.every((d): d is number => typeof d === \"number\" && Number.isFinite(d) && d > 0)\n ? Math.max(...lengths)\n : undefined\n}\n\n// ── Pricing ────────────────────────────────────────────────────────────────\n\n/**\n * Credits for one page of results (up to 20 posts), set by the owner: 20 /\n * 40 / 60 results cost 20 / 40 / 60 credits on every platform. The\n * `model_pricing` rows seed the same values. A run is charged by the results\n * it asks for (pages), never by the platform.\n */\nexport const SOCIAL_SEARCH_CREDITS_PER_PAGE = 20\n\nexport function socialSearchCreditId(count: SocialSearchCount): string {\n return `${SOCIAL_SEARCH_NODE_TYPE}:${socialSearchPages(count)}`\n}\n\nexport function socialSearchCreditIdFromNode(data: Readonly<Record<string, unknown>>): string {\n const platform = socialSearchPlatform(data.platform)\n return socialSearchCreditId(socialSearchEffectiveCount(platform, socialSearchMode(platform, data.mode), data.count))\n}\n\n/** Every id a search can reserve, plus the bare id (the node's headline price). */\nexport const SOCIAL_SEARCH_CREDIT_COSTS: Readonly<Record<string, number>> = Object.fromEntries([\n [SOCIAL_SEARCH_NODE_TYPE, SOCIAL_SEARCH_CREDITS_PER_PAGE],\n ...SOCIAL_SEARCH_COUNTS.map((count) => [socialSearchCreditId(count), SOCIAL_SEARCH_CREDITS_PER_PAGE * socialSearchPages(count)] as const),\n])\n\n// ── Which posts a run passes on ────────────────────────────────────────────\n\nexport function socialSearchPickTop(value: unknown): number {\n const n = typeof value === \"number\" && Number.isFinite(value) ? Math.round(value) : SOCIAL_SEARCH_DEFAULT_PICK_TOP\n return Math.min(60, Math.max(1, n))\n}\n\n/**\n * The posts passed on: the ones a person picked, in the order they picked\n * them, when any of them is among the results; otherwise the first `pickTop`.\n * Picks belong to the search a person picked from: a NEW search (the editor's\n * run, a workflow run) starts with none, so it passes on the first `pickTop`\n * — the same in both engines. Keeping picks means not searching again\n * (`isSocialSearchPickFrozen`).\n */\nexport function pickSocialPosts(\n results: readonly SocialPost[],\n pickedIds: readonly string[] | undefined,\n pickTop: unknown,\n): SocialPost[] {\n const byId = new Map(results.map((p) => [p.id, p]))\n const picked = (pickedIds ?? []).map((id) => byId.get(id)).filter((p): p is SocialPost => p !== undefined)\n return picked.length > 0 ? picked : results.slice(0, socialSearchPickTop(pickTop))\n}\n\n/**\n * \"Keep my picks\": a node whose author picked posts and chose to keep them\n * does not search again on a workflow run — it passes its picks on, like a\n * frozen (skipped) node. Both engines treat it as skipped.\n */\nexport function isSocialSearchPickFrozen(type: string | undefined, data: Readonly<Record<string, unknown>>): boolean {\n return type === SOCIAL_SEARCH_NODE_TYPE && data.keepPicks === true && socialPostsFrom(data.generatedJson).length > 0\n}\n\nfunction metricLine(post: SocialPost): string {\n const m = post.metrics\n if (m.views !== undefined) return `${m.views} views`\n if (m.score !== undefined) return `${m.score} points`\n if (m.likes !== undefined) return `${m.likes} likes`\n return \"\"\n}\n\n/** One post as a few plain lines: who, when, reach; the words; the link. */\nexport function socialPostDigestLine(post: SocialPost, index: number): string {\n const who = post.author.handle ? `@${post.author.handle.replace(/^@/, \"\")}` : post.author.name || post.container || \"\"\n const when = post.publishedAt ? post.publishedAt.slice(0, 10) : \"\"\n const words = (post.title || post.text).replace(/\\s+/g, \" \").trim()\n const snippet = words.length > 160 ? `${words.slice(0, 159)}…` : words\n const head = `${index + 1}. ${[who, when, metricLine(post)].filter(Boolean).join(\" · \")}`\n return [head, snippet, post.url].filter(Boolean).join(\"\\n \")\n}\n\n/** The posts as text, for nodes that read text (a prompt, a writer). */\nexport function socialPostsDigest(posts: readonly SocialPost[]): string {\n return posts.map(socialPostDigestLine).join(\"\\n\\n\")\n}\n","/**\n * Saved posts — the inspiration wall's wire contract.\n *\n * A person saves a post they found (a Social Search result) with a note and\n * tags, to come back to it or feed it into a workflow. The row keeps a\n * snapshot of the post, because platform links and numbers change, and the\n * post's still is copied into the person's storage so the wall outlives the\n * platform's signed image links.\n *\n * Why public: `SavedPost` is what `GET /v1/saved-posts` returns and the SDK's\n * `savedPosts` resource types.\n */\nimport type { SocialPlatform, SocialPost } from \"./social-search.js\"\n\n/** Where a save came from. */\nexport const SAVED_POST_SOURCES = [\"picker\", \"competitors\", \"manual\", \"api\"] as const\nexport type SavedPostSource = (typeof SAVED_POST_SOURCES)[number]\n\nexport const SAVED_POST_NOTE_MAX = 2000\nexport const SAVED_POST_MAX_TAGS = 10\nexport const SAVED_POST_TAG_MAX = 40\nexport const SAVED_POSTS_PAGE_MAX = 100\n/** How many post ids one lookup may ask about. */\nexport const SAVED_POSTS_LOOKUP_MAX = 200\n\nexport interface SavedPost {\n readonly id: string\n /** The post's own id (`SocialPost.id`); one save per post per person. */\n readonly postId: string\n readonly platform: SocialPlatform\n readonly url: string\n /** The post as it was when saved. */\n readonly post: SocialPost\n /** The still, copied into the person's storage; null when the copy failed\n * (the post's own `media.thumbnailUrl` is then the only, expiring, link). */\n readonly thumbnailUrl: string | null\n readonly note: string\n readonly tags: readonly string[]\n readonly source: SavedPostSource\n readonly createdAt: string\n readonly updatedAt: string\n}\n\n/** The body of `POST /v1/saved-posts`. Saving a post already saved updates\n * its note and tags (when given) and returns the existing save. */\nexport type SavePostInput = {\n readonly post: SocialPost\n readonly note?: string\n readonly tags?: readonly string[]\n readonly source?: SavedPostSource\n}\n\n/** The body of `PATCH /v1/saved-posts/:id`. */\nexport type UpdateSavedPostInput = {\n readonly note?: string\n readonly tags?: readonly string[]\n}\n\n/** Query of `GET /v1/saved-posts`. */\nexport type ListSavedPostsParams = {\n readonly platform?: SocialPlatform\n /** Only saves carrying this tag. */\n readonly tag?: string\n /** Words to find in the note or the post's text. */\n readonly q?: string\n /** The `nextCursor` of the previous page. */\n readonly cursor?: string\n /** 1–100, default 40. */\n readonly limit?: number\n}\n\nexport interface ListSavedPostsResult {\n readonly data: readonly SavedPost[]\n readonly nextCursor: string | null\n}\n\n/** The answer of `POST /v1/saved-posts/lookup`: which of the asked posts are saved. */\nexport interface SavedPostsLookupResult {\n readonly saved: ReadonlyArray<{ readonly postId: string; readonly id: string }>\n}\n\n/**\n * Tags as stored: split on commas (`,` `,` `、`, so \"hooks, openers\" is two\n * tags in any script), trimmed, inner whitespace collapsed, lower-cased, a\n * leading `#` dropped, braces, quotes and backslashes removed (they would\n * change a tag filter's meaning), each at most 40 characters, no repeats, at\n * most 10.\n */\nexport function normalizeSavedPostTags(tags: unknown): string[] {\n if (!Array.isArray(tags)) return []\n const clean = tags\n .filter((t): t is string => typeof t === \"string\")\n .flatMap((t) => t.split(/[,,、]/))\n .map((t) =>\n t\n .replace(/[{}\"\\\\]/g, \"\")\n .trim()\n .replace(/^#+/, \"\")\n .replace(/\\s+/g, \" \")\n .toLowerCase()\n .slice(0, SAVED_POST_TAG_MAX)\n .trim(),\n )\n .filter((t) => t.length > 0)\n return Array.from(new Set(clean)).slice(0, SAVED_POST_MAX_TAGS)\n}\n","/**\n * Read Inspiration and Read Competitor — the nodes that read posts the person\n * already has (the Inspiration library; a tracked brand's scans) and emit them\n * the way Social Search does: `json` the posts (`SocialPost[]`), `text` their\n * digest (`socialPostsDigest`), one list item per post. Both engines' output\n * branches read this ONE list, so a new reader is routed like the rest.\n *\n * The routes behind them (`/v1/inspiration-read`, `/v1/competitor-read`) are\n * free: they read what the account already holds.\n */\n\nexport const INSPIRATION_READ_NODE_TYPE = \"inspiration-read\" as const\nexport const COMPETITOR_READ_NODE_TYPE = \"competitor-read\" as const\n\nexport const SOCIAL_POST_READER_NODE_TYPES: ReadonlySet<string> = new Set([INSPIRATION_READ_NODE_TYPE, COMPETITOR_READ_NODE_TYPE])\n\nexport function isSocialPostReaderNodeType(type: unknown): boolean {\n return typeof type === \"string\" && SOCIAL_POST_READER_NODE_TYPES.has(type)\n}\n\n/** The most posts one run reads. */\nexport const SOCIAL_READ_LIMIT_MAX = 100\nexport const SOCIAL_READ_DEFAULT_LIMIT = 20\n/** A window in hours reaches back at most 30 days; in days, at most a year (Competitors keep at most twelve months of scans). */\nexport const SOCIAL_READ_WINDOW_HOURS_MAX = 720\nexport const SOCIAL_READ_WINDOW_DAYS_MAX = 365\n\n/** `window`: the last N hours or days. `day`: one calendar day in the node's timezone. */\nexport const SOCIAL_READ_PERIODS = [\"window\", \"day\"] as const\nexport type SocialReadPeriod = (typeof SOCIAL_READ_PERIODS)[number]\n\n/** Which of a brand's posts Read Competitor reads: its own, posts about it, or both. */\nexport const COMPETITOR_READ_ROLES = [\"own\", \"about\", \"all\"] as const\nexport type CompetitorReadRole = (typeof COMPETITOR_READ_ROLES)[number]\n\n/** A calendar day as the node stores it. */\nexport const SOCIAL_READ_DAY_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/\n","/**\n * Competitors — the wire contract of the competitor tracking area.\n *\n * A person tracks brands (competitors, or their own brand): their accounts,\n * where to look for posts that name them, and a schedule. Each scan reads the\n * accounts and searches the name, one Social Search page per search, and\n * produces action cards: what happened, why it matters, what to do, with the\n * posts it rests on.\n *\n * Why public: these are the shapes `/v1/competitors*` answers and the SDK's\n * `competitors` resource types; the card `kind` vocabulary is what a client\n * phrases a card by. How a card is decided is not part of the contract.\n */\nimport type { SocialPlatform, SocialPost } from \"./social-search.js\"\nimport { SOCIAL_SEARCH_CREDITS_PER_PAGE } from \"./social-search.js\"\n\n/** The accounts a scan reads straight from. */\nexport const COMPETITOR_ACCOUNT_KEYS = [\"tiktok\", \"instagram\", \"youtube\", \"x\", \"linkedin\", \"meta_ads\"] as const\nexport type CompetitorAccountKey = (typeof COMPETITOR_ACCOUNT_KEYS)[number]\n\n/** Where a scan looks for posts that name the brand. */\nexport const COMPETITOR_ABOUT_PLATFORMS = [\"tiktok\", \"instagram\", \"youtube\", \"x\", \"reddit\", \"linkedin\"] as const\nexport type CompetitorAboutPlatform = (typeof COMPETITOR_ABOUT_PLATFORMS)[number]\nexport const COMPETITOR_DEFAULT_ABOUT_PLATFORMS: readonly CompetitorAboutPlatform[] = [\"tiktok\", \"instagram\", \"youtube\", \"x\", \"reddit\"]\n\nexport const COMPETITOR_SCHEDULES = [\"off\", \"weekly\", \"daily\"] as const\nexport type CompetitorSchedule = (typeof COMPETITOR_SCHEDULES)[number]\n\n/** One search per account and per about-platform. */\nexport const COMPETITOR_SCAN_MAX_SEARCHES = COMPETITOR_ACCOUNT_KEYS.length + COMPETITOR_ABOUT_PLATFORMS.length\nexport const COMPETITOR_SCAN_NODE_TYPE = \"competitor-scan\"\n/** How many brands one person can track. */\nexport const COMPETITORS_MAX = 50\n\nexport type CompetitorAccounts = Partial<Record<CompetitorAccountKey, string>>\n\n/** A search of a brand: its account (\"own\") or its name (\"about\"). */\nexport type CompetitorSearchKind = \"own\" | \"about\"\n\n/** One search a scan runs. */\nexport interface CompetitorSearch {\n readonly kind: CompetitorSearchKind\n readonly platform: SocialPlatform\n}\n\nexport interface TrackedCompetitor {\n readonly id: string\n readonly brand: string\n readonly website: string\n readonly accounts: CompetitorAccounts\n readonly aboutPlatforms: readonly CompetitorAboutPlatform[]\n /** The person's own brand: cards speak to them. */\n readonly isOwn: boolean\n readonly schedule: CompetitorSchedule\n readonly nextScanAt: string | null\n readonly lastScanAt: string | null\n readonly lastScanId: string | null\n /** Why the last scan (or scheduled start) fell short; null when it did not. */\n readonly lastScanError: string | null\n /** A scan is running now. */\n readonly scanning: boolean\n /** Searches one scan runs; a scan costs this many Social Search pages. */\n readonly searches: number\n /** What the next scan searches. Absent from a server older than this field. */\n readonly searchPlan?: readonly CompetitorSearch[]\n readonly createdAt: string\n readonly updatedAt: string\n}\n\n/** What a brand's latest scan found on one platform, and what works for it there. */\nexport interface CompetitorPlatformTally {\n readonly platform: SocialPlatform\n /** The brand's own posts the scan kept there. */\n readonly own: number\n /** Posts about the brand the scan kept there. */\n readonly about: number\n /** The searches the scan ran there. */\n readonly searched: readonly CompetitorSearchKind[]\n /** Of those, the ones that failed; null when the scan cannot say which (a scan stored before this was kept, that had failures). */\n readonly failed: readonly CompetitorSearchKind[] | null\n /** Its typical reach there, in `unit`; null while too few of its posts, or until its next scan. */\n readonly usual: number | null\n readonly unit: \"views\" | \"points\" | \"likes\" | null\n /** What its best posts there share most strongly; null when nothing stands out, or until its next scan. */\n readonly top: BrandLesson | null\n /** The account's followers at this scan; null when the platform gives none (YouTube, Reddit) or no post of its own was read. Absent from an older server. */\n readonly followers?: number | null\n}\n\n/** A brand's latest scan, platform by platform. */\nexport interface CompetitorBrandTally {\n readonly scanId: string\n readonly at: string\n readonly platforms: readonly CompetitorPlatformTally[]\n}\n\nexport const ACTION_CARD_KINDS = [\n \"outlier\",\n \"launch\",\n \"complaints\",\n \"spreading\",\n \"sound\",\n \"mentions_up\",\n \"pace\",\n \"market_sound\",\n \"top_in_sources\",\n] as const\nexport type ActionCardKind = (typeof ACTION_CARD_KINDS)[number]\n\n/** 1 = act now · 2 = an opening worth taking · 3 = good to know. */\nexport type ActionCardPriority = 1 | 2 | 3\n\nexport interface ActionCard {\n /** Stable across scans for the same finding. */\n readonly id: string\n readonly kind: ActionCardKind\n readonly priority: ActionCardPriority\n /** How strong the finding is within its kind, 0 to 1. The API returns\n * cards already in order (priority, then kind, then strength). */\n readonly strength?: number\n /** The tracked brand it is about; null for a market card. */\n readonly subjectId: string | null\n /**\n * The numbers and words to phrase the card with. Common: `brand`, `own`.\n * Per kind: outlier `platform, ratio, over100, reach, usual, unit` ·\n * launch `firstLine, posts` · complaints `count, example` · spreading and\n * top_in_sources `platform, reach, perDay, unit, firstLine` · sound\n * `soundTitle, posts, views` · market_sound `soundTitle, brands, views` ·\n * mentions_up `now, before` · pace `platform, recent, before`.\n */\n readonly params: Readonly<Record<string, string | number | boolean | readonly string[]>>\n /** Ids of the posts it rests on (at most four). */\n readonly evidence: readonly string[]\n /** English text, for surfaces that do not phrase cards themselves. */\n readonly title: string\n readonly why: string\n readonly action: string\n}\n\n/** A post a scan found, with whose it is. */\nexport type CompetitorPost = SocialPost & { readonly role: \"own\" | \"about\" | \"market\" }\n\nexport interface CompetitorScanCounts {\n readonly own: number\n readonly about: number\n readonly searches: number\n readonly failedSearches: number\n /** The searches that returned, as `<own|about>:<platform>`. */\n readonly okSearches?: readonly string[]\n}\n\nexport interface CompetitorScanSummary {\n readonly id: string\n readonly at: string\n readonly counts: CompetitorScanCounts\n readonly cards: number\n}\n\nexport interface CompetitorScan {\n readonly id: string\n readonly at: string\n readonly counts: CompetitorScanCounts\n readonly posts: readonly CompetitorPost[]\n readonly cards: readonly ActionCard[]\n}\n\n/** `GET /v1/competitors`. */\nexport interface CompetitorListResult {\n readonly data: readonly TrackedCompetitor[]\n /** How many months of scans your plan keeps (older scans are deleted at a brand's next scan). Absent from an older server. */\n readonly historyMonths?: number\n}\n\n/** One platform as one scan found and read it. Numbers a scan stored before they were kept answer null. */\nexport interface CompetitorHistoryPlatform {\n readonly platform: SocialPlatform\n readonly own: number | null\n readonly about: number | null\n /** The account's followers at that scan; null when the platform gives none. */\n readonly followers: number | null\n /** The brand's usual reach there as learned at that scan, in `unit`. */\n readonly usual: number | null\n readonly unit: \"views\" | \"points\" | \"likes\" | null\n}\n\nexport interface CompetitorHistoryPoint {\n readonly id: string\n readonly at: string\n readonly platforms: readonly CompetitorHistoryPlatform[]\n}\n\n/** `GET /v1/competitors/:id/history`: the brand's scans, oldest first. */\nexport interface CompetitorHistory {\n readonly scans: readonly CompetitorHistoryPoint[]\n}\n\n/** The followers a scan read, and when. */\nexport interface CompetitorPeriodFollowers {\n readonly value: number\n readonly at: string\n}\n\n/** A brand on one platform over a period. */\nexport interface CompetitorPeriodPlatform {\n readonly platform: SocialPlatform\n /** The brand's own posts published in the period, and the posts about it. */\n readonly own: number\n readonly about: number\n /** The median reach of its own posts in the period; null below three posts. */\n readonly usual: number | null\n readonly unit: \"views\" | \"points\" | \"likes\" | null\n /** From the newest scan inside the period; null when no scan read them. */\n readonly followers: CompetitorPeriodFollowers | null\n /** Followers gained (or lost) since the newest scan before the period; null when either side is unknown. */\n readonly change: number | null\n /** What worked there in the period (the lessons need eight posts). */\n readonly lessons: readonly BrandLesson[]\n /** Its best posts of the period there, best first, at most four. */\n readonly best: readonly string[]\n}\n\nexport interface CompetitorPeriod {\n readonly from: string\n readonly to: string\n readonly platforms: readonly CompetitorPeriodPlatform[]\n}\n\n/** `GET /v1/competitors/:id/compare`: ISO datetimes; a period is at most a year; `vsFrom` and `vsTo` go together. */\nexport interface CompetitorCompareInput {\n readonly from: string\n readonly to: string\n readonly vsFrom?: string\n readonly vsTo?: string\n}\n\n/** One or two periods, and the posts they name. */\nexport interface CompetitorCompareResult {\n readonly periods: readonly CompetitorPeriod[]\n readonly posts: Readonly<Record<string, CompetitorPost>>\n}\n\n/** `GET /v1/competitors/:id`. */\nexport interface CompetitorDetail extends TrackedCompetitor {\n readonly latestScan: CompetitorScan | null\n /** Its latest scan, platform by platform; null before its first scan. Absent from an older server. */\n readonly platforms?: readonly CompetitorPlatformTally[] | null\n /** Newest first, at most twelve. */\n readonly scans: readonly CompetitorScanSummary[]\n}\n\n/** `GET /v1/competitors/cards`: every card, most urgent first, and the posts they rest on. */\nexport interface CompetitorCardsResult {\n readonly cards: readonly ActionCard[]\n readonly posts: Readonly<Record<string, CompetitorPost>>\n /**\n * How the advice the person acted on went, per family. Within a priority,\n * cards of a family marked `proven` come first and `weak` ones last; the\n * order of priorities never changes. Empty until there are verdicts.\n */\n readonly record?: readonly AdviceRecord[]\n /** Each tracked brand with a scan (by id): its latest scan, platform by platform. Absent from an older server. */\n readonly brands?: Readonly<Record<string, CompetitorBrandTally>>\n}\n\n// ── Did it work? (\"I did this\" on a card) ─────────────────────────────────\n\n/**\n * Advice is summed up by family: a competitor's sound and a sound around the\n * market are both \"sound\"; \"outlier\" is making a post like a competitor's\n * best one.\n */\nexport const ADVICE_FAMILIES = [\"sound\", \"outlier\", \"launch\", \"complaints\"] as const\nexport type AdviceFamily = (typeof ADVICE_FAMILIES)[number]\n\n/** The family a card's advice belongs to; null for a card whose advice is not a post. */\nexport function adviceFamilyOf(kind: string): AdviceFamily | null {\n if (kind === \"sound\" || kind === \"market_sound\") return \"sound\"\n if (kind === \"outlier\" || kind === \"launch\" || kind === \"complaints\") return kind\n return null\n}\n\n/**\n * Whether \"I did this\" applies: the card's advice ends in a post of the\n * person's own. Complaints about their own brand end in replies, so not those.\n * The server is the judge; this only decides whether to offer the button.\n */\nexport function isMeasurableCard(card: Pick<ActionCard, \"kind\" | \"params\">): boolean {\n if (card.kind === \"complaints\") return card.params.own !== true\n return adviceFamilyOf(card.kind) !== null\n}\n\n/** What a card said when it was acted on (cards change with every scan). */\nexport interface CardSnapshot {\n readonly title: string\n readonly why: string\n readonly action: string\n readonly priority?: ActionCardPriority\n /** The card's numbers and words, to phrase it as the wall did. */\n readonly params?: ActionCard[\"params\"]\n readonly brand?: string\n readonly platform?: string\n readonly evidence: readonly string[]\n /** A sound card's sound. */\n readonly soundId?: string\n /** When the card first showed. */\n readonly cardAt?: string\n}\n\nexport const CARD_OUTCOME_STATES = [\n \"worked\",\n \"flat\",\n \"missed\",\n \"waiting\",\n \"not_found\",\n \"older_than_advice\",\n \"no_baseline\",\n \"posts_since\",\n \"no_posts_yet\",\n \"no_brand\",\n] as const\n/**\n * worked / flat (about the usual) / missed (below it): the verdict on the one\n * post tied to the card. waiting: that post is too new, or not scanned yet.\n * not_found: the linked post never showed up in the brand's scans.\n * older_than_advice: the linked post went up before the advice.\n * no_baseline: too few of the brand's posts on that platform to compare with.\n * posts_since: nothing tied to the card; the brand's posts since, no verdict.\n * no_posts_yet: nothing tied and no post since. no_brand: no own brand scanned.\n */\nexport type CardOutcomeState = (typeof CARD_OUTCOME_STATES)[number]\n\nexport interface CardOutcome {\n readonly state: CardOutcomeState\n /** The post's reach over the brand's usual. */\n readonly ratio?: number\n readonly liftLabel?: string\n readonly reach?: number\n readonly usual?: number\n readonly unit?: \"views\" | \"points\" | \"likes\"\n readonly platform?: string\n /** The judged post first; with no tie, the best posts since. */\n readonly postIds?: readonly string[]\n readonly ageDays?: number\n /** How the judged post was tied: the person's link, or a sound card's sound. */\n readonly matchedBy?: \"link\" | \"sound\"\n /** The brand's posts since the advice, newest first, to pick the one that came of it. */\n readonly candidates?: readonly string[]\n}\n\n/** The first verdict, kept as it was reached. */\nexport interface CardVerdict {\n readonly state: \"worked\" | \"flat\" | \"missed\"\n readonly ratio: number\n readonly reach: number\n readonly usual: number\n readonly unit: \"views\" | \"points\" | \"likes\"\n readonly platform: string\n readonly postId: string\n readonly matchedBy: \"link\" | \"sound\"\n readonly at: string\n}\n\n/** A card the person acted on, and how it went. */\nexport interface CardAction {\n readonly id: string\n /** The card on the wall it was made on. */\n readonly cardId: string\n readonly cardKind: ActionCardKind\n readonly card: CardSnapshot\n /** The tracked brand it was about; null for a market card (or a removed brand). */\n readonly subjectId: string | null\n readonly postUrl: string | null\n /** When the post was linked. */\n readonly linkedAt: string | null\n readonly actedAt: string\n readonly verdict: CardVerdict | null\n /** When the person first saw the verdict. */\n readonly seenAt: string | null\n /**\n * The card is still on the wall. Once it leaves, the mark stays (in Tried\n * and the record), and the card can be marked anew if it comes back.\n */\n readonly onWall: boolean\n readonly outcome: CardOutcome\n}\n\n/** How one family of advice went for the person, one verdict per post. */\nexport interface AdviceRecord {\n readonly family: AdviceFamily\n readonly tried: number\n readonly worked: number\n readonly flat: number\n readonly missed: number\n /** The mean of those posts' reach over the usual. */\n readonly avgRatio: number\n /** Enough verdicts to show this record. */\n readonly shown: boolean\n /** Whether it moves this family's cards (up when proven, down when weak). */\n readonly tier: \"proven\" | \"weak\" | \"neutral\"\n}\n\n/** `GET /v1/competitors/actions`: the cards the person acted on, newest first. */\nexport interface CompetitorActionsResult {\n readonly actions: readonly CardAction[]\n readonly record: readonly AdviceRecord[]\n /** The posts the outcomes name, by id. */\n readonly posts: Readonly<Record<string, CompetitorPost>>\n}\n\n/** `POST /v1/competitors/actions`: mark a card on the wall as done. */\nexport interface MarkCardInput {\n readonly cardId: string\n /** The person's own post that came of it (http(s), up to 1,000 characters). */\n readonly postUrl?: string | null\n}\n\n/** `POST` and `PATCH /v1/competitors/actions*`: the mark, and the posts its outcome names. */\nexport interface CardActionResult {\n readonly action: CardAction\n readonly posts: Readonly<Record<string, CompetitorPost>>\n /** POST only: false when the card was already marked (the mark is returned as it was). */\n readonly created?: boolean\n}\n\n/** `PATCH /v1/competitors/actions/:id`: link (or unlink with null) the post, or mark the verdict seen. */\nexport interface UpdateCardActionInput {\n readonly postUrl?: string | null\n readonly seen?: true\n}\n\n// ── What works (stage 4: learning from results) ───────────────────────────\n\n/** The traits a brand's best posts can share. */\nexport const BRAND_LESSON_KINDS = [\n \"short_videos\",\n \"long_videos\",\n \"format\",\n \"question_hook\",\n \"number_hook\",\n \"short_caption\",\n \"long_caption\",\n \"hashtag\",\n \"sound\",\n \"weekday\",\n] as const\nexport type BrandLessonKind = (typeof BRAND_LESSON_KINDS)[number]\n\n/**\n * One thing a brand's best posts share, measured on its own posts: the posts\n * with the trait reached `lift` times what the rest did.\n */\nexport interface BrandLesson {\n /** `<platform>:<kind>:<key>`, stable across reads. */\n readonly id: string\n readonly kind: BrandLessonKind\n readonly platform: string\n /**\n * Always `lift` (number), `liftLabel` (\"2.4x\"), `posts` (with the trait),\n * `winners` (of the best among them) and `unit` (\"views\" | \"likes\" |\n * \"points\"). Per kind: short_videos `maxSec` · long_videos `minSec` ·\n * format `format` · short_caption and long_caption `chars` · hashtag `tag` ·\n * sound `sound` · weekday `day` (0 = Sunday, UTC).\n */\n readonly params: Readonly<Record<string, string | number | boolean | readonly string[]>>\n /** Ids of the posts it rests on, best first (at most four). */\n readonly evidence: readonly string[]\n readonly strength: number\n /** English, for surfaces that do not phrase lessons themselves. */\n readonly text: string\n}\n\n/** What works for a brand on one platform. */\nexport interface BrandPlatformLessons {\n readonly platform: string\n /** The brand's own posts counted there. */\n readonly posts: number\n /** Their typical reach; null while there are fewer than `minPosts`. */\n readonly usual: number | null\n readonly unit: \"views\" | \"points\" | \"likes\"\n /** Its best posts, best first. */\n readonly winners: readonly string[]\n /** Its weakest posts, weakest first. */\n readonly misses: readonly string[]\n readonly lessons: readonly BrandLesson[]\n}\n\nexport interface BrandLessons {\n readonly subjectId: string\n /** The user's own brand (\"what works for you\"), not a competitor. */\n readonly isOwn: boolean\n readonly platforms: readonly BrandPlatformLessons[]\n /** Posts a platform needs before it gets lessons. */\n readonly minPosts: number\n}\n\n/** `GET /v1/competitors/:id/lessons`: what works for a tracked brand, and the posts it names. */\nexport interface CompetitorLessonsResult {\n readonly lessons: BrandLessons\n readonly posts: Readonly<Record<string, CompetitorPost>>\n}\n\n/** `POST /v1/competitor-discover`: a brand's accounts found from its website. */\nexport interface CompetitorDiscovery {\n readonly brand: string\n readonly website: string\n readonly accounts: Partial<Record<CompetitorAccountKey, { readonly value: string; readonly from: \"site\" | \"guess\" }>>\n}\n\nexport type CreateCompetitorInput = {\n readonly brand: string\n readonly website?: string\n readonly accounts?: CompetitorAccounts\n readonly aboutPlatforms?: readonly CompetitorAboutPlatform[]\n readonly isOwn?: boolean\n /** Default weekly. */\n readonly schedule?: CompetitorSchedule\n}\n\nexport type UpdateCompetitorInput = Partial<CreateCompetitorInput>\n\n/** Searches a scan of this configuration runs. */\nexport function competitorScanSearches(c: { readonly accounts?: CompetitorAccounts; readonly aboutPlatforms?: readonly string[] }): number {\n const accounts = COMPETITOR_ACCOUNT_KEYS.filter((k) => (c.accounts?.[k] ?? \"\").trim() !== \"\").length\n const about = (c.aboutPlatforms ?? []).filter((p) => (COMPETITOR_ABOUT_PLATFORMS as readonly string[]).includes(p)).length\n return accounts + about\n}\n\n/** The credit id of a scan of `n` searches. */\nexport function competitorScanCreditId(n: number): string {\n const clamped = Math.min(Math.max(Math.round(n), 1), COMPETITOR_SCAN_MAX_SEARCHES)\n return `${COMPETITOR_SCAN_NODE_TYPE}:${clamped}`\n}\n\n/** A scan costs one Social Search page per search: every id it can reserve. */\nexport const COMPETITOR_SCAN_CREDIT_COSTS: Readonly<Record<string, number>> = Object.fromEntries(\n Array.from({ length: COMPETITOR_SCAN_MAX_SEARCHES }, (_, i) => [competitorScanCreditId(i + 1), (i + 1) * SOCIAL_SEARCH_CREDITS_PER_PAGE] as const),\n)\n\n/** The credits a scan of this many searches costs. */\nexport function competitorScanCredits(searches: number): number {\n return searches <= 0 ? 0 : COMPETITOR_SCAN_CREDIT_COSTS[competitorScanCreditId(searches)] ?? 0\n}\n\n/** Whether a platform is one the about-search covers (used by pickers). */\nexport function isCompetitorAboutPlatform(value: string): value is CompetitorAboutPlatform & SocialPlatform {\n return (COMPETITOR_ABOUT_PLATFORMS as readonly string[]).includes(value)\n}\n","export type SocialMediaPlatform = \"instagram\" | \"tiktok\" | \"x\" | \"youtube\" | \"facebook\" | \"linkedin\" | \"telegram\"\n\nexport type SocialMediaContentType =\n | \"feed-square\" | \"feed-portrait\" | \"feed-landscape\" | \"story-reel\" // Instagram\n | \"video\" // TikTok\n | \"image-landscape\" | \"image-square\" | \"x-video\" // X\n | \"short\" // YouTube\n | \"fb-feed-portrait\" | \"reel\" // Facebook\n | \"li-image-landscape\" | \"li-image-square\" | \"li-video\" // LinkedIn\n\nexport interface SocialMediaSpec {\n readonly platform: SocialMediaPlatform\n readonly contentType: SocialMediaContentType\n readonly label: string\n readonly width: number\n readonly height: number\n readonly maxDurationSeconds: number | null // null = image only (no duration limit)\n readonly textLimit: number\n readonly isVideo: boolean\n}\n\nexport const PLATFORM_SPECS: Record<string, SocialMediaSpec> = {\n \"instagram:feed-square\": {\n platform: \"instagram\", contentType: \"feed-square\", label: \"Feed Square\",\n width: 1080, height: 1080, maxDurationSeconds: 60, textLimit: 2200, isVideo: true,\n },\n \"instagram:feed-portrait\": {\n platform: \"instagram\", contentType: \"feed-portrait\", label: \"Feed Portrait\",\n width: 1080, height: 1350, maxDurationSeconds: 60, textLimit: 2200, isVideo: true,\n },\n \"instagram:feed-landscape\": {\n platform: \"instagram\", contentType: \"feed-landscape\", label: \"Feed Landscape\",\n width: 1080, height: 566, maxDurationSeconds: 60, textLimit: 2200, isVideo: true,\n },\n \"instagram:story-reel\": {\n platform: \"instagram\", contentType: \"story-reel\", label: \"Story / Reel\",\n width: 1080, height: 1920, maxDurationSeconds: 180, textLimit: 2200, isVideo: true,\n },\n \"tiktok:video\": {\n platform: \"tiktok\", contentType: \"video\", label: \"Video\",\n width: 1080, height: 1920, maxDurationSeconds: 600, textLimit: 4000, isVideo: true,\n },\n \"x:image-landscape\": {\n platform: \"x\", contentType: \"image-landscape\", label: \"Image Landscape\",\n width: 1200, height: 675, maxDurationSeconds: null, textLimit: 280, isVideo: false,\n },\n \"x:image-square\": {\n platform: \"x\", contentType: \"image-square\", label: \"Image Square\",\n width: 1080, height: 1080, maxDurationSeconds: null, textLimit: 280, isVideo: false,\n },\n \"x:x-video\": {\n platform: \"x\", contentType: \"x-video\", label: \"Video\",\n width: 1920, height: 1080, maxDurationSeconds: 140, textLimit: 280, isVideo: true,\n },\n \"youtube:short\": {\n platform: \"youtube\", contentType: \"short\", label: \"Short\",\n width: 1080, height: 1920, maxDurationSeconds: 180, textLimit: 5000, isVideo: true,\n },\n \"facebook:fb-feed-portrait\": {\n platform: \"facebook\", contentType: \"fb-feed-portrait\", label: \"Feed Portrait\",\n width: 1080, height: 1350, maxDurationSeconds: null, textLimit: 63206, isVideo: false,\n },\n \"facebook:reel\": {\n platform: \"facebook\", contentType: \"reel\", label: \"Reel\",\n width: 1080, height: 1920, maxDurationSeconds: 90, textLimit: 63206, isVideo: true,\n },\n \"linkedin:li-image-landscape\": {\n platform: \"linkedin\", contentType: \"li-image-landscape\", label: \"Image Landscape\",\n width: 1200, height: 627, maxDurationSeconds: null, textLimit: 3000, isVideo: false,\n },\n \"linkedin:li-image-square\": {\n platform: \"linkedin\", contentType: \"li-image-square\", label: \"Image Square\",\n width: 1080, height: 1080, maxDurationSeconds: null, textLimit: 3000, isVideo: false,\n },\n \"linkedin:li-video\": {\n platform: \"linkedin\", contentType: \"li-video\", label: \"Video\",\n width: 1920, height: 1080, maxDurationSeconds: 600, textLimit: 3000, isVideo: true,\n },\n}\n\nexport const CONTENT_TYPES_BY_PLATFORM: Record<SocialMediaPlatform, ReadonlyArray<{ key: string; label: string }>> = {\n instagram: [\n { key: \"instagram:feed-square\", label: \"Feed Square (1080×1080)\" },\n { key: \"instagram:feed-portrait\", label: \"Feed Portrait (1080×1350)\" },\n { key: \"instagram:feed-landscape\", label: \"Feed Landscape (1080×566)\" },\n { key: \"instagram:story-reel\", label: \"Story / Reel (1080×1920)\" },\n ],\n tiktok: [\n { key: \"tiktok:video\", label: \"Video (1080×1920)\" },\n ],\n x: [\n { key: \"x:image-landscape\", label: \"Image Landscape (1200×675)\" },\n { key: \"x:image-square\", label: \"Image Square (1080×1080)\" },\n { key: \"x:x-video\", label: \"Video (1920×1080)\" },\n ],\n youtube: [\n { key: \"youtube:short\", label: \"Short (1080×1920)\" },\n ],\n facebook: [\n { key: \"facebook:fb-feed-portrait\", label: \"Feed Portrait (1080×1350)\" },\n { key: \"facebook:reel\", label: \"Reel (1080×1920)\" },\n ],\n linkedin: [\n { key: \"linkedin:li-image-landscape\", label: \"Image Landscape (1200×627)\" },\n { key: \"linkedin:li-image-square\", label: \"Image Square (1080×1080)\" },\n { key: \"linkedin:li-video\", label: \"Video (1920×1080)\" },\n ],\n telegram: [\n { key: \"telegram:message\", label: \"Message (text)\" },\n ],\n}\n\nexport const PLATFORM_LABELS: Record<SocialMediaPlatform, string> = {\n instagram: \"Instagram\",\n tiktok: \"TikTok\",\n x: \"X (Twitter)\",\n youtube: \"YouTube\",\n facebook: \"Facebook\",\n linkedin: \"LinkedIn\",\n telegram: \"Telegram\",\n}\n","/**\n * Telegram Channel Feed — the post shape the node emits on its `json` handle,\n * the digest its `text` handle carries, and the ONE cursor rule (where the\n * feed's position goes after a run). Structural vocabulary and a pure rule;\n * the fetching lives in the backend (`services/social/telegram-channel.ts`).\n *\n * Media links (`cdn*.telesco.pe/...`) carry a `?token=` and expire within days:\n * a consumer that needs the picture later copies it (an upload node, a\n * collection), never stores the link alone.\n */\n\nexport interface TelegramChannelPostMedia {\n readonly type: \"photo\" | \"video\"\n /** The file — a photo's, or a video's when the preview page embeds the file (\"Watch in Telegram\" players have none). */\n readonly url?: string\n /** A video's poster frame. */\n readonly posterUrl?: string\n}\n\nexport interface TelegramChannelPost {\n /** Sequential per-channel message id. */\n readonly id: number\n /** The channel's bare id (no `@`). */\n readonly channel: string\n /** Canonical link to the post. */\n readonly postUrl: string\n /** Plain text (HTML stripped, entities decoded); a reply's quoted text is not part of it. */\n readonly text: string\n /** ISO timestamp of the post. */\n readonly date?: string\n /** The channel or person the post was forwarded from. */\n readonly forwardedFrom?: { readonly name: string; readonly url?: string }\n /** Every photo and video of the post, in page order (an album is several). */\n readonly media: readonly TelegramChannelPostMedia[]\n /** The first picture — the first photo, else the first video's poster — for a consumer that takes one image. */\n readonly imageUrl?: string\n /** The view counter as the page shows it (\"1.52M\"). */\n readonly views?: string\n}\n\n/** The most posts a poll emits per run — two preview pages at most. */\nexport const TELEGRAM_FEED_LIMIT_MAX = 30\n/** The most posts a peek (\"re-fetch the last N\") can show — one preview page. */\nexport const TELEGRAM_FEED_PEEK_MAX = 20\n/** What one preview page (`t.me/s/<channel>[?after=<id>]`) renders. */\nexport const TELEGRAM_FEED_PAGE_SIZE = 20\n/** The default posts per run. */\nexport const TELEGRAM_FEED_DEFAULT_LIMIT = 5\nexport const TELEGRAM_FEED_DIGEST_SEPARATOR = \"\\n\\n---\\n\\n\"\n\n/** The `text` handle: the posts' text, oldest first, joined by a rule. Posts with no text (a bare picture) add nothing. */\nexport function telegramFeedDigest(posts: ReadonlyArray<Pick<TelegramChannelPost, \"text\">>): string {\n return posts\n .map((p) => p.text)\n .filter((t) => typeof t === \"string\" && t.trim().length > 0)\n .join(TELEGRAM_FEED_DIGEST_SEPARATOR)\n}\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null && !Array.isArray(v)\nconst str = (v: unknown): string | undefined => (typeof v === \"string\" ? v : undefined)\n\n/**\n * The posts held in a saved `generatedJson` / a run's `output.json`, normalized:\n * anything that is not a post with a numeric id and a text is left out, and a\n * post saved before a field existed reads with that field at its default.\n */\nexport function telegramPostsFrom(value: unknown): TelegramChannelPost[] {\n if (!Array.isArray(value)) return []\n const out: TelegramChannelPost[] = []\n for (const item of value) {\n if (!isRecord(item) || typeof item.id !== \"number\" || !Number.isFinite(item.id) || typeof item.text !== \"string\") continue\n const media = Array.isArray(item.media)\n ? item.media.filter((m): m is TelegramChannelPostMedia => isRecord(m) && (m.type === \"photo\" || m.type === \"video\"))\n : []\n const forwarded = isRecord(item.forwardedFrom) && typeof item.forwardedFrom.name === \"string\"\n ? { name: item.forwardedFrom.name, ...(str(item.forwardedFrom.url) ? { url: item.forwardedFrom.url as string } : {}) }\n : undefined\n const channel = str(item.channel) ?? \"\"\n out.push({\n id: item.id,\n channel,\n postUrl: str(item.postUrl) ?? str(item.url) ?? (channel ? `https://t.me/${channel}/${item.id}` : \"\"),\n text: item.text,\n ...(str(item.date) ? { date: item.date as string } : {}),\n ...(forwarded ? { forwardedFrom: forwarded } : {}),\n media,\n ...(str(item.imageUrl) ? { imageUrl: item.imageUrl as string } : {}),\n ...(str(item.views) ? { views: item.views as string } : {}),\n })\n }\n return out\n}\n\nexport interface FeedEmissionPlan<P extends { readonly id: number }> {\n /** The posts this run emits, oldest first. */\n readonly emitted: P[]\n /** The feed's position after this run (the cursor to store), or undefined when there is nothing to stand on. */\n readonly latestId: number | undefined\n}\n\n/**\n * Where the feed stands after a run — the ONE rule both the route and the\n * tests read (decided 2026-10-05):\n *\n * - no position yet (first run, after Reset): the NEWEST `limit` posts, and\n * the position jumps to the newest post — the person asked for what is new\n * from now on; older posts are never revisited;\n * - a stored position: the OLDEST `limit` posts above it, and the position\n * becomes the highest post EMITTED — a backlog drains `limit` per run and\n * nothing is lost (the old rule jumped to the newest post even when `limit`\n * cut the fetch short, and the posts in between were gone for good).\n *\n * `posts` may come in any order and repeat (a pinned post renders twice).\n */\nexport function planFeedEmission<P extends { readonly id: number }>(\n posts: ReadonlyArray<P>,\n since: number | undefined,\n limit: number,\n /**\n * The highest message id the fetched page(s) rendered above `since`, posts\n * with nothing to read included. When nothing readable lies above the\n * position but the page went further, the position moves past the unreadable\n * posts — else the feed reads the same page every tick for ever.\n */\n pageMaxId?: number,\n): FeedEmissionPlan<P> {\n const cap = Math.max(1, Math.min(TELEGRAM_FEED_LIMIT_MAX, Math.floor(Number.isFinite(limit) ? limit : TELEGRAM_FEED_DEFAULT_LIMIT) || 1))\n const byId = new Map<number, P>()\n for (const post of posts) byId.set(post.id, post)\n const sorted = [...byId.values()].sort((a, b) => a.id - b.id)\n if (since === undefined) {\n const emitted = sorted.slice(-cap)\n return { emitted, latestId: sorted.length > 0 ? sorted[sorted.length - 1]!.id : undefined }\n }\n const fresh = sorted.filter((p) => p.id > since)\n const emitted = fresh.slice(0, cap)\n if (emitted.length > 0) return { emitted, latestId: emitted[emitted.length - 1]!.id }\n const pastUnreadable = pageMaxId !== undefined && Number.isFinite(pageMaxId) && pageMaxId > since\n return { emitted, latestId: pastUnreadable ? pageMaxId : since }\n}\n"]}
|