@nodaro/shared 3.27.0 → 3.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/index.cjs +1050 -105
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +801 -46
  4. package/dist/index.d.ts +801 -46
  5. package/dist/index.js +950 -106
  6. package/dist/index.js.map +1 -1
  7. package/package.json +1 -1
  8. package/src/__tests__/entity-image-handle.test.ts +61 -1
  9. package/src/__tests__/json-kinds.test.ts +10 -0
  10. package/src/__tests__/model-seed-capability.test.ts +34 -0
  11. package/src/__tests__/node-preset-extract.test.ts +8 -0
  12. package/src/__tests__/node-run-routes.test.ts +63 -0
  13. package/src/__tests__/node-runtime-keys.test.ts +61 -0
  14. package/src/__tests__/pitch-tempo-pricing.test.ts +62 -0
  15. package/src/__tests__/presentation-utils.test.ts +14 -0
  16. package/src/__tests__/producer-types.test.ts +15 -0
  17. package/src/__tests__/render-nodes.test.ts +38 -4
  18. package/src/__tests__/seedance-draft.test.ts +74 -0
  19. package/src/__tests__/ugc-clip-saved-list.test.ts +19 -0
  20. package/src/__tests__/ugc-node-wires.test.ts +600 -0
  21. package/src/__tests__/ugc-run-state.test.ts +80 -3
  22. package/src/__tests__/video-depth.test.ts +146 -0
  23. package/src/__tests__/video-mask.test.ts +77 -0
  24. package/src/__tests__/workflow-export-strip.test.ts +14 -0
  25. package/src/credit-estimators/index.ts +10 -0
  26. package/src/credit-estimators/pitch-tempo.ts +68 -0
  27. package/src/credit-identifiers.ts +32 -7
  28. package/src/entity-image-handle.ts +48 -1
  29. package/src/fan-out-rows.ts +2 -0
  30. package/src/index.ts +15 -1
  31. package/src/json-kinds.ts +9 -0
  32. package/src/mask-composite.ts +108 -0
  33. package/src/model-catalog.ts +101 -2
  34. package/src/model-constants.ts +3 -0
  35. package/src/model-tree.ts +2 -0
  36. package/src/node-mappable-fields.ts +2 -0
  37. package/src/node-preset-export.ts +2 -2
  38. package/src/node-preset-extract.ts +6 -4
  39. package/src/node-run-routes.ts +76 -0
  40. package/src/node-runtime-keys.ts +42 -1
  41. package/src/presentation-utils.ts +6 -2
  42. package/src/producer-types.ts +19 -0
  43. package/src/render-nodes.ts +14 -5
  44. package/src/seedance-draft.ts +64 -0
  45. package/src/social-post.ts +13 -0
  46. package/src/ugc-node-wires.ts +623 -0
  47. package/src/ugc-run-state.ts +60 -5
  48. package/src/video-depth.ts +151 -0
  49. package/src/video-mask.ts +96 -0
  50. package/src/workflow-export.ts +3 -1
@@ -0,0 +1,600 @@
1
+ import { describe, expect, it } from "vitest"
2
+ import { DEFAULT_TRANSCRIBE_NODE_PROVIDER, FAN_OUT_EACH_HANDLES, UGC_NODE_TYPES, VIDEO_PRODUCER_TYPES, defaultEdgeOutputMode, parseCaptionPlan } from "../index.js"
3
+ import {
4
+ UGC_CREATOR_MISSING_MESSAGE, UGC_CREATOR_PICKER_TYPES, UGC_NEWER_APP_MESSAGE, UGC_NOT_SERVED_MESSAGE, UGC_PICK_GONE_MESSAGE, UGC_PRIMARY_HANDLE, UGC_SCREENSHOT_HANDLES,
5
+ UGC_SCRIPT_DEFAULT_TARGET_SEC, UGC_VERSION_MESSAGE, readUgcWire, ugcCardsBody, ugcCardsJobs, ugcCardsOutputs, ugcClipBody, ugcClipOutputs, ugcClipsBody, ugcClipsOutputs,
6
+ ugcAwaitsPick, ugcCreatorBody, ugcCreatorCallsToRender, ugcCreatorCandidate, ugcCreatorCandidates, ugcCreatorOutputs, ugcCreatorPick, ugcFailure,
7
+ ugcKeptOutputs, ugcPipValue, ugcScriptBody, ugcScriptOutputs, ugcScriptResult, type UgcCreatorCandidateCalls,
8
+ } from "../ugc-node-wires.js"
9
+
10
+ const ticket = (i: number) => ({ v: 1, index: i, durationSec: 12, video: { tool: "t", args: {} } })
11
+
12
+ describe("UGC wires", () => {
13
+ it("fan-out only from the clips handle; UGC Clip is a video producer", () => {
14
+ expect(FAN_OUT_EACH_HANDLES["ugc-clips"]).toEqual({ each: ["clips"], primary: "clips" })
15
+ expect(defaultEdgeOutputMode("ugc-clips", "clips")).toBe("each")
16
+ expect(defaultEdgeOutputMode("ugc-clips", "plan-out")).toBe("last")
17
+ expect(defaultEdgeOutputMode("ugc-clips", "transcript")).toBe("last")
18
+ expect(VIDEO_PRODUCER_TYPES.has("ugc-clip")).toBe(true)
19
+ })
20
+ it("refuses a wire from a newer version", () => {
21
+ expect(readUgcWire(JSON.stringify({ v: 2 }))).toEqual({ error: UGC_VERSION_MESSAGE })
22
+ expect(readUgcWire({ v: 1, a: 1 })).toEqual({ value: { v: 1, a: 1 } })
23
+ })
24
+ it("maps a router 404 to the Cloud sentence and forwards a route message", () => {
25
+ expect(ugcFailure(404, "")).toBe(UGC_NOT_SERVED_MESSAGE)
26
+ expect(ugcFailure(422, JSON.stringify({ error: { code: "minor_age_refused", message: "m" } }))).toBe("That age can't be used: UGC creators are adults only.")
27
+ expect(ugcFailure(422, JSON.stringify({ error: { code: "language_not_available", message: "Not yet." } }))).toBe("Not yet.")
28
+ })
29
+ it("creator: sampled needs a category; photo needs a photo; a wired photo wins", () => {
30
+ expect(ugcCreatorBody({ data: { source: "sampled", gender: "woman", keepResult: false } })).toEqual({ error: "Run UGC Script first, or pick a product category." })
31
+ expect(ugcCreatorBody({ data: { source: "photo", gender: "man", keepResult: false } })).toEqual({ error: "Connect or upload a photo of yourself." })
32
+ expect(ugcCreatorBody({ data: { source: "photo", gender: "man", keepResult: false, photoUrl: "https://cdn.example/a.png" }, photoUrl: "https://cdn.example/wired.png" }))
33
+ .toEqual({ body: { source: { kind: "photo", imageUrl: "https://cdn.example/wired.png", gender: "man" } } })
34
+ expect(ugcCreatorBody({ data: { source: "sampled", gender: "woman", keepResult: false, seed: 7 }, category: "saas", pickers: { setting: { setting: "kitchen" } } }))
35
+ .toEqual({ body: { seed: 7, source: { kind: "sampled", gender: "woman", productCategory: "saas", pickers: { setting: { setting: "kitchen" } } } } })
36
+ })
37
+ it("script: slots in order, empty ones dropped, English until the language card", () => {
38
+ expect(ugcScriptBody({ site: "Acme", screenshots: ["https://cdn.example/1.png", undefined, "https://cdn.example/3.png"], targetDurationSec: 20 }))
39
+ .toEqual({ body: { site: "Acme", screenshots: ["https://cdn.example/1.png", "https://cdn.example/3.png"], targetDurationSec: 20, language: "en" } })
40
+ expect(ugcScriptBody({ screenshots: [] })).toEqual({ error: "Add the product name or website." })
41
+ })
42
+ it("script outputs: the plan gets v: 1, the category is text", () => {
43
+ expect(ugcScriptOutputs({ plan: { hook: "h" }, productCategory: "saas" })).toEqual({ plan: JSON.stringify({ v: 1, hook: "h" }), category: "saas" })
44
+ })
45
+ it("clips: canvas body, invalid plan message, outputs", () => {
46
+ const body = ugcClipsBody({ planWire: JSON.stringify({ v: 1, hook: "h" }), creatorWire: JSON.stringify({ v: 1, gender: "woman", identityImages: ["https://cdn.example/c.png"], traits: null }), voiceId: "voice-1" })
47
+ expect(body).toEqual({ body: { plan: { v: 1, hook: "h" }, gender: "woman", traits: null, identityImages: ["https://cdn.example/c.png"], surface: "canvas", voiceId: "voice-1" } })
48
+ expect(ugcClipsOutputs({ errors: [{ message: "Too long.", fix: "Trim it." }] })).toEqual({ error: "The script needs changes: Too long. Trim it." })
49
+ const ok = ugcClipsOutputs({ errors: [], tickets: [ticket(0), ticket(1)], sizedPlan: { p: 1 }, transcript: "a b", speechCheckCall: { tool: "transcribe", args: { language: "he" } }, hasCards: true })
50
+ expect("tickets" in ok && ok.tickets).toEqual([JSON.stringify(ticket(0)), JSON.stringify(ticket(1))])
51
+ expect("outputs" in ok && JSON.parse(ok.outputs["plan-out"]!)).toEqual({ v: 1, plan: { p: 1 }, transcribeArgs: { language: "he" } })
52
+ const old = ugcClipsOutputs({ errors: [], tickets: [ticket(0)], sizedPlan: {}, transcript: "" })
53
+ expect("outputs" in old && JSON.parse(old.outputs["plan-out"]!).transcribeArgs).toEqual({})
54
+ })
55
+ it("clip: the nonce is the clip's re-render count", () => {
56
+ expect(ugcClipBody({ ticketWire: JSON.stringify(ticket(1)), rerender: { "2": 3 } })).toMatchObject({ body: { ticket: ticket(1), nonce: 3 }, clipNumber: 2, durationSec: 12 })
57
+ expect(ugcClipBody({ ticketWire: JSON.stringify(ticket(0)), runKey: "exec-1" })).toMatchObject({ body: { ticket: ticket(0), nonce: 0, runKey: "exec-1" } })
58
+ })
59
+ it("cards: the two timing bodies, the node's fields last", () => {
60
+ const planOut = JSON.stringify({ v: 1, plan: { p: 1 }, transcribeArgs: { language: "he", provider: "x", wordTimestamps: false } })
61
+ const jobs = ugcCardsJobs({ planOutWire: planOut, videoUrl: "https://cdn.example/v.mp4", transcript: "a b" })
62
+ expect("transcribe" in jobs && jobs.transcribe.body).toEqual({ language: "he", audioUrl: "https://cdn.example/v.mp4", provider: DEFAULT_TRANSCRIBE_NODE_PROVIDER, wordTimestamps: true })
63
+ expect("alignment" in jobs && jobs.alignment.body).toEqual({ audioUrl: "https://cdn.example/v.mp4", transcript: "a b" })
64
+ const en = ugcCardsJobs({ planOutWire: JSON.stringify({ v: 1, plan: {}, transcribeArgs: {} }), videoUrl: "https://cdn.example/v.mp4", transcript: "a" })
65
+ expect("transcribe" in en && en.transcribe.body).toEqual({ audioUrl: "https://cdn.example/v.mp4", provider: DEFAULT_TRANSCRIBE_NODE_PROVIDER, wordTimestamps: true })
66
+ expect(ugcCardsJobs({ planOutWire: JSON.stringify({ v: 1, hook: "a bare plan" }), videoUrl: "https://cdn.example/v.mp4", transcript: "a" })).toEqual({ error: "Connect the Script (sized) output of UGC Clips." })
67
+ })
68
+ it("cards outputs: an empty timing becomes the empty caption plan", () => {
69
+ const o = ugcCardsOutputs({ layerPlan: [], captionTiming: null, report: { lines: ["No cards or captions: the speech could not be timed."] } })
70
+ expect(JSON.parse(o.captionPlan!)).toEqual({ v: 1, hookText: "", hookEndMs: 0, bodyEndMs: 0, captions: [] })
71
+ expect(o.layerPlan).toBe("[]")
72
+ expect(o.report).toBe("No cards or captions: the speech could not be timed.")
73
+ })
74
+ })
75
+
76
+ const imageCall = (m: string) => ({ tool: "generate_image", args: { prompt: "p", model: m, aspect_ratio: "3:4" } })
77
+ const FALLBACK = imageCall("image-model-c")
78
+ const SAMPLED = {
79
+ kind: "sampled", seed: 7, gender: "woman", traits: { t: 1 }, identityImages: [], promptsVersion: "1.0.0", productCategory: "saas",
80
+ image: { ...imageCall("image-model-a"), fallback: FALLBACK },
81
+ candidates: [{ model: "image-model-a", ...imageCall("image-model-a") }, { model: "image-model-b", ...imageCall("image-model-b") }],
82
+ fallback: FALLBACK,
83
+ pick: { how: "user" },
84
+ realismPass: null, secondFrame: null, photoCheck: null,
85
+ genderCheck: { tool: "image_to_text", args: { custom_prompt: "q" }, passToken: "PASS", refusal: "R" },
86
+ }
87
+ const read = (a: Record<string, unknown>): UgcCreatorCandidateCalls => {
88
+ const r = ugcCreatorCandidates(a)
89
+ if ("error" in r) throw new Error(r.error)
90
+ return r
91
+ }
92
+
93
+ describe("UGC Creator candidates", () => {
94
+ it("two candidates: tool and args only, the primary first and equal to `image`, which is not run as well", () => {
95
+ const r = read(SAMPLED)
96
+ expect(r).toEqual({ calls: [imageCall("image-model-a"), imageCall("image-model-b")], fallback: FALLBACK, pick: "user" })
97
+ expect(r.calls[0]).toEqual({ tool: SAMPLED.image.tool, args: SAMPLED.image.args })
98
+ for (const c of r.calls) expect(Object.keys(c).sort()).toEqual(["args", "tool"])
99
+ })
100
+ it("one candidate is the primary: nothing to pick", () => {
101
+ expect(read({ ...SAMPLED, candidates: [SAMPLED.candidates[0]], pick: { how: "primary" } }))
102
+ .toEqual({ calls: [imageCall("image-model-a")], fallback: FALLBACK, pick: "primary" })
103
+ // A builder that says "user" over one call, or names no pick over two, still renders the primary alone.
104
+ expect(read({ ...SAMPLED, candidates: [SAMPLED.candidates[0]] }).pick).toBe("primary")
105
+ expect(read({ ...SAMPLED, pick: null }).pick).toBe("primary")
106
+ })
107
+ it("an answer from before candidates renders `image` with its own fallback, as today", () => {
108
+ const { candidates: _c, fallback: _f, pick: _p, ...older } = SAMPLED
109
+ expect(read(older)).toEqual({ calls: [imageCall("image-model-a")], fallback: FALLBACK, pick: "primary" })
110
+ expect(read({ ...older, candidates: [] })).toEqual({ calls: [imageCall("image-model-a")], fallback: FALLBACK, pick: "primary" })
111
+ })
112
+ it("a photo renders nothing", () => {
113
+ expect(read({ kind: "photo", image: null, candidates: [], fallback: null, pick: null })).toEqual({ calls: [], fallback: null, pick: null })
114
+ })
115
+ it("a shape the app cannot read → the newer-app message", () => {
116
+ expect(ugcCreatorCandidates({ ...SAMPLED, candidates: [{ model: "image-model-a" }] })).toEqual({ error: UGC_NEWER_APP_MESSAGE })
117
+ expect(ugcCreatorCandidates({ ...SAMPLED, candidates: "two" })).toEqual({ error: UGC_NEWER_APP_MESSAGE })
118
+ expect(ugcCreatorCandidates({ ...SAMPLED, candidates: undefined, image: { tool: 1, args: {} } })).toEqual({ error: UGC_NEWER_APP_MESSAGE })
119
+ })
120
+ it("every candidate is rendered only where a person picks", () => {
121
+ const r = read(SAMPLED)
122
+ expect(ugcCreatorCallsToRender(r, { personPicks: true })).toEqual(r.calls)
123
+ expect(ugcCreatorCallsToRender(r, { personPicks: false })).toEqual([r.calls[0]])
124
+ const one = read({ ...SAMPLED, candidates: [SAMPLED.candidates[0]] })
125
+ expect(ugcCreatorCallsToRender(one, { personPicks: true })).toEqual([one.calls[0]])
126
+ })
127
+ it("the record is built from the picked image and never carries the round", () => {
128
+ const o = ugcCreatorOutputs(SAMPLED, ["https://cdn.example/b.png"])
129
+ expect(o.record).toEqual({ v: 1, kind: "sampled", gender: "woman", identityImages: ["https://cdn.example/b.png"], traits: { t: 1 }, seed: 7, promptsVersion: "1.0.0", productCategory: "saas" })
130
+ expect(o.outputs).toEqual({ creator: JSON.stringify(o.record), image: "https://cdn.example/b.png" })
131
+ expect(o.imageUrl).toBe("https://cdn.example/b.png")
132
+ })
133
+ it("a candidate keeps its image and record; the pick hands the picked one on", () => {
134
+ const a = ugcCreatorCandidate(SAMPLED, ["https://cdn.example/a.png"])
135
+ const b = ugcCreatorCandidate(SAMPLED, ["https://cdn.example/b.png"])
136
+ expect(a).toEqual({ imageUrl: "https://cdn.example/a.png", record: ugcCreatorOutputs(SAMPLED, ["https://cdn.example/a.png"]).record })
137
+ expect(ugcCreatorPick([a, b], 1)).toEqual({ result: b.record, outputs: { creator: JSON.stringify(b.record), image: "https://cdn.example/b.png" }, imageUrl: "https://cdn.example/b.png" })
138
+ })
139
+ it("a pick of a stale or foreign list is refused, never guessed", () => {
140
+ const a = ugcCreatorCandidate(SAMPLED, ["https://cdn.example/a.png"])
141
+ expect(ugcCreatorPick([a], 1)).toEqual({ error: UGC_PICK_GONE_MESSAGE })
142
+ expect(ugcCreatorPick(undefined, 0)).toEqual({ error: UGC_PICK_GONE_MESSAGE })
143
+ expect(ugcCreatorPick([a], -1)).toEqual({ error: UGC_PICK_GONE_MESSAGE })
144
+ expect(ugcCreatorPick([{ imageUrl: "https://cdn.example/x.png", record: { v: 2, identityImages: ["https://cdn.example/x.png"] } }], 0)).toEqual({ error: UGC_VERSION_MESSAGE })
145
+ expect(ugcCreatorPick([{ imageUrl: "https://cdn.example/x.png", record: { v: 1, identityImages: ["https://cdn.example/y.png"] } }], 0)).toEqual({ error: UGC_PICK_GONE_MESSAGE })
146
+ })
147
+ })
148
+
149
+ // The edge cases the cases above leave open. Placeholders only.
150
+ describe("UGC wires: the module surface", () => {
151
+ it("is re-exported from the package index", async () => {
152
+ const shared: Record<string, unknown> = await import("../index.js")
153
+ for (const name of ["readUgcWire", "ugcFailure", "ugcCreatorBody", "ugcCreatorOutputs", "ugcCreatorCandidates", "ugcCreatorCallsToRender", "ugcCreatorCandidate", "ugcCreatorPick", "ugcScriptBody", "ugcScriptOutputs", "ugcClipsBody", "ugcClipsOutputs", "ugcClipBody", "ugcClipOutputs", "ugcCardsJobs", "ugcCardsBody", "ugcCardsOutputs"]) {
154
+ expect(typeof shared[name], name).toBe("function")
155
+ }
156
+ expect(shared.UGC_NEWER_APP_MESSAGE).toBe("This step needs a newer app version.")
157
+ expect(shared.UGC_PICK_GONE_MESSAGE).toBe(UGC_PICK_GONE_MESSAGE)
158
+ expect(shared.UGC_CREATOR_MISSING_MESSAGE).toBe("UGC Creator has no creator yet. Run it, or pick one of its options.")
159
+ expect(shared.UGC_SCRIPT_DEFAULT_TARGET_SEC).toBe(UGC_SCRIPT_DEFAULT_TARGET_SEC)
160
+ expect(shared.UGC_PRIMARY_HANDLE).toBe(UGC_PRIMARY_HANDLE)
161
+ })
162
+ it("names a primary handle for exactly the five UGC types", () => {
163
+ expect(Object.keys(UGC_PRIMARY_HANDLE).sort()).toEqual([...UGC_NODE_TYPES].sort())
164
+ expect(UGC_PRIMARY_HANDLE).toEqual({ "ugc-creator": "creator", "ugc-script": "plan", "ugc-clips": "clips", "ugc-clip": "video-out", "ugc-cards": "layerPlan" })
165
+ })
166
+ it("lists the eight screenshot slots in card order", () => {
167
+ expect(UGC_SCREENSHOT_HANDLES).toEqual(["screenshot", "screenshot2", "screenshot3", "screenshot4", "screenshot5", "screenshot6", "screenshot7", "screenshot8"])
168
+ })
169
+ it("names the four pickers UGC Creator's look input takes, from the index too", async () => {
170
+ expect([...UGC_CREATOR_PICKER_TYPES].sort()).toEqual(["lighting", "person", "setting", "styling"])
171
+ const shared: Record<string, unknown> = await import("../index.js")
172
+ expect(shared.UGC_CREATOR_PICKER_TYPES).toBe(UGC_CREATOR_PICKER_TYPES)
173
+ })
174
+ })
175
+
176
+ describe("ugcPipValue: what an edge from a UGC node reads", () => {
177
+ const outputs = { clips: "t0", "plan-out": "p", transcript: "" }
178
+ it("the pip the edge leaves; no pip reads the node's primary output", () => {
179
+ expect(ugcPipValue(outputs, "ugc-clips", "plan-out")).toBe("p")
180
+ expect(ugcPipValue(outputs, "ugc-clips", null)).toBe("t0")
181
+ expect(ugcPipValue(outputs, "ugc-clips", undefined)).toBe("t0")
182
+ expect(ugcPipValue(outputs, "ugc-clips", "")).toBe("t0")
183
+ })
184
+ it("an empty string is a value; a pip the node does not hold is none", () => {
185
+ expect(ugcPipValue(outputs, "ugc-clips", "transcript")).toBe("")
186
+ expect(ugcPipValue({ creator: "{}" }, "ugc-creator", "image")).toBeUndefined()
187
+ })
188
+ it("never reads an inherited key, a non-string or something that is not outputs", () => {
189
+ expect(ugcPipValue(outputs, "ugc-clips", "constructor")).toBeUndefined()
190
+ expect(ugcPipValue({ clips: 3 }, "ugc-clips", "clips")).toBeUndefined()
191
+ for (const raw of [undefined, null, "x", ["t0"]]) expect(ugcPipValue(raw, "ugc-clips", "clips")).toBeUndefined()
192
+ expect(ugcPipValue(outputs, "constructor", null)).toBeUndefined()
193
+ })
194
+ })
195
+
196
+ describe("readUgcWire", () => {
197
+ it("anything that is not a UGC wire gets the caller's message (the version message by default); another v gets the version message", () => {
198
+ for (const raw of [undefined, null, "", "not json", "[1]", [1], 3, { hook: "h" }]) {
199
+ expect(readUgcWire(raw), String(raw)).toEqual({ error: UGC_VERSION_MESSAGE })
200
+ expect(readUgcWire(raw, "Connect it."), String(raw)).toEqual({ error: "Connect it." })
201
+ }
202
+ expect(readUgcWire({ v: "1" }, "Connect it.")).toEqual({ error: UGC_VERSION_MESSAGE })
203
+ expect(readUgcWire(JSON.stringify({ v: 1, a: [1] }))).toEqual({ value: { v: 1, a: [1] } })
204
+ })
205
+ })
206
+
207
+ describe("ugcFailure", () => {
208
+ it("only the router's 404 (no error code) is the Cloud sentence; a route's own 404 keeps its message", () => {
209
+ expect(ugcFailure(404, JSON.stringify({ message: "Route POST:/v1/ugc/clip not found", error: "Not Found", statusCode: 404 }))).toBe(UGC_NOT_SERVED_MESSAGE)
210
+ expect(ugcFailure(404, "<html>not found</html>")).toBe(UGC_NOT_SERVED_MESSAGE)
211
+ expect(ugcFailure(404, JSON.stringify({ error: { code: "not_found", message: "That image is gone." } }))).toBe("That image is gone.")
212
+ })
213
+ it("forwards a 4xx or 503 message; any other failure names its status", () => {
214
+ expect(ugcFailure(400, JSON.stringify({ error: { code: "validation_error", message: "source.imageUrl: Invalid url", issues: [] } }))).toBe("source.imageUrl: Invalid url")
215
+ expect(ugcFailure(402, JSON.stringify({ error: { code: "insufficient_credits", message: "Not enough credits." } }))).toBe("Not enough credits.")
216
+ expect(ugcFailure(429, JSON.stringify({ statusCode: 429, error: { code: "rate_limit_exceeded", message: "Too many requests. Retry in 9s." } }))).toBe("Too many requests. Retry in 9s.")
217
+ expect(ugcFailure(413, JSON.stringify({ statusCode: 413, error: "Payload Too Large", message: "Request body is too large" }))).toBe("Request body is too large")
218
+ expect(ugcFailure(503, JSON.stringify({ error: { code: "x", message: "UGC clips need a newer app version" } }))).toBe("UGC clips need a newer app version")
219
+ expect(ugcFailure(503, "")).toBe("UGC step failed (503)")
220
+ expect(ugcFailure(500, JSON.stringify({ error: { code: "internal", message: "stack details" } }))).toBe("UGC step failed (500)")
221
+ expect(ugcFailure(400, "not json")).toBe("UGC step failed (400)")
222
+ expect(ugcFailure(422, JSON.stringify({ error: { code: "x", message: " " } }))).toBe("UGC step failed (422)")
223
+ })
224
+ })
225
+
226
+ describe("ugcCreatorBody: the remaining rules", () => {
227
+ it("needs woman or man, on either source", () => {
228
+ expect(ugcCreatorBody({ data: { source: "sampled" }, category: "saas" })).toEqual({ error: "Choose woman or man." })
229
+ expect(ugcCreatorBody({ data: { source: "photo", gender: "other" }, photoUrl: "https://cdn.example/p.png" })).toEqual({ error: "Choose woman or man." })
230
+ })
231
+ it("no source is a sampled creator; the override wins over the wired category; an empty one is absent", () => {
232
+ expect(ugcCreatorBody({ data: { gender: "man", categoryOverride: "beauty" }, category: "saas" }))
233
+ .toEqual({ body: { source: { kind: "sampled", gender: "man", productCategory: "beauty" } } })
234
+ expect(ugcCreatorBody({ data: { gender: "man", categoryOverride: "" }, category: "saas" }))
235
+ .toEqual({ body: { source: { kind: "sampled", gender: "man", productCategory: "saas" } } })
236
+ expect(ugcCreatorBody({ data: { gender: "man", categoryOverride: " " }, category: " " })).toEqual({ error: "Run UGC Script first, or pick a product category." })
237
+ })
238
+ it("a re-roll sends the last sampled traits as previous; a kept result, a photo result or a photo source sends none", () => {
239
+ const result = { v: 1, kind: "sampled", gender: "woman", identityImages: ["https://cdn.example/c.png"], traits: { t: 1 } }
240
+ expect(ugcCreatorBody({ data: { gender: "woman", keepResult: false, result }, category: "saas" }))
241
+ .toEqual({ body: { source: { kind: "sampled", gender: "woman", productCategory: "saas", previous: { t: 1 } } } })
242
+ expect(ugcCreatorBody({ data: { gender: "woman", keepResult: true, result }, category: "saas" }))
243
+ .toEqual({ body: { source: { kind: "sampled", gender: "woman", productCategory: "saas" } } })
244
+ expect(ugcCreatorBody({ data: { gender: "woman", result: { ...result, kind: "photo", traits: null } }, category: "saas" }))
245
+ .toEqual({ body: { source: { kind: "sampled", gender: "woman", productCategory: "saas" } } })
246
+ expect(ugcCreatorBody({ data: { source: "photo", gender: "woman", photoUrl: "https://cdn.example/p.png", seed: 3, result }, category: "saas", pickers: { person: { age: "a" } } }))
247
+ .toEqual({ body: { source: { kind: "photo", imageUrl: "https://cdn.example/p.png", gender: "woman" } } })
248
+ })
249
+ it("sends only the pickers that set a field", () => {
250
+ expect(ugcCreatorBody({ data: { gender: "woman" }, category: "saas", pickers: { person: {}, setting: { setting: "s" } } }))
251
+ .toEqual({ body: { source: { kind: "sampled", gender: "woman", productCategory: "saas", pickers: { setting: { setting: "s" } } } } })
252
+ expect(ugcCreatorBody({ data: { gender: "woman" }, category: "saas", pickers: { person: {} } }))
253
+ .toEqual({ body: { source: { kind: "sampled", gender: "woman", productCategory: "saas" } } })
254
+ })
255
+ it("uses the node's photo when none is wired, and passes the URL on for the route to check", () => {
256
+ expect(ugcCreatorBody({ data: { source: "photo", gender: "man", photoUrl: "https://cdn.example/typed.png" }, photoUrl: "" }))
257
+ .toEqual({ body: { source: { kind: "photo", imageUrl: "https://cdn.example/typed.png", gender: "man" } } })
258
+ expect(ugcCreatorBody({ data: { source: "photo", gender: "man", photoUrl: "file:///etc/x.png" } }))
259
+ .toEqual({ body: { source: { kind: "photo", imageUrl: "file:///etc/x.png", gender: "man" } } })
260
+ })
261
+ })
262
+
263
+ describe("ugcCreatorOutputs: a photo", () => {
264
+ it("keeps the photo as the identity image; the missing sampled fields are null", () => {
265
+ const answer = { kind: "photo", gender: "man", traits: null, identityImages: ["https://cdn.example/p.png"], seed: 4, promptsVersion: "1.0.0", image: null, candidates: [], fallback: null, pick: null, photoCheck: { tool: "image_to_text", args: {} } }
266
+ const o = ugcCreatorOutputs(answer, ["https://cdn.example/p.png"])
267
+ expect(o.record).toEqual({ v: 1, kind: "photo", gender: "man", identityImages: ["https://cdn.example/p.png"], traits: null, seed: 4, promptsVersion: "1.0.0", productCategory: null })
268
+ expect(o.outputs.image).toBe("https://cdn.example/p.png")
269
+ })
270
+ it("copies the images it is given", () => {
271
+ const images = ["https://cdn.example/a.png", "https://cdn.example/a2.png"]
272
+ const o = ugcCreatorOutputs(SAMPLED, images)
273
+ expect(o.record.identityImages).toEqual(images)
274
+ expect(o.record.identityImages).not.toBe(images)
275
+ expect(o.imageUrl).toBe("https://cdn.example/a.png")
276
+ })
277
+ })
278
+
279
+ describe("ugcScriptBody / ugcScriptOutputs: the remaining rules", () => {
280
+ it("trims the site, refuses a blank one, and sends a product image only when there is one", () => {
281
+ expect(ugcScriptBody({ site: " https://acme.example\n", screenshots: ["", "https://cdn.example/2.png"], productImage: "https://cdn.example/p.png", targetDurationSec: 30 }))
282
+ .toEqual({ body: { site: "https://acme.example", screenshots: ["https://cdn.example/2.png"], productImage: "https://cdn.example/p.png", targetDurationSec: 30, language: "en" } })
283
+ expect(ugcScriptBody({ site: " \n", screenshots: ["https://cdn.example/1.png"] })).toEqual({ error: "Add the product name or website." })
284
+ })
285
+ it("always sends a length: a node with no number gets the default, which is the node's own default", () => {
286
+ // The node's default length and the length the run sends for a node without one are this one constant.
287
+ expect(UGC_SCRIPT_DEFAULT_TARGET_SEC).toBe(15)
288
+ const length = (targetDurationSec: unknown) => {
289
+ const r = ugcScriptBody({ site: "Acme", screenshots: [], targetDurationSec: targetDurationSec as number | undefined })
290
+ return "body" in r ? r.body.targetDurationSec : r.error
291
+ }
292
+ expect(length(undefined)).toBe(UGC_SCRIPT_DEFAULT_TARGET_SEC)
293
+ expect(length(null)).toBe(UGC_SCRIPT_DEFAULT_TARGET_SEC)
294
+ expect(length("20")).toBe(UGC_SCRIPT_DEFAULT_TARGET_SEC)
295
+ expect(length(20)).toBe(20)
296
+ // A number outside the route's range is sent as set, so the route names it.
297
+ expect(length(2)).toBe(2)
298
+ })
299
+ it("an answer without a plan or a category hands nothing on for it", () => {
300
+ expect(ugcScriptOutputs({ productCategory: "saas" })).toEqual({ category: "saas" })
301
+ expect(ugcScriptOutputs({ plan: { hook: "h" } })).toEqual({ plan: JSON.stringify({ v: 1, hook: "h" }) })
302
+ })
303
+ })
304
+
305
+ describe("ugcClipsBody / ugcClipsOutputs: the remaining rules", () => {
306
+ const PLAN = JSON.stringify({ v: 1, hook: "h" })
307
+ const CREATOR = JSON.stringify({ v: 1, gender: "man", identityImages: ["https://cdn.example/c.png"] })
308
+ it("names the missing input; refuses a newer wire", () => {
309
+ expect(ugcClipsBody({ planWire: undefined, creatorWire: CREATOR })).toEqual({ error: "Connect the Script output of UGC Script." })
310
+ expect(ugcClipsBody({ planWire: PLAN, creatorWire: JSON.stringify({ v: 2, gender: "man" }) })).toEqual({ error: UGC_VERSION_MESSAGE })
311
+ })
312
+ it("no creator on the creator input, or one it cannot read, is the one creator-missing message", () => {
313
+ for (const creatorWire of [undefined, null, "", "not json", JSON.stringify({ gender: "man" })]) {
314
+ expect(ugcClipsBody({ planWire: PLAN, creatorWire }), String(creatorWire)).toEqual({ error: UGC_CREATOR_MISSING_MESSAGE })
315
+ }
316
+ })
317
+ it("no voice, no voiceId; a record without traits sends null", () => {
318
+ expect(ugcClipsBody({ planWire: PLAN, creatorWire: CREATOR, voiceId: "" }))
319
+ .toEqual({ body: { plan: { v: 1, hook: "h" }, gender: "man", traits: null, identityImages: ["https://cdn.example/c.png"], surface: "canvas" } })
320
+ })
321
+ it("joins every error with its fix", () => {
322
+ expect(ugcClipsOutputs({ errors: [{ code: "A", message: "One.", fix: "Fix one." }, { code: "B", message: "Two." }] }))
323
+ .toEqual({ error: "The script needs changes: One. Fix one. Two." })
324
+ })
325
+ it("a valid answer the app cannot use fails before any clip renders", () => {
326
+ const ok = { errors: [], tickets: [ticket(0)], sizedPlan: {}, transcript: "a" }
327
+ expect(ugcClipsOutputs({ ...ok, tickets: undefined })).toEqual({ error: UGC_NEWER_APP_MESSAGE })
328
+ expect(ugcClipsOutputs({ ...ok, tickets: [] })).toEqual({ error: UGC_NEWER_APP_MESSAGE })
329
+ expect(ugcClipsOutputs({ ...ok, tickets: ["t"] })).toEqual({ error: UGC_NEWER_APP_MESSAGE })
330
+ expect(ugcClipsOutputs({ ...ok, sizedPlan: undefined })).toEqual({ error: UGC_NEWER_APP_MESSAGE })
331
+ expect(ugcClipsOutputs({ ...ok, transcript: undefined })).toEqual({ error: UGC_NEWER_APP_MESSAGE })
332
+ expect(ugcClipsOutputs({ errors: [{}] })).toEqual({ error: UGC_NEWER_APP_MESSAGE })
333
+ })
334
+ it("hands on the first ticket, the plan-out, the transcript and whether there are cards", () => {
335
+ const ok = ugcClipsOutputs({ errors: [], tickets: [ticket(0), ticket(1)], sizedPlan: { p: 1 }, transcript: "a b", hasCards: true })
336
+ expect(ok).toEqual({
337
+ outputs: { clips: JSON.stringify(ticket(0)), "plan-out": JSON.stringify({ v: 1, plan: { p: 1 }, transcribeArgs: {} }), transcript: "a b" },
338
+ tickets: [JSON.stringify(ticket(0)), JSON.stringify(ticket(1))],
339
+ hasCards: true,
340
+ })
341
+ const none = ugcClipsOutputs({ tickets: [ticket(0)], sizedPlan: {}, transcript: "a", speechCheckCall: { tool: "transcribe", args: null } })
342
+ expect("hasCards" in none && none.hasCards).toBe(false)
343
+ expect("outputs" in none && JSON.parse(none.outputs["plan-out"]!).transcribeArgs).toEqual({})
344
+ })
345
+ })
346
+
347
+ describe("ugcClipBody / ugcClipOutputs: the remaining rules", () => {
348
+ it("names the missing ticket, a ticket without its index or length, and a newer ticket", () => {
349
+ expect(ugcClipBody({ ticketWire: undefined })).toEqual({ error: "Connect the Clips output of UGC Clips." })
350
+ expect(ugcClipBody({ ticketWire: JSON.stringify({ v: 1, hook: "a plan" }) })).toEqual({ error: "Connect the Clips output of UGC Clips." })
351
+ expect(ugcClipBody({ ticketWire: JSON.stringify({ ...ticket(0), index: -1 }) })).toEqual({ error: "Connect the Clips output of UGC Clips." })
352
+ expect(ugcClipBody({ ticketWire: JSON.stringify({ ...ticket(0), durationSec: 0 }) })).toEqual({ error: "Connect the Clips output of UGC Clips." })
353
+ expect(ugcClipBody({ ticketWire: JSON.stringify({ ...ticket(0), v: 2 }) })).toEqual({ error: UGC_VERSION_MESSAGE })
354
+ })
355
+ it("no re-render of this clip, or an unreadable count, is nonce 0; no runKey without one", () => {
356
+ expect(ugcClipBody({ ticketWire: JSON.stringify(ticket(0)), rerender: { "2": 4 } })).toEqual({ body: { ticket: ticket(0), nonce: 0 }, clipNumber: 1, durationSec: 12 })
357
+ expect(ugcClipBody({ ticketWire: JSON.stringify(ticket(0)), rerender: { "1": "2" } as never })).toEqual({ body: { ticket: ticket(0), nonce: 0 }, clipNumber: 1, durationSec: 12 })
358
+ expect(ugcClipBody({ ticketWire: ticket(2), runKey: "" })).toEqual({ body: { ticket: ticket(2), nonce: 0 }, clipNumber: 3, durationSec: 12 })
359
+ })
360
+ it("the finished clip: its video, its real length and its warnings", () => {
361
+ expect(ugcClipOutputs({ videoUrl: "https://cdn.example/c1.mp4", durationSec: 13, clipWarnings: ["clip_lengthened:13", 7], frameCheck: { passed: true } }))
362
+ .toEqual({ outputs: { "video-out": "https://cdn.example/c1.mp4" }, videoUrl: "https://cdn.example/c1.mp4", durationSec: 13, clipWarnings: ["clip_lengthened:13"] })
363
+ expect(ugcClipOutputs({ videoUrl: "https://cdn.example/c1.mp4", durationSec: "13" })).toMatchObject({ durationSec: null, clipWarnings: [] })
364
+ expect(ugcClipOutputs({})).toEqual({ outputs: {}, videoUrl: "", durationSec: null, clipWarnings: [] })
365
+ })
366
+ it("reads the clip job's completion exactly as the plugin writes it: clipWarnings, never warnings", () => {
367
+ // The clip job completes with { durationSec, clipWarnings, frameCheck, videoUrl }.
368
+ const completed = { durationSec: 16, clipWarnings: ["clip_lengthened:16", "frame_check_failed"], frameCheck: { passed: false, rerendered: true }, videoUrl: "https://cdn.example/c2.mp4" }
369
+ expect(ugcClipOutputs(completed)).toEqual({
370
+ outputs: { "video-out": "https://cdn.example/c2.mp4" },
371
+ videoUrl: "https://cdn.example/c2.mp4",
372
+ durationSec: 16,
373
+ clipWarnings: ["clip_lengthened:16", "frame_check_failed"],
374
+ })
375
+ expect(ugcClipOutputs({ ...completed, clipWarnings: [] }).clipWarnings).toEqual([])
376
+ const { clipWarnings: _w, ...noWarnings } = completed
377
+ expect(ugcClipOutputs(noWarnings).clipWarnings).toEqual([])
378
+ expect(ugcClipOutputs({ ...noWarnings, warnings: ["frame_check_failed"] }).clipWarnings).toEqual([])
379
+ })
380
+ })
381
+
382
+ describe("ugcCardsJobs / ugcCardsBody / ugcCardsOutputs: the remaining rules", () => {
383
+ const PLAN_OUT = JSON.stringify({ v: 1, plan: { hook: "h" }, transcribeArgs: {} })
384
+ const NOT_PLAN_OUT = "Connect the Script (sized) output of UGC Clips."
385
+ it("refuses before any job: no plan-out, a plan-out without its parts, a newer one, no video, no transcript", () => {
386
+ const at = { videoUrl: "https://cdn.example/v.mp4", transcript: "a" }
387
+ expect(ugcCardsJobs({ planOutWire: undefined, ...at })).toEqual({ error: NOT_PLAN_OUT })
388
+ expect(ugcCardsJobs({ planOutWire: "not json", ...at })).toEqual({ error: NOT_PLAN_OUT })
389
+ expect(ugcCardsJobs({ planOutWire: JSON.stringify({ v: 1, plan: {}, transcribeArgs: [] }), ...at })).toEqual({ error: NOT_PLAN_OUT })
390
+ expect(ugcCardsJobs({ planOutWire: JSON.stringify({ v: 2, plan: {}, transcribeArgs: {} }), ...at })).toEqual({ error: UGC_VERSION_MESSAGE })
391
+ expect(ugcCardsJobs({ planOutWire: PLAN_OUT, transcript: "a" })).toEqual({ error: "Connect the joined video." })
392
+ expect(ugcCardsJobs({ planOutWire: PLAN_OUT, videoUrl: "https://cdn.example/v.mp4" })).toEqual({ error: "Connect the Transcript output of UGC Clips." })
393
+ })
394
+ it("an empty transcript is UGC Clips' answer, not a missing input: it goes on as it came", () => {
395
+ for (const transcript of ["", " "]) {
396
+ const jobs = ugcCardsJobs({ planOutWire: PLAN_OUT, videoUrl: "https://cdn.example/v.mp4", transcript })
397
+ expect("alignment" in jobs && jobs.alignment.body, JSON.stringify(transcript)).toEqual({ audioUrl: "https://cdn.example/v.mp4", transcript })
398
+ }
399
+ })
400
+ it("hands the wrapper's plan on, never the wrapper", () => {
401
+ const jobs = ugcCardsJobs({ planOutWire: PLAN_OUT, videoUrl: "https://cdn.example/v.mp4", transcript: "a b" })
402
+ expect(jobs).toMatchObject({ alignment: { path: "/v1/forced-alignment" }, transcribe: { path: "/v1/transcribe" }, plan: { hook: "h" } })
403
+ })
404
+ it("the cards body: canvas, the timing sources that are lists, the failures and the notes always", () => {
405
+ const base = { plan: { hook: "h" }, videoUrl: "https://cdn.example/v.mp4", failed: [] as const, clipNotes: [] }
406
+ expect(ugcCardsBody({ ...base, alignment: [{ word: "a", start: 0, end: 0.3 }], words: [{ text: "a", startMs: 0, endMs: 300 }] }))
407
+ .toEqual({ surface: "canvas", plan: { hook: "h" }, videoUrl: "https://cdn.example/v.mp4", alignment: [{ word: "a", start: 0, end: 0.3 }], words: [{ text: "a", startMs: 0, endMs: 300 }], failed: [], clipNotes: [] })
408
+ expect(ugcCardsBody({ ...base, alignment: undefined, words: { not: "a list" }, failed: ["alignment"], clipNotes: [{ clip: 1, warnings: ["w"], durationSec: 12 }] }))
409
+ .toEqual({ surface: "canvas", plan: { hook: "h" }, videoUrl: "https://cdn.example/v.mp4", failed: ["alignment"], clipNotes: [{ clip: 1, warnings: ["w"], durationSec: 12 }] })
410
+ })
411
+ it("a timing becomes a caption plan Add Captions reads; the report lines are joined", () => {
412
+ const timing = { hookText: "h", hookEndMs: 900, bodyEndMs: 4000, captions: [{ text: "a", startMs: 1000, endMs: 1300 }], videoDurationMs: 4200, language: "en" }
413
+ const o = ugcCardsOutputs({ layerPlan: [{ imageUrl: "https://cdn.example/1.png", start: 1, end: 2 }], captionTiming: timing, report: { lines: ["One.", "Two."] } })
414
+ expect(JSON.parse(o.captionPlan!)).toEqual({ v: 1, ...timing })
415
+ expect(parseCaptionPlan(o.captionPlan)).toEqual({ plan: { v: 1, ...timing } })
416
+ expect(JSON.parse(o.layerPlan!)).toEqual([{ imageUrl: "https://cdn.example/1.png", start: 1, end: 2 }])
417
+ expect(o.report).toBe("One.\nTwo.")
418
+ const empty = ugcCardsOutputs({})
419
+ expect(empty).toEqual({ layerPlan: "[]", captionPlan: JSON.stringify({ v: 1, hookText: "", hookEndMs: 0, bodyEndMs: 0, captions: [] }), report: "" })
420
+ expect("plan" in parseCaptionPlan(empty.captionPlan)).toBe(true)
421
+ })
422
+ })
423
+
424
+ describe("a kept result is handed on without a run", () => {
425
+ const record = { v: 1, kind: "sampled", gender: "woman", identityImages: ["https://cdn.example/c.png"], traits: { t: 1 }, seed: 7, promptsVersion: "1.0.0", productCategory: "saas" }
426
+ const scriptResult = { plan: { hook: "h" }, productCategory: "saas", warnings: [], notes: [], rounds: 1 }
427
+ it("a kept creator hands on its record and its first image", () => {
428
+ expect(ugcKeptOutputs("ugc-creator", { keepResult: true, result: record })).toEqual({ creator: JSON.stringify(record), image: "https://cdn.example/c.png" })
429
+ })
430
+ it("a kept script hands on its result's outputs", () => {
431
+ expect(ugcKeptOutputs("ugc-script", { keepResult: true, result: scriptResult })).toEqual(ugcScriptOutputs(scriptResult))
432
+ })
433
+ it("not kept: nothing, so the node runs", () => {
434
+ expect(ugcKeptOutputs("ugc-creator", { keepResult: false, result: record })).toBeNull()
435
+ expect(ugcKeptOutputs("ugc-script", { result: scriptResult })).toBeNull()
436
+ expect(ugcKeptOutputs("ugc-creator", { keepResult: "true", result: record })).toBeNull()
437
+ })
438
+ it("Keep on with nothing to hand on runs the node: no result, a creator with no image, a script with no plan", () => {
439
+ expect(ugcKeptOutputs("ugc-creator", { keepResult: true })).toBeNull()
440
+ expect(ugcKeptOutputs("ugc-creator", { keepResult: true, result: "a record" })).toBeNull()
441
+ expect(ugcKeptOutputs("ugc-creator", { keepResult: true, result: { ...record, identityImages: [] } })).toBeNull()
442
+ expect(ugcKeptOutputs("ugc-creator", { keepResult: true, result: { ...record, identityImages: [" "] } })).toBeNull()
443
+ expect(ugcKeptOutputs("ugc-script", { keepResult: true, result: { productCategory: "saas" } })).toBeNull()
444
+ expect(ugcKeptOutputs("ugc-script", { keepResult: true, result: [scriptResult] })).toBeNull()
445
+ })
446
+ it("the kept record goes on unread: one from another version is refused where it is read", () => {
447
+ const newer = ugcKeptOutputs("ugc-creator", { keepResult: true, result: { ...record, v: 2 } })
448
+ expect(newer?.creator).toBe(JSON.stringify({ ...record, v: 2 }))
449
+ expect(ugcClipsBody({ planWire: JSON.stringify({ v: 1, hook: "h" }), creatorWire: newer?.creator })).toEqual({ error: UGC_VERSION_MESSAGE })
450
+ })
451
+ it("only UGC Creator and UGC Script keep a result", () => {
452
+ for (const type of ["ugc-clips", "ugc-clip", "ugc-cards"]) {
453
+ expect(ugcKeptOutputs(type as "ugc-script", { keepResult: true, result: scriptResult }), type).toBeNull()
454
+ }
455
+ })
456
+ it("is re-exported from the package index", async () => {
457
+ const shared: Record<string, unknown> = await import("../index.js")
458
+ expect(shared.ugcKeptOutputs).toBe(ugcKeptOutputs)
459
+ expect(shared.ugcScriptResult).toBe(ugcScriptResult)
460
+ })
461
+ })
462
+
463
+ describe("UGC Script's result, the same on both engines", () => {
464
+ it("takes the plan, the category, the warnings, the notes and the rounds; nothing else", () => {
465
+ expect(ugcScriptResult({ plan: { hook: "h" }, productCategory: "saas", warnings: [{ code: "w" }], notes: ["n", 3], rounds: 2, extra: 1 }))
466
+ .toEqual({ plan: { hook: "h" }, productCategory: "saas", warnings: [{ code: "w" }], notes: ["n"], rounds: 2 })
467
+ })
468
+ it("a row without a plan has no result", () => {
469
+ expect(ugcScriptResult({ productCategory: "saas" })).toBeUndefined()
470
+ })
471
+ it("fills what the row leaves out, and copies the lists it keeps", () => {
472
+ expect(ugcScriptResult({ plan: { hook: "h" }, productCategory: " ", rounds: Number.NaN })).toEqual({ plan: { hook: "h" }, productCategory: "", warnings: [], notes: [], rounds: 0 })
473
+ const warnings = [{ code: "w" }]
474
+ expect(ugcScriptResult({ plan: { hook: "h" }, warnings })?.warnings).not.toBe(warnings)
475
+ expect(ugcScriptResult({ plan: [{ hook: "h" }] })).toBeUndefined()
476
+ })
477
+ })
478
+
479
+ describe("a creator waiting for a pick hands nothing on", () => {
480
+ const record = { v: 1, gender: "woman", identityImages: ["https://cdn.example/old.png"] }
481
+ it("ugcKeptOutputs is null while options wait, whatever keepResult says", () => {
482
+ const kept = { keepResult: true, result: record }
483
+ expect(ugcKeptOutputs("ugc-creator", kept)).not.toBeNull()
484
+ expect(ugcKeptOutputs("ugc-creator", { ...kept, candidates: [{ imageUrl: "https://cdn.example/a.png", record }] })).toBeNull()
485
+ })
486
+ })
487
+
488
+ describe("a UGC Creator waiting for a pick", () => {
489
+ const cand = (url: string, traits: Record<string, unknown>) => ({ imageUrl: url, record: { v: 1, gender: "woman", identityImages: [url], traits } })
490
+ it("two or more options on a run's output wait; one, none or a creator does not", () => {
491
+ expect(ugcAwaitsPick({ ugcCandidates: [cand("https://cdn.example/a.png", {}), cand("https://cdn.example/b.png", {})] })).toBe(true)
492
+ expect(ugcAwaitsPick({ ugcCandidates: [cand("https://cdn.example/a.png", {})] })).toBe(false)
493
+ expect(ugcAwaitsPick({ ugcOutputs: { creator: "{}" } })).toBe(false)
494
+ expect(ugcAwaitsPick(undefined)).toBe(false)
495
+ })
496
+ it("a re-draw takes `previous` from the latest creator the person saw: the waiting options, else the result", () => {
497
+ const data = { source: "sampled", gender: "woman", keepResult: false, result: { v: 1, traits: { t: 1 } }, candidates: [cand("https://cdn.example/a.png", { t: 2 }), cand("https://cdn.example/b.png", { t: 2 })] }
498
+ expect(ugcCreatorBody({ data, category: "saas" })).toEqual({ body: { source: { kind: "sampled", gender: "woman", productCategory: "saas", previous: { t: 2 } } } })
499
+ const { candidates: _c, ...picked } = data
500
+ expect(ugcCreatorBody({ data: picked, category: "saas" })).toEqual({ body: { source: { kind: "sampled", gender: "woman", productCategory: "saas", previous: { t: 1 } } } })
501
+ })
502
+ it("waiting options name `previous` even with Keep on, and an option without traits names none", () => {
503
+ const kept = { source: "sampled", gender: "woman", keepResult: true, result: { v: 1, traits: { t: 1 } }, candidates: [cand("https://cdn.example/a.png", { t: 3 })] }
504
+ expect(ugcCreatorBody({ data: kept, category: "saas" })).toEqual({ body: { source: { kind: "sampled", gender: "woman", productCategory: "saas", previous: { t: 3 } } } })
505
+ const bare = { ...kept, candidates: [{ imageUrl: "https://cdn.example/a.png", record: { v: 1 } }] }
506
+ expect(ugcCreatorBody({ data: bare, category: "saas" })).toEqual({ body: { source: { kind: "sampled", gender: "woman", productCategory: "saas" } } })
507
+ })
508
+ it("a run output that is not an object, or a list that is not one, never waits", () => {
509
+ expect(ugcAwaitsPick("two")).toBe(false)
510
+ expect(ugcAwaitsPick({ ugcCandidates: "two" })).toBe(false)
511
+ expect(ugcAwaitsPick({ ugcCandidates: { length: 2 } })).toBe(false)
512
+ })
513
+ })
514
+
515
+ describe("ugcPlanLengthSec: the length a saved plan was written to", () => {
516
+ it("reads the plan's own length, from the plan or its wire", async () => {
517
+ const { ugcPlanLengthSec } = await import("../ugc-node-wires.js")
518
+ const plan = { v: 1, hook: "h", beats: [{ line: "b" }], closer: { line: "c" }, targetDurationSec: 30 }
519
+ expect(ugcPlanLengthSec(plan)).toBe(30)
520
+ expect(ugcPlanLengthSec(JSON.stringify(plan))).toBe(30)
521
+ })
522
+ it("is undefined for a plan with no length, or one outside the script's range, and for anything that is not a plan", async () => {
523
+ const { ugcPlanLengthSec, UGC_SCRIPT_MIN_TARGET_SEC, UGC_SCRIPT_MAX_TARGET_SEC } = await import("../ugc-node-wires.js")
524
+ expect(ugcPlanLengthSec({ v: 1, hook: "h" })).toBeUndefined()
525
+ for (const bad of [UGC_SCRIPT_MIN_TARGET_SEC - 1, UGC_SCRIPT_MAX_TARGET_SEC + 1, 15.5, "15", null, Number.NaN]) {
526
+ expect(ugcPlanLengthSec({ v: 1, targetDurationSec: bad }), String(bad)).toBeUndefined()
527
+ }
528
+ for (const notPlan of [undefined, null, "", "not json", 15, [], "[1]"]) expect(ugcPlanLengthSec(notPlan), String(notPlan)).toBeUndefined()
529
+ expect(ugcPlanLengthSec({ v: 1, targetDurationSec: UGC_SCRIPT_MIN_TARGET_SEC })).toBe(UGC_SCRIPT_MIN_TARGET_SEC)
530
+ expect(ugcPlanLengthSec({ v: 1, targetDurationSec: UGC_SCRIPT_MAX_TARGET_SEC })).toBe(UGC_SCRIPT_MAX_TARGET_SEC)
531
+ })
532
+ })
533
+
534
+ describe("ugcPlanScreenshotCount: the screenshot cards a saved plan was written with", () => {
535
+ // Placeholders: a beat's screenshot names an upload or an asset; only that it is there is read.
536
+ const shot = { url: "https://cdn.example/1.png" }
537
+ it("counts the beats that carry a screenshot, from the plan or its wire", async () => {
538
+ const { ugcPlanScreenshotCount } = await import("../ugc-node-wires.js")
539
+ const plan = { v: 1, hook: "h", beats: [{ line: "a", screenshot: shot }, { line: "b", screenshot: { asset_id: "x" } }, { line: "c", screenshot: shot }], closer: { line: "c" } }
540
+ expect(ugcPlanScreenshotCount(plan)).toBe(3)
541
+ expect(ugcPlanScreenshotCount(JSON.stringify(plan))).toBe(3)
542
+ })
543
+ it("a plan whose beats carry none is a talking-head plan: 0", async () => {
544
+ const { ugcPlanScreenshotCount } = await import("../ugc-node-wires.js")
545
+ expect(ugcPlanScreenshotCount({ v: 1, hook: "h", beats: [{ line: "a" }, { line: "b", screenshot: null }] })).toBe(0)
546
+ })
547
+ it("reads each beat on its own: a beat counts only when its screenshot is an object; a malformed or empty beat counts none and never makes the plan unreadable", async () => {
548
+ const { ugcPlanScreenshotCount } = await import("../ugc-node-wires.js")
549
+ expect(ugcPlanScreenshotCount({ v: 1, beats: [{ line: "a", screenshot: shot }, "b", null, 7, [shot]] })).toBe(1)
550
+ expect(ugcPlanScreenshotCount({ v: 1, beats: [{ line: "a", screenshot: "https://cdn.example/1.png" }, { line: "b", screenshot: shot }] })).toBe(1)
551
+ expect(ugcPlanScreenshotCount({ v: 1, beats: [{ line: "a", screenshot: false }, { line: "b", screenshot: [shot] }, { line: "c", screenshot: 1 }] })).toBe(0)
552
+ expect(ugcPlanScreenshotCount({ v: 1, beats: [] })).toBe(0)
553
+ })
554
+ it("is undefined only for a plan that cannot be read at all: no beats to read, or not a plan", async () => {
555
+ const { ugcPlanScreenshotCount } = await import("../ugc-node-wires.js")
556
+ expect(ugcPlanScreenshotCount({ v: 1, hook: "h" })).toBeUndefined()
557
+ expect(ugcPlanScreenshotCount({ v: 1, beats: "three" })).toBeUndefined()
558
+ for (const notPlan of [undefined, null, "", "not json", 15, [], "[1]"]) expect(ugcPlanScreenshotCount(notPlan), String(notPlan)).toBeUndefined()
559
+ })
560
+ })
561
+
562
+ describe("UGC_NODE_MESSAGES: every fixed sentence a UGC node fails with, by id", () => {
563
+ it("each id is the sentence its refusal answers", async () => {
564
+ const shared: Record<string, unknown> = await import("../index.js")
565
+ const { UGC_NODE_MESSAGES: M, UGC_SCRIPT_NEEDS_CHANGES } = await import("../ugc-node-wires.js")
566
+ expect(shared.UGC_NODE_MESSAGES).toBe(M)
567
+ expect(shared.UGC_SCRIPT_NEEDS_CHANGES).toBe(UGC_SCRIPT_NEEDS_CHANGES)
568
+ expect(Object.isFrozen(M)).toBe(true)
569
+
570
+ const CREATOR = JSON.stringify({ v: 1, gender: "man", identityImages: ["https://cdn.example/c.png"] })
571
+ const PLAN_OUT = JSON.stringify({ v: 1, plan: { hook: "h" }, transcribeArgs: {} })
572
+ const answers: Record<keyof typeof M, unknown> = {
573
+ notServed: ugcFailure(404, ""),
574
+ version: readUgcWire(JSON.stringify({ v: 2 })),
575
+ newerApp: ugcClipsOutputs({}),
576
+ pickGone: ugcCreatorPick(undefined, 0),
577
+ creatorMissing: ugcClipsBody({ planWire: JSON.stringify({ v: 1, hook: "h" }), creatorWire: undefined }),
578
+ minorAge: ugcFailure(422, JSON.stringify({ error: { code: "minor_age_refused", message: "m" } })),
579
+ needsGender: ugcCreatorBody({ data: { source: "sampled" }, category: "saas" }),
580
+ needsPhoto: ugcCreatorBody({ data: { source: "photo", gender: "man", keepResult: false } }),
581
+ needsCategory: ugcCreatorBody({ data: { source: "sampled", gender: "woman", keepResult: false } }),
582
+ needsSite: ugcScriptBody({ screenshots: [] }),
583
+ needsPlanOut: ugcCardsJobs({ planOutWire: JSON.stringify({ v: 1, hook: "a bare plan" }), videoUrl: "https://cdn.example/v.mp4", transcript: "a" }),
584
+ needsPlan: ugcClipsBody({ planWire: undefined, creatorWire: CREATOR }),
585
+ needsTicket: ugcClipBody({ ticketWire: undefined }),
586
+ needsVideo: ugcCardsJobs({ planOutWire: PLAN_OUT, transcript: "a" }),
587
+ needsTranscript: ugcCardsJobs({ planOutWire: PLAN_OUT, videoUrl: "https://cdn.example/v.mp4" }),
588
+ }
589
+ for (const [id, answer] of Object.entries(answers)) {
590
+ const said = typeof answer === "string" ? answer : (answer as { error?: unknown }).error
591
+ expect(said, id).toBe(M[id as keyof typeof M])
592
+ }
593
+ expect(new Set(Object.values(M)).size).toBe(Object.keys(M).length)
594
+ })
595
+
596
+ it("a refused script opens with UGC_SCRIPT_NEEDS_CHANGES, then the plugin's own words", async () => {
597
+ const { UGC_SCRIPT_NEEDS_CHANGES } = await import("../ugc-node-wires.js")
598
+ expect(ugcClipsOutputs({ errors: [{ message: "Too long.", fix: "Trim it." }] })).toEqual({ error: `${UGC_SCRIPT_NEEDS_CHANGES} Too long. Trim it.` })
599
+ })
600
+ })