@posty5/social-publisher-post 4.2.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -11734,6 +11734,12 @@ var require_follow_redirects = __commonJS({
11734
11734
  RedirectableRequest.prototype._sanitizeOptions = function(options) {
11735
11735
  if (!options.headers) {
11736
11736
  options.headers = {};
11737
+ } else if (Array.isArray(options.headers)) {
11738
+ var headerList = options.headers;
11739
+ options.headers = {};
11740
+ for (var i = 0; i < headerList.length; i += 2) {
11741
+ options.headers[headerList[i]] = headerList[i + 1];
11742
+ }
11737
11743
  }
11738
11744
  if (!isArray2(options.sensitiveHeaders)) {
11739
11745
  options.sensitiveHeaders = [];
@@ -12008,7 +12014,7 @@ var require_follow_redirects = __commonJS({
12008
12014
  return URL2 && value instanceof URL2;
12009
12015
  }
12010
12016
  function escapeRegex(regex) {
12011
- return regex.replace(/[\]\\/()*+?.$]/g, "\\$&");
12017
+ return regex.replace(/[[\]\\/()*+?.^$|]/g, "\\$&");
12012
12018
  }
12013
12019
  module.exports = wrap({ http: http3, https: https2 });
12014
12020
  module.exports.wrap = wrap;
@@ -17881,6 +17887,20 @@ var ServerError = class extends Posty5Error {
17881
17887
  this.name = "ServerError";
17882
17888
  }
17883
17889
  };
17890
+ var ConflictError = class extends Posty5Error {
17891
+ constructor(message = "The document was changed by someone else", currentVersion = -1, resourceId = "", details) {
17892
+ super(message, "VERSION_CONFLICT", 409, details);
17893
+ this.name = "ConflictError";
17894
+ this.currentVersion = currentVersion;
17895
+ this.resourceId = resourceId;
17896
+ }
17897
+ };
17898
+ var VersionRequiredError = class extends Posty5Error {
17899
+ constructor(message = "The document version is required", details) {
17900
+ super(message, "VERSION_REQUIRED", 428, details);
17901
+ this.name = "VersionRequiredError";
17902
+ }
17903
+ };
17884
17904
  function transformError(error) {
17885
17905
  if (error instanceof Posty5Error) {
17886
17906
  return error;
@@ -17905,6 +17925,22 @@ function transformError(error) {
17905
17925
  return new AuthorizationError(message, details);
17906
17926
  case 404:
17907
17927
  return new NotFoundError(message, details);
17928
+ case 409: {
17929
+ const body = data;
17930
+ if (body?.code === "VERSION_CONFLICT") {
17931
+ const result = body?.result ?? {};
17932
+ const current = Number(result.currentVersion ?? body?.currentVersion);
17933
+ return new ConflictError(
17934
+ message,
17935
+ Number.isFinite(current) ? current : -1,
17936
+ String(result._id ?? body?._id ?? ""),
17937
+ details
17938
+ );
17939
+ }
17940
+ return new Posty5Error(message, body?.code, status, details);
17941
+ }
17942
+ case 428:
17943
+ return new VersionRequiredError(message, details);
17908
17944
  case 429:
17909
17945
  const retryAfter2 = axiosError.response.headers["retry-after"];
17910
17946
  return new RateLimitError(
@@ -17926,6 +17962,67 @@ function transformError(error) {
17926
17962
  }
17927
17963
  return new Posty5Error("An unknown error occurred", void 0, void 0, { originalError: error });
17928
17964
  }
17965
+ var CORE_VERSION = "5.0.0";
17966
+ var DEFAULT_BASE_URL = "https://api.posty5.com";
17967
+ var DEFAULT_TIMEOUT_MS = 3e4;
17968
+ var DEFAULT_MAX_RETRIES = 3;
17969
+ var DEFAULT_RETRY_DELAY_MS = 1e3;
17970
+ var CLIENT_HEADER_NAME = "X-Posty5-Client";
17971
+ var SDK_CLIENT_NAME = "posty5-npm";
17972
+ var SDK_CLIENT_ID = `${SDK_CLIENT_NAME}/${CORE_VERSION}`;
17973
+ var DEFAULT_CREATED_FROM = "npmPackage";
17974
+ var IDEMPOTENT_METHODS = ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"];
17975
+ var NEVER_CONNECTED_ERROR_CODES = ["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "ENETUNREACH", "EHOSTUNREACH"];
17976
+ var IF_MATCH_HEADER = "If-Match";
17977
+ var CONCURRENCY_REPORT_HEADER = "X-Posty5-Concurrency";
17978
+ var CONCURRENCY_REPORT_MISSING_VERSION = "missing-version";
17979
+ var NON_RETRYABLE_VERSION_STATUSES = [409, 428];
17980
+ function assertVersion(version, name = "version") {
17981
+ if (typeof version !== "number" || !Number.isInteger(version) || version < 0) {
17982
+ throw new TypeError(`Posty5: \`${name}\` must be a non-negative integer (the document's __v), got ${String(version)}`);
17983
+ }
17984
+ }
17985
+ function ifMatchHeader(version) {
17986
+ assertVersion(version);
17987
+ return `"${version}"`;
17988
+ }
17989
+ function hasIfMatch(headers) {
17990
+ if (!headers) return false;
17991
+ if (typeof headers.get === "function") {
17992
+ const value = headers.get(IF_MATCH_HEADER);
17993
+ if (value !== void 0 && value !== null) return true;
17994
+ }
17995
+ return Object.keys(headers).some((key) => key.toLowerCase() === IF_MATCH_HEADER.toLowerCase());
17996
+ }
17997
+ function withVersion(response, id) {
17998
+ const result = response.result && typeof response.result === "object" ? { ...response.result } : {};
17999
+ if (id !== void 0 && result._id === void 0) result._id = id;
18000
+ if (typeof response.version === "number") result.__v = response.version;
18001
+ return result;
18002
+ }
18003
+ var missingVersionWarned = false;
18004
+ function warnOnMissingVersion(headers, method, url2) {
18005
+ if (missingVersionWarned || !headers) return false;
18006
+ const value = typeof headers.get === "function" ? headers.get(CONCURRENCY_REPORT_HEADER) : headers[CONCURRENCY_REPORT_HEADER.toLowerCase()];
18007
+ if (String(value ?? "").toLowerCase() !== CONCURRENCY_REPORT_MISSING_VERSION) return false;
18008
+ missingVersionWarned = true;
18009
+ console.warn(
18010
+ `[Posty5 SDK] ${String(method || "").toUpperCase()} ${url2 ?? ""} was sent without a document version; the API will refuse it once versions are enforced. Please report this SDK bug.`
18011
+ );
18012
+ return true;
18013
+ }
18014
+ function shouldRetryRequest(error) {
18015
+ const method = String(error?.config?.method || "").toUpperCase();
18016
+ const idempotent = IDEMPOTENT_METHODS.includes(method);
18017
+ const status = error?.response?.status;
18018
+ if (hasIfMatch(error?.config?.headers)) return false;
18019
+ if (status !== void 0 && NON_RETRYABLE_VERSION_STATUSES.includes(status)) return false;
18020
+ if (status === void 0) {
18021
+ if (idempotent) return esm_default.isNetworkError(error);
18022
+ return NEVER_CONNECTED_ERROR_CODES.includes(String(error?.code || ""));
18023
+ }
18024
+ return idempotent && status >= 500;
18025
+ }
17929
18026
  function parseFileName(disposition) {
17930
18027
  if (!disposition) return void 0;
17931
18028
  const match = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(disposition);
@@ -17939,28 +18036,27 @@ function parseFileName(disposition) {
17939
18036
  var HttpClient = class {
17940
18037
  constructor(config = {}) {
17941
18038
  this.config = {
17942
- timeout: 3e4,
17943
- maxRetries: 3,
17944
- retryDelay: 1e3,
18039
+ timeout: DEFAULT_TIMEOUT_MS,
18040
+ maxRetries: DEFAULT_MAX_RETRIES,
18041
+ retryDelay: DEFAULT_RETRY_DELAY_MS,
17945
18042
  ...config,
17946
- baseUrl: config.baseUrl || process.env.POSTY5_BASE_URL || "https://api.posty5.com"
18043
+ baseUrl: config.baseUrl || process.env.POSTY5_BASE_URL || DEFAULT_BASE_URL
17947
18044
  };
17948
18045
  this.axiosInstance = axios_default.create({
17949
18046
  baseURL: this.config.baseUrl,
17950
18047
  timeout: this.config.timeout,
17951
18048
  headers: {
17952
18049
  "Content-Type": "application/json",
18050
+ [CLIENT_HEADER_NAME]: SDK_CLIENT_ID,
17953
18051
  ...this.config.headers
17954
18052
  }
17955
18053
  });
17956
18054
  esm_default(this.axiosInstance, {
17957
- retries: this.config.maxRetries || 3,
18055
+ retries: this.config.maxRetries ?? DEFAULT_MAX_RETRIES,
17958
18056
  retryDelay: (retryCount) => {
17959
- return retryCount * (this.config.retryDelay || 1e3);
18057
+ return retryCount * (this.config.retryDelay ?? DEFAULT_RETRY_DELAY_MS);
17960
18058
  },
17961
- retryCondition: (error) => {
17962
- return esm_default.isNetworkOrIdempotentRequestError(error) || error.response?.status !== void 0 && error.response.status >= 500;
17963
- }
18059
+ retryCondition: shouldRetryRequest
17964
18060
  });
17965
18061
  this.axiosInstance.interceptors.request.use(
17966
18062
  (config2) => {
@@ -17989,6 +18085,7 @@ var HttpClient = class {
17989
18085
  );
17990
18086
  this.axiosInstance.interceptors.response.use(
17991
18087
  (response) => {
18088
+ warnOnMissingVersion(response.headers, response.config?.method, response.config?.url);
17992
18089
  if (this.config.debug) {
17993
18090
  console.log("[Posty5 SDK] Response:", {
17994
18091
  status: response.status,
@@ -18005,6 +18102,10 @@ var HttpClient = class {
18005
18102
  }
18006
18103
  );
18007
18104
  }
18105
+ /** The `createdFrom` label the clients stamp on records they create. */
18106
+ get createdFrom() {
18107
+ return this.config.createdFrom || DEFAULT_CREATED_FROM;
18108
+ }
18008
18109
  /**
18009
18110
  * Set or update the API key
18010
18111
  */
@@ -18109,11 +18210,18 @@ var HttpClient = class {
18109
18210
  }
18110
18211
  const axiosConfig = {};
18111
18212
  if (config.headers) {
18112
- axiosConfig.headers = config.headers;
18213
+ axiosConfig.headers = { ...config.headers };
18214
+ }
18215
+ if (config.version !== void 0) {
18216
+ axiosConfig.headers = { ...axiosConfig.headers || {}, [IF_MATCH_HEADER]: ifMatchHeader(config.version) };
18217
+ axiosConfig["axios-retry"] = { retries: 0 };
18113
18218
  }
18114
18219
  if (config.params) {
18115
18220
  axiosConfig.params = config.params;
18116
18221
  }
18222
+ if (config.data !== void 0) {
18223
+ axiosConfig.data = config.data;
18224
+ }
18117
18225
  if (config.timeout) {
18118
18226
  axiosConfig.timeout = config.timeout;
18119
18227
  }
@@ -18393,17 +18501,20 @@ var SocialPublisherPostClient = class {
18393
18501
  * cannot be removed programmatically and no credits are charged.
18394
18502
  *
18395
18503
  * @param id - Post ID
18396
- * @returns Per-platform removal results
18504
+ * @param version - The post's `__v` as you read it. A stale one throws `ConflictError`.
18505
+ * @returns Per-platform removal results, `__v` set to the post's new version
18397
18506
  *
18398
18507
  * @example
18399
18508
  * ```ts
18400
- * const { results } = await client.removePost("post_123");
18509
+ * const post = await client.getStatus("post_123");
18510
+ * const { results } = await client.removePost("post_123", post.__v);
18401
18511
  * // results.youtube?.success === true
18402
18512
  * ```
18403
18513
  */
18404
- async removePost(id) {
18405
- const response = await this.http.post(`${this.basePath}/${id}/remove`, {});
18406
- return response.result;
18514
+ async removePost(id, version) {
18515
+ assertVersion(version);
18516
+ const response = await this.http.post(`${this.basePath}/${id}/remove`, {}, { version });
18517
+ return withVersion(response, id);
18407
18518
  }
18408
18519
  /**
18409
18520
  * Get next and previous post IDs
@@ -18422,7 +18533,7 @@ var SocialPublisherPostClient = class {
18422
18533
  const url2 = id ? `${this.basePath}/short-video/workspace/by-file/${id}` : `${this.basePath}/short-video/workspace/by-file`;
18423
18534
  const response = await this.http.post(url2, {
18424
18535
  ...data,
18425
- createdFrom: "npmPackage"
18536
+ createdFrom: this.http.createdFrom
18426
18537
  });
18427
18538
  return response.result?._id;
18428
18539
  }
@@ -18435,7 +18546,7 @@ var SocialPublisherPostClient = class {
18435
18546
  const url2 = id ? `${this.basePath}/short-video/workspace/by-url/${id}` : `${this.basePath}/short-video/workspace/by-url`;
18436
18547
  const response = await this.http.post(url2, {
18437
18548
  ...data,
18438
- createdFrom: "npmPackage"
18549
+ createdFrom: this.http.createdFrom
18439
18550
  });
18440
18551
  return response.result?._id;
18441
18552
  }
@@ -18448,7 +18559,7 @@ var SocialPublisherPostClient = class {
18448
18559
  const url2 = id ? `${this.basePath}/short-video/account/by-file/${id}` : `${this.basePath}/short-video/account/by-file`;
18449
18560
  const response = await this.http.post(url2, {
18450
18561
  ...data,
18451
- createdFrom: "npmPackage"
18562
+ createdFrom: this.http.createdFrom
18452
18563
  });
18453
18564
  return response.result?._id;
18454
18565
  }
@@ -18461,7 +18572,7 @@ var SocialPublisherPostClient = class {
18461
18572
  const url2 = id ? `${this.basePath}/short-video/account/by-url/${id}` : `${this.basePath}/short-video/account/by-url`;
18462
18573
  const response = await this.http.post(url2, {
18463
18574
  ...data,
18464
- createdFrom: "npmPackage"
18575
+ createdFrom: this.http.createdFrom
18465
18576
  });
18466
18577
  return response.result?._id;
18467
18578
  }
@@ -18485,7 +18596,7 @@ var SocialPublisherPostClient = class {
18485
18596
  const url2 = id ? `${this.basePath}/image/workspace/${id}` : `${this.basePath}/image/workspace`;
18486
18597
  const response = await this.http.post(url2, {
18487
18598
  ...data,
18488
- createdFrom: "npmPackage"
18599
+ createdFrom: this.http.createdFrom
18489
18600
  });
18490
18601
  return response.result?._id;
18491
18602
  }
@@ -18498,10 +18609,50 @@ var SocialPublisherPostClient = class {
18498
18609
  const url2 = id ? `${this.basePath}/image/account/${id}` : `${this.basePath}/image/account`;
18499
18610
  const response = await this.http.post(url2, {
18500
18611
  ...data,
18501
- createdFrom: "npmPackage"
18612
+ createdFrom: this.http.createdFrom
18502
18613
  });
18503
18614
  return response.result?._id;
18504
18615
  }
18616
+ /**
18617
+ * Publish a text-only post to every text-capable account in a workspace
18618
+ * (Facebook, Threads, X). Platforms that cannot take text are reported in
18619
+ * `skippedPlatforms`; X below the Pro plan is dropped into `refusedTargets`.
18620
+ */
18621
+ async createTextPostToWorkspace(data) {
18622
+ const response = await this.http.post(`${this.basePath}/text/workspace`, {
18623
+ ...data,
18624
+ createdFrom: this.http.createdFrom
18625
+ });
18626
+ return response.result;
18627
+ }
18628
+ /** Publish a text-only post to one account. */
18629
+ async createTextPostToAccount(data) {
18630
+ const response = await this.http.post(`${this.basePath}/text/account`, {
18631
+ ...data,
18632
+ createdFrom: this.http.createdFrom
18633
+ });
18634
+ return response.result;
18635
+ }
18636
+ /**
18637
+ * Publish a story to every story-capable account in a workspace. Media by URL
18638
+ * only in this release: `image: { source: "image-url", externalUrl }`, or
18639
+ * `source: "video-url"` with `videoURL`.
18640
+ */
18641
+ async createStoryPostToWorkspace(data) {
18642
+ const response = await this.http.post(`${this.basePath}/story/workspace`, {
18643
+ ...data,
18644
+ createdFrom: this.http.createdFrom
18645
+ });
18646
+ return response.result;
18647
+ }
18648
+ /** Publish a story to one account. Media by URL only, as for the workspace form. */
18649
+ async createStoryPostToAccount(data) {
18650
+ const response = await this.http.post(`${this.basePath}/story/account`, {
18651
+ ...data,
18652
+ createdFrom: this.http.createdFrom
18653
+ });
18654
+ return response.result;
18655
+ }
18505
18656
  /**
18506
18657
  * Handle thumbnail upload - accepts either File or URL string
18507
18658
  * @param thumb - Thumbnail as File (will be uploaded) or URL string (will be passed directly)
@@ -18849,7 +19000,7 @@ var SocialPublisherPostClient = class {
18849
19000
  const target = isFile2 ? "by-file" : "by-url";
18850
19001
  const id = postId ?? thumb?.postId;
18851
19002
  const url2 = id ? `${this.basePath}/long-video/workspace/${target}/${id}` : `${this.basePath}/long-video/workspace/${target}`;
18852
- const response = await this.http.post(url2, { ...body, createdFrom: "npmPackage" });
19003
+ const response = await this.http.post(url2, { ...body, createdFrom: this.http.createdFrom });
18853
19004
  return this.normaliseLongVideoResult(response.result);
18854
19005
  }
18855
19006
  /**
@@ -18901,7 +19052,7 @@ var SocialPublisherPostClient = class {
18901
19052
  const target = isFile2 ? "by-file" : "by-url";
18902
19053
  const id = postId ?? thumb?.postId;
18903
19054
  const url2 = id ? `${this.basePath}/long-video/account/${target}/${id}` : `${this.basePath}/long-video/account/${target}`;
18904
- const response = await this.http.post(url2, { ...body, createdFrom: "npmPackage" });
19055
+ const response = await this.http.post(url2, { ...body, createdFrom: this.http.createdFrom });
18905
19056
  return this.normaliseLongVideoResult(response.result);
18906
19057
  }
18907
19058
  /**
@@ -18913,18 +19064,29 @@ var SocialPublisherPostClient = class {
18913
19064
  *
18914
19065
  * @example
18915
19066
  * ```ts
18916
- * await client.reschedulePost("post_123", { schedule: new Date("2026-09-01T09:00:00Z") });
18917
- * await client.reschedulePost("post_123", { schedule: "now" });
19067
+ * const post = await client.getStatus("post_123");
19068
+ * const { __v } = await client.reschedulePost("post_123", { schedule: new Date("2026-09-01T09:00:00Z") }, post.__v);
19069
+ * await client.reschedulePost("post_123", { schedule: "now" }, __v);
18918
19070
  * ```
19071
+ *
19072
+ * @param version - The post's `__v` as you read it. A stale one throws `ConflictError`.
19073
+ * @returns `{ _id, __v }`, `__v` being the new version
18919
19074
  */
18920
- async reschedulePost(id, data) {
19075
+ async reschedulePost(id, data, version) {
18921
19076
  if (!id) {
18922
19077
  throw new Error("id is required");
18923
19078
  }
18924
- await this.http.put(`${this.basePath}/${id}`, {
18925
- schedule: this.buildSchedule(data.schedule),
18926
- ...data.caption !== void 0 ? { caption: data.caption } : {}
18927
- });
19079
+ assertVersion(version);
19080
+ const response = await this.http.put(
19081
+ `${this.basePath}/${id}`,
19082
+ {
19083
+ ...data.schedule === "now" ? { scheduleType: "now" } : { scheduleType: "schedule", scheduledAt: data.schedule.toISOString() },
19084
+ ...data.caption !== void 0 ? { caption: data.caption } : {}
19085
+ },
19086
+ { version }
19087
+ );
19088
+ const updated = withVersion(response, id);
19089
+ return { _id: updated._id, __v: updated.__v };
18928
19090
  }
18929
19091
  /**
18930
19092
  * Delete a post that has not published yet, releasing its uploaded media in
@@ -18936,14 +19098,17 @@ var SocialPublisherPostClient = class {
18936
19098
  *
18937
19099
  * @example
18938
19100
  * ```ts
18939
- * await client.deletePost("post_123");
19101
+ * await client.deletePost("post_123", post.__v);
18940
19102
  * ```
19103
+ *
19104
+ * @param version - The post's `__v` as you read it. A stale one throws `ConflictError`.
18941
19105
  */
18942
- async deletePost(id) {
19106
+ async deletePost(id, version) {
18943
19107
  if (!id) {
18944
19108
  throw new Error("id is required");
18945
19109
  }
18946
- await this.http.delete(`${this.basePath}/${id}`);
19110
+ assertVersion(version);
19111
+ await this.http.delete(`${this.basePath}/${id}`, { version });
18947
19112
  }
18948
19113
  /**
18949
19114
  * Upload a long video and return the URL to publish from.