@happyvertical/garrula 0.1.6 → 0.1.8

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
@@ -1,8 +1,8 @@
1
+ import { SocialError, getSocial } from "@happyvertical/social";
1
2
  import { Agent } from "@happyvertical/smrt-agents";
2
3
  import { SmrtCollection, SmrtObject, smrt } from "@happyvertical/smrt-core";
3
4
  import { SocialAccountCollection, SocialPostAnalyticsSnapshotCollection, SocialPostCollection } from "@happyvertical/smrt-social";
4
5
  import { TenantScoped, getTenantId, tenantId, withTenant } from "@happyvertical/smrt-tenancy";
5
- import { SocialError, getSocial } from "@happyvertical/social";
6
6
  //#region src/credentials.ts
7
7
  /**
8
8
  * Social OAuth token upkeep for Garrula's publisher.
@@ -380,6 +380,13 @@ var GarrulaOutboundPost = class GarrulaOutboundPost extends SmrtObject {
380
380
  sourceKind = "package-publish";
381
381
  sourceUrl = null;
382
382
  claims = [];
383
+ media = null;
384
+ youtubeMetadata = null;
385
+ parentOutboundId = null;
386
+ xRepostMode = null;
387
+ requestedTargetAccountIds = null;
388
+ requestedXRepostMode = null;
389
+ utmCampaign = null;
383
390
  /** Who supplied a manual draft (`createDraft`); null for ingested drafts. */
384
391
  createdBy = null;
385
392
  approvedBy = null;
@@ -394,6 +401,13 @@ var GarrulaOutboundPost = class GarrulaOutboundPost extends SmrtObject {
394
401
  if (options.sourceKind !== void 0) this.sourceKind = options.sourceKind;
395
402
  if (options.sourceUrl !== void 0) this.sourceUrl = options.sourceUrl;
396
403
  if (options.claims !== void 0) this.claims = options.claims;
404
+ if (options.media !== void 0) this.media = options.media;
405
+ if (options.youtubeMetadata !== void 0) this.youtubeMetadata = options.youtubeMetadata;
406
+ if (options.parentOutboundId !== void 0) this.parentOutboundId = options.parentOutboundId;
407
+ if (options.xRepostMode !== void 0) this.xRepostMode = options.xRepostMode;
408
+ if (options.requestedTargetAccountIds !== void 0) this.requestedTargetAccountIds = options.requestedTargetAccountIds;
409
+ if (options.requestedXRepostMode !== void 0) this.requestedXRepostMode = options.requestedXRepostMode;
410
+ if (options.utmCampaign !== void 0) this.utmCampaign = options.utmCampaign;
397
411
  if (options.createdBy !== void 0) this.createdBy = options.createdBy;
398
412
  if (options.approvedBy !== void 0) this.approvedBy = options.approvedBy;
399
413
  if (options.rejectedReason !== void 0) this.rejectedReason = options.rejectedReason;
@@ -455,12 +469,16 @@ var GarrulaSourceEvent = class GarrulaSourceEvent extends SmrtObject {
455
469
  /** `drafted` | `ignored` */
456
470
  outcome = "ignored";
457
471
  outboundPostIds = [];
472
+ requestedTargetAccountIds = null;
473
+ requestedXRepostMode = null;
458
474
  constructor(options = {}) {
459
475
  super(options);
460
476
  if (options.tenantId !== void 0) this.tenantId = options.tenantId;
461
477
  if (options.eventKey !== void 0) this.eventKey = options.eventKey;
462
478
  if (options.outcome !== void 0) this.outcome = options.outcome;
463
479
  if (options.outboundPostIds !== void 0) this.outboundPostIds = options.outboundPostIds;
480
+ if (options.requestedTargetAccountIds !== void 0) this.requestedTargetAccountIds = options.requestedTargetAccountIds;
481
+ if (options.requestedXRepostMode !== void 0) this.requestedXRepostMode = options.requestedXRepostMode;
464
482
  }
465
483
  };
466
484
  __decorate([tenantId({ nullable: false }), __decorateMetadata("design:type", Object)], GarrulaSourceEvent.prototype, "tenantId", void 0);
@@ -624,6 +642,13 @@ var OUTBOUND_STATES = [
624
642
  "failed",
625
643
  "rejected"
626
644
  ];
645
+ var YOUTUBE_MAX_TITLE_LENGTH = 100;
646
+ var YOUTUBE_MAX_DESCRIPTION_LENGTH = 5e3;
647
+ var X_REPOST_MODES = [
648
+ "teaser_plus_link",
649
+ "full_video",
650
+ "link_only"
651
+ ];
627
652
  /** Thrown by the public API for refused changes (never for a publish). */
628
653
  var OutboundError = class extends Error {
629
654
  code;
@@ -644,6 +669,10 @@ async function createOutboundStores(options) {
644
669
  events: await GarrulaSourceEventCollection.create(opts)
645
670
  };
646
671
  }
672
+ /** Unready only because the access token's recorded expiry has passed. */
673
+ function isLapsedOnly(account) {
674
+ return account.isActive !== false && account.status === "connected" && account.hasCredentials && (account.missingPermissions?.length ?? 0) === 0 && (account.publishMode !== "public" || account.publicPublishingAllowed === true) && account.isTokenExpired;
675
+ }
647
676
  var locks = /* @__PURE__ */ new Map();
648
677
  function withLock(tenantId, fn) {
649
678
  const run = (locks.get(tenantId) ?? Promise.resolve()).then(fn, fn);
@@ -669,13 +698,145 @@ var OUTBOUND_POST_MARKER = "garrula-outbound:";
669
698
  function isOutboundMarked(post) {
670
699
  return typeof post.title === "string" && post.title.startsWith("garrula-outbound:");
671
700
  }
701
+ var VALID_ASPECT_RATIOS = [
702
+ "16:9",
703
+ "9:16",
704
+ "1:1"
705
+ ];
706
+ function validateYouTubeMetadata(input) {
707
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new OutboundError("invalid", "YouTube metadata must be an object.");
708
+ const raw = input;
709
+ const title = typeof raw.title === "string" ? raw.title.trim() : "";
710
+ if (!title) throw new OutboundError("invalid", "YouTube metadata requires a non-empty title.");
711
+ if (title.length > 100) throw new OutboundError("invalid", `YouTube title must be at most 100 characters.`);
712
+ let description;
713
+ if (raw.description !== void 0 && raw.description !== null) {
714
+ if (typeof raw.description !== "string") throw new OutboundError("invalid", "YouTube description must be a string.");
715
+ if (raw.description.length > 5e3) throw new OutboundError("invalid", `YouTube description must be at most ${YOUTUBE_MAX_DESCRIPTION_LENGTH} characters.`);
716
+ description = raw.description;
717
+ }
718
+ let tags;
719
+ if (raw.tags !== void 0 && raw.tags !== null) {
720
+ if (!Array.isArray(raw.tags)) throw new OutboundError("invalid", "YouTube tags must be a list of strings.");
721
+ tags = [...new Set(raw.tags.map((item) => String(item ?? "").trim()).filter(Boolean))];
722
+ }
723
+ return {
724
+ title,
725
+ ...description !== void 0 ? { description } : {},
726
+ ...tags !== void 0 ? { tags } : {}
727
+ };
728
+ }
729
+ function normalizeAttachMedia(input) {
730
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new OutboundError("invalid", "Media attachment requires postType and videoContentId.");
731
+ if (input.postType !== "video" && input.postType !== "image") throw new OutboundError("invalid", "postType must be 'video' or 'image'.");
732
+ const videoContentId = typeof input.videoContentId === "string" ? input.videoContentId.trim() : "";
733
+ if (!videoContentId) throw new OutboundError("invalid", "videoContentId cannot be empty.");
734
+ let hasMediaUrl = false;
735
+ let mediaUrl;
736
+ if (input.mediaUrl !== void 0) {
737
+ hasMediaUrl = true;
738
+ if (input.mediaUrl === null) mediaUrl = null;
739
+ else if (typeof input.mediaUrl === "string") {
740
+ const trimmed = input.mediaUrl.trim();
741
+ if (!trimmed || /^(javascript|data):/i.test(trimmed)) throw new OutboundError("invalid", "mediaUrl must be a valid media URL.");
742
+ mediaUrl = trimmed;
743
+ } else throw new OutboundError("invalid", "mediaUrl must be a string or null.");
744
+ }
745
+ let variants;
746
+ if (input.variants !== void 0) {
747
+ if (!Array.isArray(input.variants)) throw new OutboundError("invalid", "variants must be a list.");
748
+ variants = input.variants.map((item) => {
749
+ if (!item || typeof item !== "object" || Array.isArray(item)) throw new OutboundError("invalid", "Each media variant must be an object.");
750
+ const vid = typeof item.videoContentId === "string" ? item.videoContentId.trim() : "";
751
+ if (!vid) throw new OutboundError("invalid", "Each media variant requires a non-empty videoContentId.");
752
+ if (item.aspectRatio !== void 0 && !VALID_ASPECT_RATIOS.includes(item.aspectRatio)) throw new OutboundError("invalid", `Unsupported aspectRatio: ${String(item.aspectRatio)}.`);
753
+ let outputId;
754
+ if (item.outputId !== void 0) {
755
+ const trimmedOut = typeof item.outputId === "string" ? item.outputId.trim() : "";
756
+ if (!trimmedOut) throw new OutboundError("invalid", "Variant outputId must be a non-empty string.");
757
+ outputId = trimmedOut;
758
+ }
759
+ if (item.isShort !== void 0 && typeof item.isShort !== "boolean") throw new OutboundError("invalid", "Variant isShort must be a boolean.");
760
+ if (item.role !== void 0 && item.role !== "primary" && item.role !== "teaser") throw new OutboundError("invalid", "Variant role must be 'primary' or 'teaser'.");
761
+ return {
762
+ ...outputId !== void 0 ? { outputId } : {},
763
+ ...item.aspectRatio !== void 0 ? { aspectRatio: item.aspectRatio } : {},
764
+ videoContentId: vid,
765
+ ...item.isShort !== void 0 ? { isShort: item.isShort } : {},
766
+ ...item.role !== void 0 ? { role: item.role } : {}
767
+ };
768
+ });
769
+ }
770
+ const youtube = input.youtube !== void 0 ? validateYouTubeMetadata(input.youtube) : void 0;
771
+ return {
772
+ media: {
773
+ postType: input.postType,
774
+ videoContentId,
775
+ ...variants !== void 0 ? { variants } : {},
776
+ ...youtube !== void 0 ? { youtube } : {}
777
+ },
778
+ hasMediaUrl,
779
+ mediaUrl
780
+ };
781
+ }
782
+ function selectMediaVariant(media, platform, postVideoContentId, xRepostMode) {
783
+ if (!media?.variants?.length) return null;
784
+ const { variants } = media;
785
+ if (platform === "youtube") return variants.find((v) => v.role === "primary") ?? variants.find((v) => v.aspectRatio === "16:9") ?? variants[0] ?? null;
786
+ if (platform === "x" && xRepostMode === "teaser_plus_link") return variants.find((v) => v.role === "teaser") ?? variants.find((v) => v.aspectRatio === "9:16") ?? variants.find((v) => v.aspectRatio === "1:1") ?? (postVideoContentId ? variants.find((v) => v.videoContentId === postVideoContentId) : void 0) ?? variants[0] ?? null;
787
+ if (platform === "x" && xRepostMode === "full_video") return variants.find((v) => v.role === "primary") ?? variants.find((v) => v.aspectRatio === "16:9") ?? (media.videoContentId ? variants.find((v) => v.videoContentId === media.videoContentId) : void 0) ?? null;
788
+ return (postVideoContentId ? variants.find((v) => v.videoContentId === postVideoContentId) : void 0) ?? variants.find((v) => v.aspectRatio === "9:16") ?? variants[0] ?? null;
789
+ }
790
+ function buildPairedYouTubeUrl(youtubeUrl, draftLinkUrl, configuredUtmCampaign) {
791
+ let utm = configuredUtmCampaign?.trim() || null;
792
+ if (!utm && draftLinkUrl) try {
793
+ utm = new URL(draftLinkUrl).searchParams.get("utm_campaign")?.trim() || null;
794
+ } catch {}
795
+ if (!utm) return youtubeUrl;
796
+ try {
797
+ const parsed = new URL(youtubeUrl);
798
+ if (!parsed.searchParams.has("utm_campaign")) parsed.searchParams.set("utm_campaign", utm);
799
+ return parsed.toString();
800
+ } catch {
801
+ return `${youtubeUrl}${youtubeUrl.includes("?") ? "&" : "?"}utm_campaign=${encodeURIComponent(utm)}`;
802
+ }
803
+ }
804
+ function stripUrlFromDescription(description, url) {
805
+ if (!url || !description.includes(url)) return description;
806
+ return description.replace(url, "").trim();
807
+ }
808
+ function computeXPostLength(text, hashtags, linkUrl, linkBehavior) {
809
+ const cleanText = linkUrl ? stripUrlFromDescription(text, linkUrl) : text;
810
+ const suffixParts = [];
811
+ if (linkUrl && linkBehavior !== "reply" && linkBehavior !== "none") suffixParts.push(linkUrl);
812
+ if (hashtags.length > 0) suffixParts.push(hashtags.map((tag) => tag.startsWith("#") ? tag : `#${tag}`).join(" "));
813
+ const suffix = suffixParts.join("\n\n");
814
+ if (!suffix) return cleanText.length;
815
+ const separator = cleanText.length > 0 ? "\n\n" : "";
816
+ return cleanText.length + separator.length + suffix.length;
817
+ }
818
+ function sameStringArray(a, b) {
819
+ const normA = a && a.length > 0 ? a : null;
820
+ const normB = b && b.length > 0 ? b : null;
821
+ if (normA === null && normB === null) return true;
822
+ if (normA === null || normB === null) return false;
823
+ if (normA.length !== normB.length) return false;
824
+ return normA.every((item, idx) => item === normB[idx]);
825
+ }
826
+ function fallbackMediaUrlForVariant(media, resolvedVideoContentId, hasMediaUrl, mediaUrl) {
827
+ if (!hasMediaUrl) return void 0;
828
+ if (resolvedVideoContentId && resolvedVideoContentId !== media.videoContentId) return null;
829
+ return mediaUrl ?? null;
830
+ }
672
831
  var OutboundService = class {
673
832
  stores;
674
833
  social;
675
834
  configFn;
676
835
  aiFn;
677
836
  nowFn;
837
+ refreshAccount;
678
838
  constructor(options) {
839
+ this.refreshAccount = options.refreshAccount;
679
840
  this.stores = options.stores;
680
841
  this.social = options.social;
681
842
  this.configFn = options.config;
@@ -893,6 +1054,34 @@ var OutboundService = class {
893
1054
  }));
894
1055
  const linkUrl = input.linkUrl?.trim() || null;
895
1056
  if (linkUrl && !/^https?:\/\/\S+$/i.test(linkUrl)) throw new OutboundError("invalid", "linkUrl must be an http(s) URL.");
1057
+ let requestedTargetAccountIds;
1058
+ let canonicalTargetAccountIds = null;
1059
+ if (input.targetAccountIds !== void 0) {
1060
+ if (!Array.isArray(input.targetAccountIds)) throw new OutboundError("invalid", "targetAccountIds must be a list of account IDs.");
1061
+ if (input.targetAccountIds.length === 0) throw new OutboundError("invalid", "targetAccountIds cannot be empty.");
1062
+ const trimmedIds = input.targetAccountIds.map((id) => typeof id === "string" ? id.trim() : "");
1063
+ if (trimmedIds.some((id) => !id)) throw new OutboundError("invalid", "targetAccountIds must contain non-empty account IDs.");
1064
+ requestedTargetAccountIds = [...new Set(trimmedIds)];
1065
+ canonicalTargetAccountIds = [...requestedTargetAccountIds].sort();
1066
+ }
1067
+ let xRepostMode = null;
1068
+ if (input.xRepostMode !== void 0) {
1069
+ if (!X_REPOST_MODES.includes(input.xRepostMode)) throw new OutboundError("invalid", `Unknown xRepostMode: ${String(input.xRepostMode)}.`);
1070
+ xRepostMode = input.xRepostMode;
1071
+ }
1072
+ let utmCampaign = null;
1073
+ if (input.utmCampaign !== void 0 && input.utmCampaign !== null) {
1074
+ if (typeof input.utmCampaign !== "string") throw new OutboundError("invalid", "utmCampaign must be a string or null.");
1075
+ utmCampaign = input.utmCampaign.trim() || null;
1076
+ }
1077
+ const normalizedMedia = input.media !== void 0 ? normalizeAttachMedia(input.media) : null;
1078
+ const validatedYoutube = input.youtube !== void 0 ? validateYouTubeMetadata(input.youtube) : null;
1079
+ if (normalizedMedia?.media.youtube && validatedYoutube && JSON.stringify(normalizedMedia.media.youtube) !== JSON.stringify(validatedYoutube)) throw new OutboundError("invalid", "Conflicting YouTube metadata was supplied.");
1080
+ const effectiveYoutube = normalizedMedia?.media.youtube ?? validatedYoutube ?? null;
1081
+ const effectiveMedia = normalizedMedia ? {
1082
+ ...normalizedMedia.media,
1083
+ ...effectiveYoutube ? { youtube: effectiveYoutube } : {}
1084
+ } : null;
896
1085
  return withLock(tenantId, () => withTenant({ tenantId }, async () => {
897
1086
  const ledgerKey = `manual:${key}`;
898
1087
  const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));
@@ -901,6 +1090,7 @@ var OutboundService = class {
901
1090
  eventKey: ledgerKey
902
1091
  } })).find((row) => row.tenantId === tenantId);
903
1092
  if (seen) {
1093
+ if (!sameStringArray(seen.requestedTargetAccountIds ?? null, canonicalTargetAccountIds) || (seen.requestedXRepostMode ?? null) !== xRepostMode) throw new OutboundError("invalid", "Idempotency key replay conflicts with the original targetAccountIds or xRepostMode.");
904
1094
  const drafts = [];
905
1095
  for (const id of seen.outboundPostIds ?? []) drafts.push(await this.view(tenantId, await this.requireRow(tenantId, id), settings));
906
1096
  return {
@@ -908,8 +1098,21 @@ var OutboundService = class {
908
1098
  drafts
909
1099
  };
910
1100
  }
911
- const accounts = await this.targetAccounts(tenantId, settings);
1101
+ const accounts = requestedTargetAccountIds ? await this.resolveSelectedAccounts(tenantId, requestedTargetAccountIds) : await this.targetAccounts(tenantId, settings);
912
1102
  if (accounts.length === 0) return { outcome: "no-accounts" };
1103
+ let orderedAccounts = accounts;
1104
+ if (xRepostMode) {
1105
+ const ytAccounts = accounts.filter((a) => a.platform === "youtube");
1106
+ const xAccounts = accounts.filter((a) => a.platform === "x");
1107
+ if (ytAccounts.length !== 1) throw new OutboundError("invalid", "Paired YouTube-to-X publishing requires exactly one YouTube target account.");
1108
+ if (xAccounts.length === 0) throw new OutboundError("invalid", "Paired YouTube-to-X publishing requires at least one X target account.");
1109
+ const otherAccounts = accounts.filter((a) => a.platform !== "youtube" && a.platform !== "x");
1110
+ orderedAccounts = [
1111
+ ...ytAccounts,
1112
+ ...xAccounts,
1113
+ ...otherAccounts
1114
+ ];
1115
+ }
913
1116
  const drafts = [];
914
1117
  const ids = [];
915
1118
  const covered = /* @__PURE__ */ new Set();
@@ -918,17 +1121,45 @@ var OutboundService = class {
918
1121
  sourceKind: "manual",
919
1122
  sourceEventId: key
920
1123
  } })).filter((row) => row.tenantId === tenantId);
1124
+ let parentYoutubeRowId = null;
921
1125
  for (const row of earlier) {
922
1126
  const view = await this.view(tenantId, row, settings);
923
1127
  covered.add(view.accountId);
924
1128
  ids.push(row.id);
925
1129
  drafts.push(view);
1130
+ if (!row.parentOutboundId && view.accountId) {
1131
+ if (orderedAccounts.find((a) => a.id === view.accountId)?.platform === "youtube") parentYoutubeRowId = row.id;
1132
+ }
926
1133
  }
927
- for (const account of accounts) {
928
- if (covered.has(account.id)) continue;
1134
+ if (earlier.length > 0) {
1135
+ for (const row of earlier) if (!sameStringArray(row.requestedTargetAccountIds ?? null, canonicalTargetAccountIds) || (row.requestedXRepostMode ?? null) !== xRepostMode) throw new OutboundError("invalid", "Idempotency key retry conflicts with partially created targetAccountIds or xRepostMode.");
1136
+ }
1137
+ for (const account of orderedAccounts) {
1138
+ const accountId = account.id;
1139
+ if (covered.has(accountId)) continue;
1140
+ const isPairedYoutube = Boolean(xRepostMode && account.platform === "youtube");
1141
+ const isPairedX = Boolean(xRepostMode && account.platform === "x");
1142
+ let postType = "text";
1143
+ let videoContentId = null;
1144
+ let mediaUrl = null;
1145
+ let rowMedia = null;
1146
+ if (effectiveMedia) if (isPairedX && xRepostMode === "link_only") {
1147
+ postType = "text";
1148
+ videoContentId = null;
1149
+ mediaUrl = null;
1150
+ rowMedia = null;
1151
+ } else {
1152
+ const variant = selectMediaVariant(effectiveMedia, account.platform, null, isPairedX ? xRepostMode : null);
1153
+ postType = effectiveMedia.postType;
1154
+ videoContentId = variant?.videoContentId ?? effectiveMedia.videoContentId;
1155
+ mediaUrl = normalizedMedia?.hasMediaUrl ? fallbackMediaUrlForVariant(effectiveMedia, videoContentId, true, normalizedMedia.mediaUrl) ?? null : null;
1156
+ rowMedia = effectiveMedia;
1157
+ }
929
1158
  const post = await this.social.socialPosts.createDraft({
930
- socialAccountId: account.id,
931
- postType: "text",
1159
+ socialAccountId: accountId,
1160
+ postType,
1161
+ videoContentId,
1162
+ mediaUrl,
932
1163
  title: `${OUTBOUND_POST_MARKER}manual:${key}`,
933
1164
  description: text,
934
1165
  linkUrl,
@@ -945,12 +1176,20 @@ var OutboundService = class {
945
1176
  sourceKind: "manual",
946
1177
  sourceUrl: linkUrl,
947
1178
  claims,
1179
+ media: rowMedia,
1180
+ youtubeMetadata: isPairedYoutube || account.platform === "youtube" ? effectiveYoutube : null,
1181
+ parentOutboundId: isPairedX ? parentYoutubeRowId : null,
1182
+ xRepostMode: isPairedX ? xRepostMode : null,
1183
+ requestedTargetAccountIds: canonicalTargetAccountIds,
1184
+ requestedXRepostMode: xRepostMode,
1185
+ utmCampaign: isPairedYoutube || isPairedX ? utmCampaign : null,
948
1186
  createdBy
949
1187
  });
950
1188
  } catch (error) {
951
1189
  await this.discardSocialDraft(post);
952
1190
  throw error;
953
1191
  }
1192
+ if (isPairedYoutube) parentYoutubeRowId = row.id;
954
1193
  ids.push(row.id);
955
1194
  drafts.push(await this.view(tenantId, row, settings));
956
1195
  }
@@ -958,7 +1197,9 @@ var OutboundService = class {
958
1197
  tenantId,
959
1198
  eventKey: ledgerKey,
960
1199
  outcome: "drafted",
961
- outboundPostIds: ids
1200
+ outboundPostIds: ids,
1201
+ requestedTargetAccountIds: canonicalTargetAccountIds,
1202
+ requestedXRepostMode: xRepostMode
962
1203
  });
963
1204
  return {
964
1205
  outcome: "drafted",
@@ -966,8 +1207,52 @@ var OutboundService = class {
966
1207
  };
967
1208
  }));
968
1209
  }
1210
+ isAccountValidAndReady(account, tenantId) {
1211
+ return Boolean(account.id) && account.tenantId === tenantId && account.isActive !== false && account.status === "connected" && (account.missingPermissions?.length ?? 0) === 0 && account.isReady !== false;
1212
+ }
1213
+ async resolveSelectedAccounts(tenantId, requestedIds) {
1214
+ const readyById = /* @__PURE__ */ new Map();
1215
+ const ready = await this.social.socialAccounts.findReady();
1216
+ for (const account of ready) if (account.id && this.isAccountValidAndReady(account, tenantId)) readyById.set(account.id, account);
1217
+ const collection = this.social.socialAccounts;
1218
+ const missing = requestedIds.filter((id) => !readyById.has(id));
1219
+ if (missing.length > 0 && this.refreshAccount && typeof collection.findActive === "function") {
1220
+ const missingSet = new Set(missing);
1221
+ for (const account of await collection.findActive()) {
1222
+ if (!account.id || !missingSet.has(account.id) || account.tenantId !== tenantId || !isLapsedOnly(account)) continue;
1223
+ try {
1224
+ await this.refreshAccount(account);
1225
+ } catch {
1226
+ continue;
1227
+ }
1228
+ if (this.isAccountValidAndReady(account, tenantId)) readyById.set(account.id, account);
1229
+ }
1230
+ }
1231
+ const selected = [];
1232
+ for (const id of requestedIds) {
1233
+ const account = readyById.get(id);
1234
+ if (!account) throw new OutboundError("invalid", "One or more target accounts are invalid, inactive, or not ready for this tenant.");
1235
+ selected.push(account);
1236
+ }
1237
+ return selected;
1238
+ }
969
1239
  async targetAccounts(tenantId, settings) {
970
- return (await this.social.socialAccounts.findReady()).filter((account) => account.id && account.tenantId === tenantId && (settings.accountIds.length === 0 || settings.accountIds.includes(account.id)));
1240
+ const wanted = (account) => Boolean(account.id) && account.tenantId === tenantId && (settings.accountIds.length === 0 || settings.accountIds.includes(account.id));
1241
+ const ready = (await this.social.socialAccounts.findReady()).filter(wanted);
1242
+ const collection = this.social.socialAccounts;
1243
+ if (!this.refreshAccount || typeof collection.findActive !== "function") return ready;
1244
+ const readyIds = new Set(ready.map((account) => account.id));
1245
+ const accounts = [...ready];
1246
+ for (const account of (await collection.findActive()).filter(wanted)) {
1247
+ if (readyIds.has(account.id) || !isLapsedOnly(account)) continue;
1248
+ try {
1249
+ await this.refreshAccount(account);
1250
+ } catch {
1251
+ continue;
1252
+ }
1253
+ if (account.isReady) accounts.push(account);
1254
+ }
1255
+ return accounts;
971
1256
  }
972
1257
  async requireRow(tenantId, id) {
973
1258
  const row = (await this.stores.posts.list({ where: {
@@ -986,6 +1271,17 @@ var OutboundService = class {
986
1271
  const post = known === void 0 ? await this.loadPost(tenantId, row) : known;
987
1272
  const accountId = post?.socialAccountId ?? null;
988
1273
  const policy = accountId && settings.linkPolicy[accountId] || settings.defaultLinkPolicy;
1274
+ const media = row.media ?? (post && (post.postType === "video" || post.postType === "image") && post.videoContentId ? {
1275
+ postType: post.postType,
1276
+ videoContentId: post.videoContentId
1277
+ } : null);
1278
+ let linkUrl = policy === "include" ? post?.linkUrl ?? row.sourceUrl ?? null : null;
1279
+ if (row.parentOutboundId) {
1280
+ const parentRow = await this.requireRow(tenantId, row.parentOutboundId).catch(() => null);
1281
+ const parentPost = parentRow ? await this.loadPost(tenantId, parentRow) : null;
1282
+ const parentUrl = parentPost?.platformUrl?.trim() || "";
1283
+ if (parentPost?.status === "published" && parentUrl) linkUrl = buildPairedYouTubeUrl(parentUrl, post?.linkUrl ?? row.sourceUrl, row.utmCampaign);
1284
+ }
989
1285
  return {
990
1286
  id: row.id,
991
1287
  tenantId,
@@ -996,7 +1292,10 @@ var OutboundService = class {
996
1292
  text: post?.description ?? "",
997
1293
  hashtags: post?.hashtags ?? [],
998
1294
  claims: row.claims ?? [],
999
- linkUrl: policy === "include" ? post?.linkUrl ?? row.sourceUrl ?? null : null,
1295
+ linkUrl,
1296
+ media,
1297
+ parentOutboundId: row.parentOutboundId ?? null,
1298
+ xRepostMode: row.xRepostMode ?? null,
1000
1299
  sourceEventId: row.sourceEventId,
1001
1300
  sourceKind: row.sourceKind,
1002
1301
  createdBy: row.createdBy ?? null,
@@ -1057,18 +1356,210 @@ var OutboundService = class {
1057
1356
  }))
1058
1357
  }));
1059
1358
  }
1359
+ const post = await this.loadPost(tenantId, row);
1360
+ if (!post) throw new OutboundError("not-found", "The social post for this draft is missing.");
1361
+ const dependents = await this.findDependents(tenantId, row.id);
1362
+ await this.assertDependentsMutable(tenantId, dependents, "edited");
1363
+ const prevRowState = row.state;
1364
+ const prevRowApprovedBy = row.approvedBy;
1365
+ const prevRowClaims = row.claims;
1366
+ const back = state !== "draft";
1367
+ const undoStack = [];
1368
+ try {
1369
+ for (const dep of dependents) {
1370
+ if (dep.state === "draft" || dep.state === "published" || dep.state === "rejected") continue;
1371
+ const depPost = await this.loadPost(tenantId, dep);
1372
+ if (!depPost) throw new OutboundError("not-found", "The social post for a dependent draft is missing.");
1373
+ const prevDepState = dep.state;
1374
+ const prevDepApprovedBy = dep.approvedBy;
1375
+ await this.updateSocialPost(tenantId, dep, {
1376
+ status: socialStatusFor("draft"),
1377
+ scheduled_at: null
1378
+ });
1379
+ undoStack.push(() => this.updateSocialPost(tenantId, dep, {
1380
+ status: socialStatusFor(prevDepState),
1381
+ scheduled_at: depPost.scheduledAt ?? null
1382
+ }));
1383
+ dep.state = "draft";
1384
+ dep.approvedBy = null;
1385
+ await dep.save();
1386
+ undoStack.push(async () => {
1387
+ dep.state = prevDepState;
1388
+ dep.approvedBy = prevDepApprovedBy;
1389
+ await dep.save();
1390
+ });
1391
+ }
1392
+ const rollbackParentSocial = {
1393
+ ...patch.text !== void 0 ? { description: post.description } : {},
1394
+ ...patch.linkUrl !== void 0 ? { link_url: post.linkUrl ?? null } : {},
1395
+ ...back ? {
1396
+ status: socialStatusFor(state),
1397
+ scheduled_at: post.scheduledAt ?? null
1398
+ } : {}
1399
+ };
1400
+ await this.updateSocialPost(tenantId, row, {
1401
+ ...social,
1402
+ ...back ? {
1403
+ status: socialStatusFor("draft"),
1404
+ scheduled_at: null
1405
+ } : {}
1406
+ });
1407
+ undoStack.push(() => this.updateSocialPost(tenantId, row, rollbackParentSocial));
1408
+ if (back) {
1409
+ row.state = "draft";
1410
+ row.approvedBy = null;
1411
+ }
1412
+ await row.save();
1413
+ undoStack.push(async () => {
1414
+ row.state = prevRowState;
1415
+ row.approvedBy = prevRowApprovedBy;
1416
+ row.claims = prevRowClaims;
1417
+ await row.save();
1418
+ });
1419
+ } catch (error) {
1420
+ for (const undo of undoStack.reverse()) await undo().catch(() => void 0);
1421
+ throw error;
1422
+ }
1423
+ return this.getDraft(tenantId, id);
1424
+ });
1425
+ }
1426
+ /**
1427
+ * Attach a video or image reference (with optional aspect-ratio variants and
1428
+ * YouTube metadata) to an outbound draft. Like `editDraft`, attaching media
1429
+ * withdraws any existing approval back to `draft` (and on any paired
1430
+ * dependent X draft) while keeping the outbound marker on `SocialPost.title`
1431
+ * intact.
1432
+ */
1433
+ attachMedia(tenantId, id, input) {
1434
+ assertAmbientTenant(tenantId);
1435
+ const { media, hasMediaUrl, mediaUrl } = normalizeAttachMedia(input);
1436
+ return withLock(tenantId, () => withTenant({ tenantId }, async () => {
1437
+ const row = await this.requireRow(tenantId, id);
1438
+ const state = row.state;
1439
+ if (state === "published" || state === "rejected") throw new OutboundError("illegal-transition", `A ${state} post cannot have media attached.`);
1440
+ const post = await this.loadPost(tenantId, row);
1441
+ if (!post) throw new OutboundError("not-found", "The social post for this draft is missing.");
1442
+ const dependents = await this.findDependents(tenantId, row.id);
1443
+ await this.assertDependentsMutable(tenantId, dependents, "updated with new media");
1444
+ const effectiveYoutube = media.youtube ?? row.youtubeMetadata ?? void 0;
1445
+ const effectiveMedia = {
1446
+ ...media,
1447
+ ...effectiveYoutube ? { youtube: effectiveYoutube } : {}
1448
+ };
1449
+ const account = post.socialAccountId ? await this.social.socialAccounts.get({ id: post.socialAccountId }) : null;
1450
+ const isLinkOnly = row.xRepostMode === "link_only";
1451
+ const resolvedVariant = selectMediaVariant(effectiveMedia, account?.platform ?? "", post.videoContentId, row.xRepostMode ?? null);
1452
+ const resolvedVideoContentId = isLinkOnly ? null : resolvedVariant?.videoContentId ?? effectiveMedia.videoContentId;
1453
+ const resolvedPostType = isLinkOnly ? "text" : effectiveMedia.postType;
1454
+ const parentAssignedMediaUrl = fallbackMediaUrlForVariant(effectiveMedia, resolvedVideoContentId, hasMediaUrl, mediaUrl);
1455
+ const parentAssetChanged = resolvedVideoContentId !== (post.videoContentId ?? null) || row.media !== null && row.media.videoContentId !== effectiveMedia.videoContentId;
1456
+ const clearParentMediaUrl = isLinkOnly || parentAssignedMediaUrl === null || !hasMediaUrl && parentAssetChanged;
1457
+ const prevRowMedia = row.media;
1458
+ const prevRowYoutube = row.youtubeMetadata;
1459
+ const prevRowState = row.state;
1460
+ const prevRowApprovedBy = row.approvedBy;
1060
1461
  const back = state !== "draft";
1061
- await this.updateSocialPost(tenantId, row, {
1062
- ...social,
1462
+ const rollbackPost = {
1463
+ post_type: post.postType ?? "text",
1464
+ video_content_id: post.videoContentId ?? null,
1465
+ ...hasMediaUrl || clearParentMediaUrl ? { media_url: post.mediaUrl ?? null } : {},
1063
1466
  ...back ? {
1064
- status: socialStatusFor("draft"),
1065
- scheduled_at: null
1467
+ status: socialStatusFor(state),
1468
+ scheduled_at: post.scheduledAt ?? null
1066
1469
  } : {}
1067
- });
1068
- if (back) row.state = "draft";
1069
- await row.save();
1470
+ };
1471
+ const undoStack = [];
1472
+ try {
1473
+ for (const dep of dependents) {
1474
+ if (dep.state === "rejected") continue;
1475
+ const depPost = await this.loadPost(tenantId, dep);
1476
+ if (!depPost) throw new OutboundError("not-found", "The social post for a dependent draft is missing.");
1477
+ const depMode = dep.xRepostMode ?? null;
1478
+ const depLinkOnly = depMode === "link_only";
1479
+ const depVariant = depLinkOnly ? null : selectMediaVariant(effectiveMedia, "x", null, depMode);
1480
+ const depVideoId = depLinkOnly ? null : depVariant?.videoContentId ?? effectiveMedia.videoContentId;
1481
+ const depPostType = depLinkOnly ? "text" : effectiveMedia.postType;
1482
+ const depAssignedMediaUrl = fallbackMediaUrlForVariant(effectiveMedia, depVideoId, hasMediaUrl, mediaUrl);
1483
+ const depAssetChanged = depVideoId !== (depPost.videoContentId ?? null) || dep.media !== null && dep.media.videoContentId !== effectiveMedia.videoContentId;
1484
+ const clearDepMediaUrl = depLinkOnly || depAssignedMediaUrl === null || !hasMediaUrl && depAssetChanged;
1485
+ const depBack = dep.state !== "draft";
1486
+ const prevDepState = dep.state;
1487
+ const prevDepApprovedBy = dep.approvedBy;
1488
+ const prevDepMedia = dep.media;
1489
+ const depRollbackSocial = {
1490
+ post_type: depPost.postType ?? "text",
1491
+ video_content_id: depPost.videoContentId ?? null,
1492
+ ...hasMediaUrl || clearDepMediaUrl ? { media_url: depPost.mediaUrl ?? null } : {},
1493
+ ...depBack ? {
1494
+ status: socialStatusFor(prevDepState),
1495
+ scheduled_at: depPost.scheduledAt ?? null
1496
+ } : {}
1497
+ };
1498
+ await this.updateSocialPost(tenantId, dep, {
1499
+ post_type: depPostType,
1500
+ video_content_id: depVideoId,
1501
+ ...clearDepMediaUrl ? { media_url: null } : hasMediaUrl ? { media_url: mediaUrl ?? null } : {},
1502
+ ...depBack ? {
1503
+ status: socialStatusFor("draft"),
1504
+ scheduled_at: null
1505
+ } : {}
1506
+ });
1507
+ undoStack.push(() => this.updateSocialPost(tenantId, dep, depRollbackSocial));
1508
+ dep.media = depLinkOnly ? null : effectiveMedia;
1509
+ if (depBack) {
1510
+ dep.state = "draft";
1511
+ dep.approvedBy = null;
1512
+ }
1513
+ await dep.save();
1514
+ undoStack.push(async () => {
1515
+ dep.media = prevDepMedia;
1516
+ dep.state = prevDepState;
1517
+ dep.approvedBy = prevDepApprovedBy;
1518
+ await dep.save();
1519
+ });
1520
+ }
1521
+ await this.updateSocialPost(tenantId, row, {
1522
+ post_type: resolvedPostType,
1523
+ video_content_id: resolvedVideoContentId,
1524
+ ...clearParentMediaUrl ? { media_url: null } : hasMediaUrl ? { media_url: mediaUrl ?? null } : {},
1525
+ ...back ? {
1526
+ status: socialStatusFor("draft"),
1527
+ scheduled_at: null
1528
+ } : {}
1529
+ });
1530
+ undoStack.push(() => this.updateSocialPost(tenantId, row, rollbackPost));
1531
+ row.media = isLinkOnly ? null : effectiveMedia;
1532
+ if (effectiveYoutube) row.youtubeMetadata = effectiveYoutube;
1533
+ if (back) {
1534
+ row.state = "draft";
1535
+ row.approvedBy = null;
1536
+ }
1537
+ await row.save();
1538
+ undoStack.push(async () => {
1539
+ row.media = prevRowMedia;
1540
+ row.youtubeMetadata = prevRowYoutube;
1541
+ row.state = prevRowState;
1542
+ row.approvedBy = prevRowApprovedBy;
1543
+ await row.save();
1544
+ });
1545
+ } catch (error) {
1546
+ for (const undo of undoStack.reverse()) await undo().catch(() => void 0);
1547
+ throw error;
1548
+ }
1070
1549
  return this.getDraft(tenantId, id);
1071
- });
1550
+ }));
1551
+ }
1552
+ async findDependents(tenantId, parentOutboundId) {
1553
+ return (await this.stores.posts.list({ where: {
1554
+ tenantId,
1555
+ parentOutboundId
1556
+ } })).filter((item) => item.tenantId === tenantId && item.parentOutboundId === parentOutboundId);
1557
+ }
1558
+ async assertDependentsMutable(tenantId, dependents, action) {
1559
+ for (const dep of dependents) {
1560
+ if (dep.state === "published") throw new OutboundError("illegal-transition", `A paired dependent post is already published, so this parent cannot be ${action}.`);
1561
+ if ((await this.loadPost(tenantId, dep))?.status === "publishing") throw new OutboundError("in-flight", "A paired dependent post is being published right now, so it was not changed.");
1562
+ }
1072
1563
  }
1073
1564
  approve(tenantId, id, approvedBy = "user") {
1074
1565
  assertAmbientTenant(tenantId);
@@ -1108,7 +1599,7 @@ var OutboundService = class {
1108
1599
  return this.getDraft(tenantId, id);
1109
1600
  });
1110
1601
  }
1111
- /** Approved or scheduled posts of the tenant whose time has come. */
1602
+ /** Approved or scheduled posts of the tenant whose time has come (parents before dependents). */
1112
1603
  async dueForPublish(tenantId, now) {
1113
1604
  assertAmbientTenant(tenantId);
1114
1605
  return withTenant({ tenantId }, async () => {
@@ -1116,8 +1607,10 @@ var OutboundService = class {
1116
1607
  where: { tenantId },
1117
1608
  orderBy: "created_at ASC"
1118
1609
  })).filter((row) => row.tenantId === tenantId && (row.state === "approved" || row.state === "scheduled"));
1610
+ const parents = rows.filter((row) => !row.parentOutboundId);
1611
+ const children = rows.filter((row) => Boolean(row.parentOutboundId));
1119
1612
  const due = [];
1120
- for (const row of rows) {
1613
+ for (const row of [...parents, ...children]) {
1121
1614
  const post = await this.loadPost(tenantId, row);
1122
1615
  if (!post) continue;
1123
1616
  const at = post.scheduledAt ? new Date(post.scheduledAt) : null;
@@ -1126,6 +1619,26 @@ var OutboundService = class {
1126
1619
  return due;
1127
1620
  });
1128
1621
  }
1622
+ /** Order social posts so parent YouTube posts run ahead of dependent X posts. */
1623
+ async orderSocialPostsForPublish(posts) {
1624
+ if (posts.length <= 1) return posts;
1625
+ const tagged = await Promise.all(posts.map(async (post, index) => {
1626
+ const tenantId = post.tenantId?.trim();
1627
+ if (!tenantId || !post.id) return {
1628
+ post,
1629
+ index,
1630
+ hasParent: false
1631
+ };
1632
+ const row = await withTenant({ tenantId }, () => this.findRowForPost(tenantId, post.id)).catch(() => null);
1633
+ return {
1634
+ post,
1635
+ index,
1636
+ hasParent: Boolean(row?.parentOutboundId)
1637
+ };
1638
+ }));
1639
+ tagged.sort((a, b) => Number(a.hasParent) - Number(b.hasParent) || a.index - b.index);
1640
+ return tagged.map((entry) => entry.post);
1641
+ }
1129
1642
  /** The tenant's post to publish now: it must be approved or scheduled. */
1130
1643
  async postForPublish(tenantId, id) {
1131
1644
  assertAmbientTenant(tenantId);
@@ -1244,7 +1757,7 @@ var OutboundService = class {
1244
1757
  * the monthly cap. On success a spend reservation is held (atomically with
1245
1758
  * the cap check) until {@link finish}.
1246
1759
  */
1247
- beforeSend(post, platform) {
1760
+ beforeSend(post, platform, linkBehavior) {
1248
1761
  const tenantId = post.tenantId?.trim();
1249
1762
  const refuse = (code, message) => ({
1250
1763
  ok: false,
@@ -1259,15 +1772,68 @@ var OutboundService = class {
1259
1772
  return withLock(tenantId, () => withTenant({ tenantId }, async () => {
1260
1773
  const settings = this.toSettings(tenantId, await this.findSettingsRow(tenantId));
1261
1774
  if (settings.paused) return refuse("paused", "Posting is paused for this tenant, so nothing was posted.");
1775
+ const config = this.configFn();
1262
1776
  const row = post.id ? await this.findRowForPost(tenantId, post.id) : null;
1263
1777
  let linkUrl = post.linkUrl ?? null;
1778
+ let resolved;
1264
1779
  if (row) {
1265
1780
  if (row.state !== "approved" && row.state !== "scheduled") return refuse("not-approved", `This post is ${row.state}, not approved.`);
1266
1781
  if (!isFullyCited(row.claims)) return refuse("uncited", "A claim in this post has no evidence, so it was not posted.");
1267
1782
  const accountId = post.socialAccountId ?? "";
1268
1783
  linkUrl = (settings.linkPolicy[accountId] ?? settings.defaultLinkPolicy) === "include" ? post.linkUrl ?? row.sourceUrl ?? null : null;
1784
+ let descriptionOverride;
1785
+ let postTypeOverride = row.media?.postType;
1786
+ let videoContentIdOverride;
1787
+ let mediaUrlOverride;
1788
+ let linkBehaviorOverride;
1789
+ const xRepostMode = row.xRepostMode ?? null;
1790
+ if (row.parentOutboundId) {
1791
+ const parentRow = await this.requireRow(tenantId, row.parentOutboundId).catch(() => null);
1792
+ const parentPost = parentRow ? await this.loadPost(tenantId, parentRow) : null;
1793
+ if (!parentRow || !parentPost) return refuse("dependency-not-ready", "The parent YouTube post is missing, so this dependent X post was not published.");
1794
+ if (parentRow.state === "failed" || parentPost.status === "failed") {
1795
+ const reason = parentPost.errorMessage ? `: ${parentPost.errorMessage}` : "";
1796
+ return refuse("dependency-not-ready", `The parent YouTube publish failed${reason}, so this dependent X post remains blocked.`);
1797
+ }
1798
+ if (parentRow.state === "rejected" || parentPost.status === "cancelled") return refuse("dependency-not-ready", "The parent YouTube post was rejected, so this dependent X post was not published.");
1799
+ const parentUrl = parentPost.platformUrl?.trim() || "";
1800
+ if (parentPost.status !== "published" || !parentUrl) return refuse("dependency-not-ready", `The parent YouTube post is ${parentPost.status} without a live URL, so this dependent X post is waiting.`);
1801
+ const liveYouTubeUrl = buildPairedYouTubeUrl(parentUrl, post.linkUrl ?? row.sourceUrl, row.utmCampaign);
1802
+ linkUrl = liveYouTubeUrl;
1803
+ descriptionOverride = stripUrlFromDescription(post.description, liveYouTubeUrl);
1804
+ if (linkBehavior === "none") linkBehaviorOverride = "inline";
1805
+ const maxLen = config.outboundMaxLength;
1806
+ const effectiveLen = linkBehavior === "reply" ? Math.max(computeXPostLength(descriptionOverride, post.hashtags ?? [], null, "reply"), liveYouTubeUrl.length) : computeXPostLength(descriptionOverride, post.hashtags ?? [], liveYouTubeUrl, "inline");
1807
+ if (effectiveLen > maxLen) return refuse("invalid", `The X repost text with YouTube URL exceeds ${maxLen} characters (${effectiveLen} > ${maxLen}).`);
1808
+ if (xRepostMode === "link_only") {
1809
+ postTypeOverride = "text";
1810
+ videoContentIdOverride = null;
1811
+ mediaUrlOverride = null;
1812
+ }
1813
+ }
1814
+ const variant = xRepostMode === "link_only" ? null : selectMediaVariant(row.media, platform, post.videoContentId, xRepostMode);
1815
+ const isShort = xRepostMode === "link_only" ? false : variant?.isShort === true || variant?.aspectRatio === "9:16";
1816
+ if (xRepostMode !== "link_only") {
1817
+ videoContentIdOverride = variant?.videoContentId ?? row.media?.videoContentId;
1818
+ if (videoContentIdOverride && post.videoContentId && videoContentIdOverride !== post.videoContentId) mediaUrlOverride = null;
1819
+ }
1820
+ const yt = platform === "youtube" ? row.media?.youtube ?? row.youtubeMetadata ?? void 0 : void 0;
1821
+ resolved = {
1822
+ linkUrl,
1823
+ ...postTypeOverride !== void 0 ? { postType: postTypeOverride } : {},
1824
+ ...videoContentIdOverride !== void 0 ? { videoContentId: videoContentIdOverride } : {},
1825
+ ...mediaUrlOverride !== void 0 ? { mediaUrl: mediaUrlOverride } : {},
1826
+ ...descriptionOverride !== void 0 ? { description: descriptionOverride } : {},
1827
+ ...linkBehaviorOverride !== void 0 ? { linkBehavior: linkBehaviorOverride } : {},
1828
+ ...yt ? {
1829
+ title: yt.title,
1830
+ ...yt.description !== void 0 ? { description: yt.description } : {},
1831
+ ...yt.tags !== void 0 ? { hashtags: yt.tags } : {}
1832
+ } : {},
1833
+ isShort
1834
+ };
1269
1835
  } else if (isOutboundMarked(post)) return refuse("not-approved", "This post was drafted by the outbound pipeline but has no approval record, so it was not posted.");
1270
- const estimate = estimateCost(this.configFn().outboundRates, platform, linkUrl !== null);
1836
+ const estimate = estimateCost(config.outboundRates, platform, linkUrl !== null);
1271
1837
  const month = monthKey(this.nowFn());
1272
1838
  const spent = (await this.monthEntries(tenantId, month)).filter((entry) => entry.status !== "released").reduce((sum, entry) => sum + entry.costMicros, 0);
1273
1839
  const valid = (n) => Number.isFinite(n) && n >= 0;
@@ -1284,6 +1850,7 @@ var OutboundService = class {
1284
1850
  return {
1285
1851
  ok: true,
1286
1852
  linkUrl,
1853
+ ...resolved ? { resolved } : {},
1287
1854
  reservation: {
1288
1855
  tenantId,
1289
1856
  entryId: entry.id,
@@ -1322,7 +1889,7 @@ var OutboundService = class {
1322
1889
  }
1323
1890
  await entry.save();
1324
1891
  }
1325
- if (reservation.outboundId) {
1892
+ if (reservation.outboundId && !outcome.skipped) {
1326
1893
  const row = await this.requireRow(tenantId, reservation.outboundId).catch(() => null);
1327
1894
  if (row && (row.state === "approved" || row.state === "scheduled")) {
1328
1895
  row.state = outcome.result || outcome.success ? "published" : "failed";
@@ -1445,7 +2012,8 @@ var Garrula = class Garrula extends Agent {
1445
2012
  },
1446
2013
  config: () => this.garrulaConfig,
1447
2014
  ai: () => this.draftingAI ?? this.ai,
1448
- now: () => this.nowFn()
2015
+ now: () => this.nowFn(),
2016
+ refreshAccount: (account) => this.renewLapsedAccount(account)
1449
2017
  });
1450
2018
  }
1451
2019
  if (!this.outbound && !this.unsafeDisableOutboundGate) throw new Error("Garrula has no outbound gate: pass `outboundStores` (or let it use its own database). `unsafeDisableOutboundGate: true` disables it and is for tests only.");
@@ -1467,7 +2035,8 @@ var Garrula = class Garrula extends Agent {
1467
2035
  * are and picked up by a later run.
1468
2036
  */
1469
2037
  async run() {
1470
- const duePosts = await this.socialPosts.findDueForPublish(/* @__PURE__ */ new Date());
2038
+ const rawDuePosts = await this.socialPosts.findDueForPublish(/* @__PURE__ */ new Date());
2039
+ const duePosts = this.outbound ? await this.outbound.orderSocialPostsForPublish(rawDuePosts) : rawDuePosts;
1471
2040
  let published = 0;
1472
2041
  let failed = 0;
1473
2042
  let skipped = 0;
@@ -1558,6 +2127,11 @@ var Garrula = class Garrula extends Agent {
1558
2127
  const { service, tenantId } = this.outboundFor(options);
1559
2128
  return service.editDraft(tenantId, id, patch);
1560
2129
  }
2130
+ /** Attach video/image media (and optional variants/YouTube metadata). Withdraws approval. */
2131
+ async attachMedia(id, media, options) {
2132
+ const { service, tenantId } = this.outboundFor(options);
2133
+ return service.attachMedia(tenantId, id, media);
2134
+ }
1561
2135
  async approve(id, options) {
1562
2136
  const { service, tenantId } = this.outboundFor(options);
1563
2137
  return service.approve(tenantId, id, options?.approvedBy);
@@ -1699,7 +2273,8 @@ var Garrula = class Garrula extends Agent {
1699
2273
  if (context.reservation) await this.outbound?.finish(context.reservation, {
1700
2274
  result: context.sent ?? null,
1701
2275
  success,
1702
- error
2276
+ error,
2277
+ skipped
1703
2278
  });
1704
2279
  else if (!success && !skipped && postId) await this.outbound?.failUnreserved(tenantId, postId);
1705
2280
  });
@@ -1781,10 +2356,9 @@ var Garrula = class Garrula extends Agent {
1781
2356
  const credentials = await account.getCredentials();
1782
2357
  if (!credentials) throw new Error(`No credentials configured for ${account.name}`);
1783
2358
  let session = await this.openAdapter(account, credentials);
1784
- const mediaUrl = post.postType === "video" ? await this.hostHooks.resolveMediaUrl?.(post) || post.mediaUrl : post.mediaUrl;
1785
2359
  let sendPost = post;
1786
2360
  if (this.outbound) {
1787
- const gate = await this.outbound.beforeSend(post, account.platform);
2361
+ const gate = await this.outbound.beforeSend(post, account.platform, account.linkBehavior);
1788
2362
  if (!gate.ok) {
1789
2363
  await this.releaseClaim(post, previousStatus);
1790
2364
  return {
@@ -1797,19 +2371,74 @@ var Garrula = class Garrula extends Agent {
1797
2371
  };
1798
2372
  }
1799
2373
  context.reservation = gate.reservation;
2374
+ context.isShort = gate.resolved?.isShort === true;
2375
+ context.linkBehavior = gate.resolved?.linkBehavior;
1800
2376
  sendPost = {
1801
2377
  ...post,
1802
2378
  linkUrl: gate.linkUrl,
1803
- ...isOutboundMarked(post) ? { title: null } : {}
2379
+ ...gate.resolved?.postType !== void 0 ? { postType: gate.resolved.postType } : {},
2380
+ ...gate.resolved?.videoContentId !== void 0 ? { videoContentId: gate.resolved.videoContentId } : {},
2381
+ ...gate.resolved?.mediaUrl !== void 0 ? { mediaUrl: gate.resolved.mediaUrl } : {},
2382
+ ...gate.resolved?.description !== void 0 ? { description: gate.resolved.description } : {},
2383
+ ...gate.resolved?.hashtags !== void 0 ? { hashtags: gate.resolved.hashtags } : {},
2384
+ ...gate.resolved?.title !== void 0 ? { title: gate.resolved.title } : isOutboundMarked(post) ? { title: null } : {}
1804
2385
  };
1805
2386
  }
2387
+ let mediaUrl = sendPost.mediaUrl;
2388
+ if (sendPost.postType === "video") {
2389
+ let resolvedUrl;
2390
+ try {
2391
+ resolvedUrl = await this.hostHooks.resolveMediaUrl?.(sendPost);
2392
+ } catch (mediaError) {
2393
+ if (isMediaUnavailableError(mediaError)) {
2394
+ const message = errorMessage(mediaError) || "Video post has no resolvable media URL.";
2395
+ await this.releaseClaim(post, previousStatus);
2396
+ return {
2397
+ postId,
2398
+ platform,
2399
+ success: false,
2400
+ error: message,
2401
+ skipped: "refused",
2402
+ refusal: {
2403
+ code: "media-unavailable",
2404
+ message
2405
+ }
2406
+ };
2407
+ }
2408
+ throw mediaError;
2409
+ }
2410
+ const trimmedResolved = typeof resolvedUrl === "string" ? resolvedUrl.trim() : "";
2411
+ const trimmedFallback = typeof sendPost.mediaUrl === "string" ? sendPost.mediaUrl.trim() : "";
2412
+ mediaUrl = trimmedResolved || trimmedFallback || null;
2413
+ if (!mediaUrl) {
2414
+ const message = "Video post has no resolvable media URL.";
2415
+ await this.releaseClaim(post, previousStatus);
2416
+ return {
2417
+ postId,
2418
+ platform,
2419
+ success: false,
2420
+ error: message,
2421
+ skipped: "refused",
2422
+ refusal: {
2423
+ code: "media-unavailable",
2424
+ message
2425
+ }
2426
+ };
2427
+ }
2428
+ }
1806
2429
  try {
1807
- result = await this.publishWithAdapter(session.adapter, sendPost, mediaUrl ?? null);
2430
+ result = await this.publishWithAdapter(session.adapter, sendPost, mediaUrl ?? null, {
2431
+ isShort: context.isShort,
2432
+ linkBehavior: context.linkBehavior
2433
+ });
1808
2434
  } catch (publishError) {
1809
2435
  if (!isAuthError(publishError)) throw publishError;
1810
2436
  session = await this.openAdapter(account, session.credentials, { force: true });
1811
2437
  try {
1812
- result = await this.publishWithAdapter(session.adapter, sendPost, mediaUrl ?? null);
2438
+ result = await this.publishWithAdapter(session.adapter, sendPost, mediaUrl ?? null, {
2439
+ isShort: context.isShort,
2440
+ linkBehavior: context.linkBehavior
2441
+ });
1813
2442
  } catch (retryError) {
1814
2443
  if (!isAuthError(retryError)) throw retryError;
1815
2444
  throw await this.requireReconnect(account, "publish rejected after refresh");
@@ -1995,6 +2624,18 @@ var Garrula = class Garrula extends Agent {
1995
2624
  return account;
1996
2625
  }
1997
2626
  /**
2627
+ * Renew an account whose recorded expiry has passed, as publishing would:
2628
+ * refresh the access token when it is due and save the new token set, which
2629
+ * clears the lapsed expiry on a refreshable OAuth 2 account. Throws when the
2630
+ * account has no credentials, cannot refresh, or the refresh fails.
2631
+ */
2632
+ async renewLapsedAccount(account) {
2633
+ const credentials = await account.getCredentials();
2634
+ if (!credentials || !refreshKind(account.platform, credentials)) throw new Error("Account cannot be refreshed");
2635
+ const { credentials: fresh } = await this.openAdapter(account, credentials);
2636
+ if (fresh === credentials && account.isTokenExpired && refreshKind(account.platform, fresh) === "oauth2") await this.saveRefreshedCredentials(account, fresh, null);
2637
+ }
2638
+ /**
1998
2639
  * Build the account's adapter with a usable access token. A token that is
1999
2640
  * expired or close to it (or of unknown age) is refreshed first and the new
2000
2641
  * token set is saved on the account, so the next publish starts from it.
@@ -2067,10 +2708,15 @@ var Garrula = class Garrula extends Agent {
2067
2708
  * Save a refreshed token set on the account (encrypted, tenant-scoped).
2068
2709
  * `tokenExpiresAt` on the account means "the connection lapses then", so it
2069
2710
  * is cleared for refreshable OAuth 2 tokens and moved forward for Threads.
2070
- * A failed save is logged and the fresh token is still used for this
2071
- * publish.
2711
+ * A failed save is logged, the account's in-memory state is restored, and
2712
+ * the fresh token is still used for this publish.
2072
2713
  */
2073
2714
  async saveRefreshedCredentials(account, credentials, connectionExpiresAt) {
2715
+ const previous = {
2716
+ tokenExpiresAt: account.tokenExpiresAt,
2717
+ status: account.status,
2718
+ errorMessage: account.errorMessage
2719
+ };
2074
2720
  try {
2075
2721
  account.tokenExpiresAt = connectionExpiresAt;
2076
2722
  if (account.status !== "connected") {
@@ -2083,6 +2729,9 @@ var Garrula = class Garrula extends Agent {
2083
2729
  platform: account.platform
2084
2730
  });
2085
2731
  } catch (error) {
2732
+ account.tokenExpiresAt = previous.tokenExpiresAt;
2733
+ account.status = previous.status;
2734
+ account.errorMessage = previous.errorMessage;
2086
2735
  this.logger.error("Could not save a refreshed social account token", {
2087
2736
  accountId: account.id,
2088
2737
  platform: account.platform,
@@ -2176,14 +2825,16 @@ var Garrula = class Garrula extends Agent {
2176
2825
  case "bluesky": throw new SocialError("Posting to Bluesky is not available yet.", "UNSUPPORTED_PLATFORM", "bluesky");
2177
2826
  }
2178
2827
  }
2179
- publishWithAdapter(adapter, post, mediaUrl) {
2828
+ publishWithAdapter(adapter, post, mediaUrl, options = {}) {
2829
+ const linkBehaviorOpt = options.linkBehavior ? { linkBehavior: options.linkBehavior } : {};
2180
2830
  if (post.postType === "link") {
2181
2831
  if (!post.linkUrl) throw new SocialError("Link URL is required", "MISSING_LINK_URL");
2182
2832
  return adapter.publishLink({
2183
2833
  url: post.linkUrl,
2184
2834
  text: post.description,
2185
2835
  title: post.title ?? void 0,
2186
- tags: post.hashtags
2836
+ tags: post.hashtags,
2837
+ ...linkBehaviorOpt
2187
2838
  });
2188
2839
  }
2189
2840
  if (post.postType === "video") {
@@ -2194,7 +2845,8 @@ var Garrula = class Garrula extends Agent {
2194
2845
  description: post.description,
2195
2846
  tags: post.hashtags,
2196
2847
  linkUrl: post.linkUrl ?? void 0,
2197
- isShort: adapter.platform === "youtube"
2848
+ isShort: options.isShort === true,
2849
+ ...linkBehaviorOpt
2198
2850
  });
2199
2851
  }
2200
2852
  if (post.postType === "image") {
@@ -2204,13 +2856,15 @@ var Garrula = class Garrula extends Agent {
2204
2856
  description: post.description,
2205
2857
  altText: post.title ?? void 0,
2206
2858
  tags: post.hashtags,
2207
- linkUrl: post.linkUrl ?? void 0
2859
+ linkUrl: post.linkUrl ?? void 0,
2860
+ ...linkBehaviorOpt
2208
2861
  });
2209
2862
  }
2210
2863
  return adapter.publishText({
2211
2864
  text: post.description,
2212
2865
  tags: post.hashtags,
2213
- linkUrl: post.linkUrl ?? void 0
2866
+ linkUrl: post.linkUrl ?? void 0,
2867
+ ...linkBehaviorOpt
2214
2868
  });
2215
2869
  }
2216
2870
  async syncAnalyticsForPost(post, adapter, platform) {
@@ -2244,10 +2898,19 @@ function toRawAnalyticsPayload(value) {
2244
2898
  if (value === null || Array.isArray(value)) return value;
2245
2899
  return typeof value === "object" ? value : void 0;
2246
2900
  }
2901
+ function isMediaUnavailableError(error) {
2902
+ if (error instanceof OutboundError && error.code === "media-unavailable") return true;
2903
+ if (error instanceof SocialError && (error.code === "MEDIA_UNAVAILABLE" || error.code === "MISSING_MEDIA_URL")) return true;
2904
+ if (typeof error === "object" && error !== null && "code" in error) {
2905
+ const code = error.code;
2906
+ return code === "media-unavailable" || code === "MEDIA_UNAVAILABLE";
2907
+ }
2908
+ return false;
2909
+ }
2247
2910
  function errorMessage(error) {
2248
2911
  return error instanceof Error ? error.message : String(error);
2249
2912
  }
2250
2913
  //#endregion
2251
- export { DEFAULT_AUTONOMY, DEFAULT_GARRULA_CONFIG, DEFAULT_OUTBOUND_RATES, DEFAULT_SOURCE_RULES, FALLBACK_X_RATES, GARRULA_ACCOUNT_INACTIVE_MESSAGE, GARRULA_POST_BUSY_MESSAGE, GARRULA_TENANT_BLOCKED_MESSAGE, Garrula, GarrulaOutboundPost, GarrulaOutboundPostCollection, GarrulaOutboundSettings, GarrulaOutboundSettingsCollection, GarrulaReconnectError, GarrulaSourceEvent, GarrulaSourceEventCollection, GarrulaSpendEntry, GarrulaSpendEntryCollection, OUTBOUND_TRANSITIONS, OutboundError, OutboundService, canTransition, createOutboundStores, reconnectMessage, resolveGarrulaConfig, setGarrulaConfig, setGarrulaHost };
2914
+ export { DEFAULT_AUTONOMY, DEFAULT_GARRULA_CONFIG, DEFAULT_OUTBOUND_RATES, DEFAULT_SOURCE_RULES, FALLBACK_X_RATES, GARRULA_ACCOUNT_INACTIVE_MESSAGE, GARRULA_POST_BUSY_MESSAGE, GARRULA_TENANT_BLOCKED_MESSAGE, Garrula, GarrulaOutboundPost, GarrulaOutboundPostCollection, GarrulaOutboundSettings, GarrulaOutboundSettingsCollection, GarrulaReconnectError, GarrulaSourceEvent, GarrulaSourceEventCollection, GarrulaSpendEntry, GarrulaSpendEntryCollection, OUTBOUND_TRANSITIONS, OutboundError, OutboundService, X_REPOST_MODES, YOUTUBE_MAX_DESCRIPTION_LENGTH, YOUTUBE_MAX_TITLE_LENGTH, canTransition, createOutboundStores, reconnectMessage, resolveGarrulaConfig, setGarrulaConfig, setGarrulaHost };
2252
2915
 
2253
2916
  //# sourceMappingURL=index.js.map