@zerodot/post-bridge 0.0.0-stage → 1.0.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/index.cjs ADDED
@@ -0,0 +1,1087 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let zod = require("zod");
3
+ let _zerodot_node_sdk = require("@zerodot/node-sdk");
4
+ // src/api.ts
5
+ const POST_BRIDGE_CREDENTIAL = "post-bridge.api";
6
+ const POST_BRIDGE_API = "https://api.post-bridge.com";
7
+ /** The most items that "return all" collects. A node output has a size limit too. */
8
+ const MAX_ITEMS = 5e3;
9
+ /** The number of items to ask for in one page. */
10
+ const PAGE_SIZE = 100;
11
+ const text = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
12
+ /** Check the API address of the credential. */
13
+ function normalizeBaseUrl(raw) {
14
+ const value = text(raw);
15
+ if (!value) return POST_BRIDGE_API;
16
+ let parsed;
17
+ try {
18
+ parsed = new URL(value);
19
+ } catch {
20
+ throw new Error("The Post Bridge credential \"baseUrl\" is not a valid URL");
21
+ }
22
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error("The Post Bridge credential \"baseUrl\" must use http or https");
23
+ return parsed.toString().replace(/\/+$/, "");
24
+ }
25
+ /** The API key and the API address of a Post Bridge credential. */
26
+ function postBridgeAccess(credential) {
27
+ if (!credential || credential.type !== "post-bridge.api") throw new Error("The node needs a Post Bridge credential");
28
+ const apiKey = text(credential.data.apiKey);
29
+ if (!apiKey) throw new Error("The credential has no \"apiKey\"");
30
+ return {
31
+ apiKey,
32
+ baseUrl: normalizeBaseUrl(credential.data.baseUrl)
33
+ };
34
+ }
35
+ /** An error from Post Bridge. `status` is the HTTP status code. */
36
+ var PostBridgeError = class extends Error {
37
+ status;
38
+ constructor(message, status) {
39
+ super(message);
40
+ this.name = "PostBridgeError";
41
+ this.status = status;
42
+ }
43
+ };
44
+ const HINTS = {
45
+ 400: "Post Bridge did not accept the request",
46
+ 401: "Post Bridge did not accept the API key",
47
+ 402: "The plan limit for connected accounts is reached",
48
+ 403: "The API key cannot do this call",
49
+ 404: "Post Bridge did not find the item",
50
+ 429: "The rate limit is reached. Try again later",
51
+ 500: "Post Bridge had a server error. Try again later"
52
+ };
53
+ function detailOf(answer) {
54
+ if (!(0, _zerodot_node_sdk.isRecord)(answer)) return void 0;
55
+ for (const key of [
56
+ "error",
57
+ "message",
58
+ "detail"
59
+ ]) {
60
+ const value = answer[key];
61
+ if (typeof value === "string" && value.trim() !== "") return value.trim();
62
+ if (Array.isArray(value)) {
63
+ const lines = value.filter((line) => typeof line === "string");
64
+ if (lines.length > 0) return lines.join("; ");
65
+ }
66
+ }
67
+ }
68
+ /** The error for a failed call. The text never has the API key. */
69
+ function postBridgeErrorOf(label, status, answer) {
70
+ const parts = [`Post Bridge ${label} failed (${status})`];
71
+ const detail = detailOf(answer);
72
+ if (detail) parts.push(detail);
73
+ const hint = HINTS[status];
74
+ if (hint) parts.push(hint);
75
+ return new PostBridgeError(parts.join(". "), status);
76
+ }
77
+ function urlFor(access, request) {
78
+ const url = new URL(`${access.baseUrl}${request.path}`);
79
+ for (const [key, value] of Object.entries(request.query ?? {})) {
80
+ if (value === void 0 || value === "") continue;
81
+ if (typeof value === "object") for (const item of value) url.searchParams.append(key, item);
82
+ else url.searchParams.set(key, String(value));
83
+ }
84
+ return url;
85
+ }
86
+ /** One call to the Post Bridge API. */
87
+ async function callPostBridge(access, request, options) {
88
+ const response = await fetch(urlFor(access, request), {
89
+ method: request.method,
90
+ headers: {
91
+ accept: "application/json",
92
+ authorization: `Bearer ${access.apiKey}`,
93
+ ...request.body ? { "content-type": "application/json" } : {}
94
+ },
95
+ body: request.body ? JSON.stringify(request.body) : void 0,
96
+ redirect: "error",
97
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)])
98
+ });
99
+ const raw = await response.text();
100
+ let answer = {};
101
+ if (raw !== "") try {
102
+ answer = JSON.parse(raw);
103
+ } catch {
104
+ answer = null;
105
+ }
106
+ if (!response.ok) throw postBridgeErrorOf(`${request.method} ${request.path}`, response.status, answer);
107
+ return answer ?? {};
108
+ }
109
+ /**
110
+ * A list. Post Bridge answers with `{ data, meta: { total, offset, limit, next } }`. This follows
111
+ * the pages until it has `limit` items, or all items when `limit` is null.
112
+ */
113
+ async function callPostBridgeList(access, request, limit, options) {
114
+ const wanted = Math.min(limit ?? 5e3, MAX_ITEMS);
115
+ const items = [];
116
+ while (items.length < wanted) {
117
+ const page = await callPostBridge(access, {
118
+ ...request,
119
+ query: {
120
+ ...request.query,
121
+ offset: items.length,
122
+ limit: Math.min(PAGE_SIZE, wanted - items.length)
123
+ }
124
+ }, options);
125
+ if (!(0, _zerodot_node_sdk.isRecord)(page) || !Array.isArray(page.data) || page.data.length === 0) break;
126
+ items.push(...page.data);
127
+ const meta = (0, _zerodot_node_sdk.isRecord)(page.meta) ? page.meta : {};
128
+ const total = typeof meta.total === "number" ? meta.total : void 0;
129
+ if (!(meta.next !== null && meta.next !== void 0) && (total === void 0 || items.length >= total)) break;
130
+ }
131
+ return items.slice(0, wanted);
132
+ }
133
+ /** Read the answer of the call that makes an upload URL. */
134
+ function uploadTargetOf(answer) {
135
+ if (!(0, _zerodot_node_sdk.isRecord)(answer) || typeof answer.media_id !== "string" || typeof answer.upload_url !== "string") throw new Error("Post Bridge did not give a media ID and an upload URL");
136
+ return {
137
+ mediaId: answer.media_id,
138
+ uploadUrl: answer.upload_url,
139
+ name: typeof answer.name === "string" ? answer.name : ""
140
+ };
141
+ }
142
+ /** Send the bytes to the signed upload URL. This call has no API key. */
143
+ async function putMedia(uploadUrl, bytes, mimeType, options) {
144
+ const response = await fetch(uploadUrl, {
145
+ method: "PUT",
146
+ headers: { "content-type": mimeType },
147
+ body: new Blob([Uint8Array.from(bytes)], { type: mimeType }),
148
+ redirect: "error",
149
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)])
150
+ });
151
+ if (!response.ok) throw new PostBridgeError(`The media upload failed (${response.status})`, response.status);
152
+ }
153
+ // src/icon.ts
154
+ const POST_BRIDGE_ICON = (0, _zerodot_node_sdk.fileIcon)(require("url").pathToFileURL(__filename).href, "../post-bridge.svg");
155
+ // src/credential.ts
156
+ const TIMEOUT_MS = 1e4;
157
+ const postBridgeCredential = {
158
+ type: POST_BRIDGE_CREDENTIAL,
159
+ label: "Post Bridge API",
160
+ fields: zod.z.object({
161
+ apiKey: zod.z.string().min(1).meta({
162
+ title: "API Key",
163
+ description: "The API key from your Post Bridge account"
164
+ }),
165
+ baseUrl: zod.z.string().optional().meta({
166
+ title: "Base URL",
167
+ placeholder: POST_BRIDGE_API,
168
+ description: `Optional. Empty means ${POST_BRIDGE_API}`
169
+ })
170
+ }),
171
+ secretFields: ["apiKey"],
172
+ icon: "Key01Icon",
173
+ iconUrl: POST_BRIDGE_ICON,
174
+ async test(credential) {
175
+ await callPostBridge(postBridgeAccess(credential), {
176
+ method: "GET",
177
+ path: "/v1/social-accounts",
178
+ query: { limit: 1 }
179
+ }, {
180
+ signal: AbortSignal.timeout(TIMEOUT_MS),
181
+ timeoutMs: TIMEOUT_MS
182
+ });
183
+ }
184
+ };
185
+ // src/config.ts
186
+ const RESOURCES = [
187
+ "post",
188
+ "media",
189
+ "socialAccount",
190
+ "postResult",
191
+ "analytics"
192
+ ];
193
+ const OPERATIONS_OF = {
194
+ post: [
195
+ "create",
196
+ "getAll",
197
+ "get",
198
+ "update",
199
+ "delete"
200
+ ],
201
+ media: [
202
+ "upload",
203
+ "createUploadUrl",
204
+ "getAll",
205
+ "get",
206
+ "delete"
207
+ ],
208
+ socialAccount: [
209
+ "getAll",
210
+ "get",
211
+ "disconnect",
212
+ "createConnectLink",
213
+ "searchInstagramAudio"
214
+ ],
215
+ postResult: ["getAll", "get"],
216
+ analytics: [
217
+ "getAll",
218
+ "get",
219
+ "getDaily",
220
+ "sync"
221
+ ]
222
+ };
223
+ const ALL_OPERATIONS = [...new Set(Object.values(OPERATIONS_OF).flat())];
224
+ const PLATFORMS = [
225
+ "bluesky",
226
+ "facebook",
227
+ "google_business",
228
+ "instagram",
229
+ "linkedin",
230
+ "pinterest",
231
+ "threads",
232
+ "tiktok",
233
+ "twitter",
234
+ "youtube"
235
+ ];
236
+ const POST_STATUSES = [
237
+ "posted",
238
+ "scheduled",
239
+ "processing",
240
+ "failed"
241
+ ];
242
+ const MEDIA_TYPES = ["image", "video"];
243
+ const UPLOAD_MIME_TYPES = [
244
+ "image/png",
245
+ "image/jpeg",
246
+ "video/mp4",
247
+ "video/quicktime",
248
+ "application/pdf"
249
+ ];
250
+ const CONNECT_PLATFORMS = [
251
+ "instagram",
252
+ "facebook",
253
+ "tiktok",
254
+ "youtube",
255
+ "twitter",
256
+ "linkedin",
257
+ "threads",
258
+ "pinterest",
259
+ "bluesky"
260
+ ];
261
+ /** Show a field only for these operations of a resource. */
262
+ const on = (resource, ...operations) => ({ showWhen: {
263
+ resource: [resource],
264
+ operation: operations
265
+ } });
266
+ const platformLabels = {
267
+ bluesky: "Bluesky",
268
+ facebook: "Facebook",
269
+ google_business: "Google Business Profile",
270
+ instagram: "Instagram",
271
+ linkedin: "LinkedIn",
272
+ pinterest: "Pinterest",
273
+ threads: "Threads",
274
+ tiktok: "TikTok",
275
+ twitter: "X (Twitter)",
276
+ youtube: "YouTube"
277
+ };
278
+ const postBridgeConfig = zod.z.object({
279
+ resource: zod.z.enum(RESOURCES).default("post").meta({
280
+ labels: {
281
+ post: "Post",
282
+ media: "Media",
283
+ socialAccount: "Social Account",
284
+ postResult: "Post Result",
285
+ analytics: "Analytics"
286
+ },
287
+ hints: {
288
+ post: "Create, schedule, find, change, or delete posts",
289
+ media: "Upload files and manage uploaded media",
290
+ socialAccount: "List, connect, and disconnect social accounts",
291
+ postResult: "See what happened to a post on each platform",
292
+ analytics: "Views, likes, comments, and shares of published posts"
293
+ }
294
+ }),
295
+ operation: zod.z.enum(ALL_OPERATIONS).default("getAll").meta({
296
+ labels: {
297
+ create: "Create",
298
+ getAll: "Get Many",
299
+ get: "Get",
300
+ update: "Update",
301
+ delete: "Delete",
302
+ upload: "Upload",
303
+ createUploadUrl: "Create Upload URL",
304
+ disconnect: "Disconnect",
305
+ createConnectLink: "Create Connect Link",
306
+ searchInstagramAudio: "Search Instagram Audio",
307
+ getDaily: "Get Daily",
308
+ sync: "Sync"
309
+ },
310
+ hints: {
311
+ create: "Publish a post now, schedule it, or save it as a draft",
312
+ getAll: "Get all items, or use filters",
313
+ get: "Get one item",
314
+ update: "Change a scheduled or draft post",
315
+ delete: "Delete a scheduled or draft post",
316
+ upload: "Upload the binary data of the input and get a media ID",
317
+ createUploadUrl: "Get a media ID and a signed upload URL. You send the file yourself",
318
+ disconnect: "Disconnect a social account",
319
+ createConnectLink: "Make a link that connects a social account for another person",
320
+ searchInstagramAudio: "Find the music tracks that an Instagram account can use in a reel",
321
+ getDaily: "Get the daily totals and changes of a post",
322
+ sync: "Ask the platforms for new numbers. Once every 30 minutes"
323
+ }
324
+ }),
325
+ id: zod.z.string().optional().meta({
326
+ title: "ID",
327
+ showWhen: {
328
+ resource: [
329
+ "post",
330
+ "media",
331
+ "socialAccount",
332
+ "postResult",
333
+ "analytics"
334
+ ],
335
+ operation: [
336
+ "get",
337
+ "update",
338
+ "delete",
339
+ "disconnect",
340
+ "searchInstagramAudio",
341
+ "getDaily"
342
+ ]
343
+ },
344
+ description: "The ID of the item. For analytics, this is the ID of the post result. For a social account, this is a number"
345
+ }),
346
+ caption: zod.z.string().optional().meta({
347
+ ...on("post", "create", "update"),
348
+ ui: "textarea",
349
+ description: "The text of the post. A caption is needed, unless the post is a draft. Links are removed for X (Twitter)"
350
+ }),
351
+ socialAccounts: zod.z.string().optional().meta({
352
+ ...on("post", "create", "update"),
353
+ title: "Social Account IDs",
354
+ description: "IDs with commas between, for example 12,34. Use Get Many on Social Account to find them"
355
+ }),
356
+ media: zod.z.string().optional().meta({
357
+ ...on("post", "create", "update"),
358
+ title: "Media IDs",
359
+ description: "Media IDs with commas between. Use the Upload operation of Media to get them"
360
+ }),
361
+ mediaUrls: zod.z.string().optional().meta({
362
+ ...on("post", "create", "update"),
363
+ title: "Media URLs",
364
+ description: "Public URLs with commas between. Post Bridge ignores them if the post has media IDs"
365
+ }),
366
+ binaryPropertyNames: zod.z.string().optional().meta({
367
+ ...on("post", "create"),
368
+ title: "Binary Properties",
369
+ description: "Names of properties of `binary` in the input, with commas between. Each file is uploaded and added to the media of the post"
370
+ }),
371
+ scheduleMode: zod.z.enum([
372
+ "now",
373
+ "at",
374
+ "queue"
375
+ ]).default("now").meta({
376
+ ...on("post", "create"),
377
+ title: "Publish",
378
+ labels: {
379
+ now: "Now",
380
+ at: "At a Date and Time",
381
+ queue: "In the Next Queue Slot"
382
+ }
383
+ }),
384
+ updateScheduleMode: zod.z.enum([
385
+ "unchanged",
386
+ "now",
387
+ "at"
388
+ ]).default("unchanged").meta({
389
+ ...on("post", "update"),
390
+ title: "Publish",
391
+ labels: {
392
+ unchanged: "Keep as is",
393
+ now: "Now",
394
+ at: "At a Date and Time"
395
+ },
396
+ description: "To change a scheduled post, choose At a Date and Time and set the time again. If you do not, Post Bridge publishes the post now"
397
+ }),
398
+ scheduledAt: zod.z.string().optional().meta({
399
+ showWhen: {
400
+ resource: ["post"],
401
+ operation: ["create"],
402
+ scheduleMode: ["at"]
403
+ },
404
+ title: "Date and Time",
405
+ placeholder: "2026-12-31T23:59:00Z",
406
+ description: "A date and time in ISO 8601 format"
407
+ }),
408
+ scheduledAtUpdate: zod.z.string().optional().meta({
409
+ showWhen: {
410
+ resource: ["post"],
411
+ operation: ["update"],
412
+ updateScheduleMode: ["at"]
413
+ },
414
+ title: "Date and Time",
415
+ placeholder: "2026-12-31T23:59:00Z",
416
+ description: "A date and time in ISO 8601 format"
417
+ }),
418
+ queueTimezone: zod.z.string().optional().meta({
419
+ showWhen: {
420
+ resource: ["post"],
421
+ operation: ["create"],
422
+ scheduleMode: ["queue"]
423
+ },
424
+ title: "Queue Time Zone",
425
+ placeholder: "America/New_York",
426
+ description: "Optional. Empty means the time zone that is saved in your Post Bridge account"
427
+ }),
428
+ isDraft: zod.z.boolean().default(false).meta({
429
+ ...on("post", "create"),
430
+ title: "Save as Draft",
431
+ description: "Post Bridge does not publish a draft until you update it"
432
+ }),
433
+ draftState: zod.z.enum([
434
+ "unchanged",
435
+ "draft",
436
+ "send"
437
+ ]).default("unchanged").meta({
438
+ ...on("post", "update"),
439
+ title: "Draft",
440
+ labels: {
441
+ unchanged: "Keep as is",
442
+ draft: "Save as Draft",
443
+ send: "Send the Draft"
444
+ }
445
+ }),
446
+ processingEnabled: zod.z.boolean().default(true).meta({
447
+ ...on("post", "create", "update"),
448
+ title: "Process Videos",
449
+ description: "On: Post Bridge processes video files so that they can be posted"
450
+ }),
451
+ platformConfigurations: zod.z.string().optional().meta({
452
+ ...on("post", "create", "update"),
453
+ ui: "textarea",
454
+ title: "Platform Configurations (JSON)",
455
+ placeholder: "{\"tiktok\":{\"privacy_status\":\"private\"},\"instagram\":{\"placement\":\"story\"}}",
456
+ description: "A JSON object with one key for each platform: bluesky, facebook, google_business, instagram, linkedin, pinterest, threads, tiktok, twitter, youtube. Each platform can change the caption and the media"
457
+ }),
458
+ accountConfigurations: zod.z.string().optional().meta({
459
+ ...on("post", "create", "update"),
460
+ ui: "textarea",
461
+ title: "Account Configurations (JSON)",
462
+ placeholder: "{\"account_configurations\":[{\"account_id\":12,\"caption\":\"Other text\"}]}",
463
+ description: "A JSON object with the key \"account_configurations\". It changes the caption or the media for single accounts"
464
+ }),
465
+ binaryPropertyName: zod.z.string().default("data").meta({
466
+ ...on("media", "upload"),
467
+ title: "Binary Property",
468
+ description: "The property of `binary` in the input that holds the file"
469
+ }),
470
+ fileName: zod.z.string().optional().meta({
471
+ showWhen: {
472
+ resource: ["media"],
473
+ operation: ["upload", "createUploadUrl"]
474
+ },
475
+ title: "File Name",
476
+ description: "The name of the file, with the extension. For Upload, empty means the name in the binary data"
477
+ }),
478
+ mimeType: zod.z.enum(UPLOAD_MIME_TYPES).optional().meta({
479
+ showWhen: {
480
+ resource: ["media"],
481
+ operation: ["upload", "createUploadUrl"]
482
+ },
483
+ title: "File Type",
484
+ labels: {
485
+ "image/png": "PNG image",
486
+ "image/jpeg": "JPEG image",
487
+ "video/mp4": "MP4 video",
488
+ "video/quicktime": "QuickTime video",
489
+ "application/pdf": "PDF document"
490
+ },
491
+ description: "For Upload, empty means the type in the binary data"
492
+ }),
493
+ sizeBytes: zod.z.number().int().min(1).optional().meta({
494
+ ...on("media", "createUploadUrl"),
495
+ title: "Size (Bytes)",
496
+ description: "The size of the file in bytes"
497
+ }),
498
+ connectPlatform: zod.z.enum(CONNECT_PLATFORMS).default("instagram").meta({
499
+ ...on("socialAccount", "createConnectLink"),
500
+ title: "Platform",
501
+ labels: platformLabels,
502
+ description: "One link connects one platform. Google Business Profile is not available"
503
+ }),
504
+ returnUrl: zod.z.string().optional().meta({
505
+ ...on("socialAccount", "createConnectLink"),
506
+ title: "Return URL",
507
+ placeholder: "https://app.example.com/social/callback",
508
+ description: "Where the person goes after the platform consent screen. Use HTTPS (HTTP for localhost)"
509
+ }),
510
+ expiresIn: zod.z.number().int().min(60).max(604800).optional().meta({
511
+ ...on("socialAccount", "createConnectLink"),
512
+ title: "Expires In (Seconds)",
513
+ description: "Empty means 86400 (24 hours). The most is 604800 (7 days)"
514
+ }),
515
+ audioQuery: zod.z.string().optional().meta({
516
+ ...on("socialAccount", "searchInstagramAudio"),
517
+ title: "Search Text",
518
+ description: "Empty gives the tracks that are trending now"
519
+ }),
520
+ audioType: zod.z.enum(["music", "original_sound"]).optional().meta({
521
+ ...on("socialAccount", "searchInstagramAudio"),
522
+ title: "Audio Type",
523
+ labels: {
524
+ music: "Music",
525
+ original_sound: "Original Sound"
526
+ }
527
+ }),
528
+ platforms: zod.z.string().optional().meta({
529
+ showWhen: {
530
+ resource: [
531
+ "post",
532
+ "postResult",
533
+ "socialAccount"
534
+ ],
535
+ operation: ["getAll"]
536
+ },
537
+ title: "Platforms",
538
+ placeholder: "instagram,tiktok",
539
+ description: `Platform names with commas between. Post Bridge uses: ${PLATFORMS.join(", ")}`
540
+ }),
541
+ analyticsPlatform: zod.z.string().optional().meta({
542
+ ...on("analytics", "getAll", "sync"),
543
+ title: "Platform",
544
+ placeholder: "tiktok",
545
+ description: "Only one platform. Empty means all platforms. Sync works for tiktok, youtube, and instagram"
546
+ }),
547
+ statuses: zod.z.string().optional().meta({
548
+ ...on("post", "getAll"),
549
+ title: "Statuses",
550
+ placeholder: "scheduled,failed",
551
+ description: `Statuses with commas between: ${POST_STATUSES.join(", ")}`
552
+ }),
553
+ postIds: zod.z.string().optional().meta({
554
+ showWhen: {
555
+ resource: ["postResult", "media"],
556
+ operation: ["getAll"]
557
+ },
558
+ title: "Post IDs",
559
+ description: "Only items of these posts. IDs with commas between"
560
+ }),
561
+ mediaTypes: zod.z.string().optional().meta({
562
+ ...on("media", "getAll"),
563
+ title: "Media Types",
564
+ placeholder: "image,video",
565
+ description: "Types with commas between: image, video"
566
+ }),
567
+ usernames: zod.z.string().optional().meta({
568
+ ...on("socialAccount", "getAll"),
569
+ description: "Only these usernames. Names with commas between"
570
+ }),
571
+ externalRef: zod.z.string().optional().meta({
572
+ showWhen: {
573
+ resource: ["socialAccount"],
574
+ operation: ["getAll", "createConnectLink"]
575
+ },
576
+ title: "External Reference",
577
+ description: "Your own reference for a customer. Create Connect Link saves it on the accounts. Get Many finds the accounts with it"
578
+ }),
579
+ workspaceId: zod.z.string().optional().meta({
580
+ ...on("socialAccount", "getAll"),
581
+ title: "Workspace ID",
582
+ description: "Only accounts of this workspace"
583
+ }),
584
+ postResultIds: zod.z.string().optional().meta({
585
+ ...on("analytics", "getAll"),
586
+ title: "Post Result IDs",
587
+ description: "Only these post results. IDs with commas between"
588
+ }),
589
+ timeframe: zod.z.string().optional().meta({
590
+ ...on("analytics", "getAll"),
591
+ placeholder: "all",
592
+ description: "The time frame of the numbers. Empty means all"
593
+ }),
594
+ analyticsMediaType: zod.z.enum(["video", "slideshow"]).optional().meta({
595
+ ...on("analytics", "getAll"),
596
+ title: "Media Type",
597
+ labels: {
598
+ video: "Video",
599
+ slideshow: "Slideshow"
600
+ }
601
+ }),
602
+ returnAll: zod.z.boolean().default(false).meta({ showWhen: {
603
+ resource: [
604
+ "post",
605
+ "media",
606
+ "socialAccount",
607
+ "postResult",
608
+ "analytics"
609
+ ],
610
+ operation: ["getAll"]
611
+ } }),
612
+ limit: zod.z.number().int().min(1).max(5e3).default(50).meta({ showWhen: {
613
+ resource: [
614
+ "post",
615
+ "media",
616
+ "socialAccount",
617
+ "postResult",
618
+ "analytics"
619
+ ],
620
+ operation: ["getAll"],
621
+ returnAll: [false]
622
+ } }),
623
+ timeoutMs: zod.z.number().int().min(1).max(6e5).default(3e4).meta({
624
+ title: "Timeout (ms)",
625
+ description: "The time limit for each call"
626
+ })
627
+ }).superRefine((config, context) => {
628
+ if (!OPERATIONS_OF[config.resource].includes(config.operation)) context.addIssue({
629
+ code: "custom",
630
+ path: ["operation"],
631
+ message: `"${config.operation}" is not an operation of "${config.resource}"`
632
+ });
633
+ });
634
+ // src/request.ts
635
+ const seg = encodeURIComponent;
636
+ /** Split text with commas. Empty items go away. */
637
+ const listOf = (value) => value?.split(",").map((item) => item.trim()).filter(Boolean) ?? [];
638
+ const need = (value, name, operation) => {
639
+ if (value === void 0 || value === "") throw new Error(`"${name}" is needed to ${operation}`);
640
+ return value;
641
+ };
642
+ const compact = (body) => Object.fromEntries(Object.entries(body).filter(([, value]) => value !== void 0));
643
+ /** A list of words that must be in a known set. */
644
+ function known(value, allowed, name) {
645
+ const items = listOf(value);
646
+ for (const item of items) if (!allowed.includes(item)) throw new Error(`"${item}" is not a value for "${name}". Use: ${allowed.join(", ")}`);
647
+ return items.length > 0 ? items : void 0;
648
+ }
649
+ const orNone = (items) => items.length > 0 ? items : void 0;
650
+ /** The IDs of social accounts are numbers. */
651
+ function accountIds(value, name) {
652
+ return listOf(value).map((item) => {
653
+ if (!/^\d+$/.test(item)) throw new Error(`"${item}" is not a social account ID in "${name}"`);
654
+ return Number(item);
655
+ });
656
+ }
657
+ function accountId(value, operation) {
658
+ const id = need(value?.trim(), "id", operation);
659
+ if (!/^\d+$/.test(id)) throw new Error(`The social account ID must be a number. Got "${id}"`);
660
+ return id;
661
+ }
662
+ /** Read JSON text that must be an object. Empty text gives nothing. */
663
+ function jsonObjectOf(value, name) {
664
+ if (value === void 0 || value.trim() === "") return void 0;
665
+ let parsed;
666
+ try {
667
+ parsed = JSON.parse(value);
668
+ } catch {
669
+ throw new Error(`"${name}" is not valid JSON`);
670
+ }
671
+ if (!(0, _zerodot_node_sdk.isRecord)(parsed)) throw new Error(`"${name}" must be a JSON object`);
672
+ return parsed;
673
+ }
674
+ function isoDate(value, name) {
675
+ const text = need(value?.trim(), name, "publish at a date and time");
676
+ if (Number.isNaN(Date.parse(text))) throw new Error(`"${name}" is not a date. Use ISO 8601, for example 2026-12-31T23:59:00Z`);
677
+ return text;
678
+ }
679
+ /** The API call for one operation, without the network. A list returns `list: true`. */
680
+ function buildRequest(c, extras = {}) {
681
+ const op = `${c.resource}.${c.operation}`;
682
+ const id = () => seg(need(c.id?.trim(), "id", op));
683
+ switch (op) {
684
+ case "post.create": {
685
+ const media = [...listOf(c.media), ...extras.uploadedMedia ?? []];
686
+ const caption = c.caption ?? "";
687
+ if (caption === "" && !c.isDraft) throw new Error(`"caption" is needed to ${op}`);
688
+ const accounts = accountIds(c.socialAccounts, "socialAccounts");
689
+ if (accounts.length === 0) throw new Error(`"socialAccounts" is needed to ${op}`);
690
+ if (c.scheduleMode === "at" && c.scheduledAt === void 0) throw new Error(`"scheduledAt" is needed to ${op} at a date and time`);
691
+ return {
692
+ method: "POST",
693
+ path: "/v1/posts",
694
+ body: compact({
695
+ caption: caption === "" ? void 0 : caption,
696
+ social_accounts: accounts,
697
+ media: orNone(media),
698
+ media_urls: orNone(listOf(c.mediaUrls)),
699
+ scheduled_at: c.scheduleMode === "at" ? isoDate(c.scheduledAt, "scheduledAt") : void 0,
700
+ use_queue: c.scheduleMode === "queue" ? c.queueTimezone?.trim() ? { timezone: c.queueTimezone.trim() } : true : void 0,
701
+ is_draft: c.isDraft ? true : void 0,
702
+ processing_enabled: c.processingEnabled ? void 0 : false,
703
+ platform_configurations: jsonObjectOf(c.platformConfigurations, "platformConfigurations"),
704
+ account_configurations: jsonObjectOf(c.accountConfigurations, "accountConfigurations")
705
+ })
706
+ };
707
+ }
708
+ case "post.getAll": return {
709
+ method: "GET",
710
+ path: "/v1/posts",
711
+ query: {
712
+ platform: known(c.platforms, PLATFORMS, "platforms"),
713
+ status: known(c.statuses, POST_STATUSES, "statuses")
714
+ },
715
+ list: true
716
+ };
717
+ case "post.get": return {
718
+ method: "GET",
719
+ path: `/v1/posts/${id()}`
720
+ };
721
+ case "post.update": {
722
+ const accounts = accountIds(c.socialAccounts, "socialAccounts");
723
+ const body = compact({
724
+ caption: c.caption === "" ? void 0 : c.caption,
725
+ social_accounts: orNone(accounts),
726
+ media: orNone(listOf(c.media)),
727
+ media_urls: orNone(listOf(c.mediaUrls)),
728
+ scheduled_at: c.updateScheduleMode === "at" ? isoDate(c.scheduledAtUpdate, "scheduledAtUpdate") : c.updateScheduleMode === "now" ? null : void 0,
729
+ is_draft: c.draftState === "draft" ? true : c.draftState === "send" ? false : void 0,
730
+ processing_enabled: c.processingEnabled ? void 0 : false,
731
+ platform_configurations: jsonObjectOf(c.platformConfigurations, "platformConfigurations"),
732
+ account_configurations: jsonObjectOf(c.accountConfigurations, "accountConfigurations")
733
+ });
734
+ if (Object.keys(body).length === 0) throw new Error(`A field to change is needed to ${op}`);
735
+ return {
736
+ method: "PATCH",
737
+ path: `/v1/posts/${id()}`,
738
+ body
739
+ };
740
+ }
741
+ case "post.delete": return {
742
+ method: "DELETE",
743
+ path: `/v1/posts/${id()}`
744
+ };
745
+ case "media.createUploadUrl": return {
746
+ method: "POST",
747
+ path: "/v1/media/create-upload-url",
748
+ body: uploadUrlBody(need(c.fileName, "fileName", op), need(c.mimeType, "mimeType", op), need(c.sizeBytes, "sizeBytes", op))
749
+ };
750
+ case "media.getAll": return {
751
+ method: "GET",
752
+ path: "/v1/media",
753
+ query: {
754
+ post_id: orNone(listOf(c.postIds)),
755
+ type: known(c.mediaTypes, MEDIA_TYPES, "mediaTypes")
756
+ },
757
+ list: true
758
+ };
759
+ case "media.get": return {
760
+ method: "GET",
761
+ path: `/v1/media/${id()}`
762
+ };
763
+ case "media.delete": return {
764
+ method: "DELETE",
765
+ path: `/v1/media/${id()}`
766
+ };
767
+ case "socialAccount.getAll": return {
768
+ method: "GET",
769
+ path: "/v1/social-accounts",
770
+ query: {
771
+ platform: orNone(listOf(c.platforms)),
772
+ username: orNone(listOf(c.usernames)),
773
+ external_ref: c.externalRef?.trim(),
774
+ workspace_id: c.workspaceId?.trim()
775
+ },
776
+ list: true
777
+ };
778
+ case "socialAccount.get": return {
779
+ method: "GET",
780
+ path: `/v1/social-accounts/${accountId(c.id, op)}`
781
+ };
782
+ case "socialAccount.disconnect": return {
783
+ method: "DELETE",
784
+ path: `/v1/social-accounts/${accountId(c.id, op)}`
785
+ };
786
+ case "socialAccount.createConnectLink": return {
787
+ method: "POST",
788
+ path: "/v1/social-accounts/connect-link",
789
+ body: compact({
790
+ platform: c.connectPlatform,
791
+ return_url: need(c.returnUrl?.trim(), "returnUrl", op),
792
+ external_ref: c.externalRef?.trim() || void 0,
793
+ expires_in: c.expiresIn
794
+ })
795
+ };
796
+ case "socialAccount.searchInstagramAudio": return {
797
+ method: "GET",
798
+ path: `/v1/social-accounts/${accountId(c.id, op)}/instagram-audio`,
799
+ query: {
800
+ query: c.audioQuery?.trim(),
801
+ type: c.audioType
802
+ }
803
+ };
804
+ case "postResult.getAll": return {
805
+ method: "GET",
806
+ path: "/v1/post-results",
807
+ query: {
808
+ post_id: orNone(listOf(c.postIds)),
809
+ platform: orNone(listOf(c.platforms))
810
+ },
811
+ list: true
812
+ };
813
+ case "postResult.get": return {
814
+ method: "GET",
815
+ path: `/v1/post-results/${id()}`
816
+ };
817
+ case "analytics.getAll": return {
818
+ method: "GET",
819
+ path: "/v1/analytics",
820
+ query: {
821
+ platform: c.analyticsPlatform?.trim(),
822
+ post_result_id: orNone(listOf(c.postResultIds)),
823
+ timeframe: c.timeframe?.trim(),
824
+ media_type: c.analyticsMediaType
825
+ },
826
+ list: true
827
+ };
828
+ case "analytics.get": return {
829
+ method: "GET",
830
+ path: `/v1/analytics/${id()}`
831
+ };
832
+ case "analytics.getDaily": return {
833
+ method: "GET",
834
+ path: `/v1/analytics/${id()}/daily`
835
+ };
836
+ case "analytics.sync": return {
837
+ method: "POST",
838
+ path: "/v1/analytics/sync",
839
+ query: { platform: c.analyticsPlatform?.trim() }
840
+ };
841
+ }
842
+ throw new Error(`Unknown Post Bridge operation "${op}"`);
843
+ }
844
+ /** The body of the call that makes an upload URL. */
845
+ function uploadUrlBody(name, mimeType, sizeBytes) {
846
+ if (!UPLOAD_MIME_TYPES.includes(mimeType)) throw new Error(`Post Bridge cannot upload "${mimeType}". Use: ${UPLOAD_MIME_TYPES.join(", ")}`);
847
+ return {
848
+ name,
849
+ mime_type: mimeType,
850
+ size_bytes: sizeBytes
851
+ };
852
+ }
853
+ // src/upload.ts
854
+ /**
855
+ * The upload flow of Post Bridge. Step 1 asks for a media ID and a signed URL. Step 2 sends the
856
+ * bytes to that URL with PUT.
857
+ */
858
+ async function uploadBinary(access, input, property, overrides, options) {
859
+ const file = (0, _zerodot_node_sdk.readBinary)(input, property);
860
+ const bytes = Buffer.from(file.data, "base64");
861
+ const name = overrides.fileName?.trim() || file.fileName;
862
+ if (!name) throw new Error(`A file name is needed to upload "${property}". Set "fileName", or set it in the binary data`);
863
+ const mimeType = overrides.mimeType || file.mimeType;
864
+ const target = uploadTargetOf(await callPostBridge(access, {
865
+ method: "POST",
866
+ path: "/v1/media/create-upload-url",
867
+ body: uploadUrlBody(name, mimeType, bytes.byteLength)
868
+ }, options));
869
+ await putMedia(target.uploadUrl, bytes, mimeType, options);
870
+ return {
871
+ media_id: target.mediaId,
872
+ name: target.name || name,
873
+ mime_type: mimeType,
874
+ size_bytes: bytes.byteLength
875
+ };
876
+ }
877
+ // src/index.ts
878
+ const nodes = [(0, _zerodot_node_sdk.defineNode)({
879
+ type: "post-bridge.api",
880
+ label: "Post Bridge",
881
+ description: "Publish and schedule social media posts, upload media, and read results",
882
+ category: "integration",
883
+ app: "Post Bridge",
884
+ actions: [
885
+ {
886
+ label: "Create a post",
887
+ config: {
888
+ resource: "post",
889
+ operation: "create"
890
+ }
891
+ },
892
+ {
893
+ label: "Get many posts",
894
+ config: {
895
+ resource: "post",
896
+ operation: "getAll"
897
+ }
898
+ },
899
+ {
900
+ label: "Get a post",
901
+ config: {
902
+ resource: "post",
903
+ operation: "get"
904
+ }
905
+ },
906
+ {
907
+ label: "Update a post",
908
+ config: {
909
+ resource: "post",
910
+ operation: "update"
911
+ }
912
+ },
913
+ {
914
+ label: "Delete a post",
915
+ config: {
916
+ resource: "post",
917
+ operation: "delete"
918
+ }
919
+ },
920
+ {
921
+ label: "Upload media",
922
+ config: {
923
+ resource: "media",
924
+ operation: "upload"
925
+ }
926
+ },
927
+ {
928
+ label: "Create a media upload URL",
929
+ config: {
930
+ resource: "media",
931
+ operation: "createUploadUrl"
932
+ }
933
+ },
934
+ {
935
+ label: "Get many media",
936
+ config: {
937
+ resource: "media",
938
+ operation: "getAll"
939
+ }
940
+ },
941
+ {
942
+ label: "Get a media item",
943
+ config: {
944
+ resource: "media",
945
+ operation: "get"
946
+ }
947
+ },
948
+ {
949
+ label: "Delete a media item",
950
+ config: {
951
+ resource: "media",
952
+ operation: "delete"
953
+ }
954
+ },
955
+ {
956
+ label: "Get many social accounts",
957
+ config: {
958
+ resource: "socialAccount",
959
+ operation: "getAll"
960
+ }
961
+ },
962
+ {
963
+ label: "Get a social account",
964
+ config: {
965
+ resource: "socialAccount",
966
+ operation: "get"
967
+ }
968
+ },
969
+ {
970
+ label: "Disconnect a social account",
971
+ config: {
972
+ resource: "socialAccount",
973
+ operation: "disconnect"
974
+ }
975
+ },
976
+ {
977
+ label: "Create a connect link for a social account",
978
+ config: {
979
+ resource: "socialAccount",
980
+ operation: "createConnectLink"
981
+ }
982
+ },
983
+ {
984
+ label: "Search Instagram audio",
985
+ config: {
986
+ resource: "socialAccount",
987
+ operation: "searchInstagramAudio"
988
+ }
989
+ },
990
+ {
991
+ label: "Get many post results",
992
+ config: {
993
+ resource: "postResult",
994
+ operation: "getAll"
995
+ }
996
+ },
997
+ {
998
+ label: "Get a post result",
999
+ config: {
1000
+ resource: "postResult",
1001
+ operation: "get"
1002
+ }
1003
+ },
1004
+ {
1005
+ label: "Get many analytics records",
1006
+ config: {
1007
+ resource: "analytics",
1008
+ operation: "getAll"
1009
+ }
1010
+ },
1011
+ {
1012
+ label: "Get an analytics record",
1013
+ config: {
1014
+ resource: "analytics",
1015
+ operation: "get"
1016
+ }
1017
+ },
1018
+ {
1019
+ label: "Get daily analytics of a post",
1020
+ config: {
1021
+ resource: "analytics",
1022
+ operation: "getDaily"
1023
+ }
1024
+ },
1025
+ {
1026
+ label: "Sync analytics",
1027
+ config: {
1028
+ resource: "analytics",
1029
+ operation: "sync"
1030
+ }
1031
+ }
1032
+ ],
1033
+ icon: "Share08Icon",
1034
+ iconUrl: POST_BRIDGE_ICON,
1035
+ config: postBridgeConfig,
1036
+ defaultConfig: {
1037
+ resource: "post",
1038
+ operation: "getAll",
1039
+ scheduleMode: "now",
1040
+ updateScheduleMode: "unchanged",
1041
+ draftState: "unchanged",
1042
+ isDraft: false,
1043
+ processingEnabled: true,
1044
+ binaryPropertyName: "data",
1045
+ connectPlatform: "instagram",
1046
+ returnAll: false,
1047
+ limit: 50,
1048
+ timeoutMs: 3e4
1049
+ },
1050
+ credentialTypes: [POST_BRIDGE_CREDENTIAL],
1051
+ ports: {
1052
+ in: ["in"],
1053
+ out: ["out"]
1054
+ },
1055
+ subtitle: (config) => typeof config.operation === "string" ? `${String(config.resource ?? "post")}: ${config.operation}` : void 0,
1056
+ async run({ config, input, credential, signal }) {
1057
+ const access = postBridgeAccess(credential);
1058
+ const options = {
1059
+ signal,
1060
+ timeoutMs: config.timeoutMs
1061
+ };
1062
+ if (config.resource === "media" && config.operation === "upload") return {
1063
+ port: "out",
1064
+ data: await uploadBinary(access, input, config.binaryPropertyName, {
1065
+ fileName: config.fileName,
1066
+ mimeType: config.mimeType
1067
+ }, options)
1068
+ };
1069
+ const uploadedMedia = [];
1070
+ if (config.resource === "post" && config.operation === "create") for (const property of listOf(config.binaryPropertyNames)) {
1071
+ const media = await uploadBinary(access, input, property, {}, options);
1072
+ uploadedMedia.push(media.media_id);
1073
+ }
1074
+ const request = buildRequest(config, { uploadedMedia });
1075
+ if (request.list) return {
1076
+ port: "out",
1077
+ data: await callPostBridgeList(access, request, config.returnAll ? null : config.limit, options)
1078
+ };
1079
+ return {
1080
+ port: "out",
1081
+ data: await callPostBridge(access, request, options)
1082
+ };
1083
+ }
1084
+ })];
1085
+ const credentialTypes = [postBridgeCredential];
1086
+ exports.credentialTypes = credentialTypes;
1087
+ exports.nodes = nodes;