@01.software/sdk 0.29.0 → 0.31.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 (78) hide show
  1. package/README.md +331 -77
  2. package/dist/analytics/react.cjs +4 -1
  3. package/dist/analytics/react.cjs.map +1 -1
  4. package/dist/analytics/react.js +4 -1
  5. package/dist/analytics/react.js.map +1 -1
  6. package/dist/analytics.cjs +4 -1
  7. package/dist/analytics.cjs.map +1 -1
  8. package/dist/analytics.js +4 -1
  9. package/dist/analytics.js.map +1 -1
  10. package/dist/client.cjs +1541 -0
  11. package/dist/client.cjs.map +1 -0
  12. package/dist/client.d.cts +28 -0
  13. package/dist/client.d.ts +28 -0
  14. package/dist/client.js +1518 -0
  15. package/dist/client.js.map +1 -0
  16. package/dist/collection-client-ByzY3hWK.d.ts +218 -0
  17. package/dist/collection-client-DFXXz0vk.d.cts +218 -0
  18. package/dist/{const-DAjQYNuM.d.ts → const-AytzliEu.d.cts} +5 -7
  19. package/dist/{const-Dsixdi6z.d.cts → const-BGCP-OJL.d.ts} +5 -7
  20. package/dist/index-BGEhoDUs.d.cts +106 -0
  21. package/dist/index-BGEhoDUs.d.ts +106 -0
  22. package/dist/index.cjs +1006 -1615
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +11 -115
  25. package/dist/index.d.ts +11 -115
  26. package/dist/index.js +932 -1559
  27. package/dist/index.js.map +1 -1
  28. package/dist/metadata.cjs +91 -0
  29. package/dist/metadata.cjs.map +1 -0
  30. package/dist/metadata.d.cts +58 -0
  31. package/dist/metadata.d.ts +58 -0
  32. package/dist/metadata.js +68 -0
  33. package/dist/metadata.js.map +1 -0
  34. package/dist/{payload-types-Ci-ZA7aM.d.cts → payload-types-Wa4-eC6x.d.cts} +794 -532
  35. package/dist/{payload-types-Ci-ZA7aM.d.ts → payload-types-Wa4-eC6x.d.ts} +794 -532
  36. package/dist/query.cjs +1841 -0
  37. package/dist/query.cjs.map +1 -0
  38. package/dist/query.d.cts +244 -0
  39. package/dist/query.d.ts +244 -0
  40. package/dist/query.js +1836 -0
  41. package/dist/query.js.map +1 -0
  42. package/dist/realtime.cjs +4 -1
  43. package/dist/realtime.cjs.map +1 -1
  44. package/dist/realtime.d.cts +2 -2
  45. package/dist/realtime.d.ts +2 -2
  46. package/dist/realtime.js +4 -1
  47. package/dist/realtime.js.map +1 -1
  48. package/dist/{server-BINWywT8.d.cts → server-CrsPyqEc.d.cts} +14 -31
  49. package/dist/{server-BINWywT8.d.ts → server-CrsPyqEc.d.ts} +14 -31
  50. package/dist/server.cjs +430 -846
  51. package/dist/server.cjs.map +1 -1
  52. package/dist/server.d.cts +137 -7
  53. package/dist/server.d.ts +137 -7
  54. package/dist/server.js +430 -864
  55. package/dist/server.js.map +1 -1
  56. package/dist/{server-Cv0Q4dPQ.d.ts → types-BX2mqDf6.d.ts} +270 -743
  57. package/dist/{types-BWq_WlbB.d.ts → types-CVA10VC-.d.ts} +6 -2
  58. package/dist/{types-zKjATmDK.d.cts → types-CmLG-7RL.d.cts} +6 -2
  59. package/dist/{server-C0C8dtms.d.cts → types-DChFjQGz.d.cts} +270 -743
  60. package/dist/ui/canvas/server.cjs +7 -6
  61. package/dist/ui/canvas/server.cjs.map +1 -1
  62. package/dist/ui/canvas/server.d.cts +1 -3
  63. package/dist/ui/canvas/server.d.ts +1 -3
  64. package/dist/ui/canvas/server.js +7 -6
  65. package/dist/ui/canvas/server.js.map +1 -1
  66. package/dist/ui/canvas.cjs +11 -10
  67. package/dist/ui/canvas.cjs.map +1 -1
  68. package/dist/ui/canvas.d.cts +29 -6
  69. package/dist/ui/canvas.d.ts +29 -6
  70. package/dist/ui/canvas.js +11 -10
  71. package/dist/ui/canvas.js.map +1 -1
  72. package/dist/ui/form.d.cts +1 -1
  73. package/dist/ui/form.d.ts +1 -1
  74. package/dist/ui/video.d.cts +1 -1
  75. package/dist/ui/video.d.ts +1 -1
  76. package/dist/webhook.d.cts +3 -3
  77. package/dist/webhook.d.ts +3 -3
  78. package/package.json +84 -15
@@ -0,0 +1,1541 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/client.ts
21
+ var client_exports = {};
22
+ __export(client_exports, {
23
+ Client: () => Client,
24
+ createClient: () => createClient
25
+ });
26
+ module.exports = __toCommonJS(client_exports);
27
+
28
+ // src/core/collection/http-client.ts
29
+ var import_qs_esm = require("qs-esm");
30
+
31
+ // src/core/internal/errors/index.ts
32
+ var SDKError = class extends Error {
33
+ constructor(code, message, status, details, userMessage, suggestion, requestId) {
34
+ super(message);
35
+ this.name = "SDKError";
36
+ this.code = code;
37
+ this.status = status;
38
+ this.details = details;
39
+ this.userMessage = userMessage;
40
+ this.suggestion = suggestion;
41
+ this.requestId = requestId;
42
+ if (Error.captureStackTrace) {
43
+ Error.captureStackTrace(this, new.target);
44
+ }
45
+ }
46
+ getUserMessage() {
47
+ return this.userMessage || this.message;
48
+ }
49
+ toJSON() {
50
+ return {
51
+ name: this.name,
52
+ code: this.code,
53
+ message: this.message,
54
+ status: this.status,
55
+ details: this.details,
56
+ userMessage: this.userMessage,
57
+ suggestion: this.suggestion,
58
+ ...this.requestId !== void 0 && { requestId: this.requestId }
59
+ };
60
+ }
61
+ };
62
+ var NetworkError = class extends SDKError {
63
+ constructor(message, status, details, userMessage, suggestion) {
64
+ super("NETWORK_ERROR", message, status, details, userMessage, suggestion);
65
+ this.name = "NetworkError";
66
+ }
67
+ };
68
+ var ValidationError = class extends SDKError {
69
+ constructor(message, details, userMessage, suggestion, status = 400) {
70
+ super("VALIDATION_ERROR", message, status, details, userMessage, suggestion);
71
+ this.name = "ValidationError";
72
+ }
73
+ };
74
+ var ApiError = class extends SDKError {
75
+ constructor(message, status, details, userMessage, suggestion, requestId) {
76
+ super(
77
+ "API_ERROR",
78
+ message,
79
+ status,
80
+ details,
81
+ userMessage,
82
+ suggestion,
83
+ requestId
84
+ );
85
+ this.name = "ApiError";
86
+ }
87
+ };
88
+ var ConfigError = class extends SDKError {
89
+ constructor(message, details, userMessage, suggestion) {
90
+ super("CONFIG_ERROR", message, void 0, details, userMessage, suggestion);
91
+ this.name = "ConfigError";
92
+ }
93
+ };
94
+ var TimeoutError = class extends SDKError {
95
+ constructor(message = "Request timed out.", details, userMessage, suggestion) {
96
+ super("TIMEOUT_ERROR", message, 408, details, userMessage, suggestion);
97
+ this.name = "TimeoutError";
98
+ }
99
+ };
100
+ var UsageLimitError = class extends SDKError {
101
+ constructor(message, usage, details, userMessage, suggestion) {
102
+ super("USAGE_LIMIT_ERROR", message, 429, details, userMessage, suggestion);
103
+ this.name = "UsageLimitError";
104
+ this.usage = usage;
105
+ }
106
+ toJSON() {
107
+ return {
108
+ ...super.toJSON(),
109
+ usage: this.usage
110
+ };
111
+ }
112
+ };
113
+ var AuthError = class extends SDKError {
114
+ constructor(message, details, userMessage, suggestion, requestId) {
115
+ super(
116
+ "auth_error",
117
+ message,
118
+ 401,
119
+ details,
120
+ userMessage,
121
+ suggestion,
122
+ requestId
123
+ );
124
+ this.name = "AuthError";
125
+ }
126
+ };
127
+ var PermissionError = class extends SDKError {
128
+ constructor(message, details, userMessage, suggestion, requestId) {
129
+ super(
130
+ "permission_error",
131
+ message,
132
+ 403,
133
+ details,
134
+ userMessage,
135
+ suggestion,
136
+ requestId
137
+ );
138
+ this.name = "PermissionError";
139
+ }
140
+ };
141
+ var NotFoundError = class extends SDKError {
142
+ constructor(message, details, userMessage, suggestion, requestId) {
143
+ super(
144
+ "not_found",
145
+ message,
146
+ 404,
147
+ details,
148
+ userMessage,
149
+ suggestion,
150
+ requestId
151
+ );
152
+ this.name = "NotFoundError";
153
+ }
154
+ };
155
+ var ConflictError = class extends SDKError {
156
+ constructor(message, details, userMessage, suggestion, requestId) {
157
+ super("conflict", message, 409, details, userMessage, suggestion, requestId);
158
+ this.name = "ConflictError";
159
+ }
160
+ };
161
+ var RateLimitError = class extends SDKError {
162
+ constructor(message, retryAfter, details, userMessage, suggestion, requestId) {
163
+ super(
164
+ "rate_limit_exceeded",
165
+ message,
166
+ 429,
167
+ details,
168
+ userMessage,
169
+ suggestion,
170
+ requestId
171
+ );
172
+ this.name = "RateLimitError";
173
+ this.retryAfter = retryAfter;
174
+ }
175
+ };
176
+ var createNetworkError = (message, status, details, userMessage, suggestion) => new NetworkError(message, status, details, userMessage, suggestion);
177
+ var createValidationError = (message, details, userMessage, suggestion, status) => new ValidationError(message, details, userMessage, suggestion, status);
178
+ var createApiError = (message, status, details, userMessage, suggestion, requestId) => new ApiError(message, status, details, userMessage, suggestion, requestId);
179
+ var createConfigError = (message, details, userMessage, suggestion) => new ConfigError(message, details, userMessage, suggestion);
180
+ var createTimeoutError = (message, details, userMessage, suggestion) => new TimeoutError(message, details, userMessage, suggestion);
181
+ var createUsageLimitError = (message, usage, details, userMessage, suggestion) => new UsageLimitError(message, usage, details, userMessage, suggestion);
182
+ var createAuthError = (message, details, userMessage, suggestion, requestId) => new AuthError(message, details, userMessage, suggestion, requestId);
183
+ var createPermissionError = (message, details, userMessage, suggestion, requestId) => new PermissionError(message, details, userMessage, suggestion, requestId);
184
+ var createNotFoundError = (message, details, userMessage, suggestion, requestId) => new NotFoundError(message, details, userMessage, suggestion, requestId);
185
+ var createConflictError = (message, details, userMessage, suggestion, requestId) => new ConflictError(message, details, userMessage, suggestion, requestId);
186
+ var createRateLimitError = (message, retryAfter, details, userMessage, suggestion, requestId) => new RateLimitError(
187
+ message,
188
+ retryAfter,
189
+ details,
190
+ userMessage,
191
+ suggestion,
192
+ requestId
193
+ );
194
+
195
+ // src/core/internal/utils/credentials.ts
196
+ function requirePublishableKeyForSecret(apiName, publishableKey, secretKey) {
197
+ if (secretKey && !publishableKey) {
198
+ throw createConfigError(
199
+ `publishableKey is required for ${apiName} when secretKey is used. It is sent as X-Publishable-Key for tenant routing, rate limiting, and quota enforcement.`
200
+ );
201
+ }
202
+ return publishableKey ?? "";
203
+ }
204
+
205
+ // src/core/client/types.ts
206
+ function resolveApiUrl(apiUrl) {
207
+ if (apiUrl) {
208
+ return apiUrl.replace(/\/$/, "");
209
+ }
210
+ if (typeof process !== "undefined" && process.env) {
211
+ const envUrl = process.env.SOFTWARE_API_URL || process.env.NEXT_PUBLIC_SOFTWARE_API_URL;
212
+ if (envUrl) {
213
+ return envUrl.replace(/\/$/, "");
214
+ }
215
+ }
216
+ return "https://api.01.software";
217
+ }
218
+
219
+ // src/core/internal/utils/http.ts
220
+ var DEFAULT_TIMEOUT = 3e4;
221
+ var DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504];
222
+ var NON_RETRYABLE_STATUSES = [400, 401, 403, 404, 409, 422];
223
+ var SAFE_METHODS = ["GET", "HEAD", "OPTIONS"];
224
+ function debugLog(debug, type, message, data) {
225
+ if (!debug) return;
226
+ const shouldLog = debug === true || type === "request" && debug.logRequests || type === "response" && debug.logResponses || type === "error" && debug.logErrors;
227
+ if (shouldLog) {
228
+ console.group(`[SDK ${type.toUpperCase()}] ${message}`);
229
+ if (data) console.log(data);
230
+ console.groupEnd();
231
+ }
232
+ }
233
+ function redactSensitiveHeader(value) {
234
+ const prefix = value.toLowerCase().startsWith("bearer ") ? "Bearer " : "";
235
+ return value.length > 20 ? `${prefix}...****${value.slice(-8)}` : "****";
236
+ }
237
+ function redactSensitiveHeaders(headers) {
238
+ const redacted = Object.fromEntries(headers.entries());
239
+ if (redacted.authorization) {
240
+ redacted.authorization = redactSensitiveHeader(redacted.authorization);
241
+ }
242
+ if (redacted["x-preview-token"]) {
243
+ redacted["x-preview-token"] = redactSensitiveHeader(
244
+ redacted["x-preview-token"]
245
+ );
246
+ }
247
+ return redacted;
248
+ }
249
+ function getErrorSuggestion(status) {
250
+ if (status === 400)
251
+ return "The request data failed validation. Check field values and types.";
252
+ if (status === 401) return "Please check your authentication credentials.";
253
+ if (status === 403)
254
+ return "Access denied. Check your credentials or permissions.";
255
+ if (status === 404) return "The requested resource was not found.";
256
+ if (status === 422) return "The request data failed validation.";
257
+ if (status >= 500) return "A server error occurred. Please try again later.";
258
+ return void 0;
259
+ }
260
+ function isUsageLimitExceededResponse(response) {
261
+ if (response.status !== 429) return false;
262
+ const limit = parseInt(response.headers.get("X-Usage-Limit") || "", 10);
263
+ const current = parseInt(response.headers.get("X-Usage-Current") || "", 10);
264
+ if (!Number.isFinite(limit) || !Number.isFinite(current)) return false;
265
+ return response.headers.get("X-Usage-Exceeded") === "true" || current > limit;
266
+ }
267
+ async function parseErrorBody(response) {
268
+ const fallback = {
269
+ errorMessage: `HTTP ${response.status}: ${response.statusText}`,
270
+ userMessage: `Request failed (status: ${response.status})`
271
+ };
272
+ try {
273
+ const body = await response.json();
274
+ const reason = typeof body.reason === "string" ? body.reason : typeof body.code === "string" ? body.code : void 0;
275
+ if (body.errors && Array.isArray(body.errors)) {
276
+ const fieldErrors = [];
277
+ for (const e of body.errors) {
278
+ if (e.data?.errors && Array.isArray(e.data.errors) && e.data.errors.length > 0) {
279
+ for (const fe of e.data.errors) {
280
+ fieldErrors.push({
281
+ field: fe.path || fe.field,
282
+ message: fe.message
283
+ });
284
+ }
285
+ } else if (e.field || e.message) {
286
+ fieldErrors.push({ field: e.field, message: e.message });
287
+ }
288
+ }
289
+ const details = (fieldErrors.length > 0 ? fieldErrors : body.errors).map(
290
+ (e) => e.field ? `${e.field}: ${e.message}` : e.message
291
+ ).filter(Boolean).join("; ");
292
+ if (details) {
293
+ return {
294
+ errorMessage: `HTTP ${response.status}: ${details}`,
295
+ userMessage: details,
296
+ reason,
297
+ body,
298
+ errors: fieldErrors.length > 0 ? fieldErrors : body.errors
299
+ };
300
+ }
301
+ }
302
+ if (typeof body.error === "string") {
303
+ return {
304
+ errorMessage: `HTTP ${response.status}: ${body.error}`,
305
+ userMessage: body.error,
306
+ reason,
307
+ body
308
+ };
309
+ }
310
+ if (body.message) {
311
+ return {
312
+ errorMessage: `HTTP ${response.status}: ${body.message}`,
313
+ userMessage: body.message,
314
+ reason,
315
+ body
316
+ };
317
+ }
318
+ return { ...fallback, reason, body };
319
+ } catch {
320
+ return fallback;
321
+ }
322
+ }
323
+ function getParsedErrorSuggestion(status, parsed) {
324
+ if (status === 403 && parsed.reason === "origin_not_allowed") {
325
+ return "Add the request origin to the tenant Browser API origins, then retry the browser request.";
326
+ }
327
+ return getErrorSuggestion(status);
328
+ }
329
+ async function delay(ms) {
330
+ return new Promise((resolve) => setTimeout(resolve, ms));
331
+ }
332
+ function attachRequestId(err, id) {
333
+ if (id) err.requestId = id;
334
+ return err;
335
+ }
336
+ function createHttpStatusError(status, parsed, details, requestId) {
337
+ const errorDetails = {
338
+ ...details,
339
+ ...parsed.errors && { errors: parsed.errors },
340
+ ...parsed.body && { body: parsed.body }
341
+ };
342
+ const suggestion = getParsedErrorSuggestion(status, parsed);
343
+ if (status === 400 || status === 422) {
344
+ return attachRequestId(
345
+ createValidationError(
346
+ parsed.errorMessage,
347
+ errorDetails,
348
+ parsed.userMessage,
349
+ suggestion,
350
+ status
351
+ ),
352
+ requestId
353
+ );
354
+ }
355
+ if (status === 401) {
356
+ return attachRequestId(
357
+ createAuthError(
358
+ parsed.errorMessage,
359
+ errorDetails,
360
+ parsed.userMessage,
361
+ suggestion
362
+ ),
363
+ requestId
364
+ );
365
+ }
366
+ if (status === 403) {
367
+ return attachRequestId(
368
+ createPermissionError(
369
+ parsed.errorMessage,
370
+ errorDetails,
371
+ parsed.userMessage,
372
+ suggestion
373
+ ),
374
+ requestId
375
+ );
376
+ }
377
+ if (status === 404) {
378
+ return attachRequestId(
379
+ createNotFoundError(
380
+ parsed.errorMessage,
381
+ errorDetails,
382
+ parsed.userMessage,
383
+ suggestion
384
+ ),
385
+ requestId
386
+ );
387
+ }
388
+ if (status === 409) {
389
+ return attachRequestId(
390
+ createConflictError(
391
+ parsed.errorMessage,
392
+ errorDetails,
393
+ parsed.userMessage,
394
+ suggestion
395
+ ),
396
+ requestId
397
+ );
398
+ }
399
+ return attachRequestId(
400
+ createNetworkError(
401
+ parsed.errorMessage,
402
+ status,
403
+ errorDetails,
404
+ parsed.userMessage,
405
+ suggestion
406
+ ),
407
+ requestId
408
+ );
409
+ }
410
+ async function httpFetch(url, options) {
411
+ const {
412
+ apiUrl,
413
+ publishableKey,
414
+ secretKey,
415
+ customerToken,
416
+ timeout = DEFAULT_TIMEOUT,
417
+ debug,
418
+ retry,
419
+ onUnauthorized,
420
+ ...requestInit
421
+ } = options || {};
422
+ const baseUrl = resolveApiUrl(apiUrl);
423
+ const retryConfig = {
424
+ maxRetries: retry?.maxRetries ?? 3,
425
+ retryableStatuses: retry?.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES,
426
+ retryDelay: retry?.retryDelay ?? ((attempt) => Math.min(1e3 * 2 ** attempt, 1e4))
427
+ };
428
+ let authToken;
429
+ if (secretKey) {
430
+ authToken = secretKey;
431
+ } else if (customerToken) {
432
+ authToken = customerToken;
433
+ }
434
+ let lastError;
435
+ let hasRetried401 = false;
436
+ for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {
437
+ try {
438
+ const headers = new Headers(requestInit.headers);
439
+ if (publishableKey) {
440
+ headers.set("X-Publishable-Key", publishableKey);
441
+ }
442
+ if (authToken) {
443
+ headers.set("Authorization", `Bearer ${authToken}`);
444
+ }
445
+ if (!headers.has("Content-Type") && requestInit.body && !(requestInit.body instanceof FormData)) {
446
+ headers.set("Content-Type", "application/json");
447
+ }
448
+ const redactedHeaders = redactSensitiveHeaders(headers);
449
+ debugLog(debug, "request", url, {
450
+ method: requestInit.method || "GET",
451
+ headers: redactedHeaders,
452
+ attempt: attempt + 1
453
+ });
454
+ const controller = new AbortController();
455
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
456
+ const response = await fetch(`${baseUrl}${url}`, {
457
+ ...requestInit,
458
+ headers,
459
+ signal: controller.signal
460
+ });
461
+ clearTimeout(timeoutId);
462
+ const requestId = response.headers.get("x-request-id") ?? void 0;
463
+ debugLog(debug, "response", url, {
464
+ status: response.status,
465
+ statusText: response.statusText,
466
+ headers: redactSensitiveHeaders(response.headers)
467
+ });
468
+ if (!response.ok) {
469
+ if (isUsageLimitExceededResponse(response)) {
470
+ const limit = parseInt(
471
+ response.headers.get("X-Usage-Limit") || "0",
472
+ 10
473
+ );
474
+ const current = parseInt(
475
+ response.headers.get("X-Usage-Current") || "0",
476
+ 10
477
+ );
478
+ const remaining = parseInt(
479
+ response.headers.get("X-Usage-Remaining") || "0",
480
+ 10
481
+ );
482
+ throw attachRequestId(
483
+ createUsageLimitError(
484
+ `Monthly API usage limit exceeded (${current.toLocaleString()}/${limit.toLocaleString()})`,
485
+ { limit, current, remaining },
486
+ {
487
+ url,
488
+ method: requestInit.method || "GET",
489
+ attempt: attempt + 1
490
+ },
491
+ "Monthly API call limit exceeded. Please upgrade your plan.",
492
+ "Upgrade your tenant plan to increase the monthly API call limit."
493
+ ),
494
+ requestId
495
+ );
496
+ }
497
+ const parsed = await parseErrorBody(response);
498
+ if (response.status === 401 && onUnauthorized && customerToken && !hasRetried401 && parsed.reason === "token_expired") {
499
+ hasRetried401 = true;
500
+ try {
501
+ const newToken = await onUnauthorized();
502
+ if (newToken) {
503
+ authToken = newToken;
504
+ continue;
505
+ }
506
+ } catch {
507
+ }
508
+ }
509
+ const details = {
510
+ url,
511
+ method: requestInit.method || "GET",
512
+ attempt: attempt + 1
513
+ };
514
+ if (NON_RETRYABLE_STATUSES.includes(response.status)) {
515
+ throw createHttpStatusError(
516
+ response.status,
517
+ parsed,
518
+ details,
519
+ requestId
520
+ );
521
+ }
522
+ const error = attachRequestId(
523
+ createNetworkError(
524
+ parsed.errorMessage,
525
+ response.status,
526
+ details,
527
+ parsed.userMessage,
528
+ getErrorSuggestion(response.status)
529
+ ),
530
+ requestId
531
+ );
532
+ const method = (requestInit.method || "GET").toUpperCase();
533
+ if (attempt < retryConfig.maxRetries && SAFE_METHODS.includes(method) && retryConfig.retryableStatuses.includes(response.status)) {
534
+ lastError = error;
535
+ const retryDelay = retryConfig.retryDelay(attempt);
536
+ debugLog(debug, "error", `Retrying in ${retryDelay}ms...`, error);
537
+ await delay(retryDelay);
538
+ continue;
539
+ }
540
+ throw error;
541
+ }
542
+ return response;
543
+ } catch (error) {
544
+ debugLog(debug, "error", url, error);
545
+ const method = (requestInit.method || "GET").toUpperCase();
546
+ const isSafe = SAFE_METHODS.includes(method);
547
+ if (error instanceof Error && error.name === "AbortError") {
548
+ const timeoutError = createTimeoutError(
549
+ `Request timed out after ${timeout}ms.`,
550
+ { url, timeout, attempt: attempt + 1 },
551
+ "The request timed out.",
552
+ "Please check your network connection or try again later."
553
+ );
554
+ if (isSafe && attempt < retryConfig.maxRetries) {
555
+ lastError = timeoutError;
556
+ await delay(retryConfig.retryDelay(attempt));
557
+ continue;
558
+ }
559
+ throw timeoutError;
560
+ }
561
+ if (error instanceof TypeError) {
562
+ const networkError = createNetworkError(
563
+ "Network connection failed.",
564
+ void 0,
565
+ { url, originalError: error.message, attempt: attempt + 1 },
566
+ "Network connection failed.",
567
+ "Please check your internet connection and try again."
568
+ );
569
+ if (isSafe && attempt < retryConfig.maxRetries) {
570
+ lastError = networkError;
571
+ await delay(retryConfig.retryDelay(attempt));
572
+ continue;
573
+ }
574
+ throw networkError;
575
+ }
576
+ if (error instanceof NetworkError || error instanceof TimeoutError) {
577
+ if (isSafe && attempt < retryConfig.maxRetries && error.status && !NON_RETRYABLE_STATUSES.includes(error.status) && retryConfig.retryableStatuses.includes(error.status)) {
578
+ lastError = error;
579
+ await delay(retryConfig.retryDelay(attempt));
580
+ continue;
581
+ }
582
+ throw error;
583
+ }
584
+ if (error instanceof SDKError) {
585
+ throw error;
586
+ }
587
+ const unknownError = createNetworkError(
588
+ error instanceof Error ? error.message : "An unknown network error occurred.",
589
+ void 0,
590
+ { url, originalError: error, attempt: attempt + 1 },
591
+ "An unknown error occurred.",
592
+ "Please try again later."
593
+ );
594
+ if (isSafe && attempt < retryConfig.maxRetries) {
595
+ lastError = unknownError;
596
+ await delay(retryConfig.retryDelay(attempt));
597
+ continue;
598
+ }
599
+ throw unknownError;
600
+ }
601
+ }
602
+ throw lastError ?? new NetworkError("Request failed after retries");
603
+ }
604
+
605
+ // src/core/collection/http-client.ts
606
+ var HttpClient = class {
607
+ constructor(publishableKey, secretKey, getCustomerToken, onUnauthorized, onRequestId, apiUrl) {
608
+ this.publishableKey = requirePublishableKeyForSecret(
609
+ "CollectionClient",
610
+ publishableKey,
611
+ secretKey
612
+ );
613
+ this.secretKey = secretKey;
614
+ this.getCustomerToken = getCustomerToken;
615
+ this.onUnauthorized = onUnauthorized;
616
+ this.onRequestId = onRequestId;
617
+ this.apiUrl = apiUrl;
618
+ }
619
+ get defaultOptions() {
620
+ const opts = {
621
+ apiUrl: this.apiUrl,
622
+ publishableKey: this.publishableKey,
623
+ secretKey: this.secretKey
624
+ };
625
+ const token = this.getCustomerToken?.();
626
+ if (token) {
627
+ opts.customerToken = token;
628
+ if (this.onUnauthorized) {
629
+ opts.onUnauthorized = this.onUnauthorized;
630
+ }
631
+ }
632
+ return opts;
633
+ }
634
+ async fetchWithTracking(url, opts) {
635
+ try {
636
+ const response = await httpFetch(url, opts);
637
+ this.onRequestId?.(response.headers.get("x-request-id") ?? null);
638
+ return response;
639
+ } catch (err) {
640
+ const id = err instanceof SDKError ? err.requestId ?? null : null;
641
+ this.onRequestId?.(id);
642
+ throw err;
643
+ }
644
+ }
645
+ buildUrl(endpoint, options) {
646
+ if (!options) return endpoint;
647
+ const queryString = (0, import_qs_esm.stringify)(options, { addQueryPrefix: true });
648
+ return queryString ? `${endpoint}${queryString}` : endpoint;
649
+ }
650
+ assertJsonResponse(response) {
651
+ const contentType = response.headers.get("content-type");
652
+ if (!contentType?.includes("application/json")) {
653
+ throw createApiError("Response is not in JSON format.", response.status, {
654
+ contentType
655
+ });
656
+ }
657
+ }
658
+ /**
659
+ * Parse Payload CMS find response (list query)
660
+ * Returns native Payload response structure
661
+ */
662
+ async parseFindResponse(response) {
663
+ const contentType = response.headers.get("content-type");
664
+ try {
665
+ this.assertJsonResponse(response);
666
+ const jsonData = await response.json();
667
+ if (jsonData.docs === void 0) {
668
+ throw createApiError("Invalid find response.", response.status, {
669
+ jsonData
670
+ });
671
+ }
672
+ return {
673
+ docs: jsonData.docs,
674
+ totalDocs: jsonData.totalDocs ?? 0,
675
+ limit: jsonData.limit || 20,
676
+ totalPages: jsonData.totalPages ?? 0,
677
+ page: jsonData.page || 1,
678
+ pagingCounter: jsonData.pagingCounter || 1,
679
+ hasPrevPage: jsonData.hasPrevPage ?? false,
680
+ hasNextPage: jsonData.hasNextPage ?? false,
681
+ prevPage: jsonData.prevPage ?? null,
682
+ nextPage: jsonData.nextPage ?? null
683
+ };
684
+ } catch (error) {
685
+ if (error instanceof SDKError) throw error;
686
+ throw createApiError("Failed to parse response.", response.status, {
687
+ contentType,
688
+ error: error instanceof Error ? error.message : error
689
+ });
690
+ }
691
+ }
692
+ /**
693
+ * Parse Payload CMS mutation response (create/update)
694
+ * Returns native Payload response structure
695
+ */
696
+ async parseMutationResponse(response) {
697
+ const contentType = response.headers.get("content-type");
698
+ try {
699
+ this.assertJsonResponse(response);
700
+ const jsonData = await response.json();
701
+ if (jsonData.doc === void 0) {
702
+ throw createApiError("Invalid mutation response.", response.status, {
703
+ jsonData
704
+ });
705
+ }
706
+ return {
707
+ message: jsonData.message || "",
708
+ doc: jsonData.doc,
709
+ errors: jsonData.errors
710
+ };
711
+ } catch (error) {
712
+ if (error instanceof SDKError) throw error;
713
+ throw createApiError("Failed to parse response.", response.status, {
714
+ contentType,
715
+ error: error instanceof Error ? error.message : error
716
+ });
717
+ }
718
+ }
719
+ /**
720
+ * Parse Payload CMS document response (findById/delete)
721
+ * Returns document directly without wrapper
722
+ */
723
+ async parseDocumentResponse(response) {
724
+ const contentType = response.headers.get("content-type");
725
+ try {
726
+ this.assertJsonResponse(response);
727
+ const jsonData = await response.json();
728
+ return jsonData;
729
+ } catch (error) {
730
+ if (error instanceof SDKError) throw error;
731
+ throw createApiError("Failed to parse response.", response.status, {
732
+ contentType,
733
+ error: error instanceof Error ? error.message : error
734
+ });
735
+ }
736
+ }
737
+ };
738
+
739
+ // src/utils/types.ts
740
+ var resolveRelation = (ref) => {
741
+ if (typeof ref === "string" || typeof ref === "number" || ref === null || ref === void 0)
742
+ return null;
743
+ return ref;
744
+ };
745
+
746
+ // src/core/metadata/index.ts
747
+ function extractSeo(doc) {
748
+ const seo = doc.seo ?? {};
749
+ const og = seo.openGraph ?? {};
750
+ return {
751
+ title: seo.title ?? doc.title ?? null,
752
+ description: seo.description ?? null,
753
+ noIndex: seo.noIndex ?? null,
754
+ canonical: seo.canonical ?? null,
755
+ openGraph: {
756
+ title: og.title ?? null,
757
+ description: og.description ?? null,
758
+ image: og.image ?? null
759
+ }
760
+ };
761
+ }
762
+ function generateMetadata(input, options) {
763
+ const title = input.title ?? void 0;
764
+ const description = input.description ?? void 0;
765
+ const ogTitle = input.openGraph?.title ?? title;
766
+ const ogDescription = input.openGraph?.description ?? description;
767
+ const image = resolveMetaImage(input.openGraph?.image);
768
+ return {
769
+ title,
770
+ description,
771
+ ...input.noIndex && { robots: { index: false, follow: false } },
772
+ ...input.canonical && { alternates: { canonical: input.canonical } },
773
+ openGraph: {
774
+ ...ogTitle && { title: ogTitle },
775
+ ...ogDescription && { description: ogDescription },
776
+ ...options?.siteName && { siteName: options.siteName },
777
+ ...image && { images: [image] }
778
+ },
779
+ twitter: {
780
+ card: image ? "summary_large_image" : "summary",
781
+ ...ogTitle && { title: ogTitle },
782
+ ...ogDescription && { description: ogDescription },
783
+ ...image && { images: [image.url] }
784
+ }
785
+ };
786
+ }
787
+ function resolveMetaImage(ref) {
788
+ const image = resolveRelation(ref);
789
+ if (!image) return null;
790
+ const sized = image.sizes?.["1536"];
791
+ const url = sized?.url || image.url;
792
+ if (!url) return null;
793
+ const width = sized?.url ? sized.width : image.width;
794
+ const height = sized?.url ? sized.height : image.height;
795
+ return {
796
+ url,
797
+ ...width && { width },
798
+ ...height && { height },
799
+ ...image.alt && { alt: image.alt }
800
+ };
801
+ }
802
+
803
+ // src/core/collection/query-builder.ts
804
+ var ReadOnlyCollectionQueryBuilder = class {
805
+ constructor(api, collection) {
806
+ this.api = api;
807
+ this.collection = collection;
808
+ }
809
+ async find(options) {
810
+ return this.api.requestFind(
811
+ `/api/${String(this.collection)}`,
812
+ options
813
+ );
814
+ }
815
+ async findById(id, options) {
816
+ return this.api.requestFindById(
817
+ `/api/${String(this.collection)}/${String(id)}`,
818
+ options
819
+ );
820
+ }
821
+ async count(options) {
822
+ return this.api.requestCount(
823
+ `/api/${String(this.collection)}/count`,
824
+ options
825
+ );
826
+ }
827
+ async findMetadata(options, metadataOptions) {
828
+ const { docs } = await this.find({ ...options, limit: 1, depth: 1 });
829
+ const doc = docs[0];
830
+ if (!doc) return null;
831
+ return generateMetadata(
832
+ extractSeo(doc),
833
+ metadataOptions
834
+ );
835
+ }
836
+ async findMetadataById(id, metadataOptions) {
837
+ const doc = await this.findById(id, { depth: 1 });
838
+ return generateMetadata(
839
+ extractSeo(doc),
840
+ metadataOptions
841
+ );
842
+ }
843
+ };
844
+
845
+ // src/core/collection/collection-client.ts
846
+ var ReadOnlyCollectionClient = class extends HttpClient {
847
+ from(collection) {
848
+ return new ReadOnlyCollectionQueryBuilder(this, collection);
849
+ }
850
+ async requestFind(endpoint, options) {
851
+ const url = this.buildUrl(endpoint, options);
852
+ const response = await this.fetchWithTracking(url, {
853
+ ...this.defaultOptions,
854
+ method: "GET"
855
+ });
856
+ return this.parseFindResponse(response);
857
+ }
858
+ async requestFindById(endpoint, options) {
859
+ const url = this.buildUrl(endpoint, options);
860
+ const response = await this.fetchWithTracking(url, {
861
+ ...this.defaultOptions,
862
+ method: "GET"
863
+ });
864
+ return this.parseDocumentResponse(response);
865
+ }
866
+ async requestCount(endpoint, options) {
867
+ const url = this.buildUrl(endpoint, options);
868
+ const response = await this.fetchWithTracking(url, {
869
+ ...this.defaultOptions,
870
+ method: "GET"
871
+ });
872
+ return this.parseDocumentResponse(response);
873
+ }
874
+ };
875
+
876
+ // src/core/api/parse-response.ts
877
+ async function parseApiResponse(response, endpoint) {
878
+ let data;
879
+ try {
880
+ data = await response.json();
881
+ } catch {
882
+ throw createApiError(
883
+ `Invalid JSON response from ${endpoint}`,
884
+ response.status,
885
+ void 0,
886
+ "Server returned an invalid response.",
887
+ "Check if the API endpoint is available."
888
+ );
889
+ }
890
+ if (data.error) {
891
+ const errorMessage = typeof data.error === "string" ? data.error : "Unknown API error";
892
+ const reason = typeof data.reason === "string" ? data.reason : void 0;
893
+ const requestId = response.headers.get("x-request-id") ?? void 0;
894
+ const retryAfterRaw = response.headers.get("Retry-After");
895
+ const retryAfter = retryAfterRaw ? parseInt(retryAfterRaw, 10) || void 0 : void 0;
896
+ if (reason === "validation_failed") {
897
+ throw attachRequestId(createValidationError(errorMessage, data, errorMessage), requestId);
898
+ }
899
+ if (reason === "token_expired" || reason === "token_invalid" || reason === "preview_token_invalid" || reason === "preview_token_required" || reason === "key_invalid" || reason === "key_revoked") {
900
+ throw attachRequestId(createAuthError(errorMessage, data, errorMessage), requestId);
901
+ }
902
+ if (reason === "forbidden") {
903
+ throw attachRequestId(createPermissionError(errorMessage, data, errorMessage), requestId);
904
+ }
905
+ if (reason === "rate_limit_exceeded") {
906
+ throw attachRequestId(createRateLimitError(errorMessage, retryAfter, data, errorMessage), requestId);
907
+ }
908
+ if (reason === "not_found") {
909
+ throw attachRequestId(createNotFoundError(errorMessage, data, errorMessage), requestId);
910
+ }
911
+ if (reason === "conflict") {
912
+ throw attachRequestId(createConflictError(errorMessage, data, errorMessage), requestId);
913
+ }
914
+ throw attachRequestId(
915
+ createApiError(errorMessage, response.status, data, errorMessage, "An error occurred while processing the request."),
916
+ requestId
917
+ );
918
+ }
919
+ return data;
920
+ }
921
+
922
+ // src/core/community/community-client.ts
923
+ var CommunityClient = class {
924
+ constructor(options) {
925
+ this.publishableKey = requirePublishableKeyForSecret(
926
+ "CommunityClient",
927
+ options.publishableKey,
928
+ options.secretKey
929
+ );
930
+ this.secretKey = options.secretKey;
931
+ this.apiUrl = options.apiUrl;
932
+ this.customerToken = options.customerToken;
933
+ this.onUnauthorized = options.onUnauthorized;
934
+ this.onRequestId = options.onRequestId;
935
+ }
936
+ buildQuery(params) {
937
+ if (!params) return "";
938
+ const entries = Object.entries(params).filter((e) => e[1] !== void 0).map(([k, v]) => [k, String(v)]);
939
+ return entries.length ? `?${new URLSearchParams(entries).toString()}` : "";
940
+ }
941
+ async execute(endpoint, method, body) {
942
+ const token = typeof this.customerToken === "function" ? this.customerToken() : this.customerToken;
943
+ try {
944
+ const response = await httpFetch(endpoint, {
945
+ method,
946
+ apiUrl: this.apiUrl,
947
+ publishableKey: this.publishableKey,
948
+ secretKey: this.secretKey,
949
+ customerToken: token ?? void 0,
950
+ ...token && this.onUnauthorized && { onUnauthorized: this.onUnauthorized },
951
+ ...body !== void 0 && { body: JSON.stringify(body) }
952
+ });
953
+ this.onRequestId?.(response.headers.get("x-request-id") ?? null);
954
+ return parseApiResponse(response, endpoint);
955
+ } catch (err) {
956
+ const id = err instanceof SDKError ? err.requestId ?? null : null;
957
+ this.onRequestId?.(id);
958
+ throw err;
959
+ }
960
+ }
961
+ createPost(params) {
962
+ return this.execute("/api/posts", "POST", params);
963
+ }
964
+ getMyPosts(params) {
965
+ return this.execute(
966
+ `/api/posts/my${this.buildQuery(params)}`,
967
+ "GET"
968
+ );
969
+ }
970
+ getTrending(params) {
971
+ return this.execute(
972
+ `/api/posts/trending${this.buildQuery(params)}`,
973
+ "GET"
974
+ );
975
+ }
976
+ incrementView(params) {
977
+ return this.execute(
978
+ `/api/posts/${params.postId}/view`,
979
+ "POST"
980
+ );
981
+ }
982
+ reportPost(params) {
983
+ const { postId, ...body } = params;
984
+ return this.execute(
985
+ `/api/posts/${postId}/report`,
986
+ "POST",
987
+ body
988
+ );
989
+ }
990
+ // Comments
991
+ createComment(params) {
992
+ const { postId, parentId, body: commentBody } = params;
993
+ const body = { post: postId, body: commentBody };
994
+ if (parentId !== void 0) {
995
+ body.parent = parentId;
996
+ }
997
+ return this.execute("/api/comments", "POST", body);
998
+ }
999
+ listComments(params) {
1000
+ const { postId, page, limit, rootComment } = params;
1001
+ const urlParams = new URLSearchParams();
1002
+ urlParams.set("where[post][equals]", postId);
1003
+ urlParams.set("sort", "-createdAt");
1004
+ if (limit !== void 0) urlParams.set("limit", String(limit));
1005
+ if (page !== void 0) urlParams.set("page", String(page));
1006
+ if (rootComment !== void 0) urlParams.set("where[rootComment][equals]", rootComment);
1007
+ return this.execute(
1008
+ `/api/comments?${urlParams.toString()}`,
1009
+ "GET"
1010
+ );
1011
+ }
1012
+ updateComment(params) {
1013
+ const { commentId, body } = params;
1014
+ return this.execute(
1015
+ `/api/comments/${commentId}`,
1016
+ "PATCH",
1017
+ { body }
1018
+ );
1019
+ }
1020
+ deleteComment(params) {
1021
+ return this.execute(
1022
+ `/api/comments/${params.commentId}`,
1023
+ "DELETE"
1024
+ );
1025
+ }
1026
+ reportComment(params) {
1027
+ const { commentId, ...body } = params;
1028
+ return this.execute(
1029
+ `/api/comments/${commentId}/report`,
1030
+ "POST",
1031
+ body
1032
+ );
1033
+ }
1034
+ // Reactions
1035
+ addReaction(params) {
1036
+ const { postId, type } = params;
1037
+ return this.execute("/api/reactions", "POST", {
1038
+ post: postId,
1039
+ type
1040
+ });
1041
+ }
1042
+ removeReaction(params) {
1043
+ const { postId, type } = params;
1044
+ return this.execute(
1045
+ `/api/posts/${postId}/react?type=${encodeURIComponent(type)}`,
1046
+ "DELETE"
1047
+ );
1048
+ }
1049
+ addCommentReaction(params) {
1050
+ const { commentId, type } = params;
1051
+ return this.execute("/api/reactions", "POST", {
1052
+ comment: commentId,
1053
+ type
1054
+ });
1055
+ }
1056
+ removeCommentReaction(params) {
1057
+ const { commentId, type } = params;
1058
+ return this.execute(
1059
+ `/api/comments/${commentId}/react?type=${encodeURIComponent(type)}`,
1060
+ "DELETE"
1061
+ );
1062
+ }
1063
+ getReactionSummary(params) {
1064
+ return this.execute(
1065
+ `/api/posts/${params.postId}/reactions`,
1066
+ "GET"
1067
+ );
1068
+ }
1069
+ getReactionTypes() {
1070
+ return this.execute(
1071
+ "/api/reaction-types?limit=100",
1072
+ "GET"
1073
+ );
1074
+ }
1075
+ // Bookmarks
1076
+ addBookmark(params) {
1077
+ return this.execute("/api/bookmarks", "POST", {
1078
+ post: params.postId
1079
+ });
1080
+ }
1081
+ removeBookmark(params) {
1082
+ return this.execute(
1083
+ `/api/posts/${params.postId}/bookmark`,
1084
+ "DELETE"
1085
+ );
1086
+ }
1087
+ getMyBookmarks(params) {
1088
+ return this.execute(
1089
+ `/api/bookmarks/my${this.buildQuery(params)}`,
1090
+ "GET"
1091
+ );
1092
+ }
1093
+ };
1094
+
1095
+ // src/core/customer/customer-auth.ts
1096
+ var DEFAULT_TIMEOUT2 = 15e3;
1097
+ function safeGetItem(key) {
1098
+ try {
1099
+ return localStorage.getItem(key);
1100
+ } catch {
1101
+ return null;
1102
+ }
1103
+ }
1104
+ var CustomerAuth = class {
1105
+ constructor(publishableKey, options, apiUrl) {
1106
+ this.refreshPromise = null;
1107
+ this.publishableKey = publishableKey;
1108
+ this.baseUrl = resolveApiUrl(apiUrl);
1109
+ const persist = options?.persist ?? true;
1110
+ if (persist) {
1111
+ const key = typeof persist === "string" ? persist : "customer-token";
1112
+ const isBrowser = typeof window !== "undefined";
1113
+ this.token = isBrowser ? safeGetItem(key) : null;
1114
+ this.onTokenChange = isBrowser ? (token) => {
1115
+ try {
1116
+ if (token) localStorage.setItem(key, token);
1117
+ else localStorage.removeItem(key);
1118
+ } catch {
1119
+ }
1120
+ } : void 0;
1121
+ } else {
1122
+ this.token = options?.token ?? null;
1123
+ this.onTokenChange = options?.onTokenChange;
1124
+ }
1125
+ }
1126
+ /**
1127
+ * Register a new customer account
1128
+ */
1129
+ async register(data) {
1130
+ return this.requestJson("/api/customers/register", {
1131
+ method: "POST",
1132
+ body: JSON.stringify(data)
1133
+ });
1134
+ }
1135
+ /**
1136
+ * Login with email and password. Stores the token internally.
1137
+ */
1138
+ async login(data) {
1139
+ const result = await this.requestJson(
1140
+ "/api/customers/login",
1141
+ {
1142
+ method: "POST",
1143
+ body: JSON.stringify(data)
1144
+ }
1145
+ );
1146
+ this.setToken(result.token);
1147
+ return result;
1148
+ }
1149
+ /**
1150
+ * Refresh the current token. Requires a valid (non-expired) token.
1151
+ */
1152
+ async refreshToken() {
1153
+ if (!this.token) throw new ApiError("Not authenticated", 401);
1154
+ if (this.refreshPromise) return this.refreshPromise;
1155
+ this.refreshPromise = this._doRefreshToken();
1156
+ try {
1157
+ return await this.refreshPromise;
1158
+ } finally {
1159
+ this.refreshPromise = null;
1160
+ }
1161
+ }
1162
+ async _doRefreshToken() {
1163
+ const result = await this.requestJson(
1164
+ "/api/customers/refresh",
1165
+ {
1166
+ method: "POST",
1167
+ headers: { Authorization: `Bearer ${this.token}` }
1168
+ }
1169
+ );
1170
+ this.setToken(result.token);
1171
+ return result;
1172
+ }
1173
+ /**
1174
+ * Clear the stored token
1175
+ */
1176
+ logout() {
1177
+ this.setToken(null);
1178
+ }
1179
+ /**
1180
+ * Get the current authenticated customer's profile
1181
+ */
1182
+ async me() {
1183
+ if (!this.token) return null;
1184
+ try {
1185
+ const data = await this.requestJson(
1186
+ "/api/customers/me",
1187
+ {
1188
+ method: "GET",
1189
+ headers: { Authorization: `Bearer ${this.token}` }
1190
+ }
1191
+ );
1192
+ return data.customer ?? null;
1193
+ } catch (error) {
1194
+ if (error instanceof ApiError && error.status === 401) {
1195
+ this.setToken(null);
1196
+ return null;
1197
+ }
1198
+ throw error;
1199
+ }
1200
+ }
1201
+ /**
1202
+ * Request a password reset email
1203
+ */
1204
+ async forgotPassword(email) {
1205
+ await this.requestJson("/api/customers/forgot-password", {
1206
+ method: "POST",
1207
+ body: JSON.stringify({ email })
1208
+ });
1209
+ }
1210
+ /**
1211
+ * Reset password using a token from the reset email
1212
+ */
1213
+ async resetPassword(token, password) {
1214
+ await this.requestJson("/api/customers/reset-password", {
1215
+ method: "POST",
1216
+ body: JSON.stringify({ token, password })
1217
+ });
1218
+ }
1219
+ /**
1220
+ * Update the authenticated customer's profile (name, phone, marketingConsent)
1221
+ */
1222
+ async updateProfile(data) {
1223
+ if (!this.token) throw new ApiError("Not authenticated", 401);
1224
+ const result = await this.requestJson(
1225
+ "/api/customers/me",
1226
+ {
1227
+ method: "PATCH",
1228
+ headers: { Authorization: `Bearer ${this.token}` },
1229
+ body: JSON.stringify(data)
1230
+ }
1231
+ );
1232
+ return result.customer;
1233
+ }
1234
+ /**
1235
+ * Change the password of the currently authenticated customer
1236
+ */
1237
+ async changePassword(currentPassword, newPassword) {
1238
+ if (!this.token) throw new ApiError("Not authenticated", 401);
1239
+ await this.requestJson("/api/customers/change-password", {
1240
+ method: "POST",
1241
+ headers: { Authorization: `Bearer ${this.token}` },
1242
+ body: JSON.stringify({ currentPassword, newPassword })
1243
+ });
1244
+ }
1245
+ /**
1246
+ * Get the authenticated customer's orders with pagination and optional status filter
1247
+ */
1248
+ async getMyOrders(options) {
1249
+ if (!this.token) throw new ApiError("Not authenticated", 401);
1250
+ const params = new URLSearchParams();
1251
+ if (options?.page) params.set("page", String(options.page));
1252
+ if (options?.limit) params.set("limit", String(options.limit));
1253
+ if (options?.status) params.set("status", options.status);
1254
+ const qs = params.toString();
1255
+ return this.requestJson(`/api/customers/me/orders${qs ? `?${qs}` : ""}`, {
1256
+ method: "GET",
1257
+ headers: { Authorization: `Bearer ${this.token}` }
1258
+ });
1259
+ }
1260
+ /**
1261
+ * Get the current token (or null if not authenticated)
1262
+ */
1263
+ getToken() {
1264
+ return this.token;
1265
+ }
1266
+ /**
1267
+ * Set the token manually (e.g. from SSR)
1268
+ */
1269
+ setToken(token) {
1270
+ this.token = token;
1271
+ this.onTokenChange?.(token);
1272
+ }
1273
+ /**
1274
+ * Check if the customer is currently authenticated
1275
+ */
1276
+ isAuthenticated() {
1277
+ return this.token !== null;
1278
+ }
1279
+ /**
1280
+ * Internal: make a request with timeout and error handling.
1281
+ * Auth endpoints don't retry — failures are final.
1282
+ */
1283
+ async requestJson(path, init) {
1284
+ const headers = new Headers(init.headers);
1285
+ headers.set("X-Publishable-Key", this.publishableKey);
1286
+ if (!headers.has("Content-Type") && init.body) {
1287
+ headers.set("Content-Type", "application/json");
1288
+ }
1289
+ const controller = new AbortController();
1290
+ const timeoutId = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT2);
1291
+ let res;
1292
+ try {
1293
+ res = await fetch(`${this.baseUrl}${path}`, {
1294
+ ...init,
1295
+ headers,
1296
+ signal: controller.signal
1297
+ });
1298
+ } catch (error) {
1299
+ clearTimeout(timeoutId);
1300
+ if (error instanceof Error && error.name === "AbortError") {
1301
+ throw new TimeoutError(`Request timed out after ${DEFAULT_TIMEOUT2}ms`, {
1302
+ url: path,
1303
+ timeout: DEFAULT_TIMEOUT2
1304
+ });
1305
+ }
1306
+ throw new NetworkError(
1307
+ error instanceof Error ? error.message : "Network request failed",
1308
+ void 0,
1309
+ { url: path },
1310
+ "Network connection failed.",
1311
+ "Please check your internet connection and try again."
1312
+ );
1313
+ }
1314
+ clearTimeout(timeoutId);
1315
+ if (!res.ok) {
1316
+ const body = await res.json().catch(() => ({}));
1317
+ throw new ApiError(
1318
+ body.error || `HTTP ${res.status}`,
1319
+ res.status,
1320
+ body.details,
1321
+ body.error
1322
+ );
1323
+ }
1324
+ try {
1325
+ return await res.json();
1326
+ } catch {
1327
+ throw new ApiError(
1328
+ "Invalid JSON response from server",
1329
+ res.status,
1330
+ void 0,
1331
+ "INVALID_RESPONSE"
1332
+ );
1333
+ }
1334
+ }
1335
+ };
1336
+
1337
+ // src/core/customer/customer-namespace.ts
1338
+ var CustomerNamespace = class {
1339
+ constructor(publishableKey, options, apiUrl) {
1340
+ this.auth = new CustomerAuth(publishableKey, options, apiUrl);
1341
+ }
1342
+ };
1343
+
1344
+ // src/core/api/cart-api.ts
1345
+ var CartApi = class {
1346
+ constructor(options) {
1347
+ if (!options.secretKey && !options.customerToken) {
1348
+ throw createConfigError(
1349
+ "Either secretKey or customerToken is required for CartApi."
1350
+ );
1351
+ }
1352
+ this.publishableKey = requirePublishableKeyForSecret(
1353
+ "CartApi",
1354
+ options.publishableKey,
1355
+ options.secretKey
1356
+ );
1357
+ this.secretKey = options.secretKey;
1358
+ this.apiUrl = options.apiUrl;
1359
+ this.customerToken = options.customerToken;
1360
+ this.onUnauthorized = options.onUnauthorized;
1361
+ this.onRequestId = options.onRequestId;
1362
+ }
1363
+ async execute(endpoint, method, body) {
1364
+ const token = typeof this.customerToken === "function" ? this.customerToken() : this.customerToken;
1365
+ try {
1366
+ const response = await httpFetch(endpoint, {
1367
+ method,
1368
+ apiUrl: this.apiUrl,
1369
+ publishableKey: this.publishableKey,
1370
+ secretKey: this.secretKey,
1371
+ customerToken: token ?? void 0,
1372
+ ...token && this.onUnauthorized && { onUnauthorized: this.onUnauthorized },
1373
+ ...body !== void 0 && { body: JSON.stringify(body) }
1374
+ });
1375
+ this.onRequestId?.(response.headers.get("x-request-id") ?? null);
1376
+ return parseApiResponse(response, endpoint);
1377
+ } catch (err) {
1378
+ const id = err instanceof SDKError ? err.requestId ?? null : null;
1379
+ this.onRequestId?.(id);
1380
+ throw err;
1381
+ }
1382
+ }
1383
+ getCart(cartId) {
1384
+ return this.execute(`/api/carts/${cartId}`, "GET");
1385
+ }
1386
+ addItem(params) {
1387
+ return this.execute("/api/carts/add-item", "POST", params);
1388
+ }
1389
+ updateItem(params) {
1390
+ return this.execute("/api/carts/update-item", "POST", params);
1391
+ }
1392
+ removeItem(params) {
1393
+ return this.execute(
1394
+ "/api/carts/remove-item",
1395
+ "POST",
1396
+ params
1397
+ );
1398
+ }
1399
+ applyDiscount(params) {
1400
+ return this.execute("/api/carts/apply-discount", "POST", params);
1401
+ }
1402
+ removeDiscount(params) {
1403
+ return this.execute("/api/carts/remove-discount", "POST", params);
1404
+ }
1405
+ clearCart(params) {
1406
+ return this.execute(
1407
+ "/api/carts/clear",
1408
+ "POST",
1409
+ params
1410
+ );
1411
+ }
1412
+ };
1413
+
1414
+ // src/core/commerce/commerce-client.ts
1415
+ var CommerceClient = class {
1416
+ constructor(options) {
1417
+ const cartApi = new CartApi({
1418
+ publishableKey: options.publishableKey,
1419
+ apiUrl: options.apiUrl,
1420
+ customerToken: options.customerToken,
1421
+ onUnauthorized: options.onUnauthorized,
1422
+ onRequestId: options.onRequestId
1423
+ });
1424
+ const execute = async (endpoint, body) => {
1425
+ const token = options.customerToken();
1426
+ try {
1427
+ const response = await httpFetch(endpoint, {
1428
+ method: "POST",
1429
+ apiUrl: options.apiUrl,
1430
+ publishableKey: options.publishableKey,
1431
+ customerToken: token ?? void 0,
1432
+ ...token && options.onUnauthorized && { onUnauthorized: options.onUnauthorized },
1433
+ body: JSON.stringify(body)
1434
+ });
1435
+ options.onRequestId?.(response.headers.get("x-request-id") ?? null);
1436
+ return parseApiResponse(response, endpoint);
1437
+ } catch (err) {
1438
+ const id = err instanceof SDKError ? err.requestId ?? null : null;
1439
+ options.onRequestId?.(id);
1440
+ throw err;
1441
+ }
1442
+ };
1443
+ this.product = {
1444
+ stockCheck: (params) => execute("/api/products/stock-check", params),
1445
+ listingGroups: (params) => execute("/api/products/listing-groups", params),
1446
+ detail: async (params) => {
1447
+ try {
1448
+ return await execute("/api/products/detail", params);
1449
+ } catch (err) {
1450
+ if (err instanceof NotFoundError) return null;
1451
+ throw err;
1452
+ }
1453
+ }
1454
+ };
1455
+ this.cart = {
1456
+ get: cartApi.getCart.bind(cartApi),
1457
+ addItem: cartApi.addItem.bind(cartApi),
1458
+ updateItem: cartApi.updateItem.bind(cartApi),
1459
+ removeItem: cartApi.removeItem.bind(cartApi),
1460
+ applyDiscount: cartApi.applyDiscount.bind(cartApi),
1461
+ removeDiscount: cartApi.removeDiscount.bind(cartApi),
1462
+ clear: cartApi.clearCart.bind(cartApi)
1463
+ };
1464
+ this.orders = {
1465
+ checkout: (params) => execute("/api/orders/checkout", params),
1466
+ listMine: (params) => options.customerAuth.getMyOrders(params)
1467
+ };
1468
+ this.discounts = {
1469
+ validate: (params) => execute("/api/discounts/validate", params)
1470
+ };
1471
+ this.shipping = {
1472
+ calculate: (params) => execute("/api/shipping-policies/calculate", params)
1473
+ };
1474
+ }
1475
+ };
1476
+
1477
+ // src/core/client/client.ts
1478
+ var Client = class {
1479
+ constructor(options) {
1480
+ this.lastRequestId = null;
1481
+ const publishableKey = options.publishableKey;
1482
+ if (!publishableKey) {
1483
+ throw createConfigError("publishableKey is required.");
1484
+ }
1485
+ this.config = { ...options, publishableKey };
1486
+ const metadata = {
1487
+ timestamp: Date.now(),
1488
+ userAgent: typeof window !== "undefined" ? window.navigator?.userAgent : "Node.js"
1489
+ };
1490
+ this.state = { metadata };
1491
+ this.customer = new CustomerNamespace(
1492
+ this.config.publishableKey,
1493
+ options.customer,
1494
+ this.config.apiUrl
1495
+ );
1496
+ const onUnauthorized = async () => {
1497
+ try {
1498
+ const result = await this.customer.auth.refreshToken();
1499
+ return result.token ?? null;
1500
+ } catch {
1501
+ return null;
1502
+ }
1503
+ };
1504
+ const onRequestId = (id) => {
1505
+ this.lastRequestId = id;
1506
+ };
1507
+ this.commerce = new CommerceClient({
1508
+ publishableKey: this.config.publishableKey,
1509
+ apiUrl: this.config.apiUrl,
1510
+ customerToken: () => this.customer.auth.getToken(),
1511
+ onUnauthorized,
1512
+ onRequestId,
1513
+ customerAuth: this.customer.auth
1514
+ });
1515
+ this.community = new CommunityClient({
1516
+ publishableKey: this.config.publishableKey,
1517
+ apiUrl: this.config.apiUrl,
1518
+ customerToken: () => this.customer.auth.getToken(),
1519
+ onUnauthorized,
1520
+ onRequestId
1521
+ });
1522
+ this.collections = new ReadOnlyCollectionClient(
1523
+ this.config.publishableKey,
1524
+ void 0,
1525
+ () => this.customer.auth.getToken(),
1526
+ onUnauthorized,
1527
+ onRequestId,
1528
+ this.config.apiUrl
1529
+ );
1530
+ }
1531
+ getState() {
1532
+ return { ...this.state };
1533
+ }
1534
+ getConfig() {
1535
+ return { ...this.config };
1536
+ }
1537
+ };
1538
+ function createClient(options) {
1539
+ return new Client(options);
1540
+ }
1541
+ //# sourceMappingURL=client.cjs.map