@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
package/dist/query.cjs ADDED
@@ -0,0 +1,1841 @@
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/query.ts
21
+ var query_exports = {};
22
+ __export(query_exports, {
23
+ CollectionHooks: () => CollectionHooks,
24
+ CustomerHooks: () => CustomerHooks,
25
+ QueryHooks: () => QueryHooks,
26
+ RealtimeConnection: () => RealtimeConnection,
27
+ collectionKeys: () => collectionKeys,
28
+ createQueryHooks: () => createQueryHooks,
29
+ createServerQueryHooks: () => createServerQueryHooks,
30
+ customerKeys: () => customerKeys,
31
+ getQueryClient: () => getQueryClient,
32
+ productKeys: () => productKeys
33
+ });
34
+ module.exports = __toCommonJS(query_exports);
35
+
36
+ // src/core/query/get-query-client.ts
37
+ var import_react_query = require("@tanstack/react-query");
38
+ function makeQueryClient() {
39
+ return new import_react_query.QueryClient({
40
+ defaultOptions: {
41
+ queries: {
42
+ // Infinite staleTime: server-fetched data persists until explicitly invalidated.
43
+ // For browser clients needing fresher data, override per-query:
44
+ // useQuery({ ..., staleTime: 5 * 60 * 1000 })
45
+ staleTime: Number.POSITIVE_INFINITY,
46
+ refetchOnWindowFocus: false
47
+ },
48
+ dehydrate: {
49
+ shouldDehydrateQuery: (query) => (0, import_react_query.defaultShouldDehydrateQuery)(query) || query.state.status === "pending",
50
+ shouldRedactErrors: () => false
51
+ }
52
+ }
53
+ });
54
+ }
55
+ var browserQueryClient;
56
+ function getQueryClient() {
57
+ if (import_react_query.isServer) {
58
+ return makeQueryClient();
59
+ }
60
+ if (!browserQueryClient) {
61
+ browserQueryClient = makeQueryClient();
62
+ }
63
+ return browserQueryClient;
64
+ }
65
+
66
+ // src/core/query/query-keys.ts
67
+ function collectionKeys(collection) {
68
+ return {
69
+ all: [collection],
70
+ lists: () => [collection, "list"],
71
+ list: (options) => [collection, "list", options],
72
+ details: () => [collection, "detail"],
73
+ detail: (id, options) => [collection, "detail", id, options],
74
+ infinites: () => [collection, "infinite"],
75
+ infinite: (options) => [collection, "infinite", options]
76
+ };
77
+ }
78
+ var customerKeys = {
79
+ all: ["customer"],
80
+ me: () => ["customer", "me"]
81
+ };
82
+ var productKeys = {
83
+ listingGroups: (options) => ["products", "listing-groups", "list", options],
84
+ listingGroupsInfinite: (options) => ["products", "listing-groups", "infinite", options],
85
+ detail: (params) => ["products", "detail", params],
86
+ detailAll: () => ["products", "detail"]
87
+ };
88
+
89
+ // src/core/query/collection-hooks.ts
90
+ var import_react_query2 = require("@tanstack/react-query");
91
+ var PRODUCT_DETAIL_INVALIDATING_COLLECTIONS = /* @__PURE__ */ new Set([
92
+ "products",
93
+ "product-variants",
94
+ "product-options",
95
+ "product-option-values",
96
+ "product-categories",
97
+ "product-tags",
98
+ "product-collections",
99
+ "brands",
100
+ "brand-logos",
101
+ "images"
102
+ ]);
103
+ var DEFAULT_PAGE_SIZE = 20;
104
+ var CollectionHooks = class {
105
+ constructor(queryClient, collectionClient) {
106
+ this.queryClient = queryClient;
107
+ this.collectionClient = collectionClient;
108
+ }
109
+ // ===== useQuery =====
110
+ useQuery(params, options) {
111
+ const { collection, options: queryOptions } = params;
112
+ const { placeholderData, ...restOptions } = options ?? {};
113
+ return (0, import_react_query2.useQuery)({
114
+ queryKey: collectionKeys(collection).list(queryOptions),
115
+ queryFn: async () => {
116
+ return await this.collectionClient.from(collection).find(queryOptions);
117
+ },
118
+ ...restOptions,
119
+ // NonFunctionGuard<T> incompatible with generic union types — safe cast
120
+ ...placeholderData !== void 0 && {
121
+ placeholderData
122
+ }
123
+ });
124
+ }
125
+ // ===== useSuspenseQuery =====
126
+ useSuspenseQuery(params, options) {
127
+ const { collection, options: queryOptions } = params;
128
+ return (0, import_react_query2.useSuspenseQuery)({
129
+ queryKey: collectionKeys(collection).list(queryOptions),
130
+ queryFn: async () => {
131
+ return await this.collectionClient.from(collection).find(queryOptions);
132
+ },
133
+ ...options
134
+ });
135
+ }
136
+ // ===== useQueryById =====
137
+ useQueryById(params, options) {
138
+ const { collection, id, options: queryOptions } = params;
139
+ const { placeholderData, ...restOptions } = options ?? {};
140
+ return (0, import_react_query2.useQuery)({
141
+ queryKey: collectionKeys(collection).detail(id, queryOptions),
142
+ queryFn: async () => {
143
+ return await this.collectionClient.from(collection).findById(id, queryOptions);
144
+ },
145
+ ...restOptions,
146
+ // NonFunctionGuard<T> incompatible with generic union types — safe cast
147
+ ...placeholderData !== void 0 && {
148
+ placeholderData
149
+ }
150
+ });
151
+ }
152
+ // ===== useSuspenseQueryById =====
153
+ useSuspenseQueryById(params, options) {
154
+ const { collection, id, options: queryOptions } = params;
155
+ return (0, import_react_query2.useSuspenseQuery)({
156
+ queryKey: collectionKeys(collection).detail(id, queryOptions),
157
+ queryFn: async () => {
158
+ return await this.collectionClient.from(collection).findById(id, queryOptions);
159
+ },
160
+ ...options
161
+ });
162
+ }
163
+ // ===== useInfiniteQuery =====
164
+ useInfiniteQuery(params, options) {
165
+ const {
166
+ collection,
167
+ options: queryOptions,
168
+ pageSize = DEFAULT_PAGE_SIZE
169
+ } = params;
170
+ return (0, import_react_query2.useInfiniteQuery)({
171
+ queryKey: collectionKeys(collection).infinite(queryOptions),
172
+ queryFn: async ({ pageParam }) => {
173
+ const response = await this.collectionClient.from(collection).find({ ...queryOptions, page: pageParam, limit: pageSize });
174
+ return response;
175
+ },
176
+ initialPageParam: 1,
177
+ getNextPageParam: (lastPage) => {
178
+ return lastPage.hasNextPage ? lastPage.nextPage : void 0;
179
+ },
180
+ ...options
181
+ });
182
+ }
183
+ // ===== useSuspenseInfiniteQuery =====
184
+ useSuspenseInfiniteQuery(params, options) {
185
+ const {
186
+ collection,
187
+ options: queryOptions,
188
+ pageSize = DEFAULT_PAGE_SIZE
189
+ } = params;
190
+ return (0, import_react_query2.useSuspenseInfiniteQuery)({
191
+ queryKey: collectionKeys(collection).infinite(queryOptions),
192
+ queryFn: async ({ pageParam }) => {
193
+ const response = await this.collectionClient.from(collection).find({ ...queryOptions, page: pageParam, limit: pageSize });
194
+ return response;
195
+ },
196
+ initialPageParam: 1,
197
+ getNextPageParam: (lastPage) => {
198
+ return lastPage.hasNextPage ? lastPage.nextPage : void 0;
199
+ },
200
+ ...options
201
+ });
202
+ }
203
+ // ===== prefetchQuery =====
204
+ async prefetchQuery(params, options) {
205
+ const { collection, options: queryOptions } = params;
206
+ return this.queryClient.prefetchQuery({
207
+ queryKey: collectionKeys(collection).list(queryOptions),
208
+ queryFn: async () => {
209
+ return await this.collectionClient.from(collection).find(queryOptions);
210
+ },
211
+ ...options
212
+ });
213
+ }
214
+ // ===== prefetchQueryById =====
215
+ async prefetchQueryById(params, options) {
216
+ const { collection, id, options: queryOptions } = params;
217
+ return this.queryClient.prefetchQuery({
218
+ queryKey: collectionKeys(collection).detail(id, queryOptions),
219
+ queryFn: async () => {
220
+ return await this.collectionClient.from(collection).findById(id, queryOptions);
221
+ },
222
+ ...options
223
+ });
224
+ }
225
+ // ===== prefetchInfiniteQuery =====
226
+ async prefetchInfiniteQuery(params, options) {
227
+ const {
228
+ collection,
229
+ options: queryOptions,
230
+ pageSize = DEFAULT_PAGE_SIZE
231
+ } = params;
232
+ return this.queryClient.prefetchInfiniteQuery({
233
+ queryKey: collectionKeys(collection).infinite(queryOptions),
234
+ queryFn: async ({ pageParam }) => {
235
+ const response = await this.collectionClient.from(collection).find({ ...queryOptions, page: pageParam, limit: pageSize });
236
+ return response;
237
+ },
238
+ initialPageParam: 1,
239
+ getNextPageParam: (lastPage) => {
240
+ return lastPage.hasNextPage ? lastPage.nextPage : void 0;
241
+ },
242
+ pages: options?.pages ?? 1,
243
+ staleTime: options?.staleTime
244
+ });
245
+ }
246
+ // ===== Mutation Hooks =====
247
+ useCreate(params, options) {
248
+ const { collection } = params;
249
+ return (0, import_react_query2.useMutation)({
250
+ mutationFn: async (variables) => {
251
+ return await this.collectionClient.from(collection).create(
252
+ variables.data,
253
+ variables.file ? { file: variables.file, filename: variables.filename } : void 0
254
+ );
255
+ },
256
+ onSuccess: (data) => {
257
+ this.queryClient.invalidateQueries({
258
+ queryKey: collectionKeys(collection).all
259
+ });
260
+ if (PRODUCT_DETAIL_INVALIDATING_COLLECTIONS.has(collection)) {
261
+ this.queryClient.invalidateQueries({ queryKey: ["products", "detail"] });
262
+ }
263
+ options?.onSuccess?.(data);
264
+ },
265
+ onError: options?.onError,
266
+ onSettled: options?.onSettled
267
+ });
268
+ }
269
+ useUpdate(params, options) {
270
+ const { collection } = params;
271
+ return (0, import_react_query2.useMutation)({
272
+ mutationFn: async (variables) => {
273
+ return await this.collectionClient.from(collection).update(
274
+ variables.id,
275
+ variables.data,
276
+ variables.file ? { file: variables.file, filename: variables.filename } : void 0
277
+ );
278
+ },
279
+ onSuccess: (data) => {
280
+ this.queryClient.invalidateQueries({
281
+ queryKey: collectionKeys(collection).all
282
+ });
283
+ if (PRODUCT_DETAIL_INVALIDATING_COLLECTIONS.has(collection)) {
284
+ this.queryClient.invalidateQueries({ queryKey: ["products", "detail"] });
285
+ }
286
+ options?.onSuccess?.(data);
287
+ },
288
+ onError: options?.onError,
289
+ onSettled: options?.onSettled
290
+ });
291
+ }
292
+ useRemove(params, options) {
293
+ const { collection } = params;
294
+ return (0, import_react_query2.useMutation)({
295
+ mutationFn: async (id) => {
296
+ return await this.collectionClient.from(collection).remove(id);
297
+ },
298
+ onSuccess: (data) => {
299
+ this.queryClient.invalidateQueries({
300
+ queryKey: collectionKeys(collection).all
301
+ });
302
+ if (PRODUCT_DETAIL_INVALIDATING_COLLECTIONS.has(collection)) {
303
+ this.queryClient.invalidateQueries({ queryKey: ["products", "detail"] });
304
+ }
305
+ options?.onSuccess?.(data);
306
+ },
307
+ onError: options?.onError,
308
+ onSettled: options?.onSettled
309
+ });
310
+ }
311
+ // ===== Cache Utilities =====
312
+ invalidateQueries(collection, type) {
313
+ const queryKey = type ? [collection, type] : [collection];
314
+ return this.queryClient.invalidateQueries({ queryKey });
315
+ }
316
+ getQueryData(collection, type, idOrOptions, options) {
317
+ if (type === "list") {
318
+ return this.queryClient.getQueryData(
319
+ collectionKeys(collection).list(idOrOptions)
320
+ );
321
+ }
322
+ return this.queryClient.getQueryData(
323
+ collectionKeys(collection).detail(idOrOptions, options)
324
+ );
325
+ }
326
+ setQueryData(collection, type, dataOrId, dataOrOptions, options) {
327
+ if (type === "list") {
328
+ this.queryClient.setQueryData(
329
+ collectionKeys(collection).list(dataOrOptions),
330
+ dataOrId
331
+ );
332
+ } else {
333
+ this.queryClient.setQueryData(
334
+ collectionKeys(collection).detail(dataOrId, options),
335
+ dataOrOptions
336
+ );
337
+ }
338
+ }
339
+ };
340
+
341
+ // src/core/query/customer-hooks.ts
342
+ var import_react_query3 = require("@tanstack/react-query");
343
+
344
+ // src/core/internal/errors/index.ts
345
+ var SDKError = class extends Error {
346
+ constructor(code, message, status, details, userMessage, suggestion, requestId) {
347
+ super(message);
348
+ this.name = "SDKError";
349
+ this.code = code;
350
+ this.status = status;
351
+ this.details = details;
352
+ this.userMessage = userMessage;
353
+ this.suggestion = suggestion;
354
+ this.requestId = requestId;
355
+ if (Error.captureStackTrace) {
356
+ Error.captureStackTrace(this, new.target);
357
+ }
358
+ }
359
+ getUserMessage() {
360
+ return this.userMessage || this.message;
361
+ }
362
+ toJSON() {
363
+ return {
364
+ name: this.name,
365
+ code: this.code,
366
+ message: this.message,
367
+ status: this.status,
368
+ details: this.details,
369
+ userMessage: this.userMessage,
370
+ suggestion: this.suggestion,
371
+ ...this.requestId !== void 0 && { requestId: this.requestId }
372
+ };
373
+ }
374
+ };
375
+ var NetworkError = class extends SDKError {
376
+ constructor(message, status, details, userMessage, suggestion) {
377
+ super("NETWORK_ERROR", message, status, details, userMessage, suggestion);
378
+ this.name = "NetworkError";
379
+ }
380
+ };
381
+ var ValidationError = class extends SDKError {
382
+ constructor(message, details, userMessage, suggestion, status = 400) {
383
+ super("VALIDATION_ERROR", message, status, details, userMessage, suggestion);
384
+ this.name = "ValidationError";
385
+ }
386
+ };
387
+ var ApiError = class extends SDKError {
388
+ constructor(message, status, details, userMessage, suggestion, requestId) {
389
+ super(
390
+ "API_ERROR",
391
+ message,
392
+ status,
393
+ details,
394
+ userMessage,
395
+ suggestion,
396
+ requestId
397
+ );
398
+ this.name = "ApiError";
399
+ }
400
+ };
401
+ var ConfigError = class extends SDKError {
402
+ constructor(message, details, userMessage, suggestion) {
403
+ super("CONFIG_ERROR", message, void 0, details, userMessage, suggestion);
404
+ this.name = "ConfigError";
405
+ }
406
+ };
407
+ var TimeoutError = class extends SDKError {
408
+ constructor(message = "Request timed out.", details, userMessage, suggestion) {
409
+ super("TIMEOUT_ERROR", message, 408, details, userMessage, suggestion);
410
+ this.name = "TimeoutError";
411
+ }
412
+ };
413
+ var UsageLimitError = class extends SDKError {
414
+ constructor(message, usage, details, userMessage, suggestion) {
415
+ super("USAGE_LIMIT_ERROR", message, 429, details, userMessage, suggestion);
416
+ this.name = "UsageLimitError";
417
+ this.usage = usage;
418
+ }
419
+ toJSON() {
420
+ return {
421
+ ...super.toJSON(),
422
+ usage: this.usage
423
+ };
424
+ }
425
+ };
426
+ var AuthError = class extends SDKError {
427
+ constructor(message, details, userMessage, suggestion, requestId) {
428
+ super(
429
+ "auth_error",
430
+ message,
431
+ 401,
432
+ details,
433
+ userMessage,
434
+ suggestion,
435
+ requestId
436
+ );
437
+ this.name = "AuthError";
438
+ }
439
+ };
440
+ var PermissionError = class extends SDKError {
441
+ constructor(message, details, userMessage, suggestion, requestId) {
442
+ super(
443
+ "permission_error",
444
+ message,
445
+ 403,
446
+ details,
447
+ userMessage,
448
+ suggestion,
449
+ requestId
450
+ );
451
+ this.name = "PermissionError";
452
+ }
453
+ };
454
+ var NotFoundError = class extends SDKError {
455
+ constructor(message, details, userMessage, suggestion, requestId) {
456
+ super(
457
+ "not_found",
458
+ message,
459
+ 404,
460
+ details,
461
+ userMessage,
462
+ suggestion,
463
+ requestId
464
+ );
465
+ this.name = "NotFoundError";
466
+ }
467
+ };
468
+ var ConflictError = class extends SDKError {
469
+ constructor(message, details, userMessage, suggestion, requestId) {
470
+ super("conflict", message, 409, details, userMessage, suggestion, requestId);
471
+ this.name = "ConflictError";
472
+ }
473
+ };
474
+ var createNetworkError = (message, status, details, userMessage, suggestion) => new NetworkError(message, status, details, userMessage, suggestion);
475
+ var createValidationError = (message, details, userMessage, suggestion, status) => new ValidationError(message, details, userMessage, suggestion, status);
476
+ var createApiError = (message, status, details, userMessage, suggestion, requestId) => new ApiError(message, status, details, userMessage, suggestion, requestId);
477
+ var createConfigError = (message, details, userMessage, suggestion) => new ConfigError(message, details, userMessage, suggestion);
478
+ var createTimeoutError = (message, details, userMessage, suggestion) => new TimeoutError(message, details, userMessage, suggestion);
479
+ var createUsageLimitError = (message, usage, details, userMessage, suggestion) => new UsageLimitError(message, usage, details, userMessage, suggestion);
480
+ var createAuthError = (message, details, userMessage, suggestion, requestId) => new AuthError(message, details, userMessage, suggestion, requestId);
481
+ var createPermissionError = (message, details, userMessage, suggestion, requestId) => new PermissionError(message, details, userMessage, suggestion, requestId);
482
+ var createNotFoundError = (message, details, userMessage, suggestion, requestId) => new NotFoundError(message, details, userMessage, suggestion, requestId);
483
+ var createConflictError = (message, details, userMessage, suggestion, requestId) => new ConflictError(message, details, userMessage, suggestion, requestId);
484
+
485
+ // src/core/query/customer-hooks.ts
486
+ function createMutation(mutationFn, callbacks, onSuccessExtra) {
487
+ return (0, import_react_query3.useMutation)({
488
+ mutationFn,
489
+ onSuccess: (data) => {
490
+ onSuccessExtra?.(data);
491
+ callbacks?.onSuccess?.(data);
492
+ },
493
+ onError: callbacks?.onError,
494
+ onSettled: callbacks?.onSettled
495
+ });
496
+ }
497
+ var CustomerHooks = class {
498
+ constructor(queryClient, customerAuth) {
499
+ this.invalidateMe = () => {
500
+ this.queryClient.invalidateQueries({ queryKey: customerKeys.me() });
501
+ };
502
+ this.queryClient = queryClient;
503
+ this.customerAuth = customerAuth;
504
+ }
505
+ ensureCustomerAuth() {
506
+ if (!this.customerAuth) {
507
+ throw createConfigError(
508
+ "Customer hooks require Client. Use createClient() instead of createServerClient()."
509
+ );
510
+ }
511
+ return this.customerAuth;
512
+ }
513
+ // ===== useCustomerMe =====
514
+ useCustomerMe(options) {
515
+ return (0, import_react_query3.useQuery)({
516
+ queryKey: customerKeys.me(),
517
+ queryFn: async () => {
518
+ return await this.ensureCustomerAuth().me();
519
+ },
520
+ ...options,
521
+ enabled: (options?.enabled ?? true) && !!this.customerAuth?.isAuthenticated()
522
+ });
523
+ }
524
+ // ===== Mutations =====
525
+ useCustomerLogin(options) {
526
+ return createMutation(
527
+ (data) => this.ensureCustomerAuth().login(data),
528
+ options,
529
+ this.invalidateMe
530
+ );
531
+ }
532
+ useCustomerRegister(options) {
533
+ return createMutation(
534
+ (data) => this.ensureCustomerAuth().register(data),
535
+ options
536
+ );
537
+ }
538
+ useCustomerLogout(options) {
539
+ return (0, import_react_query3.useMutation)({
540
+ mutationFn: async () => {
541
+ this.ensureCustomerAuth().logout();
542
+ },
543
+ onSuccess: () => {
544
+ this.queryClient.removeQueries({ queryKey: customerKeys.all });
545
+ options?.onSuccess?.();
546
+ },
547
+ onError: options?.onError,
548
+ onSettled: options?.onSettled
549
+ });
550
+ }
551
+ useCustomerForgotPassword(options) {
552
+ return createMutation(
553
+ (email) => this.ensureCustomerAuth().forgotPassword(email).then(() => {
554
+ }),
555
+ options
556
+ );
557
+ }
558
+ useCustomerResetPassword(options) {
559
+ return createMutation(
560
+ (data) => this.ensureCustomerAuth().resetPassword(data.token, data.password).then(() => {
561
+ }),
562
+ options
563
+ );
564
+ }
565
+ useCustomerRefreshToken(options) {
566
+ return createMutation(
567
+ () => this.ensureCustomerAuth().refreshToken(),
568
+ options,
569
+ this.invalidateMe
570
+ );
571
+ }
572
+ useCustomerUpdateProfile(options) {
573
+ return createMutation(
574
+ (data) => this.ensureCustomerAuth().updateProfile(data),
575
+ options,
576
+ this.invalidateMe
577
+ );
578
+ }
579
+ useCustomerChangePassword(options) {
580
+ return createMutation(
581
+ (data) => this.ensureCustomerAuth().changePassword(data.currentPassword, data.newPassword).then(() => {
582
+ }),
583
+ options
584
+ );
585
+ }
586
+ // ===== Customer Cache Utilities =====
587
+ invalidateCustomerQueries() {
588
+ return this.queryClient.invalidateQueries({ queryKey: customerKeys.all });
589
+ }
590
+ getCustomerData() {
591
+ return this.queryClient.getQueryData(customerKeys.me());
592
+ }
593
+ setCustomerData(data) {
594
+ this.queryClient.setQueryData(customerKeys.me(), data);
595
+ }
596
+ };
597
+
598
+ // src/core/query/query-hooks.ts
599
+ var import_react_query4 = require("@tanstack/react-query");
600
+ var QueryHooks = class extends CollectionHooks {
601
+ constructor(queryClient, collectionClient, customerAuth, commerceClient) {
602
+ super(queryClient, collectionClient);
603
+ // --- Customer hooks delegation ---
604
+ this.useCustomerMe = (...args) => this._customer.useCustomerMe(...args);
605
+ this.useCustomerLogin = (...args) => this._customer.useCustomerLogin(...args);
606
+ this.useCustomerRegister = (...args) => this._customer.useCustomerRegister(...args);
607
+ this.useCustomerLogout = (...args) => this._customer.useCustomerLogout(...args);
608
+ this.useCustomerForgotPassword = (...args) => this._customer.useCustomerForgotPassword(...args);
609
+ this.useCustomerResetPassword = (...args) => this._customer.useCustomerResetPassword(...args);
610
+ this.useCustomerRefreshToken = (...args) => this._customer.useCustomerRefreshToken(...args);
611
+ this.useCustomerUpdateProfile = (...args) => this._customer.useCustomerUpdateProfile(...args);
612
+ this.useCustomerChangePassword = (...args) => this._customer.useCustomerChangePassword(...args);
613
+ // --- Customer cache delegation ---
614
+ this.invalidateCustomerQueries = () => this._customer.invalidateCustomerQueries();
615
+ this.getCustomerData = () => this._customer.getCustomerData();
616
+ this.setCustomerData = (data) => this._customer.setCustomerData(data);
617
+ this._customer = new CustomerHooks(queryClient, customerAuth);
618
+ this._commerce = commerceClient;
619
+ }
620
+ useProductListingGroupsQuery(params, options) {
621
+ const queryOptions = params.options;
622
+ const { placeholderData, ...restOptions } = options ?? {};
623
+ return (0, import_react_query4.useQuery)({
624
+ queryKey: productKeys.listingGroups(queryOptions),
625
+ queryFn: async () => this.collectionClient.requestFindEndpoint(
626
+ "/api/products/listing-groups/query",
627
+ { options: queryOptions }
628
+ ),
629
+ ...restOptions,
630
+ ...placeholderData !== void 0 && {
631
+ placeholderData
632
+ }
633
+ });
634
+ }
635
+ useSuspenseProductListingGroupsQuery(params, options) {
636
+ const queryOptions = params.options;
637
+ return (0, import_react_query4.useSuspenseQuery)({
638
+ queryKey: productKeys.listingGroups(queryOptions),
639
+ queryFn: async () => this.collectionClient.requestFindEndpoint(
640
+ "/api/products/listing-groups/query",
641
+ { options: queryOptions }
642
+ ),
643
+ ...options
644
+ });
645
+ }
646
+ useInfiniteProductListingGroupsQuery(params, options) {
647
+ const {
648
+ options: queryOptions,
649
+ pageSize = 20
650
+ } = params;
651
+ return (0, import_react_query4.useInfiniteQuery)({
652
+ queryKey: productKeys.listingGroupsInfinite(queryOptions),
653
+ queryFn: async ({ pageParam }) => this.collectionClient.requestFindEndpoint(
654
+ "/api/products/listing-groups/query",
655
+ {
656
+ options: { ...queryOptions, page: pageParam, limit: pageSize }
657
+ }
658
+ ),
659
+ initialPageParam: 1,
660
+ getNextPageParam: (lastPage) => lastPage.hasNextPage ? lastPage.nextPage : void 0,
661
+ ...options
662
+ });
663
+ }
664
+ useSuspenseInfiniteProductListingGroupsQuery(params, options) {
665
+ const {
666
+ options: queryOptions,
667
+ pageSize = 20
668
+ } = params;
669
+ return (0, import_react_query4.useSuspenseInfiniteQuery)({
670
+ queryKey: productKeys.listingGroupsInfinite(queryOptions),
671
+ queryFn: async ({ pageParam }) => this.collectionClient.requestFindEndpoint(
672
+ "/api/products/listing-groups/query",
673
+ {
674
+ options: { ...queryOptions, page: pageParam, limit: pageSize }
675
+ }
676
+ ),
677
+ initialPageParam: 1,
678
+ getNextPageParam: (lastPage) => lastPage.hasNextPage ? lastPage.nextPage : void 0,
679
+ ...options
680
+ });
681
+ }
682
+ async prefetchProductListingGroupsQuery(params, options) {
683
+ const queryOptions = params.options;
684
+ return this.queryClient.prefetchQuery({
685
+ queryKey: productKeys.listingGroups(queryOptions),
686
+ queryFn: async () => this.collectionClient.requestFindEndpoint(
687
+ "/api/products/listing-groups/query",
688
+ { options: queryOptions }
689
+ ),
690
+ ...options
691
+ });
692
+ }
693
+ async prefetchInfiniteProductListingGroupsQuery(params, options) {
694
+ const {
695
+ options: queryOptions,
696
+ pageSize = 20
697
+ } = params;
698
+ return this.queryClient.prefetchInfiniteQuery({
699
+ queryKey: productKeys.listingGroupsInfinite(queryOptions),
700
+ queryFn: async ({ pageParam }) => this.collectionClient.requestFindEndpoint(
701
+ "/api/products/listing-groups/query",
702
+ {
703
+ options: { ...queryOptions, page: pageParam, limit: pageSize }
704
+ }
705
+ ),
706
+ initialPageParam: 1,
707
+ getNextPageParam: (lastPage) => lastPage.hasNextPage ? lastPage.nextPage : void 0,
708
+ pages: options?.pages ?? 1,
709
+ staleTime: options?.staleTime
710
+ });
711
+ }
712
+ useProductDetail(params, options) {
713
+ const discriminator = "slug" in params ? params.slug : params.id;
714
+ const enabled = options?.enabled !== false && Boolean(discriminator);
715
+ return (0, import_react_query4.useQuery)({
716
+ queryKey: productKeys.detail(params),
717
+ queryFn: () => this._commerce.product.detail(params),
718
+ enabled
719
+ });
720
+ }
721
+ useProductDetailBySlug(slug, options) {
722
+ return this.useProductDetail({ slug }, options);
723
+ }
724
+ useProductDetailById(id, options) {
725
+ return this.useProductDetail({ id }, options);
726
+ }
727
+ };
728
+
729
+ // src/core/query/realtime.ts
730
+ var INITIAL_RECONNECT_DELAY = 1e3;
731
+ var MAX_RECONNECT_DELAY = 3e4;
732
+ var RECONNECT_BACKOFF_FACTOR = 2;
733
+ var MAX_NO_TOKEN_RETRIES = 5;
734
+ var RealtimeConnection = class {
735
+ constructor(baseUrl, publishableKey, getToken, collections) {
736
+ this.baseUrl = baseUrl;
737
+ this.publishableKey = publishableKey;
738
+ this.getToken = getToken;
739
+ this.collections = collections;
740
+ this.abortController = null;
741
+ this.reconnectAttempt = 0;
742
+ this.noTokenAttempts = 0;
743
+ this.reconnectTimer = null;
744
+ this.listeners = /* @__PURE__ */ new Set();
745
+ this._connected = false;
746
+ }
747
+ get connected() {
748
+ return this._connected;
749
+ }
750
+ addListener(fn) {
751
+ this.listeners.add(fn);
752
+ return () => this.listeners.delete(fn);
753
+ }
754
+ connect() {
755
+ if (this.abortController) return;
756
+ this.abortController = new AbortController();
757
+ this.startStream(this.abortController.signal);
758
+ }
759
+ disconnect() {
760
+ this._connected = false;
761
+ if (this.reconnectTimer) {
762
+ clearTimeout(this.reconnectTimer);
763
+ this.reconnectTimer = null;
764
+ }
765
+ if (this.abortController) {
766
+ this.abortController.abort();
767
+ this.abortController = null;
768
+ }
769
+ this.reconnectAttempt = 0;
770
+ this.noTokenAttempts = 0;
771
+ }
772
+ async startStream(signal) {
773
+ const token = this.getToken();
774
+ if (!token) {
775
+ this.noTokenAttempts++;
776
+ if (this.noTokenAttempts >= MAX_NO_TOKEN_RETRIES) {
777
+ this._connected = false;
778
+ this.abortController = null;
779
+ return;
780
+ }
781
+ this.scheduleReconnect();
782
+ return;
783
+ }
784
+ this.noTokenAttempts = 0;
785
+ const params = this.collections?.length ? `?collections=${this.collections.join(",")}` : "";
786
+ const url = `${this.baseUrl}/api/events/stream${params}`;
787
+ try {
788
+ const response = await fetch(url, {
789
+ headers: {
790
+ "X-Publishable-Key": this.publishableKey,
791
+ Authorization: `Bearer ${token}`
792
+ },
793
+ signal
794
+ });
795
+ if (!response.ok) {
796
+ if (response.status === 401) {
797
+ this.scheduleReconnect();
798
+ return;
799
+ }
800
+ throw new Error(`SSE connection failed: ${response.status}`);
801
+ }
802
+ if (!response.body) {
803
+ throw new Error("SSE response has no body");
804
+ }
805
+ this._connected = true;
806
+ this.reconnectAttempt = 0;
807
+ await this.readStream(response.body, signal);
808
+ } catch {
809
+ if (signal.aborted) return;
810
+ this._connected = false;
811
+ this.scheduleReconnect();
812
+ }
813
+ }
814
+ async readStream(body, signal) {
815
+ const reader = body.getReader();
816
+ const decoder = new TextDecoder();
817
+ let buffer = "";
818
+ let currentEvent = "";
819
+ let currentData = "";
820
+ try {
821
+ while (true) {
822
+ const { done, value } = await reader.read();
823
+ if (done || signal.aborted) break;
824
+ buffer += decoder.decode(value, { stream: true });
825
+ const lines = buffer.split("\n");
826
+ buffer = lines.pop() ?? "";
827
+ for (const line of lines) {
828
+ if (line.startsWith("event: ")) {
829
+ currentEvent = line.slice(7);
830
+ } else if (line.startsWith("data: ")) {
831
+ currentData += (currentData ? "\n" : "") + line.slice(6);
832
+ } else if (line === "") {
833
+ if (currentEvent === "collection:change" && currentData) {
834
+ try {
835
+ const event = JSON.parse(currentData);
836
+ for (const listener of this.listeners) {
837
+ try {
838
+ listener(event);
839
+ } catch {
840
+ }
841
+ }
842
+ } catch {
843
+ }
844
+ }
845
+ currentEvent = "";
846
+ currentData = "";
847
+ }
848
+ }
849
+ }
850
+ } catch {
851
+ } finally {
852
+ reader.releaseLock();
853
+ this._connected = false;
854
+ if (!signal.aborted) {
855
+ this.scheduleReconnect();
856
+ }
857
+ }
858
+ }
859
+ scheduleReconnect() {
860
+ if (this.reconnectTimer) return;
861
+ const delay2 = Math.min(
862
+ INITIAL_RECONNECT_DELAY * Math.pow(RECONNECT_BACKOFF_FACTOR, this.reconnectAttempt),
863
+ MAX_RECONNECT_DELAY
864
+ );
865
+ this.reconnectAttempt++;
866
+ this.reconnectTimer = setTimeout(() => {
867
+ this.reconnectTimer = null;
868
+ this.abortController = new AbortController();
869
+ this.startStream(this.abortController.signal);
870
+ }, delay2);
871
+ }
872
+ };
873
+
874
+ // src/utils/types.ts
875
+ var resolveRelation = (ref) => {
876
+ if (typeof ref === "string" || typeof ref === "number" || ref === null || ref === void 0)
877
+ return null;
878
+ return ref;
879
+ };
880
+
881
+ // src/core/metadata/index.ts
882
+ function extractSeo(doc) {
883
+ const seo = doc.seo ?? {};
884
+ const og = seo.openGraph ?? {};
885
+ return {
886
+ title: seo.title ?? doc.title ?? null,
887
+ description: seo.description ?? null,
888
+ noIndex: seo.noIndex ?? null,
889
+ canonical: seo.canonical ?? null,
890
+ openGraph: {
891
+ title: og.title ?? null,
892
+ description: og.description ?? null,
893
+ image: og.image ?? null
894
+ }
895
+ };
896
+ }
897
+ function generateMetadata(input, options) {
898
+ const title = input.title ?? void 0;
899
+ const description = input.description ?? void 0;
900
+ const ogTitle = input.openGraph?.title ?? title;
901
+ const ogDescription = input.openGraph?.description ?? description;
902
+ const image = resolveMetaImage(input.openGraph?.image);
903
+ return {
904
+ title,
905
+ description,
906
+ ...input.noIndex && { robots: { index: false, follow: false } },
907
+ ...input.canonical && { alternates: { canonical: input.canonical } },
908
+ openGraph: {
909
+ ...ogTitle && { title: ogTitle },
910
+ ...ogDescription && { description: ogDescription },
911
+ ...options?.siteName && { siteName: options.siteName },
912
+ ...image && { images: [image] }
913
+ },
914
+ twitter: {
915
+ card: image ? "summary_large_image" : "summary",
916
+ ...ogTitle && { title: ogTitle },
917
+ ...ogDescription && { description: ogDescription },
918
+ ...image && { images: [image.url] }
919
+ }
920
+ };
921
+ }
922
+ function resolveMetaImage(ref) {
923
+ const image = resolveRelation(ref);
924
+ if (!image) return null;
925
+ const sized = image.sizes?.["1536"];
926
+ const url = sized?.url || image.url;
927
+ if (!url) return null;
928
+ const width = sized?.url ? sized.width : image.width;
929
+ const height = sized?.url ? sized.height : image.height;
930
+ return {
931
+ url,
932
+ ...width && { width },
933
+ ...height && { height },
934
+ ...image.alt && { alt: image.alt }
935
+ };
936
+ }
937
+
938
+ // src/core/collection/query-builder.ts
939
+ var CollectionQueryBuilder = class {
940
+ constructor(api, collection) {
941
+ this.api = api;
942
+ this.collection = collection;
943
+ }
944
+ /**
945
+ * Find documents (list query)
946
+ * GET /api/{collection}
947
+ * @returns Payload CMS find response with docs array and pagination
948
+ */
949
+ async find(options) {
950
+ return this.api.requestFind(
951
+ `/api/${String(this.collection)}`,
952
+ options
953
+ );
954
+ }
955
+ /**
956
+ * Find document by ID
957
+ * GET /api/{collection}/{id}
958
+ * @returns Document object directly (no wrapper)
959
+ */
960
+ async findById(id, options) {
961
+ return this.api.requestFindById(
962
+ `/api/${String(this.collection)}/${String(id)}`,
963
+ options
964
+ );
965
+ }
966
+ /**
967
+ * Create a new document
968
+ * POST /api/{collection}
969
+ * @returns Payload CMS mutation response with doc and message
970
+ */
971
+ async create(data, options) {
972
+ const endpoint = `/api/${String(this.collection)}`;
973
+ if (options?.file) {
974
+ return this.api.requestCreateWithFile(
975
+ endpoint,
976
+ data,
977
+ options.file,
978
+ options.filename
979
+ );
980
+ }
981
+ return this.api.requestCreate(endpoint, data);
982
+ }
983
+ /**
984
+ * Update a document by ID
985
+ * PATCH /api/{collection}/{id}
986
+ * @returns Payload CMS mutation response with doc and message
987
+ */
988
+ async update(id, data, options) {
989
+ const endpoint = `/api/${String(this.collection)}/${String(id)}`;
990
+ if (options?.file) {
991
+ return this.api.requestUpdateWithFile(
992
+ endpoint,
993
+ data,
994
+ options.file,
995
+ options.filename
996
+ );
997
+ }
998
+ return this.api.requestUpdate(endpoint, data);
999
+ }
1000
+ /**
1001
+ * Count documents
1002
+ * GET /api/{collection}/count
1003
+ * @returns Count response with totalDocs
1004
+ */
1005
+ async count(options) {
1006
+ return this.api.requestCount(
1007
+ `/api/${String(this.collection)}/count`,
1008
+ options
1009
+ );
1010
+ }
1011
+ /**
1012
+ * Find first matching document and return its Next.js Metadata.
1013
+ * Applies depth: 1 (SEO image populate) and limit: 1 automatically.
1014
+ * @returns Metadata or null if no document matches
1015
+ */
1016
+ async findMetadata(options, metadataOptions) {
1017
+ const { docs } = await this.find({ ...options, limit: 1, depth: 1 });
1018
+ const doc = docs[0];
1019
+ if (!doc) return null;
1020
+ return generateMetadata(
1021
+ extractSeo(doc),
1022
+ metadataOptions
1023
+ );
1024
+ }
1025
+ /**
1026
+ * Find document by ID and return its Next.js Metadata.
1027
+ * Applies depth: 1 (SEO image populate) automatically.
1028
+ * @returns Metadata (throws on 404)
1029
+ */
1030
+ async findMetadataById(id, metadataOptions) {
1031
+ const doc = await this.findById(id, { depth: 1 });
1032
+ return generateMetadata(
1033
+ extractSeo(doc),
1034
+ metadataOptions
1035
+ );
1036
+ }
1037
+ /**
1038
+ * Update multiple documents (bulk update)
1039
+ * PATCH /api/{collection}
1040
+ * @returns Payload CMS find response with updated docs
1041
+ */
1042
+ async updateMany(where, data) {
1043
+ return this.api.requestUpdateMany(
1044
+ `/api/${String(this.collection)}`,
1045
+ { where, data }
1046
+ );
1047
+ }
1048
+ /**
1049
+ * Delete a document by ID
1050
+ * DELETE /api/{collection}/{id}
1051
+ * @returns Deleted document object directly (no wrapper)
1052
+ */
1053
+ async remove(id) {
1054
+ return this.api.requestDelete(
1055
+ `/api/${String(this.collection)}/${String(id)}`
1056
+ );
1057
+ }
1058
+ /**
1059
+ * Delete multiple documents (bulk delete)
1060
+ * DELETE /api/{collection}
1061
+ * @returns Payload CMS find response with deleted docs
1062
+ */
1063
+ async removeMany(where) {
1064
+ return this.api.requestDeleteMany(
1065
+ `/api/${String(this.collection)}`,
1066
+ { where }
1067
+ );
1068
+ }
1069
+ };
1070
+
1071
+ // src/core/collection/http-client.ts
1072
+ var import_qs_esm = require("qs-esm");
1073
+
1074
+ // src/core/internal/utils/credentials.ts
1075
+ function requirePublishableKeyForSecret(apiName, publishableKey, secretKey) {
1076
+ if (secretKey && !publishableKey) {
1077
+ throw createConfigError(
1078
+ `publishableKey is required for ${apiName} when secretKey is used. It is sent as X-Publishable-Key for tenant routing, rate limiting, and quota enforcement.`
1079
+ );
1080
+ }
1081
+ return publishableKey ?? "";
1082
+ }
1083
+
1084
+ // src/core/client/types.ts
1085
+ function resolveApiUrl(apiUrl) {
1086
+ if (apiUrl) {
1087
+ return apiUrl.replace(/\/$/, "");
1088
+ }
1089
+ if (typeof process !== "undefined" && process.env) {
1090
+ const envUrl = process.env.SOFTWARE_API_URL || process.env.NEXT_PUBLIC_SOFTWARE_API_URL;
1091
+ if (envUrl) {
1092
+ return envUrl.replace(/\/$/, "");
1093
+ }
1094
+ }
1095
+ return "https://api.01.software";
1096
+ }
1097
+
1098
+ // src/core/internal/utils/http.ts
1099
+ var DEFAULT_TIMEOUT = 3e4;
1100
+ var DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504];
1101
+ var NON_RETRYABLE_STATUSES = [400, 401, 403, 404, 409, 422];
1102
+ var SAFE_METHODS = ["GET", "HEAD", "OPTIONS"];
1103
+ function debugLog(debug, type, message, data) {
1104
+ if (!debug) return;
1105
+ const shouldLog = debug === true || type === "request" && debug.logRequests || type === "response" && debug.logResponses || type === "error" && debug.logErrors;
1106
+ if (shouldLog) {
1107
+ console.group(`[SDK ${type.toUpperCase()}] ${message}`);
1108
+ if (data) console.log(data);
1109
+ console.groupEnd();
1110
+ }
1111
+ }
1112
+ function redactSensitiveHeader(value) {
1113
+ const prefix = value.toLowerCase().startsWith("bearer ") ? "Bearer " : "";
1114
+ return value.length > 20 ? `${prefix}...****${value.slice(-8)}` : "****";
1115
+ }
1116
+ function redactSensitiveHeaders(headers) {
1117
+ const redacted = Object.fromEntries(headers.entries());
1118
+ if (redacted.authorization) {
1119
+ redacted.authorization = redactSensitiveHeader(redacted.authorization);
1120
+ }
1121
+ if (redacted["x-preview-token"]) {
1122
+ redacted["x-preview-token"] = redactSensitiveHeader(
1123
+ redacted["x-preview-token"]
1124
+ );
1125
+ }
1126
+ return redacted;
1127
+ }
1128
+ function getErrorSuggestion(status) {
1129
+ if (status === 400)
1130
+ return "The request data failed validation. Check field values and types.";
1131
+ if (status === 401) return "Please check your authentication credentials.";
1132
+ if (status === 403)
1133
+ return "Access denied. Check your credentials or permissions.";
1134
+ if (status === 404) return "The requested resource was not found.";
1135
+ if (status === 422) return "The request data failed validation.";
1136
+ if (status >= 500) return "A server error occurred. Please try again later.";
1137
+ return void 0;
1138
+ }
1139
+ function isUsageLimitExceededResponse(response) {
1140
+ if (response.status !== 429) return false;
1141
+ const limit = parseInt(response.headers.get("X-Usage-Limit") || "", 10);
1142
+ const current = parseInt(response.headers.get("X-Usage-Current") || "", 10);
1143
+ if (!Number.isFinite(limit) || !Number.isFinite(current)) return false;
1144
+ return response.headers.get("X-Usage-Exceeded") === "true" || current > limit;
1145
+ }
1146
+ async function parseErrorBody(response) {
1147
+ const fallback = {
1148
+ errorMessage: `HTTP ${response.status}: ${response.statusText}`,
1149
+ userMessage: `Request failed (status: ${response.status})`
1150
+ };
1151
+ try {
1152
+ const body = await response.json();
1153
+ const reason = typeof body.reason === "string" ? body.reason : typeof body.code === "string" ? body.code : void 0;
1154
+ if (body.errors && Array.isArray(body.errors)) {
1155
+ const fieldErrors = [];
1156
+ for (const e of body.errors) {
1157
+ if (e.data?.errors && Array.isArray(e.data.errors) && e.data.errors.length > 0) {
1158
+ for (const fe of e.data.errors) {
1159
+ fieldErrors.push({
1160
+ field: fe.path || fe.field,
1161
+ message: fe.message
1162
+ });
1163
+ }
1164
+ } else if (e.field || e.message) {
1165
+ fieldErrors.push({ field: e.field, message: e.message });
1166
+ }
1167
+ }
1168
+ const details = (fieldErrors.length > 0 ? fieldErrors : body.errors).map(
1169
+ (e) => e.field ? `${e.field}: ${e.message}` : e.message
1170
+ ).filter(Boolean).join("; ");
1171
+ if (details) {
1172
+ return {
1173
+ errorMessage: `HTTP ${response.status}: ${details}`,
1174
+ userMessage: details,
1175
+ reason,
1176
+ body,
1177
+ errors: fieldErrors.length > 0 ? fieldErrors : body.errors
1178
+ };
1179
+ }
1180
+ }
1181
+ if (typeof body.error === "string") {
1182
+ return {
1183
+ errorMessage: `HTTP ${response.status}: ${body.error}`,
1184
+ userMessage: body.error,
1185
+ reason,
1186
+ body
1187
+ };
1188
+ }
1189
+ if (body.message) {
1190
+ return {
1191
+ errorMessage: `HTTP ${response.status}: ${body.message}`,
1192
+ userMessage: body.message,
1193
+ reason,
1194
+ body
1195
+ };
1196
+ }
1197
+ return { ...fallback, reason, body };
1198
+ } catch {
1199
+ return fallback;
1200
+ }
1201
+ }
1202
+ function getParsedErrorSuggestion(status, parsed) {
1203
+ if (status === 403 && parsed.reason === "origin_not_allowed") {
1204
+ return "Add the request origin to the tenant Browser API origins, then retry the browser request.";
1205
+ }
1206
+ return getErrorSuggestion(status);
1207
+ }
1208
+ async function delay(ms) {
1209
+ return new Promise((resolve) => setTimeout(resolve, ms));
1210
+ }
1211
+ function attachRequestId(err, id) {
1212
+ if (id) err.requestId = id;
1213
+ return err;
1214
+ }
1215
+ function createHttpStatusError(status, parsed, details, requestId) {
1216
+ const errorDetails = {
1217
+ ...details,
1218
+ ...parsed.errors && { errors: parsed.errors },
1219
+ ...parsed.body && { body: parsed.body }
1220
+ };
1221
+ const suggestion = getParsedErrorSuggestion(status, parsed);
1222
+ if (status === 400 || status === 422) {
1223
+ return attachRequestId(
1224
+ createValidationError(
1225
+ parsed.errorMessage,
1226
+ errorDetails,
1227
+ parsed.userMessage,
1228
+ suggestion,
1229
+ status
1230
+ ),
1231
+ requestId
1232
+ );
1233
+ }
1234
+ if (status === 401) {
1235
+ return attachRequestId(
1236
+ createAuthError(
1237
+ parsed.errorMessage,
1238
+ errorDetails,
1239
+ parsed.userMessage,
1240
+ suggestion
1241
+ ),
1242
+ requestId
1243
+ );
1244
+ }
1245
+ if (status === 403) {
1246
+ return attachRequestId(
1247
+ createPermissionError(
1248
+ parsed.errorMessage,
1249
+ errorDetails,
1250
+ parsed.userMessage,
1251
+ suggestion
1252
+ ),
1253
+ requestId
1254
+ );
1255
+ }
1256
+ if (status === 404) {
1257
+ return attachRequestId(
1258
+ createNotFoundError(
1259
+ parsed.errorMessage,
1260
+ errorDetails,
1261
+ parsed.userMessage,
1262
+ suggestion
1263
+ ),
1264
+ requestId
1265
+ );
1266
+ }
1267
+ if (status === 409) {
1268
+ return attachRequestId(
1269
+ createConflictError(
1270
+ parsed.errorMessage,
1271
+ errorDetails,
1272
+ parsed.userMessage,
1273
+ suggestion
1274
+ ),
1275
+ requestId
1276
+ );
1277
+ }
1278
+ return attachRequestId(
1279
+ createNetworkError(
1280
+ parsed.errorMessage,
1281
+ status,
1282
+ errorDetails,
1283
+ parsed.userMessage,
1284
+ suggestion
1285
+ ),
1286
+ requestId
1287
+ );
1288
+ }
1289
+ async function httpFetch(url, options) {
1290
+ const {
1291
+ apiUrl,
1292
+ publishableKey,
1293
+ secretKey,
1294
+ customerToken,
1295
+ timeout = DEFAULT_TIMEOUT,
1296
+ debug,
1297
+ retry,
1298
+ onUnauthorized,
1299
+ ...requestInit
1300
+ } = options || {};
1301
+ const baseUrl = resolveApiUrl(apiUrl);
1302
+ const retryConfig = {
1303
+ maxRetries: retry?.maxRetries ?? 3,
1304
+ retryableStatuses: retry?.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES,
1305
+ retryDelay: retry?.retryDelay ?? ((attempt) => Math.min(1e3 * 2 ** attempt, 1e4))
1306
+ };
1307
+ let authToken;
1308
+ if (secretKey) {
1309
+ authToken = secretKey;
1310
+ } else if (customerToken) {
1311
+ authToken = customerToken;
1312
+ }
1313
+ let lastError;
1314
+ let hasRetried401 = false;
1315
+ for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {
1316
+ try {
1317
+ const headers = new Headers(requestInit.headers);
1318
+ if (publishableKey) {
1319
+ headers.set("X-Publishable-Key", publishableKey);
1320
+ }
1321
+ if (authToken) {
1322
+ headers.set("Authorization", `Bearer ${authToken}`);
1323
+ }
1324
+ if (!headers.has("Content-Type") && requestInit.body && !(requestInit.body instanceof FormData)) {
1325
+ headers.set("Content-Type", "application/json");
1326
+ }
1327
+ const redactedHeaders = redactSensitiveHeaders(headers);
1328
+ debugLog(debug, "request", url, {
1329
+ method: requestInit.method || "GET",
1330
+ headers: redactedHeaders,
1331
+ attempt: attempt + 1
1332
+ });
1333
+ const controller = new AbortController();
1334
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
1335
+ const response = await fetch(`${baseUrl}${url}`, {
1336
+ ...requestInit,
1337
+ headers,
1338
+ signal: controller.signal
1339
+ });
1340
+ clearTimeout(timeoutId);
1341
+ const requestId = response.headers.get("x-request-id") ?? void 0;
1342
+ debugLog(debug, "response", url, {
1343
+ status: response.status,
1344
+ statusText: response.statusText,
1345
+ headers: redactSensitiveHeaders(response.headers)
1346
+ });
1347
+ if (!response.ok) {
1348
+ if (isUsageLimitExceededResponse(response)) {
1349
+ const limit = parseInt(
1350
+ response.headers.get("X-Usage-Limit") || "0",
1351
+ 10
1352
+ );
1353
+ const current = parseInt(
1354
+ response.headers.get("X-Usage-Current") || "0",
1355
+ 10
1356
+ );
1357
+ const remaining = parseInt(
1358
+ response.headers.get("X-Usage-Remaining") || "0",
1359
+ 10
1360
+ );
1361
+ throw attachRequestId(
1362
+ createUsageLimitError(
1363
+ `Monthly API usage limit exceeded (${current.toLocaleString()}/${limit.toLocaleString()})`,
1364
+ { limit, current, remaining },
1365
+ {
1366
+ url,
1367
+ method: requestInit.method || "GET",
1368
+ attempt: attempt + 1
1369
+ },
1370
+ "Monthly API call limit exceeded. Please upgrade your plan.",
1371
+ "Upgrade your tenant plan to increase the monthly API call limit."
1372
+ ),
1373
+ requestId
1374
+ );
1375
+ }
1376
+ const parsed = await parseErrorBody(response);
1377
+ if (response.status === 401 && onUnauthorized && customerToken && !hasRetried401 && parsed.reason === "token_expired") {
1378
+ hasRetried401 = true;
1379
+ try {
1380
+ const newToken = await onUnauthorized();
1381
+ if (newToken) {
1382
+ authToken = newToken;
1383
+ continue;
1384
+ }
1385
+ } catch {
1386
+ }
1387
+ }
1388
+ const details = {
1389
+ url,
1390
+ method: requestInit.method || "GET",
1391
+ attempt: attempt + 1
1392
+ };
1393
+ if (NON_RETRYABLE_STATUSES.includes(response.status)) {
1394
+ throw createHttpStatusError(
1395
+ response.status,
1396
+ parsed,
1397
+ details,
1398
+ requestId
1399
+ );
1400
+ }
1401
+ const error = attachRequestId(
1402
+ createNetworkError(
1403
+ parsed.errorMessage,
1404
+ response.status,
1405
+ details,
1406
+ parsed.userMessage,
1407
+ getErrorSuggestion(response.status)
1408
+ ),
1409
+ requestId
1410
+ );
1411
+ const method = (requestInit.method || "GET").toUpperCase();
1412
+ if (attempt < retryConfig.maxRetries && SAFE_METHODS.includes(method) && retryConfig.retryableStatuses.includes(response.status)) {
1413
+ lastError = error;
1414
+ const retryDelay = retryConfig.retryDelay(attempt);
1415
+ debugLog(debug, "error", `Retrying in ${retryDelay}ms...`, error);
1416
+ await delay(retryDelay);
1417
+ continue;
1418
+ }
1419
+ throw error;
1420
+ }
1421
+ return response;
1422
+ } catch (error) {
1423
+ debugLog(debug, "error", url, error);
1424
+ const method = (requestInit.method || "GET").toUpperCase();
1425
+ const isSafe = SAFE_METHODS.includes(method);
1426
+ if (error instanceof Error && error.name === "AbortError") {
1427
+ const timeoutError = createTimeoutError(
1428
+ `Request timed out after ${timeout}ms.`,
1429
+ { url, timeout, attempt: attempt + 1 },
1430
+ "The request timed out.",
1431
+ "Please check your network connection or try again later."
1432
+ );
1433
+ if (isSafe && attempt < retryConfig.maxRetries) {
1434
+ lastError = timeoutError;
1435
+ await delay(retryConfig.retryDelay(attempt));
1436
+ continue;
1437
+ }
1438
+ throw timeoutError;
1439
+ }
1440
+ if (error instanceof TypeError) {
1441
+ const networkError = createNetworkError(
1442
+ "Network connection failed.",
1443
+ void 0,
1444
+ { url, originalError: error.message, attempt: attempt + 1 },
1445
+ "Network connection failed.",
1446
+ "Please check your internet connection and try again."
1447
+ );
1448
+ if (isSafe && attempt < retryConfig.maxRetries) {
1449
+ lastError = networkError;
1450
+ await delay(retryConfig.retryDelay(attempt));
1451
+ continue;
1452
+ }
1453
+ throw networkError;
1454
+ }
1455
+ if (error instanceof NetworkError || error instanceof TimeoutError) {
1456
+ if (isSafe && attempt < retryConfig.maxRetries && error.status && !NON_RETRYABLE_STATUSES.includes(error.status) && retryConfig.retryableStatuses.includes(error.status)) {
1457
+ lastError = error;
1458
+ await delay(retryConfig.retryDelay(attempt));
1459
+ continue;
1460
+ }
1461
+ throw error;
1462
+ }
1463
+ if (error instanceof SDKError) {
1464
+ throw error;
1465
+ }
1466
+ const unknownError = createNetworkError(
1467
+ error instanceof Error ? error.message : "An unknown network error occurred.",
1468
+ void 0,
1469
+ { url, originalError: error, attempt: attempt + 1 },
1470
+ "An unknown error occurred.",
1471
+ "Please try again later."
1472
+ );
1473
+ if (isSafe && attempt < retryConfig.maxRetries) {
1474
+ lastError = unknownError;
1475
+ await delay(retryConfig.retryDelay(attempt));
1476
+ continue;
1477
+ }
1478
+ throw unknownError;
1479
+ }
1480
+ }
1481
+ throw lastError ?? new NetworkError("Request failed after retries");
1482
+ }
1483
+
1484
+ // src/core/collection/http-client.ts
1485
+ var HttpClient = class {
1486
+ constructor(publishableKey, secretKey, getCustomerToken, onUnauthorized, onRequestId, apiUrl) {
1487
+ this.publishableKey = requirePublishableKeyForSecret(
1488
+ "CollectionClient",
1489
+ publishableKey,
1490
+ secretKey
1491
+ );
1492
+ this.secretKey = secretKey;
1493
+ this.getCustomerToken = getCustomerToken;
1494
+ this.onUnauthorized = onUnauthorized;
1495
+ this.onRequestId = onRequestId;
1496
+ this.apiUrl = apiUrl;
1497
+ }
1498
+ get defaultOptions() {
1499
+ const opts = {
1500
+ apiUrl: this.apiUrl,
1501
+ publishableKey: this.publishableKey,
1502
+ secretKey: this.secretKey
1503
+ };
1504
+ const token = this.getCustomerToken?.();
1505
+ if (token) {
1506
+ opts.customerToken = token;
1507
+ if (this.onUnauthorized) {
1508
+ opts.onUnauthorized = this.onUnauthorized;
1509
+ }
1510
+ }
1511
+ return opts;
1512
+ }
1513
+ async fetchWithTracking(url, opts) {
1514
+ try {
1515
+ const response = await httpFetch(url, opts);
1516
+ this.onRequestId?.(response.headers.get("x-request-id") ?? null);
1517
+ return response;
1518
+ } catch (err) {
1519
+ const id = err instanceof SDKError ? err.requestId ?? null : null;
1520
+ this.onRequestId?.(id);
1521
+ throw err;
1522
+ }
1523
+ }
1524
+ buildUrl(endpoint, options) {
1525
+ if (!options) return endpoint;
1526
+ const queryString = (0, import_qs_esm.stringify)(options, { addQueryPrefix: true });
1527
+ return queryString ? `${endpoint}${queryString}` : endpoint;
1528
+ }
1529
+ assertJsonResponse(response) {
1530
+ const contentType = response.headers.get("content-type");
1531
+ if (!contentType?.includes("application/json")) {
1532
+ throw createApiError("Response is not in JSON format.", response.status, {
1533
+ contentType
1534
+ });
1535
+ }
1536
+ }
1537
+ /**
1538
+ * Parse Payload CMS find response (list query)
1539
+ * Returns native Payload response structure
1540
+ */
1541
+ async parseFindResponse(response) {
1542
+ const contentType = response.headers.get("content-type");
1543
+ try {
1544
+ this.assertJsonResponse(response);
1545
+ const jsonData = await response.json();
1546
+ if (jsonData.docs === void 0) {
1547
+ throw createApiError("Invalid find response.", response.status, {
1548
+ jsonData
1549
+ });
1550
+ }
1551
+ return {
1552
+ docs: jsonData.docs,
1553
+ totalDocs: jsonData.totalDocs ?? 0,
1554
+ limit: jsonData.limit || 20,
1555
+ totalPages: jsonData.totalPages ?? 0,
1556
+ page: jsonData.page || 1,
1557
+ pagingCounter: jsonData.pagingCounter || 1,
1558
+ hasPrevPage: jsonData.hasPrevPage ?? false,
1559
+ hasNextPage: jsonData.hasNextPage ?? false,
1560
+ prevPage: jsonData.prevPage ?? null,
1561
+ nextPage: jsonData.nextPage ?? null
1562
+ };
1563
+ } catch (error) {
1564
+ if (error instanceof SDKError) throw error;
1565
+ throw createApiError("Failed to parse response.", response.status, {
1566
+ contentType,
1567
+ error: error instanceof Error ? error.message : error
1568
+ });
1569
+ }
1570
+ }
1571
+ /**
1572
+ * Parse Payload CMS mutation response (create/update)
1573
+ * Returns native Payload response structure
1574
+ */
1575
+ async parseMutationResponse(response) {
1576
+ const contentType = response.headers.get("content-type");
1577
+ try {
1578
+ this.assertJsonResponse(response);
1579
+ const jsonData = await response.json();
1580
+ if (jsonData.doc === void 0) {
1581
+ throw createApiError("Invalid mutation response.", response.status, {
1582
+ jsonData
1583
+ });
1584
+ }
1585
+ return {
1586
+ message: jsonData.message || "",
1587
+ doc: jsonData.doc,
1588
+ errors: jsonData.errors
1589
+ };
1590
+ } catch (error) {
1591
+ if (error instanceof SDKError) throw error;
1592
+ throw createApiError("Failed to parse response.", response.status, {
1593
+ contentType,
1594
+ error: error instanceof Error ? error.message : error
1595
+ });
1596
+ }
1597
+ }
1598
+ /**
1599
+ * Parse Payload CMS document response (findById/delete)
1600
+ * Returns document directly without wrapper
1601
+ */
1602
+ async parseDocumentResponse(response) {
1603
+ const contentType = response.headers.get("content-type");
1604
+ try {
1605
+ this.assertJsonResponse(response);
1606
+ const jsonData = await response.json();
1607
+ return jsonData;
1608
+ } catch (error) {
1609
+ if (error instanceof SDKError) throw error;
1610
+ throw createApiError("Failed to parse response.", response.status, {
1611
+ contentType,
1612
+ error: error instanceof Error ? error.message : error
1613
+ });
1614
+ }
1615
+ }
1616
+ };
1617
+
1618
+ // src/core/collection/collection-client.ts
1619
+ function buildPayloadFormData(data, file, filename) {
1620
+ const formData = new FormData();
1621
+ formData.append("file", file, filename);
1622
+ if (data != null) {
1623
+ formData.append("_payload", JSON.stringify(data));
1624
+ }
1625
+ return formData;
1626
+ }
1627
+ var CollectionClient = class extends HttpClient {
1628
+ from(collection) {
1629
+ return new CollectionQueryBuilder(this, collection);
1630
+ }
1631
+ // ============================================================================
1632
+ // Payload-native methods
1633
+ // ============================================================================
1634
+ /**
1635
+ * Find documents (list query)
1636
+ * GET /api/{collection}
1637
+ */
1638
+ async requestFind(endpoint, options) {
1639
+ const url = this.buildUrl(endpoint, options);
1640
+ const response = await this.fetchWithTracking(url, {
1641
+ ...this.defaultOptions,
1642
+ method: "GET"
1643
+ });
1644
+ return this.parseFindResponse(response);
1645
+ }
1646
+ /**
1647
+ * Find-like response from a custom endpoint
1648
+ * POST /api/...custom-endpoint
1649
+ */
1650
+ async requestFindEndpoint(endpoint, data) {
1651
+ const response = await this.fetchWithTracking(endpoint, {
1652
+ ...this.defaultOptions,
1653
+ method: "POST",
1654
+ body: data ? JSON.stringify(data) : void 0
1655
+ });
1656
+ return this.parseFindResponse(response);
1657
+ }
1658
+ /**
1659
+ * Find document by ID
1660
+ * GET /api/{collection}/{id}
1661
+ */
1662
+ async requestFindById(endpoint, options) {
1663
+ const url = this.buildUrl(endpoint, options);
1664
+ const response = await this.fetchWithTracking(url, {
1665
+ ...this.defaultOptions,
1666
+ method: "GET"
1667
+ });
1668
+ return this.parseDocumentResponse(response);
1669
+ }
1670
+ /**
1671
+ * Create document
1672
+ * POST /api/{collection}
1673
+ */
1674
+ async requestCreate(endpoint, data) {
1675
+ const response = await this.fetchWithTracking(endpoint, {
1676
+ ...this.defaultOptions,
1677
+ method: "POST",
1678
+ body: data ? JSON.stringify(data) : void 0
1679
+ });
1680
+ return this.parseMutationResponse(response);
1681
+ }
1682
+ /**
1683
+ * Update document
1684
+ * PATCH /api/{collection}/{id}
1685
+ */
1686
+ async requestUpdate(endpoint, data) {
1687
+ const response = await this.fetchWithTracking(endpoint, {
1688
+ ...this.defaultOptions,
1689
+ method: "PATCH",
1690
+ body: data ? JSON.stringify(data) : void 0
1691
+ });
1692
+ return this.parseMutationResponse(response);
1693
+ }
1694
+ /**
1695
+ * Count documents
1696
+ * GET /api/{collection}/count
1697
+ */
1698
+ async requestCount(endpoint, options) {
1699
+ const url = this.buildUrl(endpoint, options);
1700
+ const response = await this.fetchWithTracking(url, {
1701
+ ...this.defaultOptions,
1702
+ method: "GET"
1703
+ });
1704
+ return this.parseDocumentResponse(response);
1705
+ }
1706
+ /**
1707
+ * Update multiple documents (bulk update)
1708
+ * PATCH /api/{collection}
1709
+ */
1710
+ async requestUpdateMany(endpoint, data) {
1711
+ const response = await this.fetchWithTracking(endpoint, {
1712
+ ...this.defaultOptions,
1713
+ method: "PATCH",
1714
+ body: JSON.stringify(data)
1715
+ });
1716
+ return this.parseFindResponse(response);
1717
+ }
1718
+ /**
1719
+ * Delete document
1720
+ * DELETE /api/{collection}/{id}
1721
+ */
1722
+ async requestDelete(endpoint) {
1723
+ const response = await this.fetchWithTracking(endpoint, {
1724
+ ...this.defaultOptions,
1725
+ method: "DELETE"
1726
+ });
1727
+ return this.parseDocumentResponse(response);
1728
+ }
1729
+ /**
1730
+ * Delete multiple documents (bulk delete)
1731
+ * DELETE /api/{collection}
1732
+ */
1733
+ async requestDeleteMany(endpoint, data) {
1734
+ const response = await this.fetchWithTracking(endpoint, {
1735
+ ...this.defaultOptions,
1736
+ method: "DELETE",
1737
+ body: JSON.stringify(data)
1738
+ });
1739
+ return this.parseFindResponse(response);
1740
+ }
1741
+ /**
1742
+ * Create document with file upload
1743
+ * POST /api/{collection} (multipart/form-data)
1744
+ */
1745
+ async requestCreateWithFile(endpoint, data, file, filename) {
1746
+ const response = await this.fetchWithTracking(endpoint, {
1747
+ ...this.defaultOptions,
1748
+ method: "POST",
1749
+ body: buildPayloadFormData(data, file, filename)
1750
+ });
1751
+ return this.parseMutationResponse(response);
1752
+ }
1753
+ /**
1754
+ * Update document with file upload
1755
+ * PATCH /api/{collection}/{id} (multipart/form-data)
1756
+ */
1757
+ async requestUpdateWithFile(endpoint, data, file, filename) {
1758
+ const response = await this.fetchWithTracking(endpoint, {
1759
+ ...this.defaultOptions,
1760
+ method: "PATCH",
1761
+ body: buildPayloadFormData(data, file, filename)
1762
+ });
1763
+ return this.parseMutationResponse(response);
1764
+ }
1765
+ };
1766
+
1767
+ // src/core/query/query-client.ts
1768
+ function createReadOnlyQueryHooksFacade(hooks) {
1769
+ return {
1770
+ useQuery: hooks.useQuery.bind(hooks),
1771
+ useSuspenseQuery: hooks.useSuspenseQuery.bind(hooks),
1772
+ useQueryById: hooks.useQueryById.bind(hooks),
1773
+ useSuspenseQueryById: hooks.useSuspenseQueryById.bind(hooks),
1774
+ useInfiniteQuery: hooks.useInfiniteQuery.bind(hooks),
1775
+ useSuspenseInfiniteQuery: hooks.useSuspenseInfiniteQuery.bind(hooks),
1776
+ prefetchQuery: hooks.prefetchQuery.bind(hooks),
1777
+ prefetchQueryById: hooks.prefetchQueryById.bind(hooks),
1778
+ prefetchInfiniteQuery: hooks.prefetchInfiniteQuery.bind(hooks),
1779
+ invalidateQueries: hooks.invalidateQueries.bind(hooks),
1780
+ getQueryData: hooks.getQueryData.bind(hooks),
1781
+ setQueryData: hooks.setQueryData.bind(hooks),
1782
+ useCustomerMe: hooks.useCustomerMe.bind(hooks),
1783
+ useCustomerLogin: hooks.useCustomerLogin.bind(hooks),
1784
+ useCustomerRegister: hooks.useCustomerRegister.bind(hooks),
1785
+ useCustomerLogout: hooks.useCustomerLogout.bind(hooks),
1786
+ useCustomerForgotPassword: hooks.useCustomerForgotPassword.bind(hooks),
1787
+ useCustomerResetPassword: hooks.useCustomerResetPassword.bind(hooks),
1788
+ useCustomerRefreshToken: hooks.useCustomerRefreshToken.bind(hooks),
1789
+ useCustomerUpdateProfile: hooks.useCustomerUpdateProfile.bind(hooks),
1790
+ useCustomerChangePassword: hooks.useCustomerChangePassword.bind(hooks),
1791
+ invalidateCustomerQueries: hooks.invalidateCustomerQueries.bind(hooks),
1792
+ getCustomerData: hooks.getCustomerData.bind(hooks),
1793
+ setCustomerData: hooks.setCustomerData.bind(hooks),
1794
+ useProductListingGroupsQuery: hooks.useProductListingGroupsQuery.bind(hooks),
1795
+ useSuspenseProductListingGroupsQuery: hooks.useSuspenseProductListingGroupsQuery.bind(hooks),
1796
+ useInfiniteProductListingGroupsQuery: hooks.useInfiniteProductListingGroupsQuery.bind(hooks),
1797
+ useSuspenseInfiniteProductListingGroupsQuery: hooks.useSuspenseInfiniteProductListingGroupsQuery.bind(hooks),
1798
+ prefetchProductListingGroupsQuery: hooks.prefetchProductListingGroupsQuery.bind(hooks),
1799
+ prefetchInfiniteProductListingGroupsQuery: hooks.prefetchInfiniteProductListingGroupsQuery.bind(hooks),
1800
+ useProductDetail: hooks.useProductDetail.bind(hooks),
1801
+ useProductDetailBySlug: hooks.useProductDetailBySlug.bind(hooks),
1802
+ useProductDetailById: hooks.useProductDetailById.bind(hooks)
1803
+ };
1804
+ }
1805
+ function createQueryHooks(client, queryClient = getQueryClient()) {
1806
+ const config = client.getConfig();
1807
+ const onUnauthorized = async () => {
1808
+ try {
1809
+ const result = await client.customer.auth.refreshToken();
1810
+ return result.token ?? null;
1811
+ } catch {
1812
+ return null;
1813
+ }
1814
+ };
1815
+ const collectionClient = new CollectionClient(
1816
+ config.publishableKey,
1817
+ void 0,
1818
+ () => client.customer.auth.getToken(),
1819
+ onUnauthorized,
1820
+ (id) => {
1821
+ client.lastRequestId = id;
1822
+ },
1823
+ config.apiUrl
1824
+ );
1825
+ const hooks = new QueryHooks(
1826
+ queryClient,
1827
+ collectionClient,
1828
+ client.customer.auth,
1829
+ client.commerce
1830
+ );
1831
+ return createReadOnlyQueryHooksFacade(hooks);
1832
+ }
1833
+ function createServerQueryHooks(client, queryClient = getQueryClient()) {
1834
+ return new QueryHooks(
1835
+ queryClient,
1836
+ client.collections,
1837
+ void 0,
1838
+ client.commerce
1839
+ );
1840
+ }
1841
+ //# sourceMappingURL=query.cjs.map