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