@01.software/sdk 0.36.0 → 0.38.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.
Files changed (82) hide show
  1. package/README.md +142 -55
  2. package/dist/analytics/react.cjs +33 -9
  3. package/dist/analytics/react.cjs.map +1 -1
  4. package/dist/analytics/react.d.cts +1 -1
  5. package/dist/analytics/react.d.ts +1 -1
  6. package/dist/analytics/react.js +33 -9
  7. package/dist/analytics/react.js.map +1 -1
  8. package/dist/analytics.cjs +30 -8
  9. package/dist/analytics.cjs.map +1 -1
  10. package/dist/analytics.d.cts +6 -0
  11. package/dist/analytics.d.ts +6 -0
  12. package/dist/analytics.js +30 -8
  13. package/dist/analytics.js.map +1 -1
  14. package/dist/client.cjs +150 -207
  15. package/dist/client.cjs.map +1 -1
  16. package/dist/client.d.cts +6 -6
  17. package/dist/client.d.ts +6 -6
  18. package/dist/client.js +150 -207
  19. package/dist/client.js.map +1 -1
  20. package/dist/{collection-client-Cv0D2w1Q.d.cts → collection-client-B0J9wMNE.d.cts} +5 -5
  21. package/dist/{collection-client-Bq5Zd7p7.d.ts → collection-client-BroIWHY1.d.ts} +5 -5
  22. package/dist/const-6XHz_jej.d.ts +32 -0
  23. package/dist/const-B5KT72c7.d.cts +32 -0
  24. package/dist/{image-BDz2-AaO.d.cts → image-BDjHp03R.d.cts} +13 -9
  25. package/dist/{image-BDz2-AaO.d.ts → image-BDjHp03R.d.ts} +13 -9
  26. package/dist/{index-DTSXUYkr.d.ts → index-BOLQxveo.d.cts} +9 -6
  27. package/dist/{index-BHDKJ6B3.d.cts → index-CSwR2HSg.d.ts} +9 -6
  28. package/dist/index.cjs +256 -244
  29. package/dist/index.cjs.map +1 -1
  30. package/dist/index.d.cts +12 -11
  31. package/dist/index.d.ts +12 -11
  32. package/dist/index.js +256 -244
  33. package/dist/index.js.map +1 -1
  34. package/dist/metadata.cjs +5 -3
  35. package/dist/metadata.cjs.map +1 -1
  36. package/dist/metadata.js +5 -3
  37. package/dist/metadata.js.map +1 -1
  38. package/dist/{payload-types-BCui2Oml.d.cts → payload-types-m3jjhxk9.d.cts} +669 -184
  39. package/dist/{payload-types-BCui2Oml.d.ts → payload-types-m3jjhxk9.d.ts} +669 -184
  40. package/dist/query.cjs +3 -1033
  41. package/dist/query.cjs.map +1 -1
  42. package/dist/query.d.cts +13 -13
  43. package/dist/query.d.ts +13 -13
  44. package/dist/query.js +3 -1033
  45. package/dist/query.js.map +1 -1
  46. package/dist/realtime.d.cts +2 -2
  47. package/dist/realtime.d.ts +2 -2
  48. package/dist/server.cjs +121 -85
  49. package/dist/server.cjs.map +1 -1
  50. package/dist/server.d.cts +7 -7
  51. package/dist/server.d.ts +7 -7
  52. package/dist/server.js +121 -85
  53. package/dist/server.js.map +1 -1
  54. package/dist/{types-Dib-zdK6.d.cts → types-CIGscmus.d.cts} +1471 -1100
  55. package/dist/{types-3qV6sY7T.d.ts → types-Cmrd1ezc.d.ts} +1 -15
  56. package/dist/{types-CEzLf3PX.d.cts → types-D0ubzQw0.d.cts} +1 -15
  57. package/dist/{types-DK9EnLwJ.d.ts → types-D2xYdz4P.d.ts} +1471 -1100
  58. package/dist/ui/canvas.cjs +15 -5
  59. package/dist/ui/canvas.cjs.map +1 -1
  60. package/dist/ui/canvas.d.cts +1 -1
  61. package/dist/ui/canvas.d.ts +1 -1
  62. package/dist/ui/canvas.js +15 -5
  63. package/dist/ui/canvas.js.map +1 -1
  64. package/dist/ui/form.d.cts +1 -1
  65. package/dist/ui/form.d.ts +1 -1
  66. package/dist/ui/image.cjs +15 -5
  67. package/dist/ui/image.cjs.map +1 -1
  68. package/dist/ui/image.d.cts +1 -1
  69. package/dist/ui/image.d.ts +1 -1
  70. package/dist/ui/image.js +15 -5
  71. package/dist/ui/image.js.map +1 -1
  72. package/dist/ui/video.d.cts +1 -1
  73. package/dist/ui/video.d.ts +1 -1
  74. package/dist/webhook.cjs +5 -1
  75. package/dist/webhook.cjs.map +1 -1
  76. package/dist/webhook.d.cts +4 -4
  77. package/dist/webhook.d.ts +4 -4
  78. package/dist/webhook.js +5 -1
  79. package/dist/webhook.js.map +1 -1
  80. package/package.json +3 -3
  81. package/dist/const-BDUKFP9w.d.ts +0 -32
  82. package/dist/const-DVcM7Ac_.d.cts +0 -32
package/dist/query.cjs CHANGED
@@ -400,115 +400,13 @@ var SDKError = class extends Error {
400
400
  };
401
401
  }
402
402
  };
403
- var NetworkError = class extends SDKError {
404
- constructor(message, status, details, userMessage, suggestion) {
405
- super("NETWORK_ERROR", message, status, details, userMessage, suggestion);
406
- this.name = "NetworkError";
407
- }
408
- };
409
- var ValidationError = class extends SDKError {
410
- constructor(message, details, userMessage, suggestion, status = 400) {
411
- super("VALIDATION_ERROR", message, status, details, userMessage, suggestion);
412
- this.name = "ValidationError";
413
- }
414
- };
415
- var ApiError = class extends SDKError {
416
- constructor(message, status, details, userMessage, suggestion, requestId) {
417
- super(
418
- "API_ERROR",
419
- message,
420
- status,
421
- details,
422
- userMessage,
423
- suggestion,
424
- requestId
425
- );
426
- this.name = "ApiError";
427
- }
428
- };
429
403
  var ConfigError = class extends SDKError {
430
404
  constructor(message, details, userMessage, suggestion) {
431
405
  super("CONFIG_ERROR", message, void 0, details, userMessage, suggestion);
432
406
  this.name = "ConfigError";
433
407
  }
434
408
  };
435
- var TimeoutError = class extends SDKError {
436
- constructor(message = "Request timed out.", details, userMessage, suggestion) {
437
- super("TIMEOUT_ERROR", message, 408, details, userMessage, suggestion);
438
- this.name = "TimeoutError";
439
- }
440
- };
441
- var UsageLimitError = class extends SDKError {
442
- constructor(message, usage, details, userMessage, suggestion) {
443
- super("USAGE_LIMIT_ERROR", message, 429, details, userMessage, suggestion);
444
- this.name = "UsageLimitError";
445
- this.usage = usage;
446
- }
447
- toJSON() {
448
- return {
449
- ...super.toJSON(),
450
- usage: this.usage
451
- };
452
- }
453
- };
454
- var AuthError = class extends SDKError {
455
- constructor(message, details, userMessage, suggestion, requestId) {
456
- super(
457
- "auth_error",
458
- message,
459
- 401,
460
- details,
461
- userMessage,
462
- suggestion,
463
- requestId
464
- );
465
- this.name = "AuthError";
466
- }
467
- };
468
- var PermissionError = class extends SDKError {
469
- constructor(message, details, userMessage, suggestion, requestId) {
470
- super(
471
- "permission_error",
472
- message,
473
- 403,
474
- details,
475
- userMessage,
476
- suggestion,
477
- requestId
478
- );
479
- this.name = "PermissionError";
480
- }
481
- };
482
- var NotFoundError = class extends SDKError {
483
- constructor(message, details, userMessage, suggestion, requestId) {
484
- super(
485
- "not_found",
486
- message,
487
- 404,
488
- details,
489
- userMessage,
490
- suggestion,
491
- requestId
492
- );
493
- this.name = "NotFoundError";
494
- }
495
- };
496
- var ConflictError = class extends SDKError {
497
- constructor(message, details, userMessage, suggestion, requestId) {
498
- super("conflict", message, 409, details, userMessage, suggestion, requestId);
499
- this.name = "ConflictError";
500
- }
501
- };
502
- var createNetworkError = (message, status, details, userMessage, suggestion) => new NetworkError(message, status, details, userMessage, suggestion);
503
- var createValidationError = (message, details, userMessage, suggestion, status) => new ValidationError(message, details, userMessage, suggestion, status);
504
- var createApiError = (message, status, details, userMessage, suggestion, requestId) => new ApiError(message, status, details, userMessage, suggestion, requestId);
505
409
  var createConfigError = (message, details, userMessage, suggestion) => new ConfigError(message, details, userMessage, suggestion);
506
- var createTimeoutError = (message, details, userMessage, suggestion) => new TimeoutError(message, details, userMessage, suggestion);
507
- var createUsageLimitError = (message, usage, details, userMessage, suggestion) => new UsageLimitError(message, usage, details, userMessage, suggestion);
508
- var createAuthError = (message, details, userMessage, suggestion, requestId) => new AuthError(message, details, userMessage, suggestion, requestId);
509
- var createPermissionError = (message, details, userMessage, suggestion, requestId) => new PermissionError(message, details, userMessage, suggestion, requestId);
510
- var createNotFoundError = (message, details, userMessage, suggestion, requestId) => new NotFoundError(message, details, userMessage, suggestion, requestId);
511
- var createConflictError = (message, details, userMessage, suggestion, requestId) => new ConflictError(message, details, userMessage, suggestion, requestId);
512
410
 
513
411
  // src/core/query/customer-hooks.ts
514
412
  function createMutation(mutationFn, callbacks, onSuccessExtra) {
@@ -1001,7 +899,7 @@ var RealtimeConnection = class {
1001
899
  }
1002
900
  scheduleReconnect() {
1003
901
  if (this.reconnectTimer) return;
1004
- const delay2 = Math.min(
902
+ const delay = Math.min(
1005
903
  INITIAL_RECONNECT_DELAY * Math.pow(RECONNECT_BACKOFF_FACTOR, this.reconnectAttempt),
1006
904
  MAX_RECONNECT_DELAY
1007
905
  );
@@ -1010,916 +908,7 @@ var RealtimeConnection = class {
1010
908
  this.reconnectTimer = null;
1011
909
  this.abortController = new AbortController();
1012
910
  this.startStream(this.abortController.signal);
1013
- }, delay2);
1014
- }
1015
- };
1016
-
1017
- // src/utils/types.ts
1018
- var resolveRelation = (ref) => {
1019
- if (typeof ref === "string" || typeof ref === "number" || ref === null || ref === void 0)
1020
- return null;
1021
- return ref;
1022
- };
1023
-
1024
- // src/core/metadata/index.ts
1025
- function extractSeo(doc) {
1026
- const seo = doc.seo ?? {};
1027
- const og = seo.openGraph ?? {};
1028
- return {
1029
- title: seo.title ?? doc.title ?? null,
1030
- description: seo.description ?? null,
1031
- noIndex: seo.noIndex ?? null,
1032
- canonical: seo.canonical ?? null,
1033
- openGraph: {
1034
- title: og.title ?? null,
1035
- description: og.description ?? null,
1036
- image: og.image ?? null
1037
- }
1038
- };
1039
- }
1040
- function generateMetadata(input, options) {
1041
- const title = input.title ?? void 0;
1042
- const description = input.description ?? void 0;
1043
- const ogTitle = input.openGraph?.title ?? title;
1044
- const ogDescription = input.openGraph?.description ?? description;
1045
- const image = resolveMetaImage(input.openGraph?.image);
1046
- return {
1047
- title,
1048
- description,
1049
- ...input.noIndex && { robots: { index: false, follow: false } },
1050
- ...input.canonical && { alternates: { canonical: input.canonical } },
1051
- openGraph: {
1052
- ...ogTitle && { title: ogTitle },
1053
- ...ogDescription && { description: ogDescription },
1054
- ...options?.siteName && { siteName: options.siteName },
1055
- ...image && { images: [image] }
1056
- },
1057
- twitter: {
1058
- card: image ? "summary_large_image" : "summary",
1059
- ...ogTitle && { title: ogTitle },
1060
- ...ogDescription && { description: ogDescription },
1061
- ...image && { images: [image.url] }
1062
- }
1063
- };
1064
- }
1065
- function resolveMetaImage(ref) {
1066
- const image = resolveRelation(ref);
1067
- if (!image) return null;
1068
- const sized = image.sizes?.["1536"];
1069
- const url = sized?.url || image.url;
1070
- if (!url) return null;
1071
- const width = sized?.url ? sized.width : image.width;
1072
- const height = sized?.url ? sized.height : image.height;
1073
- return {
1074
- url,
1075
- ...width && { width },
1076
- ...height && { height },
1077
- ...image.alt && { alt: image.alt }
1078
- };
1079
- }
1080
-
1081
- // src/core/collection/query-builder.ts
1082
- var CollectionQueryBuilder = class {
1083
- constructor(api, collection) {
1084
- this.api = api;
1085
- this.collection = collection;
1086
- }
1087
- /**
1088
- * Find documents (list query)
1089
- * GET /api/{collection}
1090
- * @returns Payload CMS find response with docs array and pagination
1091
- */
1092
- async find(options) {
1093
- return this.api.requestFind(
1094
- `/api/${String(this.collection)}`,
1095
- options
1096
- );
1097
- }
1098
- /**
1099
- * Find document by ID
1100
- * GET /api/{collection}/{id}
1101
- * @returns Document object directly (no wrapper)
1102
- */
1103
- async findById(id, options) {
1104
- return this.api.requestFindById(
1105
- `/api/${String(this.collection)}/${String(id)}`,
1106
- options
1107
- );
1108
- }
1109
- /**
1110
- * Create a new document
1111
- * POST /api/{collection}
1112
- * @returns Payload CMS mutation response with doc and message
1113
- */
1114
- async create(data, options) {
1115
- const endpoint = `/api/${String(this.collection)}`;
1116
- if (options?.file) {
1117
- return this.api.requestCreateWithFile(
1118
- endpoint,
1119
- data,
1120
- options.file,
1121
- options.filename
1122
- );
1123
- }
1124
- return this.api.requestCreate(endpoint, data);
1125
- }
1126
- /**
1127
- * Update a document by ID
1128
- * PATCH /api/{collection}/{id}
1129
- * @returns Payload CMS mutation response with doc and message
1130
- */
1131
- async update(id, data, options) {
1132
- const endpoint = `/api/${String(this.collection)}/${String(id)}`;
1133
- if (options?.file) {
1134
- return this.api.requestUpdateWithFile(
1135
- endpoint,
1136
- data,
1137
- options.file,
1138
- options.filename
1139
- );
1140
- }
1141
- return this.api.requestUpdate(endpoint, data);
1142
- }
1143
- /**
1144
- * Count documents
1145
- * GET /api/{collection}/count
1146
- * @returns Count response with totalDocs
1147
- */
1148
- async count(options) {
1149
- return this.api.requestCount(
1150
- `/api/${String(this.collection)}/count`,
1151
- options
1152
- );
1153
- }
1154
- /**
1155
- * Find first matching document and return its Next.js Metadata.
1156
- * Applies depth: 1 (SEO image populate) and limit: 1 automatically.
1157
- * @returns Metadata or null if no document matches
1158
- */
1159
- async findMetadata(options, metadataOptions) {
1160
- const { docs } = await this.find({ ...options, limit: 1, depth: 1 });
1161
- const doc = docs[0];
1162
- if (!doc) return null;
1163
- return generateMetadata(
1164
- extractSeo(doc),
1165
- metadataOptions
1166
- );
1167
- }
1168
- /**
1169
- * Find document by ID and return its Next.js Metadata.
1170
- * Applies depth: 1 (SEO image populate) automatically.
1171
- * @returns Metadata (throws on 404)
1172
- */
1173
- async findMetadataById(id, metadataOptions) {
1174
- const doc = await this.findById(id, { depth: 1 });
1175
- return generateMetadata(
1176
- extractSeo(doc),
1177
- metadataOptions
1178
- );
1179
- }
1180
- /**
1181
- * Update multiple documents (bulk update)
1182
- * PATCH /api/{collection}
1183
- * @returns Payload CMS find response with updated docs
1184
- */
1185
- async updateMany(where, data) {
1186
- return this.api.requestUpdateMany(
1187
- `/api/${String(this.collection)}`,
1188
- { where, data }
1189
- );
1190
- }
1191
- /**
1192
- * Delete a document by ID
1193
- * DELETE /api/{collection}/{id}
1194
- * @returns Deleted document object directly (no wrapper)
1195
- */
1196
- async remove(id) {
1197
- return this.api.requestDelete(
1198
- `/api/${String(this.collection)}/${String(id)}`
1199
- );
1200
- }
1201
- /**
1202
- * Delete multiple documents (bulk delete)
1203
- * DELETE /api/{collection}
1204
- * @returns Payload CMS find response with deleted docs
1205
- */
1206
- async removeMany(where) {
1207
- return this.api.requestDeleteMany(
1208
- `/api/${String(this.collection)}`,
1209
- { where }
1210
- );
1211
- }
1212
- };
1213
-
1214
- // src/core/collection/http-client.ts
1215
- var import_qs_esm = require("qs-esm");
1216
-
1217
- // src/core/internal/utils/credentials.ts
1218
- function requirePublishableKeyForSecret(apiName, publishableKey, secretKey) {
1219
- if (secretKey && !publishableKey) {
1220
- throw createConfigError(
1221
- `publishableKey is required for ${apiName} when secretKey is used. It is sent as X-Publishable-Key for tenant routing, rate limiting, and quota enforcement.`
1222
- );
1223
- }
1224
- return publishableKey ?? "";
1225
- }
1226
-
1227
- // src/core/client/types.ts
1228
- function resolveApiUrl(apiUrl) {
1229
- if (apiUrl) {
1230
- return apiUrl.replace(/\/$/, "");
1231
- }
1232
- if (typeof process !== "undefined" && process.env) {
1233
- const envUrl = process.env.SOFTWARE_API_URL || process.env.NEXT_PUBLIC_SOFTWARE_API_URL;
1234
- if (envUrl) {
1235
- return envUrl.replace(/\/$/, "");
1236
- }
1237
- }
1238
- return "https://api.01.software";
1239
- }
1240
-
1241
- // src/core/internal/utils/http.ts
1242
- var DEFAULT_TIMEOUT = 3e4;
1243
- var STOREFRONT_BROWSER_TIMEOUT = 15e3;
1244
- var DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504];
1245
- var NON_RETRYABLE_STATUSES = [400, 401, 403, 404, 409, 422];
1246
- var SAFE_METHODS = ["GET", "HEAD", "OPTIONS"];
1247
- var DEFAULT_MAX_RETRIES = 3;
1248
- var STOREFRONT_BROWSER_MAX_RETRIES = 1;
1249
- function debugLog(debug, type, message, data) {
1250
- if (!debug) return;
1251
- const shouldLog = debug === true || type === "request" && debug.logRequests || type === "response" && debug.logResponses || type === "error" && debug.logErrors;
1252
- if (shouldLog) {
1253
- console.group(`[SDK ${type.toUpperCase()}] ${message}`);
1254
- if (data) console.log(data);
1255
- console.groupEnd();
1256
- }
1257
- }
1258
- function redactSensitiveHeader(value) {
1259
- const prefix = value.toLowerCase().startsWith("bearer ") ? "Bearer " : "";
1260
- return value.length > 20 ? `${prefix}...****${value.slice(-8)}` : "****";
1261
- }
1262
- function redactSensitiveHeaders(headers) {
1263
- const redacted = Object.fromEntries(headers.entries());
1264
- if (redacted.authorization) {
1265
- redacted.authorization = redactSensitiveHeader(redacted.authorization);
1266
- }
1267
- if (redacted["x-preview-token"]) {
1268
- redacted["x-preview-token"] = redactSensitiveHeader(
1269
- redacted["x-preview-token"]
1270
- );
1271
- }
1272
- return redacted;
1273
- }
1274
- function getErrorSuggestion(status) {
1275
- if (status === 400)
1276
- return "The request data failed validation. Check field values and types.";
1277
- if (status === 401) return "Please check your authentication credentials.";
1278
- if (status === 403)
1279
- return "Access denied. Check your credentials or permissions.";
1280
- if (status === 404) return "The requested resource was not found.";
1281
- if (status === 422) return "The request data failed validation.";
1282
- if (status >= 500) return "A server error occurred. Please try again later.";
1283
- return void 0;
1284
- }
1285
- function isUsageLimitExceededResponse(response) {
1286
- if (response.status !== 429) return false;
1287
- const limit = parseInt(response.headers.get("X-Usage-Limit") || "", 10);
1288
- const current = parseInt(response.headers.get("X-Usage-Current") || "", 10);
1289
- if (!Number.isFinite(limit) || !Number.isFinite(current)) return false;
1290
- return response.headers.get("X-Usage-Exceeded") === "true" || current > limit;
1291
- }
1292
- async function parseErrorBody(response) {
1293
- const fallback = {
1294
- errorMessage: `HTTP ${response.status}: ${response.statusText}`,
1295
- userMessage: `Request failed (status: ${response.status})`
1296
- };
1297
- try {
1298
- const body = await response.json();
1299
- const reason = typeof body.reason === "string" ? body.reason : typeof body.code === "string" ? body.code : void 0;
1300
- if (body.errors && Array.isArray(body.errors)) {
1301
- const fieldErrors = [];
1302
- for (const e of body.errors) {
1303
- if (e.data?.errors && Array.isArray(e.data.errors) && e.data.errors.length > 0) {
1304
- for (const fe of e.data.errors) {
1305
- fieldErrors.push({
1306
- field: fe.path || fe.field,
1307
- message: fe.message
1308
- });
1309
- }
1310
- } else if (e.field || e.message) {
1311
- fieldErrors.push({ field: e.field, message: e.message });
1312
- }
1313
- }
1314
- const details = (fieldErrors.length > 0 ? fieldErrors : body.errors).map(
1315
- (e) => e.field ? `${e.field}: ${e.message}` : e.message
1316
- ).filter(Boolean).join("; ");
1317
- if (details) {
1318
- return {
1319
- errorMessage: `HTTP ${response.status}: ${details}`,
1320
- userMessage: details,
1321
- reason,
1322
- body,
1323
- errors: fieldErrors.length > 0 ? fieldErrors : body.errors
1324
- };
1325
- }
1326
- }
1327
- if (typeof body.error === "string") {
1328
- return {
1329
- errorMessage: `HTTP ${response.status}: ${body.error}`,
1330
- userMessage: body.error,
1331
- reason,
1332
- body
1333
- };
1334
- }
1335
- if (body.message) {
1336
- return {
1337
- errorMessage: `HTTP ${response.status}: ${body.message}`,
1338
- userMessage: body.message,
1339
- reason,
1340
- body
1341
- };
1342
- }
1343
- return { ...fallback, reason, body };
1344
- } catch {
1345
- return fallback;
1346
- }
1347
- }
1348
- function getParsedErrorSuggestion(status, parsed) {
1349
- if (status === 403 && parsed.reason === "origin_not_allowed") {
1350
- return "Add the request origin to the tenant Browser API origins, then retry the browser request.";
1351
- }
1352
- return getErrorSuggestion(status);
1353
- }
1354
- async function delay(ms) {
1355
- return new Promise((resolve) => setTimeout(resolve, ms));
1356
- }
1357
- function attachRequestId(err, id) {
1358
- if (id) err.requestId = id;
1359
- return err;
1360
- }
1361
- function createHttpStatusError(status, parsed, details, requestId) {
1362
- const errorDetails = {
1363
- ...details,
1364
- ...parsed.errors && { errors: parsed.errors },
1365
- ...parsed.body && { body: parsed.body }
1366
- };
1367
- const suggestion = getParsedErrorSuggestion(status, parsed);
1368
- if (status === 400 || status === 422) {
1369
- return attachRequestId(
1370
- createValidationError(
1371
- parsed.errorMessage,
1372
- errorDetails,
1373
- parsed.userMessage,
1374
- suggestion,
1375
- status
1376
- ),
1377
- requestId
1378
- );
1379
- }
1380
- if (status === 401) {
1381
- return attachRequestId(
1382
- createAuthError(
1383
- parsed.errorMessage,
1384
- errorDetails,
1385
- parsed.userMessage,
1386
- suggestion
1387
- ),
1388
- requestId
1389
- );
1390
- }
1391
- if (status === 403) {
1392
- return attachRequestId(
1393
- createPermissionError(
1394
- parsed.errorMessage,
1395
- errorDetails,
1396
- parsed.userMessage,
1397
- suggestion
1398
- ),
1399
- requestId
1400
- );
1401
- }
1402
- if (status === 404) {
1403
- return attachRequestId(
1404
- createNotFoundError(
1405
- parsed.errorMessage,
1406
- errorDetails,
1407
- parsed.userMessage,
1408
- suggestion
1409
- ),
1410
- requestId
1411
- );
1412
- }
1413
- if (status === 409) {
1414
- return attachRequestId(
1415
- createConflictError(
1416
- parsed.errorMessage,
1417
- errorDetails,
1418
- parsed.userMessage,
1419
- suggestion
1420
- ),
1421
- requestId
1422
- );
1423
- }
1424
- return attachRequestId(
1425
- createNetworkError(
1426
- parsed.errorMessage,
1427
- status,
1428
- errorDetails,
1429
- parsed.userMessage,
1430
- suggestion
1431
- ),
1432
- requestId
1433
- );
1434
- }
1435
- async function httpFetch(url, options) {
1436
- const {
1437
- apiUrl,
1438
- publishableKey,
1439
- secretKey,
1440
- customerToken,
1441
- timeout: timeoutOption = DEFAULT_TIMEOUT,
1442
- debug,
1443
- retry,
1444
- onUnauthorized,
1445
- ...requestInit
1446
- } = options || {};
1447
- const baseUrl = resolveApiUrl(apiUrl);
1448
- const method = (requestInit.method || "GET").toUpperCase();
1449
- const isPublishableKeyBrowserGet = typeof window !== "undefined" && !secretKey && !customerToken && Boolean(publishableKey) && SAFE_METHODS.includes(method);
1450
- const timeout = timeoutOption === DEFAULT_TIMEOUT && isPublishableKeyBrowserGet ? STOREFRONT_BROWSER_TIMEOUT : timeoutOption;
1451
- const retryConfig = {
1452
- maxRetries: retry?.maxRetries ?? (isPublishableKeyBrowserGet ? STOREFRONT_BROWSER_MAX_RETRIES : DEFAULT_MAX_RETRIES),
1453
- retryableStatuses: retry?.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES,
1454
- retryDelay: retry?.retryDelay ?? ((attempt) => Math.min(1e3 * 2 ** attempt, 1e4))
1455
- };
1456
- let authToken;
1457
- if (secretKey) {
1458
- authToken = secretKey;
1459
- } else if (customerToken) {
1460
- authToken = customerToken;
1461
- }
1462
- let lastError;
1463
- let hasRetried401 = false;
1464
- for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {
1465
- try {
1466
- const headers = new Headers(requestInit.headers);
1467
- if (publishableKey) {
1468
- headers.set("X-Publishable-Key", publishableKey);
1469
- }
1470
- if (authToken) {
1471
- headers.set("Authorization", `Bearer ${authToken}`);
1472
- }
1473
- if (!headers.has("Content-Type") && requestInit.body && !(requestInit.body instanceof FormData)) {
1474
- headers.set("Content-Type", "application/json");
1475
- }
1476
- const redactedHeaders = redactSensitiveHeaders(headers);
1477
- debugLog(debug, "request", url, {
1478
- method: requestInit.method || "GET",
1479
- headers: redactedHeaders,
1480
- attempt: attempt + 1
1481
- });
1482
- const controller = new AbortController();
1483
- const timeoutId = setTimeout(() => controller.abort(), timeout);
1484
- const response = await fetch(`${baseUrl}${url}`, {
1485
- ...requestInit,
1486
- headers,
1487
- signal: controller.signal
1488
- });
1489
- clearTimeout(timeoutId);
1490
- const requestId = response.headers.get("x-request-id") ?? void 0;
1491
- debugLog(debug, "response", url, {
1492
- status: response.status,
1493
- statusText: response.statusText,
1494
- headers: redactSensitiveHeaders(response.headers)
1495
- });
1496
- if (!response.ok) {
1497
- if (isUsageLimitExceededResponse(response)) {
1498
- const limit = parseInt(
1499
- response.headers.get("X-Usage-Limit") || "0",
1500
- 10
1501
- );
1502
- const current = parseInt(
1503
- response.headers.get("X-Usage-Current") || "0",
1504
- 10
1505
- );
1506
- const remaining = parseInt(
1507
- response.headers.get("X-Usage-Remaining") || "0",
1508
- 10
1509
- );
1510
- throw attachRequestId(
1511
- createUsageLimitError(
1512
- `Monthly API usage limit exceeded (${current.toLocaleString()}/${limit.toLocaleString()})`,
1513
- { limit, current, remaining },
1514
- {
1515
- url,
1516
- method: requestInit.method || "GET",
1517
- attempt: attempt + 1
1518
- },
1519
- "Monthly API call limit exceeded. Please upgrade your plan.",
1520
- "Upgrade your tenant plan to increase the monthly API call limit."
1521
- ),
1522
- requestId
1523
- );
1524
- }
1525
- const parsed = await parseErrorBody(response);
1526
- if (response.status === 401 && onUnauthorized && customerToken && !hasRetried401 && parsed.reason === "token_expired") {
1527
- hasRetried401 = true;
1528
- try {
1529
- const newToken = await onUnauthorized();
1530
- if (newToken) {
1531
- authToken = newToken;
1532
- continue;
1533
- }
1534
- } catch {
1535
- }
1536
- }
1537
- const details = {
1538
- url,
1539
- method: requestInit.method || "GET",
1540
- attempt: attempt + 1
1541
- };
1542
- if (NON_RETRYABLE_STATUSES.includes(response.status)) {
1543
- throw createHttpStatusError(
1544
- response.status,
1545
- parsed,
1546
- details,
1547
- requestId
1548
- );
1549
- }
1550
- const error = attachRequestId(
1551
- createNetworkError(
1552
- parsed.errorMessage,
1553
- response.status,
1554
- details,
1555
- parsed.userMessage,
1556
- getErrorSuggestion(response.status)
1557
- ),
1558
- requestId
1559
- );
1560
- const method2 = (requestInit.method || "GET").toUpperCase();
1561
- if (attempt < retryConfig.maxRetries && SAFE_METHODS.includes(method2) && retryConfig.retryableStatuses.includes(response.status)) {
1562
- lastError = error;
1563
- const retryDelay = retryConfig.retryDelay(attempt);
1564
- debugLog(debug, "error", `Retrying in ${retryDelay}ms...`, error);
1565
- await delay(retryDelay);
1566
- continue;
1567
- }
1568
- throw error;
1569
- }
1570
- return response;
1571
- } catch (error) {
1572
- debugLog(debug, "error", url, error);
1573
- const method2 = (requestInit.method || "GET").toUpperCase();
1574
- const isSafe = SAFE_METHODS.includes(method2);
1575
- if (error instanceof Error && error.name === "AbortError") {
1576
- const timeoutError = createTimeoutError(
1577
- `Request timed out after ${timeout}ms.`,
1578
- { url, timeout, attempt: attempt + 1 },
1579
- "The request timed out.",
1580
- "Please check your network connection or try again later."
1581
- );
1582
- if (isSafe && attempt < retryConfig.maxRetries) {
1583
- lastError = timeoutError;
1584
- await delay(retryConfig.retryDelay(attempt));
1585
- continue;
1586
- }
1587
- throw timeoutError;
1588
- }
1589
- if (error instanceof TypeError) {
1590
- const networkError = createNetworkError(
1591
- "Network connection failed.",
1592
- void 0,
1593
- { url, originalError: error.message, attempt: attempt + 1 },
1594
- "Network connection failed.",
1595
- "Please check your internet connection and try again."
1596
- );
1597
- if (isSafe && attempt < retryConfig.maxRetries) {
1598
- lastError = networkError;
1599
- await delay(retryConfig.retryDelay(attempt));
1600
- continue;
1601
- }
1602
- throw networkError;
1603
- }
1604
- if (error instanceof NetworkError || error instanceof TimeoutError) {
1605
- if (isSafe && attempt < retryConfig.maxRetries && error.status && !NON_RETRYABLE_STATUSES.includes(error.status) && retryConfig.retryableStatuses.includes(error.status)) {
1606
- lastError = error;
1607
- await delay(retryConfig.retryDelay(attempt));
1608
- continue;
1609
- }
1610
- throw error;
1611
- }
1612
- if (error instanceof SDKError) {
1613
- throw error;
1614
- }
1615
- const unknownError = createNetworkError(
1616
- error instanceof Error ? error.message : "An unknown network error occurred.",
1617
- void 0,
1618
- { url, originalError: error, attempt: attempt + 1 },
1619
- "An unknown error occurred.",
1620
- "Please try again later."
1621
- );
1622
- if (isSafe && attempt < retryConfig.maxRetries) {
1623
- lastError = unknownError;
1624
- await delay(retryConfig.retryDelay(attempt));
1625
- continue;
1626
- }
1627
- throw unknownError;
1628
- }
1629
- }
1630
- throw lastError ?? new NetworkError("Request failed after retries");
1631
- }
1632
-
1633
- // src/core/collection/http-client.ts
1634
- var HttpClient = class {
1635
- constructor(publishableKey, secretKey, getCustomerToken, onUnauthorized, onRequestId, apiUrl) {
1636
- this.publishableKey = requirePublishableKeyForSecret(
1637
- "CollectionClient",
1638
- publishableKey,
1639
- secretKey
1640
- );
1641
- this.secretKey = secretKey;
1642
- this.getCustomerToken = getCustomerToken;
1643
- this.onUnauthorized = onUnauthorized;
1644
- this.onRequestId = onRequestId;
1645
- this.apiUrl = apiUrl;
1646
- }
1647
- get defaultOptions() {
1648
- const opts = {
1649
- apiUrl: this.apiUrl,
1650
- publishableKey: this.publishableKey,
1651
- secretKey: this.secretKey
1652
- };
1653
- const token = this.getCustomerToken?.();
1654
- if (token) {
1655
- opts.customerToken = token;
1656
- if (this.onUnauthorized) {
1657
- opts.onUnauthorized = this.onUnauthorized;
1658
- }
1659
- }
1660
- return opts;
1661
- }
1662
- async fetchWithTracking(url, opts) {
1663
- try {
1664
- const response = await httpFetch(url, opts);
1665
- this.onRequestId?.(response.headers.get("x-request-id") ?? null);
1666
- return response;
1667
- } catch (err) {
1668
- const id = err instanceof SDKError ? err.requestId ?? null : null;
1669
- this.onRequestId?.(id);
1670
- throw err;
1671
- }
1672
- }
1673
- buildUrl(endpoint, options) {
1674
- if (!options) return endpoint;
1675
- const queryString = (0, import_qs_esm.stringify)(options, { addQueryPrefix: true });
1676
- return queryString ? `${endpoint}${queryString}` : endpoint;
1677
- }
1678
- assertJsonResponse(response) {
1679
- const contentType = response.headers.get("content-type");
1680
- if (!contentType?.includes("application/json")) {
1681
- throw createApiError("Response is not in JSON format.", response.status, {
1682
- contentType
1683
- });
1684
- }
1685
- }
1686
- /**
1687
- * Parse Payload CMS find response (list query)
1688
- * Returns native Payload response structure
1689
- */
1690
- async parseFindResponse(response) {
1691
- const contentType = response.headers.get("content-type");
1692
- try {
1693
- this.assertJsonResponse(response);
1694
- const jsonData = await response.json();
1695
- if (jsonData.docs === void 0) {
1696
- throw createApiError("Invalid find response.", response.status, {
1697
- jsonData
1698
- });
1699
- }
1700
- return {
1701
- docs: jsonData.docs,
1702
- totalDocs: jsonData.totalDocs ?? 0,
1703
- limit: jsonData.limit || 20,
1704
- totalPages: jsonData.totalPages ?? 0,
1705
- page: jsonData.page || 1,
1706
- pagingCounter: jsonData.pagingCounter || 1,
1707
- hasPrevPage: jsonData.hasPrevPage ?? false,
1708
- hasNextPage: jsonData.hasNextPage ?? false,
1709
- prevPage: jsonData.prevPage ?? null,
1710
- nextPage: jsonData.nextPage ?? null
1711
- };
1712
- } catch (error) {
1713
- if (error instanceof SDKError) throw error;
1714
- throw createApiError("Failed to parse response.", response.status, {
1715
- contentType,
1716
- error: error instanceof Error ? error.message : error
1717
- });
1718
- }
1719
- }
1720
- /**
1721
- * Parse Payload CMS mutation response (create/update)
1722
- * Returns native Payload response structure
1723
- */
1724
- async parseMutationResponse(response) {
1725
- const contentType = response.headers.get("content-type");
1726
- try {
1727
- this.assertJsonResponse(response);
1728
- const jsonData = await response.json();
1729
- if (jsonData.doc === void 0) {
1730
- throw createApiError("Invalid mutation response.", response.status, {
1731
- jsonData
1732
- });
1733
- }
1734
- return {
1735
- message: jsonData.message || "",
1736
- doc: jsonData.doc,
1737
- errors: jsonData.errors
1738
- };
1739
- } catch (error) {
1740
- if (error instanceof SDKError) throw error;
1741
- throw createApiError("Failed to parse response.", response.status, {
1742
- contentType,
1743
- error: error instanceof Error ? error.message : error
1744
- });
1745
- }
1746
- }
1747
- /**
1748
- * Parse Payload CMS document response (findById/delete)
1749
- * Returns document directly without wrapper
1750
- */
1751
- async parseDocumentResponse(response) {
1752
- const contentType = response.headers.get("content-type");
1753
- try {
1754
- this.assertJsonResponse(response);
1755
- const jsonData = await response.json();
1756
- return jsonData;
1757
- } catch (error) {
1758
- if (error instanceof SDKError) throw error;
1759
- throw createApiError("Failed to parse response.", response.status, {
1760
- contentType,
1761
- error: error instanceof Error ? error.message : error
1762
- });
1763
- }
1764
- }
1765
- };
1766
-
1767
- // src/core/collection/collection-client.ts
1768
- function buildPayloadFormData(data, file, filename) {
1769
- const formData = new FormData();
1770
- formData.append("file", file, filename);
1771
- if (data != null) {
1772
- formData.append("_payload", JSON.stringify(data));
1773
- }
1774
- return formData;
1775
- }
1776
- var CollectionClient = class extends HttpClient {
1777
- from(collection) {
1778
- return new CollectionQueryBuilder(this, collection);
1779
- }
1780
- // ============================================================================
1781
- // Payload-native methods
1782
- // ============================================================================
1783
- /**
1784
- * Find documents (list query)
1785
- * GET /api/{collection}
1786
- */
1787
- async requestFind(endpoint, options) {
1788
- const url = this.buildUrl(endpoint, options);
1789
- const response = await this.fetchWithTracking(url, {
1790
- ...this.defaultOptions,
1791
- method: "GET"
1792
- });
1793
- return this.parseFindResponse(response);
1794
- }
1795
- /**
1796
- * Find-like response from a custom endpoint
1797
- * POST /api/...custom-endpoint
1798
- */
1799
- async requestFindEndpoint(endpoint, data) {
1800
- const response = await this.fetchWithTracking(endpoint, {
1801
- ...this.defaultOptions,
1802
- method: "POST",
1803
- body: data ? JSON.stringify(data) : void 0
1804
- });
1805
- return this.parseFindResponse(response);
1806
- }
1807
- /**
1808
- * Find-like response from a cacheable GET custom endpoint.
1809
- */
1810
- async requestFindEndpointGet(endpoint) {
1811
- const response = await this.fetchWithTracking(endpoint, {
1812
- ...this.defaultOptions,
1813
- method: "GET"
1814
- });
1815
- return this.parseFindResponse(response);
1816
- }
1817
- /**
1818
- * Find document by ID
1819
- * GET /api/{collection}/{id}
1820
- */
1821
- async requestFindById(endpoint, options) {
1822
- const url = this.buildUrl(endpoint, options);
1823
- const response = await this.fetchWithTracking(url, {
1824
- ...this.defaultOptions,
1825
- method: "GET"
1826
- });
1827
- return this.parseDocumentResponse(response);
1828
- }
1829
- /**
1830
- * Create document
1831
- * POST /api/{collection}
1832
- */
1833
- async requestCreate(endpoint, data) {
1834
- const response = await this.fetchWithTracking(endpoint, {
1835
- ...this.defaultOptions,
1836
- method: "POST",
1837
- body: data ? JSON.stringify(data) : void 0
1838
- });
1839
- return this.parseMutationResponse(response);
1840
- }
1841
- /**
1842
- * Update document
1843
- * PATCH /api/{collection}/{id}
1844
- */
1845
- async requestUpdate(endpoint, data) {
1846
- const response = await this.fetchWithTracking(endpoint, {
1847
- ...this.defaultOptions,
1848
- method: "PATCH",
1849
- body: data ? JSON.stringify(data) : void 0
1850
- });
1851
- return this.parseMutationResponse(response);
1852
- }
1853
- /**
1854
- * Count documents
1855
- * GET /api/{collection}/count
1856
- */
1857
- async requestCount(endpoint, options) {
1858
- const url = this.buildUrl(endpoint, options);
1859
- const response = await this.fetchWithTracking(url, {
1860
- ...this.defaultOptions,
1861
- method: "GET"
1862
- });
1863
- return this.parseDocumentResponse(response);
1864
- }
1865
- /**
1866
- * Update multiple documents (bulk update)
1867
- * PATCH /api/{collection}
1868
- */
1869
- async requestUpdateMany(endpoint, data) {
1870
- const response = await this.fetchWithTracking(endpoint, {
1871
- ...this.defaultOptions,
1872
- method: "PATCH",
1873
- body: JSON.stringify(data)
1874
- });
1875
- return this.parseFindResponse(response);
1876
- }
1877
- /**
1878
- * Delete document
1879
- * DELETE /api/{collection}/{id}
1880
- */
1881
- async requestDelete(endpoint) {
1882
- const response = await this.fetchWithTracking(endpoint, {
1883
- ...this.defaultOptions,
1884
- method: "DELETE"
1885
- });
1886
- return this.parseDocumentResponse(response);
1887
- }
1888
- /**
1889
- * Delete multiple documents (bulk delete)
1890
- * DELETE /api/{collection}
1891
- */
1892
- async requestDeleteMany(endpoint, data) {
1893
- const response = await this.fetchWithTracking(endpoint, {
1894
- ...this.defaultOptions,
1895
- method: "DELETE",
1896
- body: JSON.stringify(data)
1897
- });
1898
- return this.parseFindResponse(response);
1899
- }
1900
- /**
1901
- * Create document with file upload
1902
- * POST /api/{collection} (multipart/form-data)
1903
- */
1904
- async requestCreateWithFile(endpoint, data, file, filename) {
1905
- const response = await this.fetchWithTracking(endpoint, {
1906
- ...this.defaultOptions,
1907
- method: "POST",
1908
- body: buildPayloadFormData(data, file, filename)
1909
- });
1910
- return this.parseMutationResponse(response);
1911
- }
1912
- /**
1913
- * Update document with file upload
1914
- * PATCH /api/{collection}/{id} (multipart/form-data)
1915
- */
1916
- async requestUpdateWithFile(endpoint, data, file, filename) {
1917
- const response = await this.fetchWithTracking(endpoint, {
1918
- ...this.defaultOptions,
1919
- method: "PATCH",
1920
- body: buildPayloadFormData(data, file, filename)
1921
- });
1922
- return this.parseMutationResponse(response);
911
+ }, delay);
1923
912
  }
1924
913
  };
1925
914
 
@@ -1962,28 +951,9 @@ function createReadOnlyQueryHooksFacade(hooks) {
1962
951
  };
1963
952
  }
1964
953
  function createQueryHooks(client, queryClient = getQueryClient()) {
1965
- const config = client.getConfig();
1966
- const onUnauthorized = async () => {
1967
- try {
1968
- const result = await client.customer.auth.refreshToken();
1969
- return result.token ?? null;
1970
- } catch {
1971
- return null;
1972
- }
1973
- };
1974
- const collectionClient = new CollectionClient(
1975
- config.publishableKey,
1976
- void 0,
1977
- () => client.customer.auth.getToken(),
1978
- onUnauthorized,
1979
- (id) => {
1980
- client.lastRequestId = id;
1981
- },
1982
- config.apiUrl
1983
- );
1984
954
  const hooks = new QueryHooks(
1985
955
  queryClient,
1986
- collectionClient,
956
+ client.collections,
1987
957
  client.customer.auth,
1988
958
  client.commerce
1989
959
  );