@postonus/cli 0.1.22 → 0.1.24

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.js CHANGED
@@ -28,9 +28,9 @@ var PLAN_CONFIGS = {
28
28
  perPlatformMonthlyPosts: { TWITTER: 100 },
29
29
  mediaStorageGb: 10,
30
30
  vaCredits: 60,
31
- requestsPerMinute: 120,
32
- requestsPerMinutePerKey: 60,
33
- webRequestsPerMinute: 300,
31
+ requestsPerMinute: 600,
32
+ requestsPerMinutePerKey: 300,
33
+ webRequestsPerMinute: 600,
34
34
  features: [
35
35
  "Calendar & queue management",
36
36
  "Per-channel post overrides",
@@ -56,9 +56,9 @@ var PLAN_CONFIGS = {
56
56
  perPlatformMonthlyPosts: { TWITTER: 500 },
57
57
  mediaStorageGb: 50,
58
58
  vaCredits: 300,
59
- requestsPerMinute: 600,
60
- requestsPerMinutePerKey: 300,
61
- webRequestsPerMinute: 600,
59
+ requestsPerMinute: 1800,
60
+ requestsPerMinutePerKey: 900,
61
+ webRequestsPerMinute: 1200,
62
62
  features: [
63
63
  "Everything in Hobby, plus:",
64
64
  "Growth Autopilots (repurpose top posts across channels)",
@@ -82,9 +82,9 @@ var PLAN_CONFIGS = {
82
82
  mediaStorageGb: UNLIMITED,
83
83
  vaCredits: UNLIMITED,
84
84
  // Finite on purpose — see the `requestsPerMinute` doc comment.
85
- requestsPerMinute: 2e3,
86
- requestsPerMinutePerKey: 1e3,
87
- webRequestsPerMinute: 1200,
85
+ requestsPerMinute: 6e3,
86
+ requestsPerMinutePerKey: 3e3,
87
+ webRequestsPerMinute: 2400,
88
88
  features: ["Everything in Pro, plus:", "Onboarding call with founders", "Dedicated support"]
89
89
  }
90
90
  };
@@ -103,9 +103,9 @@ var TRIAL_PLAN_CONFIG = {
103
103
  perPlatformMonthlyPosts: { TWITTER: 0 },
104
104
  mediaStorageGb: 2,
105
105
  vaCredits: 30,
106
- requestsPerMinute: 120,
107
- requestsPerMinutePerKey: 60,
108
- webRequestsPerMinute: 300,
106
+ requestsPerMinute: 600,
107
+ requestsPerMinutePerKey: 300,
108
+ webRequestsPerMinute: 600,
109
109
  features: []
110
110
  };
111
111
  var PLAN_LABELS = {
@@ -209,91 +209,6 @@ var FILE_TYPE_EXTENSIONS = {
209
209
  var FILE_SCENARIOS = ["post_attachments", "user_avatar"];
210
210
  var MAX_FILE_SIZE_BYTES = Math.max(...Object.values(scenarios).map((s) => s.maxSize));
211
211
 
212
- // ../../packages/app-config/src/posting-times.ts
213
- var RECOMMENDED_POSTING_TIMES = {
214
- INSTAGRAM: [
215
- { dayOfWeek: 1, startTime: "11:00", endTime: "13:00", strength: 5 },
216
- { dayOfWeek: 2, startTime: "10:00", endTime: "13:00", strength: 5 },
217
- { dayOfWeek: 3, startTime: "11:00", endTime: "13:00", strength: 5 },
218
- { dayOfWeek: 4, startTime: "11:00", endTime: "12:00", strength: 4 },
219
- { dayOfWeek: 5, startTime: "12:00", endTime: "14:00", strength: 3 },
220
- { dayOfWeek: 6, startTime: "10:00", endTime: "11:00", strength: 2 }
221
- ],
222
- FACEBOOK: [
223
- { dayOfWeek: 2, startTime: "09:00", endTime: "13:00", strength: 5 },
224
- { dayOfWeek: 3, startTime: "09:00", endTime: "13:00", strength: 5 },
225
- { dayOfWeek: 4, startTime: "09:00", endTime: "13:00", strength: 4 },
226
- { dayOfWeek: 1, startTime: "10:00", endTime: "12:00", strength: 3 },
227
- { dayOfWeek: 5, startTime: "10:00", endTime: "11:00", strength: 3 },
228
- { dayOfWeek: 6, startTime: "09:00", endTime: "11:00", strength: 2 }
229
- ],
230
- LINKEDIN: [
231
- { dayOfWeek: 2, startTime: "08:00", endTime: "10:00", strength: 5 },
232
- { dayOfWeek: 3, startTime: "08:00", endTime: "10:00", strength: 5 },
233
- { dayOfWeek: 4, startTime: "09:00", endTime: "11:00", strength: 4 },
234
- { dayOfWeek: 2, startTime: "12:00", endTime: "13:00", strength: 3 },
235
- { dayOfWeek: 3, startTime: "12:00", endTime: "13:00", strength: 3 }
236
- ],
237
- LINKEDIN_PAGE: [
238
- { dayOfWeek: 2, startTime: "08:00", endTime: "10:00", strength: 5 },
239
- { dayOfWeek: 3, startTime: "08:00", endTime: "10:00", strength: 5 },
240
- { dayOfWeek: 4, startTime: "09:00", endTime: "11:00", strength: 4 }
241
- ],
242
- TWITTER: [
243
- { dayOfWeek: 2, startTime: "09:00", endTime: "11:00", strength: 5 },
244
- { dayOfWeek: 3, startTime: "09:00", endTime: "11:00", strength: 5 },
245
- { dayOfWeek: 4, startTime: "09:00", endTime: "11:00", strength: 4 },
246
- { dayOfWeek: 1, startTime: "09:00", endTime: "10:00", strength: 3 },
247
- { dayOfWeek: 5, startTime: "09:00", endTime: "10:00", strength: 3 },
248
- { dayOfWeek: 3, startTime: "14:00", endTime: "15:00", strength: 2 }
249
- ],
250
- TIKTOK: [
251
- { dayOfWeek: 2, startTime: "06:00", endTime: "10:00", strength: 5 },
252
- { dayOfWeek: 4, startTime: "07:00", endTime: "11:00", strength: 5 },
253
- { dayOfWeek: 2, startTime: "19:00", endTime: "21:00", strength: 4 },
254
- { dayOfWeek: 4, startTime: "19:00", endTime: "21:00", strength: 4 },
255
- { dayOfWeek: 5, startTime: "16:00", endTime: "18:00", strength: 3 },
256
- { dayOfWeek: 3, startTime: "09:00", endTime: "10:00", strength: 3 }
257
- ],
258
- PINTEREST: [
259
- { dayOfWeek: 5, startTime: "15:00", endTime: "17:00", strength: 4 },
260
- { dayOfWeek: 6, startTime: "08:00", endTime: "11:00", strength: 5 },
261
- { dayOfWeek: 0, startTime: "20:00", endTime: "22:00", strength: 4 },
262
- { dayOfWeek: 2, startTime: "20:00", endTime: "22:00", strength: 3 }
263
- ],
264
- YOUTUBE: [
265
- { dayOfWeek: 4, startTime: "14:00", endTime: "16:00", strength: 4 },
266
- { dayOfWeek: 5, startTime: "14:00", endTime: "16:00", strength: 5 },
267
- { dayOfWeek: 6, startTime: "09:00", endTime: "11:00", strength: 5 },
268
- { dayOfWeek: 0, startTime: "09:00", endTime: "11:00", strength: 4 }
269
- ]
270
- };
271
- function getRecommendedWindows(platform) {
272
- return RECOMMENDED_POSTING_TIMES[platform] ?? [];
273
- }
274
- function getConsensusWindows(platforms) {
275
- const buckets = /* @__PURE__ */ new Map();
276
- for (const platform of platforms) {
277
- for (const w of getRecommendedWindows(platform)) {
278
- const key = `${w.dayOfWeek}|${w.startTime}|${w.endTime}`;
279
- const existing = buckets.get(key);
280
- if (existing) {
281
- existing.strength += w.strength;
282
- existing.platforms.push(platform);
283
- } else {
284
- buckets.set(key, {
285
- dayOfWeek: w.dayOfWeek,
286
- startTime: w.startTime,
287
- endTime: w.endTime,
288
- strength: w.strength,
289
- platforms: [platform]
290
- });
291
- }
292
- }
293
- }
294
- return [...buckets.values()].filter((b) => b.platforms.length >= 2).toSorted((a, b) => b.strength - a.strength);
295
- }
296
-
297
212
  // src/index.ts
298
213
  import { Command, Option } from "commander";
299
214
 
@@ -3175,7 +3090,7 @@ function handleIntersectionResults(result, left, right) {
3175
3090
  const unrecKeys = /* @__PURE__ */ new Map();
3176
3091
  let unrecIssue;
3177
3092
  const keyIssues = /* @__PURE__ */ new Map();
3178
- const collect = (iss, side) => {
3093
+ const collect2 = (iss, side) => {
3179
3094
  let keys;
3180
3095
  if (iss.code === "unrecognized_keys" && !iss.path?.length) {
3181
3096
  unrecIssue ?? (unrecIssue = iss);
@@ -3196,11 +3111,11 @@ function handleIntersectionResults(result, left, right) {
3196
3111
  return true;
3197
3112
  };
3198
3113
  for (const iss of left.issues) {
3199
- if (!collect(iss, "l"))
3114
+ if (!collect2(iss, "l"))
3200
3115
  result.issues.push(iss);
3201
3116
  }
3202
3117
  for (const iss of right.issues) {
3203
- if (!collect(iss, "r"))
3118
+ if (!collect2(iss, "r"))
3204
3119
  result.issues.push(iss);
3205
3120
  }
3206
3121
  const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
@@ -6910,6 +6825,7 @@ var JsonValueSchema = lazy(
6910
6825
  ])
6911
6826
  );
6912
6827
  var DateInput = coerce_exports.date();
6828
+ var InstantInput = iso_exports.datetime({ offset: true, error: "Use an RFC 3339 time with an offset, e.g. 2026-08-01T09:30:00Z" }).transform((value2) => new Date(value2));
6913
6829
  var Uuid = string2().uuid();
6914
6830
  var IdPathParam = object({ id: Uuid });
6915
6831
  var DeletedSchema = object({ success: literal(true) });
@@ -6917,11 +6833,20 @@ var SuccessSchema = object({ success: literal(true) });
6917
6833
  var AggregateCount = coerce_exports.number().int();
6918
6834
 
6919
6835
  // ../../packages/api-contract/src/errors.ts
6836
+ var ViolationSchema = object({
6837
+ message: string2(),
6838
+ field: string2().optional(),
6839
+ platform: PlatformSchema.optional(),
6840
+ limit: number2().optional(),
6841
+ actual: number2().optional()
6842
+ });
6843
+ var ErrorDataSchema = object({ violations: array(ViolationSchema) });
6844
+ var ApiErrorSchema = object({ code: string2(), message: string2(), data: ErrorDataSchema });
6920
6845
  var publicErrors = {
6921
6846
  RATE_LIMITED: {
6922
6847
  status: 429,
6923
6848
  message: "Too many requests.",
6924
- data: object({ retryAfter: number2().int().optional() })
6849
+ data: ErrorDataSchema.extend({ retryAfter: number2().int().optional() })
6925
6850
  }
6926
6851
  };
6927
6852
  var authedErrors = {
@@ -7422,6 +7347,45 @@ var commentsContract = {
7422
7347
  resolve: tagged6.route({ method: "POST", path: "/comments/{id}/resolve", summary: "Resolve or reopen a comment" }).errors(writableErrors).input(object({ id: Uuid, resolved: boolean2() })).output(CommentSchema)
7423
7348
  };
7424
7349
 
7350
+ // ../../packages/api-contract/src/platforms.ts
7351
+ var PlatformLimitsSchema = object({
7352
+ maxChars: number2().int(),
7353
+ maxCharsWithMedia: number2().int().nullable(),
7354
+ /** `grapheme` where the platform counts an emoji as one; otherwise UTF-16 units. */
7355
+ countUnit: _enum(["grapheme", "utf16"]),
7356
+ maxTitleChars: number2().int().nullable(),
7357
+ supportsThreads: boolean2(),
7358
+ supportsFirstComment: boolean2(),
7359
+ maxFirstCommentChars: number2().int().nullable(),
7360
+ maxMediaCount: number2().int(),
7361
+ supportedMediaTypes: array(string2())
7362
+ });
7363
+ var PlatformRulesOutputSchema = object({
7364
+ platforms: array(PlatformLimitsSchema.extend({ platform: PlatformSchema }))
7365
+ });
7366
+ var BestTimeSlotSchema = object({
7367
+ scheduledAt: Timestamp,
7368
+ platforms: array(string2()),
7369
+ strength: number2(),
7370
+ /** Where the slot came from: the user's saved windows, research several platforms share, one platform's research, or a default. */
7371
+ source: _enum(["user", "consensus", "platform", "default"])
7372
+ });
7373
+ var BestTimesSchema = object({
7374
+ timezone: string2(),
7375
+ slots: array(BestTimeSlotSchema),
7376
+ /** Requested platforms with no research data; their slots are a default, not a recommendation. */
7377
+ platformsWithoutData: array(PlatformSchema)
7378
+ });
7379
+ var BestTimesInputSchema = object({
7380
+ platforms: array(PlatformSchema).min(1),
7381
+ count: coerce_exports.number().int().min(1).max(20).default(5)
7382
+ });
7383
+ var tagged7 = base.route({ tags: ["Platforms"] });
7384
+ var platformsContract = {
7385
+ rules: tagged7.route({ method: "GET", path: "/platforms/rules", summary: "Publishing limits for every platform" }).errors(orgErrors).output(PlatformRulesOutputSchema),
7386
+ bestTimes: tagged7.route({ method: "GET", path: "/best-times", summary: "Upcoming recommended send times" }).errors(orgErrors).input(BestTimesInputSchema).output(BestTimesSchema)
7387
+ };
7388
+
7425
7389
  // ../../packages/api-contract/src/integrations.ts
7426
7390
  var IntegrationConnectStatusSchema = _enum(["PENDING_SELECTION", "ACTIVE", "DISCONNECTED"]);
7427
7391
  var IntegrationTokenStatusSchema = _enum(["VALID", "EXPIRED", "UNKNOWN"]);
@@ -7449,7 +7413,9 @@ var IntegrationSchema = object({
7449
7413
  lastValidatedAt: Timestamp.nullable(),
7450
7414
  expiresAt: Timestamp.nullable(),
7451
7415
  autoRefreshUnavailable: boolean2(),
7452
- hasFailedSchedules: boolean2()
7416
+ hasFailedSchedules: boolean2(),
7417
+ /** The channel's publishing limits, the same values `GET /platforms/rules` reports for its platform. */
7418
+ limits: PlatformLimitsSchema
7453
7419
  });
7454
7420
  var UnhealthyIntegrationSchema = object({
7455
7421
  id: Uuid,
@@ -7540,10 +7506,10 @@ var DisconnectImpactSchema = object({
7540
7506
  strandedScheduleCount: number2().int(),
7541
7507
  isLastBinding: boolean2()
7542
7508
  });
7543
- var tagged7 = base.route({ tags: ["Integrations"] });
7544
- var internal2 = tagged7.meta({ internal: true });
7509
+ var tagged8 = base.route({ tags: ["Integrations"] });
7510
+ var internal2 = tagged8.meta({ internal: true });
7545
7511
  var integrationsContract = {
7546
- get: tagged7.route({ method: "GET", path: "/integrations", summary: "List active integrations with health" }).errors(orgErrors).output(array(IntegrationSchema)),
7512
+ get: tagged8.route({ method: "GET", path: "/integrations", summary: "List active integrations with health" }).errors(orgErrors).output(array(IntegrationSchema)),
7547
7513
  getCapacity: internal2.route({ method: "GET", path: "/integrations/capacity", summary: "Social-account plan capacity" }).errors(orgErrors).output(IntegrationCapacitySchema),
7548
7514
  listUnhealthy: internal2.route({ method: "GET", path: "/integrations/unhealthy", summary: "Integrations needing reconnect" }).errors(orgErrors).output(array(UnhealthyIntegrationSchema)),
7549
7515
  listAtRiskSchedules: internal2.route({
@@ -7552,7 +7518,7 @@ var integrationsContract = {
7552
7518
  summary: "Scheduled posts whose channel cannot currently publish"
7553
7519
  }).errors(orgErrors).output(array(AtRiskScheduleSchema)),
7554
7520
  listPendingSelection: internal2.route({ method: "GET", path: "/integrations/pending-selection", summary: "Channels stuck at the account picker" }).errors(orgErrors).output(array(PendingSelectionIntegrationSchema)),
7555
- connectIntegration: tagged7.route({ method: "POST", path: "/integrations/connect", summary: "Start an OAuth connect" }).errors(writableErrors).input(ConnectIntegrationInputSchema).output(object({ redirectUrl: string2() })),
7521
+ connectIntegration: tagged8.route({ method: "POST", path: "/integrations/connect", summary: "Start an OAuth connect" }).errors(writableErrors).input(ConnectIntegrationInputSchema).output(object({ redirectUrl: string2() })),
7556
7522
  connectCredentialIntegration: internal2.route({
7557
7523
  method: "POST",
7558
7524
  path: "/integrations/connect-with-credentials",
@@ -7649,17 +7615,17 @@ var FromUrlOutputSchema = object({
7649
7615
  publicUrl: string2(),
7650
7616
  type: MediaTypeSchema
7651
7617
  });
7652
- var tagged8 = base.route({ tags: ["Uploads"] });
7618
+ var tagged9 = base.route({ tags: ["Uploads"] });
7653
7619
  var uploadContract = {
7654
- initiateUpload: tagged8.route({ method: "POST", path: "/uploads/initiate", summary: "Get a signed URL to upload a file" }).errors(uploadErrors).input(InitiateUploadInputSchema).output(InitiateUploadOutputSchema),
7655
- completeUpload: tagged8.route({ method: "POST", path: "/uploads/complete", summary: "Complete an upload once its bytes are in storage" }).errors(uploadErrors).input(CompleteUploadInputSchema).output(CompleteUploadOutputSchema),
7620
+ initiateUpload: tagged9.route({ method: "POST", path: "/uploads/initiate", summary: "Get a signed URL to upload a file" }).errors(uploadErrors).input(InitiateUploadInputSchema).output(InitiateUploadOutputSchema),
7621
+ completeUpload: tagged9.route({ method: "POST", path: "/uploads/complete", summary: "Complete an upload once its bytes are in storage" }).errors(uploadErrors).input(CompleteUploadInputSchema).output(CompleteUploadOutputSchema),
7656
7622
  /** Org-scoped, not gated on `canWrite` — deleting is always allowed, even read-only. */
7657
- deleteFile: tagged8.route({ method: "DELETE", path: "/uploads/{uploadId}", summary: "Delete an uploaded file" }).errors(orgErrors).input(DeleteFileInputSchema).output(DeletedSchema),
7623
+ deleteFile: tagged9.route({ method: "DELETE", path: "/uploads/{uploadId}", summary: "Delete an uploaded file" }).errors(orgErrors).input(DeleteFileInputSchema).output(DeletedSchema),
7658
7624
  /**
7659
7625
  * Fetches a caller-supplied URL server-side (through `fetchPublicUrl`'s SSRF
7660
7626
  * guard) and stores the result as a completed upload.
7661
7627
  */
7662
- fromUrl: tagged8.route({
7628
+ fromUrl: tagged9.route({
7663
7629
  method: "POST",
7664
7630
  path: "/uploads/from-url",
7665
7631
  summary: "Import a file from a public URL",
@@ -7742,8 +7708,8 @@ var DeleteMediaOutputSchema = object({
7742
7708
  deletedIds: array(Uuid),
7743
7709
  blocked: array(object({ mediaId: Uuid, usedInPostsCount: number2().int() }))
7744
7710
  });
7745
- var tagged9 = base.route({ tags: ["Media library"] });
7746
- var internal3 = tagged9.meta({ internal: true });
7711
+ var tagged10 = base.route({ tags: ["Media library"] });
7712
+ var internal3 = tagged10.meta({ internal: true });
7747
7713
  var folderErrors = {
7748
7714
  ...writableErrors,
7749
7715
  FOLDER_CYCLE: { status: 422, message: "A folder cannot be moved inside itself." }
@@ -7830,19 +7796,19 @@ var enableSourceErrors = {
7830
7796
  ...writableErrors,
7831
7797
  NOT_CONFIGURED: { status: 412, message: "Source is not configured on this deployment." }
7832
7798
  };
7833
- var tagged10 = base.route({ tags: ["Media sources"] }).meta({ internal: true });
7799
+ var tagged11 = base.route({ tags: ["Media sources"] }).meta({ internal: true });
7834
7800
  var mediaSourcesContract = {
7835
- list: tagged10.route({ method: "GET", path: "/media-sources", summary: "List media source pickers and their status" }).errors(orgErrors).output(array(MediaSourceSchema)),
7836
- enable: tagged10.route({ method: "POST", path: "/media-sources/{sourceId}/enable", summary: "Enable a media source for this org" }).errors(enableSourceErrors).input(SourceIdInputSchema).output(DeletedSchema),
7837
- disable: tagged10.route({
7801
+ list: tagged11.route({ method: "GET", path: "/media-sources", summary: "List media source pickers and their status" }).errors(orgErrors).output(array(MediaSourceSchema)),
7802
+ enable: tagged11.route({ method: "POST", path: "/media-sources/{sourceId}/enable", summary: "Enable a media source for this org" }).errors(enableSourceErrors).input(SourceIdInputSchema).output(DeletedSchema),
7803
+ disable: tagged11.route({
7838
7804
  method: "POST",
7839
7805
  path: "/media-sources/{sourceId}/disable",
7840
7806
  summary: "Disable a media source for this org"
7841
7807
  }).errors(writableErrors).input(SourceIdInputSchema).output(DeletedSchema),
7842
- suggestSource: tagged10.route({ method: "POST", path: "/media-sources/suggestions", summary: "Suggest a media source not yet supported" }).errors(orgErrors).input(SuggestSourceInputSchema).output(DeletedSchema),
7843
- importAsset: tagged10.route({ method: "POST", path: "/media-sources/import", summary: "Import an asset picked from a media source" }).errors(writableErrors).input(ImportAssetInputSchema).output(ImportAssetOutputSchema),
7844
- unsplashTrending: tagged10.route({ method: "GET", path: "/media-sources/unsplash/trending", summary: "Unsplash curated/trending photos" }).errors(unsplashErrors).input(UnsplashPageInputSchema).output(UnsplashTrendingOutputSchema),
7845
- unsplashSearch: tagged10.route({ method: "GET", path: "/media-sources/unsplash/search", summary: "Search Unsplash photos" }).errors(unsplashErrors).input(UnsplashSearchInputSchema).output(UnsplashSearchOutputSchema)
7808
+ suggestSource: tagged11.route({ method: "POST", path: "/media-sources/suggestions", summary: "Suggest a media source not yet supported" }).errors(orgErrors).input(SuggestSourceInputSchema).output(DeletedSchema),
7809
+ importAsset: tagged11.route({ method: "POST", path: "/media-sources/import", summary: "Import an asset picked from a media source" }).errors(writableErrors).input(ImportAssetInputSchema).output(ImportAssetOutputSchema),
7810
+ unsplashTrending: tagged11.route({ method: "GET", path: "/media-sources/unsplash/trending", summary: "Unsplash curated/trending photos" }).errors(unsplashErrors).input(UnsplashPageInputSchema).output(UnsplashTrendingOutputSchema),
7811
+ unsplashSearch: tagged11.route({ method: "GET", path: "/media-sources/unsplash/search", summary: "Search Unsplash photos" }).errors(unsplashErrors).input(UnsplashSearchInputSchema).output(UnsplashSearchOutputSchema)
7846
7812
  };
7847
7813
 
7848
7814
  // ../../packages/api-contract/src/notifications.ts
@@ -7859,15 +7825,15 @@ var NotificationSchema = object({
7859
7825
  updatedAt: Timestamp
7860
7826
  });
7861
7827
  var WorkspaceUnreadCountSchema = object({ organizationId: string2(), unread: number2().int() });
7862
- var tagged11 = base.route({ tags: ["Notifications"] }).meta({ internal: true });
7828
+ var tagged12 = base.route({ tags: ["Notifications"] }).meta({ internal: true });
7863
7829
  var notificationsContract = {
7864
7830
  /** Full history across every workspace — backs the standalone /notifications page. */
7865
- list: tagged11.route({ method: "GET", path: "/notifications", summary: "List notifications across every workspace" }).errors(authedErrors).input(object({ limit: number2().int().positive().max(100).optional() })).output(object({ notifications: array(NotificationSchema) })),
7831
+ list: tagged12.route({ method: "GET", path: "/notifications", summary: "List notifications across every workspace" }).errors(authedErrors).input(object({ limit: number2().int().positive().max(100).optional() })).output(object({ notifications: array(NotificationSchema) })),
7866
7832
  /**
7867
7833
  * Bell-dropdown feed: current workspace + user-global rows, plus a compact
7868
7834
  * "other workspaces" unread summary.
7869
7835
  */
7870
- bellFeed: tagged11.route({ method: "GET", path: "/notifications/bell-feed", summary: "Get the bell-dropdown notification feed" }).errors(orgErrors).input(object({ limit: number2().int().positive().max(50).optional() })).output(
7836
+ bellFeed: tagged12.route({ method: "GET", path: "/notifications/bell-feed", summary: "Get the bell-dropdown notification feed" }).errors(orgErrors).input(object({ limit: number2().int().positive().max(50).optional() })).output(
7871
7837
  object({
7872
7838
  notifications: array(NotificationSchema),
7873
7839
  unread: object({
@@ -7877,8 +7843,8 @@ var notificationsContract = {
7877
7843
  })
7878
7844
  })
7879
7845
  ),
7880
- markRead: tagged11.route({ method: "POST", path: "/notifications/{id}/read", summary: "Mark one notification as read" }).errors({ ...authedErrors, NOT_FOUND: { message: "Notification not found." } }).input(object({ id: string2().min(1) })).output(object({ notification: NotificationSchema })),
7881
- markAllRead: tagged11.route({ method: "POST", path: "/notifications/mark-all-read", summary: "Mark every notification as read" }).errors(orgErrors).output(object({ updated: number2().int() }))
7846
+ markRead: tagged12.route({ method: "POST", path: "/notifications/{id}/read", summary: "Mark one notification as read" }).errors({ ...authedErrors, NOT_FOUND: { message: "Notification not found." } }).input(object({ id: string2().min(1) })).output(object({ notification: NotificationSchema })),
7847
+ markAllRead: tagged12.route({ method: "POST", path: "/notifications/mark-all-read", summary: "Mark every notification as read" }).errors(orgErrors).output(object({ updated: number2().int() }))
7882
7848
  };
7883
7849
 
7884
7850
  // ../../packages/api-contract/src/posts.ts
@@ -7953,17 +7919,32 @@ var hasContentOrMedia = (data) => Boolean(data.content && data.content.trim().le
7953
7919
  var CreatePostRowSchema = object({
7954
7920
  content: ContentField,
7955
7921
  media: array(PostMediaInputSchema).optional(),
7956
- scheduledAt: DateInput.optional()
7922
+ scheduledAt: InstantInput.optional()
7957
7923
  }).refine(hasContentOrMedia, "Add some content or media to your post");
7924
+ var ThreadSchema = array(string2().trim().min(1).max(DRAFT_MAX_CHARS)).min(2).max(MAX_THREAD_SEGMENTS);
7925
+ var DryRunField = boolean2().optional();
7926
+ var TargetFields = {
7927
+ /**
7928
+ * Every active channel on these platforms. The alternative to
7929
+ * `selectedIntegrations`, which names channels by id and is the only way to pick
7930
+ * between two channels on one platform.
7931
+ */
7932
+ platforms: array(PlatformSchema).min(1).optional(),
7933
+ thread: ThreadSchema.optional()
7934
+ };
7958
7935
  var CreatePostsInputSchema = object({
7959
7936
  rows: array(CreatePostRowSchema).min(1).max(50),
7960
- shared: object(SharedPostFields),
7937
+ shared: object({ ...SharedPostFields, ...TargetFields }),
7961
7938
  postAction: PostActionEnum.default("NEXT_WINDOW"),
7962
- stagger: object({ startAt: DateInput, intervalMinutes: number2().int().positive() }).optional()
7963
- }).refine((data) => data.postAction === "DRAFT" || Boolean(data.shared.selectedIntegrations?.length), {
7964
- message: "Select at least one platform",
7965
- path: ["shared", "selectedIntegrations"]
7966
- }).refine((data) => data.rows.length === 1 || !data.shared.integrationThreadSegments, {
7939
+ stagger: object({ startAt: DateInput, intervalMinutes: number2().int().positive() }).optional(),
7940
+ dryRun: DryRunField
7941
+ }).refine(
7942
+ (data) => data.postAction === "DRAFT" || Boolean(data.shared.selectedIntegrations?.length || data.shared.platforms?.length),
7943
+ { message: "Select at least one channel or platform", path: ["shared", "selectedIntegrations"] }
7944
+ ).refine((data) => !(data.shared.selectedIntegrations?.length && data.shared.platforms), {
7945
+ message: "Name channels by `selectedIntegrations` or `platforms`, not both",
7946
+ path: ["shared", "platforms"]
7947
+ }).refine((data) => data.rows.length === 1 || !(data.shared.integrationThreadSegments || data.shared.thread), {
7967
7948
  message: "Thread segments apply to a single post. Use autoThreadIntegrationIds to thread a bulk import.",
7968
7949
  path: ["shared", "integrationThreadSegments"]
7969
7950
  });
@@ -7971,19 +7952,34 @@ var UpdatePostInputSchema = object({
7971
7952
  id: Uuid,
7972
7953
  content: ContentField,
7973
7954
  media: array(PostMediaInputSchema).optional(),
7974
- scheduledAt: DateInput.optional(),
7975
- postAction: PostActionEnum.default("NEXT_WINDOW"),
7976
- ...SharedPostFields
7977
- }).refine(hasContentOrMedia, "Add some content or media to your post").refine((data) => data.postAction === "DRAFT" || Boolean(data.selectedIntegrations?.length), {
7978
- message: "Select at least one platform",
7979
- path: ["selectedIntegrations"]
7955
+ scheduledAt: InstantInput.nullable().optional(),
7956
+ postAction: PostActionEnum.optional(),
7957
+ /** Move named schedules individually. Applied after the rest of the update. */
7958
+ scheduleTimes: array(object({ scheduleId: Uuid, scheduledAt: InstantInput })).min(1).optional(),
7959
+ dryRun: DryRunField,
7960
+ ...SharedPostFields,
7961
+ ...TargetFields
7962
+ }).refine((data) => !(data.selectedIntegrations && data.platforms), {
7963
+ message: "Name channels by `selectedIntegrations` or `platforms`, not both",
7964
+ path: ["platforms"]
7965
+ }).refine((data) => !(data.content !== void 0 && data.thread), {
7966
+ message: "Send `content` or `thread`, not both: a thread carries its own text",
7967
+ path: ["thread"]
7968
+ }).refine((data) => !(data.scheduledAt && data.scheduleTimes), {
7969
+ message: "Send `scheduledAt` to move the whole post or `scheduleTimes` to move single schedules, not both",
7970
+ path: ["scheduleTimes"]
7980
7971
  });
7981
7972
  var ScheduleDraftInputSchema = object({
7982
7973
  id: Uuid,
7983
- scheduledAt: DateInput.optional(),
7974
+ scheduledAt: InstantInput.optional(),
7984
7975
  useOptimalTime: boolean2().optional(),
7985
7976
  // Required when the draft was saved with no channels; replaces them otherwise.
7986
- selectedIntegrations: array(string2()).min(1).optional()
7977
+ selectedIntegrations: array(string2()).min(1).optional(),
7978
+ platforms: array(PlatformSchema).min(1).optional(),
7979
+ dryRun: DryRunField
7980
+ }).refine((data) => !(data.selectedIntegrations && data.platforms), {
7981
+ message: "Name channels by `selectedIntegrations` or `platforms`, not both",
7982
+ path: ["platforms"]
7987
7983
  }).refine((data) => Boolean(data.scheduledAt) !== Boolean(data.useOptimalTime), {
7988
7984
  message: "Provide `scheduledAt` or set `useOptimalTime`, not both and not neither",
7989
7985
  path: ["scheduledAt"]
@@ -8023,7 +8019,7 @@ var RetryScheduleInputSchema = object({
8023
8019
  */
8024
8020
  attachmentMediaUrls: array(string2()).optional()
8025
8021
  });
8026
- var RescheduleInputSchema = object({ scheduleId: Uuid, scheduledAt: DateInput });
8022
+ var RescheduleInputSchema = object({ scheduleId: Uuid, scheduledAt: InstantInput });
8027
8023
  var BulkScheduleInWindowsInputSchema = object({
8028
8024
  scheduleIds: array(Uuid),
8029
8025
  horizonDays: number2().int().min(1).default(14),
@@ -8138,13 +8134,29 @@ var MediaMetadataSchema = object({
8138
8134
  */
8139
8135
  autoCover: object({ id: string2(), url: string2(), timestampMs: number2().int().nullable() }).nullable()
8140
8136
  });
8141
- var CreatePostsOutputSchema = object({
8142
- postId: string2().optional(),
8143
- postIds: array(string2()),
8144
- message: string2(),
8145
- scheduleCount: number2()
8137
+ var PostScheduleStateSchema = object({
8138
+ scheduleId: string2(),
8139
+ channelId: string2(),
8140
+ platform: PlatformSchema,
8141
+ channelName: string2(),
8142
+ scheduledAt: Timestamp.nullable(),
8143
+ status: _enum(SCHEDULE_STATUS_VALUES)
8146
8144
  });
8147
- var UpdatePostOutputSchema = object({ postId: string2(), message: string2() });
8145
+ var PostStateSchema = object({
8146
+ postId: string2(),
8147
+ content: string2(),
8148
+ thread: array(string2()).nullable(),
8149
+ media: array(object({ url: string2(), type: MediaTypeSchema, altText: string2().nullable() })),
8150
+ schedules: array(PostScheduleStateSchema),
8151
+ /** The post in the dashboard, for a human to take over. */
8152
+ url: string2(),
8153
+ /** `pending` while the workspace's review gate holds the post. */
8154
+ review: _enum(["pending"]).nullable(),
8155
+ /** True when the write was rehearsed with `dryRun` and nothing was stored. */
8156
+ dryRun: boolean2()
8157
+ });
8158
+ var CreatePostsOutputSchema = object({ posts: array(PostStateSchema) });
8159
+ var DeletePostOutputSchema = PostStateSchema.extend({ deletedFromPlatforms: boolean2() });
8148
8160
  var AddChannelsOutputSchema = object({ postId: string2(), scheduleCount: number2() });
8149
8161
  var BulkScheduleInWindowsOutputSchema = object({
8150
8162
  placed: array(object({ scheduleId: string2(), scheduledAt: Timestamp })),
@@ -8152,34 +8164,14 @@ var BulkScheduleInWindowsOutputSchema = object({
8152
8164
  });
8153
8165
  var DeletePostInputSchema = object({ id: Uuid, deleteRemote: boolean2().default(false) });
8154
8166
  var postDomainErrors = {
8155
- POST_QUOTA_EXCEEDED: {
8156
- status: 403,
8157
- message: "Post limit reached.",
8158
- data: object({
8159
- platform: PlatformSchema.optional(),
8160
- limit: number2().int().optional(),
8161
- used: number2().int().optional()
8162
- })
8163
- },
8167
+ POST_QUOTA_EXCEEDED: { status: 403, message: "Post limit reached.", data: ErrorDataSchema },
8164
8168
  PAYMENT_REQUIRED: {
8165
8169
  status: 402,
8166
8170
  message: "Choose a plan to schedule and publish."
8167
8171
  },
8168
- CONTENT_TOO_LONG: {
8169
- status: 400,
8170
- message: "Content exceeds the platform limit.",
8171
- data: object({ platform: PlatformSchema, limit: number2().int(), actual: number2().int() }).optional()
8172
- },
8173
- MEDIA_RULE_VIOLATED: {
8174
- status: 400,
8175
- message: "Media does not satisfy the platform rules.",
8176
- data: object({ platform: PlatformSchema, detail: string2() }).optional()
8177
- },
8178
- VIDEO_TOO_LONG: {
8179
- status: 400,
8180
- message: "Video exceeds the platform duration limit.",
8181
- data: object({ platform: PlatformSchema, detail: string2() }).optional()
8182
- },
8172
+ CONTENT_TOO_LONG: { status: 400, message: "Content exceeds the platform limit.", data: ErrorDataSchema },
8173
+ MEDIA_RULE_VIOLATED: { status: 400, message: "Media does not satisfy the platform rules.", data: ErrorDataSchema },
8174
+ VIDEO_TOO_LONG: { status: 400, message: "Video exceeds the platform duration limit.", data: ErrorDataSchema },
8183
8175
  SCHEDULE_IN_PAST: { status: 400, message: "Scheduled time must be in the future." },
8184
8176
  THREAD_NOT_ALLOWED: { status: 400, message: "Thread segments require explicit opt-in." },
8185
8177
  INVALID_INTEGRATIONS: { status: 400, message: "Some integrations are invalid or do not belong to you." },
@@ -8191,41 +8183,49 @@ var postDomainErrors = {
8191
8183
  message: "This channel cannot be changed from a retry. Edit it in the composer."
8192
8184
  },
8193
8185
  CHANNEL_ALREADY_SCHEDULED: { status: 409, message: "That channel already has a schedule on this post." },
8194
- REMOTE_DELETE_FAILED: {
8195
- status: 400,
8196
- message: "The platform refused to delete the post.",
8197
- data: object({ platform: PlatformSchema }).optional()
8198
- },
8186
+ REMOTE_DELETE_FAILED: { status: 400, message: "The platform refused to delete the post.", data: ErrorDataSchema },
8199
8187
  REMOTE_DELETE_NOT_SUPPORTED: {
8200
8188
  status: 400,
8201
8189
  message: "This platform cannot delete a published post through its API.",
8202
- data: object({ platform: PlatformSchema }).optional()
8203
- }
8204
- };
8205
- var tagged12 = base.route({ tags: ["Posts"] });
8206
- var internal4 = tagged12.meta({ internal: true });
8190
+ data: ErrorDataSchema
8191
+ },
8192
+ NOT_A_DRAFT: { status: 409, message: "That post is not a draft." },
8193
+ DRAFT_HAS_NO_CHANNELS: { status: 400, message: "Choose the channels to schedule this draft on." }
8194
+ };
8195
+ var tagged13 = base.route({ tags: ["Posts"] });
8196
+ var idempotent = tagged13.route({
8197
+ spec: (operation) => ({
8198
+ ...operation,
8199
+ parameters: [
8200
+ ...operation.parameters ?? [],
8201
+ {
8202
+ name: "Idempotency-Key",
8203
+ in: "header",
8204
+ required: false,
8205
+ schema: { type: "string", maxLength: 255 },
8206
+ description: "Repeating a key within 24 hours returns the first response and writes nothing again."
8207
+ }
8208
+ ]
8209
+ })
8210
+ });
8211
+ var internal4 = tagged13.meta({ internal: true });
8207
8212
  var postsContract = {
8208
- list: tagged12.route({ method: "GET", path: "/posts", summary: "List posts" }).errors(orgErrors).input(ListPostsInputSchema).output(PostsListOutputSchema),
8213
+ list: tagged13.route({ method: "GET", path: "/posts", summary: "List posts" }).errors(orgErrors).input(ListPostsInputSchema).output(PostsListOutputSchema),
8209
8214
  // Declared before `getById` so `/posts/counts` is not read as `/posts/{id}`.
8210
8215
  // Dashboard plumbing: the status segment row on `/posts`.
8211
8216
  counts: internal4.route({ method: "GET", path: "/posts/counts", summary: "Count posts per status" }).errors(orgErrors).input(CountPostsInputSchema).output(CountPostsOutputSchema),
8212
- getById: tagged12.route({ method: "GET", path: "/posts/{id}", summary: "Get a post" }).errors(orgErrors).input(IdPathParam).output(PostWithRelationsSchema),
8217
+ getById: tagged13.route({ method: "GET", path: "/posts/{id}", summary: "Get a post" }).errors(orgErrors).input(IdPathParam).output(PostWithRelationsSchema),
8213
8218
  mediaById: internal4.route({ method: "GET", path: "/posts/media/{id}", summary: "Get post media metadata" }).errors(orgErrors).input(IdPathParam).output(MediaMetadataSchema),
8214
- create: tagged12.route({ method: "POST", path: "/posts", summary: "Create posts in bulk", successStatus: 201 }).errors({ ...writableErrors, ...postDomainErrors }).input(CreatePostsInputSchema).output(CreatePostsOutputSchema),
8215
- update: tagged12.route({ method: "PATCH", path: "/posts/{id}", summary: "Update a post" }).errors({ ...writableErrors, ...postDomainErrors }).input(UpdatePostInputSchema).output(UpdatePostOutputSchema),
8216
- scheduleDraft: tagged12.route({ method: "POST", path: "/posts/{id}/schedule", summary: "Schedule a draft" }).errors({
8217
- ...writableErrors,
8218
- ...postDomainErrors,
8219
- NOT_A_DRAFT: { status: 409, message: "That post is not a draft." },
8220
- DRAFT_HAS_NO_CHANNELS: { status: 400, message: "Choose the channels to schedule this draft on." }
8221
- }).input(ScheduleDraftInputSchema).output(PostWithRelationsSchema),
8222
- delete: tagged12.route({ method: "DELETE", path: "/posts/{id}", summary: "Delete a post" }).errors({ ...writableErrors, ...postDomainErrors }).input(DeletePostInputSchema).output(DeletedSchema),
8223
- retrySchedule: tagged12.route({ method: "POST", path: "/posts/schedules/{scheduleId}/retry", summary: "Retry a failed schedule" }).errors({ ...publishErrors, ...postDomainErrors }).input(RetryScheduleInputSchema).output(DeletedSchema),
8224
- rescheduleSchedule: tagged12.route({
8219
+ create: idempotent.route({ method: "POST", path: "/posts", summary: "Create posts in bulk", successStatus: 201 }).errors({ ...writableErrors, ...postDomainErrors }).input(CreatePostsInputSchema).output(CreatePostsOutputSchema),
8220
+ update: idempotent.route({ method: "PATCH", path: "/posts/{id}", summary: "Update a post" }).errors({ ...writableErrors, ...postDomainErrors }).input(UpdatePostInputSchema).output(PostStateSchema),
8221
+ scheduleDraft: idempotent.route({ method: "POST", path: "/posts/{id}/schedule", summary: "Schedule a draft" }).errors({ ...writableErrors, ...postDomainErrors }).input(ScheduleDraftInputSchema).output(PostStateSchema),
8222
+ delete: idempotent.route({ method: "DELETE", path: "/posts/{id}", summary: "Delete a post" }).errors({ ...writableErrors, ...postDomainErrors }).input(DeletePostInputSchema).output(DeletePostOutputSchema),
8223
+ retrySchedule: idempotent.route({ method: "POST", path: "/posts/schedules/{scheduleId}/retry", summary: "Retry a failed schedule" }).errors({ ...publishErrors, ...postDomainErrors }).input(RetryScheduleInputSchema).output(PostStateSchema),
8224
+ rescheduleSchedule: idempotent.route({
8225
8225
  method: "POST",
8226
8226
  path: "/posts/schedules/{scheduleId}/reschedule",
8227
8227
  summary: "Move a schedule to a new time"
8228
- }).errors({ ...writableErrors, ...postDomainErrors }).input(RescheduleInputSchema).output(DeletedSchema),
8228
+ }).errors({ ...writableErrors, ...postDomainErrors }).input(RescheduleInputSchema).output(PostStateSchema),
8229
8229
  bulkScheduleInWindows: internal4.route({
8230
8230
  method: "POST",
8231
8231
  path: "/posts/schedules/bulk-schedule-windows",
@@ -8496,12 +8496,12 @@ var quotaErrors = {
8496
8496
  REPURPOSE_QUOTA_EXCEEDED: {
8497
8497
  status: 403,
8498
8498
  message: "Daily import limit reached.",
8499
- data: object({ limit: number2().int().nullable() })
8499
+ data: ErrorDataSchema.extend({ limit: number2().int().nullable() })
8500
8500
  },
8501
8501
  WORKFLOW_CONCURRENCY_EXCEEDED: {
8502
8502
  status: 403,
8503
8503
  message: "Maximum number of running workflows reached.",
8504
- data: object({ limit: number2().int().nullable() })
8504
+ data: ErrorDataSchema.extend({ limit: number2().int().nullable() })
8505
8505
  }
8506
8506
  };
8507
8507
  var badRequest = { BAD_REQUEST: { message: "Bad request." } };
@@ -8660,9 +8660,9 @@ var ArchiveImportInputSchema = discriminatedUnion("source", [
8660
8660
  posts: array(CapturedPostSchema).min(1).max(CAPTURE_BATCH_LIMIT)
8661
8661
  })
8662
8662
  ]);
8663
- var tagged13 = base.route({ tags: ["Repurpose"] }).meta({ internal: true });
8663
+ var tagged14 = base.route({ tags: ["Repurpose"] }).meta({ internal: true });
8664
8664
  var sourcesContract = {
8665
- list: tagged13.route({ method: "GET", path: "/repurpose/sources", summary: "List imported source posts" }).errors(orgErrors).input(
8665
+ list: tagged14.route({ method: "GET", path: "/repurpose/sources", summary: "List imported source posts" }).errors(orgErrors).input(
8666
8666
  object({
8667
8667
  platform: PlatformSchema.optional(),
8668
8668
  hasMedia: boolean2().optional(),
@@ -8672,13 +8672,13 @@ var sourcesContract = {
8672
8672
  page: number2().int().min(1).optional()
8673
8673
  })
8674
8674
  ).output(object({ items: array(SourcePostSchema), pageInfo: SourcePageInfoSchema })),
8675
- import: tagged13.route({
8675
+ import: tagged14.route({
8676
8676
  method: "POST",
8677
8677
  path: "/repurpose/sources/import",
8678
8678
  summary: "Import a batch of source posts from a connected integration"
8679
8679
  }).errors({ ...publishErrors, ...badRequest, ...quotaErrors }).input(object({ integrationId: Uuid })).output(object({ success: literal(true), message: string2() })),
8680
- importByUrl: tagged13.route({ method: "POST", path: "/repurpose/sources/import/url", summary: "Import a single source post by URL" }).errors({ ...publishErrors, ...badRequest, ...quotaErrors }).input(object({ url: string2().url() })).output(object({ success: literal(true), sourcePostId: Uuid })),
8681
- importArchive: tagged13.route({
8680
+ importByUrl: tagged14.route({ method: "POST", path: "/repurpose/sources/import/url", summary: "Import a single source post by URL" }).errors({ ...publishErrors, ...badRequest, ...quotaErrors }).input(object({ url: string2().url() })).output(object({ success: literal(true), sourcePostId: Uuid })),
8681
+ importArchive: tagged14.route({
8682
8682
  method: "POST",
8683
8683
  path: "/repurpose/sources/import/archive",
8684
8684
  summary: "Bulk-import a creator's own back catalogue from an export file or a client capture"
@@ -8697,9 +8697,9 @@ var sourcesContract = {
8697
8697
  })
8698
8698
  })
8699
8699
  ),
8700
- delete: tagged13.route({ method: "DELETE", path: "/repurpose/sources/{id}", summary: "Delete a source post" }).errors(orgErrors).input(IdPathParam).output(DeletedSchema),
8701
- update: tagged13.route({ method: "PATCH", path: "/repurpose/sources/{id}", summary: "Edit a source post's raw content" }).errors(writableErrors).input(object({ id: Uuid, rawContent: string2().min(1) })).output(object({ success: literal(true), id: Uuid })),
8702
- createDraft: tagged13.route({
8700
+ delete: tagged14.route({ method: "DELETE", path: "/repurpose/sources/{id}", summary: "Delete a source post" }).errors(orgErrors).input(IdPathParam).output(DeletedSchema),
8701
+ update: tagged14.route({ method: "PATCH", path: "/repurpose/sources/{id}", summary: "Edit a source post's raw content" }).errors(writableErrors).input(object({ id: Uuid, rawContent: string2().min(1) })).output(object({ success: literal(true), id: Uuid })),
8702
+ createDraft: tagged14.route({
8703
8703
  method: "POST",
8704
8704
  path: "/repurpose/sources/{id}/draft",
8705
8705
  summary: "Create a draft post from a source post, unadapted",
@@ -8707,7 +8707,7 @@ var sourcesContract = {
8707
8707
  }).errors(writableErrors).input(IdPathParam).output(object({ success: literal(true), postId: Uuid }))
8708
8708
  };
8709
8709
  var adaptContract = {
8710
- preview: tagged13.route({
8710
+ preview: tagged14.route({
8711
8711
  method: "POST",
8712
8712
  path: "/repurpose/adapt/preview",
8713
8713
  summary: "Adapt a source post for a target platform synchronously and create a draft"
@@ -8719,7 +8719,7 @@ var adaptContract = {
8719
8719
  media: array(MediaAttachmentSchema)
8720
8720
  })
8721
8721
  ),
8722
- batch: tagged13.route({
8722
+ batch: tagged14.route({
8723
8723
  method: "POST",
8724
8724
  path: "/repurpose/adapt/batch",
8725
8725
  summary: "Queue asynchronous adaptation for many source posts across many target platforms"
@@ -8731,14 +8731,14 @@ var adaptContract = {
8731
8731
  ).output(object({ success: literal(true), queued: number2().int() }))
8732
8732
  };
8733
8733
  var draftsContract = {
8734
- list: tagged13.route({ method: "GET", path: "/repurpose/drafts", summary: "List drafts created from source posts" }).errors(orgErrors).input(
8734
+ list: tagged14.route({ method: "GET", path: "/repurpose/drafts", summary: "List drafts created from source posts" }).errors(orgErrors).input(
8735
8735
  object({
8736
8736
  sourcePostId: Uuid.optional(),
8737
8737
  targetPlatform: PlatformSchema.optional(),
8738
8738
  limit: number2().int().min(1).max(100).optional()
8739
8739
  })
8740
8740
  ).output(array(DraftListItemSchema)),
8741
- listForWorkflow: tagged13.route({
8741
+ listForWorkflow: tagged14.route({
8742
8742
  method: "GET",
8743
8743
  path: "/repurpose/workflows/{workflowId}/drafts",
8744
8744
  summary: "List drafts created by one growth workflow"
@@ -8750,7 +8750,7 @@ var runsContract = {
8750
8750
  * oRPC matches the literal `recent-statuses` segment ahead of `{runId}`
8751
8751
  * regardless of declaration order.
8752
8752
  */
8753
- recentStatuses: tagged13.route({
8753
+ recentStatuses: tagged14.route({
8754
8754
  method: "GET",
8755
8755
  path: "/repurpose/workflows/{workflowId}/runs/recent-statuses",
8756
8756
  summary: "Sparkline of recent tick outcomes for a workflow"
@@ -8764,7 +8764,7 @@ var runsContract = {
8764
8764
  })
8765
8765
  )
8766
8766
  ),
8767
- list: tagged13.route({ method: "GET", path: "/repurpose/workflows/{workflowId}/runs", summary: "List a workflow\u2019s ticks" }).errors(orgErrors).input(
8767
+ list: tagged14.route({ method: "GET", path: "/repurpose/workflows/{workflowId}/runs", summary: "List a workflow\u2019s ticks" }).errors(orgErrors).input(
8768
8768
  object({
8769
8769
  workflowId: Uuid,
8770
8770
  statuses: array(WorkflowRunStatusSchema).optional(),
@@ -8782,7 +8782,7 @@ var runsContract = {
8782
8782
  })
8783
8783
  })
8784
8784
  ),
8785
- get: tagged13.route({
8785
+ get: tagged14.route({
8786
8786
  method: "GET",
8787
8787
  path: "/repurpose/workflows/{workflowId}/runs/{runId}",
8788
8788
  summary: "Get one tick, with the source posts fetched and drafts created in it"
@@ -8814,19 +8814,19 @@ var runsContract = {
8814
8814
  )
8815
8815
  };
8816
8816
  var workflowsContract = {
8817
- create: tagged13.route({ method: "POST", path: "/repurpose/workflows", summary: "Create a growth workflow", successStatus: 201 }).errors({ ...publishErrors, ...quotaErrors }).input(WorkflowSettingsSchema).output(GrowthWorkflowSchema),
8818
- list: tagged13.route({ method: "GET", path: "/repurpose/workflows", summary: "List growth workflows" }).errors(orgErrors).output(array(GrowthWorkflowSchema)),
8819
- get: tagged13.route({ method: "GET", path: "/repurpose/workflows/{id}", summary: "Get a growth workflow" }).errors(orgErrors).input(IdPathParam).output(GrowthWorkflowSchema),
8820
- update: tagged13.route({ method: "PATCH", path: "/repurpose/workflows/{id}", summary: "Update a growth workflow" }).errors({ ...publishErrors, ...quotaErrors }).input(UpdateWorkflowInputSchema).output(GrowthWorkflowSchema),
8821
- pause: tagged13.route({ method: "POST", path: "/repurpose/workflows/{id}/pause", summary: "Pause a growth workflow" }).errors({ ...writableErrors, ...stateConflict }).input(object({ id: Uuid, reason: string2().optional() })).output(GrowthWorkflowSchema),
8822
- resume: tagged13.route({ method: "POST", path: "/repurpose/workflows/{id}/resume", summary: "Resume a paused growth workflow" }).errors({ ...publishErrors, ...quotaErrors, ...stateConflict }).input(object({ id: Uuid, resumeFromCursor: _enum(["old", "now"]) })).output(GrowthWorkflowSchema),
8823
- delete: tagged13.route({ method: "DELETE", path: "/repurpose/workflows/{id}", summary: "Delete a growth workflow" }).errors(orgErrors).input(IdPathParam).output(DeletedSchema),
8824
- runNow: tagged13.route({
8817
+ create: tagged14.route({ method: "POST", path: "/repurpose/workflows", summary: "Create a growth workflow", successStatus: 201 }).errors({ ...publishErrors, ...quotaErrors }).input(WorkflowSettingsSchema).output(GrowthWorkflowSchema),
8818
+ list: tagged14.route({ method: "GET", path: "/repurpose/workflows", summary: "List growth workflows" }).errors(orgErrors).output(array(GrowthWorkflowSchema)),
8819
+ get: tagged14.route({ method: "GET", path: "/repurpose/workflows/{id}", summary: "Get a growth workflow" }).errors(orgErrors).input(IdPathParam).output(GrowthWorkflowSchema),
8820
+ update: tagged14.route({ method: "PATCH", path: "/repurpose/workflows/{id}", summary: "Update a growth workflow" }).errors({ ...publishErrors, ...quotaErrors }).input(UpdateWorkflowInputSchema).output(GrowthWorkflowSchema),
8821
+ pause: tagged14.route({ method: "POST", path: "/repurpose/workflows/{id}/pause", summary: "Pause a growth workflow" }).errors({ ...writableErrors, ...stateConflict }).input(object({ id: Uuid, reason: string2().optional() })).output(GrowthWorkflowSchema),
8822
+ resume: tagged14.route({ method: "POST", path: "/repurpose/workflows/{id}/resume", summary: "Resume a paused growth workflow" }).errors({ ...publishErrors, ...quotaErrors, ...stateConflict }).input(object({ id: Uuid, resumeFromCursor: _enum(["old", "now"]) })).output(GrowthWorkflowSchema),
8823
+ delete: tagged14.route({ method: "DELETE", path: "/repurpose/workflows/{id}", summary: "Delete a growth workflow" }).errors(orgErrors).input(IdPathParam).output(DeletedSchema),
8824
+ runNow: tagged14.route({
8825
8825
  method: "POST",
8826
8826
  path: "/repurpose/workflows/{id}/run-now",
8827
8827
  summary: "Trigger an immediate one-off tick for a running workflow"
8828
8828
  }).errors({ ...publishErrors, ...badRequest }).input(IdPathParam).output(object({ enqueued: boolean2() })),
8829
- upcomingTimeline: tagged13.route({
8829
+ upcomingTimeline: tagged14.route({
8830
8830
  method: "GET",
8831
8831
  path: "/repurpose/workflows/{id}/timeline",
8832
8832
  summary: "Project upcoming ticks and list already-scheduled drafts for a workflow"
@@ -8899,9 +8899,9 @@ var ReviewStatusSchema = object({
8899
8899
  canCurrentUserApprove: boolean2(),
8900
8900
  approvalSettings: ApprovalSettingsSchema
8901
8901
  });
8902
- var tagged14 = base.route({ tags: ["Reviews"] }).meta({ internal: true });
8902
+ var tagged15 = base.route({ tags: ["Reviews"] }).meta({ internal: true });
8903
8903
  var reviewsContract = {
8904
- getStatus: tagged14.route({ method: "GET", path: "/posts/{postId}/reviews/status", summary: "Get review status and history" }).errors(orgErrors).input(object({ postId: Uuid, postScheduleId: Uuid.optional() })).output(ReviewStatusSchema),
8904
+ getStatus: tagged15.route({ method: "GET", path: "/posts/{postId}/reviews/status", summary: "Get review status and history" }).errors(orgErrors).input(object({ postId: Uuid, postScheduleId: Uuid.optional() })).output(ReviewStatusSchema),
8905
8905
  /**
8906
8906
  * Sends mail from our domain to addresses the caller names, so it spends
8907
8907
  * outbound reputation — `publishBase`, not `writableBase`, same rule as
@@ -8909,14 +8909,14 @@ var reviewsContract = {
8909
8909
  * before anything is queued, so a caller cannot use this to email an
8910
8910
  * arbitrary address.
8911
8911
  */
8912
- requestReview: tagged14.route({ method: "POST", path: "/posts/{postId}/reviews/request", summary: "Request review of a post" }).errors(publishErrors).input(
8912
+ requestReview: tagged15.route({ method: "POST", path: "/posts/{postId}/reviews/request", summary: "Request review of a post" }).errors(publishErrors).input(
8913
8913
  object({
8914
8914
  postId: Uuid,
8915
8915
  postScheduleIds: array(Uuid).optional(),
8916
8916
  requiredApproverIds: array(string2()).optional()
8917
8917
  })
8918
8918
  ).output(SuccessSchema),
8919
- submitDecision: tagged14.route({ method: "POST", path: "/posts/{postId}/reviews/decision", summary: "Approve, reject, or request changes" }).errors(writableErrors).input(
8919
+ submitDecision: tagged15.route({ method: "POST", path: "/posts/{postId}/reviews/decision", summary: "Approve, reject, or request changes" }).errors(writableErrors).input(
8920
8920
  object({
8921
8921
  postId: Uuid,
8922
8922
  postScheduleId: Uuid.nullable().optional(),
@@ -8924,7 +8924,7 @@ var reviewsContract = {
8924
8924
  comment: string2().trim().max(2e3).optional()
8925
8925
  })
8926
8926
  ).output(SuccessSchema),
8927
- cancelReview: tagged14.route({ method: "POST", path: "/posts/{postId}/reviews/cancel", summary: "Cancel a pending review" }).errors(writableErrors).input(object({ postId: Uuid })).output(SuccessSchema)
8927
+ cancelReview: tagged15.route({ method: "POST", path: "/posts/{postId}/reviews/cancel", summary: "Cancel a pending review" }).errors(writableErrors).input(object({ postId: Uuid })).output(SuccessSchema)
8928
8928
  };
8929
8929
 
8930
8930
  // ../../packages/api-contract/src/schedules.ts
@@ -9067,14 +9067,14 @@ var ScheduleWithPostSchema = PostRowSchema.extend({
9067
9067
  /** The requested schedule, followed by the rest of its thread in publish order. */
9068
9068
  schedules: array(ScheduleWithIntegrationSchema)
9069
9069
  });
9070
- var tagged15 = base.route({ tags: ["Schedules"] });
9070
+ var tagged16 = base.route({ tags: ["Schedules"] });
9071
9071
  var schedulesContract = {
9072
- list: tagged15.route({ method: "GET", path: "/schedules", summary: "List schedules (calendar view)" }).errors(orgErrors).input(ListSchedulesInputSchema).output(ListSchedulesOutputSchema),
9072
+ list: tagged16.route({ method: "GET", path: "/schedules", summary: "List schedules (calendar view)" }).errors(orgErrors).input(ListSchedulesInputSchema).output(ListSchedulesOutputSchema),
9073
9073
  // Dashboard plumbing: the status segment row on `/posts` and `/calendar`. No
9074
9074
  // external caller needs it, so it stays out of the public surface.
9075
- counts: tagged15.route({ method: "GET", path: "/schedules/counts", summary: "Count schedules per status" }).meta({ internal: true }).errors(orgErrors).input(CountSchedulesInputSchema).output(CountSchedulesOutputSchema),
9076
- getById: tagged15.route({ method: "GET", path: "/schedules/{id}", summary: "Get a schedule" }).errors(orgErrors).input(GetScheduleByIdInputSchema).output(ScheduleWithPostSchema),
9077
- delete: tagged15.route({ method: "DELETE", path: "/schedules/{id}", summary: "Delete a schedule" }).errors({ ...writableErrors, ...postDomainErrors }).input(DeleteScheduleInputSchema).output(DeletedSchema)
9075
+ counts: tagged16.route({ method: "GET", path: "/schedules/counts", summary: "Count schedules per status" }).meta({ internal: true }).errors(orgErrors).input(CountSchedulesInputSchema).output(CountSchedulesOutputSchema),
9076
+ getById: tagged16.route({ method: "GET", path: "/schedules/{id}", summary: "Get a schedule" }).errors(orgErrors).input(GetScheduleByIdInputSchema).output(ScheduleWithPostSchema),
9077
+ delete: tagged16.route({ method: "DELETE", path: "/schedules/{id}", summary: "Delete a schedule" }).errors({ ...writableErrors, ...postDomainErrors }).input(DeleteScheduleInputSchema).output(DeletedSchema)
9078
9078
  };
9079
9079
 
9080
9080
  // ../../packages/api-contract/src/support.ts
@@ -9157,17 +9157,17 @@ var TagSchema = object({
9157
9157
  var CreateTagInputSchema = object({ name: TagNameSchema });
9158
9158
  var UpdateTagInputSchema = object({ id: Uuid, name: TagNameSchema });
9159
9159
  var TagUsageCountSchema = object({ tagId: Uuid, count: AggregateCount });
9160
- var tagged16 = base.route({ tags: ["Tags"] });
9161
- var internal6 = tagged16.meta({ internal: true });
9160
+ var tagged17 = base.route({ tags: ["Tags"] });
9161
+ var internal6 = tagged17.meta({ internal: true });
9162
9162
  var tagsContract = {
9163
- list: tagged16.route({ method: "GET", path: "/tags", summary: "List tags" }).errors(orgErrors).output(array(TagSchema)),
9163
+ list: tagged17.route({ method: "GET", path: "/tags", summary: "List tags" }).errors(orgErrors).output(array(TagSchema)),
9164
9164
  /**
9165
9165
  * Declared before `getById` for readability only — oRPC matches a literal
9166
9166
  * segment ahead of a path parameter regardless of declaration order, so
9167
9167
  * `/tags/usage-counts` never resolves as `/tags/{id}`.
9168
9168
  */
9169
9169
  getUsageCounts: internal6.route({ method: "GET", path: "/tags/usage-counts", summary: "Count posts per tag" }).errors(orgErrors).output(array(TagUsageCountSchema)),
9170
- getById: tagged16.route({ method: "GET", path: "/tags/{id}", summary: "Get a tag" }).errors(orgErrors).input(IdPathParam).output(TagSchema),
9170
+ getById: tagged17.route({ method: "GET", path: "/tags/{id}", summary: "Get a tag" }).errors(orgErrors).input(IdPathParam).output(TagSchema),
9171
9171
  create: internal6.route({ method: "POST", path: "/tags", summary: "Create a tag", successStatus: 201 }).errors({ ...writableErrors, CONFLICT: { message: "A tag with that name already exists." } }).input(CreateTagInputSchema).output(TagSchema),
9172
9172
  update: internal6.route({ method: "PATCH", path: "/tags/{id}", summary: "Rename a tag" }).errors(writableErrors).input(UpdateTagInputSchema).output(TagSchema),
9173
9173
  delete: internal6.route({ method: "DELETE", path: "/tags/{id}", summary: "Delete a tag" }).errors(orgErrors).input(IdPathParam).output(DeletedSchema)
@@ -9205,10 +9205,10 @@ var UsageEventSchema = object({
9205
9205
  callerLabel: string2().nullable(),
9206
9206
  createdAt: Timestamp
9207
9207
  });
9208
- var tagged17 = base.route({ tags: ["Usage"] });
9209
- var internal7 = tagged17.meta({ internal: true });
9208
+ var tagged18 = base.route({ tags: ["Usage"] });
9209
+ var internal7 = tagged18.meta({ internal: true });
9210
9210
  var usageContract = {
9211
- summary: tagged17.route({ method: "GET", path: "/usage", summary: "Get API and MCP call totals for the workspace" }).errors(orgErrors).input(object({ days: WindowDays })).output(UsageSummarySchema),
9211
+ summary: tagged18.route({ method: "GET", path: "/usage", summary: "Get API and MCP call totals for the workspace" }).errors(orgErrors).input(object({ days: WindowDays })).output(UsageSummarySchema),
9212
9212
  daily: internal7.route({ method: "GET", path: "/usage/daily", summary: "Get daily call counts for one surface" }).errors(orgErrors).input(object({ surface: UsageSurfaceSchema, days: WindowDays })).output(object({ items: array(UsageDailyPointSchema) })),
9213
9213
  events: internal7.route({ method: "GET", path: "/usage/events", summary: "List recent API and MCP calls" }).errors(orgErrors).input(
9214
9214
  object({
@@ -9359,15 +9359,15 @@ var AiQuotaSchema = object({
9359
9359
  remaining: number2().nullable(),
9360
9360
  unlimited: boolean2()
9361
9361
  });
9362
- var tagged18 = base.route({ tags: ["User"] });
9363
- var internal8 = tagged18.meta({ internal: true });
9362
+ var tagged19 = base.route({ tags: ["User"] });
9363
+ var internal8 = tagged19.meta({ internal: true });
9364
9364
  var userContract = {
9365
- me: tagged18.route({ method: "GET", path: "/users/me", summary: "Get the current user" }).errors({ ...authedErrors, NOT_FOUND: { message: "User not found." } }).output(MeSchema),
9365
+ me: tagged19.route({ method: "GET", path: "/users/me", summary: "Get the current user" }).errors({ ...authedErrors, NOT_FOUND: { message: "User not found." } }).output(MeSchema),
9366
9366
  update: internal8.route({ method: "PATCH", path: "/users/me", summary: "Update the current user" }).errors({ ...authedErrors, NOT_FOUND: { message: "User not found." } }).input(UpdateUserInputSchema).output(UserAccountSchema),
9367
- getPreferences: tagged18.route({ method: "GET", path: "/users/me/preferences", summary: "Get the current user's preferences" }).errors(authedErrors).output(UserPreferencesSchema),
9367
+ getPreferences: tagged19.route({ method: "GET", path: "/users/me/preferences", summary: "Get the current user's preferences" }).errors(authedErrors).output(UserPreferencesSchema),
9368
9368
  updatePreferences: internal8.route({ method: "PATCH", path: "/users/me/preferences", summary: "Update the current user's preferences" }).errors(authedErrors).input(UpdatePreferencesInputSchema).output(UserPreferencesSchema),
9369
9369
  resetPreferences: internal8.route({ method: "DELETE", path: "/users/me/preferences", summary: "Reset the current user's preferences" }).errors(authedErrors).output(object({ message: string2() })),
9370
- getPlanQuota: tagged18.route({ method: "GET", path: "/users/me/plan-quota", summary: "Get the active workspace's plan quota" }).errors(orgErrors).input(object({ platforms: array(PlatformEnum).optional() })).output(PlanQuotaSchema),
9370
+ getPlanQuota: tagged19.route({ method: "GET", path: "/users/me/plan-quota", summary: "Get the active workspace's plan quota" }).errors(orgErrors).input(object({ platforms: array(PlatformEnum).optional() })).output(PlanQuotaSchema),
9371
9371
  getAiQuota: internal8.route({ method: "GET", path: "/users/me/ai-quota", summary: "Get the active workspace's AI credit quota" }).errors(orgErrors).output(AiQuotaSchema),
9372
9372
  setDefaultWorkspace: internal8.route({ method: "POST", path: "/users/me/default-workspace", summary: "Set the current user's default workspace" }).errors({ ...authedErrors, FORBIDDEN: { message: "You are not a member of this workspace." } }).input(object({ organizationId: string2() })).output(DeletedSchema)
9373
9373
  };
@@ -9412,6 +9412,17 @@ var ApprovalSettingsInputSchema = object({
9412
9412
  approverRoles: array(_enum(["owner", "admin", "member"])),
9413
9413
  minApprovers: number2().int().min(1).max(5)
9414
9414
  });
9415
+ var AlertWebhookSettingsSchema = object({
9416
+ url: string2().nullable(),
9417
+ notifyOnPublish: boolean2()
9418
+ });
9419
+ var UpdateAlertWebhookInputSchema = object({
9420
+ url: string2().url("Must be a valid HTTP or HTTPS URL").nullable().or(literal("")),
9421
+ notifyOnPublish: boolean2().default(false)
9422
+ });
9423
+ var TestAlertWebhookInputSchema = object({
9424
+ url: string2().url("Must be a valid HTTP or HTTPS URL")
9425
+ });
9415
9426
  var WorkspaceSummarySchema = object({
9416
9427
  id: string2(),
9417
9428
  name: string2(),
@@ -9419,7 +9430,7 @@ var WorkspaceSummarySchema = object({
9419
9430
  role: string2()
9420
9431
  });
9421
9432
  var publicTagged2 = base.route({ tags: ["Workspace"] });
9422
- var tagged19 = publicTagged2.meta({ internal: true });
9433
+ var tagged20 = publicTagged2.meta({ internal: true });
9423
9434
  var workspaceContract = {
9424
9435
  /**
9425
9436
  * Public, so an OAuth client can offer a workspace switcher: the chosen id goes
@@ -9427,8 +9438,8 @@ var workspaceContract = {
9427
9438
  * only that one.
9428
9439
  */
9429
9440
  list: publicTagged2.route({ method: "GET", path: "/workspaces", summary: "List your workspaces" }).errors(authedErrors).output(array(WorkspaceSummarySchema)),
9430
- getOwnedCapacity: tagged19.route({ method: "GET", path: "/workspaces/owned-capacity", summary: "Get owned workspace capacity" }).errors(authedErrors).output(OwnedCapacitySchema),
9431
- create: tagged19.route({ method: "POST", path: "/workspaces", summary: "Create a workspace", successStatus: 201 }).errors({
9441
+ getOwnedCapacity: tagged20.route({ method: "GET", path: "/workspaces/owned-capacity", summary: "Get owned workspace capacity" }).errors(authedErrors).output(OwnedCapacitySchema),
9442
+ create: tagged20.route({ method: "POST", path: "/workspaces", summary: "Create a workspace", successStatus: 201 }).errors({
9432
9443
  ...authedErrors,
9433
9444
  FORBIDDEN: { message: "You have reached your workspace capacity." },
9434
9445
  INTERNAL_SERVER_ERROR: { message: "Failed to create workspace." }
@@ -9438,7 +9449,7 @@ var workspaceContract = {
9438
9449
  * workspace active. Ownership is verified against the `organizationId` in
9439
9450
  * the body, exactly as the tRPC procedure did.
9440
9451
  */
9441
- transferOwnership: tagged19.route({
9452
+ transferOwnership: tagged20.route({
9442
9453
  method: "POST",
9443
9454
  path: "/workspaces/{organizationId}/transfer-ownership",
9444
9455
  summary: "Transfer workspace ownership"
@@ -9448,9 +9459,23 @@ var workspaceContract = {
9448
9459
  FORBIDDEN: { message: "Only the billing owner can transfer workspace ownership." },
9449
9460
  BAD_REQUEST: { message: "New owner must be a member of the workspace." }
9450
9461
  }).input(TransferOwnershipInputSchema).output(SuccessSchema),
9451
- updateApprovalSettings: tagged19.route({ method: "PATCH", path: "/workspaces/approval-settings", summary: "Update approval settings" }).errors(orgErrors).input(ApprovalSettingsInputSchema).output(SuccessSchema),
9452
- getBrandVoice: tagged19.route({ method: "GET", path: "/workspaces/brand-voice", summary: "Get the workspace brand voice" }).errors(orgErrors).output(object({ voiceProfile: string2() })),
9453
- updateBrandVoice: tagged19.route({ method: "PATCH", path: "/workspaces/brand-voice", summary: "Update the workspace brand voice" }).errors(orgErrors).input(object({ voiceProfile: string2().max(2e3) })).output(SuccessSchema)
9462
+ updateApprovalSettings: tagged20.route({ method: "PATCH", path: "/workspaces/approval-settings", summary: "Update approval settings" }).errors(orgErrors).input(ApprovalSettingsInputSchema).output(SuccessSchema),
9463
+ getBrandVoice: tagged20.route({ method: "GET", path: "/workspaces/brand-voice", summary: "Get the workspace brand voice" }).errors(orgErrors).output(object({ voiceProfile: string2() })),
9464
+ updateBrandVoice: tagged20.route({ method: "PATCH", path: "/workspaces/brand-voice", summary: "Update the workspace brand voice" }).errors(orgErrors).input(object({ voiceProfile: string2().max(2e3) })).output(SuccessSchema),
9465
+ getAlertWebhook: tagged20.route({ method: "GET", path: "/workspaces/alert-webhook", summary: "Get workspace alert webhook settings" }).errors(orgErrors).output(AlertWebhookSettingsSchema),
9466
+ updateAlertWebhook: tagged20.route({ method: "PATCH", path: "/workspaces/alert-webhook", summary: "Update workspace alert webhook settings" }).errors({
9467
+ ...orgErrors,
9468
+ FORBIDDEN: { message: "Only workspace administrators can update alert webhook settings" }
9469
+ }).input(UpdateAlertWebhookInputSchema).output(SuccessSchema),
9470
+ testAlertWebhook: tagged20.route({
9471
+ method: "POST",
9472
+ path: "/workspaces/alert-webhook/test",
9473
+ summary: "Send a test notification to the webhook"
9474
+ }).errors({
9475
+ ...orgErrors,
9476
+ FORBIDDEN: { message: "Only workspace administrators can test alert webhook settings" },
9477
+ BAD_REQUEST: { message: "Failed to deliver test alert to the provided webhook URL" }
9478
+ }).input(TestAlertWebhookInputSchema).output(SuccessSchema)
9454
9479
  };
9455
9480
 
9456
9481
  // ../../packages/api-contract/src/contract.ts
@@ -9467,6 +9492,7 @@ var contract = {
9467
9492
  media: mediaContract,
9468
9493
  mediaSources: mediaSourcesContract,
9469
9494
  notifications: notificationsContract,
9495
+ platforms: platformsContract,
9470
9496
  posts: postsContract,
9471
9497
  publicCalendar: publicCalendarContract,
9472
9498
  publicPost: publicPostContract,
@@ -9483,17 +9509,17 @@ var contract = {
9483
9509
  workspace: workspaceContract
9484
9510
  };
9485
9511
 
9486
- // ../../node_modules/.pnpm/@orpc+openapi@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.0/node_modules/@orpc/openapi/dist/shared/openapi.BwdtJjDu.mjs
9512
+ // ../../node_modules/.pnpm/@orpc+openapi@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.1/node_modules/@orpc/openapi/dist/shared/openapi.BwdtJjDu.mjs
9487
9513
  import { isORPCErrorStatus, fallbackORPCErrorStatus, fallbackORPCErrorMessage } from "@orpc/client";
9488
9514
  import { toHttpPath } from "@orpc/client/standard";
9489
9515
  import { fallbackContractConfig as fallbackContractConfig2, getEventIteratorSchemaDetails } from "@orpc/contract";
9490
9516
  import { standardizeHTTPPath, StandardOpenAPIJsonSerializer, getDynamicParams } from "@orpc/openapi-client/standard";
9491
9517
 
9492
- // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.0/node_modules/@orpc/server/dist/index.mjs
9518
+ // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.1/node_modules/@orpc/server/dist/index.mjs
9493
9519
  import { mergeErrorMap as mergeErrorMap2, mergeMeta, mergeRoute, mergePrefix as mergePrefix2, mergeTags, isContractProcedure as isContractProcedure2, getContractRouter, fallbackContractConfig } from "@orpc/contract";
9494
9520
  import { ValidationError as ValidationError2, eventIterator, type, validateORPCError as validateORPCError2 } from "@orpc/contract";
9495
9521
 
9496
- // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.0/node_modules/@orpc/server/dist/shared/server.DEBcqOjg.mjs
9522
+ // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.1/node_modules/@orpc/server/dist/shared/server.DEBcqOjg.mjs
9497
9523
  import { isContractProcedure, validateORPCError, ValidationError, mergePrefix, mergeErrorMap, enhanceRoute } from "@orpc/contract";
9498
9524
 
9499
9525
  // ../../node_modules/.pnpm/@orpc+shared@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/shared/dist/index.mjs
@@ -9753,7 +9779,7 @@ function overlayProxy(target, partial2) {
9753
9779
  return proxy;
9754
9780
  }
9755
9781
 
9756
- // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.0/node_modules/@orpc/server/dist/shared/server.DEBcqOjg.mjs
9782
+ // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.1/node_modules/@orpc/server/dist/shared/server.DEBcqOjg.mjs
9757
9783
  import { ORPCError, mapEventIterator } from "@orpc/client";
9758
9784
 
9759
9785
  // ../../node_modules/.pnpm/@orpc+standard-server@1.16.1_@opentelemetry+api@1.10.0/node_modules/@orpc/standard-server/dist/index.mjs
@@ -9902,7 +9928,7 @@ var HibernationEventIterator = class extends AsyncIteratorClass {
9902
9928
  }
9903
9929
  };
9904
9930
 
9905
- // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.0/node_modules/@orpc/server/dist/shared/server.DEBcqOjg.mjs
9931
+ // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.1/node_modules/@orpc/server/dist/shared/server.DEBcqOjg.mjs
9906
9932
  var LAZY_SYMBOL = /* @__PURE__ */ Symbol("ORPC_LAZY_SYMBOL");
9907
9933
  function lazy2(loader, meta2 = {}) {
9908
9934
  return {
@@ -10255,7 +10281,7 @@ async function resolveContractProcedures(options, callback) {
10255
10281
  }
10256
10282
  }
10257
10283
 
10258
- // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.0/node_modules/@orpc/server/dist/index.mjs
10284
+ // ../../node_modules/.pnpm/@orpc+server@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.1/node_modules/@orpc/server/dist/index.mjs
10259
10285
  import { toORPCError } from "@orpc/client";
10260
10286
  import { ORPCError as ORPCError2, isDefinedError, safe } from "@orpc/client";
10261
10287
  var DEFAULT_CONFIG = {
@@ -10650,7 +10676,7 @@ var TypeName;
10650
10676
  TypeName2["String"] = "string";
10651
10677
  })(TypeName || (TypeName = {}));
10652
10678
 
10653
- // ../../node_modules/.pnpm/@orpc+openapi@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.0/node_modules/@orpc/openapi/dist/shared/openapi.BwdtJjDu.mjs
10679
+ // ../../node_modules/.pnpm/@orpc+openapi@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.1/node_modules/@orpc/openapi/dist/shared/openapi.BwdtJjDu.mjs
10654
10680
  var OPERATION_EXTENDER_SYMBOL = /* @__PURE__ */ Symbol("ORPC_OPERATION_EXTENDER");
10655
10681
  function getCustomOpenAPIOperation(o) {
10656
10682
  return o[OPERATION_EXTENDER_SYMBOL];
@@ -11505,13 +11531,13 @@ ${errors.join("\n\n")}`
11505
11531
  }
11506
11532
  };
11507
11533
 
11508
- // ../../node_modules/.pnpm/@orpc+openapi@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.0/node_modules/@orpc/openapi/dist/index.mjs
11534
+ // ../../node_modules/.pnpm/@orpc+openapi@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.1/node_modules/@orpc/openapi/dist/index.mjs
11509
11535
  import { createORPCErrorFromJson } from "@orpc/client";
11510
11536
  import { StandardOpenAPISerializer, StandardOpenAPIJsonSerializer as StandardOpenAPIJsonSerializer2, StandardBracketNotationSerializer } from "@orpc/openapi-client/standard";
11511
11537
  import "@orpc/client/standard";
11512
11538
  import "@orpc/contract";
11513
11539
 
11514
- // ../../node_modules/.pnpm/@orpc+json-schema@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.0/node_modules/@orpc/json-schema/dist/index.mjs
11540
+ // ../../node_modules/.pnpm/@orpc+json-schema@1.16.1_@opentelemetry+api@1.10.0_ws@8.22.1/node_modules/@orpc/json-schema/dist/index.mjs
11515
11541
  var JsonSchemaXNativeType = /* @__PURE__ */ ((JsonSchemaXNativeType2) => {
11516
11542
  JsonSchemaXNativeType2["BigInt"] = "bigint";
11517
11543
  JsonSchemaXNativeType2["RegExp"] = "regexp";
@@ -11522,7 +11548,7 @@ var JsonSchemaXNativeType = /* @__PURE__ */ ((JsonSchemaXNativeType2) => {
11522
11548
  return JsonSchemaXNativeType2;
11523
11549
  })(JsonSchemaXNativeType || {});
11524
11550
 
11525
- // ../../node_modules/.pnpm/@orpc+zod@1.16.1_@opentelemetry+api@1.10.0_@orpc+contract@1.16.1_@opentelemetry+api@1.1_5e7190f497e0d8af82eb254f52223720/node_modules/@orpc/zod/dist/zod4/index.mjs
11551
+ // ../../node_modules/.pnpm/@orpc+zod@1.16.1_@opentelemetry+api@1.10.0_@orpc+contract@1.16.1_@opentelemetry+api@1.1_2308bc075ea90d1ee11574f662e35bd3/node_modules/@orpc/zod/dist/zod4/index.mjs
11526
11552
  var JSON_SCHEMA_REGISTRY = registry();
11527
11553
  var JSON_SCHEMA_INPUT_REGISTRY = registry();
11528
11554
  var JSON_SCHEMA_OUTPUT_REGISTRY = registry();
@@ -12078,7 +12104,7 @@ function resolveApiKey() {
12078
12104
  }
12079
12105
 
12080
12106
  // src/output.ts
12081
- var EXIT = { ok: 0, failure: 1, usage: 2 };
12107
+ var EXIT = { ok: 0, failure: 1, usage: 2, auth: 3, plan: 4, rateLimited: 5 };
12082
12108
  var globals = {};
12083
12109
  function setGlobalOptions(options) {
12084
12110
  globals = options;
@@ -12103,18 +12129,48 @@ function printStatus(line) {
12103
12129
  process.stderr.write(`${line}
12104
12130
  `);
12105
12131
  }
12106
- function fail(message, code = EXIT.failure) {
12132
+ function workspaceOption() {
12133
+ return globals.workspace;
12134
+ }
12135
+ var PLAN_CODES = /* @__PURE__ */ new Set(["PAYMENT_REQUIRED", "POST_QUOTA_EXCEEDED", "REPURPOSE_QUOTA_EXCEEDED"]);
12136
+ function exitCodeFor(error2, status) {
12137
+ if (error2.code === "RATE_LIMITED" || status === 429) return EXIT.rateLimited;
12138
+ if (PLAN_CODES.has(error2.code) || status === 402) return EXIT.plan;
12139
+ if (error2.code === "UNAUTHORIZED" || status === 401) return EXIT.auth;
12140
+ if (status === 400) return EXIT.usage;
12141
+ return EXIT.failure;
12142
+ }
12143
+ function failWith(error2, exitCode) {
12107
12144
  if (globals.json) {
12108
- process.stdout.write(`${JSON.stringify({ error: message }, null, 2)}
12145
+ process.stdout.write(`${JSON.stringify(error2, null, 2)}
12109
12146
  `);
12110
12147
  } else {
12111
- process.stderr.write(`Error: ${message}
12148
+ process.stderr.write(`Error: ${error2.message}
12149
+ `);
12150
+ if (error2.data.violations.length > 1) {
12151
+ for (const violation of error2.data.violations) process.stderr.write(` - ${violation.message}
12112
12152
  `);
12153
+ }
12113
12154
  }
12114
- process.exit(code);
12155
+ process.exit(exitCode);
12156
+ }
12157
+ function fail(message, exitCode = EXIT.failure) {
12158
+ return failWith(
12159
+ { code: exitCode === EXIT.usage ? "BAD_REQUEST" : "CLI_ERROR", message, data: { violations: [] } },
12160
+ exitCode
12161
+ );
12115
12162
  }
12116
12163
  function failUsage(message) {
12117
- return fail(message, EXIT.usage);
12164
+ return failWith({ code: "BAD_REQUEST", message, data: { violations: [{ message }] } }, EXIT.usage);
12165
+ }
12166
+ var INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/i;
12167
+ function parseInstant(value2, flag) {
12168
+ if (!INSTANT.test(value2) || Number.isNaN(new Date(value2).getTime())) {
12169
+ failUsage(
12170
+ `${flag} "${value2}" needs a time zone. Use RFC 3339 with an offset, e.g. 2026-08-01T09:30:00Z or 2026-08-01T11:30:00+02:00.`
12171
+ );
12172
+ }
12173
+ return value2;
12118
12174
  }
12119
12175
  function requireInteractive(what) {
12120
12176
  if (isInteractive()) return;
@@ -12129,7 +12185,7 @@ function formatTable(headers, rows) {
12129
12185
  }
12130
12186
 
12131
12187
  // src/version.ts
12132
- var CLI_VERSION = "0.1.22";
12188
+ var CLI_VERSION = "0.1.24";
12133
12189
 
12134
12190
  // src/client.ts
12135
12191
  var DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
@@ -12197,11 +12253,16 @@ function buildClient(apiUrl, auth) {
12197
12253
  const oauth = auth.kind === "oauth" ? { accessToken: auth.accessToken, refreshToken: auth.refreshToken, clientId: auth.clientId } : null;
12198
12254
  const link = new OpenAPILink(contract, {
12199
12255
  url: `${apiUrl}/api/v1`,
12200
- headers: () => ({
12201
- [CLI_VERSION_HEADER]: CLI_VERSION,
12202
- "x-postonus-client": "cli",
12203
- ...auth.kind === "api-key" ? { "x-api-key": auth.apiKey } : { authorization: `Bearer ${oauth?.accessToken}` }
12204
- }),
12256
+ headers: () => {
12257
+ const headers = new Headers({
12258
+ [CLI_VERSION_HEADER]: CLI_VERSION,
12259
+ "x-postonus-client": "cli",
12260
+ ...auth.kind === "api-key" ? { "x-api-key": auth.apiKey } : { authorization: `Bearer ${oauth?.accessToken}` }
12261
+ });
12262
+ const workspace = workspaceOption();
12263
+ if (workspace) headers.set("x-workspace-id", workspace);
12264
+ return Object.fromEntries(headers);
12265
+ },
12205
12266
  fetch: oauth ? createOAuthFetch(apiUrl, oauth, persistRefreshedTokens(apiUrl, oauth)) : (request, init) => fetch(request, init)
12206
12267
  });
12207
12268
  return createORPCClient(link);
@@ -12252,6 +12313,18 @@ function describeError(cause) {
12252
12313
  }
12253
12314
  return String(cause);
12254
12315
  }
12316
+ function failApi(cause) {
12317
+ if (cause instanceof ORPCError3) {
12318
+ const data = cause.data;
12319
+ const error2 = {
12320
+ code: cause.code,
12321
+ message: describeError(cause),
12322
+ data: { violations: data?.violations ?? [] }
12323
+ };
12324
+ return failWith(error2, exitCodeFor(error2, cause.status));
12325
+ }
12326
+ return failWith({ code: "CLI_ERROR", message: describeError(cause), data: { violations: [] } }, EXIT.failure);
12327
+ }
12255
12328
 
12256
12329
  // src/ui.tsx
12257
12330
  import { Box, render, Text, useApp, useInput } from "ink";
@@ -12468,7 +12541,7 @@ async function login() {
12468
12541
  ;
12469
12542
  ({ clientId, device } = await startDeviceLogin(apiUrl, carried.clientId));
12470
12543
  } catch (error2) {
12471
- fail(describeError(error2));
12544
+ failApi(error2);
12472
12545
  }
12473
12546
  if (clientId !== carried.clientId) await writeConfig({ ...carried, clientId, apiUrl });
12474
12547
  void open2(device.verification_uri_complete).catch(() => {
@@ -12502,7 +12575,7 @@ async function login() {
12502
12575
  try {
12503
12576
  await finish(await pollForToken(apiUrl, clientId, device));
12504
12577
  } catch (error2) {
12505
- fail(describeError(error2));
12578
+ failApi(error2);
12506
12579
  }
12507
12580
  return;
12508
12581
  }
@@ -12512,7 +12585,7 @@ async function login() {
12512
12585
  try {
12513
12586
  await instance.waitUntilExit();
12514
12587
  } catch (error2) {
12515
- fail(describeError(error2));
12588
+ failApi(error2);
12516
12589
  }
12517
12590
  }
12518
12591
  async function logout() {
@@ -12535,7 +12608,7 @@ async function whoami() {
12535
12608
  printLine(`${user.email} (${user.name})`);
12536
12609
  printStatus(`${apiUrl} \xB7 ${auth.kind === "api-key" ? "API key" : "OAuth"}`);
12537
12610
  } catch (error2) {
12538
- fail(describeError(error2));
12611
+ failApi(error2);
12539
12612
  }
12540
12613
  }
12541
12614
 
@@ -12562,7 +12635,7 @@ async function listChannels() {
12562
12635
  try {
12563
12636
  channels2 = await api.integrations.get();
12564
12637
  } catch (error2) {
12565
- fail(describeError(error2));
12638
+ failApi(error2);
12566
12639
  }
12567
12640
  if (isJsonMode()) {
12568
12641
  printJson({
@@ -12646,7 +12719,7 @@ async function connectChannel(options) {
12646
12719
  try {
12647
12720
  existing = await api.integrations.get();
12648
12721
  } catch (error2) {
12649
- fail(describeError(error2));
12722
+ failApi(error2);
12650
12723
  }
12651
12724
  let platform;
12652
12725
  if (options.platform) {
@@ -12665,7 +12738,7 @@ async function connectChannel(options) {
12665
12738
  const result = await api.integrations.connectIntegration({ platform });
12666
12739
  redirectUrl = result.redirectUrl;
12667
12740
  } catch (error2) {
12668
- fail(describeError(error2));
12741
+ failApi(error2);
12669
12742
  }
12670
12743
  if (isJsonMode()) {
12671
12744
  printJson({ platform, authorizeUrl: redirectUrl });
@@ -12897,7 +12970,7 @@ async function uploadCommand(paths) {
12897
12970
  try {
12898
12971
  uploaded.push(await uploadMedia(api, path));
12899
12972
  } catch (error2) {
12900
- fail(describeError(error2));
12973
+ failApi(error2);
12901
12974
  }
12902
12975
  }
12903
12976
  if (isJsonMode()) {
@@ -12908,19 +12981,27 @@ async function uploadCommand(paths) {
12908
12981
  printLine(`${item.mediaId} ${item.url}`);
12909
12982
  }
12910
12983
  }
12984
+ async function importCommand(url2) {
12985
+ const { api } = await getApi();
12986
+ try {
12987
+ const imported = await api.upload.fromUrl({ url: url2, scenarioId: SCENARIO });
12988
+ if (isJsonMode()) {
12989
+ printJson(imported);
12990
+ return;
12991
+ }
12992
+ printLine(`${imported.type.toLowerCase()} ${imported.mediaId ?? "\u2014"} ${imported.publicUrl}`);
12993
+ } catch (error2) {
12994
+ failApi(error2);
12995
+ }
12996
+ }
12911
12997
 
12912
12998
  // src/commands/post.ts
12913
12999
  import { spawnSync } from "child_process";
12914
13000
  import { mkdtemp, readFile as readFile2, rm as rm2, writeFile as writeFile2 } from "fs/promises";
12915
13001
  import { tmpdir } from "os";
12916
13002
  import { join as join2 } from "path";
12917
- async function resolveContent(text, options) {
12918
- if (options.file) {
12919
- const content = await readFile2(options.file, "utf8").catch(() => {
12920
- return fail(`Could not read ${options.file}`);
12921
- });
12922
- return content.trim();
12923
- }
13003
+ async function readContent(text, options) {
13004
+ if (options.file) return (await readFileOrFail(options.file)).trim();
12924
13005
  if (options.editor) {
12925
13006
  requireInteractive("--editor");
12926
13007
  return openEditor(text ?? "");
@@ -12932,7 +13013,15 @@ async function resolveContent(text, options) {
12932
13013
  const piped = Buffer.concat(chunks).toString("utf8").trim();
12933
13014
  if (piped) return piped;
12934
13015
  }
12935
- return failUsage("No content. Pass text, --file <path>, --editor, or pipe it in.");
13016
+ return void 0;
13017
+ }
13018
+ function readFileOrFail(path) {
13019
+ return readFile2(path, "utf8").catch(() => fail(`Could not read ${path}`));
13020
+ }
13021
+ async function readThread(path) {
13022
+ const segments = (await readFileOrFail(path)).split(/^---[ \t]*$/m).map((segment) => segment.trim()).filter(Boolean);
13023
+ if (segments.length < 2) failUsage(`${path} holds one segment. Separate thread segments with a line of \`---\`.`);
13024
+ return segments;
12936
13025
  }
12937
13026
  async function openEditor(initial) {
12938
13027
  const editor = process.env.VISUAL || process.env.EDITOR;
@@ -12950,123 +13039,164 @@ async function openEditor(initial) {
12950
13039
  await rm2(directory, { recursive: true, force: true });
12951
13040
  }
12952
13041
  }
12953
- async function resolveIntegrations(api, platforms) {
12954
- const channels2 = await api.integrations.get();
12955
- const active = channels2.filter((channel) => channel.connectStatus === "ACTIVE");
12956
- const missing = platforms.filter((platform) => !active.some((channel) => channel.platform === platform));
12957
- if (missing.length > 0) {
12958
- fail(
12959
- `No active channel for ${missing.join(", ").toLowerCase()}. Run \`postonus channels connect\` or check \`postonus channels list\`.`
12960
- );
12961
- }
12962
- const matched = active.filter((channel) => platforms.includes(channel.platform));
12963
- return { ids: matched.map((channel) => channel.id), matched };
13042
+ function readTargets(options) {
13043
+ const platforms = (options.to ?? "").split(",").map((value2) => value2.trim()).filter(Boolean).map(parsePlatform);
13044
+ if (platforms.length > 0 && options.channel?.length) failUsage("Use --to or --channel, not both.");
13045
+ return {
13046
+ platforms: platforms.length > 0 ? platforms : void 0,
13047
+ selectedIntegrations: options.channel?.length ? options.channel : void 0
13048
+ };
13049
+ }
13050
+ function readCopy(pairs) {
13051
+ if (!pairs?.length) return void 0;
13052
+ return Object.fromEntries(
13053
+ pairs.map((pair) => {
13054
+ const split = pair.indexOf("=");
13055
+ if (split < 1) failUsage(`--copy "${pair}" must be <channelId>=<text>.`);
13056
+ return [pair.slice(0, split), pair.slice(split + 1)];
13057
+ })
13058
+ );
12964
13059
  }
12965
- function resolveSchedule(options) {
13060
+ function readTiming(options) {
13061
+ const chosen = [options.at, options.optimal, options.now, options.draft].filter(Boolean);
13062
+ if (chosen.length > 1) failUsage("Use one of --at, --optimal, --now or --draft.");
12966
13063
  if (options.draft) return { postAction: "DRAFT" };
12967
- if (options.at) {
12968
- const when = new Date(options.at);
12969
- if (Number.isNaN(when.getTime())) {
12970
- return failUsage(`Could not read "${options.at}" as a date. Use an ISO timestamp, e.g. 2026-08-01T09:30:00Z.`);
12971
- }
12972
- if (when.getTime() <= Date.now()) return failUsage("That time is in the past.");
12973
- return { postAction: "SCHEDULED_TIME", scheduledAt: when };
12974
- }
13064
+ if (options.now) return { postAction: "PUBLISH_NOW" };
12975
13065
  if (options.optimal) return { postAction: "NEXT_WINDOW" };
12976
- return failUsage("Say when to post: --at <ISO time>, --optimal, or --draft.");
13066
+ if (options.at) return { postAction: "SCHEDULED_TIME", scheduledAt: parseInstant(options.at, "--at") };
13067
+ return failUsage("Say when to post: --at <time>, --optimal, --now, or --draft.");
12977
13068
  }
12978
- async function post(text, options) {
12979
- if (options.at && options.optimal) failUsage("Use either --at or --optimal, not both.");
12980
- const platforms = (options.to ?? "").split(",").map((value2) => value2.trim()).filter(Boolean).map(parsePlatform);
12981
- const content = await resolveContent(text, options);
12982
- const { postAction, scheduledAt } = resolveSchedule(options);
12983
- if (postAction !== "DRAFT" && platforms.length === 0) {
12984
- failUsage("Say where to post: --to x,linkedin (or use --draft).");
12985
- }
12986
- const { api } = await getApi();
12987
- let integrationIds = [];
12988
- let matched = [];
12989
- if (platforms.length > 0) {
12990
- const resolved = await resolveIntegrations(api, platforms);
12991
- integrationIds = resolved.ids;
12992
- matched = resolved.matched;
12993
- }
12994
- if (options.dryRun) {
12995
- const plan = {
12996
- dryRun: true,
12997
- content,
12998
- postAction,
12999
- scheduledAt: scheduledAt?.toISOString() ?? null,
13000
- media: options.media ?? [],
13001
- channels: matched.map((channel) => ({ id: channel.id, platform: channel.platform, name: channel.name }))
13002
- };
13003
- if (isJsonMode()) {
13004
- printJson(plan);
13005
- return;
13006
- }
13007
- printLine(`Would ${postAction === "DRAFT" ? "save a draft" : "schedule"}: ${content}`);
13008
- for (const channel of matched) printLine(` \u2192 ${channel.platform} ${channel.name}`);
13009
- if (scheduledAt) printLine(` at ${scheduledAt.toISOString()}`);
13010
- return;
13011
- }
13069
+ async function uploadAll(api, paths) {
13012
13070
  const media2 = [];
13013
- for (const path of options.media ?? []) {
13071
+ for (const path of paths ?? []) {
13014
13072
  printStatus(`Uploading ${path}\u2026`);
13015
13073
  try {
13016
13074
  media2.push(await uploadMedia(api, path));
13017
13075
  } catch (error2) {
13018
- fail(describeError(error2));
13076
+ failApi(error2);
13019
13077
  }
13020
13078
  }
13079
+ return media2;
13080
+ }
13081
+ function printState(state, verb) {
13082
+ if (isJsonMode()) {
13083
+ printJson(state);
13084
+ return;
13085
+ }
13086
+ printLine(
13087
+ `${state.dryRun ? `Would ${verb.toLowerCase()}` : verb} ${state.postId}${state.review ? " (waiting for review)" : ""}`
13088
+ );
13089
+ for (const schedule of state.schedules) {
13090
+ printLine(
13091
+ ` ${schedule.platform.toLowerCase()} ${schedule.channelName} ${schedule.status.toLowerCase()} ${schedule.scheduledAt ?? "\u2014"} ${schedule.scheduleId}`
13092
+ );
13093
+ }
13094
+ if (!state.dryRun) printStatus(state.url);
13095
+ }
13096
+ async function post(text, options) {
13097
+ const thread = options.threadFile ? await readThread(options.threadFile) : void 0;
13098
+ const content = thread ? void 0 : await readContent(text, options);
13099
+ if (!thread && !content) failUsage("No content. Pass text, --file, --thread-file, --editor, or pipe it in.");
13100
+ const timing = readTiming(options);
13101
+ const targets = readTargets(options);
13102
+ if (timing.postAction !== "DRAFT" && !targets.platforms && !targets.selectedIntegrations) {
13103
+ failUsage("Say where to post: --to x,linkedin or --channel <id> (or use --draft).");
13104
+ }
13105
+ const { api } = await getApi();
13106
+ const media2 = options.dryRun ? [] : await uploadAll(api, options.media);
13021
13107
  try {
13022
- const result = await api.posts.create({
13108
+ const { posts } = await api.posts.create({
13023
13109
  rows: [
13024
13110
  {
13025
- content,
13026
- scheduledAt,
13111
+ content: thread ? thread.join("\n\n") : content,
13112
+ scheduledAt: "scheduledAt" in timing ? timing.scheduledAt : void 0,
13027
13113
  media: media2.map((item) => ({ url: item.url, type: item.type, id: item.mediaId, fileId: item.uploadId }))
13028
13114
  }
13029
13115
  ],
13030
- shared: { selectedIntegrations: integrationIds },
13031
- postAction
13116
+ shared: { ...targets, thread, integrationContent: readCopy(options.copy) },
13117
+ postAction: timing.postAction,
13118
+ dryRun: options.dryRun
13032
13119
  });
13120
+ const created = posts[0];
13121
+ if (!created) return fail("The server created no post.");
13122
+ printState(created, timing.postAction === "DRAFT" ? "Saved draft" : "Scheduled");
13123
+ } catch (error2) {
13124
+ failApi(error2);
13125
+ }
13126
+ }
13127
+ async function editPost(postId, text, options) {
13128
+ const thread = options.threadFile ? await readThread(options.threadFile) : void 0;
13129
+ const content = thread ? void 0 : await readContent(text, options);
13130
+ const targets = readTargets(options);
13131
+ const integrationContent = readCopy(options.copy);
13132
+ const scheduledAt = options.at ? parseInstant(options.at, "--at") : void 0;
13133
+ if (!thread && content === void 0 && !targets.platforms && !targets.selectedIntegrations && !integrationContent && !scheduledAt && !options.media?.length) {
13134
+ failUsage("Nothing to change. Pass new text, --thread-file, --at, --to, --channel, --copy or --media.");
13135
+ }
13136
+ const { api } = await getApi();
13137
+ const media2 = options.media?.length ? await uploadAll(api, options.media) : void 0;
13138
+ try {
13139
+ const state = await api.posts.update({
13140
+ id: postId,
13141
+ content,
13142
+ thread,
13143
+ scheduledAt,
13144
+ ...targets,
13145
+ integrationContent,
13146
+ media: media2?.map((item) => ({ url: item.url, type: item.type, id: item.mediaId, fileId: item.uploadId })),
13147
+ dryRun: options.dryRun
13148
+ });
13149
+ printState(state, "Updated");
13150
+ } catch (error2) {
13151
+ failApi(error2);
13152
+ }
13153
+ }
13154
+ async function deletePost(postId, options) {
13155
+ const { api } = await getApi();
13156
+ try {
13157
+ const state = await api.posts.delete({ id: postId, deleteRemote: options.remote ?? false });
13033
13158
  if (isJsonMode()) {
13034
- printJson({ postId: result.postId, postIds: result.postIds, scheduleCount: result.scheduleCount });
13159
+ printJson(state);
13035
13160
  return;
13036
13161
  }
13037
- printLine(
13038
- postAction === "DRAFT" ? `Draft saved (${result.postId})` : `Scheduled ${result.scheduleCount} post${result.scheduleCount === 1 ? "" : "s"} (${result.postId})`
13039
- );
13162
+ printLine(`Deleted ${postId}${state.deletedFromPlatforms ? ", and on its platforms" : ""}`);
13040
13163
  } catch (error2) {
13041
- fail(describeError(error2));
13164
+ failApi(error2);
13042
13165
  }
13043
13166
  }
13044
- function bestTimes(options) {
13167
+ async function retrySchedule(scheduleId, options) {
13168
+ const { api } = await getApi();
13169
+ try {
13170
+ printState(await api.posts.retrySchedule({ scheduleId, content: options.content }), "Queued again");
13171
+ } catch (error2) {
13172
+ failApi(error2);
13173
+ }
13174
+ }
13175
+ async function bestTimes(options) {
13045
13176
  const platforms = (options.to ?? "").split(",").map((value2) => value2.trim()).filter(Boolean).map(parsePlatform);
13046
13177
  if (platforms.length === 0) failUsage("Which platforms? e.g. --to x,linkedin");
13047
- const windows = getConsensusWindows(platforms);
13048
- if (isJsonMode()) {
13049
- printJson({ platforms, windows });
13050
- return;
13051
- }
13052
- if (windows.length === 0) {
13053
- printStatus(
13054
- platforms.length < 2 ? "Consensus windows need two or more platforms. Add another to --to." : "No overlapping recommended windows for those platforms."
13178
+ const count = Number.parseInt(options.count ?? "5", 10);
13179
+ if (!Number.isInteger(count) || count < 1 || count > 20) failUsage("--count must be between 1 and 20.");
13180
+ const { api } = await getApi();
13181
+ try {
13182
+ const result = await api.platforms.bestTimes({ platforms, count });
13183
+ if (isJsonMode()) {
13184
+ printJson(result);
13185
+ return;
13186
+ }
13187
+ printLine(
13188
+ formatTable(
13189
+ ["WHEN", "PLATFORMS", "SOURCE"],
13190
+ result.slots.map((slot) => [slot.scheduledAt, slot.platforms.join(", ").toLowerCase(), slot.source])
13191
+ )
13055
13192
  );
13056
- return;
13193
+ if (result.platformsWithoutData.length > 0) {
13194
+ printStatus(`No research for ${result.platformsWithoutData.join(", ").toLowerCase()}; those times are a default.`);
13195
+ }
13196
+ } catch (error2) {
13197
+ failApi(error2);
13057
13198
  }
13058
- printLine(
13059
- formatTable(
13060
- ["DAY", "WINDOW", "PLATFORMS"],
13061
- windows.map((window) => [
13062
- DAY_NAMES[window.dayOfWeek],
13063
- `${window.startTime}\u2013${window.endTime}`,
13064
- window.platforms.join(", ").toLowerCase()
13065
- ])
13066
- )
13067
- );
13068
13199
  }
13069
- var DAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
13070
13200
 
13071
13201
  // src/commands/queue.tsx
13072
13202
  import { jsx as jsx4 } from "react/jsx-runtime";
@@ -13106,14 +13236,12 @@ async function listQueue(options) {
13106
13236
  limit,
13107
13237
  direction: "forward",
13108
13238
  platforms: platforms.length > 0 ? platforms : void 0,
13109
- // Default to what "queue" means to a user: not-yet-published work.
13110
- // `PENDING` is not one of them — no such schedule status has ever
13111
- // existed, and asking for it made every default `queue list` a 500.
13112
- statuses: statuses.length > 0 ? statuses : ["SCHEDULED", "PUBLISHING"]
13239
+ // The same default as MCP's `list_queue`: work the user can still act on.
13240
+ statuses: statuses.length > 0 ? statuses : ["DRAFT", "SCHEDULED", "FAILED"]
13113
13241
  });
13114
13242
  schedules = result.schedules;
13115
13243
  } catch (error2) {
13116
- fail(describeError(error2));
13244
+ failApi(error2);
13117
13245
  }
13118
13246
  if (isJsonMode()) {
13119
13247
  printJson({
@@ -13148,49 +13276,61 @@ async function listQueue(options) {
13148
13276
  printLine(formatTable(HEADERS2, rows));
13149
13277
  }
13150
13278
  async function scheduleDraft(postId, options) {
13151
- if (Boolean(options.at) === Boolean(options.optimal)) failUsage("Say when to post: --at <ISO time> or --optimal.");
13152
- const when = options.at ? new Date(options.at) : void 0;
13153
- if (when && Number.isNaN(when.getTime())) {
13154
- failUsage(`Could not read "${options.at}" as a date. Use an ISO timestamp, e.g. 2026-08-01T09:30:00Z.`);
13155
- }
13156
- if (when && when.getTime() <= Date.now()) failUsage("That time is in the past.");
13279
+ if (Boolean(options.at) === Boolean(options.optimal)) failUsage("Say when to post: --at <time> or --optimal.");
13280
+ const scheduledAt = options.at ? parseInstant(options.at, "--at") : void 0;
13157
13281
  const channelIds = options.channels?.split(",").map((id) => id.trim()).filter(Boolean);
13158
13282
  const { api } = await getApi();
13159
- let post2;
13160
13283
  try {
13161
- post2 = await api.posts.scheduleDraft({
13284
+ const state = await api.posts.scheduleDraft({
13162
13285
  id: postId,
13163
- scheduledAt: when,
13286
+ scheduledAt,
13164
13287
  useOptimalTime: options.optimal,
13165
- selectedIntegrations: channelIds?.length ? channelIds : void 0
13288
+ selectedIntegrations: channelIds?.length ? channelIds : void 0,
13289
+ dryRun: options.dryRun
13166
13290
  });
13291
+ if (isJsonMode()) {
13292
+ printJson(state);
13293
+ return;
13294
+ }
13295
+ const when = state.schedules.find((schedule) => schedule.scheduledAt)?.scheduledAt;
13296
+ printLine(`${state.dryRun ? "Would schedule" : "Scheduled"} ${postId} for ${when ?? "its next window"}`);
13167
13297
  } catch (error2) {
13168
- fail(describeError(error2));
13169
- }
13170
- const times = post2.schedules.flatMap((schedule) => schedule.scheduledAt ? [schedule.scheduledAt] : []);
13171
- if (isJsonMode()) {
13172
- printJson({ postId, schedules: post2.schedules.map(({ id, scheduledAt, status }) => ({ id, scheduledAt, status })) });
13173
- return;
13298
+ failApi(error2);
13174
13299
  }
13175
- printLine(`Scheduled ${postId} for ${times[0] ?? "its next window"}`);
13176
13300
  }
13177
13301
  async function moveQueueItem(scheduleId, options) {
13178
- const when = new Date(options.at);
13179
- if (Number.isNaN(when.getTime())) {
13180
- failUsage(`Could not read "${options.at}" as a date. Use an ISO timestamp, e.g. 2026-08-01T09:30:00Z.`);
13181
- }
13182
- if (when.getTime() <= Date.now()) failUsage("That time is in the past.");
13302
+ const scheduledAt = parseInstant(options.at, "--at");
13183
13303
  const { api } = await getApi();
13184
13304
  try {
13185
- await api.posts.rescheduleSchedule({ scheduleId, scheduledAt: when.toISOString() });
13305
+ const state = await api.posts.rescheduleSchedule({ scheduleId, scheduledAt });
13306
+ if (isJsonMode()) {
13307
+ printJson(state);
13308
+ return;
13309
+ }
13310
+ printLine(`Moved ${scheduleId} to ${scheduledAt}`);
13186
13311
  } catch (error2) {
13187
- fail(describeError(error2));
13312
+ failApi(error2);
13188
13313
  }
13189
- if (isJsonMode()) {
13190
- printJson({ scheduleId, scheduledAt: when.toISOString() });
13191
- return;
13314
+ }
13315
+
13316
+ // src/commands/workspaces.ts
13317
+ async function listWorkspaces() {
13318
+ const { api } = await getApi();
13319
+ try {
13320
+ const workspaces = await api.workspace.list();
13321
+ if (isJsonMode()) {
13322
+ printJson({ workspaces: workspaces.map(({ id, name, role }) => ({ id, name, role })) });
13323
+ return;
13324
+ }
13325
+ printLine(
13326
+ formatTable(
13327
+ ["NAME", "ROLE", "ID"],
13328
+ workspaces.map((w) => [w.name, w.role, w.id])
13329
+ )
13330
+ );
13331
+ } catch (error2) {
13332
+ failApi(error2);
13192
13333
  }
13193
- printLine(`Moved ${scheduleId} to ${when.toISOString()}`);
13194
13334
  }
13195
13335
 
13196
13336
  // src/index.ts
@@ -13198,7 +13338,7 @@ var program = new Command();
13198
13338
  program.exitOverride((error2) => {
13199
13339
  process.exit(error2.exitCode === 0 ? EXIT.ok : EXIT.usage);
13200
13340
  });
13201
- program.name("postonus").description("Schedule and publish social posts from your terminal").version(CLI_VERSION, "-v, --version").option("--json", "output machine-readable JSON on stdout").option("-q, --quiet", "suppress progress output on stderr").option("--no-color", "disable coloured output").option("--no-input", "never prompt; fail instead of waiting for input").addHelpText(
13341
+ program.name("postonus").description("Schedule and publish social posts from your terminal").version(CLI_VERSION, "-v, --version").option("--json", "output machine-readable JSON on stdout").option("-q, --quiet", "suppress progress output on stderr").option("--no-color", "disable coloured output").option("--no-input", "never prompt; fail instead of waiting for input").option("-w, --workspace <id>", "workspace to act in (from `postonus workspaces list`); sent as x-workspace-id").addHelpText(
13202
13342
  "after",
13203
13343
  `
13204
13344
  Environment:
@@ -13207,10 +13347,17 @@ Environment:
13207
13347
  ${"EDITOR".padEnd(18)} editor opened by \`post --editor\`
13208
13348
  ${"NO_COLOR".padEnd(18)} disable coloured output
13209
13349
 
13350
+ Times are RFC 3339 with an offset: 2026-08-01T09:30:00Z or 2026-08-01T11:30:00+02:00.
13351
+
13352
+ Exit codes:
13353
+ 0 ok, 1 other failure, 2 usage or validation, 3 auth, 4 plan or quota, 5 rate limit.
13354
+ With --json a failure prints { code, message, data: { violations } } on stdout.
13355
+
13210
13356
  Examples:
13211
13357
  $ postonus login
13212
13358
  $ postonus post "shipping today" --to x,linkedin --optimal
13213
13359
  $ postonus post --file notes.md --to linkedin --at 2026-08-01T09:30:00Z
13360
+ $ postonus post --thread-file thread.md --channel <id> --at 2026-08-01T09:30:00Z --dry-run
13214
13361
  $ postonus queue list --json | jq '.queue[].scheduledAt'
13215
13362
  $ postonus media upload ./demo.mp4
13216
13363
 
@@ -13227,17 +13374,23 @@ program.command("whoami").description("show the signed-in account").action(whoam
13227
13374
  var channels = program.command("channels").description("manage connected channels");
13228
13375
  channels.command("list").alias("ls").description("list connected channels").action(listChannels);
13229
13376
  channels.command("connect").description("connect a new channel via OAuth").option("-p, --platform <platform>", "platform to connect (prompts when omitted)").option("--no-wait", "return immediately instead of waiting for approval").action(connectChannel);
13230
- program.command("post").description("schedule a post (never publishes immediately)").argument("[text]", "post content; also accepts piped stdin").option("-t, --to <platforms>", "comma-separated platforms, e.g. x,linkedin").option("-a, --at <time>", "ISO timestamp to publish at").option("-o, --optimal", "use the next recommended window").option("-d, --draft", "save as a draft without scheduling").option("-f, --file <path>", "read content from a file").option("-e, --editor", "compose in $EDITOR").option("-m, --media <path...>", "attach local image or video files").option("--dry-run", "show what would be scheduled without doing it").action(post);
13231
- program.command("best-times").description("recommended posting windows for the given platforms").requiredOption("-t, --to <platforms>", "comma-separated platforms, e.g. x,linkedin").action(bestTimes);
13377
+ var collect = (value2, previous = []) => [...previous, value2];
13378
+ var postCommand = program.command("post").description("create a post: scheduled, now, at the next optimal time, or as a draft").argument("[text]", "post content; also accepts piped stdin").option("-t, --to <platforms>", "comma-separated platforms, e.g. x,linkedin").option("-c, --channel <id>", "a channel id from `postonus channels list`; repeatable", collect).option("-a, --at <time>", "RFC 3339 time with an offset").option("-o, --optimal", "the next recommended window").option("--now", "publish as soon as the queue picks it up").option("-d, --draft", "save as a draft without scheduling").option("-f, --file <path>", "read content from a file").option("--thread-file <path>", "read a thread: segments separated by a line of ---").option("-e, --editor", "compose in $EDITOR").option("-m, --media <path...>", "attach local image or video files").option("--copy <channelId=text>", "text that replaces the body on one channel; repeatable", collect).option("--dry-run", "run every server check and show the result without saving").action(post);
13379
+ postCommand.command("edit").description("change a post; only the flags given change").argument("<postId>", "post id from `postonus queue list`").argument("[text]", "new content").option("-t, --to <platforms>", "replace the channels with these platforms").option("-c, --channel <id>", "replace the channels with these ids; repeatable", collect).option("-a, --at <time>", "move every channel to this RFC 3339 time").option("-f, --file <path>", "read new content from a file").option("--thread-file <path>", "replace the body with a thread file").option("-m, --media <path...>", "replace the media with these files").option("--copy <channelId=text>", "replace one channel's copy; repeatable", collect).option("--dry-run", "run every server check and show the result without saving").action(editPost);
13380
+ postCommand.command("delete").description("delete a post and every schedule on it").argument("<postId>", "post id from `postonus queue list`").option("--remote", "also delete published copies on their platforms").action(deletePost);
13381
+ postCommand.command("retry").description("queue a failed schedule to publish again").argument("<scheduleId>", "schedule id from `postonus queue list --status failed`").option("--content <text>", "replacement copy for this channel only").action(retrySchedule);
13382
+ program.command("best-times").description("recommended posting windows for the given platforms").requiredOption("-t, --to <platforms>", "comma-separated platforms, e.g. x,linkedin").option("-n, --count <count>", "how many times to list (1-20)", "5").action(bestTimes);
13383
+ program.command("workspaces").description("workspaces you belong to").command("list").alias("ls").description("list workspaces and their ids").action(listWorkspaces);
13232
13384
  var queue = program.command("queue").description("inspect and adjust scheduled posts");
13233
- queue.command("list").alias("ls").description("list upcoming scheduled posts").addOption(new Option("-n, --limit <count>", "how many to show (10-100)").default("20")).option("-t, --to <platforms>", "filter by comma-separated platforms").option("-s, --status <statuses>", "filter by comma-separated statuses").action(listQueue);
13234
- queue.command("schedule").description("give a draft its send time").argument("<postId>", "post id from `postonus queue list --status draft` or `postonus post --draft`").option("-a, --at <time>", "ISO timestamp").option("-o, --optimal", "next recommended window").option(
13385
+ queue.command("list").alias("ls").description("list drafts, scheduled posts and failures").addOption(new Option("-n, --limit <count>", "how many to show (10-100)").default("20")).option("-t, --to <platforms>", "filter by comma-separated platforms").option("-s, --status <statuses>", "filter by comma-separated statuses").action(listQueue);
13386
+ queue.command("schedule").description("give a draft its send time").argument("<postId>", "post id from `postonus queue list --status draft` or `postonus post --draft`").option("-a, --at <time>", "RFC 3339 time with an offset").option("-o, --optimal", "next recommended window").option("--dry-run", "run every server check and show the result without saving").option(
13235
13387
  "-c, --channels <ids>",
13236
13388
  "comma-separated channel ids from `postonus channels list`; needed if the draft has none"
13237
13389
  ).action(scheduleDraft);
13238
- queue.command("move").description("reschedule one queued post").argument("<scheduleId>", "schedule id from `postonus queue list`").requiredOption("-a, --at <time>", "new ISO timestamp").action(moveQueueItem);
13390
+ queue.command("move").description("reschedule one queued post").argument("<scheduleId>", "schedule id from `postonus queue list`").requiredOption("-a, --at <time>", "new RFC 3339 time with an offset").action(moveQueueItem);
13239
13391
  var media = program.command("media").description("upload media for use in posts");
13240
13392
  media.command("upload").description("upload one or more local files").argument("<paths...>", "local image or video paths").action(uploadCommand);
13393
+ media.command("import").description("import an image or video from a public URL").argument("<url>", "public http(s) URL").action(importCommand);
13241
13394
  program.command("mcp").description("serve the Postonus MCP tools over stdio for an editor").action(mcpServe);
13242
13395
  try {
13243
13396
  await program.parseAsync(process.argv);