@posterly/cli 0.1.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.
@@ -0,0 +1,873 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { readFile, mkdir, writeFile, rm } from 'node:fs/promises';
4
+ import { existsSync } from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { createServer } from 'node:http';
8
+ import { spawn } from 'node:child_process';
9
+ import { createHash, randomBytes } from 'node:crypto';
10
+ import {
11
+ PLATFORM_HELPER_NAMES,
12
+ PLATFORM_MANIFEST,
13
+ } from '../generated/platform-manifest.mjs';
14
+
15
+ const DEFAULT_BASE_URL = 'https://www.poster.ly';
16
+ const CONFIG_DIR = path.join(os.homedir(), '.posterly');
17
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
18
+ const OAUTH_CLIENT_ID = 'posterly-cli';
19
+ const OAUTH_CALLBACK_PORT = 37373;
20
+ const OAUTH_CALLBACK_PATH = '/oauth/callback';
21
+ const OAUTH_SCOPES = ['accounts:read', 'accounts:write', 'posts:read', 'posts:write', 'media:write', 'analytics:read'];
22
+
23
+ const COMMANDS = [
24
+ 'auth:login [--url https://www.poster.ly] [--no-open]',
25
+ 'auth:key [key] [--url https://www.poster.ly]',
26
+ 'auth:status',
27
+ 'auth:logout',
28
+ 'whoami',
29
+ 'accounts:list|disconnect [--workspace-id id]',
30
+ 'connect:link [platform] [--workspace-id id] [--include-planned]',
31
+ 'oauth:clients|create-client|update-client|delete-client',
32
+ 'brands:list|get|accounts|profile',
33
+ 'platforms:list|schema|trigger',
34
+ 'posts:list|get|create|update|status|missing|release-id|delete|delete-group|batch',
35
+ 'slots:next',
36
+ 'media:upload|signed-upload|upload-from-url',
37
+ 'analytics:account|posts',
38
+ 'gbp:reviews|review-link|audit|suggest-reply|reply|delete-reply',
39
+ 'ai:video-options|video-function|generate-video|video-jobs|video-job',
40
+ 'activity:list',
41
+ 'notifications:list',
42
+ 'x:quota',
43
+ 'webhooks:list|create|update|delete|test',
44
+ ];
45
+
46
+ main().catch((error) => {
47
+ printError(error);
48
+ process.exit(1);
49
+ });
50
+
51
+ async function main() {
52
+ const { command, flags, positional } = parseArgs(process.argv.slice(2));
53
+ if (!command || command === 'help' || flags.help) {
54
+ return print({
55
+ posterly: 'CLI for the posterly API',
56
+ usage: 'posterly <command> [--flag value]',
57
+ commands: COMMANDS,
58
+ auth: 'Run `posterly auth:login`, `posterly auth:key pst_live_...`, or set POSTERLY_API_KEY.',
59
+ }, flags);
60
+ }
61
+
62
+ if (command === 'auth:login') return authLogin(flags);
63
+ if (command === 'auth:key') return saveKey(positional[0], flags);
64
+ if (command === 'auth:status') return authStatus(flags);
65
+ if (command === 'auth:logout') return logout(flags);
66
+
67
+ const client = await createClient(flags);
68
+
69
+ switch (command) {
70
+ case 'whoami':
71
+ return print(await client.get('/whoami'), flags);
72
+
73
+ case 'accounts:list':
74
+ return print(await client.get(withQuery('/accounts', { workspace_id: flags.workspaceId })), flags);
75
+ case 'accounts:disconnect': {
76
+ if (!flagEnabled(flags.confirm)) {
77
+ throw new Error('Disconnecting an account is irreversible. Re-run with --confirm after verifying the account ID.');
78
+ }
79
+ return print(await client.delete(`/accounts/${required(positional[0] || flags.id || flags.accountId, 'account id')}`), flags);
80
+ }
81
+
82
+ case 'connect:link': {
83
+ const platform = normalizeConnectTarget(flags.platform || positional[0], {
84
+ includePlanned: flagEnabled(flags.includePlanned),
85
+ });
86
+ const pathname = platform ? `/connect/${encodeURIComponent(platform)}` : '/connect';
87
+ return print(await client.get(withQuery(pathname, {
88
+ workspace_id: flags.workspaceId,
89
+ include_planned: flagEnabled(flags.includePlanned),
90
+ })), flags);
91
+ }
92
+
93
+ case 'oauth:clients':
94
+ return print(await client.get('/oauth/clients'), flags);
95
+ case 'oauth:create-client':
96
+ return print(await client.post('/oauth/clients', await oauthClientPayload(flags, positional, { creating: true })), flags);
97
+ case 'oauth:update-client':
98
+ return print(await client.patch(`/oauth/clients/${required(positional[0] || flags.clientId, 'client id')}`, await oauthClientPayload(flags, positional, { creating: false })), flags);
99
+ case 'oauth:delete-client':
100
+ if (!flagEnabled(flags.confirm)) {
101
+ throw new Error('Deleting an OAuth client prevents new authorizations for that client_id. Re-run with --confirm after verifying the client ID.');
102
+ }
103
+ return print(await client.delete(`/oauth/clients/${required(positional[0] || flags.clientId, 'client id')}`), flags);
104
+
105
+ case 'brands:list':
106
+ return print(await client.get(withQuery('/brands', { workspace_id: flags.workspaceId })), flags);
107
+ case 'brands:get':
108
+ return print(await client.get(`/brands/${required(positional[0] || flags.id, 'brand id')}`), flags);
109
+ case 'brands:accounts':
110
+ return print(await client.get(`/brands/${required(positional[0] || flags.id, 'brand id')}/accounts`), flags);
111
+ case 'brands:profile':
112
+ return print(await client.get(`/brands/${required(positional[0] || flags.id, 'brand id')}/profile`), flags);
113
+
114
+ case 'platforms:list':
115
+ return print(await client.get(withQuery('/platforms', { include_planned: flagEnabled(flags.includePlanned) })), flags);
116
+ case 'platforms:schema':
117
+ if (flags.accountId) {
118
+ return print(await client.get(`/accounts/${flags.accountId}/schema`), flags);
119
+ }
120
+ return print(await client.get(withQuery('/platforms', {
121
+ platform: normalizePlatform(flags.platform || positional[0], {
122
+ includePlanned: flagEnabled(flags.includePlanned),
123
+ }),
124
+ include_planned: flagEnabled(flags.includePlanned),
125
+ })), flags);
126
+ case 'platforms:trigger':
127
+ return print(await client.post('/platforms/trigger', {
128
+ helper: validateHelperName(required(flags.helper || positional[0], 'helper')),
129
+ account_id: flags.accountId,
130
+ platform: normalizePlatform(flags.platform, { supportedOnly: true }),
131
+ params: jsonFlag(flags.params, {}),
132
+ }), flags);
133
+
134
+ case 'posts:list':
135
+ return print(await client.get(withQuery('/posts', {
136
+ status: flags.status,
137
+ platform: normalizePlatform(flags.platform, { supportedOnly: true }),
138
+ account_id: flags.accountId,
139
+ workspace_id: flags.workspaceId,
140
+ limit: flags.limit,
141
+ offset: flags.offset,
142
+ updated_since: flags.updatedSince,
143
+ created_since: flags.createdSince,
144
+ sort_by: flags.sortBy,
145
+ })), flags);
146
+ case 'posts:get':
147
+ return print(await client.get(`/posts/${required(positional[0] || flags.id, 'post id')}`), flags);
148
+ case 'posts:missing':
149
+ return print(await client.get(`/posts/${required(positional[0] || flags.id, 'post id')}/missing`), flags);
150
+ case 'posts:create':
151
+ return print(await client.post('/posts', await postPayloadFromFlags(flags)), flags);
152
+ case 'posts:update':
153
+ return print(await client.patch(`/posts/${required(positional[0] || flags.id, 'post id')}`, await updatePayloadFromFlags(flags)), flags);
154
+ case 'posts:status':
155
+ if (!flagEnabled(flags.confirm)) {
156
+ throw new Error('Changing post status affects publishing. Re-run with --confirm after verifying the post ID and target status.');
157
+ }
158
+ return print(await client.put(`/posts/${required(positional[0] || flags.id, 'post id')}/status`, clean({
159
+ status: validatePostStatus(required(flags.status || positional[1], 'status')),
160
+ scheduled_at: flags.scheduledAt,
161
+ })), flags);
162
+ case 'posts:release-id':
163
+ return print(await client.put(`/posts/${required(positional[0] || flags.id, 'post id')}/release-id`, clean({
164
+ release_id: required(flags.releaseId || positional[1], 'release id'),
165
+ group_id: flags.groupId,
166
+ })), flags);
167
+ case 'posts:delete':
168
+ return print(await client.delete(`/posts/${required(positional[0] || flags.id, 'post id')}`), flags);
169
+ case 'posts:delete-group':
170
+ if (!flagEnabled(flags.confirm)) {
171
+ throw new Error('Deleting a post group is irreversible. Re-run with --confirm after verifying the group ID.');
172
+ }
173
+ return print(await client.delete(`/posts/group/${required(positional[0] || flags.groupId, 'group id')}?confirm=true`), flags);
174
+ case 'posts:batch':
175
+ return print(await client.post('/posts/batch', clean({
176
+ group_id: flags.groupId,
177
+ release_id: flags.releaseId,
178
+ posts: (await readJsonArray(required(flags.file, '--file'))).map(validatePostPayload),
179
+ })), flags);
180
+
181
+ case 'slots:next':
182
+ return print(await client.get(withQuery('/slots/next', {
183
+ account_ids: flags.accountIds,
184
+ timezone: flags.timezone,
185
+ workspace_id: flags.workspaceId,
186
+ count: flags.count,
187
+ })), flags);
188
+
189
+ case 'media:signed-upload':
190
+ return print(await client.post('/media/signed-upload', {
191
+ filename: required(flags.filename || positional[0], 'filename'),
192
+ content_type: required(flags.contentType, '--content-type'),
193
+ size: Number(required(flags.size, '--size')),
194
+ }), flags);
195
+ case 'media:upload-from-url':
196
+ return print(await client.post('/media/upload-from-url', {
197
+ url: required(flags.url || positional[0], 'url'),
198
+ filename: flags.filename,
199
+ content_type: flags.contentType,
200
+ }), flags);
201
+ case 'media:upload':
202
+ return print(await client.post('/media/upload', await mediaUploadPayload(flags, positional)), flags);
203
+
204
+ case 'analytics:account':
205
+ return print(await client.get(withQuery('/analytics/accounts', {
206
+ account_id: required(flags.accountId || positional[0], 'account id'),
207
+ from: flags.from,
208
+ to: flags.to,
209
+ })), flags);
210
+ case 'analytics:posts':
211
+ return print(await client.get(withQuery('/analytics/posts', {
212
+ account_id: required(flags.accountId || positional[0], 'account id'),
213
+ from: flags.from,
214
+ to: flags.to,
215
+ limit: flags.limit,
216
+ offset: flags.offset,
217
+ })), flags);
218
+
219
+ case 'gbp:reviews':
220
+ return print(await client.get(withQuery('/google-business/reviews', {
221
+ workspace_id: flags.workspaceId,
222
+ account_id: flags.accountId || positional[0],
223
+ location_id: flags.locationId,
224
+ rating: flags.rating,
225
+ unanswered: flagEnabled(flags.unanswered),
226
+ })), flags);
227
+ case 'gbp:review-link':
228
+ return print(await client.get(withQuery('/google-business/review-link', {
229
+ workspace_id: flags.workspaceId,
230
+ account_id: flags.accountId || positional[0],
231
+ location_id: flags.locationId,
232
+ })), flags);
233
+ case 'gbp:audit':
234
+ return print(await client.get(withQuery('/google-business/audit', {
235
+ workspace_id: flags.workspaceId,
236
+ account_id: flags.accountId || positional[0],
237
+ location_id: flags.locationId,
238
+ })), flags);
239
+ case 'gbp:suggest-reply':
240
+ return print(await client.post('/google-business/reviews/suggest-reply', clean({
241
+ workspace_id: flags.workspaceId,
242
+ account_id: flags.accountId,
243
+ location_id: flags.locationId,
244
+ review_text: flags.reviewText || flags.text || positional[0],
245
+ star_rating: Number(required(flags.starRating || flags.rating, '--star-rating')),
246
+ reviewer_name: flags.reviewerName,
247
+ business_name: flags.businessName,
248
+ tone: flags.tone,
249
+ count: flags.count ? Number(flags.count) : undefined,
250
+ })), flags);
251
+ case 'gbp:reply':
252
+ if (!flagEnabled(flags.confirm)) {
253
+ throw new Error('Posting a Google review reply is public. Re-run with --confirm after verifying the review and exact reply text.');
254
+ }
255
+ return print(await client.post('/google-business/reviews/reply', clean({
256
+ workspace_id: flags.workspaceId,
257
+ account_id: flags.accountId,
258
+ location_id: flags.locationId,
259
+ review_name: required(flags.reviewName || positional[0], '--review-name'),
260
+ comment: required(flags.comment || positional[1], '--comment'),
261
+ })), flags);
262
+ case 'gbp:delete-reply':
263
+ if (!flagEnabled(flags.confirm)) {
264
+ throw new Error('Deleting a Google review reply is irreversible. Re-run with --confirm after verifying the review.');
265
+ }
266
+ return print(await client.delete('/google-business/reviews/reply', clean({
267
+ workspace_id: flags.workspaceId,
268
+ account_id: flags.accountId,
269
+ location_id: flags.locationId,
270
+ review_name: required(flags.reviewName || positional[0], '--review-name'),
271
+ })), flags);
272
+
273
+ case 'ai:video-options':
274
+ return print(await client.get('/ai/video-options'), flags);
275
+ case 'ai:video-function':
276
+ return print(await client.post('/ai/video-function', await videoFunctionPayloadFromFlags(flags, positional)), flags);
277
+ case 'ai:generate-video':
278
+ return print(await client.post('/ai/generate-video', await videoPayloadFromFlags(flags)), flags);
279
+ case 'ai:video-jobs':
280
+ return print(await client.get(withQuery('/ai/video-jobs', {
281
+ status: flags.status,
282
+ limit: flags.limit,
283
+ })), flags);
284
+ case 'ai:video-job':
285
+ return print(await client.get(`/ai/video-jobs/${required(positional[0] || flags.id, 'video job id')}`), flags);
286
+
287
+ case 'activity:list':
288
+ return print(await client.get(withQuery('/activity', {
289
+ workspace_id: flags.workspaceId,
290
+ post_id: flags.postId,
291
+ since: flags.since,
292
+ type: flags.type,
293
+ limit: flags.limit,
294
+ })), flags);
295
+ case 'notifications:list':
296
+ return print(await client.get(withQuery('/notifications', {
297
+ workspace_id: flags.workspaceId,
298
+ post_id: flags.postId,
299
+ since: flags.since,
300
+ type: flags.type,
301
+ limit: flags.limit,
302
+ })), flags);
303
+
304
+ case 'x:quota':
305
+ return print(await client.get(withQuery('/x-posting/quota', { workspace_id: flags.workspaceId })), flags);
306
+
307
+ case 'webhooks:list':
308
+ return print(await client.get(withQuery('/webhooks', { workspace_id: flags.workspaceId })), flags);
309
+ case 'webhooks:create':
310
+ return print(await client.post('/webhooks', {
311
+ url: required(flags.url || positional[0], 'url'),
312
+ workspace_id: flags.workspaceId,
313
+ description: flags.description,
314
+ events: csv(flags.events),
315
+ }), flags);
316
+ case 'webhooks:update':
317
+ return print(await client.patch(`/webhooks/${required(positional[0] || flags.id, 'webhook id')}`, clean({
318
+ url: flags.url,
319
+ workspace_id: flags.workspaceId,
320
+ description: flags.description,
321
+ events: flags.events ? csv(flags.events) : undefined,
322
+ is_active: flags.active === undefined ? undefined : booleanFlag(flags.active),
323
+ })), flags);
324
+ case 'webhooks:delete':
325
+ return print(await client.delete(`/webhooks/${required(positional[0] || flags.id, 'webhook id')}`), flags);
326
+ case 'webhooks:test':
327
+ return print(await client.post(`/webhooks/${required(positional[0] || flags.id, 'webhook id')}/test`, {}), flags);
328
+
329
+ default:
330
+ throw new Error(`Unknown command: ${command}. Run posterly help.`);
331
+ }
332
+ }
333
+
334
+ function parseArgs(args) {
335
+ const [command, ...rest] = args;
336
+ const flags = {};
337
+ const positional = [];
338
+
339
+ for (let i = 0; i < rest.length; i += 1) {
340
+ const arg = rest[i];
341
+ if (!arg.startsWith('--')) {
342
+ positional.push(arg);
343
+ continue;
344
+ }
345
+ const eq = arg.indexOf('=');
346
+ const rawKey = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
347
+ const key = camel(rawKey);
348
+ if (eq !== -1) {
349
+ flags[key] = arg.slice(eq + 1);
350
+ continue;
351
+ }
352
+ const next = rest[i + 1];
353
+ if (!next || next.startsWith('--')) {
354
+ flags[key] = true;
355
+ } else {
356
+ flags[key] = next;
357
+ i += 1;
358
+ }
359
+ }
360
+
361
+ return { command, flags, positional };
362
+ }
363
+
364
+ async function createClient(flags) {
365
+ const config = await readConfig();
366
+ const apiKey = flags.apiKey || process.env.POSTERLY_API_KEY || config.apiKey;
367
+ const baseUrl = normalizeBaseUrl(flags.url || process.env.POSTERLY_URL || config.baseUrl || DEFAULT_BASE_URL);
368
+ if (!apiKey) throw new Error('Missing API key. Run `posterly auth:key pst_live_...` or set POSTERLY_API_KEY.');
369
+
370
+ async function request(method, path, body) {
371
+ const res = await fetch(`${baseUrl}/api/v1${path}`, {
372
+ method,
373
+ headers: clean({
374
+ Authorization: `Bearer ${apiKey}`,
375
+ Accept: 'application/json',
376
+ 'Content-Type': body === undefined ? undefined : 'application/json',
377
+ 'X-Posterly-Source': 'cli',
378
+ }),
379
+ body: body === undefined ? undefined : JSON.stringify(body),
380
+ });
381
+ const text = await res.text();
382
+ const data = text ? safeJson(text) : {};
383
+ if (!res.ok) {
384
+ const error = new Error(data?.error || data?.message || `HTTP ${res.status}`);
385
+ error.response = data;
386
+ error.status = res.status;
387
+ throw error;
388
+ }
389
+ return data;
390
+ }
391
+
392
+ return {
393
+ get: (path) => request('GET', path),
394
+ post: (path, body) => request('POST', path, body),
395
+ put: (path, body) => request('PUT', path, body),
396
+ patch: (path, body) => request('PATCH', path, body),
397
+ delete: (path, body) => request('DELETE', path, body),
398
+ };
399
+ }
400
+
401
+ async function saveKey(key, flags) {
402
+ const apiKey = key || flags.apiKey || process.env.POSTERLY_API_KEY;
403
+ if (!apiKey) throw new Error('Pass an API key: posterly auth:key pst_live_...');
404
+ await mkdir(CONFIG_DIR, { recursive: true });
405
+ const config = {
406
+ apiKey,
407
+ baseUrl: normalizeBaseUrl(flags.url || process.env.POSTERLY_URL || DEFAULT_BASE_URL),
408
+ updatedAt: new Date().toISOString(),
409
+ };
410
+ await writeFile(CONFIG_FILE, `${JSON.stringify(config, null, 2)}\n`, 'utf8');
411
+ return print({ saved: true, config_file: CONFIG_FILE, base_url: config.baseUrl }, flags);
412
+ }
413
+
414
+ async function authLogin(flags) {
415
+ const baseUrl = normalizeBaseUrl(flags.url || process.env.POSTERLY_URL || DEFAULT_BASE_URL);
416
+ const redirectUri = `http://127.0.0.1:${OAUTH_CALLBACK_PORT}${OAUTH_CALLBACK_PATH}`;
417
+ const state = randomBytes(18).toString('base64url');
418
+ const codeVerifier = randomBytes(48).toString('base64url');
419
+ const codeChallenge = createHash('sha256').update(codeVerifier).digest('base64url');
420
+
421
+ const authorizationUrl = `${baseUrl}/oauth/authorize?${new URLSearchParams({
422
+ response_type: 'code',
423
+ client_id: OAUTH_CLIENT_ID,
424
+ redirect_uri: redirectUri,
425
+ scope: OAUTH_SCOPES.join(' '),
426
+ state,
427
+ code_challenge: codeChallenge,
428
+ code_challenge_method: 'S256',
429
+ })}`;
430
+
431
+ const loginPromise = waitForOAuthCallback({
432
+ baseUrl,
433
+ redirectUri,
434
+ state,
435
+ codeVerifier,
436
+ });
437
+
438
+ if (flags.noOpen) {
439
+ process.stderr.write(`Open this URL to authorize posterly CLI:\n${authorizationUrl}\n`);
440
+ } else {
441
+ openBrowser(authorizationUrl);
442
+ process.stderr.write('Opening browser for posterly CLI authorization...\n');
443
+ }
444
+
445
+ const token = await loginPromise;
446
+ await mkdir(CONFIG_DIR, { recursive: true });
447
+ const config = {
448
+ apiKey: token.access_token,
449
+ baseUrl,
450
+ authType: 'oauth',
451
+ scopes: String(token.scope || '').split(/\s+/).filter(Boolean),
452
+ expiresAt: token.expires_in ? new Date(Date.now() + Number(token.expires_in) * 1000).toISOString() : null,
453
+ updatedAt: new Date().toISOString(),
454
+ };
455
+ await writeFile(CONFIG_FILE, `${JSON.stringify(config, null, 2)}\n`, 'utf8');
456
+
457
+ return print({
458
+ authenticated: true,
459
+ source: 'oauth',
460
+ config_file: CONFIG_FILE,
461
+ base_url: baseUrl,
462
+ scopes: config.scopes,
463
+ expires_at: config.expiresAt,
464
+ }, flags);
465
+ }
466
+
467
+ function waitForOAuthCallback({ baseUrl, redirectUri, state, codeVerifier }) {
468
+ return new Promise((resolve, reject) => {
469
+ const timeout = setTimeout(() => {
470
+ server.close();
471
+ reject(new Error('Timed out waiting for OAuth callback. Run `posterly auth:login` again.'));
472
+ }, 5 * 60 * 1000);
473
+
474
+ const server = createServer(async (req, res) => {
475
+ try {
476
+ const currentUrl = new URL(req.url || '/', `http://127.0.0.1:${OAUTH_CALLBACK_PORT}`);
477
+ if (currentUrl.pathname !== OAUTH_CALLBACK_PATH) {
478
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
479
+ res.end('Not found');
480
+ return;
481
+ }
482
+
483
+ const returnedState = currentUrl.searchParams.get('state') || '';
484
+ if (returnedState !== state) {
485
+ throw new Error('OAuth state mismatch. Authorization was not completed.');
486
+ }
487
+
488
+ const oauthError = currentUrl.searchParams.get('error');
489
+ if (oauthError) {
490
+ throw new Error(currentUrl.searchParams.get('error_description') || oauthError);
491
+ }
492
+
493
+ const code = currentUrl.searchParams.get('code');
494
+ if (!code) throw new Error('OAuth callback did not include an authorization code.');
495
+
496
+ const token = await exchangeOAuthCode({
497
+ baseUrl,
498
+ code,
499
+ redirectUri,
500
+ codeVerifier,
501
+ });
502
+
503
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
504
+ res.end(successHtml());
505
+ clearTimeout(timeout);
506
+ server.close();
507
+ resolve(token);
508
+ } catch (error) {
509
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
510
+ res.end(errorHtml(error?.message || String(error)));
511
+ clearTimeout(timeout);
512
+ server.close();
513
+ reject(error);
514
+ }
515
+ });
516
+
517
+ server.on('error', (error) => {
518
+ clearTimeout(timeout);
519
+ reject(new Error(`Could not start local OAuth callback server on port ${OAUTH_CALLBACK_PORT}: ${error.message}`));
520
+ });
521
+
522
+ server.listen(OAUTH_CALLBACK_PORT, '127.0.0.1');
523
+ });
524
+ }
525
+
526
+ async function exchangeOAuthCode({ baseUrl, code, redirectUri, codeVerifier }) {
527
+ const body = new URLSearchParams({
528
+ grant_type: 'authorization_code',
529
+ client_id: OAUTH_CLIENT_ID,
530
+ code,
531
+ redirect_uri: redirectUri,
532
+ code_verifier: codeVerifier,
533
+ });
534
+
535
+ const res = await fetch(`${baseUrl}/api/oauth/token`, {
536
+ method: 'POST',
537
+ headers: {
538
+ Accept: 'application/json',
539
+ 'Content-Type': 'application/x-www-form-urlencoded',
540
+ },
541
+ body,
542
+ });
543
+ const text = await res.text();
544
+ const data = text ? safeJson(text) : {};
545
+ if (!res.ok) {
546
+ throw new Error(data?.error_description || data?.error || `OAuth token exchange failed: HTTP ${res.status}`);
547
+ }
548
+ return data;
549
+ }
550
+
551
+ function openBrowser(url) {
552
+ const command = process.platform === 'darwin'
553
+ ? 'open'
554
+ : process.platform === 'win32'
555
+ ? 'cmd'
556
+ : 'xdg-open';
557
+ const args = process.platform === 'win32'
558
+ ? ['/c', 'start', '', url]
559
+ : [url];
560
+ const child = spawn(command, args, { detached: true, stdio: 'ignore' });
561
+ child.on('error', () => {
562
+ process.stderr.write(`Could not open a browser automatically. Open this URL instead:\n${url}\n`);
563
+ });
564
+ child.unref();
565
+ }
566
+
567
+ function successHtml() {
568
+ return '<!doctype html><title>posterly CLI connected</title><body style="font-family:system-ui;margin:3rem"><h1>posterly CLI connected</h1><p>You can close this window and return to your terminal.</p></body>';
569
+ }
570
+
571
+ function errorHtml(message) {
572
+ return `<!doctype html><title>posterly CLI authorization failed</title><body style="font-family:system-ui;margin:3rem"><h1>Authorization failed</h1><p>${escapeHtml(message)}</p></body>`;
573
+ }
574
+
575
+ async function authStatus(flags) {
576
+ const config = await readConfig();
577
+ const envKey = Boolean(process.env.POSTERLY_API_KEY);
578
+ return print({
579
+ authenticated: Boolean(envKey || config.apiKey),
580
+ source: envKey ? 'env' : config.apiKey ? 'config' : null,
581
+ base_url: process.env.POSTERLY_URL || config.baseUrl || DEFAULT_BASE_URL,
582
+ config_file: CONFIG_FILE,
583
+ auth_type: envKey ? 'env' : config.authType || (config.apiKey ? 'api_key' : null),
584
+ scopes: config.scopes,
585
+ expires_at: config.expiresAt,
586
+ }, flags);
587
+ }
588
+
589
+ async function logout(flags) {
590
+ if (existsSync(CONFIG_FILE)) await rm(CONFIG_FILE);
591
+ return print({ logged_out: true, config_file: CONFIG_FILE }, flags);
592
+ }
593
+
594
+ async function readConfig() {
595
+ try {
596
+ return JSON.parse(await readFile(CONFIG_FILE, 'utf8'));
597
+ } catch {
598
+ return {};
599
+ }
600
+ }
601
+
602
+ async function postPayloadFromFlags(flags) {
603
+ if (flags.file) return validatePostPayload(await readJson(required(flags.file, '--file')));
604
+ return clean({
605
+ account_id: flags.accountId,
606
+ username: flags.username,
607
+ platform: normalizePlatform(flags.platform, { supportedOnly: true }),
608
+ caption: flags.caption,
609
+ scheduled_at: flags.scheduledAt,
610
+ post_type: flags.postType,
611
+ media_url: flags.mediaUrl,
612
+ media_urls: csv(flags.mediaUrls),
613
+ workspace_id: flags.workspaceId,
614
+ metadata: jsonFlag(flags.metadata),
615
+ settings: jsonFlag(flags.settings || flags.platformSettings),
616
+ reel_cover_url: flags.reelCoverUrl,
617
+ reel_cover_method: flags.reelCoverMethod,
618
+ reel_thumb_offset: flags.reelThumbOffset ? Number(flags.reelThumbOffset) : undefined,
619
+ group_id: flags.groupId,
620
+ release_id: flags.releaseId,
621
+ });
622
+ }
623
+
624
+ async function updatePayloadFromFlags(flags) {
625
+ if (flags.file) return readJson(required(flags.file, '--file'));
626
+ return clean({
627
+ caption: flags.caption,
628
+ scheduled_at: flags.scheduledAt,
629
+ post_type: flags.postType,
630
+ media_url: flags.mediaUrl,
631
+ media_urls: csv(flags.mediaUrls),
632
+ metadata: jsonFlag(flags.metadata),
633
+ settings: jsonFlag(flags.settings || flags.platformSettings),
634
+ reel_cover_url: flags.reelCoverUrl,
635
+ reel_cover_method: flags.reelCoverMethod,
636
+ reel_thumb_offset: flags.reelThumbOffset ? Number(flags.reelThumbOffset) : undefined,
637
+ });
638
+ }
639
+
640
+ async function mediaUploadPayload(flags, positional) {
641
+ const filePath = required(flags.file || positional[0], '--file');
642
+ const buffer = await readFile(filePath);
643
+ return {
644
+ filename: flags.filename || path.basename(filePath),
645
+ content_type: flags.contentType || guessContentType(filePath),
646
+ data: buffer.toString('base64'),
647
+ };
648
+ }
649
+
650
+ async function videoPayloadFromFlags(flags) {
651
+ if (flags.file) return readJson(required(flags.file, '--file'));
652
+ return clean({
653
+ prompt: required(flags.prompt, '--prompt'),
654
+ negative_prompt: flags.negativePrompt,
655
+ aspect_ratio: flags.aspectRatio,
656
+ duration_seconds: flags.durationSeconds ? Number(flags.durationSeconds) : undefined,
657
+ resolution: flags.resolution,
658
+ model: flags.model,
659
+ image_url: flags.imageUrl,
660
+ end_image_url: flags.endImageUrl,
661
+ reference_images: jsonFlag(flags.referenceImages),
662
+ generate_audio: flags.generateAudio === undefined ? undefined : booleanFlag(flags.generateAudio),
663
+ source_video_url: flags.sourceVideoUrl,
664
+ });
665
+ }
666
+
667
+ async function videoFunctionPayloadFromFlags(flags, positional) {
668
+ if (flags.file) return readJson(required(flags.file, '--file'));
669
+ const params = jsonFlag(flags.params, {});
670
+ return {
671
+ identifier: required(flags.identifier || positional[0], 'identifier'),
672
+ functionName: required(flags.functionName || flags.function || positional[1], 'functionName'),
673
+ params: clean({
674
+ ...params,
675
+ model: flags.model,
676
+ duration_seconds: flags.durationSeconds ? Number(flags.durationSeconds) : undefined,
677
+ resolution: flags.resolution,
678
+ output: flags.output,
679
+ prompt: flags.prompt,
680
+ negative_prompt: flags.negativePrompt,
681
+ aspect_ratio: flags.aspectRatio,
682
+ image_url: flags.imageUrl,
683
+ end_image_url: flags.endImageUrl,
684
+ reference_images: jsonFlag(flags.referenceImages),
685
+ generate_audio: flags.generateAudio === undefined ? undefined : booleanFlag(flags.generateAudio),
686
+ source_video_url: flags.sourceVideoUrl,
687
+ }),
688
+ };
689
+ }
690
+
691
+ async function oauthClientPayload(flags, positional, options) {
692
+ if (flags.file) return readJson(required(flags.file, '--file'));
693
+ return clean({
694
+ client_name: options.creating
695
+ ? required(flags.clientName || flags.name || positional[0], '--client-name')
696
+ : (flags.clientName || flags.name),
697
+ description: flags.description,
698
+ homepage: flags.homepage,
699
+ allowed_redirect_uris: flags.redirectUris ? csv(flags.redirectUris) : flags.redirectUri ? [flags.redirectUri] : undefined,
700
+ default_scopes: flags.scopes ? csv(flags.scopes) : undefined,
701
+ is_active: flags.active === undefined ? undefined : booleanFlag(flags.active),
702
+ });
703
+ }
704
+
705
+ async function readJson(file) {
706
+ return JSON.parse(await readFile(file, 'utf8'));
707
+ }
708
+
709
+ async function readJsonArray(file) {
710
+ const value = await readJson(file);
711
+ if (!Array.isArray(value)) throw new Error('--file must contain a JSON array of post payloads');
712
+ return value;
713
+ }
714
+
715
+ function withQuery(pathname, params) {
716
+ const query = new URLSearchParams();
717
+ for (const [key, value] of Object.entries(params)) {
718
+ if (value === undefined || value === null || value === '' || value === false) continue;
719
+ query.set(key, String(value));
720
+ }
721
+ const qs = query.toString();
722
+ return qs ? `${pathname}?${qs}` : pathname;
723
+ }
724
+
725
+ function csv(value) {
726
+ if (value === undefined || value === null || value === '') return undefined;
727
+ if (Array.isArray(value)) return value;
728
+ return String(value).split(',').map((item) => item.trim()).filter(Boolean);
729
+ }
730
+
731
+ function jsonFlag(value, fallback = undefined) {
732
+ if (value === undefined || value === null || value === '') return fallback;
733
+ if (typeof value !== 'string') return value;
734
+ return JSON.parse(value);
735
+ }
736
+
737
+ function clean(obj) {
738
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => value !== undefined));
739
+ }
740
+
741
+ function required(value, label) {
742
+ if (value === undefined || value === null || value === '') throw new Error(`${label} is required`);
743
+ return value;
744
+ }
745
+
746
+ function validatePostPayload(payload) {
747
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
748
+ throw new Error('Post payload must be a JSON object');
749
+ }
750
+ return clean({
751
+ ...payload,
752
+ platform: normalizePlatform(payload.platform, { supportedOnly: true }),
753
+ });
754
+ }
755
+
756
+ function normalizePlatform(value, options = {}) {
757
+ if (value === undefined || value === null || value === '') return undefined;
758
+ const canonical = PLATFORM_MANIFEST.platformAliases[normalizeManifestKey(value)];
759
+ if (!canonical) {
760
+ throw new Error(`Unknown platform "${value}". Supported platforms: ${formatList(PLATFORM_MANIFEST.supportedPlatformIds)}.`);
761
+ }
762
+ const platform = PLATFORM_MANIFEST.platforms.find((item) => item.id === canonical);
763
+ if (!platform) throw new Error(`Unknown platform "${value}".`);
764
+ if (options.supportedOnly && platform.status !== 'supported') {
765
+ throw new Error(`${platform.label} is planned, not supported yet.`);
766
+ }
767
+ if (!options.includePlanned && platform.status === 'planned') {
768
+ throw new Error(`${platform.label} is planned. Re-run with --include-planned to inspect planned platform schemas.`);
769
+ }
770
+ return canonical;
771
+ }
772
+
773
+ function normalizeConnectTarget(value, options = {}) {
774
+ if (value === undefined || value === null || value === '') return undefined;
775
+ const canonical = PLATFORM_MANIFEST.connectAliases[normalizeManifestKey(value)];
776
+ if (!canonical) {
777
+ throw new Error(`Unknown connection target "${value}". Known targets: ${formatList(PLATFORM_MANIFEST.connectTargetIds)}.`);
778
+ }
779
+ const target = PLATFORM_MANIFEST.connectTargets.find((item) => item.id === canonical);
780
+ if (!target) throw new Error(`Unknown connection target "${value}".`);
781
+ if (!options.includePlanned && target.status === 'planned') {
782
+ throw new Error(`${target.label} is planned. Re-run with --include-planned to inspect planned connection handoff details.`);
783
+ }
784
+ return canonical;
785
+ }
786
+
787
+ function validateHelperName(value) {
788
+ if (!PLATFORM_HELPER_NAMES.includes(value)) {
789
+ throw new Error(`Unknown helper "${value}". Available helpers: ${formatList(PLATFORM_HELPER_NAMES)}.`);
790
+ }
791
+ return value;
792
+ }
793
+
794
+ function validatePostStatus(value) {
795
+ const status = String(value || '').trim().toLowerCase();
796
+ const allowed = ['scheduled', 'paused', 'draft'];
797
+ if (!allowed.includes(status)) {
798
+ throw new Error(`Unknown target status "${value}". Allowed statuses: ${formatList(allowed)}.`);
799
+ }
800
+ return status;
801
+ }
802
+
803
+ function normalizeManifestKey(value) {
804
+ return String(value || '').trim().toLowerCase().replace(/[\s-]+/g, '_');
805
+ }
806
+
807
+ function formatList(values) {
808
+ return values.join(', ');
809
+ }
810
+
811
+ function booleanFlag(value) {
812
+ if (value === true || value === 'true' || value === '1') return true;
813
+ if (value === false || value === 'false' || value === '0') return false;
814
+ throw new Error('Boolean flag must be true or false');
815
+ }
816
+
817
+ function flagEnabled(value) {
818
+ return value === true || value === 'true' || value === '1';
819
+ }
820
+
821
+ function normalizeBaseUrl(value) {
822
+ return String(value || DEFAULT_BASE_URL).replace(/\/$/, '');
823
+ }
824
+
825
+ function safeJson(text) {
826
+ try {
827
+ return JSON.parse(text);
828
+ } catch {
829
+ return { text };
830
+ }
831
+ }
832
+
833
+ function escapeHtml(value) {
834
+ return String(value)
835
+ .replace(/&/g, '&amp;')
836
+ .replace(/</g, '&lt;')
837
+ .replace(/>/g, '&gt;')
838
+ .replace(/"/g, '&quot;')
839
+ .replace(/'/g, '&#39;');
840
+ }
841
+
842
+ function print(value, flags = {}) {
843
+ const json = flags.pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value);
844
+ process.stdout.write(`${json}\n`);
845
+ }
846
+
847
+ function printError(error) {
848
+ const payload = {
849
+ error: error?.message || String(error),
850
+ status: error?.status,
851
+ response: error?.response,
852
+ };
853
+ process.stderr.write(`${JSON.stringify(clean(payload), null, 2)}\n`);
854
+ }
855
+
856
+ function camel(value) {
857
+ return value.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
858
+ }
859
+
860
+ function guessContentType(filename) {
861
+ const ext = filename.split('.').pop()?.toLowerCase();
862
+ const map = {
863
+ jpg: 'image/jpeg',
864
+ jpeg: 'image/jpeg',
865
+ png: 'image/png',
866
+ gif: 'image/gif',
867
+ webp: 'image/webp',
868
+ mp4: 'video/mp4',
869
+ mov: 'video/quicktime',
870
+ webm: 'video/webm',
871
+ };
872
+ return map[ext] || 'application/octet-stream';
873
+ }