@nodaro/shared 3.13.0 → 3.16.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 (142) hide show
  1. package/dist/index.cjs +1293 -55
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +1502 -30
  4. package/dist/index.d.ts +1502 -30
  5. package/dist/index.js +1134 -56
  6. package/dist/index.js.map +1 -1
  7. package/package.json +1 -1
  8. package/src/__tests__/camera-switch-contract.test.ts +98 -0
  9. package/src/__tests__/competitors.test.ts +49 -0
  10. package/src/__tests__/content-recipe-ideas.test.ts +96 -0
  11. package/src/__tests__/edl-multicam.test.ts +192 -0
  12. package/src/__tests__/llm-models.test.ts +5 -2
  13. package/src/__tests__/music-provider.test.ts +17 -0
  14. package/src/__tests__/node-runtime-keys.test.ts +10 -0
  15. package/src/__tests__/parameter-node-value.test.ts +2 -1
  16. package/src/__tests__/per-unit-video-pricing.test.ts +97 -0
  17. package/src/__tests__/producer-types.test.ts +35 -0
  18. package/src/__tests__/saved-posts.test.ts +37 -0
  19. package/src/__tests__/script-settings.test.ts +61 -0
  20. package/src/__tests__/settings-input.test.ts +252 -0
  21. package/src/__tests__/social-search.test.ts +243 -0
  22. package/src/__tests__/studio-take-voice.test.ts +200 -0
  23. package/src/__tests__/studio-transient.test.ts +37 -0
  24. package/src/__tests__/sub-gates.test.ts +21 -0
  25. package/src/__tests__/telegram-account-trigger.test.ts +120 -0
  26. package/src/__tests__/video-analysis-pricing.test.ts +27 -13
  27. package/src/__tests__/video-link.test.ts +2 -2
  28. package/src/__tests__/video-utils.test.ts +89 -83
  29. package/src/__tests__/workflow-export-strip.test.ts +37 -0
  30. package/src/camera-switch-contract.ts +166 -0
  31. package/src/catalog-projection.ts +27 -0
  32. package/src/competitors.ts +430 -0
  33. package/src/content-recipe-ideas.ts +69 -0
  34. package/src/credit-estimators/index.ts +14 -0
  35. package/src/credit-estimators/ltx-extend.ts +33 -0
  36. package/src/credit-estimators/ltx-retake.ts +30 -0
  37. package/src/credit-estimators/video-sfx.ts +41 -0
  38. package/src/credit-estimators/video-utils.ts +38 -24
  39. package/src/credit-identifiers.ts +10 -0
  40. package/src/edl-multicam.ts +220 -0
  41. package/src/fan-out-rows.ts +7 -2
  42. package/src/i18n/action-fx.ko.ts +18 -18
  43. package/src/i18n/action-fx.pt-BR.ts +66 -66
  44. package/src/i18n/aesthetic.ko.ts +49 -49
  45. package/src/i18n/aesthetic.pt-BR.ts +14 -14
  46. package/src/i18n/animals.ko.ts +126 -126
  47. package/src/i18n/animals.pt-BR.ts +33 -33
  48. package/src/i18n/atmosphere.ko.ts +37 -37
  49. package/src/i18n/atmosphere.pt-BR.ts +29 -29
  50. package/src/i18n/backdrop.ko.ts +40 -40
  51. package/src/i18n/backdrop.pt-BR.ts +38 -38
  52. package/src/i18n/camera-format.ko.ts +31 -31
  53. package/src/i18n/camera-format.pt-BR.ts +12 -12
  54. package/src/i18n/camera-motions.ko.ts +66 -66
  55. package/src/i18n/camera-motions.pt-BR.ts +51 -51
  56. package/src/i18n/character-fx.ko.ts +19 -19
  57. package/src/i18n/character-fx.pt-BR.ts +64 -52
  58. package/src/i18n/character-motion.ko.ts +164 -164
  59. package/src/i18n/character-motion.pt-BR.ts +867 -858
  60. package/src/i18n/color-look.ko.ts +41 -41
  61. package/src/i18n/color-look.pt-BR.ts +23 -23
  62. package/src/i18n/composition-effects.ko.ts +18 -18
  63. package/src/i18n/composition-effects.pt-BR.ts +17 -17
  64. package/src/i18n/era.ko.ts +28 -28
  65. package/src/i18n/era.pt-BR.ts +20 -20
  66. package/src/i18n/exposure-settings.ko.ts +20 -20
  67. package/src/i18n/exposure-settings.pt-BR.ts +3 -3
  68. package/src/i18n/framing.ko.ts +66 -66
  69. package/src/i18n/framing.pt-BR.ts +50 -50
  70. package/src/i18n/furniture.ko.ts +78 -78
  71. package/src/i18n/furniture.pt-BR.ts +46 -46
  72. package/src/i18n/held-prop.ko.ts +60 -60
  73. package/src/i18n/held-prop.pt-BR.ts +30 -30
  74. package/src/i18n/instrumentation.ko.ts +62 -62
  75. package/src/i18n/instrumentation.pt-BR.ts +64 -64
  76. package/src/i18n/lens.ko.ts +16 -16
  77. package/src/i18n/lens.pt-BR.ts +5 -5
  78. package/src/i18n/lighting.ko.ts +68 -68
  79. package/src/i18n/lighting.pt-BR.ts +43 -43
  80. package/src/i18n/loop-subject.ko.ts +1 -1
  81. package/src/i18n/loop-subject.pt-BR.ts +31 -31
  82. package/src/i18n/materials.ko.ts +66 -66
  83. package/src/i18n/materials.pt-BR.ts +22 -22
  84. package/src/i18n/mood.ko.ts +50 -50
  85. package/src/i18n/mood.pt-BR.ts +12 -12
  86. package/src/i18n/music-genre.ko.ts +28 -28
  87. package/src/i18n/music-genre.pt-BR.ts +50 -50
  88. package/src/i18n/music-mood.ko.ts +27 -27
  89. package/src/i18n/music-mood.pt-BR.ts +20 -20
  90. package/src/i18n/person.ko.ts +396 -396
  91. package/src/i18n/person.pt-BR.ts +237 -237
  92. package/src/i18n/photo-genre.ko.ts +46 -46
  93. package/src/i18n/photo-genre.pt-BR.ts +32 -32
  94. package/src/i18n/photographer.ko.ts +63 -63
  95. package/src/i18n/photographer.pt-BR.ts +15 -15
  96. package/src/i18n/pose.ko.ts +81 -81
  97. package/src/i18n/pose.pt-BR.ts +65 -65
  98. package/src/i18n/post-process-effects.ko.ts +18 -18
  99. package/src/i18n/post-process-effects.pt-BR.ts +18 -18
  100. package/src/i18n/render-quality.ko.ts +24 -24
  101. package/src/i18n/render-quality.pt-BR.ts +12 -12
  102. package/src/i18n/setting.ko.ts +64 -64
  103. package/src/i18n/setting.pt-BR.ts +41 -41
  104. package/src/i18n/style.ko.ts +49 -49
  105. package/src/i18n/style.pt-BR.ts +19 -19
  106. package/src/i18n/styling.ko.ts +265 -265
  107. package/src/i18n/styling.pt-BR.ts +141 -141
  108. package/src/i18n/temporal.ko.ts +18 -18
  109. package/src/i18n/temporal.pt-BR.ts +12 -12
  110. package/src/i18n/transitions.ko.ts +14 -14
  111. package/src/i18n/transitions.pt-BR.ts +83 -71
  112. package/src/i18n/vehicles.ko.ts +107 -107
  113. package/src/i18n/vehicles.pt-BR.ts +55 -55
  114. package/src/i18n/voice-character.ko.ts +19 -19
  115. package/src/i18n/voice-character.pt-BR.ts +19 -19
  116. package/src/i18n/voice-delivery.ko.ts +22 -22
  117. package/src/i18n/voice-delivery.pt-BR.ts +22 -22
  118. package/src/i18n/weapons.ko.ts +85 -85
  119. package/src/i18n/weapons.pt-BR.ts +46 -46
  120. package/src/index.ts +202 -1
  121. package/src/llm-models.ts +11 -0
  122. package/src/model-catalog.ts +30 -14
  123. package/src/model-constants.ts +28 -0
  124. package/src/node-mappable-fields.ts +21 -5
  125. package/src/node-runtime-keys.ts +33 -0
  126. package/src/oauth-scopes.ts +28 -0
  127. package/src/parameter-node-value.ts +13 -5
  128. package/src/pipeline-defaults.ts +14 -0
  129. package/src/pipeline-state-types.ts +14 -0
  130. package/src/producer-types.ts +85 -0
  131. package/src/recast-segment-packs.ts +13 -0
  132. package/src/resolve-field-mappings.ts +15 -5
  133. package/src/saved-posts.ts +106 -0
  134. package/src/script-settings.ts +70 -0
  135. package/src/settings-input.ts +366 -0
  136. package/src/social-search.ts +467 -0
  137. package/src/studio-transient.ts +176 -5
  138. package/src/telegram-account-send.ts +32 -0
  139. package/src/telegram-account-trigger.ts +108 -0
  140. package/src/video-analysis-pricing.ts +17 -6
  141. package/src/video-link.ts +16 -4
  142. package/src/workflow-export.ts +7 -0
@@ -0,0 +1,467 @@
1
+ /**
2
+ * Social Search node — shared vocabulary, the post shape, credit identifiers,
3
+ * and the rule for which posts a run passes on.
4
+ *
5
+ * One node searches one platform (TikTok, Instagram, YouTube, X, Reddit,
6
+ * LinkedIn, Meta's Ad Library) by keyword or by account and returns up to 60
7
+ * posts in one shape. In the editor a person picks the posts to keep; a
8
+ * workflow run without picks passes on the first few. Everything the route
9
+ * reservation, the orchestrator, the editor, the SDK and the docs must agree
10
+ * on lives here.
11
+ *
12
+ * Why public: `SocialPost` is the node's output and the SDK's return type,
13
+ * and `SocialSearchParams` is the `/v1/social-search` request body. The search
14
+ * itself runs in a private plugin (Cloud only).
15
+ */
16
+
17
+ export const SOCIAL_SEARCH_NODE_TYPE = "social-search" as const
18
+
19
+ export const SOCIAL_PLATFORMS = ["tiktok", "instagram", "youtube", "x", "reddit", "linkedin", "meta_ads"] as const
20
+ export type SocialPlatform = (typeof SOCIAL_PLATFORMS)[number]
21
+
22
+ /** `account` is a creator, a LinkedIn company page or a Meta advertiser;
23
+ * `community` is a subreddit. */
24
+ export const SOCIAL_SEARCH_MODES = ["keyword", "account", "community"] as const
25
+ export type SocialSearchMode = (typeof SOCIAL_SEARCH_MODES)[number]
26
+
27
+ export const SOCIAL_SEARCH_PLATFORM_MODES: Readonly<Record<SocialPlatform, readonly SocialSearchMode[]>> = {
28
+ tiktok: ["keyword", "account"],
29
+ instagram: ["keyword", "account"],
30
+ youtube: ["keyword", "account"],
31
+ x: ["keyword", "account"],
32
+ reddit: ["keyword", "community"],
33
+ linkedin: ["keyword", "account"],
34
+ meta_ads: ["keyword", "account"],
35
+ }
36
+
37
+ export const SOCIAL_SEARCH_PERIODS = ["day", "week", "month", "year", "all"] as const
38
+ export type SocialSearchPeriod = (typeof SOCIAL_SEARCH_PERIODS)[number]
39
+
40
+ export const SOCIAL_SEARCH_SORTS = ["relevance", "popular", "newest"] as const
41
+ export type SocialSearchSort = (typeof SOCIAL_SEARCH_SORTS)[number]
42
+
43
+ /** Results per search: one page of the platform per 20 posts. */
44
+ export const SOCIAL_SEARCH_COUNTS = [20, 40, 60] as const
45
+ export type SocialSearchCount = (typeof SOCIAL_SEARCH_COUNTS)[number]
46
+
47
+ /**
48
+ * The searches that can fetch more than one page. Every other one (an
49
+ * account's latest posts on TikTok, Instagram, YouTube or LinkedIn, a YouTube
50
+ * keyword search, a Reddit keyword search) returns one page however many
51
+ * results are asked for, so it is capped at 20 — and billed for one page. The
52
+ * plugin applies the same table to what it fetches and reserves.
53
+ */
54
+ export const SOCIAL_SEARCH_PAGED_MODES: Readonly<Record<SocialPlatform, readonly SocialSearchMode[]>> = {
55
+ tiktok: ["keyword"],
56
+ instagram: ["keyword"],
57
+ youtube: [],
58
+ x: ["keyword", "account"],
59
+ reddit: ["community"],
60
+ linkedin: ["keyword"],
61
+ meta_ads: ["keyword", "account"],
62
+ }
63
+
64
+ /** The most results this platform and mode can return in one search. */
65
+ export function socialSearchMaxCount(platform: SocialPlatform, mode: SocialSearchMode): SocialSearchCount {
66
+ return SOCIAL_SEARCH_PAGED_MODES[platform].includes(mode) ? 60 : 20
67
+ }
68
+
69
+ export const SOCIAL_SEARCH_VIDEO_KINDS = ["all", "videos", "shorts"] as const
70
+ export type SocialSearchVideoKind = (typeof SOCIAL_SEARCH_VIDEO_KINDS)[number]
71
+
72
+ /** How many posts a run passes on when nobody picked: the first five. */
73
+ export const SOCIAL_SEARCH_DEFAULT_PICK_TOP = 5
74
+ export const SOCIAL_SEARCH_MAX_QUERY_LENGTH = 300
75
+
76
+ // ── The post ───────────────────────────────────────────────────────────────
77
+
78
+ export interface SocialPostAuthor {
79
+ readonly handle: string
80
+ readonly name: string
81
+ readonly avatarUrl?: string
82
+ readonly followers?: number
83
+ readonly verified?: boolean
84
+ readonly url?: string
85
+ }
86
+
87
+ /** Absent means the platform did not report it, never zero. */
88
+ export interface SocialPostMetrics {
89
+ readonly views?: number
90
+ readonly likes?: number
91
+ readonly comments?: number
92
+ readonly shares?: number
93
+ readonly saves?: number
94
+ /** Reddit's vote score. */
95
+ readonly score?: number
96
+ }
97
+
98
+ export interface SocialPostMedia {
99
+ readonly kind: "video" | "image" | "text"
100
+ /** The platform's own still. Signed links expire within days. */
101
+ readonly thumbnailUrl?: string
102
+ /** A direct video file when the platform hands one out. Also short-lived. */
103
+ readonly videoUrl?: string
104
+ readonly durationSec?: number
105
+ readonly aspect?: "9:16" | "16:9" | "1:1"
106
+ }
107
+
108
+ export interface SocialPost {
109
+ /** `<platform>:<the platform's own id>`, stable across searches. */
110
+ readonly id: string
111
+ readonly platform: SocialPlatform
112
+ /** The post's page. */
113
+ readonly url: string
114
+ readonly title?: string
115
+ readonly text: string
116
+ readonly author: SocialPostAuthor
117
+ /** Where it was posted: `r/<subreddit>`, a channel, a company page, an advertiser. */
118
+ readonly container?: string
119
+ /** ISO 8601, UTC. */
120
+ readonly publishedAt?: string
121
+ readonly metrics: SocialPostMetrics
122
+ readonly media: SocialPostMedia
123
+ readonly hashtags: readonly string[]
124
+ /** Platform-specific facts: a TikTok `sound`, an ad's `active` / `endedAt` /
125
+ * `variants` / `cta`, a Reddit `subreddit`, an X `reply` flag. */
126
+ readonly extra: Readonly<Record<string, unknown>>
127
+ }
128
+
129
+ function isRecord(value: unknown): value is Record<string, unknown> {
130
+ return typeof value === "object" && value !== null && !Array.isArray(value)
131
+ }
132
+
133
+ /** Every field the card, the digest and the picker read, with its type. A
134
+ * saved post that fails this is skipped, never rendered half-broken. */
135
+ export function isSocialPost(value: unknown): value is SocialPost {
136
+ if (!isRecord(value)) return false
137
+ return (
138
+ typeof value.id === "string" &&
139
+ typeof value.url === "string" &&
140
+ typeof value.text === "string" &&
141
+ typeof value.platform === "string" &&
142
+ (SOCIAL_PLATFORMS as readonly string[]).includes(value.platform) &&
143
+ isRecord(value.author) &&
144
+ typeof value.author.handle === "string" &&
145
+ typeof value.author.name === "string" &&
146
+ isRecord(value.metrics) &&
147
+ isRecord(value.media) &&
148
+ Array.isArray(value.hashtags) &&
149
+ isRecord(value.extra)
150
+ )
151
+ }
152
+
153
+ /** The posts in an unknown value (a job's output, a node's saved data). */
154
+ export function socialPostsFrom(value: unknown): SocialPost[] {
155
+ return Array.isArray(value) ? value.filter(isSocialPost) : []
156
+ }
157
+
158
+ // ── The request ────────────────────────────────────────────────────────────
159
+
160
+ /** The body of `POST /v1/social-search` (and `nodes.run("social-search", …)`).
161
+ * A type alias, not an interface, so it is assignable to a plain record (the
162
+ * SDK's generic `run` body). */
163
+ export type SocialSearchParams = {
164
+ readonly platform: SocialPlatform
165
+ /** Default `keyword`. */
166
+ readonly mode?: SocialSearchMode
167
+ /** A keyword, or an account: a handle, a profile link, a subreddit, a
168
+ * LinkedIn company page, a Meta advertiser's name or page id. */
169
+ readonly query: string
170
+ /** 20, 40 or 60 results. Default 20. */
171
+ readonly count?: SocialSearchCount
172
+ /** Default `month`. */
173
+ readonly period?: SocialSearchPeriod
174
+ /** Default `relevance` (the platform's own order). */
175
+ readonly sort?: SocialSearchSort
176
+ /** TikTok keyword search: a two-letter region. */
177
+ readonly region?: string
178
+ /** Meta ads: a two-letter country, or `ALL`. */
179
+ readonly country?: string
180
+ /** Meta ads: only ads that are running now. Default true. */
181
+ readonly activeOnly?: boolean
182
+ /** Reddit keyword search inside one subreddit. */
183
+ readonly subreddit?: string
184
+ /** YouTube: long videos, Shorts, or both. Default `all`. */
185
+ readonly videoKind?: SocialSearchVideoKind
186
+ }
187
+
188
+ function oneOf<T extends string>(list: readonly T[], value: unknown, fallback: T): T {
189
+ return typeof value === "string" && (list as readonly string[]).includes(value) ? (value as T) : fallback
190
+ }
191
+
192
+ export function socialSearchPlatform(value: unknown): SocialPlatform {
193
+ return oneOf(SOCIAL_PLATFORMS, value, "tiktok")
194
+ }
195
+
196
+ /** The mode, or the platform's first one when the stored mode does not apply
197
+ * (a node switched from Reddit "community" to TikTok). */
198
+ export function socialSearchMode(platform: SocialPlatform, value: unknown): SocialSearchMode {
199
+ const allowed = SOCIAL_SEARCH_PLATFORM_MODES[platform]
200
+ return oneOf(allowed, value, allowed[0]!)
201
+ }
202
+
203
+ export function socialSearchCount(value: unknown): SocialSearchCount {
204
+ return value === 60 ? 60 : value === 40 ? 40 : 20
205
+ }
206
+
207
+ export function socialSearchPages(count: SocialSearchCount): 1 | 2 | 3 {
208
+ return count === 60 ? 3 : count === 40 ? 2 : 1
209
+ }
210
+
211
+ function cleanText(value: unknown, max: number): string | undefined {
212
+ return typeof value === "string" && value.trim() ? value.trim().slice(0, max) : undefined
213
+ }
214
+
215
+ /** The count a search really runs at: the asked count, capped for a search
216
+ * that returns one page (`socialSearchMaxCount`). */
217
+ export function socialSearchEffectiveCount(platform: SocialPlatform, mode: SocialSearchMode, value: unknown): SocialSearchCount {
218
+ const asked = socialSearchCount(value)
219
+ const max = socialSearchMaxCount(platform, mode)
220
+ return asked > max ? max : asked
221
+ }
222
+
223
+ /** A two-letter region (TikTok), upper-cased, or undefined. */
224
+ export function socialSearchRegion(value: unknown): string | undefined {
225
+ const text = typeof value === "string" ? value.trim().toUpperCase() : ""
226
+ return /^[A-Z]{2}$/.test(text) ? text : undefined
227
+ }
228
+
229
+ /** A two-letter country or ALL (Meta ads), upper-cased; anything else is ALL. */
230
+ export function socialSearchCountry(value: unknown): string {
231
+ const text = typeof value === "string" ? value.trim().toUpperCase() : ""
232
+ return /^([A-Z]{2}|ALL)$/.test(text) ? text : "ALL"
233
+ }
234
+
235
+ /**
236
+ * The request a Social Search node sends — the ONE builder the editor's run
237
+ * and the workflow orchestrator share. `query` is the wired text when there is
238
+ * one (a Text node, a List item), else the node's own field.
239
+ */
240
+ export function socialSearchRequestFromNode(
241
+ data: Readonly<Record<string, unknown>>,
242
+ wiredQuery?: string,
243
+ ): SocialSearchParams {
244
+ const platform = socialSearchPlatform(data.platform)
245
+ const mode = socialSearchMode(platform, data.mode)
246
+ const query = cleanText(wiredQuery, SOCIAL_SEARCH_MAX_QUERY_LENGTH) ?? cleanText(data.query, SOCIAL_SEARCH_MAX_QUERY_LENGTH) ?? ""
247
+ const region = socialSearchRegion(data.region)
248
+ const country = socialSearchCountry(data.country)
249
+ const subreddit = cleanText(data.subreddit, 100)
250
+ return {
251
+ platform,
252
+ mode,
253
+ query,
254
+ count: socialSearchEffectiveCount(platform, mode, data.count),
255
+ period: oneOf(SOCIAL_SEARCH_PERIODS, data.period, "month"),
256
+ sort: oneOf(SOCIAL_SEARCH_SORTS, data.sort, "relevance"),
257
+ ...(platform === "tiktok" && mode === "keyword" && region ? { region } : {}),
258
+ ...(platform === "meta_ads" ? { country, activeOnly: data.activeOnly !== false } : {}),
259
+ ...(platform === "reddit" && mode === "keyword" && subreddit ? { subreddit } : {}),
260
+ ...(platform === "youtube" ? { videoKind: oneOf(SOCIAL_SEARCH_VIDEO_KINDS, data.videoKind, "all") } : {}),
261
+ }
262
+ }
263
+
264
+ /**
265
+ * The page link of a Social Search post, read from the node's `json` output
266
+ * as a wire hands it on: one post (a wire in Each mode) or the list of posts
267
+ * (any other wire: the first). Undefined when the output holds no post with
268
+ * an http(s) link.
269
+ */
270
+ export function socialSearchPostLink(output: string): string | undefined {
271
+ let parsed: unknown
272
+ try {
273
+ parsed = JSON.parse(output)
274
+ } catch {
275
+ return undefined
276
+ }
277
+ const post = Array.isArray(parsed) ? parsed[0] : parsed
278
+ const url = typeof post === "object" && post !== null ? (post as { url?: unknown }).url : undefined
279
+ return httpLink(url)
280
+ }
281
+
282
+ function httpLink(value: unknown): string | undefined {
283
+ const link = typeof value === "string" ? value.trim() : ""
284
+ return /^https?:\/\/\S+$/i.test(link) ? link : undefined
285
+ }
286
+
287
+ // ── A post's video, for Video Analysis ─────────────────────────────────────
288
+
289
+ /**
290
+ * A signed link counts as expired this long before its stated end, so it
291
+ * still answers when the run reads it: the length check, then the download.
292
+ */
293
+ export const SOCIAL_POST_VIDEO_LINK_MARGIN_MS = 60 * 60 * 1000
294
+
295
+ /**
296
+ * When a platform's signed media link stops working, in epoch milliseconds,
297
+ * if the link says: `oe` (hex seconds: Instagram, Facebook and ad videos),
298
+ * `x-expires` (TikTok), `Expires` (S3, CloudFront), `e` (LinkedIn). Undefined
299
+ * for a link that names no end (an X video's link does not expire).
300
+ */
301
+ export function signedLinkExpiresAt(link: string): number | undefined {
302
+ let url: URL
303
+ try {
304
+ url = new URL(link)
305
+ } catch {
306
+ return undefined
307
+ }
308
+ const params = url.searchParams
309
+ const oe = params.get("oe")
310
+ if (oe !== null && /^[0-9a-f]{6,10}$/i.test(oe)) return parseInt(oe, 16) * 1000
311
+ const linkedin = /(^|\.)licdn\.com$/i.test(url.hostname)
312
+ const seconds = params.get("x-expires") ?? params.get("Expires") ?? params.get("expires") ?? (linkedin ? params.get("e") : null)
313
+ return seconds !== null && /^\d{9,11}$/.test(seconds) ? Number(seconds) * 1000 : undefined
314
+ }
315
+
316
+ /**
317
+ * A post's video link when it is a FILE the analysis can download whole; a
318
+ * streaming playlist (an HLS `.m3u8`, which some LinkedIn videos are) is not
319
+ * one, so the post is read by its page instead.
320
+ */
321
+ function videoFileLink(value: unknown): string | undefined {
322
+ const link = httpLink(value)
323
+ if (!link) return undefined
324
+ try {
325
+ return /\.m3u8$/i.test(new URL(link).pathname) ? undefined : link
326
+ } catch {
327
+ return undefined
328
+ }
329
+ }
330
+
331
+ /** What a Social Search post hands Video Analysis. */
332
+ export type SocialSearchPostVideo =
333
+ /** The post's own video file, while the platform's signed link is valid. */
334
+ | { readonly kind: "file"; readonly url: string }
335
+ /** No file came with the post (TikTok, YouTube): its page, which the analysis fetches. */
336
+ | { readonly kind: "page"; readonly url: string }
337
+ /** The file's signed link has expired: the search has to run again. */
338
+ | { readonly kind: "expired" }
339
+ /** The post is an image or a text post: there is no video to analyze. */
340
+ | { readonly kind: "none" }
341
+
342
+ /**
343
+ * The video Video Analysis reads from a Social Search node's `json` output,
344
+ * as a wire hands it on: one post (a wire in Each mode) or the list (any
345
+ * other wire: the first post). A post that came with its own video file is
346
+ * analyzed from that file, so the platform's page is never read: Instagram's
347
+ * page does not say how long the video is, and a video without a length
348
+ * cannot be priced. A file whose signed link has expired is reported as such
349
+ * rather than swapped for the page. Undefined when the output holds no post.
350
+ * Both engines read it (input-resolver / node-input-resolver).
351
+ */
352
+ export function socialSearchPostVideo(output: string, now: number = Date.now()): SocialSearchPostVideo | undefined {
353
+ let parsed: unknown
354
+ try {
355
+ parsed = JSON.parse(output)
356
+ } catch {
357
+ return undefined
358
+ }
359
+ const post = Array.isArray(parsed) ? socialPostsFrom(parsed)[0] : isSocialPost(parsed) ? parsed : undefined
360
+ if (!post) return undefined
361
+ if (post.media.kind !== "video") return { kind: "none" }
362
+ const file = videoFileLink(post.media.videoUrl)
363
+ if (file) {
364
+ const end = signedLinkExpiresAt(file)
365
+ return end !== undefined && end - SOCIAL_POST_VIDEO_LINK_MARGIN_MS <= now ? { kind: "expired" } : { kind: "file", url: file }
366
+ }
367
+ const page = httpLink(post.url)
368
+ return page ? { kind: "page", url: page } : undefined
369
+ }
370
+
371
+ /**
372
+ * The longest video among the posts, in seconds: what Video Analysis quotes
373
+ * for each post a Social Search wire hands it (each post is charged by its
374
+ * own length when it runs, so the quote is never lower than the charge).
375
+ * Posts without a video are left out: Video Analysis refuses them without a
376
+ * charge. Undefined when no post has a video, or one of them does not say
377
+ * how long it is (the ceiling quotes it).
378
+ */
379
+ export function socialPostsLongestVideoSec(posts: readonly SocialPost[]): number | undefined {
380
+ const lengths = posts.filter((p) => p.media.kind === "video").map((p) => p.media.durationSec)
381
+ if (lengths.length === 0) return undefined
382
+ return lengths.every((d): d is number => typeof d === "number" && Number.isFinite(d) && d > 0)
383
+ ? Math.max(...lengths)
384
+ : undefined
385
+ }
386
+
387
+ // ── Pricing ────────────────────────────────────────────────────────────────
388
+
389
+ /**
390
+ * Credits for one page of results (up to 20 posts), set by the owner: 20 /
391
+ * 40 / 60 results cost 20 / 40 / 60 credits on every platform. The
392
+ * `model_pricing` rows seed the same values. A run is charged by the results
393
+ * it asks for (pages), never by the platform.
394
+ */
395
+ export const SOCIAL_SEARCH_CREDITS_PER_PAGE = 20
396
+
397
+ export function socialSearchCreditId(count: SocialSearchCount): string {
398
+ return `${SOCIAL_SEARCH_NODE_TYPE}:${socialSearchPages(count)}`
399
+ }
400
+
401
+ export function socialSearchCreditIdFromNode(data: Readonly<Record<string, unknown>>): string {
402
+ const platform = socialSearchPlatform(data.platform)
403
+ return socialSearchCreditId(socialSearchEffectiveCount(platform, socialSearchMode(platform, data.mode), data.count))
404
+ }
405
+
406
+ /** Every id a search can reserve, plus the bare id (the node's headline price). */
407
+ export const SOCIAL_SEARCH_CREDIT_COSTS: Readonly<Record<string, number>> = Object.fromEntries([
408
+ [SOCIAL_SEARCH_NODE_TYPE, SOCIAL_SEARCH_CREDITS_PER_PAGE],
409
+ ...SOCIAL_SEARCH_COUNTS.map((count) => [socialSearchCreditId(count), SOCIAL_SEARCH_CREDITS_PER_PAGE * socialSearchPages(count)] as const),
410
+ ])
411
+
412
+ // ── Which posts a run passes on ────────────────────────────────────────────
413
+
414
+ export function socialSearchPickTop(value: unknown): number {
415
+ const n = typeof value === "number" && Number.isFinite(value) ? Math.round(value) : SOCIAL_SEARCH_DEFAULT_PICK_TOP
416
+ return Math.min(60, Math.max(1, n))
417
+ }
418
+
419
+ /**
420
+ * The posts passed on: the ones a person picked, in the order they picked
421
+ * them, when any of them is among the results; otherwise the first `pickTop`.
422
+ * Picks belong to the search a person picked from: a NEW search (the editor's
423
+ * run, a workflow run) starts with none, so it passes on the first `pickTop`
424
+ * — the same in both engines. Keeping picks means not searching again
425
+ * (`isSocialSearchPickFrozen`).
426
+ */
427
+ export function pickSocialPosts(
428
+ results: readonly SocialPost[],
429
+ pickedIds: readonly string[] | undefined,
430
+ pickTop: unknown,
431
+ ): SocialPost[] {
432
+ const byId = new Map(results.map((p) => [p.id, p]))
433
+ const picked = (pickedIds ?? []).map((id) => byId.get(id)).filter((p): p is SocialPost => p !== undefined)
434
+ return picked.length > 0 ? picked : results.slice(0, socialSearchPickTop(pickTop))
435
+ }
436
+
437
+ /**
438
+ * "Keep my picks": a node whose author picked posts and chose to keep them
439
+ * does not search again on a workflow run — it passes its picks on, like a
440
+ * frozen (skipped) node. Both engines treat it as skipped.
441
+ */
442
+ export function isSocialSearchPickFrozen(type: string | undefined, data: Readonly<Record<string, unknown>>): boolean {
443
+ return type === SOCIAL_SEARCH_NODE_TYPE && data.keepPicks === true && socialPostsFrom(data.generatedJson).length > 0
444
+ }
445
+
446
+ function metricLine(post: SocialPost): string {
447
+ const m = post.metrics
448
+ if (m.views !== undefined) return `${m.views} views`
449
+ if (m.score !== undefined) return `${m.score} points`
450
+ if (m.likes !== undefined) return `${m.likes} likes`
451
+ return ""
452
+ }
453
+
454
+ /** One post as a few plain lines: who, when, reach; the words; the link. */
455
+ export function socialPostDigestLine(post: SocialPost, index: number): string {
456
+ const who = post.author.handle ? `@${post.author.handle.replace(/^@/, "")}` : post.author.name || post.container || ""
457
+ const when = post.publishedAt ? post.publishedAt.slice(0, 10) : ""
458
+ const words = (post.title || post.text).replace(/\s+/g, " ").trim()
459
+ const snippet = words.length > 160 ? `${words.slice(0, 159)}…` : words
460
+ const head = `${index + 1}. ${[who, when, metricLine(post)].filter(Boolean).join(" · ")}`
461
+ return [head, snippet, post.url].filter(Boolean).join("\n ")
462
+ }
463
+
464
+ /** The posts as text, for nodes that read text (a prompt, a writer). */
465
+ export function socialPostsDigest(posts: readonly SocialPost[]): string {
466
+ return posts.map(socialPostDigestLine).join("\n\n")
467
+ }