@01.software/sdk 0.29.0 → 0.30.1

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