@01.software/sdk 0.31.0 → 0.32.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.
- package/README.md +87 -29
- package/dist/analytics/react.cjs.map +1 -1
- package/dist/analytics/react.js.map +1 -1
- package/dist/analytics.cjs.map +1 -1
- package/dist/analytics.js.map +1 -1
- package/dist/client.cjs +10 -46
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +6 -6
- package/dist/client.d.ts +6 -6
- package/dist/client.js +10 -46
- package/dist/client.js.map +1 -1
- package/dist/{collection-client-DFXXz0vk.d.cts → collection-client-CORhppPb.d.cts} +3 -3
- package/dist/{collection-client-ByzY3hWK.d.ts → collection-client-DPGXnhoF.d.ts} +3 -3
- package/dist/{const-AytzliEu.d.cts → const-Brk2Ff0q.d.cts} +1 -1
- package/dist/{const-BGCP-OJL.d.ts → const-DcY2_z9O.d.ts} +1 -1
- package/dist/index.cjs +58 -47
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +58 -47
- package/dist/index.js.map +1 -1
- package/dist/{payload-types-Wa4-eC6x.d.cts → payload-types-DVK1QCeU.d.cts} +8 -2
- package/dist/{payload-types-Wa4-eC6x.d.ts → payload-types-DVK1QCeU.d.ts} +8 -2
- package/dist/query.cjs.map +1 -1
- package/dist/query.d.cts +16 -16
- package/dist/query.d.ts +16 -16
- package/dist/query.js.map +1 -1
- package/dist/realtime.cjs.map +1 -1
- package/dist/realtime.d.cts +2 -2
- package/dist/realtime.d.ts +2 -2
- package/dist/realtime.js.map +1 -1
- package/dist/server.cjs +34 -1
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +99 -7
- package/dist/server.d.ts +99 -7
- package/dist/server.js +34 -1
- package/dist/server.js.map +1 -1
- package/dist/{types-CmLG-7RL.d.cts → types-ByMrR_Z_.d.cts} +1 -1
- package/dist/{types-DChFjQGz.d.cts → types-CAkWqIr6.d.cts} +41 -8
- package/dist/{types-BX2mqDf6.d.ts → types-CYMSBkJC.d.ts} +41 -8
- package/dist/{types-CVA10VC-.d.ts → types-DUPC7Xn6.d.ts} +1 -1
- package/dist/ui/form.d.cts +1 -1
- package/dist/ui/form.d.ts +1 -1
- package/dist/ui/video.d.cts +1 -1
- package/dist/ui/video.d.ts +1 -1
- package/dist/webhook.cjs +48 -1
- package/dist/webhook.cjs.map +1 -1
- package/dist/webhook.d.cts +73 -4
- package/dist/webhook.d.ts +73 -4
- package/dist/webhook.js +48 -1
- package/dist/webhook.js.map +1 -1
- package/package.json +3 -3
package/dist/query.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/query.ts","../src/core/query/get-query-client.ts","../src/core/query/query-keys.ts","../src/core/query/collection-hooks.ts","../src/core/query/customer-hooks.ts","../src/core/internal/errors/index.ts","../src/core/query/query-hooks.ts","../src/core/query/realtime.ts","../src/utils/types.ts","../src/core/metadata/index.ts","../src/core/collection/query-builder.ts","../src/core/collection/http-client.ts","../src/core/internal/utils/credentials.ts","../src/core/client/types.ts","../src/core/internal/utils/http.ts","../src/core/collection/collection-client.ts","../src/core/query/query-client.ts"],"sourcesContent":["export * from './core/query'\n","import {\n isServer,\n QueryClient,\n defaultShouldDehydrateQuery,\n} from '@tanstack/react-query'\n\nfunction makeQueryClient() {\n return new QueryClient({\n defaultOptions: {\n queries: {\n // Infinite staleTime: server-fetched data persists until explicitly invalidated.\n // For browser clients needing fresher data, override per-query:\n // useQuery({ ..., staleTime: 5 * 60 * 1000 })\n staleTime: Number.POSITIVE_INFINITY,\n refetchOnWindowFocus: false,\n },\n dehydrate: {\n shouldDehydrateQuery: (query) =>\n defaultShouldDehydrateQuery(query) ||\n query.state.status === 'pending',\n shouldRedactErrors: () => false,\n },\n },\n })\n}\n\nlet browserQueryClient: QueryClient | undefined\n\nexport function getQueryClient() {\n if (isServer) {\n return makeQueryClient()\n }\n if (!browserQueryClient) {\n browserQueryClient = makeQueryClient()\n }\n return browserQueryClient\n}\n","import type { ServerCollection, ApiQueryOptions } from '../client/types'\nimport type { ProductListingGroupsQueryOptions } from './query-hooks'\n\nexport function collectionKeys<T extends ServerCollection>(collection: T) {\n return {\n all: [collection] as const,\n lists: () => [collection, 'list'] as const,\n list: (options?: ApiQueryOptions) => [collection, 'list', options] as const,\n details: () => [collection, 'detail'] as const,\n detail: (id: string, options?: ApiQueryOptions) =>\n [collection, 'detail', id, options] as const,\n infinites: () => [collection, 'infinite'] as const,\n infinite: (options?: Omit<ApiQueryOptions, 'page'>) =>\n [collection, 'infinite', options] as const,\n }\n}\n\nexport const customerKeys = {\n all: ['customer'] as const,\n me: () => ['customer', 'me'] as const,\n}\n\nexport const productKeys = {\n listingGroups: (options?: ProductListingGroupsQueryOptions) =>\n ['products', 'listing-groups', 'list', options] as const,\n listingGroupsInfinite: (\n options?: Omit<ProductListingGroupsQueryOptions, 'page' | 'limit'>,\n ) =>\n ['products', 'listing-groups', 'infinite', options] as const,\n detail: (params: { slug: string } | { id: string }) =>\n ['products', 'detail', params] as const,\n detailAll: () => ['products', 'detail'] as const,\n}\n","import {\n QueryClient,\n useQuery as useQueryOriginal,\n useSuspenseQuery as useSuspenseQueryOriginal,\n useInfiniteQuery as useInfiniteQueryOriginal,\n useSuspenseInfiniteQuery as useSuspenseInfiniteQueryOriginal,\n useMutation as useMutationOriginal,\n} from '@tanstack/react-query'\nimport type { InfiniteData } from '@tanstack/react-query'\nimport type {\n PublicCollection,\n ServerCollection,\n ApiQueryOptions,\n PayloadFindResponse,\n PayloadMutationResponse,\n} from '../client/types'\nimport { type CollectionClient, type CollectionType } from '../collection'\nimport { SDKError } from '../internal/errors'\nimport { collectionKeys } from './query-keys'\n\n// ============================================================================\n// Query Params Types\n// ============================================================================\n\nexport interface CollectionQueryParams<T extends ServerCollection> {\n collection: T\n options?: ApiQueryOptions\n}\n\nexport interface CollectionDetailQueryParams<T extends ServerCollection> {\n collection: T\n id: string\n options?: ApiQueryOptions\n}\n\nexport interface CollectionInfiniteQueryParams<T extends ServerCollection> {\n collection: T\n options?: Omit<ApiQueryOptions, 'page'>\n pageSize?: number\n}\n\n// ============================================================================\n// Shared option types\n// ============================================================================\n\nexport interface QueryOptions<TQueryFnData = unknown, TData = TQueryFnData> {\n enabled?: boolean\n staleTime?: number\n gcTime?: number\n refetchOnWindowFocus?: boolean\n refetchOnMount?: boolean | 'always'\n refetchInterval?: number | false\n retry?: boolean | number\n select?: (data: TQueryFnData) => TData\n placeholderData?:\n | TQueryFnData\n | ((previousData: TData | undefined) => TQueryFnData | undefined)\n initialData?: TQueryFnData | (() => TQueryFnData)\n initialDataUpdatedAt?: number | (() => number | undefined)\n}\n\nexport type SuspenseQueryOptions<\n TQueryFnData = unknown,\n TData = TQueryFnData,\n> = Omit<QueryOptions<TQueryFnData, TData>, 'enabled' | 'placeholderData'>\n\n// placeholderData/initialData omitted: InfiniteData<T> structure is complex to construct\nexport interface InfiniteQueryOptions<\n TQueryFnData = unknown,\n TData = InfiniteData<TQueryFnData>,\n> {\n enabled?: boolean\n staleTime?: number\n gcTime?: number\n refetchOnWindowFocus?: boolean\n refetchOnMount?: boolean | 'always'\n refetchInterval?: number | false\n retry?: boolean | number\n select?: (data: InfiniteData<TQueryFnData>) => TData\n}\n\nexport type SuspenseInfiniteQueryOptions<\n TQueryFnData = unknown,\n TData = InfiniteData<TQueryFnData>,\n> = Omit<InfiniteQueryOptions<TQueryFnData, TData>, 'enabled'>\n\ninterface MutationCallbacks<TData> {\n onSuccess?: (data: TData) => void\n onError?: (error: SDKError) => void\n onSettled?: () => void\n}\n\n// ============================================================================\n// Product detail invalidation\n// ============================================================================\n\nconst PRODUCT_DETAIL_INVALIDATING_COLLECTIONS = new Set([\n 'products',\n 'product-variants',\n 'product-options',\n 'product-option-values',\n 'product-categories',\n 'product-tags',\n 'product-collections',\n 'brands',\n 'brand-logos',\n 'images',\n])\n\n// ============================================================================\n// Collection Hooks Mixin\n// ============================================================================\n\nconst DEFAULT_PAGE_SIZE = 20\n\nexport class CollectionHooks<TCollection extends ServerCollection = PublicCollection> {\n protected queryClient: QueryClient\n protected collectionClient: CollectionClient<TCollection>\n\n constructor(\n queryClient: QueryClient,\n collectionClient: CollectionClient<TCollection>,\n ) {\n this.queryClient = queryClient\n this.collectionClient = collectionClient\n }\n\n // ===== useQuery =====\n useQuery<\n T extends TCollection,\n TData = PayloadFindResponse<CollectionType<T>>,\n >(\n params: CollectionQueryParams<T>,\n options?: QueryOptions<PayloadFindResponse<CollectionType<T>>, TData>,\n ) {\n const { collection, options: queryOptions } = params\n const { placeholderData, ...restOptions } = (options ?? {}) as QueryOptions<\n PayloadFindResponse<CollectionType<T>>,\n TData\n >\n\n return useQueryOriginal({\n queryKey: collectionKeys(collection).list(queryOptions),\n queryFn: async () => {\n return await this.collectionClient\n .from(collection)\n .find(queryOptions)\n },\n ...restOptions,\n // NonFunctionGuard<T> incompatible with generic union types — safe cast\n ...(placeholderData !== undefined && {\n placeholderData: placeholderData as never,\n }),\n })\n }\n\n // ===== useSuspenseQuery =====\n useSuspenseQuery<\n T extends TCollection,\n TData = PayloadFindResponse<CollectionType<T>>,\n >(\n params: CollectionQueryParams<T>,\n options?: SuspenseQueryOptions<\n PayloadFindResponse<CollectionType<T>>,\n TData\n >,\n ) {\n const { collection, options: queryOptions } = params\n\n return useSuspenseQueryOriginal({\n queryKey: collectionKeys(collection).list(queryOptions),\n queryFn: async () => {\n return await this.collectionClient\n .from(collection)\n .find(queryOptions)\n },\n ...options,\n })\n }\n\n // ===== useQueryById =====\n useQueryById<T extends TCollection, TData = CollectionType<T>>(\n params: CollectionDetailQueryParams<T>,\n options?: QueryOptions<CollectionType<T>, TData>,\n ) {\n const { collection, id, options: queryOptions } = params\n const { placeholderData, ...restOptions } = (options ?? {}) as QueryOptions<\n CollectionType<T>,\n TData\n >\n\n return useQueryOriginal({\n queryKey: collectionKeys(collection).detail(id, queryOptions),\n queryFn: async () => {\n return await this.collectionClient\n .from(collection)\n .findById(id, queryOptions)\n },\n ...restOptions,\n // NonFunctionGuard<T> incompatible with generic union types — safe cast\n ...(placeholderData !== undefined && {\n placeholderData: placeholderData as never,\n }),\n })\n }\n\n // ===== useSuspenseQueryById =====\n useSuspenseQueryById<T extends TCollection, TData = CollectionType<T>>(\n params: CollectionDetailQueryParams<T>,\n options?: SuspenseQueryOptions<CollectionType<T>, TData>,\n ) {\n const { collection, id, options: queryOptions } = params\n\n return useSuspenseQueryOriginal({\n queryKey: collectionKeys(collection).detail(id, queryOptions),\n queryFn: async () => {\n return await this.collectionClient\n .from(collection)\n .findById(id, queryOptions)\n },\n ...options,\n })\n }\n\n // ===== useInfiniteQuery =====\n useInfiniteQuery<\n T extends TCollection,\n TData = InfiniteData<PayloadFindResponse<CollectionType<T>>>,\n >(\n params: CollectionInfiniteQueryParams<T>,\n options?: InfiniteQueryOptions<\n PayloadFindResponse<CollectionType<T>>,\n TData\n >,\n ) {\n const {\n collection,\n options: queryOptions,\n pageSize = DEFAULT_PAGE_SIZE,\n } = params\n\n return useInfiniteQueryOriginal({\n queryKey: collectionKeys(collection).infinite(queryOptions),\n queryFn: async ({ pageParam }) => {\n const response = await this.collectionClient\n .from(collection)\n .find({ ...queryOptions, page: pageParam, limit: pageSize })\n return response\n },\n initialPageParam: 1,\n getNextPageParam: (lastPage: PayloadFindResponse<CollectionType<T>>) => {\n return lastPage.hasNextPage ? lastPage.nextPage : undefined\n },\n ...options,\n })\n }\n\n // ===== useSuspenseInfiniteQuery =====\n useSuspenseInfiniteQuery<\n T extends TCollection,\n TData = InfiniteData<PayloadFindResponse<CollectionType<T>>>,\n >(\n params: CollectionInfiniteQueryParams<T>,\n options?: SuspenseInfiniteQueryOptions<\n PayloadFindResponse<CollectionType<T>>,\n TData\n >,\n ) {\n const {\n collection,\n options: queryOptions,\n pageSize = DEFAULT_PAGE_SIZE,\n } = params\n\n return useSuspenseInfiniteQueryOriginal({\n queryKey: collectionKeys(collection).infinite(queryOptions),\n queryFn: async ({ pageParam }) => {\n const response = await this.collectionClient\n .from(collection)\n .find({ ...queryOptions, page: pageParam, limit: pageSize })\n return response\n },\n initialPageParam: 1,\n getNextPageParam: (lastPage: PayloadFindResponse<CollectionType<T>>) => {\n return lastPage.hasNextPage ? lastPage.nextPage : undefined\n },\n ...options,\n })\n }\n\n // ===== prefetchQuery =====\n async prefetchQuery<T extends TCollection>(\n params: CollectionQueryParams<T>,\n options?: { staleTime?: number },\n ) {\n const { collection, options: queryOptions } = params\n\n return this.queryClient.prefetchQuery({\n queryKey: collectionKeys(collection).list(queryOptions),\n queryFn: async () => {\n return await this.collectionClient\n .from(collection)\n .find(queryOptions)\n },\n ...options,\n })\n }\n\n // ===== prefetchQueryById =====\n async prefetchQueryById<T extends TCollection>(\n params: CollectionDetailQueryParams<T>,\n options?: { staleTime?: number },\n ) {\n const { collection, id, options: queryOptions } = params\n\n return this.queryClient.prefetchQuery({\n queryKey: collectionKeys(collection).detail(id, queryOptions),\n queryFn: async () => {\n return await this.collectionClient\n .from(collection)\n .findById(id, queryOptions)\n },\n ...options,\n })\n }\n\n // ===== prefetchInfiniteQuery =====\n async prefetchInfiniteQuery<T extends TCollection>(\n params: CollectionInfiniteQueryParams<T>,\n options?: { pages?: number; staleTime?: number },\n ) {\n const {\n collection,\n options: queryOptions,\n pageSize = DEFAULT_PAGE_SIZE,\n } = params\n\n return this.queryClient.prefetchInfiniteQuery({\n queryKey: collectionKeys(collection).infinite(queryOptions),\n queryFn: async ({ pageParam }) => {\n const response = await this.collectionClient\n .from(collection)\n .find({ ...queryOptions, page: pageParam, limit: pageSize })\n return response\n },\n initialPageParam: 1,\n getNextPageParam: (lastPage: PayloadFindResponse<CollectionType<T>>) => {\n return lastPage.hasNextPage ? lastPage.nextPage : undefined\n },\n pages: options?.pages ?? 1,\n staleTime: options?.staleTime,\n })\n }\n\n // ===== Mutation Hooks =====\n\n useCreate<T extends TCollection>(\n params: { collection: T },\n options?: MutationCallbacks<PayloadMutationResponse<CollectionType<T>>>,\n ) {\n const { collection } = params\n\n return useMutationOriginal<\n PayloadMutationResponse<CollectionType<T>>,\n SDKError,\n {\n data: Partial<CollectionType<T>>\n file?: File | Blob\n filename?: string\n }\n >({\n mutationFn: async (variables) => {\n return await this.collectionClient\n .from(collection)\n .create(\n variables.data,\n variables.file\n ? { file: variables.file, filename: variables.filename }\n : undefined,\n )\n },\n onSuccess: (data) => {\n this.queryClient.invalidateQueries({\n queryKey: collectionKeys(collection).all,\n })\n if (PRODUCT_DETAIL_INVALIDATING_COLLECTIONS.has(collection)) {\n this.queryClient.invalidateQueries({ queryKey: ['products', 'detail'] })\n }\n options?.onSuccess?.(data)\n },\n onError: options?.onError,\n onSettled: options?.onSettled,\n })\n }\n\n useUpdate<T extends TCollection>(\n params: { collection: T },\n options?: MutationCallbacks<PayloadMutationResponse<CollectionType<T>>>,\n ) {\n const { collection } = params\n\n return useMutationOriginal<\n PayloadMutationResponse<CollectionType<T>>,\n SDKError,\n {\n id: string\n data: Partial<CollectionType<T>>\n file?: File | Blob\n filename?: string\n }\n >({\n mutationFn: async (variables) => {\n return await this.collectionClient\n .from(collection)\n .update(\n variables.id,\n variables.data,\n variables.file\n ? { file: variables.file, filename: variables.filename }\n : undefined,\n )\n },\n onSuccess: (data) => {\n this.queryClient.invalidateQueries({\n queryKey: collectionKeys(collection).all,\n })\n if (PRODUCT_DETAIL_INVALIDATING_COLLECTIONS.has(collection)) {\n this.queryClient.invalidateQueries({ queryKey: ['products', 'detail'] })\n }\n options?.onSuccess?.(data)\n },\n onError: options?.onError,\n onSettled: options?.onSettled,\n })\n }\n\n useRemove<T extends TCollection>(\n params: { collection: T },\n options?: MutationCallbacks<CollectionType<T>>,\n ) {\n const { collection } = params\n\n return useMutationOriginal<CollectionType<T>, SDKError, string>({\n mutationFn: async (id) => {\n return await this.collectionClient.from(collection).remove(id)\n },\n onSuccess: (data) => {\n this.queryClient.invalidateQueries({\n queryKey: collectionKeys(collection).all,\n })\n if (PRODUCT_DETAIL_INVALIDATING_COLLECTIONS.has(collection)) {\n this.queryClient.invalidateQueries({ queryKey: ['products', 'detail'] })\n }\n options?.onSuccess?.(data)\n },\n onError: options?.onError,\n onSettled: options?.onSettled,\n })\n }\n\n // ===== Cache Utilities =====\n\n invalidateQueries<T extends TCollection>(\n collection: T,\n type?: 'list' | 'detail' | 'infinite',\n ) {\n const queryKey = type ? [collection, type] : [collection]\n return this.queryClient.invalidateQueries({ queryKey })\n }\n\n getQueryData<T extends TCollection>(\n collection: T,\n type: 'list',\n options?: ApiQueryOptions,\n ): PayloadFindResponse<CollectionType<T>> | undefined\n getQueryData<T extends TCollection>(\n collection: T,\n type: 'detail',\n id: string,\n options?: ApiQueryOptions,\n ): CollectionType<T> | null | undefined\n getQueryData<T extends TCollection>(\n collection: T,\n type: 'list' | 'detail',\n idOrOptions?: string | ApiQueryOptions,\n options?: ApiQueryOptions,\n ) {\n if (type === 'list') {\n return this.queryClient.getQueryData(\n collectionKeys(collection).list(idOrOptions as ApiQueryOptions),\n )\n }\n return this.queryClient.getQueryData(\n collectionKeys(collection).detail(idOrOptions as string, options),\n )\n }\n\n setQueryData<T extends TCollection>(\n collection: T,\n type: 'list',\n data: PayloadFindResponse<CollectionType<T>>,\n options?: ApiQueryOptions,\n ): void\n setQueryData<T extends TCollection>(\n collection: T,\n type: 'detail',\n id: string,\n data: CollectionType<T> | null,\n options?: ApiQueryOptions,\n ): void\n setQueryData<T extends TCollection>(\n collection: T,\n type: 'list' | 'detail',\n dataOrId: PayloadFindResponse<CollectionType<T>> | string,\n dataOrOptions?: CollectionType<T> | null | ApiQueryOptions,\n options?: ApiQueryOptions,\n ) {\n if (type === 'list') {\n this.queryClient.setQueryData(\n collectionKeys(collection).list(dataOrOptions as ApiQueryOptions),\n dataOrId as PayloadFindResponse<CollectionType<T>>,\n )\n } else {\n this.queryClient.setQueryData(\n collectionKeys(collection).detail(dataOrId as string, options),\n dataOrOptions as CollectionType<T> | null,\n )\n }\n }\n}\n","import {\n QueryClient,\n useQuery as useQueryOriginal,\n useMutation as useMutationOriginal,\n} from '@tanstack/react-query'\nimport type { CustomerAuth } from '../customer/customer-auth'\nimport type {\n CustomerAuthResponse,\n CustomerRefreshResponse,\n CustomerProfile,\n CustomerRegisterData,\n CustomerLoginData,\n UpdateProfileData,\n} from '../customer/types'\nimport { createConfigError, SDKError } from '../internal/errors'\nimport { customerKeys } from './query-keys'\n\n// ============================================================================\n// Mutation helper\n// ============================================================================\n\ninterface MutationCallbacks<TData> {\n onSuccess?: (data: TData) => void\n onError?: (error: SDKError) => void\n onSettled?: () => void\n}\n\nfunction createMutation<TData, TVariables>(\n mutationFn: (variables: TVariables) => Promise<TData>,\n callbacks?: MutationCallbacks<TData>,\n onSuccessExtra?: (data: TData) => void,\n) {\n return useMutationOriginal({\n mutationFn,\n onSuccess: (data) => {\n onSuccessExtra?.(data)\n callbacks?.onSuccess?.(data)\n },\n onError: callbacks?.onError,\n onSettled: callbacks?.onSettled,\n })\n}\n\n// ============================================================================\n// Customer Hooks Mixin\n// ============================================================================\n\nexport class CustomerHooks {\n private queryClient: QueryClient\n private customerAuth?: CustomerAuth\n\n constructor(queryClient: QueryClient, customerAuth?: CustomerAuth) {\n this.queryClient = queryClient\n this.customerAuth = customerAuth\n }\n\n private ensureCustomerAuth(): CustomerAuth {\n if (!this.customerAuth) {\n throw createConfigError(\n 'Customer hooks require Client. Use createClient() instead of createServerClient().',\n )\n }\n return this.customerAuth\n }\n\n private invalidateMe = () => {\n this.queryClient.invalidateQueries({ queryKey: customerKeys.me() })\n }\n\n // ===== useCustomerMe =====\n useCustomerMe(options?: {\n enabled?: boolean\n staleTime?: number\n gcTime?: number\n refetchOnWindowFocus?: boolean\n refetchOnMount?: boolean | 'always'\n refetchInterval?: number | false\n retry?: boolean | number\n }) {\n return useQueryOriginal({\n queryKey: customerKeys.me(),\n queryFn: async () => {\n return await this.ensureCustomerAuth().me()\n },\n ...options,\n enabled:\n (options?.enabled ?? true) && !!this.customerAuth?.isAuthenticated(),\n })\n }\n\n // ===== Mutations =====\n\n useCustomerLogin(options?: MutationCallbacks<CustomerAuthResponse>) {\n return createMutation(\n (data: CustomerLoginData) => this.ensureCustomerAuth().login(data),\n options,\n this.invalidateMe,\n )\n }\n\n useCustomerRegister(\n options?: MutationCallbacks<{ customer: CustomerProfile }>,\n ) {\n return createMutation(\n (data: CustomerRegisterData) => this.ensureCustomerAuth().register(data),\n options,\n )\n }\n\n useCustomerLogout(options?: MutationCallbacks<void>) {\n return useMutationOriginal({\n mutationFn: async () => {\n this.ensureCustomerAuth().logout()\n },\n onSuccess: () => {\n this.queryClient.removeQueries({ queryKey: customerKeys.all })\n options?.onSuccess?.()\n },\n onError: options?.onError,\n onSettled: options?.onSettled,\n })\n }\n\n useCustomerForgotPassword(options?: MutationCallbacks<void>) {\n return createMutation(\n (email: string) =>\n this.ensureCustomerAuth()\n .forgotPassword(email)\n .then(() => {}),\n options,\n )\n }\n\n useCustomerResetPassword(options?: MutationCallbacks<void>) {\n return createMutation(\n (data: { token: string; password: string }) =>\n this.ensureCustomerAuth()\n .resetPassword(data.token, data.password)\n .then(() => {}),\n options,\n )\n }\n\n useCustomerRefreshToken(\n options?: MutationCallbacks<CustomerRefreshResponse>,\n ) {\n return createMutation(\n () => this.ensureCustomerAuth().refreshToken(),\n options,\n this.invalidateMe,\n )\n }\n\n useCustomerUpdateProfile(options?: MutationCallbacks<CustomerProfile>) {\n return createMutation(\n (data: UpdateProfileData) =>\n this.ensureCustomerAuth().updateProfile(data),\n options,\n this.invalidateMe,\n )\n }\n\n useCustomerChangePassword(options?: MutationCallbacks<void>) {\n return createMutation(\n (data: { currentPassword: string; newPassword: string }) =>\n this.ensureCustomerAuth()\n .changePassword(data.currentPassword, data.newPassword)\n .then(() => {}),\n options,\n )\n }\n\n // ===== Customer Cache Utilities =====\n\n invalidateCustomerQueries() {\n return this.queryClient.invalidateQueries({ queryKey: customerKeys.all })\n }\n\n getCustomerData(): CustomerProfile | null | undefined {\n return this.queryClient.getQueryData(customerKeys.me())\n }\n\n setCustomerData(data: CustomerProfile | null) {\n this.queryClient.setQueryData(customerKeys.me(), data)\n }\n}\n","export class SDKError extends Error {\n readonly code: string\n readonly status?: number\n readonly details?: unknown\n readonly userMessage?: string\n readonly suggestion?: string\n readonly requestId?: string\n\n constructor(\n code: string,\n message: string,\n status?: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n ) {\n super(message)\n this.name = 'SDKError'\n this.code = code\n this.status = status\n this.details = details\n this.userMessage = userMessage\n this.suggestion = suggestion\n this.requestId = requestId\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, new.target)\n }\n }\n\n getUserMessage(): string {\n return this.userMessage || this.message\n }\n\n toJSON() {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n status: this.status,\n details: this.details,\n userMessage: this.userMessage,\n suggestion: this.suggestion,\n ...(this.requestId !== undefined && { requestId: this.requestId }),\n }\n }\n}\n\nexport class NetworkError extends SDKError {\n constructor(\n message: string,\n status?: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n ) {\n super('NETWORK_ERROR', message, status, details, userMessage, suggestion)\n this.name = 'NetworkError'\n }\n}\n\nexport class ValidationError extends SDKError {\n constructor(\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n status = 400,\n ) {\n super('VALIDATION_ERROR', message, status, details, userMessage, suggestion)\n this.name = 'ValidationError'\n }\n}\n\nexport class ApiError extends SDKError {\n constructor(\n message: string,\n status: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n ) {\n super(\n 'API_ERROR',\n message,\n status,\n details,\n userMessage,\n suggestion,\n requestId,\n )\n this.name = 'ApiError'\n }\n}\n\nexport class ConfigError extends SDKError {\n constructor(\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n ) {\n super('CONFIG_ERROR', message, undefined, details, userMessage, suggestion)\n this.name = 'ConfigError'\n }\n}\n\nexport class TimeoutError extends SDKError {\n constructor(\n message = 'Request timed out.',\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n ) {\n super('TIMEOUT_ERROR', message, 408, details, userMessage, suggestion)\n this.name = 'TimeoutError'\n }\n}\n\nexport class GoneError extends SDKError {\n constructor(\n message = 'The requested resource is no longer available.',\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n ) {\n super('GONE_ERROR', message, 410, details, userMessage, suggestion)\n this.name = 'GoneError'\n }\n}\n\nexport class ServiceUnavailableError extends SDKError {\n readonly retryAfter?: number\n\n constructor(\n message = 'Service temporarily unavailable.',\n retryAfter?: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n ) {\n super(\n 'SERVICE_UNAVAILABLE_ERROR',\n message,\n 503,\n details,\n userMessage,\n suggestion,\n )\n this.name = 'ServiceUnavailableError'\n this.retryAfter = retryAfter\n }\n}\n\nexport class UsageLimitError extends SDKError {\n readonly usage: { limit: number; current: number; remaining: number }\n\n constructor(\n message: string,\n usage: { limit: number; current: number; remaining: number },\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n ) {\n super('USAGE_LIMIT_ERROR', message, 429, details, userMessage, suggestion)\n this.name = 'UsageLimitError'\n this.usage = usage\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n usage: this.usage,\n }\n }\n}\n\nexport class AuthError extends SDKError {\n constructor(\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n ) {\n super(\n 'auth_error',\n message,\n 401,\n details,\n userMessage,\n suggestion,\n requestId,\n )\n this.name = 'AuthError'\n }\n}\n\nexport class PermissionError extends SDKError {\n constructor(\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n ) {\n super(\n 'permission_error',\n message,\n 403,\n details,\n userMessage,\n suggestion,\n requestId,\n )\n this.name = 'PermissionError'\n }\n}\n\nexport class NotFoundError extends SDKError {\n constructor(\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n ) {\n super(\n 'not_found',\n message,\n 404,\n details,\n userMessage,\n suggestion,\n requestId,\n )\n this.name = 'NotFoundError'\n }\n}\n\nexport class ConflictError extends SDKError {\n constructor(\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n ) {\n super('conflict', message, 409, details, userMessage, suggestion, requestId)\n this.name = 'ConflictError'\n }\n}\n\nexport class RateLimitError extends SDKError {\n readonly retryAfter?: number\n\n constructor(\n message: string,\n retryAfter?: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n ) {\n super(\n 'rate_limit_exceeded',\n message,\n 429,\n details,\n userMessage,\n suggestion,\n requestId,\n )\n this.name = 'RateLimitError'\n this.retryAfter = retryAfter\n }\n}\n\nexport function isSDKError(error: unknown): error is SDKError {\n return error instanceof SDKError\n}\n\nexport function isNetworkError(error: unknown): error is NetworkError {\n return error instanceof NetworkError\n}\n\nexport function isValidationError(error: unknown): error is ValidationError {\n return error instanceof ValidationError\n}\n\nexport function isApiError(error: unknown): error is ApiError {\n return error instanceof ApiError\n}\n\nexport function isConfigError(error: unknown): error is ConfigError {\n return error instanceof ConfigError\n}\n\nexport function isTimeoutError(error: unknown): error is TimeoutError {\n return error instanceof TimeoutError\n}\n\nexport function isGoneError(error: unknown): error is GoneError {\n return error instanceof GoneError\n}\n\nexport function isServiceUnavailableError(\n error: unknown,\n): error is ServiceUnavailableError {\n return error instanceof ServiceUnavailableError\n}\n\nexport function isUsageLimitError(error: unknown): error is UsageLimitError {\n return error instanceof UsageLimitError\n}\n\nexport function isAuthError(error: unknown): error is AuthError {\n return error instanceof AuthError\n}\n\nexport function isPermissionError(error: unknown): error is PermissionError {\n return error instanceof PermissionError\n}\n\nexport function isNotFoundError(error: unknown): error is NotFoundError {\n return error instanceof NotFoundError\n}\n\nexport function isConflictError(error: unknown): error is ConflictError {\n return error instanceof ConflictError\n}\n\nexport function isRateLimitError(error: unknown): error is RateLimitError {\n return error instanceof RateLimitError\n}\n\nexport const createNetworkError = (\n message: string,\n status?: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n) => new NetworkError(message, status, details, userMessage, suggestion)\n\nexport const createValidationError = (\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n status?: number,\n) => new ValidationError(message, details, userMessage, suggestion, status)\n\nexport const createApiError = (\n message: string,\n status: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n) => new ApiError(message, status, details, userMessage, suggestion, requestId)\n\nexport const createConfigError = (\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n) => new ConfigError(message, details, userMessage, suggestion)\n\nexport const createTimeoutError = (\n message?: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n) => new TimeoutError(message, details, userMessage, suggestion)\n\nexport const createGoneError = (\n message?: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n) => new GoneError(message, details, userMessage, suggestion)\n\nexport const createServiceUnavailableError = (\n message?: string,\n retryAfter?: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n) =>\n new ServiceUnavailableError(\n message,\n retryAfter,\n details,\n userMessage,\n suggestion,\n )\n\nexport const createUsageLimitError = (\n message: string,\n usage: { limit: number; current: number; remaining: number },\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n) => new UsageLimitError(message, usage, details, userMessage, suggestion)\n\nexport const createAuthError = (\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n) => new AuthError(message, details, userMessage, suggestion, requestId)\n\nexport const createPermissionError = (\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n) => new PermissionError(message, details, userMessage, suggestion, requestId)\n\nexport const createNotFoundError = (\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n) => new NotFoundError(message, details, userMessage, suggestion, requestId)\n\nexport const createConflictError = (\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n) => new ConflictError(message, details, userMessage, suggestion, requestId)\n\nexport const createRateLimitError = (\n message: string,\n retryAfter?: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n) =>\n new RateLimitError(\n message,\n retryAfter,\n details,\n userMessage,\n suggestion,\n requestId,\n )\n","import {\n QueryClient,\n useInfiniteQuery as useInfiniteQueryOriginal,\n useQuery as useQueryOriginal,\n useSuspenseInfiniteQuery as useSuspenseInfiniteQueryOriginal,\n useSuspenseQuery as useSuspenseQueryOriginal,\n} from '@tanstack/react-query'\nimport type { InfiniteData, UseQueryResult } from '@tanstack/react-query'\nimport type {\n ApiQueryOptions,\n PayloadFindResponse,\n PublicCollection,\n ServerCollection,\n} from '../client/types'\nimport type { CustomerAuth } from '../customer/customer-auth'\nimport type { CollectionClient } from '../collection'\nimport type { ProductListingGroupsItem, ProductDetail, ProductDetailParams } from '../api'\nimport { CollectionHooks } from './collection-hooks'\nimport { CustomerHooks } from './customer-hooks'\nimport { productKeys } from './query-keys'\nimport type {\n InfiniteQueryOptions,\n QueryOptions,\n SuspenseInfiniteQueryOptions,\n SuspenseQueryOptions,\n} from './collection-hooks'\n\n// Re-export everything from sub-modules for barrel compatibility\nexport { collectionKeys, customerKeys } from './query-keys'\nexport { productKeys } from './query-keys'\nexport type {\n CollectionQueryParams,\n CollectionDetailQueryParams,\n CollectionInfiniteQueryParams,\n QueryOptions,\n SuspenseQueryOptions,\n InfiniteQueryOptions,\n SuspenseInfiniteQueryOptions,\n} from './collection-hooks'\n\nexport type ProductListingGroupsQueryOptions = Pick<\n ApiQueryOptions,\n 'page' | 'limit' | 'sort' | 'where'\n>\n\nexport type ReadOnlyQueryHooks = Omit<\n QueryHooks<PublicCollection>,\n 'useCreate' | 'useUpdate' | 'useRemove'\n>\n\n/**\n * Composes CollectionHooks + CustomerHooks into a single API surface.\n * All methods are delegated; no logic lives here.\n */\ninterface ProductDetailCallable {\n product: {\n detail: (params: ProductDetailParams) => Promise<ProductDetail | null>\n }\n}\n\nexport class QueryHooks<\n TCollection extends ServerCollection = PublicCollection,\n> extends CollectionHooks<TCollection> {\n private _customer: CustomerHooks\n private _commerce?: ProductDetailCallable\n\n constructor(\n queryClient: QueryClient,\n collectionClient: CollectionClient<TCollection>,\n customerAuth?: CustomerAuth,\n commerceClient?: ProductDetailCallable,\n ) {\n super(queryClient, collectionClient)\n this._customer = new CustomerHooks(queryClient, customerAuth)\n this._commerce = commerceClient\n }\n\n // --- Customer hooks delegation ---\n useCustomerMe: CustomerHooks['useCustomerMe'] = (...args) =>\n this._customer.useCustomerMe(...args)\n useCustomerLogin: CustomerHooks['useCustomerLogin'] = (...args) =>\n this._customer.useCustomerLogin(...args)\n useCustomerRegister: CustomerHooks['useCustomerRegister'] = (...args) =>\n this._customer.useCustomerRegister(...args)\n useCustomerLogout: CustomerHooks['useCustomerLogout'] = (...args) =>\n this._customer.useCustomerLogout(...args)\n useCustomerForgotPassword: CustomerHooks['useCustomerForgotPassword'] = (\n ...args\n ) => this._customer.useCustomerForgotPassword(...args)\n useCustomerResetPassword: CustomerHooks['useCustomerResetPassword'] = (\n ...args\n ) => this._customer.useCustomerResetPassword(...args)\n useCustomerRefreshToken: CustomerHooks['useCustomerRefreshToken'] = (\n ...args\n ) => this._customer.useCustomerRefreshToken(...args)\n useCustomerUpdateProfile: CustomerHooks['useCustomerUpdateProfile'] = (\n ...args\n ) => this._customer.useCustomerUpdateProfile(...args)\n useCustomerChangePassword: CustomerHooks['useCustomerChangePassword'] = (\n ...args\n ) => this._customer.useCustomerChangePassword(...args)\n\n // --- Customer cache delegation ---\n invalidateCustomerQueries: CustomerHooks['invalidateCustomerQueries'] = () =>\n this._customer.invalidateCustomerQueries()\n getCustomerData: CustomerHooks['getCustomerData'] = () =>\n this._customer.getCustomerData()\n setCustomerData: CustomerHooks['setCustomerData'] = (data) =>\n this._customer.setCustomerData(data)\n\n useProductListingGroupsQuery<\n TData = PayloadFindResponse<ProductListingGroupsItem>,\n >(\n params: { options?: ProductListingGroupsQueryOptions },\n options?: QueryOptions<PayloadFindResponse<ProductListingGroupsItem>, TData>,\n ) {\n const queryOptions = params.options\n const { placeholderData, ...restOptions } = (options ?? {}) as QueryOptions<\n PayloadFindResponse<ProductListingGroupsItem>,\n TData\n >\n\n return useQueryOriginal({\n queryKey: productKeys.listingGroups(queryOptions),\n queryFn: async () =>\n this.collectionClient.requestFindEndpoint<ProductListingGroupsItem>(\n '/api/products/listing-groups/query',\n { options: queryOptions },\n ),\n ...restOptions,\n ...(placeholderData !== undefined && {\n placeholderData: placeholderData as never,\n }),\n })\n }\n\n useSuspenseProductListingGroupsQuery<\n TData = PayloadFindResponse<ProductListingGroupsItem>,\n >(\n params: { options?: ProductListingGroupsQueryOptions },\n options?: SuspenseQueryOptions<\n PayloadFindResponse<ProductListingGroupsItem>,\n TData\n >,\n ) {\n const queryOptions = params.options\n\n return useSuspenseQueryOriginal({\n queryKey: productKeys.listingGroups(queryOptions),\n queryFn: async () =>\n this.collectionClient.requestFindEndpoint<ProductListingGroupsItem>(\n '/api/products/listing-groups/query',\n { options: queryOptions },\n ),\n ...options,\n })\n }\n\n useInfiniteProductListingGroupsQuery<\n TData = InfiniteData<PayloadFindResponse<ProductListingGroupsItem>>,\n >(\n params: {\n options?: Omit<ProductListingGroupsQueryOptions, 'page' | 'limit'>\n pageSize?: number\n },\n options?: InfiniteQueryOptions<\n PayloadFindResponse<ProductListingGroupsItem>,\n TData\n >,\n ) {\n const {\n options: queryOptions,\n pageSize = 20,\n } = params\n\n return useInfiniteQueryOriginal({\n queryKey: productKeys.listingGroupsInfinite(queryOptions),\n queryFn: async ({ pageParam }) =>\n this.collectionClient.requestFindEndpoint<ProductListingGroupsItem>(\n '/api/products/listing-groups/query',\n {\n options: { ...queryOptions, page: pageParam, limit: pageSize },\n },\n ),\n initialPageParam: 1,\n getNextPageParam: (\n lastPage: PayloadFindResponse<ProductListingGroupsItem>,\n ) => (lastPage.hasNextPage ? lastPage.nextPage : undefined),\n ...options,\n })\n }\n\n useSuspenseInfiniteProductListingGroupsQuery<\n TData = InfiniteData<PayloadFindResponse<ProductListingGroupsItem>>,\n >(\n params: {\n options?: Omit<ProductListingGroupsQueryOptions, 'page' | 'limit'>\n pageSize?: number\n },\n options?: SuspenseInfiniteQueryOptions<\n PayloadFindResponse<ProductListingGroupsItem>,\n TData\n >,\n ) {\n const {\n options: queryOptions,\n pageSize = 20,\n } = params\n\n return useSuspenseInfiniteQueryOriginal({\n queryKey: productKeys.listingGroupsInfinite(queryOptions),\n queryFn: async ({ pageParam }) =>\n this.collectionClient.requestFindEndpoint<ProductListingGroupsItem>(\n '/api/products/listing-groups/query',\n {\n options: { ...queryOptions, page: pageParam, limit: pageSize },\n },\n ),\n initialPageParam: 1,\n getNextPageParam: (\n lastPage: PayloadFindResponse<ProductListingGroupsItem>,\n ) => (lastPage.hasNextPage ? lastPage.nextPage : undefined),\n ...options,\n })\n }\n\n async prefetchProductListingGroupsQuery(\n params: { options?: ProductListingGroupsQueryOptions },\n options?: { staleTime?: number },\n ) {\n const queryOptions = params.options\n\n return this.queryClient.prefetchQuery({\n queryKey: productKeys.listingGroups(queryOptions),\n queryFn: async () =>\n this.collectionClient.requestFindEndpoint<ProductListingGroupsItem>(\n '/api/products/listing-groups/query',\n { options: queryOptions },\n ),\n ...options,\n })\n }\n\n async prefetchInfiniteProductListingGroupsQuery(\n params: {\n options?: Omit<ProductListingGroupsQueryOptions, 'page' | 'limit'>\n pageSize?: number\n },\n options?: { pages?: number; staleTime?: number },\n ) {\n const {\n options: queryOptions,\n pageSize = 20,\n } = params\n\n return this.queryClient.prefetchInfiniteQuery({\n queryKey: productKeys.listingGroupsInfinite(queryOptions),\n queryFn: async ({ pageParam }) =>\n this.collectionClient.requestFindEndpoint<ProductListingGroupsItem>(\n '/api/products/listing-groups/query',\n {\n options: { ...queryOptions, page: pageParam, limit: pageSize },\n },\n ),\n initialPageParam: 1,\n getNextPageParam: (\n lastPage: PayloadFindResponse<ProductListingGroupsItem>,\n ) => (lastPage.hasNextPage ? lastPage.nextPage : undefined),\n pages: options?.pages ?? 1,\n staleTime: options?.staleTime,\n })\n }\n\n useProductDetail(\n params: { slug: string } | { id: string },\n options?: { enabled?: boolean },\n ): UseQueryResult<ProductDetail | null> {\n const discriminator = 'slug' in params ? params.slug : params.id\n const enabled = options?.enabled !== false && Boolean(discriminator)\n\n return useQueryOriginal({\n queryKey: productKeys.detail(params),\n queryFn: () => this._commerce!.product.detail(params),\n enabled,\n }) as UseQueryResult<ProductDetail | null>\n }\n\n useProductDetailBySlug(\n slug: string,\n options?: { enabled?: boolean },\n ): UseQueryResult<ProductDetail | null> {\n return this.useProductDetail({ slug }, options)\n }\n\n useProductDetailById(\n id: string,\n options?: { enabled?: boolean },\n ): UseQueryResult<ProductDetail | null> {\n return this.useProductDetail({ id }, options)\n }\n}\n","/**\n * Fetch-based SSE connection manager for real-time collection change events.\n * Uses fetch + ReadableStream to support custom auth headers (unlike native EventSource).\n */\n\nexport interface RealtimeEvent {\n collection: string\n operation: string\n id: string | null\n timestamp: string\n}\n\nexport type RealtimeListener = (event: RealtimeEvent) => void\n\nconst INITIAL_RECONNECT_DELAY = 1_000\nconst MAX_RECONNECT_DELAY = 30_000\nconst RECONNECT_BACKOFF_FACTOR = 2\nconst MAX_NO_TOKEN_RETRIES = 5\n\nexport class RealtimeConnection {\n private abortController: AbortController | null = null\n private reconnectAttempt = 0\n private noTokenAttempts = 0\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null\n private listeners = new Set<RealtimeListener>()\n private _connected = false\n\n constructor(\n private baseUrl: string,\n private publishableKey: string,\n private getToken: () => string | null,\n private collections?: string[],\n ) {}\n\n get connected(): boolean {\n return this._connected\n }\n\n addListener(fn: RealtimeListener): () => void {\n this.listeners.add(fn)\n return () => this.listeners.delete(fn)\n }\n\n connect(): void {\n if (this.abortController) return // Already connecting/connected\n\n this.abortController = new AbortController()\n this.startStream(this.abortController.signal)\n }\n\n disconnect(): void {\n this._connected = false\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer)\n this.reconnectTimer = null\n }\n if (this.abortController) {\n this.abortController.abort()\n this.abortController = null\n }\n this.reconnectAttempt = 0\n this.noTokenAttempts = 0\n }\n\n private async startStream(signal: AbortSignal): Promise<void> {\n const token = this.getToken()\n if (!token) {\n this.noTokenAttempts++\n if (this.noTokenAttempts >= MAX_NO_TOKEN_RETRIES) {\n // Stop reconnecting — no token available after multiple attempts\n this._connected = false\n this.abortController = null\n return\n }\n this.scheduleReconnect()\n return\n }\n this.noTokenAttempts = 0\n\n const params = this.collections?.length\n ? `?collections=${this.collections.join(',')}`\n : ''\n const url = `${this.baseUrl}/api/events/stream${params}`\n\n try {\n const response = await fetch(url, {\n headers: {\n 'X-Publishable-Key': this.publishableKey,\n Authorization: `Bearer ${token}`,\n },\n signal,\n })\n\n if (!response.ok) {\n if (response.status === 401) {\n // Token expired — try reconnecting (will get fresh token)\n this.scheduleReconnect()\n return\n }\n throw new Error(`SSE connection failed: ${response.status}`)\n }\n\n if (!response.body) {\n throw new Error('SSE response has no body')\n }\n\n this._connected = true\n this.reconnectAttempt = 0\n\n await this.readStream(response.body, signal)\n } catch {\n if (signal.aborted) return // Intentional disconnect\n this._connected = false\n this.scheduleReconnect()\n }\n }\n\n private async readStream(\n body: ReadableStream<Uint8Array>,\n signal: AbortSignal,\n ): Promise<void> {\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n let currentEvent = ''\n let currentData = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done || signal.aborted) break\n\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? '' // Keep incomplete last line in buffer\n\n for (const line of lines) {\n if (line.startsWith('event: ')) {\n currentEvent = line.slice(7)\n } else if (line.startsWith('data: ')) {\n currentData += (currentData ? '\\n' : '') + line.slice(6)\n } else if (line === '') {\n // Empty line = end of event\n if (currentEvent === 'collection:change' && currentData) {\n try {\n const event: RealtimeEvent = JSON.parse(currentData)\n for (const listener of this.listeners) {\n try {\n listener(event)\n } catch {\n // Listener error — ignore\n }\n }\n } catch {\n // Malformed JSON — ignore\n }\n }\n currentEvent = ''\n currentData = ''\n }\n // Ignore comment lines (: heartbeat)\n }\n }\n } catch {\n // Stream read error\n } finally {\n reader.releaseLock()\n this._connected = false\n if (!signal.aborted) {\n this.scheduleReconnect()\n }\n }\n }\n\n private scheduleReconnect(): void {\n if (this.reconnectTimer) return\n\n const delay = Math.min(\n INITIAL_RECONNECT_DELAY *\n Math.pow(RECONNECT_BACKOFF_FACTOR, this.reconnectAttempt),\n MAX_RECONNECT_DELAY,\n )\n this.reconnectAttempt++\n\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null\n this.abortController = new AbortController()\n this.startStream(this.abortController.signal)\n }, delay)\n }\n}\n","/**\n * Resolves a Payload CMS relation field value.\n * When depth is 0, relation fields return just the ID (string or number).\n * When depth > 0, they return the full document object (T).\n * This utility normalizes both cases to T | null.\n *\n * @param ref - The relation field value (T, string, number, null, or undefined)\n * @returns The resolved document object, or null if not populated\n */\nexport const resolveRelation = <T>(\n ref: T | string | number | null | undefined,\n): T | null => {\n if (\n typeof ref === 'string' ||\n typeof ref === 'number' ||\n ref === null ||\n ref === undefined\n )\n return null\n return ref\n}\n","import { resolveRelation } from '../../utils/types'\n\nexport interface MetadataImage {\n url: string\n width?: number\n height?: number\n alt?: string\n}\n\nexport interface Metadata {\n title?: string\n description?: string\n robots?: {\n index?: boolean\n follow?: boolean\n }\n alternates?: {\n canonical?: string\n }\n openGraph?: {\n title?: string\n description?: string\n siteName?: string\n images?: MetadataImage[]\n }\n twitter?: {\n card?: 'summary' | 'summary_large_image'\n title?: string\n description?: string\n images?: string[]\n }\n}\n\nexport interface ImageLike {\n url?: string | null\n width?: number | null\n height?: number | null\n alt?: string | null\n sizes?: Record<\n string,\n | { url?: string | null; width?: number | null; height?: number | null }\n | undefined\n >\n}\n\nexport interface SeoInput {\n title?: string | null\n description?: string | null\n noIndex?: boolean | null\n canonical?: string | null\n openGraph?: {\n title?: string | null\n description?: string | null\n image?: ImageLike | string | null\n } | null\n}\n\nexport interface GenerateMetadataOptions {\n siteName?: string\n}\n\nexport function extractSeo(doc: Record<string, unknown>): SeoInput {\n const seo = (doc.seo ?? {}) as Record<string, unknown>\n const og = (seo.openGraph ?? {}) as Record<string, unknown>\n\n return {\n title: (seo.title as string) ?? (doc.title as string) ?? null,\n description: (seo.description as string) ?? null,\n noIndex: (seo.noIndex as boolean) ?? null,\n canonical: (seo.canonical as string) ?? null,\n openGraph: {\n title: (og.title as string) ?? null,\n description: (og.description as string) ?? null,\n image: (og.image as ImageLike | string | null) ?? null,\n },\n }\n}\n\nexport function generateMetadata(\n input: SeoInput,\n options?: GenerateMetadataOptions,\n): Metadata {\n const title = input.title ?? undefined\n const description = input.description ?? undefined\n\n const ogTitle = input.openGraph?.title ?? title\n const ogDescription = input.openGraph?.description ?? description\n const image = resolveMetaImage(input.openGraph?.image)\n\n return {\n title,\n description,\n ...(input.noIndex && { robots: { index: false, follow: false } }),\n ...(input.canonical && { alternates: { canonical: input.canonical } }),\n openGraph: {\n ...(ogTitle && { title: ogTitle }),\n ...(ogDescription && { description: ogDescription }),\n ...(options?.siteName && { siteName: options.siteName }),\n ...(image && { images: [image] }),\n },\n twitter: {\n card: image ? 'summary_large_image' : 'summary',\n ...(ogTitle && { title: ogTitle }),\n ...(ogDescription && { description: ogDescription }),\n ...(image && { images: [image.url] }),\n },\n }\n}\n\nfunction resolveMetaImage(\n ref: ImageLike | string | null | undefined,\n): MetadataImage | null {\n const image = resolveRelation<ImageLike>(ref)\n if (!image) return null\n\n // Prefer sizes['1536'] (closest to OG 1200px standard), fallback to original url\n const sized = image.sizes?.['1536']\n const url = sized?.url || image.url\n if (!url) return null\n\n const width = sized?.url ? sized.width : image.width\n const height = sized?.url ? sized.height : image.height\n\n return {\n url,\n ...(width && { width }),\n ...(height && { height }),\n ...(image.alt && { alt: image.alt }),\n }\n}\n","import type {\n ApiQueryOptions,\n PublicCollection,\n ServerCollection,\n PayloadFindResponse,\n PayloadMutationResponse,\n} from '../client/types'\nimport { generateMetadata, extractSeo } from '../metadata'\nimport type { GenerateMetadataOptions, Metadata } from '../metadata'\nimport type { CollectionClient } from './collection-client'\nimport type { CollectionType } from './types'\n\ntype ReadOnlyCollectionApi = Pick<\n CollectionClient,\n 'requestFind' | 'requestFindById' | 'requestCount'\n>\n\n/**\n * Read-only subset of CollectionQueryBuilder.\n * Client.from() returns this type to prevent write operations at compile time.\n */\nexport type ReadOnlyQueryBuilder<T extends PublicCollection> =\n ReadOnlyCollectionQueryBuilder<T>\n\nexport class ReadOnlyCollectionQueryBuilder<T extends PublicCollection> {\n constructor(\n private api: ReadOnlyCollectionApi,\n private collection: T,\n ) {}\n\n async find(\n options?: ApiQueryOptions,\n ): Promise<PayloadFindResponse<CollectionType<T>>> {\n return this.api.requestFind<CollectionType<T>>(\n `/api/${String(this.collection)}`,\n options,\n )\n }\n\n async findById(\n id: string | number,\n options?: ApiQueryOptions,\n ): Promise<CollectionType<T>> {\n return this.api.requestFindById<CollectionType<T>>(\n `/api/${String(this.collection)}/${String(id)}`,\n options,\n )\n }\n\n async count(options?: ApiQueryOptions): Promise<{ totalDocs: number }> {\n return this.api.requestCount(\n `/api/${String(this.collection)}/count`,\n options,\n )\n }\n\n async findMetadata(\n options?: ApiQueryOptions,\n metadataOptions?: GenerateMetadataOptions,\n ): Promise<Metadata | null> {\n const { docs } = await this.find({ ...options, limit: 1, depth: 1 })\n const doc = docs[0]\n if (!doc) return null\n return generateMetadata(\n extractSeo(doc as unknown as Record<string, unknown>),\n metadataOptions,\n )\n }\n\n async findMetadataById(\n id: string,\n metadataOptions?: GenerateMetadataOptions,\n ): Promise<Metadata> {\n const doc = await this.findById(id, { depth: 1 })\n return generateMetadata(\n extractSeo(doc as unknown as Record<string, unknown>),\n metadataOptions,\n )\n }\n}\n\nexport class CollectionQueryBuilder<T extends string> {\n constructor(\n private api: CollectionClient,\n private collection: T,\n ) {}\n\n /**\n * Find documents (list query)\n * GET /api/{collection}\n * @returns Payload CMS find response with docs array and pagination\n */\n async find(\n options?: ApiQueryOptions,\n ): Promise<PayloadFindResponse<CollectionType<T>>> {\n return this.api.requestFind<CollectionType<T>>(\n `/api/${String(this.collection)}`,\n options,\n )\n }\n\n /**\n * Find document by ID\n * GET /api/{collection}/{id}\n * @returns Document object directly (no wrapper)\n */\n async findById(\n id: string | number,\n options?: ApiQueryOptions,\n ): Promise<CollectionType<T>> {\n return this.api.requestFindById<CollectionType<T>>(\n `/api/${String(this.collection)}/${String(id)}`,\n options,\n )\n }\n\n /**\n * Create a new document\n * POST /api/{collection}\n * @returns Payload CMS mutation response with doc and message\n */\n async create(\n data: Partial<CollectionType<T>>,\n options?: { file?: File | Blob; filename?: string },\n ): Promise<PayloadMutationResponse<CollectionType<T>>> {\n const endpoint = `/api/${String(this.collection)}`\n if (options?.file) {\n return this.api.requestCreateWithFile<CollectionType<T>>(\n endpoint,\n data,\n options.file,\n options.filename,\n )\n }\n return this.api.requestCreate<CollectionType<T>>(endpoint, data)\n }\n\n /**\n * Update a document by ID\n * PATCH /api/{collection}/{id}\n * @returns Payload CMS mutation response with doc and message\n */\n async update(\n id: string,\n data: Partial<CollectionType<T>>,\n options?: { file?: File | Blob; filename?: string },\n ): Promise<PayloadMutationResponse<CollectionType<T>>> {\n const endpoint = `/api/${String(this.collection)}/${String(id)}`\n if (options?.file) {\n return this.api.requestUpdateWithFile<CollectionType<T>>(\n endpoint,\n data,\n options.file,\n options.filename,\n )\n }\n return this.api.requestUpdate<CollectionType<T>>(endpoint, data)\n }\n\n /**\n * Count documents\n * GET /api/{collection}/count\n * @returns Count response with totalDocs\n */\n async count(options?: ApiQueryOptions): Promise<{ totalDocs: number }> {\n return this.api.requestCount(\n `/api/${String(this.collection)}/count`,\n options,\n )\n }\n\n /**\n * Find first matching document and return its Next.js Metadata.\n * Applies depth: 1 (SEO image populate) and limit: 1 automatically.\n * @returns Metadata or null if no document matches\n */\n async findMetadata(\n options?: ApiQueryOptions,\n metadataOptions?: GenerateMetadataOptions,\n ): Promise<Metadata | null> {\n const { docs } = await this.find({ ...options, limit: 1, depth: 1 })\n const doc = docs[0]\n if (!doc) return null\n return generateMetadata(\n extractSeo(doc as unknown as Record<string, unknown>),\n metadataOptions,\n )\n }\n\n /**\n * Find document by ID and return its Next.js Metadata.\n * Applies depth: 1 (SEO image populate) automatically.\n * @returns Metadata (throws on 404)\n */\n async findMetadataById(\n id: string,\n metadataOptions?: GenerateMetadataOptions,\n ): Promise<Metadata> {\n const doc = await this.findById(id, { depth: 1 })\n return generateMetadata(\n extractSeo(doc as unknown as Record<string, unknown>),\n metadataOptions,\n )\n }\n\n /**\n * Update multiple documents (bulk update)\n * PATCH /api/{collection}\n * @returns Payload CMS find response with updated docs\n */\n async updateMany(\n where: ApiQueryOptions['where'],\n data: Partial<CollectionType<T>>,\n ): Promise<PayloadFindResponse<CollectionType<T>>> {\n return this.api.requestUpdateMany<CollectionType<T>>(\n `/api/${String(this.collection)}`,\n { where, data },\n )\n }\n\n /**\n * Delete a document by ID\n * DELETE /api/{collection}/{id}\n * @returns Deleted document object directly (no wrapper)\n */\n async remove(id: string): Promise<CollectionType<T>> {\n return this.api.requestDelete<CollectionType<T>>(\n `/api/${String(this.collection)}/${String(id)}`,\n )\n }\n\n /**\n * Delete multiple documents (bulk delete)\n * DELETE /api/{collection}\n * @returns Payload CMS find response with deleted docs\n */\n async removeMany(\n where: ApiQueryOptions['where'],\n ): Promise<PayloadFindResponse<CollectionType<T>>> {\n return this.api.requestDeleteMany<CollectionType<T>>(\n `/api/${String(this.collection)}`,\n { where },\n )\n }\n}\n\nexport class ServerCollectionQueryBuilder<\n T extends ServerCollection,\n> extends CollectionQueryBuilder<T> {}\n","import { stringify } from 'qs-esm'\nimport {\n httpFetch,\n requirePublishableKeyForSecret,\n type FetchOptions,\n} from '../internal/utils'\nimport type {\n ApiQueryOptions,\n PayloadFindResponse,\n PayloadMutationResponse,\n} from '../client/types'\nimport { SDKError, createApiError } from '../internal/errors'\n\nexport class HttpClient {\n protected publishableKey: string\n protected secretKey?: string\n private getCustomerToken?: () => string | null\n private onUnauthorized?: () => Promise<string | null>\n private onRequestId?: (id: string | null) => void\n private apiUrl?: string\n\n constructor(\n publishableKey: string,\n secretKey?: string,\n getCustomerToken?: () => string | null,\n onUnauthorized?: () => Promise<string | null>,\n onRequestId?: (id: string | null) => void,\n apiUrl?: string,\n ) {\n this.publishableKey = requirePublishableKeyForSecret(\n 'CollectionClient',\n publishableKey,\n secretKey,\n )\n this.secretKey = secretKey\n this.getCustomerToken = getCustomerToken\n this.onUnauthorized = onUnauthorized\n this.onRequestId = onRequestId\n this.apiUrl = apiUrl\n }\n\n protected get defaultOptions(): FetchOptions {\n const opts: FetchOptions = {\n apiUrl: this.apiUrl,\n publishableKey: this.publishableKey,\n secretKey: this.secretKey,\n }\n const token = this.getCustomerToken?.()\n if (token) {\n opts.customerToken = token\n if (this.onUnauthorized) {\n opts.onUnauthorized = this.onUnauthorized\n }\n }\n return opts\n }\n\n protected async fetchWithTracking(url: string, opts: FetchOptions): Promise<Response> {\n try {\n const response = await httpFetch(url, opts)\n this.onRequestId?.(response.headers.get('x-request-id') ?? null)\n return response\n } catch (err) {\n const id = err instanceof SDKError ? (err.requestId ?? null) : null\n this.onRequestId?.(id)\n throw err\n }\n }\n\n protected buildUrl(endpoint: string, options?: ApiQueryOptions): string {\n if (!options) return endpoint\n const queryString = stringify(options, { addQueryPrefix: true })\n return queryString ? `${endpoint}${queryString}` : endpoint\n }\n\n protected assertJsonResponse(response: Response): void {\n const contentType = response.headers.get('content-type')\n if (!contentType?.includes('application/json')) {\n throw createApiError('Response is not in JSON format.', response.status, {\n contentType,\n })\n }\n }\n\n /**\n * Parse Payload CMS find response (list query)\n * Returns native Payload response structure\n */\n protected async parseFindResponse<T>(\n response: Response,\n ): Promise<PayloadFindResponse<T>> {\n const contentType = response.headers.get('content-type')\n\n try {\n this.assertJsonResponse(response)\n\n const jsonData = await response.json()\n\n // Validate it's a find response\n if (jsonData.docs === undefined) {\n throw createApiError('Invalid find response.', response.status, {\n jsonData,\n })\n }\n\n return {\n docs: jsonData.docs,\n totalDocs: jsonData.totalDocs ?? 0,\n limit: jsonData.limit || 20,\n totalPages: jsonData.totalPages ?? 0,\n page: jsonData.page || 1,\n pagingCounter: jsonData.pagingCounter || 1,\n hasPrevPage: jsonData.hasPrevPage ?? false,\n hasNextPage: jsonData.hasNextPage ?? false,\n prevPage: jsonData.prevPage ?? null,\n nextPage: jsonData.nextPage ?? null,\n }\n } catch (error) {\n if (error instanceof SDKError) throw error\n throw createApiError('Failed to parse response.', response.status, {\n contentType,\n error: error instanceof Error ? error.message : error,\n })\n }\n }\n\n /**\n * Parse Payload CMS mutation response (create/update)\n * Returns native Payload response structure\n */\n protected async parseMutationResponse<T>(\n response: Response,\n ): Promise<PayloadMutationResponse<T>> {\n const contentType = response.headers.get('content-type')\n\n try {\n this.assertJsonResponse(response)\n\n const jsonData = await response.json()\n\n // Validate it's a mutation response\n if (jsonData.doc === undefined) {\n throw createApiError('Invalid mutation response.', response.status, {\n jsonData,\n })\n }\n\n return {\n message: jsonData.message || '',\n doc: jsonData.doc,\n errors: jsonData.errors,\n }\n } catch (error) {\n if (error instanceof SDKError) throw error\n throw createApiError('Failed to parse response.', response.status, {\n contentType,\n error: error instanceof Error ? error.message : error,\n })\n }\n }\n\n /**\n * Parse Payload CMS document response (findById/delete)\n * Returns document directly without wrapper\n */\n protected async parseDocumentResponse<T>(response: Response): Promise<T> {\n const contentType = response.headers.get('content-type')\n\n try {\n this.assertJsonResponse(response)\n\n const jsonData = await response.json()\n return jsonData as T\n } catch (error) {\n if (error instanceof SDKError) throw error\n throw createApiError('Failed to parse response.', response.status, {\n contentType,\n error: error instanceof Error ? error.message : error,\n })\n }\n }\n}\n","import { createConfigError } from '../errors'\n\nexport function requirePublishableKeyForSecret(\n apiName: string,\n publishableKey: string | undefined,\n secretKey: string | undefined,\n): string {\n if (secretKey && !publishableKey) {\n throw createConfigError(\n `publishableKey is required for ${apiName} when secretKey is used. ` +\n 'It is sent as X-Publishable-Key for tenant routing, rate limiting, and quota enforcement.',\n )\n }\n\n return publishableKey ?? ''\n}\n","import type {\n Collection,\n PublicCollection,\n ServerCollection,\n ServerOnlyCollection,\n} from '../collection/const'\nimport type { CollectionType } from '../collection/types'\nimport type { CommunityClient } from '../community/community-client'\nimport type {\n BanCustomerParams,\n CommunityBan,\n UnbanCustomerParams,\n} from '../community/moderation-api'\nimport type { CommerceClient } from '../commerce/commerce-client'\nimport type { ServerCommerceClient } from '../commerce/server-commerce-client'\nimport type { CustomerNamespace } from '../customer/customer-namespace'\n\nexport type {\n Collection,\n PublicCollection,\n ServerCollection,\n ServerOnlyCollection,\n}\n\n// ============================================================================\n// API URL Configuration\n// ============================================================================\n\ndeclare const __DEFAULT_API_URL__: string\n\nexport function resolveApiUrl(apiUrl?: string): string {\n if (apiUrl) {\n return apiUrl.replace(/\\/$/, '')\n }\n\n if (typeof process !== 'undefined' && process.env) {\n const envUrl =\n process.env.SOFTWARE_API_URL || process.env.NEXT_PUBLIC_SOFTWARE_API_URL\n if (envUrl) {\n return envUrl.replace(/\\/$/, '')\n }\n }\n return __DEFAULT_API_URL__\n}\n\n// ============================================================================\n// Client Configuration\n// ============================================================================\n\nexport interface ClientConfig {\n publishableKey: string\n /** API base URL for staging, self-hosted, preview, or proxy deployments. */\n apiUrl?: string\n /**\n * Customer authentication options.\n * Used to initialize CustomerAuth on Client.\n */\n customer?: {\n /**\n * Persist token in localStorage. Defaults to `true`.\n * - `true` (default): uses key `'customer-token'`\n * - `string`: uses the given string as localStorage key\n * - `false`: disables persistence (token/onTokenChange used instead)\n *\n * Handles SSR safely (no-op on server).\n * When enabled, `token` and `onTokenChange` are ignored.\n */\n persist?: boolean | string\n /** Initial token (e.g. from SSR cookie) */\n token?: string\n /** Called when token changes (login/logout) — use to persist in localStorage/cookie */\n onTokenChange?: (token: string | null) => void\n }\n}\n\n// Server client: requires both publishableKey (for CDN routing + rate limit +\n// monthly quota enforcement via the edge proxy) and secretKey (sk01_ opaque\n// bearer token, the authentication credential).\n// The proxy keys its tenant lookup off `X-Publishable-Key`, so omitting\n// publishableKey would silently bypass rate limiting and plan-based quota\n// enforcement.\nexport interface ClientServerConfig extends ClientConfig {\n secretKey: string\n}\n\nexport interface ClientMetadata {\n userAgent?: string\n timestamp: number\n}\n\nexport interface ClientState {\n metadata: ClientMetadata\n}\n\nexport interface PaginationMeta {\n page: number\n limit: number\n totalDocs: number\n totalPages: number\n hasNextPage: boolean\n hasPrevPage: boolean\n pagingCounter: number\n prevPage: number | null\n nextPage: number | null\n}\n\n// ============================================================================\n// Payload CMS Native Response Types\n// ============================================================================\n\n/**\n * Payload CMS Find (List) Response\n * GET /api/{collection}\n */\nexport interface PayloadFindResponse<T = unknown> {\n docs: T[]\n totalDocs: number\n limit: number\n totalPages: number\n page: number\n pagingCounter: number\n hasPrevPage: boolean\n hasNextPage: boolean\n prevPage: number | null\n nextPage: number | null\n}\n\n/**\n * Payload CMS Create/Update Response\n * POST /api/{collection}\n * PATCH /api/{collection}/{id}\n */\nexport interface PayloadMutationResponse<T = unknown> {\n message: string\n doc: T\n errors?: unknown[]\n}\n\n// ============================================================================\n// Query Options\n// ============================================================================\n\nexport type Sort = string | string[]\nexport type Where = Record<string, unknown>\n\n/**\n * Do NOT replace with `Pick<FindOptions>` from `payload` or import Payload\n * types here. Payload's generic query types depend on `PayloadTypes` module\n * augmentation; external SDK consumers who only use `createClient` should not\n * install Payload just to type REST query objects. Excluded vs native:\n * Local-API-only fields, `locale`/`fallbackLocale`.\n */\nexport interface ApiQueryOptions {\n page?: number\n limit?: number\n sort?: Sort\n /**\n * Filter documents. Id-based relation filters (`where: { product: { equals: id } }`) are the\n * most reliable pattern. Dotted-path relation filters (`where: { 'product.slug': { equals } }`)\n * are Payload-native but may silently return empty when access control restricts the related\n * document or when the relation is polymorphic. String shorthand (`where: { slug: 'x' }`)\n * silently matches nothing — always use `{ slug: { equals: 'x' } }`.\n */\n where?: Where\n /**\n * Controls how deeply relationship fields are populated. This is the primary control for\n * populating relationships like `category`, `images`, `brand`. The configured Payload default\n * applies when unset.\n */\n depth?: number\n select?: Record<string, boolean>\n /**\n * Controls which fields are returned for already-populated relationships, keyed by collection\n * slug. Does NOT control which relationships to populate — that is `depth`.\n *\n * @example\n * // depth: 2 populates category; populate trims which fields come back\n * populate: { categories: { title: true, slug: true } }\n */\n populate?: Record<string, boolean | Record<string, boolean>>\n /**\n * Controls Payload `type: 'join'` virtual reverse-relation fields only (pagination, sort,\n * filter, count per join field, or `false` to disable all join-field population).\n *\n * Does NOT populate normal relationship fields like `category`, `images`, or `brand`.\n * For normal relationship population use `depth` (and optionally `populate` for field\n * selection).\n *\n * Pass `joins: false` to disable all join-field population — useful for lightweight list\n * queries where join fields are not needed.\n *\n * @example\n * // `article-authors` has a `type: 'join'` field `articles` (reverse-relation)\n * joins: { articles: { limit: 10, sort: '-publishedAt' } }\n *\n * // depth: 2 populates product.category — joins has no effect on this\n * depth: 2\n *\n * // Disable all join-field population\n * joins: false\n */\n joins?:\n | Record<\n string,\n | {\n limit?: number\n page?: number\n sort?: string\n where?: Where\n count?: boolean\n }\n | false\n >\n | false\n /** Set to `false` to skip the count query — returns docs without totalDocs/totalPages */\n pagination?: boolean\n /** Include draft versions (access control still applies on the server) */\n draft?: boolean\n /** Include soft-deleted documents (requires `trash` enabled on the collection) */\n trash?: boolean\n}\n\n// ============================================================================\n// Debug & Retry Configuration\n// ============================================================================\n\nexport interface DebugConfig {\n logRequests?: boolean\n logResponses?: boolean\n logErrors?: boolean\n}\n\nexport interface RetryConfig {\n maxRetries?: number\n retryableStatuses?: number[]\n retryDelay?: (attempt: number) => number\n}\n\n// ============================================================================\n// Lightweight root entry contracts\n// ============================================================================\n\ninterface RootQueryLookup<T extends string> {\n find(options?: ApiQueryOptions): Promise<PayloadFindResponse<CollectionType<T>>>\n findById(\n id: string | number,\n options?: ApiQueryOptions,\n ): Promise<CollectionType<T>>\n count(options?: ApiQueryOptions): Promise<{ totalDocs: number }>\n}\n\nexport type RootReadOnlyQueryBuilder<T extends PublicCollection> =\n RootQueryLookup<T>\n\nexport interface RootServerQueryBuilder<T extends ServerCollection>\n extends RootQueryLookup<T> {\n create(\n data: Partial<CollectionType<T>>,\n options?: { file?: File | Blob; filename?: string },\n ): Promise<PayloadMutationResponse<CollectionType<T>>>\n update(\n id: string,\n data: Partial<CollectionType<T>>,\n options?: { file?: File | Blob; filename?: string },\n ): Promise<PayloadMutationResponse<CollectionType<T>>>\n updateMany(\n where: ApiQueryOptions['where'],\n data: Partial<CollectionType<T>>,\n ): Promise<PayloadFindResponse<CollectionType<T>>>\n remove(id: string): Promise<CollectionType<T>>\n removeMany(\n where: ApiQueryOptions['where'],\n ): Promise<PayloadFindResponse<CollectionType<T>>>\n}\n\nexport interface RootCollectionClient {\n from<T extends PublicCollection>(collection: T): RootReadOnlyQueryBuilder<T>\n}\n\nexport interface RootServerCollectionClient {\n from<T extends ServerCollection>(collection: T): RootServerQueryBuilder<T>\n}\n\nexport interface RootClient {\n commerce: CommerceClient\n community: CommunityClient\n customer: CustomerNamespace\n collections: RootCollectionClient\n lastRequestId: string | null\n getState(): ClientState\n getConfig(): ClientConfig\n}\n\nexport interface RootServerClient {\n commerce: ServerCommerceClient\n community: CommunityClient & {\n moderation: {\n banCustomer: (p: BanCustomerParams) => Promise<CommunityBan>\n unbanCustomer: (p: UnbanCustomerParams) => Promise<{ success: true }>\n }\n }\n collections: RootServerCollectionClient\n lastRequestId: string | null\n getState(): ClientState\n getConfig(): Omit<ClientServerConfig, 'secretKey'>\n}\n\n// ============================================================================\n// Type Utilities\n// ============================================================================\n\nexport type DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]\n}\n\nexport type ExtractArrayType<T> = T extends (infer U)[] ? U : never\n","import {\n createAuthError,\n createConflictError,\n createNetworkError,\n createNotFoundError,\n createPermissionError,\n createValidationError,\n createUsageLimitError,\n createTimeoutError,\n TimeoutError,\n NetworkError,\n SDKError,\n} from '../errors'\nimport type { DebugConfig, RetryConfig } from '../../client/types'\nimport { resolveApiUrl } from '../../client/types'\nconst DEFAULT_TIMEOUT = 30000\nconst DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504]\nconst NON_RETRYABLE_STATUSES = [400, 401, 403, 404, 409, 422]\nconst SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']\n\nexport interface FetchOptions extends RequestInit {\n apiUrl?: string\n publishableKey?: string\n secretKey?: string\n customerToken?: string\n timeout?: number\n debug?: boolean | DebugConfig\n retry?: RetryConfig\n /** Called on 401 when customerToken is set and reason=token_expired. Return a new token to retry, or null to fail. */\n onUnauthorized?: () => Promise<string | null>\n}\n\nfunction debugLog(\n debug: boolean | DebugConfig | undefined,\n type: 'request' | 'response' | 'error',\n message: string,\n data?: unknown,\n) {\n if (!debug) return\n\n const shouldLog =\n debug === true ||\n (type === 'request' && (debug as DebugConfig).logRequests) ||\n (type === 'response' && (debug as DebugConfig).logResponses) ||\n (type === 'error' && (debug as DebugConfig).logErrors)\n\n if (shouldLog) {\n console.group(`[SDK ${type.toUpperCase()}] ${message}`)\n if (data) console.log(data)\n console.groupEnd()\n }\n}\n\nfunction redactSensitiveHeader(value: string): string {\n const prefix = value.toLowerCase().startsWith('bearer ') ? 'Bearer ' : ''\n return value.length > 20 ? `${prefix}...****${value.slice(-8)}` : '****'\n}\n\nfunction redactSensitiveHeaders(headers: Headers): Record<string, string> {\n const redacted = Object.fromEntries(headers.entries())\n if (redacted.authorization) {\n redacted.authorization = redactSensitiveHeader(redacted.authorization)\n }\n if (redacted['x-preview-token']) {\n redacted['x-preview-token'] = redactSensitiveHeader(\n redacted['x-preview-token'],\n )\n }\n return redacted\n}\n\nfunction getErrorSuggestion(status: number): string | undefined {\n if (status === 400)\n return 'The request data failed validation. Check field values and types.'\n if (status === 401) return 'Please check your authentication credentials.'\n if (status === 403)\n return 'Access denied. Check your credentials or permissions.'\n if (status === 404) return 'The requested resource was not found.'\n if (status === 422) return 'The request data failed validation.'\n if (status >= 500) return 'A server error occurred. Please try again later.'\n return undefined\n}\n\nfunction isUsageLimitExceededResponse(response: Response): boolean {\n if (response.status !== 429) return false\n\n const limit = parseInt(response.headers.get('X-Usage-Limit') || '', 10)\n const current = parseInt(response.headers.get('X-Usage-Current') || '', 10)\n if (!Number.isFinite(limit) || !Number.isFinite(current)) return false\n\n return response.headers.get('X-Usage-Exceeded') === 'true' || current > limit\n}\n\n/**\n * Parse error details from HTTP response body.\n * Supports Payload native format:\n * - ValidationError: { errors: [{ message, data: { errors: [{ path, message }] } }] }\n * - Simple: { errors: [{ message, field? }] }\n * Also supports custom endpoint format ({ error: string, reason?: string, message?: string }).\n */\nasync function parseErrorBody(response: Response): Promise<{\n errorMessage: string\n userMessage: string\n reason?: string\n body?: Record<string, unknown>\n errors?: Array<{ message?: string; field?: string }>\n}> {\n const fallback = {\n errorMessage: `HTTP ${response.status}: ${response.statusText}`,\n userMessage: `Request failed (status: ${response.status})`,\n }\n\n try {\n const body = await response.json()\n const reason: string | undefined =\n typeof body.reason === 'string'\n ? body.reason\n : typeof body.code === 'string'\n ? body.code\n : undefined\n\n // Payload native: { errors: [{ message, field?, data? }] }\n if (body.errors && Array.isArray(body.errors)) {\n // Extract nested ValidationError field details\n // Payload ValidationError format: errors[].data.errors[].{path, message}\n const fieldErrors: Array<{ message?: string; field?: string }> = []\n for (const e of body.errors) {\n if (\n e.data?.errors &&\n Array.isArray(e.data.errors) &&\n e.data.errors.length > 0\n ) {\n for (const fe of e.data.errors) {\n fieldErrors.push({\n field: fe.path || fe.field,\n message: fe.message,\n })\n }\n } else if (e.field || e.message) {\n fieldErrors.push({ field: e.field, message: e.message })\n }\n }\n\n const details = (fieldErrors.length > 0 ? fieldErrors : body.errors)\n .map((e: { message?: string; field?: string }) =>\n e.field ? `${e.field}: ${e.message}` : e.message,\n )\n .filter(Boolean)\n .join('; ')\n if (details) {\n return {\n errorMessage: `HTTP ${response.status}: ${details}`,\n userMessage: details,\n reason,\n body,\n errors: fieldErrors.length > 0 ? fieldErrors : body.errors,\n }\n }\n }\n\n // Custom endpoint: { error: string, reason?: string, details?: { fieldErrors? } }\n if (typeof body.error === 'string') {\n return {\n errorMessage: `HTTP ${response.status}: ${body.error}`,\n userMessage: body.error,\n reason,\n body,\n }\n }\n\n // Fallback: { message: string }\n if (body.message) {\n return {\n errorMessage: `HTTP ${response.status}: ${body.message}`,\n userMessage: body.message,\n reason,\n body,\n }\n }\n\n return { ...fallback, reason, body }\n } catch {\n return fallback\n }\n}\n\nfunction getParsedErrorSuggestion(\n status: number,\n parsed: Awaited<ReturnType<typeof parseErrorBody>>,\n): string | undefined {\n if (status === 403 && parsed.reason === 'origin_not_allowed') {\n return 'Add the request origin to the tenant Browser API origins, then retry the browser request.'\n }\n\n return getErrorSuggestion(status)\n}\n\nasync function delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n// Attach requestId to any SDKError instance (readonly bypass is intentional — internal transport layer only)\nexport function attachRequestId<T extends SDKError>(\n err: T,\n id: string | undefined,\n): T {\n if (id) (err as Record<string, unknown>).requestId = id\n return err\n}\n\nfunction createHttpStatusError(\n status: number,\n parsed: Awaited<ReturnType<typeof parseErrorBody>>,\n details: Record<string, unknown>,\n requestId: string | undefined,\n): SDKError {\n const errorDetails = {\n ...details,\n ...(parsed.errors && { errors: parsed.errors }),\n ...(parsed.body && { body: parsed.body }),\n }\n const suggestion = getParsedErrorSuggestion(status, parsed)\n\n if (status === 400 || status === 422) {\n return attachRequestId(\n createValidationError(\n parsed.errorMessage,\n errorDetails,\n parsed.userMessage,\n suggestion,\n status,\n ),\n requestId,\n )\n }\n\n if (status === 401) {\n return attachRequestId(\n createAuthError(\n parsed.errorMessage,\n errorDetails,\n parsed.userMessage,\n suggestion,\n ),\n requestId,\n )\n }\n\n if (status === 403) {\n return attachRequestId(\n createPermissionError(\n parsed.errorMessage,\n errorDetails,\n parsed.userMessage,\n suggestion,\n ),\n requestId,\n )\n }\n\n if (status === 404) {\n return attachRequestId(\n createNotFoundError(\n parsed.errorMessage,\n errorDetails,\n parsed.userMessage,\n suggestion,\n ),\n requestId,\n )\n }\n\n if (status === 409) {\n return attachRequestId(\n createConflictError(\n parsed.errorMessage,\n errorDetails,\n parsed.userMessage,\n suggestion,\n ),\n requestId,\n )\n }\n\n return attachRequestId(\n createNetworkError(\n parsed.errorMessage,\n status,\n errorDetails,\n parsed.userMessage,\n suggestion,\n ),\n requestId,\n )\n}\n\nexport async function httpFetch(\n url: string,\n options?: FetchOptions,\n): Promise<Response> {\n const {\n apiUrl,\n publishableKey,\n secretKey,\n customerToken,\n timeout = DEFAULT_TIMEOUT,\n debug,\n retry,\n onUnauthorized,\n ...requestInit\n } = options || {}\n\n const baseUrl = resolveApiUrl(apiUrl)\n\n const retryConfig = {\n maxRetries: retry?.maxRetries ?? 3,\n retryableStatuses: retry?.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES,\n retryDelay:\n retry?.retryDelay ??\n ((attempt: number) => Math.min(1000 * 2 ** attempt, 10000)),\n }\n\n // Server auth: secretKey is now the raw opaque bearer token (sk01_...).\n // Customer auth: customerToken is a JWT.\n let authToken: string | undefined\n if (secretKey) {\n authToken = secretKey\n } else if (customerToken) {\n authToken = customerToken\n }\n\n let lastError: Error | undefined\n let hasRetried401 = false\n\n for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {\n try {\n const headers = new Headers(requestInit.headers)\n\n if (publishableKey) {\n headers.set('X-Publishable-Key', publishableKey)\n }\n\n if (authToken) {\n headers.set('Authorization', `Bearer ${authToken}`)\n }\n\n if (\n !headers.has('Content-Type') &&\n requestInit.body &&\n !(requestInit.body instanceof FormData)\n ) {\n headers.set('Content-Type', 'application/json')\n }\n\n // Redact sensitive headers for debug logging\n const redactedHeaders = redactSensitiveHeaders(headers)\n\n debugLog(debug, 'request', url, {\n method: requestInit.method || 'GET',\n headers: redactedHeaders,\n attempt: attempt + 1,\n })\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n const response = await fetch(`${baseUrl}${url}`, {\n ...requestInit,\n headers,\n signal: controller.signal,\n })\n\n clearTimeout(timeoutId)\n\n const requestId = response.headers.get('x-request-id') ?? undefined\n\n debugLog(debug, 'response', url, {\n status: response.status,\n statusText: response.statusText,\n headers: redactSensitiveHeaders(response.headers),\n })\n\n if (!response.ok) {\n // Usage limit 429 — never retry. Older servers identify this when\n // current usage is above the limit; newer servers also send\n // X-Usage-Exceeded to avoid confusing other 429s with quota exhaustion.\n if (isUsageLimitExceededResponse(response)) {\n const limit = parseInt(\n response.headers.get('X-Usage-Limit') || '0',\n 10,\n )\n const current = parseInt(\n response.headers.get('X-Usage-Current') || '0',\n 10,\n )\n const remaining = parseInt(\n response.headers.get('X-Usage-Remaining') || '0',\n 10,\n )\n\n throw attachRequestId(\n createUsageLimitError(\n `Monthly API usage limit exceeded (${current.toLocaleString()}/${limit.toLocaleString()})`,\n { limit, current, remaining },\n {\n url,\n method: requestInit.method || 'GET',\n attempt: attempt + 1,\n },\n 'Monthly API call limit exceeded. Please upgrade your plan.',\n 'Upgrade your tenant plan to increase the monthly API call limit.',\n ),\n requestId,\n )\n }\n\n // Parse body once — captures reason field for 401 branching and error details\n const parsed = await parseErrorBody(response)\n\n // Auto-refresh customer token on 401 — only when reason=token_expired\n if (\n response.status === 401 &&\n onUnauthorized &&\n customerToken &&\n !hasRetried401 &&\n parsed.reason === 'token_expired'\n ) {\n hasRetried401 = true\n try {\n const newToken = await onUnauthorized()\n if (newToken) {\n authToken = newToken\n continue\n }\n } catch {\n // Refresh failed, fall through to throw\n }\n }\n\n const details = {\n url,\n method: requestInit.method || 'GET',\n attempt: attempt + 1,\n }\n\n // Never retry non-retryable statuses regardless of user config\n if (NON_RETRYABLE_STATUSES.includes(response.status)) {\n throw createHttpStatusError(\n response.status,\n parsed,\n details,\n requestId,\n )\n }\n\n // Retryable errors\n const error = attachRequestId(\n createNetworkError(\n parsed.errorMessage,\n response.status,\n details,\n parsed.userMessage,\n getErrorSuggestion(response.status),\n ),\n requestId,\n )\n\n const method = (requestInit.method || 'GET').toUpperCase()\n if (\n attempt < retryConfig.maxRetries &&\n SAFE_METHODS.includes(method) &&\n retryConfig.retryableStatuses.includes(response.status)\n ) {\n lastError = error\n const retryDelay = retryConfig.retryDelay(attempt)\n debugLog(debug, 'error', `Retrying in ${retryDelay}ms...`, error)\n await delay(retryDelay)\n continue\n }\n\n throw error\n }\n\n return response\n } catch (error) {\n debugLog(debug, 'error', url, error)\n\n const method = (requestInit.method || 'GET').toUpperCase()\n const isSafe = SAFE_METHODS.includes(method)\n\n if (error instanceof Error && error.name === 'AbortError') {\n const timeoutError = createTimeoutError(\n `Request timed out after ${timeout}ms.`,\n { url, timeout, attempt: attempt + 1 },\n 'The request timed out.',\n 'Please check your network connection or try again later.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = timeoutError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw timeoutError\n }\n\n if (error instanceof TypeError) {\n const networkError = createNetworkError(\n 'Network connection failed.',\n undefined,\n { url, originalError: error.message, attempt: attempt + 1 },\n 'Network connection failed.',\n 'Please check your internet connection and try again.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = networkError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw networkError\n }\n\n if (error instanceof NetworkError || error instanceof TimeoutError) {\n if (\n isSafe &&\n attempt < retryConfig.maxRetries &&\n error.status &&\n !NON_RETRYABLE_STATUSES.includes(error.status) &&\n retryConfig.retryableStatuses.includes(error.status)\n ) {\n lastError = error\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw error\n }\n\n // Re-throw any other SDKError subclass (e.g. UsageLimitError) without wrapping\n if (error instanceof SDKError) {\n throw error\n }\n\n const unknownError = createNetworkError(\n error instanceof Error\n ? error.message\n : 'An unknown network error occurred.',\n undefined,\n { url, originalError: error, attempt: attempt + 1 },\n 'An unknown error occurred.',\n 'Please try again later.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = unknownError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw unknownError\n }\n }\n\n throw lastError ?? new NetworkError('Request failed after retries')\n}\n","import { HttpClient } from './http-client'\nimport type {\n ApiQueryOptions,\n PublicCollection,\n ServerCollection,\n PayloadFindResponse,\n PayloadMutationResponse,\n} from '../client/types'\nimport {\n CollectionQueryBuilder,\n ReadOnlyCollectionQueryBuilder,\n ServerCollectionQueryBuilder,\n type ReadOnlyQueryBuilder,\n} from './query-builder'\n\nfunction buildPayloadFormData(\n data: unknown,\n file: File | Blob,\n filename?: string,\n): FormData {\n const formData = new FormData()\n formData.append('file', file, filename)\n if (data != null) {\n formData.append('_payload', JSON.stringify(data))\n }\n return formData\n}\n\nexport class CollectionClient<\n TCollection extends string = PublicCollection,\n> extends HttpClient {\n from<T extends TCollection>(collection: T): CollectionQueryBuilder<T> {\n return new CollectionQueryBuilder(this, collection)\n }\n\n // ============================================================================\n // Payload-native methods\n // ============================================================================\n\n /**\n * Find documents (list query)\n * GET /api/{collection}\n */\n async requestFind<T = unknown>(\n endpoint: string,\n options?: ApiQueryOptions,\n ): Promise<PayloadFindResponse<T>> {\n const url = this.buildUrl(endpoint, options)\n const response = await this.fetchWithTracking(url, {\n ...this.defaultOptions,\n method: 'GET',\n })\n return this.parseFindResponse<T>(response)\n }\n\n /**\n * Find-like response from a custom endpoint\n * POST /api/...custom-endpoint\n */\n async requestFindEndpoint<T = unknown>(\n endpoint: string,\n data?: unknown,\n ): Promise<PayloadFindResponse<T>> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'POST',\n body: data ? JSON.stringify(data) : undefined,\n })\n return this.parseFindResponse<T>(response)\n }\n\n /**\n * Find document by ID\n * GET /api/{collection}/{id}\n */\n async requestFindById<T = unknown>(\n endpoint: string,\n options?: ApiQueryOptions,\n ): Promise<T> {\n const url = this.buildUrl(endpoint, options)\n const response = await this.fetchWithTracking(url, {\n ...this.defaultOptions,\n method: 'GET',\n })\n return this.parseDocumentResponse<T>(response)\n }\n\n /**\n * Create document\n * POST /api/{collection}\n */\n async requestCreate<T = unknown>(\n endpoint: string,\n data?: unknown,\n ): Promise<PayloadMutationResponse<T>> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'POST',\n body: data ? JSON.stringify(data) : undefined,\n })\n return this.parseMutationResponse<T>(response)\n }\n\n /**\n * Update document\n * PATCH /api/{collection}/{id}\n */\n async requestUpdate<T = unknown>(\n endpoint: string,\n data?: unknown,\n ): Promise<PayloadMutationResponse<T>> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'PATCH',\n body: data ? JSON.stringify(data) : undefined,\n })\n return this.parseMutationResponse<T>(response)\n }\n\n /**\n * Count documents\n * GET /api/{collection}/count\n */\n async requestCount(\n endpoint: string,\n options?: ApiQueryOptions,\n ): Promise<{ totalDocs: number }> {\n const url = this.buildUrl(endpoint, options)\n const response = await this.fetchWithTracking(url, {\n ...this.defaultOptions,\n method: 'GET',\n })\n return this.parseDocumentResponse<{ totalDocs: number }>(response)\n }\n\n /**\n * Update multiple documents (bulk update)\n * PATCH /api/{collection}\n */\n async requestUpdateMany<T = unknown>(\n endpoint: string,\n data: { where?: unknown; data: unknown },\n ): Promise<PayloadFindResponse<T>> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'PATCH',\n body: JSON.stringify(data),\n })\n return this.parseFindResponse<T>(response)\n }\n\n /**\n * Delete document\n * DELETE /api/{collection}/{id}\n */\n async requestDelete<T = unknown>(endpoint: string): Promise<T> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'DELETE',\n })\n return this.parseDocumentResponse<T>(response)\n }\n\n /**\n * Delete multiple documents (bulk delete)\n * DELETE /api/{collection}\n */\n async requestDeleteMany<T = unknown>(\n endpoint: string,\n data: { where?: unknown },\n ): Promise<PayloadFindResponse<T>> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'DELETE',\n body: JSON.stringify(data),\n })\n return this.parseFindResponse<T>(response)\n }\n\n /**\n * Create document with file upload\n * POST /api/{collection} (multipart/form-data)\n */\n async requestCreateWithFile<T = unknown>(\n endpoint: string,\n data: unknown,\n file: File | Blob,\n filename?: string,\n ): Promise<PayloadMutationResponse<T>> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'POST',\n body: buildPayloadFormData(data, file, filename),\n })\n return this.parseMutationResponse<T>(response)\n }\n\n /**\n * Update document with file upload\n * PATCH /api/{collection}/{id} (multipart/form-data)\n */\n async requestUpdateWithFile<T = unknown>(\n endpoint: string,\n data: unknown,\n file: File | Blob,\n filename?: string,\n ): Promise<PayloadMutationResponse<T>> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'PATCH',\n body: buildPayloadFormData(data, file, filename),\n })\n return this.parseMutationResponse<T>(response)\n }\n}\n\nexport class ServerCollectionClient extends CollectionClient<ServerCollection> {\n override from<T extends ServerCollection>(\n collection: T,\n ): ServerCollectionQueryBuilder<T> {\n return new ServerCollectionQueryBuilder(this, collection)\n }\n}\n\nexport class ReadOnlyCollectionClient extends HttpClient {\n from<T extends PublicCollection>(collection: T): ReadOnlyQueryBuilder<T> {\n return new ReadOnlyCollectionQueryBuilder(this, collection)\n }\n\n async requestFind<T = unknown>(\n endpoint: string,\n options?: ApiQueryOptions,\n ): Promise<PayloadFindResponse<T>> {\n const url = this.buildUrl(endpoint, options)\n const response = await this.fetchWithTracking(url, {\n ...this.defaultOptions,\n method: 'GET',\n })\n return this.parseFindResponse<T>(response)\n }\n\n async requestFindById<T = unknown>(\n endpoint: string,\n options?: ApiQueryOptions,\n ): Promise<T> {\n const url = this.buildUrl(endpoint, options)\n const response = await this.fetchWithTracking(url, {\n ...this.defaultOptions,\n method: 'GET',\n })\n return this.parseDocumentResponse<T>(response)\n }\n\n async requestCount(\n endpoint: string,\n options?: ApiQueryOptions,\n ): Promise<{ totalDocs: number }> {\n const url = this.buildUrl(endpoint, options)\n const response = await this.fetchWithTracking(url, {\n ...this.defaultOptions,\n method: 'GET',\n })\n return this.parseDocumentResponse<{ totalDocs: number }>(response)\n }\n}\n","import type ServerClient from '../client/client.server'\nimport type {\n PublicCollection,\n RootClient,\n ServerCollection,\n} from '../client/types'\nimport { CollectionClient } from '../collection'\nimport { QueryHooks, type ReadOnlyQueryHooks } from './query-hooks'\nimport { getQueryClient } from './get-query-client'\nimport type { QueryClient } from '@tanstack/react-query'\n\nfunction createReadOnlyQueryHooksFacade(\n hooks: QueryHooks<PublicCollection>,\n): ReadOnlyQueryHooks {\n return {\n useQuery: hooks.useQuery.bind(hooks),\n useSuspenseQuery: hooks.useSuspenseQuery.bind(hooks),\n useQueryById: hooks.useQueryById.bind(hooks),\n useSuspenseQueryById: hooks.useSuspenseQueryById.bind(hooks),\n useInfiniteQuery: hooks.useInfiniteQuery.bind(hooks),\n useSuspenseInfiniteQuery: hooks.useSuspenseInfiniteQuery.bind(hooks),\n prefetchQuery: hooks.prefetchQuery.bind(hooks),\n prefetchQueryById: hooks.prefetchQueryById.bind(hooks),\n prefetchInfiniteQuery: hooks.prefetchInfiniteQuery.bind(hooks),\n invalidateQueries: hooks.invalidateQueries.bind(hooks),\n getQueryData: hooks.getQueryData.bind(hooks),\n setQueryData: hooks.setQueryData.bind(hooks),\n useCustomerMe: hooks.useCustomerMe.bind(hooks),\n useCustomerLogin: hooks.useCustomerLogin.bind(hooks),\n useCustomerRegister: hooks.useCustomerRegister.bind(hooks),\n useCustomerLogout: hooks.useCustomerLogout.bind(hooks),\n useCustomerForgotPassword: hooks.useCustomerForgotPassword.bind(hooks),\n useCustomerResetPassword: hooks.useCustomerResetPassword.bind(hooks),\n useCustomerRefreshToken: hooks.useCustomerRefreshToken.bind(hooks),\n useCustomerUpdateProfile: hooks.useCustomerUpdateProfile.bind(hooks),\n useCustomerChangePassword: hooks.useCustomerChangePassword.bind(hooks),\n invalidateCustomerQueries: hooks.invalidateCustomerQueries.bind(hooks),\n getCustomerData: hooks.getCustomerData.bind(hooks),\n setCustomerData: hooks.setCustomerData.bind(hooks),\n useProductListingGroupsQuery:\n hooks.useProductListingGroupsQuery.bind(hooks),\n useSuspenseProductListingGroupsQuery:\n hooks.useSuspenseProductListingGroupsQuery.bind(hooks),\n useInfiniteProductListingGroupsQuery:\n hooks.useInfiniteProductListingGroupsQuery.bind(hooks),\n useSuspenseInfiniteProductListingGroupsQuery:\n hooks.useSuspenseInfiniteProductListingGroupsQuery.bind(hooks),\n prefetchProductListingGroupsQuery:\n hooks.prefetchProductListingGroupsQuery.bind(hooks),\n prefetchInfiniteProductListingGroupsQuery:\n hooks.prefetchInfiniteProductListingGroupsQuery.bind(hooks),\n useProductDetail: hooks.useProductDetail.bind(hooks),\n useProductDetailBySlug: hooks.useProductDetailBySlug.bind(hooks),\n useProductDetailById: hooks.useProductDetailById.bind(hooks),\n } as ReadOnlyQueryHooks\n}\n\nexport function createQueryHooks(\n client: RootClient,\n queryClient: QueryClient = getQueryClient(),\n): ReadOnlyQueryHooks {\n const config = client.getConfig()\n const onUnauthorized = async (): Promise<string | null> => {\n try {\n const result = await client.customer.auth.refreshToken()\n return result.token ?? null\n } catch {\n return null\n }\n }\n\n const collectionClient = new CollectionClient(\n config.publishableKey,\n undefined,\n () => client.customer.auth.getToken(),\n onUnauthorized,\n (id) => {\n client.lastRequestId = id\n },\n config.apiUrl,\n )\n\n const hooks = new QueryHooks<PublicCollection>(\n queryClient,\n collectionClient,\n client.customer.auth,\n client.commerce,\n )\n\n return createReadOnlyQueryHooksFacade(hooks)\n}\n\nexport function createServerQueryHooks(\n client: ServerClient,\n queryClient: QueryClient = getQueryClient(),\n): QueryHooks<ServerCollection> {\n return new QueryHooks<ServerCollection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BACd,QACA,cAA2B,eAAe,GACtB;AACpB,QAAM,SAAS,OAAO,UAAU;AAChC,QAAM,iBAAiB,YAAoC;AACzD,QAAI;AACF,YAAM,SAAS,MAAM,OAAO,SAAS,KAAK,aAAa;AACvD,aAAO,OAAO,SAAS;AAAA,IACzB,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AAEA,QAAM,mBAAmB,IAAI;AAAA,IAC3B,OAAO;AAAA,IACP;AAAA,IACA,MAAM,OAAO,SAAS,KAAK,SAAS;AAAA,IACpC;AAAA,IACA,CAAC,OAAO;AACN,aAAO,gBAAgB;AAAA,IACzB;AAAA,IACA,OAAO;AAAA,EACT;AAEA,QAAM,QAAQ,IAAI;AAAA,IAChB;AAAA,IACA;AAAA,IACA,OAAO,SAAS;AAAA,IAChB,OAAO;AAAA,EACT;AAEA,SAAO,+BAA+B,KAAK;AAC7C;AAEO,SAAS,uBACd,QACA,cAA2B,eAAe,GACZ;AAC9B,SAAO,IAAI;AAAA,IACT;AAAA,IACA,OAAO;AAAA,IACP;AAAA,IACA,OAAO;AAAA,EACT;AACF;","names":["import_react_query","useQueryOriginal","useSuspenseQueryOriginal","useInfiniteQueryOriginal","useSuspenseInfiniteQueryOriginal","useMutationOriginal","import_react_query","useMutationOriginal","useQueryOriginal","import_react_query","useQueryOriginal","useSuspenseQueryOriginal","useInfiniteQueryOriginal","useSuspenseInfiniteQueryOriginal","delay"]}
|
|
1
|
+
{"version":3,"sources":["../src/query.ts","../src/core/query/get-query-client.ts","../src/core/query/query-keys.ts","../src/core/query/collection-hooks.ts","../src/core/query/customer-hooks.ts","../src/core/internal/errors/index.ts","../src/core/query/query-hooks.ts","../src/core/query/realtime.ts","../src/utils/types.ts","../src/core/metadata/index.ts","../src/core/collection/query-builder.ts","../src/core/collection/http-client.ts","../src/core/internal/utils/credentials.ts","../src/core/client/types.ts","../src/core/internal/utils/http.ts","../src/core/collection/collection-client.ts","../src/core/query/query-client.ts"],"sourcesContent":["export * from './core/query'\n","import {\n isServer,\n QueryClient,\n defaultShouldDehydrateQuery,\n} from '@tanstack/react-query'\n\nfunction makeQueryClient() {\n return new QueryClient({\n defaultOptions: {\n queries: {\n // Infinite staleTime: server-fetched data persists until explicitly invalidated.\n // For browser clients needing fresher data, override per-query:\n // useQuery({ ..., staleTime: 5 * 60 * 1000 })\n staleTime: Number.POSITIVE_INFINITY,\n refetchOnWindowFocus: false,\n },\n dehydrate: {\n shouldDehydrateQuery: (query) =>\n defaultShouldDehydrateQuery(query) ||\n query.state.status === 'pending',\n shouldRedactErrors: () => false,\n },\n },\n })\n}\n\nlet browserQueryClient: QueryClient | undefined\n\nexport function getQueryClient() {\n if (isServer) {\n return makeQueryClient()\n }\n if (!browserQueryClient) {\n browserQueryClient = makeQueryClient()\n }\n return browserQueryClient\n}\n","import type { ServerCollection, ApiQueryOptions } from '../client/types'\nimport type { ProductListingGroupsQueryOptions } from './query-hooks'\n\nexport function collectionKeys<T extends ServerCollection>(collection: T) {\n return {\n all: [collection] as const,\n lists: () => [collection, 'list'] as const,\n list: (options?: ApiQueryOptions) => [collection, 'list', options] as const,\n details: () => [collection, 'detail'] as const,\n detail: (id: string, options?: ApiQueryOptions) =>\n [collection, 'detail', id, options] as const,\n infinites: () => [collection, 'infinite'] as const,\n infinite: (options?: Omit<ApiQueryOptions, 'page'>) =>\n [collection, 'infinite', options] as const,\n }\n}\n\nexport const customerKeys = {\n all: ['customer'] as const,\n me: () => ['customer', 'me'] as const,\n}\n\nexport const productKeys = {\n listingGroups: (options?: ProductListingGroupsQueryOptions) =>\n ['products', 'listing-groups', 'list', options] as const,\n listingGroupsInfinite: (\n options?: Omit<ProductListingGroupsQueryOptions, 'page' | 'limit'>,\n ) =>\n ['products', 'listing-groups', 'infinite', options] as const,\n detail: (params: { slug: string } | { id: string }) =>\n ['products', 'detail', params] as const,\n detailAll: () => ['products', 'detail'] as const,\n}\n","import {\n QueryClient,\n useQuery as useQueryOriginal,\n useSuspenseQuery as useSuspenseQueryOriginal,\n useInfiniteQuery as useInfiniteQueryOriginal,\n useSuspenseInfiniteQuery as useSuspenseInfiniteQueryOriginal,\n useMutation as useMutationOriginal,\n} from '@tanstack/react-query'\nimport type {\n InfiniteData,\n UseInfiniteQueryResult,\n UseQueryResult,\n UseSuspenseInfiniteQueryResult,\n UseSuspenseQueryResult,\n} from '@tanstack/react-query'\nimport type {\n PublicCollection,\n ServerCollection,\n ApiQueryOptions,\n PayloadFindResponse,\n PayloadMutationResponse,\n} from '../client/types'\nimport { type CollectionClient, type CollectionType } from '../collection'\nimport { SDKError } from '../internal/errors'\nimport { collectionKeys } from './query-keys'\n\n// ============================================================================\n// Query Params Types\n// ============================================================================\n\nexport interface CollectionQueryParams<T extends ServerCollection> {\n collection: T\n options?: ApiQueryOptions\n}\n\nexport interface CollectionDetailQueryParams<T extends ServerCollection> {\n collection: T\n id: string\n options?: ApiQueryOptions\n}\n\nexport interface CollectionInfiniteQueryParams<T extends ServerCollection> {\n collection: T\n options?: Omit<ApiQueryOptions, 'page'>\n pageSize?: number\n}\n\n// ============================================================================\n// Shared option types\n// ============================================================================\n\nexport interface QueryOptions<TQueryFnData = unknown, TData = TQueryFnData> {\n enabled?: boolean\n staleTime?: number\n gcTime?: number\n refetchOnWindowFocus?: boolean\n refetchOnMount?: boolean | 'always'\n refetchInterval?: number | false\n retry?: boolean | number\n select?: (data: TQueryFnData) => TData\n placeholderData?:\n | TQueryFnData\n | ((previousData: TData | undefined) => TQueryFnData | undefined)\n initialData?: TQueryFnData | (() => TQueryFnData)\n initialDataUpdatedAt?: number | (() => number | undefined)\n}\n\nexport type SuspenseQueryOptions<\n TQueryFnData = unknown,\n TData = TQueryFnData,\n> = Omit<QueryOptions<TQueryFnData, TData>, 'enabled' | 'placeholderData'>\n\n// placeholderData/initialData omitted: InfiniteData<T> structure is complex to construct\nexport interface InfiniteQueryOptions<\n TQueryFnData = unknown,\n TData = InfiniteData<TQueryFnData>,\n> {\n enabled?: boolean\n staleTime?: number\n gcTime?: number\n refetchOnWindowFocus?: boolean\n refetchOnMount?: boolean | 'always'\n refetchInterval?: number | false\n retry?: boolean | number\n select?: (data: InfiniteData<TQueryFnData>) => TData\n}\n\nexport type SuspenseInfiniteQueryOptions<\n TQueryFnData = unknown,\n TData = InfiniteData<TQueryFnData>,\n> = Omit<InfiniteQueryOptions<TQueryFnData, TData>, 'enabled'>\n\ninterface MutationCallbacks<TData> {\n onSuccess?: (data: TData) => void\n onError?: (error: SDKError) => void\n onSettled?: () => void\n}\n\n// ============================================================================\n// Product detail invalidation\n// ============================================================================\n\nconst PRODUCT_DETAIL_INVALIDATING_COLLECTIONS = new Set([\n 'products',\n 'product-variants',\n 'product-options',\n 'product-option-values',\n 'product-categories',\n 'product-tags',\n 'product-collections',\n 'brands',\n 'brand-logos',\n 'images',\n])\n\n// ============================================================================\n// Collection Hooks Mixin\n// ============================================================================\n\nconst DEFAULT_PAGE_SIZE = 20\n\nexport class CollectionHooks<TCollection extends ServerCollection = PublicCollection> {\n protected queryClient: QueryClient\n protected collectionClient: CollectionClient<TCollection>\n\n constructor(\n queryClient: QueryClient,\n collectionClient: CollectionClient<TCollection>,\n ) {\n this.queryClient = queryClient\n this.collectionClient = collectionClient\n }\n\n // ===== useQuery =====\n useQuery<\n T extends TCollection,\n TData = PayloadFindResponse<CollectionType<T>>,\n >(\n params: CollectionQueryParams<T>,\n options?: QueryOptions<PayloadFindResponse<CollectionType<T>>, TData>,\n ): UseQueryResult<TData> {\n const { collection, options: queryOptions } = params\n const { placeholderData, ...restOptions } = (options ?? {}) as QueryOptions<\n PayloadFindResponse<CollectionType<T>>,\n TData\n >\n\n return useQueryOriginal({\n queryKey: collectionKeys(collection).list(queryOptions),\n queryFn: async () => {\n return await this.collectionClient\n .from(collection)\n .find(queryOptions)\n },\n ...restOptions,\n // NonFunctionGuard<T> incompatible with generic union types — safe cast\n ...(placeholderData !== undefined && {\n placeholderData: placeholderData as never,\n }),\n })\n }\n\n // ===== useSuspenseQuery =====\n useSuspenseQuery<\n T extends TCollection,\n TData = PayloadFindResponse<CollectionType<T>>,\n >(\n params: CollectionQueryParams<T>,\n options?: SuspenseQueryOptions<\n PayloadFindResponse<CollectionType<T>>,\n TData\n >,\n ): UseSuspenseQueryResult<TData> {\n const { collection, options: queryOptions } = params\n\n return useSuspenseQueryOriginal({\n queryKey: collectionKeys(collection).list(queryOptions),\n queryFn: async () => {\n return await this.collectionClient\n .from(collection)\n .find(queryOptions)\n },\n ...options,\n })\n }\n\n // ===== useQueryById =====\n useQueryById<T extends TCollection, TData = CollectionType<T>>(\n params: CollectionDetailQueryParams<T>,\n options?: QueryOptions<CollectionType<T>, TData>,\n ): UseQueryResult<TData> {\n const { collection, id, options: queryOptions } = params\n const { placeholderData, ...restOptions } = (options ?? {}) as QueryOptions<\n CollectionType<T>,\n TData\n >\n\n return useQueryOriginal({\n queryKey: collectionKeys(collection).detail(id, queryOptions),\n queryFn: async () => {\n return await this.collectionClient\n .from(collection)\n .findById(id, queryOptions)\n },\n ...restOptions,\n // NonFunctionGuard<T> incompatible with generic union types — safe cast\n ...(placeholderData !== undefined && {\n placeholderData: placeholderData as never,\n }),\n })\n }\n\n // ===== useSuspenseQueryById =====\n useSuspenseQueryById<T extends TCollection, TData = CollectionType<T>>(\n params: CollectionDetailQueryParams<T>,\n options?: SuspenseQueryOptions<CollectionType<T>, TData>,\n ): UseSuspenseQueryResult<TData> {\n const { collection, id, options: queryOptions } = params\n\n return useSuspenseQueryOriginal({\n queryKey: collectionKeys(collection).detail(id, queryOptions),\n queryFn: async () => {\n return await this.collectionClient\n .from(collection)\n .findById(id, queryOptions)\n },\n ...options,\n })\n }\n\n // ===== useInfiniteQuery =====\n useInfiniteQuery<\n T extends TCollection,\n TData = InfiniteData<PayloadFindResponse<CollectionType<T>>>,\n >(\n params: CollectionInfiniteQueryParams<T>,\n options?: InfiniteQueryOptions<\n PayloadFindResponse<CollectionType<T>>,\n TData\n >,\n ): UseInfiniteQueryResult<TData> {\n const {\n collection,\n options: queryOptions,\n pageSize = DEFAULT_PAGE_SIZE,\n } = params\n\n return useInfiniteQueryOriginal({\n queryKey: collectionKeys(collection).infinite(queryOptions),\n queryFn: async ({ pageParam }) => {\n const response = await this.collectionClient\n .from(collection)\n .find({ ...queryOptions, page: pageParam, limit: pageSize })\n return response\n },\n initialPageParam: 1,\n getNextPageParam: (lastPage: PayloadFindResponse<CollectionType<T>>) => {\n return lastPage.hasNextPage ? lastPage.nextPage : undefined\n },\n ...options,\n })\n }\n\n // ===== useSuspenseInfiniteQuery =====\n useSuspenseInfiniteQuery<\n T extends TCollection,\n TData = InfiniteData<PayloadFindResponse<CollectionType<T>>>,\n >(\n params: CollectionInfiniteQueryParams<T>,\n options?: SuspenseInfiniteQueryOptions<\n PayloadFindResponse<CollectionType<T>>,\n TData\n >,\n ): UseSuspenseInfiniteQueryResult<TData> {\n const {\n collection,\n options: queryOptions,\n pageSize = DEFAULT_PAGE_SIZE,\n } = params\n\n return useSuspenseInfiniteQueryOriginal({\n queryKey: collectionKeys(collection).infinite(queryOptions),\n queryFn: async ({ pageParam }) => {\n const response = await this.collectionClient\n .from(collection)\n .find({ ...queryOptions, page: pageParam, limit: pageSize })\n return response\n },\n initialPageParam: 1,\n getNextPageParam: (lastPage: PayloadFindResponse<CollectionType<T>>) => {\n return lastPage.hasNextPage ? lastPage.nextPage : undefined\n },\n ...options,\n })\n }\n\n // ===== prefetchQuery =====\n async prefetchQuery<T extends TCollection>(\n params: CollectionQueryParams<T>,\n options?: { staleTime?: number },\n ) {\n const { collection, options: queryOptions } = params\n\n return this.queryClient.prefetchQuery({\n queryKey: collectionKeys(collection).list(queryOptions),\n queryFn: async () => {\n return await this.collectionClient\n .from(collection)\n .find(queryOptions)\n },\n ...options,\n })\n }\n\n // ===== prefetchQueryById =====\n async prefetchQueryById<T extends TCollection>(\n params: CollectionDetailQueryParams<T>,\n options?: { staleTime?: number },\n ) {\n const { collection, id, options: queryOptions } = params\n\n return this.queryClient.prefetchQuery({\n queryKey: collectionKeys(collection).detail(id, queryOptions),\n queryFn: async () => {\n return await this.collectionClient\n .from(collection)\n .findById(id, queryOptions)\n },\n ...options,\n })\n }\n\n // ===== prefetchInfiniteQuery =====\n async prefetchInfiniteQuery<T extends TCollection>(\n params: CollectionInfiniteQueryParams<T>,\n options?: { pages?: number; staleTime?: number },\n ) {\n const {\n collection,\n options: queryOptions,\n pageSize = DEFAULT_PAGE_SIZE,\n } = params\n\n return this.queryClient.prefetchInfiniteQuery({\n queryKey: collectionKeys(collection).infinite(queryOptions),\n queryFn: async ({ pageParam }) => {\n const response = await this.collectionClient\n .from(collection)\n .find({ ...queryOptions, page: pageParam, limit: pageSize })\n return response\n },\n initialPageParam: 1,\n getNextPageParam: (lastPage: PayloadFindResponse<CollectionType<T>>) => {\n return lastPage.hasNextPage ? lastPage.nextPage : undefined\n },\n pages: options?.pages ?? 1,\n staleTime: options?.staleTime,\n })\n }\n\n // ===== Mutation Hooks =====\n\n useCreate<T extends TCollection>(\n params: { collection: T },\n options?: MutationCallbacks<PayloadMutationResponse<CollectionType<T>>>,\n ) {\n const { collection } = params\n\n return useMutationOriginal<\n PayloadMutationResponse<CollectionType<T>>,\n SDKError,\n {\n data: Partial<CollectionType<T>>\n file?: File | Blob\n filename?: string\n }\n >({\n mutationFn: async (variables) => {\n return await this.collectionClient\n .from(collection)\n .create(\n variables.data,\n variables.file\n ? { file: variables.file, filename: variables.filename }\n : undefined,\n )\n },\n onSuccess: (data) => {\n this.queryClient.invalidateQueries({\n queryKey: collectionKeys(collection).all,\n })\n if (PRODUCT_DETAIL_INVALIDATING_COLLECTIONS.has(collection)) {\n this.queryClient.invalidateQueries({ queryKey: ['products', 'detail'] })\n }\n options?.onSuccess?.(data)\n },\n onError: options?.onError,\n onSettled: options?.onSettled,\n })\n }\n\n useUpdate<T extends TCollection>(\n params: { collection: T },\n options?: MutationCallbacks<PayloadMutationResponse<CollectionType<T>>>,\n ) {\n const { collection } = params\n\n return useMutationOriginal<\n PayloadMutationResponse<CollectionType<T>>,\n SDKError,\n {\n id: string\n data: Partial<CollectionType<T>>\n file?: File | Blob\n filename?: string\n }\n >({\n mutationFn: async (variables) => {\n return await this.collectionClient\n .from(collection)\n .update(\n variables.id,\n variables.data,\n variables.file\n ? { file: variables.file, filename: variables.filename }\n : undefined,\n )\n },\n onSuccess: (data) => {\n this.queryClient.invalidateQueries({\n queryKey: collectionKeys(collection).all,\n })\n if (PRODUCT_DETAIL_INVALIDATING_COLLECTIONS.has(collection)) {\n this.queryClient.invalidateQueries({ queryKey: ['products', 'detail'] })\n }\n options?.onSuccess?.(data)\n },\n onError: options?.onError,\n onSettled: options?.onSettled,\n })\n }\n\n useRemove<T extends TCollection>(\n params: { collection: T },\n options?: MutationCallbacks<CollectionType<T>>,\n ) {\n const { collection } = params\n\n return useMutationOriginal<CollectionType<T>, SDKError, string>({\n mutationFn: async (id) => {\n return await this.collectionClient.from(collection).remove(id)\n },\n onSuccess: (data) => {\n this.queryClient.invalidateQueries({\n queryKey: collectionKeys(collection).all,\n })\n if (PRODUCT_DETAIL_INVALIDATING_COLLECTIONS.has(collection)) {\n this.queryClient.invalidateQueries({ queryKey: ['products', 'detail'] })\n }\n options?.onSuccess?.(data)\n },\n onError: options?.onError,\n onSettled: options?.onSettled,\n })\n }\n\n // ===== Cache Utilities =====\n\n invalidateQueries<T extends TCollection>(\n collection: T,\n type?: 'list' | 'detail' | 'infinite',\n ) {\n const queryKey = type ? [collection, type] : [collection]\n return this.queryClient.invalidateQueries({ queryKey })\n }\n\n getQueryData<T extends TCollection>(\n collection: T,\n type: 'list',\n options?: ApiQueryOptions,\n ): PayloadFindResponse<CollectionType<T>> | undefined\n getQueryData<T extends TCollection>(\n collection: T,\n type: 'detail',\n id: string,\n options?: ApiQueryOptions,\n ): CollectionType<T> | null | undefined\n getQueryData<T extends TCollection>(\n collection: T,\n type: 'list' | 'detail',\n idOrOptions?: string | ApiQueryOptions,\n options?: ApiQueryOptions,\n ) {\n if (type === 'list') {\n return this.queryClient.getQueryData(\n collectionKeys(collection).list(idOrOptions as ApiQueryOptions),\n )\n }\n return this.queryClient.getQueryData(\n collectionKeys(collection).detail(idOrOptions as string, options),\n )\n }\n\n setQueryData<T extends TCollection>(\n collection: T,\n type: 'list',\n data: PayloadFindResponse<CollectionType<T>>,\n options?: ApiQueryOptions,\n ): void\n setQueryData<T extends TCollection>(\n collection: T,\n type: 'detail',\n id: string,\n data: CollectionType<T> | null,\n options?: ApiQueryOptions,\n ): void\n setQueryData<T extends TCollection>(\n collection: T,\n type: 'list' | 'detail',\n dataOrId: PayloadFindResponse<CollectionType<T>> | string,\n dataOrOptions?: CollectionType<T> | null | ApiQueryOptions,\n options?: ApiQueryOptions,\n ) {\n if (type === 'list') {\n this.queryClient.setQueryData(\n collectionKeys(collection).list(dataOrOptions as ApiQueryOptions),\n dataOrId as PayloadFindResponse<CollectionType<T>>,\n )\n } else {\n this.queryClient.setQueryData(\n collectionKeys(collection).detail(dataOrId as string, options),\n dataOrOptions as CollectionType<T> | null,\n )\n }\n }\n}\n","import {\n QueryClient,\n useQuery as useQueryOriginal,\n useMutation as useMutationOriginal,\n} from '@tanstack/react-query'\nimport type { CustomerAuth } from '../customer/customer-auth'\nimport type {\n CustomerAuthResponse,\n CustomerRefreshResponse,\n CustomerProfile,\n CustomerRegisterData,\n CustomerLoginData,\n UpdateProfileData,\n} from '../customer/types'\nimport { createConfigError, SDKError } from '../internal/errors'\nimport { customerKeys } from './query-keys'\n\n// ============================================================================\n// Mutation helper\n// ============================================================================\n\ninterface MutationCallbacks<TData> {\n onSuccess?: (data: TData) => void\n onError?: (error: SDKError) => void\n onSettled?: () => void\n}\n\nfunction createMutation<TData, TVariables>(\n mutationFn: (variables: TVariables) => Promise<TData>,\n callbacks?: MutationCallbacks<TData>,\n onSuccessExtra?: (data: TData) => void,\n) {\n return useMutationOriginal({\n mutationFn,\n onSuccess: (data) => {\n onSuccessExtra?.(data)\n callbacks?.onSuccess?.(data)\n },\n onError: callbacks?.onError,\n onSettled: callbacks?.onSettled,\n })\n}\n\n// ============================================================================\n// Customer Hooks Mixin\n// ============================================================================\n\nexport class CustomerHooks {\n private queryClient: QueryClient\n private customerAuth?: CustomerAuth\n\n constructor(queryClient: QueryClient, customerAuth?: CustomerAuth) {\n this.queryClient = queryClient\n this.customerAuth = customerAuth\n }\n\n private ensureCustomerAuth(): CustomerAuth {\n if (!this.customerAuth) {\n throw createConfigError(\n 'Customer hooks require Client. Use createClient() instead of createServerClient().',\n )\n }\n return this.customerAuth\n }\n\n private invalidateMe = () => {\n this.queryClient.invalidateQueries({ queryKey: customerKeys.me() })\n }\n\n // ===== useCustomerMe =====\n useCustomerMe(options?: {\n enabled?: boolean\n staleTime?: number\n gcTime?: number\n refetchOnWindowFocus?: boolean\n refetchOnMount?: boolean | 'always'\n refetchInterval?: number | false\n retry?: boolean | number\n }) {\n return useQueryOriginal({\n queryKey: customerKeys.me(),\n queryFn: async () => {\n return await this.ensureCustomerAuth().me()\n },\n ...options,\n enabled:\n (options?.enabled ?? true) && !!this.customerAuth?.isAuthenticated(),\n })\n }\n\n // ===== Mutations =====\n\n useCustomerLogin(options?: MutationCallbacks<CustomerAuthResponse>) {\n return createMutation(\n (data: CustomerLoginData) => this.ensureCustomerAuth().login(data),\n options,\n this.invalidateMe,\n )\n }\n\n useCustomerRegister(\n options?: MutationCallbacks<{ customer: CustomerProfile }>,\n ) {\n return createMutation(\n (data: CustomerRegisterData) => this.ensureCustomerAuth().register(data),\n options,\n )\n }\n\n useCustomerLogout(options?: MutationCallbacks<void>) {\n return useMutationOriginal({\n mutationFn: async () => {\n this.ensureCustomerAuth().logout()\n },\n onSuccess: () => {\n this.queryClient.removeQueries({ queryKey: customerKeys.all })\n options?.onSuccess?.()\n },\n onError: options?.onError,\n onSettled: options?.onSettled,\n })\n }\n\n useCustomerForgotPassword(options?: MutationCallbacks<void>) {\n return createMutation(\n (email: string) =>\n this.ensureCustomerAuth()\n .forgotPassword(email)\n .then(() => {}),\n options,\n )\n }\n\n useCustomerResetPassword(options?: MutationCallbacks<void>) {\n return createMutation(\n (data: { token: string; password: string }) =>\n this.ensureCustomerAuth()\n .resetPassword(data.token, data.password)\n .then(() => {}),\n options,\n )\n }\n\n useCustomerRefreshToken(\n options?: MutationCallbacks<CustomerRefreshResponse>,\n ) {\n return createMutation(\n () => this.ensureCustomerAuth().refreshToken(),\n options,\n this.invalidateMe,\n )\n }\n\n useCustomerUpdateProfile(options?: MutationCallbacks<CustomerProfile>) {\n return createMutation(\n (data: UpdateProfileData) =>\n this.ensureCustomerAuth().updateProfile(data),\n options,\n this.invalidateMe,\n )\n }\n\n useCustomerChangePassword(options?: MutationCallbacks<void>) {\n return createMutation(\n (data: { currentPassword: string; newPassword: string }) =>\n this.ensureCustomerAuth()\n .changePassword(data.currentPassword, data.newPassword)\n .then(() => {}),\n options,\n )\n }\n\n // ===== Customer Cache Utilities =====\n\n invalidateCustomerQueries() {\n return this.queryClient.invalidateQueries({ queryKey: customerKeys.all })\n }\n\n getCustomerData(): CustomerProfile | null | undefined {\n return this.queryClient.getQueryData(customerKeys.me())\n }\n\n setCustomerData(data: CustomerProfile | null) {\n this.queryClient.setQueryData(customerKeys.me(), data)\n }\n}\n","export class SDKError extends Error {\n readonly code: string\n readonly status?: number\n readonly details?: unknown\n readonly userMessage?: string\n readonly suggestion?: string\n readonly requestId?: string\n\n constructor(\n code: string,\n message: string,\n status?: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n ) {\n super(message)\n this.name = 'SDKError'\n this.code = code\n this.status = status\n this.details = details\n this.userMessage = userMessage\n this.suggestion = suggestion\n this.requestId = requestId\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, new.target)\n }\n }\n\n getUserMessage(): string {\n return this.userMessage || this.message\n }\n\n toJSON() {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n status: this.status,\n details: this.details,\n userMessage: this.userMessage,\n suggestion: this.suggestion,\n ...(this.requestId !== undefined && { requestId: this.requestId }),\n }\n }\n}\n\nexport class NetworkError extends SDKError {\n constructor(\n message: string,\n status?: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n ) {\n super('NETWORK_ERROR', message, status, details, userMessage, suggestion)\n this.name = 'NetworkError'\n }\n}\n\nexport class ValidationError extends SDKError {\n constructor(\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n status = 400,\n ) {\n super('VALIDATION_ERROR', message, status, details, userMessage, suggestion)\n this.name = 'ValidationError'\n }\n}\n\nexport class ApiError extends SDKError {\n constructor(\n message: string,\n status: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n ) {\n super(\n 'API_ERROR',\n message,\n status,\n details,\n userMessage,\n suggestion,\n requestId,\n )\n this.name = 'ApiError'\n }\n}\n\nexport class ConfigError extends SDKError {\n constructor(\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n ) {\n super('CONFIG_ERROR', message, undefined, details, userMessage, suggestion)\n this.name = 'ConfigError'\n }\n}\n\nexport class TimeoutError extends SDKError {\n constructor(\n message = 'Request timed out.',\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n ) {\n super('TIMEOUT_ERROR', message, 408, details, userMessage, suggestion)\n this.name = 'TimeoutError'\n }\n}\n\nexport class GoneError extends SDKError {\n constructor(\n message = 'The requested resource is no longer available.',\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n ) {\n super('GONE_ERROR', message, 410, details, userMessage, suggestion)\n this.name = 'GoneError'\n }\n}\n\nexport class ServiceUnavailableError extends SDKError {\n readonly retryAfter?: number\n\n constructor(\n message = 'Service temporarily unavailable.',\n retryAfter?: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n ) {\n super(\n 'SERVICE_UNAVAILABLE_ERROR',\n message,\n 503,\n details,\n userMessage,\n suggestion,\n )\n this.name = 'ServiceUnavailableError'\n this.retryAfter = retryAfter\n }\n}\n\nexport class UsageLimitError extends SDKError {\n readonly usage: { limit: number; current: number; remaining: number }\n\n constructor(\n message: string,\n usage: { limit: number; current: number; remaining: number },\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n ) {\n super('USAGE_LIMIT_ERROR', message, 429, details, userMessage, suggestion)\n this.name = 'UsageLimitError'\n this.usage = usage\n }\n\n toJSON() {\n return {\n ...super.toJSON(),\n usage: this.usage,\n }\n }\n}\n\nexport class AuthError extends SDKError {\n constructor(\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n ) {\n super(\n 'auth_error',\n message,\n 401,\n details,\n userMessage,\n suggestion,\n requestId,\n )\n this.name = 'AuthError'\n }\n}\n\nexport class PermissionError extends SDKError {\n constructor(\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n ) {\n super(\n 'permission_error',\n message,\n 403,\n details,\n userMessage,\n suggestion,\n requestId,\n )\n this.name = 'PermissionError'\n }\n}\n\nexport class NotFoundError extends SDKError {\n constructor(\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n ) {\n super(\n 'not_found',\n message,\n 404,\n details,\n userMessage,\n suggestion,\n requestId,\n )\n this.name = 'NotFoundError'\n }\n}\n\nexport class ConflictError extends SDKError {\n constructor(\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n ) {\n super('conflict', message, 409, details, userMessage, suggestion, requestId)\n this.name = 'ConflictError'\n }\n}\n\nexport class RateLimitError extends SDKError {\n readonly retryAfter?: number\n\n constructor(\n message: string,\n retryAfter?: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n ) {\n super(\n 'rate_limit_exceeded',\n message,\n 429,\n details,\n userMessage,\n suggestion,\n requestId,\n )\n this.name = 'RateLimitError'\n this.retryAfter = retryAfter\n }\n}\n\nexport function isSDKError(error: unknown): error is SDKError {\n return error instanceof SDKError\n}\n\nexport function isNetworkError(error: unknown): error is NetworkError {\n return error instanceof NetworkError\n}\n\nexport function isValidationError(error: unknown): error is ValidationError {\n return error instanceof ValidationError\n}\n\nexport function isApiError(error: unknown): error is ApiError {\n return error instanceof ApiError\n}\n\nexport function isConfigError(error: unknown): error is ConfigError {\n return error instanceof ConfigError\n}\n\nexport function isTimeoutError(error: unknown): error is TimeoutError {\n return error instanceof TimeoutError\n}\n\nexport function isGoneError(error: unknown): error is GoneError {\n return error instanceof GoneError\n}\n\nexport function isServiceUnavailableError(\n error: unknown,\n): error is ServiceUnavailableError {\n return error instanceof ServiceUnavailableError\n}\n\nexport function isUsageLimitError(error: unknown): error is UsageLimitError {\n return error instanceof UsageLimitError\n}\n\nexport function isAuthError(error: unknown): error is AuthError {\n return error instanceof AuthError\n}\n\nexport function isPermissionError(error: unknown): error is PermissionError {\n return error instanceof PermissionError\n}\n\nexport function isNotFoundError(error: unknown): error is NotFoundError {\n return error instanceof NotFoundError\n}\n\nexport function isConflictError(error: unknown): error is ConflictError {\n return error instanceof ConflictError\n}\n\nexport function isRateLimitError(error: unknown): error is RateLimitError {\n return error instanceof RateLimitError\n}\n\nexport const createNetworkError = (\n message: string,\n status?: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n) => new NetworkError(message, status, details, userMessage, suggestion)\n\nexport const createValidationError = (\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n status?: number,\n) => new ValidationError(message, details, userMessage, suggestion, status)\n\nexport const createApiError = (\n message: string,\n status: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n) => new ApiError(message, status, details, userMessage, suggestion, requestId)\n\nexport const createConfigError = (\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n) => new ConfigError(message, details, userMessage, suggestion)\n\nexport const createTimeoutError = (\n message?: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n) => new TimeoutError(message, details, userMessage, suggestion)\n\nexport const createGoneError = (\n message?: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n) => new GoneError(message, details, userMessage, suggestion)\n\nexport const createServiceUnavailableError = (\n message?: string,\n retryAfter?: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n) =>\n new ServiceUnavailableError(\n message,\n retryAfter,\n details,\n userMessage,\n suggestion,\n )\n\nexport const createUsageLimitError = (\n message: string,\n usage: { limit: number; current: number; remaining: number },\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n) => new UsageLimitError(message, usage, details, userMessage, suggestion)\n\nexport const createAuthError = (\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n) => new AuthError(message, details, userMessage, suggestion, requestId)\n\nexport const createPermissionError = (\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n) => new PermissionError(message, details, userMessage, suggestion, requestId)\n\nexport const createNotFoundError = (\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n) => new NotFoundError(message, details, userMessage, suggestion, requestId)\n\nexport const createConflictError = (\n message: string,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n) => new ConflictError(message, details, userMessage, suggestion, requestId)\n\nexport const createRateLimitError = (\n message: string,\n retryAfter?: number,\n details?: unknown,\n userMessage?: string,\n suggestion?: string,\n requestId?: string,\n) =>\n new RateLimitError(\n message,\n retryAfter,\n details,\n userMessage,\n suggestion,\n requestId,\n )\n","import {\n QueryClient,\n useInfiniteQuery as useInfiniteQueryOriginal,\n useQuery as useQueryOriginal,\n useSuspenseInfiniteQuery as useSuspenseInfiniteQueryOriginal,\n useSuspenseQuery as useSuspenseQueryOriginal,\n} from '@tanstack/react-query'\nimport type {\n InfiniteData,\n UseInfiniteQueryResult,\n UseQueryResult,\n UseSuspenseInfiniteQueryResult,\n UseSuspenseQueryResult,\n} from '@tanstack/react-query'\nimport type {\n ApiQueryOptions,\n PayloadFindResponse,\n PublicCollection,\n ServerCollection,\n} from '../client/types'\nimport type { CustomerAuth } from '../customer/customer-auth'\nimport type { CollectionClient } from '../collection'\nimport type { ProductListingGroupsItem, ProductDetail, ProductDetailParams } from '../api'\nimport { CollectionHooks } from './collection-hooks'\nimport { CustomerHooks } from './customer-hooks'\nimport { productKeys } from './query-keys'\nimport type {\n InfiniteQueryOptions,\n QueryOptions,\n SuspenseInfiniteQueryOptions,\n SuspenseQueryOptions,\n} from './collection-hooks'\n\n// Re-export everything from sub-modules for barrel compatibility\nexport { collectionKeys, customerKeys } from './query-keys'\nexport { productKeys } from './query-keys'\nexport type {\n CollectionQueryParams,\n CollectionDetailQueryParams,\n CollectionInfiniteQueryParams,\n QueryOptions,\n SuspenseQueryOptions,\n InfiniteQueryOptions,\n SuspenseInfiniteQueryOptions,\n} from './collection-hooks'\n\nexport type ProductListingGroupsQueryOptions = Pick<\n ApiQueryOptions,\n 'page' | 'limit' | 'sort' | 'where'\n>\n\nexport type ReadOnlyQueryHooks = Omit<\n QueryHooks<PublicCollection>,\n 'useCreate' | 'useUpdate' | 'useRemove'\n>\n\n/**\n * Composes CollectionHooks + CustomerHooks into a single API surface.\n * All methods are delegated; no logic lives here.\n */\ninterface ProductDetailCallable {\n product: {\n detail: (params: ProductDetailParams) => Promise<ProductDetail | null>\n }\n}\n\nexport class QueryHooks<\n TCollection extends ServerCollection = PublicCollection,\n> extends CollectionHooks<TCollection> {\n private _customer: CustomerHooks\n private _commerce?: ProductDetailCallable\n\n constructor(\n queryClient: QueryClient,\n collectionClient: CollectionClient<TCollection>,\n customerAuth?: CustomerAuth,\n commerceClient?: ProductDetailCallable,\n ) {\n super(queryClient, collectionClient)\n this._customer = new CustomerHooks(queryClient, customerAuth)\n this._commerce = commerceClient\n }\n\n // --- Customer hooks delegation ---\n useCustomerMe: CustomerHooks['useCustomerMe'] = (...args) =>\n this._customer.useCustomerMe(...args)\n useCustomerLogin: CustomerHooks['useCustomerLogin'] = (...args) =>\n this._customer.useCustomerLogin(...args)\n useCustomerRegister: CustomerHooks['useCustomerRegister'] = (...args) =>\n this._customer.useCustomerRegister(...args)\n useCustomerLogout: CustomerHooks['useCustomerLogout'] = (...args) =>\n this._customer.useCustomerLogout(...args)\n useCustomerForgotPassword: CustomerHooks['useCustomerForgotPassword'] = (\n ...args\n ) => this._customer.useCustomerForgotPassword(...args)\n useCustomerResetPassword: CustomerHooks['useCustomerResetPassword'] = (\n ...args\n ) => this._customer.useCustomerResetPassword(...args)\n useCustomerRefreshToken: CustomerHooks['useCustomerRefreshToken'] = (\n ...args\n ) => this._customer.useCustomerRefreshToken(...args)\n useCustomerUpdateProfile: CustomerHooks['useCustomerUpdateProfile'] = (\n ...args\n ) => this._customer.useCustomerUpdateProfile(...args)\n useCustomerChangePassword: CustomerHooks['useCustomerChangePassword'] = (\n ...args\n ) => this._customer.useCustomerChangePassword(...args)\n\n // --- Customer cache delegation ---\n invalidateCustomerQueries: CustomerHooks['invalidateCustomerQueries'] = () =>\n this._customer.invalidateCustomerQueries()\n getCustomerData: CustomerHooks['getCustomerData'] = () =>\n this._customer.getCustomerData()\n setCustomerData: CustomerHooks['setCustomerData'] = (data) =>\n this._customer.setCustomerData(data)\n\n useProductListingGroupsQuery<\n TData = PayloadFindResponse<ProductListingGroupsItem>,\n >(\n params: { options?: ProductListingGroupsQueryOptions },\n options?: QueryOptions<PayloadFindResponse<ProductListingGroupsItem>, TData>,\n ): UseQueryResult<TData> {\n const queryOptions = params.options\n const { placeholderData, ...restOptions } = (options ?? {}) as QueryOptions<\n PayloadFindResponse<ProductListingGroupsItem>,\n TData\n >\n\n return useQueryOriginal({\n queryKey: productKeys.listingGroups(queryOptions),\n queryFn: async () =>\n this.collectionClient.requestFindEndpoint<ProductListingGroupsItem>(\n '/api/products/listing-groups/query',\n { options: queryOptions },\n ),\n ...restOptions,\n ...(placeholderData !== undefined && {\n placeholderData: placeholderData as never,\n }),\n })\n }\n\n useSuspenseProductListingGroupsQuery<\n TData = PayloadFindResponse<ProductListingGroupsItem>,\n >(\n params: { options?: ProductListingGroupsQueryOptions },\n options?: SuspenseQueryOptions<\n PayloadFindResponse<ProductListingGroupsItem>,\n TData\n >,\n ): UseSuspenseQueryResult<TData> {\n const queryOptions = params.options\n\n return useSuspenseQueryOriginal({\n queryKey: productKeys.listingGroups(queryOptions),\n queryFn: async () =>\n this.collectionClient.requestFindEndpoint<ProductListingGroupsItem>(\n '/api/products/listing-groups/query',\n { options: queryOptions },\n ),\n ...options,\n })\n }\n\n useInfiniteProductListingGroupsQuery<\n TData = InfiniteData<PayloadFindResponse<ProductListingGroupsItem>>,\n >(\n params: {\n options?: Omit<ProductListingGroupsQueryOptions, 'page' | 'limit'>\n pageSize?: number\n },\n options?: InfiniteQueryOptions<\n PayloadFindResponse<ProductListingGroupsItem>,\n TData\n >,\n ): UseInfiniteQueryResult<TData> {\n const {\n options: queryOptions,\n pageSize = 20,\n } = params\n\n return useInfiniteQueryOriginal({\n queryKey: productKeys.listingGroupsInfinite(queryOptions),\n queryFn: async ({ pageParam }) =>\n this.collectionClient.requestFindEndpoint<ProductListingGroupsItem>(\n '/api/products/listing-groups/query',\n {\n options: { ...queryOptions, page: pageParam, limit: pageSize },\n },\n ),\n initialPageParam: 1,\n getNextPageParam: (\n lastPage: PayloadFindResponse<ProductListingGroupsItem>,\n ) => (lastPage.hasNextPage ? lastPage.nextPage : undefined),\n ...options,\n })\n }\n\n useSuspenseInfiniteProductListingGroupsQuery<\n TData = InfiniteData<PayloadFindResponse<ProductListingGroupsItem>>,\n >(\n params: {\n options?: Omit<ProductListingGroupsQueryOptions, 'page' | 'limit'>\n pageSize?: number\n },\n options?: SuspenseInfiniteQueryOptions<\n PayloadFindResponse<ProductListingGroupsItem>,\n TData\n >,\n ): UseSuspenseInfiniteQueryResult<TData> {\n const {\n options: queryOptions,\n pageSize = 20,\n } = params\n\n return useSuspenseInfiniteQueryOriginal({\n queryKey: productKeys.listingGroupsInfinite(queryOptions),\n queryFn: async ({ pageParam }) =>\n this.collectionClient.requestFindEndpoint<ProductListingGroupsItem>(\n '/api/products/listing-groups/query',\n {\n options: { ...queryOptions, page: pageParam, limit: pageSize },\n },\n ),\n initialPageParam: 1,\n getNextPageParam: (\n lastPage: PayloadFindResponse<ProductListingGroupsItem>,\n ) => (lastPage.hasNextPage ? lastPage.nextPage : undefined),\n ...options,\n })\n }\n\n async prefetchProductListingGroupsQuery(\n params: { options?: ProductListingGroupsQueryOptions },\n options?: { staleTime?: number },\n ) {\n const queryOptions = params.options\n\n return this.queryClient.prefetchQuery({\n queryKey: productKeys.listingGroups(queryOptions),\n queryFn: async () =>\n this.collectionClient.requestFindEndpoint<ProductListingGroupsItem>(\n '/api/products/listing-groups/query',\n { options: queryOptions },\n ),\n ...options,\n })\n }\n\n async prefetchInfiniteProductListingGroupsQuery(\n params: {\n options?: Omit<ProductListingGroupsQueryOptions, 'page' | 'limit'>\n pageSize?: number\n },\n options?: { pages?: number; staleTime?: number },\n ) {\n const {\n options: queryOptions,\n pageSize = 20,\n } = params\n\n return this.queryClient.prefetchInfiniteQuery({\n queryKey: productKeys.listingGroupsInfinite(queryOptions),\n queryFn: async ({ pageParam }) =>\n this.collectionClient.requestFindEndpoint<ProductListingGroupsItem>(\n '/api/products/listing-groups/query',\n {\n options: { ...queryOptions, page: pageParam, limit: pageSize },\n },\n ),\n initialPageParam: 1,\n getNextPageParam: (\n lastPage: PayloadFindResponse<ProductListingGroupsItem>,\n ) => (lastPage.hasNextPage ? lastPage.nextPage : undefined),\n pages: options?.pages ?? 1,\n staleTime: options?.staleTime,\n })\n }\n\n useProductDetail(\n params: { slug: string } | { id: string },\n options?: { enabled?: boolean },\n ): UseQueryResult<ProductDetail | null> {\n const discriminator = 'slug' in params ? params.slug : params.id\n const enabled = options?.enabled !== false && Boolean(discriminator)\n\n return useQueryOriginal({\n queryKey: productKeys.detail(params),\n queryFn: () => this._commerce!.product.detail(params),\n enabled,\n }) as UseQueryResult<ProductDetail | null>\n }\n\n useProductDetailBySlug(\n slug: string,\n options?: { enabled?: boolean },\n ): UseQueryResult<ProductDetail | null> {\n return this.useProductDetail({ slug }, options)\n }\n\n useProductDetailById(\n id: string,\n options?: { enabled?: boolean },\n ): UseQueryResult<ProductDetail | null> {\n return this.useProductDetail({ id }, options)\n }\n}\n","/**\n * Fetch-based SSE connection manager for real-time collection change events.\n * Uses fetch + ReadableStream to support custom auth headers (unlike native EventSource).\n */\n\nexport interface RealtimeEvent {\n collection: string\n operation: string\n id: string | null\n timestamp: string\n}\n\nexport type RealtimeListener = (event: RealtimeEvent) => void\n\nconst INITIAL_RECONNECT_DELAY = 1_000\nconst MAX_RECONNECT_DELAY = 30_000\nconst RECONNECT_BACKOFF_FACTOR = 2\nconst MAX_NO_TOKEN_RETRIES = 5\n\nexport class RealtimeConnection {\n private abortController: AbortController | null = null\n private reconnectAttempt = 0\n private noTokenAttempts = 0\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null\n private listeners = new Set<RealtimeListener>()\n private _connected = false\n\n constructor(\n private baseUrl: string,\n private publishableKey: string,\n private getToken: () => string | null,\n private collections?: string[],\n ) {}\n\n get connected(): boolean {\n return this._connected\n }\n\n addListener(fn: RealtimeListener): () => void {\n this.listeners.add(fn)\n return () => this.listeners.delete(fn)\n }\n\n connect(): void {\n if (this.abortController) return // Already connecting/connected\n\n this.abortController = new AbortController()\n this.startStream(this.abortController.signal)\n }\n\n disconnect(): void {\n this._connected = false\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer)\n this.reconnectTimer = null\n }\n if (this.abortController) {\n this.abortController.abort()\n this.abortController = null\n }\n this.reconnectAttempt = 0\n this.noTokenAttempts = 0\n }\n\n private async startStream(signal: AbortSignal): Promise<void> {\n const token = this.getToken()\n if (!token) {\n this.noTokenAttempts++\n if (this.noTokenAttempts >= MAX_NO_TOKEN_RETRIES) {\n // Stop reconnecting — no token available after multiple attempts\n this._connected = false\n this.abortController = null\n return\n }\n this.scheduleReconnect()\n return\n }\n this.noTokenAttempts = 0\n\n const params = this.collections?.length\n ? `?collections=${this.collections.join(',')}`\n : ''\n const url = `${this.baseUrl}/api/events/stream${params}`\n\n try {\n const response = await fetch(url, {\n headers: {\n 'X-Publishable-Key': this.publishableKey,\n Authorization: `Bearer ${token}`,\n },\n signal,\n })\n\n if (!response.ok) {\n if (response.status === 401) {\n // Token expired — try reconnecting (will get fresh token)\n this.scheduleReconnect()\n return\n }\n throw new Error(`SSE connection failed: ${response.status}`)\n }\n\n if (!response.body) {\n throw new Error('SSE response has no body')\n }\n\n this._connected = true\n this.reconnectAttempt = 0\n\n await this.readStream(response.body, signal)\n } catch {\n if (signal.aborted) return // Intentional disconnect\n this._connected = false\n this.scheduleReconnect()\n }\n }\n\n private async readStream(\n body: ReadableStream<Uint8Array>,\n signal: AbortSignal,\n ): Promise<void> {\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n let currentEvent = ''\n let currentData = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done || signal.aborted) break\n\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? '' // Keep incomplete last line in buffer\n\n for (const line of lines) {\n if (line.startsWith('event: ')) {\n currentEvent = line.slice(7)\n } else if (line.startsWith('data: ')) {\n currentData += (currentData ? '\\n' : '') + line.slice(6)\n } else if (line === '') {\n // Empty line = end of event\n if (currentEvent === 'collection:change' && currentData) {\n try {\n const event: RealtimeEvent = JSON.parse(currentData)\n for (const listener of this.listeners) {\n try {\n listener(event)\n } catch {\n // Listener error — ignore\n }\n }\n } catch {\n // Malformed JSON — ignore\n }\n }\n currentEvent = ''\n currentData = ''\n }\n // Ignore comment lines (: heartbeat)\n }\n }\n } catch {\n // Stream read error\n } finally {\n reader.releaseLock()\n this._connected = false\n if (!signal.aborted) {\n this.scheduleReconnect()\n }\n }\n }\n\n private scheduleReconnect(): void {\n if (this.reconnectTimer) return\n\n const delay = Math.min(\n INITIAL_RECONNECT_DELAY *\n Math.pow(RECONNECT_BACKOFF_FACTOR, this.reconnectAttempt),\n MAX_RECONNECT_DELAY,\n )\n this.reconnectAttempt++\n\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null\n this.abortController = new AbortController()\n this.startStream(this.abortController.signal)\n }, delay)\n }\n}\n","/**\n * Resolves a Payload CMS relation field value.\n * When depth is 0, relation fields return just the ID (string or number).\n * When depth > 0, they return the full document object (T).\n * This utility normalizes both cases to T | null.\n *\n * @param ref - The relation field value (T, string, number, null, or undefined)\n * @returns The resolved document object, or null if not populated\n */\nexport const resolveRelation = <T>(\n ref: T | string | number | null | undefined,\n): T | null => {\n if (\n typeof ref === 'string' ||\n typeof ref === 'number' ||\n ref === null ||\n ref === undefined\n )\n return null\n return ref\n}\n","import { resolveRelation } from '../../utils/types'\n\nexport interface MetadataImage {\n url: string\n width?: number\n height?: number\n alt?: string\n}\n\nexport interface Metadata {\n title?: string\n description?: string\n robots?: {\n index?: boolean\n follow?: boolean\n }\n alternates?: {\n canonical?: string\n }\n openGraph?: {\n title?: string\n description?: string\n siteName?: string\n images?: MetadataImage[]\n }\n twitter?: {\n card?: 'summary' | 'summary_large_image'\n title?: string\n description?: string\n images?: string[]\n }\n}\n\nexport interface ImageLike {\n url?: string | null\n width?: number | null\n height?: number | null\n alt?: string | null\n sizes?: Record<\n string,\n | { url?: string | null; width?: number | null; height?: number | null }\n | undefined\n >\n}\n\nexport interface SeoInput {\n title?: string | null\n description?: string | null\n noIndex?: boolean | null\n canonical?: string | null\n openGraph?: {\n title?: string | null\n description?: string | null\n image?: ImageLike | string | null\n } | null\n}\n\nexport interface GenerateMetadataOptions {\n siteName?: string\n}\n\nexport function extractSeo(doc: Record<string, unknown>): SeoInput {\n const seo = (doc.seo ?? {}) as Record<string, unknown>\n const og = (seo.openGraph ?? {}) as Record<string, unknown>\n\n return {\n title: (seo.title as string) ?? (doc.title as string) ?? null,\n description: (seo.description as string) ?? null,\n noIndex: (seo.noIndex as boolean) ?? null,\n canonical: (seo.canonical as string) ?? null,\n openGraph: {\n title: (og.title as string) ?? null,\n description: (og.description as string) ?? null,\n image: (og.image as ImageLike | string | null) ?? null,\n },\n }\n}\n\nexport function generateMetadata(\n input: SeoInput,\n options?: GenerateMetadataOptions,\n): Metadata {\n const title = input.title ?? undefined\n const description = input.description ?? undefined\n\n const ogTitle = input.openGraph?.title ?? title\n const ogDescription = input.openGraph?.description ?? description\n const image = resolveMetaImage(input.openGraph?.image)\n\n return {\n title,\n description,\n ...(input.noIndex && { robots: { index: false, follow: false } }),\n ...(input.canonical && { alternates: { canonical: input.canonical } }),\n openGraph: {\n ...(ogTitle && { title: ogTitle }),\n ...(ogDescription && { description: ogDescription }),\n ...(options?.siteName && { siteName: options.siteName }),\n ...(image && { images: [image] }),\n },\n twitter: {\n card: image ? 'summary_large_image' : 'summary',\n ...(ogTitle && { title: ogTitle }),\n ...(ogDescription && { description: ogDescription }),\n ...(image && { images: [image.url] }),\n },\n }\n}\n\nfunction resolveMetaImage(\n ref: ImageLike | string | null | undefined,\n): MetadataImage | null {\n const image = resolveRelation<ImageLike>(ref)\n if (!image) return null\n\n // Prefer sizes['1536'] (closest to OG 1200px standard), fallback to original url\n const sized = image.sizes?.['1536']\n const url = sized?.url || image.url\n if (!url) return null\n\n const width = sized?.url ? sized.width : image.width\n const height = sized?.url ? sized.height : image.height\n\n return {\n url,\n ...(width && { width }),\n ...(height && { height }),\n ...(image.alt && { alt: image.alt }),\n }\n}\n","import type {\n ApiQueryOptions,\n PublicCollection,\n ServerCollection,\n PayloadFindResponse,\n PayloadMutationResponse,\n} from '../client/types'\nimport { generateMetadata, extractSeo } from '../metadata'\nimport type { GenerateMetadataOptions, Metadata } from '../metadata'\nimport type { CollectionClient } from './collection-client'\nimport type { CollectionType } from './types'\n\ntype ReadOnlyCollectionApi = Pick<\n CollectionClient,\n 'requestFind' | 'requestFindById' | 'requestCount'\n>\n\n/**\n * Read-only subset of CollectionQueryBuilder.\n * Client.from() returns this type to prevent write operations at compile time.\n */\nexport type ReadOnlyQueryBuilder<T extends PublicCollection> =\n ReadOnlyCollectionQueryBuilder<T>\n\nexport class ReadOnlyCollectionQueryBuilder<T extends PublicCollection> {\n constructor(\n private api: ReadOnlyCollectionApi,\n private collection: T,\n ) {}\n\n async find(\n options?: ApiQueryOptions,\n ): Promise<PayloadFindResponse<CollectionType<T>>> {\n return this.api.requestFind<CollectionType<T>>(\n `/api/${String(this.collection)}`,\n options,\n )\n }\n\n async findById(\n id: string | number,\n options?: ApiQueryOptions,\n ): Promise<CollectionType<T>> {\n return this.api.requestFindById<CollectionType<T>>(\n `/api/${String(this.collection)}/${String(id)}`,\n options,\n )\n }\n\n async count(options?: ApiQueryOptions): Promise<{ totalDocs: number }> {\n return this.api.requestCount(\n `/api/${String(this.collection)}/count`,\n options,\n )\n }\n\n async findMetadata(\n options?: ApiQueryOptions,\n metadataOptions?: GenerateMetadataOptions,\n ): Promise<Metadata | null> {\n const { docs } = await this.find({ ...options, limit: 1, depth: 1 })\n const doc = docs[0]\n if (!doc) return null\n return generateMetadata(\n extractSeo(doc as unknown as Record<string, unknown>),\n metadataOptions,\n )\n }\n\n async findMetadataById(\n id: string,\n metadataOptions?: GenerateMetadataOptions,\n ): Promise<Metadata> {\n const doc = await this.findById(id, { depth: 1 })\n return generateMetadata(\n extractSeo(doc as unknown as Record<string, unknown>),\n metadataOptions,\n )\n }\n}\n\nexport class CollectionQueryBuilder<T extends string> {\n constructor(\n private api: CollectionClient,\n private collection: T,\n ) {}\n\n /**\n * Find documents (list query)\n * GET /api/{collection}\n * @returns Payload CMS find response with docs array and pagination\n */\n async find(\n options?: ApiQueryOptions,\n ): Promise<PayloadFindResponse<CollectionType<T>>> {\n return this.api.requestFind<CollectionType<T>>(\n `/api/${String(this.collection)}`,\n options,\n )\n }\n\n /**\n * Find document by ID\n * GET /api/{collection}/{id}\n * @returns Document object directly (no wrapper)\n */\n async findById(\n id: string | number,\n options?: ApiQueryOptions,\n ): Promise<CollectionType<T>> {\n return this.api.requestFindById<CollectionType<T>>(\n `/api/${String(this.collection)}/${String(id)}`,\n options,\n )\n }\n\n /**\n * Create a new document\n * POST /api/{collection}\n * @returns Payload CMS mutation response with doc and message\n */\n async create(\n data: Partial<CollectionType<T>>,\n options?: { file?: File | Blob; filename?: string },\n ): Promise<PayloadMutationResponse<CollectionType<T>>> {\n const endpoint = `/api/${String(this.collection)}`\n if (options?.file) {\n return this.api.requestCreateWithFile<CollectionType<T>>(\n endpoint,\n data,\n options.file,\n options.filename,\n )\n }\n return this.api.requestCreate<CollectionType<T>>(endpoint, data)\n }\n\n /**\n * Update a document by ID\n * PATCH /api/{collection}/{id}\n * @returns Payload CMS mutation response with doc and message\n */\n async update(\n id: string,\n data: Partial<CollectionType<T>>,\n options?: { file?: File | Blob; filename?: string },\n ): Promise<PayloadMutationResponse<CollectionType<T>>> {\n const endpoint = `/api/${String(this.collection)}/${String(id)}`\n if (options?.file) {\n return this.api.requestUpdateWithFile<CollectionType<T>>(\n endpoint,\n data,\n options.file,\n options.filename,\n )\n }\n return this.api.requestUpdate<CollectionType<T>>(endpoint, data)\n }\n\n /**\n * Count documents\n * GET /api/{collection}/count\n * @returns Count response with totalDocs\n */\n async count(options?: ApiQueryOptions): Promise<{ totalDocs: number }> {\n return this.api.requestCount(\n `/api/${String(this.collection)}/count`,\n options,\n )\n }\n\n /**\n * Find first matching document and return its Next.js Metadata.\n * Applies depth: 1 (SEO image populate) and limit: 1 automatically.\n * @returns Metadata or null if no document matches\n */\n async findMetadata(\n options?: ApiQueryOptions,\n metadataOptions?: GenerateMetadataOptions,\n ): Promise<Metadata | null> {\n const { docs } = await this.find({ ...options, limit: 1, depth: 1 })\n const doc = docs[0]\n if (!doc) return null\n return generateMetadata(\n extractSeo(doc as unknown as Record<string, unknown>),\n metadataOptions,\n )\n }\n\n /**\n * Find document by ID and return its Next.js Metadata.\n * Applies depth: 1 (SEO image populate) automatically.\n * @returns Metadata (throws on 404)\n */\n async findMetadataById(\n id: string,\n metadataOptions?: GenerateMetadataOptions,\n ): Promise<Metadata> {\n const doc = await this.findById(id, { depth: 1 })\n return generateMetadata(\n extractSeo(doc as unknown as Record<string, unknown>),\n metadataOptions,\n )\n }\n\n /**\n * Update multiple documents (bulk update)\n * PATCH /api/{collection}\n * @returns Payload CMS find response with updated docs\n */\n async updateMany(\n where: ApiQueryOptions['where'],\n data: Partial<CollectionType<T>>,\n ): Promise<PayloadFindResponse<CollectionType<T>>> {\n return this.api.requestUpdateMany<CollectionType<T>>(\n `/api/${String(this.collection)}`,\n { where, data },\n )\n }\n\n /**\n * Delete a document by ID\n * DELETE /api/{collection}/{id}\n * @returns Deleted document object directly (no wrapper)\n */\n async remove(id: string): Promise<CollectionType<T>> {\n return this.api.requestDelete<CollectionType<T>>(\n `/api/${String(this.collection)}/${String(id)}`,\n )\n }\n\n /**\n * Delete multiple documents (bulk delete)\n * DELETE /api/{collection}\n * @returns Payload CMS find response with deleted docs\n */\n async removeMany(\n where: ApiQueryOptions['where'],\n ): Promise<PayloadFindResponse<CollectionType<T>>> {\n return this.api.requestDeleteMany<CollectionType<T>>(\n `/api/${String(this.collection)}`,\n { where },\n )\n }\n}\n\nexport class ServerCollectionQueryBuilder<\n T extends ServerCollection,\n> extends CollectionQueryBuilder<T> {}\n","import { stringify } from 'qs-esm'\nimport {\n httpFetch,\n requirePublishableKeyForSecret,\n type FetchOptions,\n} from '../internal/utils'\nimport type {\n ApiQueryOptions,\n PayloadFindResponse,\n PayloadMutationResponse,\n} from '../client/types'\nimport { SDKError, createApiError } from '../internal/errors'\n\nexport class HttpClient {\n protected publishableKey: string\n protected secretKey?: string\n private getCustomerToken?: () => string | null\n private onUnauthorized?: () => Promise<string | null>\n private onRequestId?: (id: string | null) => void\n private apiUrl?: string\n\n constructor(\n publishableKey: string,\n secretKey?: string,\n getCustomerToken?: () => string | null,\n onUnauthorized?: () => Promise<string | null>,\n onRequestId?: (id: string | null) => void,\n apiUrl?: string,\n ) {\n this.publishableKey = requirePublishableKeyForSecret(\n 'CollectionClient',\n publishableKey,\n secretKey,\n )\n this.secretKey = secretKey\n this.getCustomerToken = getCustomerToken\n this.onUnauthorized = onUnauthorized\n this.onRequestId = onRequestId\n this.apiUrl = apiUrl\n }\n\n protected get defaultOptions(): FetchOptions {\n const opts: FetchOptions = {\n apiUrl: this.apiUrl,\n publishableKey: this.publishableKey,\n secretKey: this.secretKey,\n }\n const token = this.getCustomerToken?.()\n if (token) {\n opts.customerToken = token\n if (this.onUnauthorized) {\n opts.onUnauthorized = this.onUnauthorized\n }\n }\n return opts\n }\n\n protected async fetchWithTracking(url: string, opts: FetchOptions): Promise<Response> {\n try {\n const response = await httpFetch(url, opts)\n this.onRequestId?.(response.headers.get('x-request-id') ?? null)\n return response\n } catch (err) {\n const id = err instanceof SDKError ? (err.requestId ?? null) : null\n this.onRequestId?.(id)\n throw err\n }\n }\n\n protected buildUrl(endpoint: string, options?: ApiQueryOptions): string {\n if (!options) return endpoint\n const queryString = stringify(options, { addQueryPrefix: true })\n return queryString ? `${endpoint}${queryString}` : endpoint\n }\n\n protected assertJsonResponse(response: Response): void {\n const contentType = response.headers.get('content-type')\n if (!contentType?.includes('application/json')) {\n throw createApiError('Response is not in JSON format.', response.status, {\n contentType,\n })\n }\n }\n\n /**\n * Parse Payload CMS find response (list query)\n * Returns native Payload response structure\n */\n protected async parseFindResponse<T>(\n response: Response,\n ): Promise<PayloadFindResponse<T>> {\n const contentType = response.headers.get('content-type')\n\n try {\n this.assertJsonResponse(response)\n\n const jsonData = await response.json()\n\n // Validate it's a find response\n if (jsonData.docs === undefined) {\n throw createApiError('Invalid find response.', response.status, {\n jsonData,\n })\n }\n\n return {\n docs: jsonData.docs,\n totalDocs: jsonData.totalDocs ?? 0,\n limit: jsonData.limit || 20,\n totalPages: jsonData.totalPages ?? 0,\n page: jsonData.page || 1,\n pagingCounter: jsonData.pagingCounter || 1,\n hasPrevPage: jsonData.hasPrevPage ?? false,\n hasNextPage: jsonData.hasNextPage ?? false,\n prevPage: jsonData.prevPage ?? null,\n nextPage: jsonData.nextPage ?? null,\n }\n } catch (error) {\n if (error instanceof SDKError) throw error\n throw createApiError('Failed to parse response.', response.status, {\n contentType,\n error: error instanceof Error ? error.message : error,\n })\n }\n }\n\n /**\n * Parse Payload CMS mutation response (create/update)\n * Returns native Payload response structure\n */\n protected async parseMutationResponse<T>(\n response: Response,\n ): Promise<PayloadMutationResponse<T>> {\n const contentType = response.headers.get('content-type')\n\n try {\n this.assertJsonResponse(response)\n\n const jsonData = await response.json()\n\n // Validate it's a mutation response\n if (jsonData.doc === undefined) {\n throw createApiError('Invalid mutation response.', response.status, {\n jsonData,\n })\n }\n\n return {\n message: jsonData.message || '',\n doc: jsonData.doc,\n errors: jsonData.errors,\n }\n } catch (error) {\n if (error instanceof SDKError) throw error\n throw createApiError('Failed to parse response.', response.status, {\n contentType,\n error: error instanceof Error ? error.message : error,\n })\n }\n }\n\n /**\n * Parse Payload CMS document response (findById/delete)\n * Returns document directly without wrapper\n */\n protected async parseDocumentResponse<T>(response: Response): Promise<T> {\n const contentType = response.headers.get('content-type')\n\n try {\n this.assertJsonResponse(response)\n\n const jsonData = await response.json()\n return jsonData as T\n } catch (error) {\n if (error instanceof SDKError) throw error\n throw createApiError('Failed to parse response.', response.status, {\n contentType,\n error: error instanceof Error ? error.message : error,\n })\n }\n }\n}\n","import { createConfigError } from '../errors'\n\nexport function requirePublishableKeyForSecret(\n apiName: string,\n publishableKey: string | undefined,\n secretKey: string | undefined,\n): string {\n if (secretKey && !publishableKey) {\n throw createConfigError(\n `publishableKey is required for ${apiName} when secretKey is used. ` +\n 'It is sent as X-Publishable-Key for tenant routing, rate limiting, and quota enforcement.',\n )\n }\n\n return publishableKey ?? ''\n}\n","import type {\n Collection,\n PublicCollection,\n ServerCollection,\n ServerOnlyCollection,\n} from '../collection/const'\nimport type { CollectionType } from '../collection/types'\nimport type { CommunityClient } from '../community/community-client'\nimport type {\n BanCustomerParams,\n CommunityBan,\n UnbanCustomerParams,\n} from '../community/moderation-api'\nimport type { CommerceClient } from '../commerce/commerce-client'\nimport type { ServerCommerceClient } from '../commerce/server-commerce-client'\nimport type { CustomerNamespace } from '../customer/customer-namespace'\nimport type { TenantIntrospectionClient } from '../api/tenant-introspection-api'\n\nexport type {\n Collection,\n PublicCollection,\n ServerCollection,\n ServerOnlyCollection,\n}\n\n// ============================================================================\n// API URL Configuration\n// ============================================================================\n\ndeclare const __DEFAULT_API_URL__: string\n\nexport function resolveApiUrl(apiUrl?: string): string {\n if (apiUrl) {\n return apiUrl.replace(/\\/$/, '')\n }\n\n if (typeof process !== 'undefined' && process.env) {\n const envUrl =\n process.env.SOFTWARE_API_URL || process.env.NEXT_PUBLIC_SOFTWARE_API_URL\n if (envUrl) {\n return envUrl.replace(/\\/$/, '')\n }\n }\n return __DEFAULT_API_URL__\n}\n\n// ============================================================================\n// Client Configuration\n// ============================================================================\n\nexport interface ClientConfig {\n publishableKey: string\n /** API base URL for staging, self-hosted, preview, or proxy deployments. */\n apiUrl?: string\n /**\n * Customer authentication options.\n * Used to initialize CustomerAuth on Client.\n */\n customer?: {\n /**\n * Persist token in localStorage. Defaults to `true`.\n * - `true` (default): uses key `'customer-token'`\n * - `string`: uses the given string as localStorage key\n * - `false`: disables persistence (token/onTokenChange used instead)\n *\n * Handles SSR safely (no-op on server).\n * When enabled, `token` and `onTokenChange` are ignored.\n */\n persist?: boolean | string\n /** Initial token (e.g. from SSR cookie) */\n token?: string\n /** Called when token changes (login/logout) — use to persist in localStorage/cookie */\n onTokenChange?: (token: string | null) => void\n }\n}\n\n// Server client: requires both publishableKey (for CDN routing + rate limit +\n// monthly quota enforcement via the edge proxy) and secretKey (sk01_ opaque\n// bearer token, the authentication credential).\n// The proxy keys its tenant lookup off `X-Publishable-Key`, so omitting\n// publishableKey would silently bypass rate limiting and plan-based quota\n// enforcement.\nexport interface ClientServerConfig extends ClientConfig {\n secretKey: string\n}\n\nexport interface ClientMetadata {\n userAgent?: string\n timestamp: number\n}\n\nexport interface ClientState {\n metadata: ClientMetadata\n}\n\nexport interface PaginationMeta {\n page: number\n limit: number\n totalDocs: number\n totalPages: number\n hasNextPage: boolean\n hasPrevPage: boolean\n pagingCounter: number\n prevPage: number | null\n nextPage: number | null\n}\n\n// ============================================================================\n// Payload CMS Native Response Types\n// ============================================================================\n\n/**\n * Payload CMS Find (List) Response\n * GET /api/{collection}\n */\nexport interface PayloadFindResponse<T = unknown> {\n docs: T[]\n totalDocs: number\n limit: number\n totalPages: number\n page: number\n pagingCounter: number\n hasPrevPage: boolean\n hasNextPage: boolean\n prevPage: number | null\n nextPage: number | null\n}\n\n/**\n * Payload CMS Create/Update Response\n * POST /api/{collection}\n * PATCH /api/{collection}/{id}\n */\nexport interface PayloadMutationResponse<T = unknown> {\n message: string\n doc: T\n errors?: unknown[]\n}\n\n// ============================================================================\n// Query Options\n// ============================================================================\n\nexport type Sort = string | string[]\nexport type Where = Record<string, unknown>\n\n/**\n * Do NOT replace with `Pick<FindOptions>` from `payload` or import Payload\n * types here. Payload's generic query types depend on `PayloadTypes` module\n * augmentation; external SDK consumers who only use `createClient` should not\n * install Payload just to type REST query objects. Excluded vs native:\n * Local-API-only fields, `locale`/`fallbackLocale`.\n */\nexport interface ApiQueryOptions {\n page?: number\n limit?: number\n sort?: Sort\n /**\n * Filter documents. Id-based relation filters (`where: { product: { equals: id } }`) are the\n * most reliable pattern. Dotted-path relation filters (`where: { 'product.slug': { equals } }`)\n * are Payload-native but may silently return empty when access control restricts the related\n * document or when the relation is polymorphic. String shorthand (`where: { slug: 'x' }`)\n * silently matches nothing — always use `{ slug: { equals: 'x' } }`.\n */\n where?: Where\n /**\n * Controls how deeply relationship fields are populated. This is the primary control for\n * populating relationships like `category`, `images`, `brand`. The configured Payload default\n * applies when unset.\n */\n depth?: number\n select?: Record<string, boolean>\n /**\n * Controls which fields are returned for already-populated relationships, keyed by collection\n * slug. Does NOT control which relationships to populate — that is `depth`.\n *\n * @example\n * // depth: 2 populates category; populate trims which fields come back\n * populate: { categories: { title: true, slug: true } }\n */\n populate?: Record<string, boolean | Record<string, boolean>>\n /**\n * Controls Payload `type: 'join'` virtual reverse-relation fields only (pagination, sort,\n * filter, count per join field, or `false` to disable all join-field population).\n *\n * Does NOT populate normal relationship fields like `category`, `images`, or `brand`.\n * For normal relationship population use `depth` (and optionally `populate` for field\n * selection).\n *\n * Pass `joins: false` to disable all join-field population — useful for lightweight list\n * queries where join fields are not needed.\n *\n * @example\n * // `article-authors` has a `type: 'join'` field `articles` (reverse-relation)\n * joins: { articles: { limit: 10, sort: '-publishedAt' } }\n *\n * // depth: 2 populates product.category — joins has no effect on this\n * depth: 2\n *\n * // Disable all join-field population\n * joins: false\n */\n joins?:\n | Record<\n string,\n | {\n limit?: number\n page?: number\n sort?: string\n where?: Where\n count?: boolean\n }\n | false\n >\n | false\n /** Set to `false` to skip the count query — returns docs without totalDocs/totalPages */\n pagination?: boolean\n /** Include draft versions (access control still applies on the server) */\n draft?: boolean\n /** Include soft-deleted documents (requires `trash` enabled on the collection) */\n trash?: boolean\n}\n\n// ============================================================================\n// Debug & Retry Configuration\n// ============================================================================\n\nexport interface DebugConfig {\n logRequests?: boolean\n logResponses?: boolean\n logErrors?: boolean\n}\n\nexport interface RetryConfig {\n maxRetries?: number\n retryableStatuses?: number[]\n retryDelay?: (attempt: number) => number\n}\n\n// ============================================================================\n// Lightweight root entry contracts\n// ============================================================================\n\ninterface RootQueryLookup<T extends string> {\n find(options?: ApiQueryOptions): Promise<PayloadFindResponse<CollectionType<T>>>\n findById(\n id: string | number,\n options?: ApiQueryOptions,\n ): Promise<CollectionType<T>>\n count(options?: ApiQueryOptions): Promise<{ totalDocs: number }>\n}\n\nexport type RootReadOnlyQueryBuilder<T extends PublicCollection> =\n RootQueryLookup<T>\n\nexport interface RootServerQueryBuilder<T extends ServerCollection>\n extends RootQueryLookup<T> {\n create(\n data: Partial<CollectionType<T>>,\n options?: { file?: File | Blob; filename?: string },\n ): Promise<PayloadMutationResponse<CollectionType<T>>>\n update(\n id: string,\n data: Partial<CollectionType<T>>,\n options?: { file?: File | Blob; filename?: string },\n ): Promise<PayloadMutationResponse<CollectionType<T>>>\n updateMany(\n where: ApiQueryOptions['where'],\n data: Partial<CollectionType<T>>,\n ): Promise<PayloadFindResponse<CollectionType<T>>>\n remove(id: string): Promise<CollectionType<T>>\n removeMany(\n where: ApiQueryOptions['where'],\n ): Promise<PayloadFindResponse<CollectionType<T>>>\n}\n\nexport interface RootCollectionClient {\n from<T extends PublicCollection>(collection: T): RootReadOnlyQueryBuilder<T>\n}\n\nexport interface RootServerCollectionClient {\n from<T extends ServerCollection>(collection: T): RootServerQueryBuilder<T>\n}\n\nexport interface RootClient {\n commerce: CommerceClient\n community: CommunityClient\n customer: CustomerNamespace\n collections: RootCollectionClient\n lastRequestId: string | null\n getState(): ClientState\n getConfig(): ClientConfig\n}\n\nexport interface RootServerClient {\n commerce: ServerCommerceClient\n tenant: TenantIntrospectionClient\n community: CommunityClient & {\n moderation: {\n banCustomer: (p: BanCustomerParams) => Promise<CommunityBan>\n unbanCustomer: (p: UnbanCustomerParams) => Promise<{ success: true }>\n }\n }\n collections: RootServerCollectionClient\n lastRequestId: string | null\n getState(): ClientState\n getConfig(): Omit<ClientServerConfig, 'secretKey'>\n}\n\n// ============================================================================\n// Type Utilities\n// ============================================================================\n\nexport type DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]\n}\n\nexport type ExtractArrayType<T> = T extends (infer U)[] ? U : never\n","import {\n createAuthError,\n createConflictError,\n createNetworkError,\n createNotFoundError,\n createPermissionError,\n createValidationError,\n createUsageLimitError,\n createTimeoutError,\n TimeoutError,\n NetworkError,\n SDKError,\n} from '../errors'\nimport type { DebugConfig, RetryConfig } from '../../client/types'\nimport { resolveApiUrl } from '../../client/types'\nconst DEFAULT_TIMEOUT = 30000\nconst DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504]\nconst NON_RETRYABLE_STATUSES = [400, 401, 403, 404, 409, 422]\nconst SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']\n\nexport interface FetchOptions extends RequestInit {\n apiUrl?: string\n publishableKey?: string\n secretKey?: string\n customerToken?: string\n timeout?: number\n debug?: boolean | DebugConfig\n retry?: RetryConfig\n /** Called on 401 when customerToken is set and reason=token_expired. Return a new token to retry, or null to fail. */\n onUnauthorized?: () => Promise<string | null>\n}\n\nfunction debugLog(\n debug: boolean | DebugConfig | undefined,\n type: 'request' | 'response' | 'error',\n message: string,\n data?: unknown,\n) {\n if (!debug) return\n\n const shouldLog =\n debug === true ||\n (type === 'request' && (debug as DebugConfig).logRequests) ||\n (type === 'response' && (debug as DebugConfig).logResponses) ||\n (type === 'error' && (debug as DebugConfig).logErrors)\n\n if (shouldLog) {\n console.group(`[SDK ${type.toUpperCase()}] ${message}`)\n if (data) console.log(data)\n console.groupEnd()\n }\n}\n\nfunction redactSensitiveHeader(value: string): string {\n const prefix = value.toLowerCase().startsWith('bearer ') ? 'Bearer ' : ''\n return value.length > 20 ? `${prefix}...****${value.slice(-8)}` : '****'\n}\n\nfunction redactSensitiveHeaders(headers: Headers): Record<string, string> {\n const redacted = Object.fromEntries(headers.entries())\n if (redacted.authorization) {\n redacted.authorization = redactSensitiveHeader(redacted.authorization)\n }\n if (redacted['x-preview-token']) {\n redacted['x-preview-token'] = redactSensitiveHeader(\n redacted['x-preview-token'],\n )\n }\n return redacted\n}\n\nfunction getErrorSuggestion(status: number): string | undefined {\n if (status === 400)\n return 'The request data failed validation. Check field values and types.'\n if (status === 401) return 'Please check your authentication credentials.'\n if (status === 403)\n return 'Access denied. Check your credentials or permissions.'\n if (status === 404) return 'The requested resource was not found.'\n if (status === 422) return 'The request data failed validation.'\n if (status >= 500) return 'A server error occurred. Please try again later.'\n return undefined\n}\n\nfunction isUsageLimitExceededResponse(response: Response): boolean {\n if (response.status !== 429) return false\n\n const limit = parseInt(response.headers.get('X-Usage-Limit') || '', 10)\n const current = parseInt(response.headers.get('X-Usage-Current') || '', 10)\n if (!Number.isFinite(limit) || !Number.isFinite(current)) return false\n\n return response.headers.get('X-Usage-Exceeded') === 'true' || current > limit\n}\n\n/**\n * Parse error details from HTTP response body.\n * Supports Payload native format:\n * - ValidationError: { errors: [{ message, data: { errors: [{ path, message }] } }] }\n * - Simple: { errors: [{ message, field? }] }\n * Also supports custom endpoint format ({ error: string, reason?: string, message?: string }).\n */\nasync function parseErrorBody(response: Response): Promise<{\n errorMessage: string\n userMessage: string\n reason?: string\n body?: Record<string, unknown>\n errors?: Array<{ message?: string; field?: string }>\n}> {\n const fallback = {\n errorMessage: `HTTP ${response.status}: ${response.statusText}`,\n userMessage: `Request failed (status: ${response.status})`,\n }\n\n try {\n const body = await response.json()\n const reason: string | undefined =\n typeof body.reason === 'string'\n ? body.reason\n : typeof body.code === 'string'\n ? body.code\n : undefined\n\n // Payload native: { errors: [{ message, field?, data? }] }\n if (body.errors && Array.isArray(body.errors)) {\n // Extract nested ValidationError field details\n // Payload ValidationError format: errors[].data.errors[].{path, message}\n const fieldErrors: Array<{ message?: string; field?: string }> = []\n for (const e of body.errors) {\n if (\n e.data?.errors &&\n Array.isArray(e.data.errors) &&\n e.data.errors.length > 0\n ) {\n for (const fe of e.data.errors) {\n fieldErrors.push({\n field: fe.path || fe.field,\n message: fe.message,\n })\n }\n } else if (e.field || e.message) {\n fieldErrors.push({ field: e.field, message: e.message })\n }\n }\n\n const details = (fieldErrors.length > 0 ? fieldErrors : body.errors)\n .map((e: { message?: string; field?: string }) =>\n e.field ? `${e.field}: ${e.message}` : e.message,\n )\n .filter(Boolean)\n .join('; ')\n if (details) {\n return {\n errorMessage: `HTTP ${response.status}: ${details}`,\n userMessage: details,\n reason,\n body,\n errors: fieldErrors.length > 0 ? fieldErrors : body.errors,\n }\n }\n }\n\n // Custom endpoint: { error: string, reason?: string, details?: { fieldErrors? } }\n if (typeof body.error === 'string') {\n return {\n errorMessage: `HTTP ${response.status}: ${body.error}`,\n userMessage: body.error,\n reason,\n body,\n }\n }\n\n // Fallback: { message: string }\n if (body.message) {\n return {\n errorMessage: `HTTP ${response.status}: ${body.message}`,\n userMessage: body.message,\n reason,\n body,\n }\n }\n\n return { ...fallback, reason, body }\n } catch {\n return fallback\n }\n}\n\nfunction getParsedErrorSuggestion(\n status: number,\n parsed: Awaited<ReturnType<typeof parseErrorBody>>,\n): string | undefined {\n if (status === 403 && parsed.reason === 'origin_not_allowed') {\n return 'Add the request origin to the tenant Browser API origins, then retry the browser request.'\n }\n\n return getErrorSuggestion(status)\n}\n\nasync function delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n// Attach requestId to any SDKError instance (readonly bypass is intentional — internal transport layer only)\nexport function attachRequestId<T extends SDKError>(\n err: T,\n id: string | undefined,\n): T {\n if (id) (err as Record<string, unknown>).requestId = id\n return err\n}\n\nfunction createHttpStatusError(\n status: number,\n parsed: Awaited<ReturnType<typeof parseErrorBody>>,\n details: Record<string, unknown>,\n requestId: string | undefined,\n): SDKError {\n const errorDetails = {\n ...details,\n ...(parsed.errors && { errors: parsed.errors }),\n ...(parsed.body && { body: parsed.body }),\n }\n const suggestion = getParsedErrorSuggestion(status, parsed)\n\n if (status === 400 || status === 422) {\n return attachRequestId(\n createValidationError(\n parsed.errorMessage,\n errorDetails,\n parsed.userMessage,\n suggestion,\n status,\n ),\n requestId,\n )\n }\n\n if (status === 401) {\n return attachRequestId(\n createAuthError(\n parsed.errorMessage,\n errorDetails,\n parsed.userMessage,\n suggestion,\n ),\n requestId,\n )\n }\n\n if (status === 403) {\n return attachRequestId(\n createPermissionError(\n parsed.errorMessage,\n errorDetails,\n parsed.userMessage,\n suggestion,\n ),\n requestId,\n )\n }\n\n if (status === 404) {\n return attachRequestId(\n createNotFoundError(\n parsed.errorMessage,\n errorDetails,\n parsed.userMessage,\n suggestion,\n ),\n requestId,\n )\n }\n\n if (status === 409) {\n return attachRequestId(\n createConflictError(\n parsed.errorMessage,\n errorDetails,\n parsed.userMessage,\n suggestion,\n ),\n requestId,\n )\n }\n\n return attachRequestId(\n createNetworkError(\n parsed.errorMessage,\n status,\n errorDetails,\n parsed.userMessage,\n suggestion,\n ),\n requestId,\n )\n}\n\nexport async function httpFetch(\n url: string,\n options?: FetchOptions,\n): Promise<Response> {\n const {\n apiUrl,\n publishableKey,\n secretKey,\n customerToken,\n timeout = DEFAULT_TIMEOUT,\n debug,\n retry,\n onUnauthorized,\n ...requestInit\n } = options || {}\n\n const baseUrl = resolveApiUrl(apiUrl)\n\n const retryConfig = {\n maxRetries: retry?.maxRetries ?? 3,\n retryableStatuses: retry?.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES,\n retryDelay:\n retry?.retryDelay ??\n ((attempt: number) => Math.min(1000 * 2 ** attempt, 10000)),\n }\n\n // Server auth: secretKey is now the raw opaque bearer token (sk01_...).\n // Customer auth: customerToken is a JWT.\n let authToken: string | undefined\n if (secretKey) {\n authToken = secretKey\n } else if (customerToken) {\n authToken = customerToken\n }\n\n let lastError: Error | undefined\n let hasRetried401 = false\n\n for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {\n try {\n const headers = new Headers(requestInit.headers)\n\n if (publishableKey) {\n headers.set('X-Publishable-Key', publishableKey)\n }\n\n if (authToken) {\n headers.set('Authorization', `Bearer ${authToken}`)\n }\n\n if (\n !headers.has('Content-Type') &&\n requestInit.body &&\n !(requestInit.body instanceof FormData)\n ) {\n headers.set('Content-Type', 'application/json')\n }\n\n // Redact sensitive headers for debug logging\n const redactedHeaders = redactSensitiveHeaders(headers)\n\n debugLog(debug, 'request', url, {\n method: requestInit.method || 'GET',\n headers: redactedHeaders,\n attempt: attempt + 1,\n })\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n const response = await fetch(`${baseUrl}${url}`, {\n ...requestInit,\n headers,\n signal: controller.signal,\n })\n\n clearTimeout(timeoutId)\n\n const requestId = response.headers.get('x-request-id') ?? undefined\n\n debugLog(debug, 'response', url, {\n status: response.status,\n statusText: response.statusText,\n headers: redactSensitiveHeaders(response.headers),\n })\n\n if (!response.ok) {\n // Usage limit 429 — never retry. Older servers identify this when\n // current usage is above the limit; newer servers also send\n // X-Usage-Exceeded to avoid confusing other 429s with quota exhaustion.\n if (isUsageLimitExceededResponse(response)) {\n const limit = parseInt(\n response.headers.get('X-Usage-Limit') || '0',\n 10,\n )\n const current = parseInt(\n response.headers.get('X-Usage-Current') || '0',\n 10,\n )\n const remaining = parseInt(\n response.headers.get('X-Usage-Remaining') || '0',\n 10,\n )\n\n throw attachRequestId(\n createUsageLimitError(\n `Monthly API usage limit exceeded (${current.toLocaleString()}/${limit.toLocaleString()})`,\n { limit, current, remaining },\n {\n url,\n method: requestInit.method || 'GET',\n attempt: attempt + 1,\n },\n 'Monthly API call limit exceeded. Please upgrade your plan.',\n 'Upgrade your tenant plan to increase the monthly API call limit.',\n ),\n requestId,\n )\n }\n\n // Parse body once — captures reason field for 401 branching and error details\n const parsed = await parseErrorBody(response)\n\n // Auto-refresh customer token on 401 — only when reason=token_expired\n if (\n response.status === 401 &&\n onUnauthorized &&\n customerToken &&\n !hasRetried401 &&\n parsed.reason === 'token_expired'\n ) {\n hasRetried401 = true\n try {\n const newToken = await onUnauthorized()\n if (newToken) {\n authToken = newToken\n continue\n }\n } catch {\n // Refresh failed, fall through to throw\n }\n }\n\n const details = {\n url,\n method: requestInit.method || 'GET',\n attempt: attempt + 1,\n }\n\n // Never retry non-retryable statuses regardless of user config\n if (NON_RETRYABLE_STATUSES.includes(response.status)) {\n throw createHttpStatusError(\n response.status,\n parsed,\n details,\n requestId,\n )\n }\n\n // Retryable errors\n const error = attachRequestId(\n createNetworkError(\n parsed.errorMessage,\n response.status,\n details,\n parsed.userMessage,\n getErrorSuggestion(response.status),\n ),\n requestId,\n )\n\n const method = (requestInit.method || 'GET').toUpperCase()\n if (\n attempt < retryConfig.maxRetries &&\n SAFE_METHODS.includes(method) &&\n retryConfig.retryableStatuses.includes(response.status)\n ) {\n lastError = error\n const retryDelay = retryConfig.retryDelay(attempt)\n debugLog(debug, 'error', `Retrying in ${retryDelay}ms...`, error)\n await delay(retryDelay)\n continue\n }\n\n throw error\n }\n\n return response\n } catch (error) {\n debugLog(debug, 'error', url, error)\n\n const method = (requestInit.method || 'GET').toUpperCase()\n const isSafe = SAFE_METHODS.includes(method)\n\n if (error instanceof Error && error.name === 'AbortError') {\n const timeoutError = createTimeoutError(\n `Request timed out after ${timeout}ms.`,\n { url, timeout, attempt: attempt + 1 },\n 'The request timed out.',\n 'Please check your network connection or try again later.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = timeoutError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw timeoutError\n }\n\n if (error instanceof TypeError) {\n const networkError = createNetworkError(\n 'Network connection failed.',\n undefined,\n { url, originalError: error.message, attempt: attempt + 1 },\n 'Network connection failed.',\n 'Please check your internet connection and try again.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = networkError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw networkError\n }\n\n if (error instanceof NetworkError || error instanceof TimeoutError) {\n if (\n isSafe &&\n attempt < retryConfig.maxRetries &&\n error.status &&\n !NON_RETRYABLE_STATUSES.includes(error.status) &&\n retryConfig.retryableStatuses.includes(error.status)\n ) {\n lastError = error\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw error\n }\n\n // Re-throw any other SDKError subclass (e.g. UsageLimitError) without wrapping\n if (error instanceof SDKError) {\n throw error\n }\n\n const unknownError = createNetworkError(\n error instanceof Error\n ? error.message\n : 'An unknown network error occurred.',\n undefined,\n { url, originalError: error, attempt: attempt + 1 },\n 'An unknown error occurred.',\n 'Please try again later.',\n )\n\n if (isSafe && attempt < retryConfig.maxRetries) {\n lastError = unknownError\n await delay(retryConfig.retryDelay(attempt))\n continue\n }\n\n throw unknownError\n }\n }\n\n throw lastError ?? new NetworkError('Request failed after retries')\n}\n","import { HttpClient } from './http-client'\nimport type {\n ApiQueryOptions,\n PublicCollection,\n ServerCollection,\n PayloadFindResponse,\n PayloadMutationResponse,\n} from '../client/types'\nimport {\n CollectionQueryBuilder,\n ReadOnlyCollectionQueryBuilder,\n ServerCollectionQueryBuilder,\n type ReadOnlyQueryBuilder,\n} from './query-builder'\n\nfunction buildPayloadFormData(\n data: unknown,\n file: File | Blob,\n filename?: string,\n): FormData {\n const formData = new FormData()\n formData.append('file', file, filename)\n if (data != null) {\n formData.append('_payload', JSON.stringify(data))\n }\n return formData\n}\n\nexport class CollectionClient<\n TCollection extends string = PublicCollection,\n> extends HttpClient {\n from<T extends TCollection>(collection: T): CollectionQueryBuilder<T> {\n return new CollectionQueryBuilder(this, collection)\n }\n\n // ============================================================================\n // Payload-native methods\n // ============================================================================\n\n /**\n * Find documents (list query)\n * GET /api/{collection}\n */\n async requestFind<T = unknown>(\n endpoint: string,\n options?: ApiQueryOptions,\n ): Promise<PayloadFindResponse<T>> {\n const url = this.buildUrl(endpoint, options)\n const response = await this.fetchWithTracking(url, {\n ...this.defaultOptions,\n method: 'GET',\n })\n return this.parseFindResponse<T>(response)\n }\n\n /**\n * Find-like response from a custom endpoint\n * POST /api/...custom-endpoint\n */\n async requestFindEndpoint<T = unknown>(\n endpoint: string,\n data?: unknown,\n ): Promise<PayloadFindResponse<T>> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'POST',\n body: data ? JSON.stringify(data) : undefined,\n })\n return this.parseFindResponse<T>(response)\n }\n\n /**\n * Find document by ID\n * GET /api/{collection}/{id}\n */\n async requestFindById<T = unknown>(\n endpoint: string,\n options?: ApiQueryOptions,\n ): Promise<T> {\n const url = this.buildUrl(endpoint, options)\n const response = await this.fetchWithTracking(url, {\n ...this.defaultOptions,\n method: 'GET',\n })\n return this.parseDocumentResponse<T>(response)\n }\n\n /**\n * Create document\n * POST /api/{collection}\n */\n async requestCreate<T = unknown>(\n endpoint: string,\n data?: unknown,\n ): Promise<PayloadMutationResponse<T>> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'POST',\n body: data ? JSON.stringify(data) : undefined,\n })\n return this.parseMutationResponse<T>(response)\n }\n\n /**\n * Update document\n * PATCH /api/{collection}/{id}\n */\n async requestUpdate<T = unknown>(\n endpoint: string,\n data?: unknown,\n ): Promise<PayloadMutationResponse<T>> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'PATCH',\n body: data ? JSON.stringify(data) : undefined,\n })\n return this.parseMutationResponse<T>(response)\n }\n\n /**\n * Count documents\n * GET /api/{collection}/count\n */\n async requestCount(\n endpoint: string,\n options?: ApiQueryOptions,\n ): Promise<{ totalDocs: number }> {\n const url = this.buildUrl(endpoint, options)\n const response = await this.fetchWithTracking(url, {\n ...this.defaultOptions,\n method: 'GET',\n })\n return this.parseDocumentResponse<{ totalDocs: number }>(response)\n }\n\n /**\n * Update multiple documents (bulk update)\n * PATCH /api/{collection}\n */\n async requestUpdateMany<T = unknown>(\n endpoint: string,\n data: { where?: unknown; data: unknown },\n ): Promise<PayloadFindResponse<T>> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'PATCH',\n body: JSON.stringify(data),\n })\n return this.parseFindResponse<T>(response)\n }\n\n /**\n * Delete document\n * DELETE /api/{collection}/{id}\n */\n async requestDelete<T = unknown>(endpoint: string): Promise<T> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'DELETE',\n })\n return this.parseDocumentResponse<T>(response)\n }\n\n /**\n * Delete multiple documents (bulk delete)\n * DELETE /api/{collection}\n */\n async requestDeleteMany<T = unknown>(\n endpoint: string,\n data: { where?: unknown },\n ): Promise<PayloadFindResponse<T>> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'DELETE',\n body: JSON.stringify(data),\n })\n return this.parseFindResponse<T>(response)\n }\n\n /**\n * Create document with file upload\n * POST /api/{collection} (multipart/form-data)\n */\n async requestCreateWithFile<T = unknown>(\n endpoint: string,\n data: unknown,\n file: File | Blob,\n filename?: string,\n ): Promise<PayloadMutationResponse<T>> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'POST',\n body: buildPayloadFormData(data, file, filename),\n })\n return this.parseMutationResponse<T>(response)\n }\n\n /**\n * Update document with file upload\n * PATCH /api/{collection}/{id} (multipart/form-data)\n */\n async requestUpdateWithFile<T = unknown>(\n endpoint: string,\n data: unknown,\n file: File | Blob,\n filename?: string,\n ): Promise<PayloadMutationResponse<T>> {\n const response = await this.fetchWithTracking(endpoint, {\n ...this.defaultOptions,\n method: 'PATCH',\n body: buildPayloadFormData(data, file, filename),\n })\n return this.parseMutationResponse<T>(response)\n }\n}\n\nexport class ServerCollectionClient extends CollectionClient<ServerCollection> {\n override from<T extends ServerCollection>(\n collection: T,\n ): ServerCollectionQueryBuilder<T> {\n return new ServerCollectionQueryBuilder(this, collection)\n }\n}\n\nexport class ReadOnlyCollectionClient extends HttpClient {\n from<T extends PublicCollection>(collection: T): ReadOnlyQueryBuilder<T> {\n return new ReadOnlyCollectionQueryBuilder(this, collection)\n }\n\n async requestFind<T = unknown>(\n endpoint: string,\n options?: ApiQueryOptions,\n ): Promise<PayloadFindResponse<T>> {\n const url = this.buildUrl(endpoint, options)\n const response = await this.fetchWithTracking(url, {\n ...this.defaultOptions,\n method: 'GET',\n })\n return this.parseFindResponse<T>(response)\n }\n\n async requestFindById<T = unknown>(\n endpoint: string,\n options?: ApiQueryOptions,\n ): Promise<T> {\n const url = this.buildUrl(endpoint, options)\n const response = await this.fetchWithTracking(url, {\n ...this.defaultOptions,\n method: 'GET',\n })\n return this.parseDocumentResponse<T>(response)\n }\n\n async requestCount(\n endpoint: string,\n options?: ApiQueryOptions,\n ): Promise<{ totalDocs: number }> {\n const url = this.buildUrl(endpoint, options)\n const response = await this.fetchWithTracking(url, {\n ...this.defaultOptions,\n method: 'GET',\n })\n return this.parseDocumentResponse<{ totalDocs: number }>(response)\n }\n}\n","import type ServerClient from '../client/client.server'\nimport type {\n PublicCollection,\n RootClient,\n ServerCollection,\n} from '../client/types'\nimport { CollectionClient } from '../collection'\nimport { QueryHooks, type ReadOnlyQueryHooks } from './query-hooks'\nimport { getQueryClient } from './get-query-client'\nimport type { QueryClient } from '@tanstack/react-query'\n\nfunction createReadOnlyQueryHooksFacade(\n hooks: QueryHooks<PublicCollection>,\n): ReadOnlyQueryHooks {\n return {\n useQuery: hooks.useQuery.bind(hooks),\n useSuspenseQuery: hooks.useSuspenseQuery.bind(hooks),\n useQueryById: hooks.useQueryById.bind(hooks),\n useSuspenseQueryById: hooks.useSuspenseQueryById.bind(hooks),\n useInfiniteQuery: hooks.useInfiniteQuery.bind(hooks),\n useSuspenseInfiniteQuery: hooks.useSuspenseInfiniteQuery.bind(hooks),\n prefetchQuery: hooks.prefetchQuery.bind(hooks),\n prefetchQueryById: hooks.prefetchQueryById.bind(hooks),\n prefetchInfiniteQuery: hooks.prefetchInfiniteQuery.bind(hooks),\n invalidateQueries: hooks.invalidateQueries.bind(hooks),\n getQueryData: hooks.getQueryData.bind(hooks),\n setQueryData: hooks.setQueryData.bind(hooks),\n useCustomerMe: hooks.useCustomerMe.bind(hooks),\n useCustomerLogin: hooks.useCustomerLogin.bind(hooks),\n useCustomerRegister: hooks.useCustomerRegister.bind(hooks),\n useCustomerLogout: hooks.useCustomerLogout.bind(hooks),\n useCustomerForgotPassword: hooks.useCustomerForgotPassword.bind(hooks),\n useCustomerResetPassword: hooks.useCustomerResetPassword.bind(hooks),\n useCustomerRefreshToken: hooks.useCustomerRefreshToken.bind(hooks),\n useCustomerUpdateProfile: hooks.useCustomerUpdateProfile.bind(hooks),\n useCustomerChangePassword: hooks.useCustomerChangePassword.bind(hooks),\n invalidateCustomerQueries: hooks.invalidateCustomerQueries.bind(hooks),\n getCustomerData: hooks.getCustomerData.bind(hooks),\n setCustomerData: hooks.setCustomerData.bind(hooks),\n useProductListingGroupsQuery:\n hooks.useProductListingGroupsQuery.bind(hooks),\n useSuspenseProductListingGroupsQuery:\n hooks.useSuspenseProductListingGroupsQuery.bind(hooks),\n useInfiniteProductListingGroupsQuery:\n hooks.useInfiniteProductListingGroupsQuery.bind(hooks),\n useSuspenseInfiniteProductListingGroupsQuery:\n hooks.useSuspenseInfiniteProductListingGroupsQuery.bind(hooks),\n prefetchProductListingGroupsQuery:\n hooks.prefetchProductListingGroupsQuery.bind(hooks),\n prefetchInfiniteProductListingGroupsQuery:\n hooks.prefetchInfiniteProductListingGroupsQuery.bind(hooks),\n useProductDetail: hooks.useProductDetail.bind(hooks),\n useProductDetailBySlug: hooks.useProductDetailBySlug.bind(hooks),\n useProductDetailById: hooks.useProductDetailById.bind(hooks),\n } as ReadOnlyQueryHooks\n}\n\nexport function createQueryHooks(\n client: RootClient,\n queryClient: QueryClient = getQueryClient(),\n): ReadOnlyQueryHooks {\n const config = client.getConfig()\n const onUnauthorized = async (): Promise<string | null> => {\n try {\n const result = await client.customer.auth.refreshToken()\n return result.token ?? null\n } catch {\n return null\n }\n }\n\n const collectionClient = new CollectionClient(\n config.publishableKey,\n undefined,\n () => client.customer.auth.getToken(),\n onUnauthorized,\n (id) => {\n client.lastRequestId = id\n },\n config.apiUrl,\n )\n\n const hooks = new QueryHooks<PublicCollection>(\n queryClient,\n collectionClient,\n client.customer.auth,\n client.commerce,\n )\n\n return createReadOnlyQueryHooksFacade(hooks)\n}\n\nexport function createServerQueryHooks(\n client: ServerClient,\n queryClient: QueryClient = getQueryClient(),\n): QueryHooks<ServerCollection> {\n return new QueryHooks<ServerCollection>(\n queryClient,\n client.collections,\n undefined,\n client.commerce,\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAIO;AAEP,SAAS,kBAAkB;AACzB,SAAO,IAAI,+BAAY;AAAA,IACrB,gBAAgB;AAAA,MACd,SAAS;AAAA;AAAA;AAAA;AAAA,QAIP,WAAW,OAAO;AAAA,QAClB,sBAAsB;AAAA,MACxB;AAAA,MACA,WAAW;AAAA,QACT,sBAAsB,CAAC,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C,OAAO;AACN,aAAO,gBAAgB;AAAA,IACzB;AAAA,IACA,OAAO;AAAA,EACT;AAEA,QAAM,QAAQ,IAAI;AAAA,IAChB;AAAA,IACA;AAAA,IACA,OAAO,SAAS;AAAA,IAChB,OAAO;AAAA,EACT;AAEA,SAAO,+BAA+B,KAAK;AAC7C;AAEO,SAAS,uBACd,QACA,cAA2B,eAAe,GACZ;AAC9B,SAAO,IAAI;AAAA,IACT;AAAA,IACA,OAAO;AAAA,IACP;AAAA,IACA,OAAO;AAAA,EACT;AACF;","names":["import_react_query","useQueryOriginal","useSuspenseQueryOriginal","useInfiniteQueryOriginal","useSuspenseInfiniteQueryOriginal","useMutationOriginal","import_react_query","useMutationOriginal","useQueryOriginal","import_react_query","useQueryOriginal","useSuspenseQueryOriginal","useInfiniteQueryOriginal","useSuspenseInfiniteQueryOriginal","delay"]}
|