@reblu/site-next 1.20.0 → 1.21.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/dist/cart.d.cts CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import * as zustand_middleware from 'zustand/middleware';
3
3
  import * as zustand from 'zustand';
4
+ import { ShopCartValidationError, ShopValidateCartInput, ShopCartValidation } from '@reblu/site-contracts';
4
5
 
5
6
  /**
6
7
  * `CartProvider` — mount this once near the root layout (inside a Client
@@ -167,4 +168,128 @@ declare function useCartHydrated(): boolean;
167
168
  */
168
169
  declare function useCart(): UseCartResult;
169
170
 
170
- export { type AddItemOutcome, type AddItemStatus, CART_STORAGE_KEY, CART_STORE_PERSIST_VERSION, type CartItem, CartProvider, type CartStore, type UseCartResult, __resetCartStoreForTests, useCart, useCartHydrated, useCartStore };
171
+ /**
172
+ * Cart validation (REB-981). A persisted cart (`localStorage` `shop-cart`)
173
+ * outlives the catalog it was filled from: a product can be deleted,
174
+ * deactivated, sold out or repriced between visits. `validateCart` asks the
175
+ * SITE's validate-cart Route Handler (`createShopValidateCartRoute`) about
176
+ * every line and APPLIES the answer to the store, so the cart page and the
177
+ * checkout never show or submit a line nobody can buy.
178
+ */
179
+ /** Calls validate-cart for the given lines. Must reject (or throw) on failure. */
180
+ type CartValidator = (input: ShopValidateCartInput) => Promise<ShopCartValidation>;
181
+ interface ValidateCartOptions {
182
+ /**
183
+ * The SITE's validate-cart Route Handler path, used by the default
184
+ * validator. Defaults to `'/api/shop/validate-cart'`.
185
+ */
186
+ endpoint?: string;
187
+ /** Replaces the default `fetch`-based validator entirely. */
188
+ validate?: CartValidator;
189
+ /**
190
+ * `true` (default) removes lines whose error says `suggestedAction:
191
+ * 'remove'` (`not_found`, `inactive`, `out_of_stock`). `false` leaves them
192
+ * in the cart and only reports them through `lineErrors`.
193
+ */
194
+ removeUnavailable?: boolean;
195
+ }
196
+ /** A line the validation removed — `name`/`variantName` come from the persisted line. */
197
+ interface CartRemovedLine {
198
+ productId: string;
199
+ variantId: string | null;
200
+ name: string;
201
+ variantName?: string;
202
+ type: ShopCartValidationError['type'];
203
+ message: string;
204
+ }
205
+ /** A line whose quantity was clamped to the stock still available. */
206
+ interface CartQuantityChange {
207
+ productId: string;
208
+ variantId: string | null;
209
+ name: string;
210
+ variantName?: string;
211
+ from: number;
212
+ to: number;
213
+ }
214
+ /** A line whose `unitPrice` (integer cents) was refreshed from the live price. */
215
+ interface CartPriceChange {
216
+ productId: string;
217
+ variantId: string | null;
218
+ name: string;
219
+ variantName?: string;
220
+ from: number;
221
+ to: number;
222
+ }
223
+ /**
224
+ * - `valid` — every line is buyable as it stands; nothing changed.
225
+ * - `adjusted` — the cart was changed (lines removed, quantities clamped or
226
+ * prices refreshed). Show the changes before letting the visitor pay.
227
+ * - `invalid` — problems remain that were not applied (lines flagged with
228
+ * `removeUnavailable: false`, or a cart-wide error).
229
+ * - `empty` — no lines; nothing was sent.
230
+ * - `failed` — the request failed; the cart was left exactly as it was.
231
+ */
232
+ type CartValidationStatus = 'valid' | 'adjusted' | 'invalid' | 'empty' | 'failed';
233
+ interface CartValidationOutcome {
234
+ status: CartValidationStatus;
235
+ removed: CartRemovedLine[];
236
+ quantityChanges: CartQuantityChange[];
237
+ priceChanges: CartPriceChange[];
238
+ /** Every line error of the response, keyed by {@link cartLineKey}. */
239
+ lineErrors: Record<string, ShopCartValidationError>;
240
+ /** Errors that match no cart line (e.g. `empty_cart`) or were not applied. */
241
+ unresolvedErrors: ShopCartValidationError[];
242
+ /** Set when `status` is `'failed'`. */
243
+ error?: unknown;
244
+ }
245
+ declare const DEFAULT_VALIDATE_CART_ENDPOINT = "/api/shop/validate-cart";
246
+ /** Stable key for a cart line: `productId` + `variantId` (absent and `null` are the same line). */
247
+ declare function cartLineKey(productId: string, variantId?: string | null): string;
248
+ /**
249
+ * Pure: applies a validate-cart response to a list of lines. Lines the
250
+ * response does not mention (e.g. added while the request was in flight)
251
+ * are left untouched.
252
+ */
253
+ declare function applyCartValidation(items: CartItem[], validation: ShopCartValidation, { removeUnavailable }?: Pick<ValidateCartOptions, 'removeUnavailable'>): Omit<CartValidationOutcome, 'status' | 'error'> & {
254
+ items: CartItem[];
255
+ };
256
+ /**
257
+ * Validates the persisted cart against live product, stock and price data
258
+ * and applies the result to `useCartStore`:
259
+ *
260
+ * 1. removes lines the API says to remove, reporting their persisted names;
261
+ * 2. clamps `insufficient_stock` lines to the quantity still available;
262
+ * 3. refreshes `unitPrice` (and `maxStock`) from the live data.
263
+ *
264
+ * Waits for `CartProvider`'s hydration first, so it never validates the
265
+ * empty pre-hydration cart. Never throws: a failed request resolves to
266
+ * `status: 'failed'` and leaves the cart untouched. Running it again on an
267
+ * already-clean cart is a no-op (`status: 'valid'`).
268
+ */
269
+ declare function validateCart(options?: ValidateCartOptions): Promise<CartValidationOutcome>;
270
+
271
+ interface UseCartValidationOptions extends ValidateCartOptions {
272
+ /** Validate once automatically when the cart has hydrated. Defaults to `true`. */
273
+ auto?: boolean;
274
+ }
275
+ interface UseCartValidationResult extends Omit<CartValidationOutcome, 'status'> {
276
+ /** `'idle'` before the first run, `'validating'` while a request is in flight. */
277
+ status: CartValidationStatus | 'idle' | 'validating';
278
+ /** The error the last run reported for this line, if any. */
279
+ getLineError: (productId: string, variantId?: string | null) => ShopCartValidationError | undefined;
280
+ /**
281
+ * Runs the validation now (e.g. right before submitting the checkout) and
282
+ * resolves to its outcome. Concurrent calls share the in-flight request.
283
+ */
284
+ revalidate: () => Promise<CartValidationOutcome>;
285
+ }
286
+ /**
287
+ * `useCartValidation` (REB-981) — runs {@link validateCart} once when the
288
+ * cart has hydrated (cart page mount) and exposes the last outcome, so the
289
+ * page can show what was removed or adjusted and mark the offending lines.
290
+ * Call `revalidate()` before checkout. Later cart edits never re-trigger the
291
+ * automatic run, so it cannot loop.
292
+ */
293
+ declare function useCartValidation(options?: UseCartValidationOptions): UseCartValidationResult;
294
+
295
+ export { type AddItemOutcome, type AddItemStatus, CART_STORAGE_KEY, CART_STORE_PERSIST_VERSION, type CartItem, type CartPriceChange, CartProvider, type CartQuantityChange, type CartRemovedLine, type CartStore, type CartValidationOutcome, type CartValidationStatus, type CartValidator, DEFAULT_VALIDATE_CART_ENDPOINT, type UseCartResult, type UseCartValidationOptions, type UseCartValidationResult, type ValidateCartOptions, __resetCartStoreForTests, applyCartValidation, cartLineKey, useCart, useCartHydrated, useCartStore, useCartValidation, validateCart };
package/dist/cart.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import * as zustand_middleware from 'zustand/middleware';
3
3
  import * as zustand from 'zustand';
4
+ import { ShopCartValidationError, ShopValidateCartInput, ShopCartValidation } from '@reblu/site-contracts';
4
5
 
5
6
  /**
6
7
  * `CartProvider` — mount this once near the root layout (inside a Client
@@ -167,4 +168,128 @@ declare function useCartHydrated(): boolean;
167
168
  */
168
169
  declare function useCart(): UseCartResult;
169
170
 
170
- export { type AddItemOutcome, type AddItemStatus, CART_STORAGE_KEY, CART_STORE_PERSIST_VERSION, type CartItem, CartProvider, type CartStore, type UseCartResult, __resetCartStoreForTests, useCart, useCartHydrated, useCartStore };
171
+ /**
172
+ * Cart validation (REB-981). A persisted cart (`localStorage` `shop-cart`)
173
+ * outlives the catalog it was filled from: a product can be deleted,
174
+ * deactivated, sold out or repriced between visits. `validateCart` asks the
175
+ * SITE's validate-cart Route Handler (`createShopValidateCartRoute`) about
176
+ * every line and APPLIES the answer to the store, so the cart page and the
177
+ * checkout never show or submit a line nobody can buy.
178
+ */
179
+ /** Calls validate-cart for the given lines. Must reject (or throw) on failure. */
180
+ type CartValidator = (input: ShopValidateCartInput) => Promise<ShopCartValidation>;
181
+ interface ValidateCartOptions {
182
+ /**
183
+ * The SITE's validate-cart Route Handler path, used by the default
184
+ * validator. Defaults to `'/api/shop/validate-cart'`.
185
+ */
186
+ endpoint?: string;
187
+ /** Replaces the default `fetch`-based validator entirely. */
188
+ validate?: CartValidator;
189
+ /**
190
+ * `true` (default) removes lines whose error says `suggestedAction:
191
+ * 'remove'` (`not_found`, `inactive`, `out_of_stock`). `false` leaves them
192
+ * in the cart and only reports them through `lineErrors`.
193
+ */
194
+ removeUnavailable?: boolean;
195
+ }
196
+ /** A line the validation removed — `name`/`variantName` come from the persisted line. */
197
+ interface CartRemovedLine {
198
+ productId: string;
199
+ variantId: string | null;
200
+ name: string;
201
+ variantName?: string;
202
+ type: ShopCartValidationError['type'];
203
+ message: string;
204
+ }
205
+ /** A line whose quantity was clamped to the stock still available. */
206
+ interface CartQuantityChange {
207
+ productId: string;
208
+ variantId: string | null;
209
+ name: string;
210
+ variantName?: string;
211
+ from: number;
212
+ to: number;
213
+ }
214
+ /** A line whose `unitPrice` (integer cents) was refreshed from the live price. */
215
+ interface CartPriceChange {
216
+ productId: string;
217
+ variantId: string | null;
218
+ name: string;
219
+ variantName?: string;
220
+ from: number;
221
+ to: number;
222
+ }
223
+ /**
224
+ * - `valid` — every line is buyable as it stands; nothing changed.
225
+ * - `adjusted` — the cart was changed (lines removed, quantities clamped or
226
+ * prices refreshed). Show the changes before letting the visitor pay.
227
+ * - `invalid` — problems remain that were not applied (lines flagged with
228
+ * `removeUnavailable: false`, or a cart-wide error).
229
+ * - `empty` — no lines; nothing was sent.
230
+ * - `failed` — the request failed; the cart was left exactly as it was.
231
+ */
232
+ type CartValidationStatus = 'valid' | 'adjusted' | 'invalid' | 'empty' | 'failed';
233
+ interface CartValidationOutcome {
234
+ status: CartValidationStatus;
235
+ removed: CartRemovedLine[];
236
+ quantityChanges: CartQuantityChange[];
237
+ priceChanges: CartPriceChange[];
238
+ /** Every line error of the response, keyed by {@link cartLineKey}. */
239
+ lineErrors: Record<string, ShopCartValidationError>;
240
+ /** Errors that match no cart line (e.g. `empty_cart`) or were not applied. */
241
+ unresolvedErrors: ShopCartValidationError[];
242
+ /** Set when `status` is `'failed'`. */
243
+ error?: unknown;
244
+ }
245
+ declare const DEFAULT_VALIDATE_CART_ENDPOINT = "/api/shop/validate-cart";
246
+ /** Stable key for a cart line: `productId` + `variantId` (absent and `null` are the same line). */
247
+ declare function cartLineKey(productId: string, variantId?: string | null): string;
248
+ /**
249
+ * Pure: applies a validate-cart response to a list of lines. Lines the
250
+ * response does not mention (e.g. added while the request was in flight)
251
+ * are left untouched.
252
+ */
253
+ declare function applyCartValidation(items: CartItem[], validation: ShopCartValidation, { removeUnavailable }?: Pick<ValidateCartOptions, 'removeUnavailable'>): Omit<CartValidationOutcome, 'status' | 'error'> & {
254
+ items: CartItem[];
255
+ };
256
+ /**
257
+ * Validates the persisted cart against live product, stock and price data
258
+ * and applies the result to `useCartStore`:
259
+ *
260
+ * 1. removes lines the API says to remove, reporting their persisted names;
261
+ * 2. clamps `insufficient_stock` lines to the quantity still available;
262
+ * 3. refreshes `unitPrice` (and `maxStock`) from the live data.
263
+ *
264
+ * Waits for `CartProvider`'s hydration first, so it never validates the
265
+ * empty pre-hydration cart. Never throws: a failed request resolves to
266
+ * `status: 'failed'` and leaves the cart untouched. Running it again on an
267
+ * already-clean cart is a no-op (`status: 'valid'`).
268
+ */
269
+ declare function validateCart(options?: ValidateCartOptions): Promise<CartValidationOutcome>;
270
+
271
+ interface UseCartValidationOptions extends ValidateCartOptions {
272
+ /** Validate once automatically when the cart has hydrated. Defaults to `true`. */
273
+ auto?: boolean;
274
+ }
275
+ interface UseCartValidationResult extends Omit<CartValidationOutcome, 'status'> {
276
+ /** `'idle'` before the first run, `'validating'` while a request is in flight. */
277
+ status: CartValidationStatus | 'idle' | 'validating';
278
+ /** The error the last run reported for this line, if any. */
279
+ getLineError: (productId: string, variantId?: string | null) => ShopCartValidationError | undefined;
280
+ /**
281
+ * Runs the validation now (e.g. right before submitting the checkout) and
282
+ * resolves to its outcome. Concurrent calls share the in-flight request.
283
+ */
284
+ revalidate: () => Promise<CartValidationOutcome>;
285
+ }
286
+ /**
287
+ * `useCartValidation` (REB-981) — runs {@link validateCart} once when the
288
+ * cart has hydrated (cart page mount) and exposes the last outcome, so the
289
+ * page can show what was removed or adjusted and mark the offending lines.
290
+ * Call `revalidate()` before checkout. Later cart edits never re-trigger the
291
+ * automatic run, so it cannot loop.
292
+ */
293
+ declare function useCartValidation(options?: UseCartValidationOptions): UseCartValidationResult;
294
+
295
+ export { type AddItemOutcome, type AddItemStatus, CART_STORAGE_KEY, CART_STORE_PERSIST_VERSION, type CartItem, type CartPriceChange, CartProvider, type CartQuantityChange, type CartRemovedLine, type CartStore, type CartValidationOutcome, type CartValidationStatus, type CartValidator, DEFAULT_VALIDATE_CART_ENDPOINT, type UseCartResult, type UseCartValidationOptions, type UseCartValidationResult, type ValidateCartOptions, __resetCartStoreForTests, applyCartValidation, cartLineKey, useCart, useCartHydrated, useCartStore, useCartValidation, validateCart };
package/dist/cart.js CHANGED
@@ -136,13 +136,226 @@ function useCart() {
136
136
  const itemCount = items.reduce((sum, item) => sum + item.quantity, 0);
137
137
  return { items, total, itemCount, hydrated, addItem, removeItem, updateQuantity, clearCart };
138
138
  }
139
+
140
+ // src/cart/validate.ts
141
+ var DEFAULT_VALIDATE_CART_ENDPOINT = "/api/shop/validate-cart";
142
+ function cartLineKey(productId, variantId) {
143
+ return JSON.stringify([productId, variantId ?? null]);
144
+ }
145
+ function emptyOutcome(status) {
146
+ return {
147
+ status,
148
+ removed: [],
149
+ quantityChanges: [],
150
+ priceChanges: [],
151
+ lineErrors: {},
152
+ unresolvedErrors: []
153
+ };
154
+ }
155
+ function isValidation(value) {
156
+ if (!value || typeof value !== "object") return false;
157
+ const v = value;
158
+ return typeof v.valid === "boolean" && Array.isArray(v.errors) && Array.isArray(v.items);
159
+ }
160
+ function defaultValidator(endpoint) {
161
+ return async (input) => {
162
+ const res = await fetch(endpoint, {
163
+ method: "POST",
164
+ headers: { "Content-Type": "application/json" },
165
+ body: JSON.stringify(input)
166
+ });
167
+ if (!res.ok) {
168
+ throw new Error(`validate-cart failed with HTTP ${res.status}`);
169
+ }
170
+ const json = await res.json();
171
+ const data = json && typeof json === "object" ? json.data : void 0;
172
+ if (!isValidation(data)) {
173
+ throw new Error("validate-cart returned an unexpected body");
174
+ }
175
+ return data;
176
+ };
177
+ }
178
+ function waitForHydration() {
179
+ if (useCartStore.persist.hasHydrated()) return Promise.resolve();
180
+ return new Promise((resolve) => {
181
+ const unsubscribe = useCartStore.persist.onFinishHydration(() => {
182
+ unsubscribe();
183
+ resolve();
184
+ });
185
+ });
186
+ }
187
+ function applyCartValidation(items, validation, { removeUnavailable = true } = {}) {
188
+ const removed = [];
189
+ const quantityChanges = [];
190
+ const priceChanges = [];
191
+ const lineErrors = {};
192
+ const unresolvedErrors = [];
193
+ const byKey = new Map(items.map((item) => [cartLineKey(item.productId, item.variantId), item]));
194
+ const removeKeys = /* @__PURE__ */ new Set();
195
+ const newQuantity = /* @__PURE__ */ new Map();
196
+ for (const error of validation.errors) {
197
+ const key = cartLineKey(error.productId, error.variantId);
198
+ const line = byKey.get(key);
199
+ if (!line) {
200
+ unresolvedErrors.push(error);
201
+ continue;
202
+ }
203
+ lineErrors[key] = error;
204
+ if (error.suggestedAction === "remove" && removeUnavailable) {
205
+ removeKeys.add(key);
206
+ removed.push({
207
+ productId: line.productId,
208
+ variantId: line.variantId ?? null,
209
+ name: line.name,
210
+ ...line.variantName !== void 0 && { variantName: line.variantName },
211
+ type: error.type,
212
+ message: error.message
213
+ });
214
+ } else if (error.suggestedAction === "update_quantity" && typeof error.newQuantity === "number") {
215
+ newQuantity.set(key, error.newQuantity);
216
+ } else {
217
+ unresolvedErrors.push(error);
218
+ }
219
+ }
220
+ const live = new Map(
221
+ validation.items.map((item) => [cartLineKey(item.productId, item.variantId), item])
222
+ );
223
+ const next = [];
224
+ for (const line of items) {
225
+ const key = cartLineKey(line.productId, line.variantId);
226
+ if (removeKeys.has(key)) continue;
227
+ let updated = line;
228
+ const liveItem = live.get(key);
229
+ if (liveItem) {
230
+ if (liveItem.unitPrice !== line.unitPrice) {
231
+ priceChanges.push({
232
+ productId: line.productId,
233
+ variantId: line.variantId ?? null,
234
+ name: line.name,
235
+ ...line.variantName !== void 0 && { variantName: line.variantName },
236
+ from: line.unitPrice,
237
+ to: liveItem.unitPrice
238
+ });
239
+ updated = { ...updated, unitPrice: liveItem.unitPrice };
240
+ }
241
+ if (liveItem.maxStock !== line.maxStock) {
242
+ updated = { ...updated, maxStock: liveItem.maxStock };
243
+ }
244
+ }
245
+ const clampTo = newQuantity.get(key);
246
+ if (clampTo !== void 0) {
247
+ const to = Math.trunc(clampTo);
248
+ if (to < 1) {
249
+ removed.push({
250
+ productId: line.productId,
251
+ variantId: line.variantId ?? null,
252
+ name: line.name,
253
+ ...line.variantName !== void 0 && { variantName: line.variantName },
254
+ type: "out_of_stock",
255
+ message: lineErrors[key]?.message ?? ""
256
+ });
257
+ continue;
258
+ }
259
+ if (to < line.quantity) {
260
+ quantityChanges.push({
261
+ productId: line.productId,
262
+ variantId: line.variantId ?? null,
263
+ name: line.name,
264
+ ...line.variantName !== void 0 && { variantName: line.variantName },
265
+ from: line.quantity,
266
+ to
267
+ });
268
+ updated = { ...updated, quantity: to };
269
+ }
270
+ }
271
+ next.push(updated);
272
+ }
273
+ return { items: next, removed, quantityChanges, priceChanges, lineErrors, unresolvedErrors };
274
+ }
275
+ async function validateCart(options = {}) {
276
+ await waitForHydration();
277
+ const items = useCartStore.getState().items;
278
+ if (items.length === 0) return emptyOutcome("empty");
279
+ const validate = options.validate ?? defaultValidator(options.endpoint ?? DEFAULT_VALIDATE_CART_ENDPOINT);
280
+ let validation;
281
+ try {
282
+ validation = await validate({
283
+ items: items.map((i) => ({
284
+ productId: i.productId,
285
+ variantId: i.variantId,
286
+ quantity: i.quantity
287
+ }))
288
+ });
289
+ } catch (error) {
290
+ return { ...emptyOutcome("failed"), error };
291
+ }
292
+ const applied = applyCartValidation(useCartStore.getState().items, validation, options);
293
+ const { items: nextItems, ...report } = applied;
294
+ const changed = report.removed.length > 0 || report.quantityChanges.length > 0 || report.priceChanges.length > 0;
295
+ const current = useCartStore.getState().items;
296
+ if (nextItems.length !== current.length || nextItems.some((item, i) => item !== current[i])) {
297
+ useCartStore.setState({ items: nextItems });
298
+ }
299
+ const status = report.unresolvedErrors.length > 0 ? "invalid" : changed ? "adjusted" : "valid";
300
+ return { status, ...report };
301
+ }
302
+
303
+ // src/cart/use-cart-validation.ts
304
+ import { useCallback, useEffect as useEffect2, useRef, useState } from "react";
305
+ var IDLE = {
306
+ removed: [],
307
+ quantityChanges: [],
308
+ priceChanges: [],
309
+ lineErrors: {},
310
+ unresolvedErrors: []
311
+ };
312
+ function useCartValidation(options = {}) {
313
+ const { auto = true } = options;
314
+ const hydrated = useCartHydrated();
315
+ const [status, setStatus] = useState("idle");
316
+ const [report, setReport] = useState(IDLE);
317
+ const optionsRef = useRef(options);
318
+ useEffect2(() => {
319
+ optionsRef.current = options;
320
+ });
321
+ const inFlight = useRef(null);
322
+ const autoRan = useRef(false);
323
+ const revalidate = useCallback(() => {
324
+ if (inFlight.current) return inFlight.current;
325
+ setStatus("validating");
326
+ const run = validateCart(optionsRef.current).then((outcome) => {
327
+ inFlight.current = null;
328
+ const { status: nextStatus, ...rest } = outcome;
329
+ setReport(rest);
330
+ setStatus(nextStatus);
331
+ return outcome;
332
+ });
333
+ inFlight.current = run;
334
+ return run;
335
+ }, []);
336
+ useEffect2(() => {
337
+ if (!auto || !hydrated || autoRan.current) return;
338
+ autoRan.current = true;
339
+ void revalidate();
340
+ }, [auto, hydrated, revalidate]);
341
+ const getLineError = useCallback(
342
+ (productId, variantId) => report.lineErrors[cartLineKey(productId, variantId)],
343
+ [report]
344
+ );
345
+ return { status, ...report, getLineError, revalidate };
346
+ }
139
347
  export {
140
348
  CART_STORAGE_KEY,
141
349
  CART_STORE_PERSIST_VERSION,
142
350
  CartProvider,
351
+ DEFAULT_VALIDATE_CART_ENDPOINT,
143
352
  __resetCartStoreForTests,
353
+ applyCartValidation,
354
+ cartLineKey,
144
355
  useCart,
145
356
  useCartHydrated,
146
- useCartStore
357
+ useCartStore,
358
+ useCartValidation,
359
+ validateCart
147
360
  };
148
361
  //# sourceMappingURL=cart.js.map
package/dist/cart.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cart/provider.tsx","../src/cart/store.ts","../src/cart/use-cart.ts"],"sourcesContent":["'use client'\n\nimport { useEffect } from 'react'\nimport { useCartStore } from './store'\n\n/**\n * `CartProvider` — mount this once near the root layout (inside a Client\n * Component boundary). It owns the ONE explicit-hydration call\n * `useCartStore.persist.rehydrate()` requires (`store.ts`'s `skipHydration`\n * doc) — a SITE that forgets to mount it gets an always-empty cart that never\n * reads back whatever a previous visit (or page reload) persisted.\n */\nexport function CartProvider({ children }: { children: React.ReactNode }) {\n useEffect(() => {\n useCartStore.persist.rehydrate()\n }, [])\n\n return <>{children}</>\n}\n","import { create } from 'zustand'\nimport { persist } from 'zustand/middleware'\n\n/**\n * `useCartStore` — the SDK's cart state (REB-829). Ported verbatim (same\n * shape, same quantity-clamping rules) from demo-site's local\n * `lib/store/cart-store.ts`, which every SITE was otherwise expected to\n * hand-copy. `CART_STORAGE_KEY` stays exactly `'shop-cart'` on purpose: a\n * SITE migrating from the local copy keeps its visitors' existing carts.\n *\n * `skipHydration: true` (zustand persist) is load-bearing for SSR: without\n * it, zustand's persist middleware reads `localStorage` synchronously during\n * module evaluation, which throws (or silently desyncs) on the server. The\n * `CartProvider` (`./provider`) calls `useCartStore.persist.rehydrate()`\n * inside a `useEffect`, so hydration only ever happens client-side, after\n * mount — the same explicit-hydration contract the SITE README documents.\n */\nexport const CART_STORAGE_KEY = 'shop-cart'\n\n/**\n * The zustand `persist` schema version for the cart's PERSISTED shape (the\n * `CartItem[]` written to `localStorage` under `CART_STORAGE_KEY`) — bump\n * this (with a `migrate` option) if that shape ever changes incompatibly.\n * Also folded into {@link CART_STORE_GLOBAL_KEY} (REB-837 review fix): a\n * future incompatible shape change should mint a NEW global singleton\n * rather than let a stale, already-evaluated old-shape instance (e.g. kept\n * alive across an HMR reload in dev) silently satisfy the new one.\n */\nexport const CART_STORE_PERSIST_VERSION = 0\n\nexport interface CartItem {\n productId: string\n variantId?: string | null\n name: string\n variantName?: string\n /** Integer cents — every Reblu shop price travels as cents, never a float. */\n unitPrice: number\n quantity: number\n imageUrl?: string\n /** `null` means untracked/unlimited stock — never clamp against it. */\n maxStock: number | null\n /** Basis points, e.g. `2100` = 21%. `null`/`undefined` = unknown or exempt. */\n taxRateBps?: number | null\n taxRateName?: string | null\n}\n\n/**\n * Outcome of `addItem` (REB-837): a SITE's add-to-cart feedback (toast,\n * `AddToCartButton`'s built-in confirmed/error state) needs to know what\n * actually happened, not just fire-and-forget — `'clamped'` only differs\n * from `'added'` in the RESULTING quantity reaching less than what was\n * requested (capped by `maxStock`) while the line still grew; `'refused'`\n * means nothing was added (invalid quantity, out of stock, or the line was\n * already at `maxStock` — REB-839).\n */\nexport type AddItemStatus = 'added' | 'clamped' | 'refused'\n\nexport interface AddItemOutcome {\n status: AddItemStatus\n /** The resulting line quantity after the call (`0` when refused and no line exists). */\n quantity: number\n}\n\nexport interface CartStore {\n items: CartItem[]\n addItem: (item: CartItem) => AddItemOutcome\n removeItem: (productId: string, variantId?: string | null) => void\n updateQuantity: (\n productId: string,\n variantId: string | null | undefined,\n quantity: number,\n ) => void\n clearCart: () => void\n getTotal: () => number\n getItemCount: () => number\n}\n\nfunction isSameItem(a: CartItem, productId: string, variantId?: string | null): boolean {\n return a.productId === productId && (a.variantId ?? null) === (variantId ?? null)\n}\n\n/**\n * REB-829 review finding: neither `addItem` nor `updateQuantity` validated\n * `quantity` — `0`, a negative number, `NaN` (e.g. a stray `parseInt('')`\n * upstream), a non-integer, or `maxStock` itself being `0` (out of stock)\n * all used to leave an invalid line sitting in the cart, silently reaching\n * checkout.\n *\n * Normalizes to a safe POSITIVE INTEGER clamped to `maxStock`. Returns `0`\n * to signal \"not a valid positive quantity\" — callers decide what that\n * means for them: `addItem` ignores the call (never creates/corrupts a\n * line), `updateQuantity` removes the line (same as its pre-existing\n * `quantity <= 0` → remove contract, just now reached by more inputs).\n *\n * `Math.trunc` rounds toward zero (not `Math.floor`, which would round a\n * negative input further negative before the `< 1` check below ever saw it\n * — not a behavioural difference here since any negative result is\n * rejected either way, but `trunc` is the operation that actually means\n * \"drop the fractional part\").\n */\nfunction normalizeQuantity(quantity: number, maxStock: number | null): number {\n if (!Number.isFinite(quantity)) return 0\n const truncated = Math.trunc(quantity)\n if (truncated < 1) return 0\n if (maxStock === null) return truncated\n const maxTruncated = Math.trunc(maxStock)\n if (maxTruncated < 1) return 0\n return Math.min(truncated, maxTruncated)\n}\n\n/**\n * REB-837 cross-entry singleton guard — the mutation that caught it: a\n * single test rendering `useShopOrderStatus` (the `./shop` tsup entry) and\n * asserting on `useCartStore` (the `./cart` entry) saw the order resolve to\n * `paid` but the cart stay non-empty. Root cause: `splitting: false` (R4,\n * `tsup.config.ts`) bundles each entry standalone, so a plain relative\n * import of this file from `./shop` INLINES a SEPARATE copy of this\n * `create(...)` call — a second, disconnected store instance with its own\n * state, not the one `@reblu/site-next/cart` consumers read. `clearCart()`\n * from inside the hook silently cleared the WRONG store.\n *\n * `globalThis` keyed by a `Symbol.for(...)` (same registry entry regardless\n * of which bundle's copy of this module evaluates it first) makes every\n * entry that imports this file — however many times esbuild inlines it —\n * resolve to the SAME store. Verified by mutation: removing this guard\n * (reverting to a bare `export const useCartStore = create(...)`) turns\n * `use-shop-order-status.test.ts`'s cart-clearing assertions red again once\n * the hook is exercised through its OWN entry rather than imported directly\n * within `cart`'s own test file (which never saw the bug, since it only\n * ever touches ONE copy of this module).\n */\nfunction createCartStore() {\n return create<CartStore>()(\n persist(\n (set, get) => ({\n items: [],\n\n addItem: (item) => {\n // REB-837: `set`'s updater can't return a value to the caller, so the\n // outcome is captured in this closure variable and returned after.\n let outcome: AddItemOutcome = { status: 'refused', quantity: 0 }\n\n set((state) => {\n const existing = state.items.find((i) => isSameItem(i, item.productId, item.variantId))\n\n if (existing) {\n // REB-829 review follow-up (a): incoming maxStock is the\n // FRESHEST stock signal available — if it says 0, the product is\n // confirmed out of stock right now, so the existing line is\n // removed outright (same contract as updateQuantity's own\n // \"quantity resolves to <1 → remove\"), not merely left alone.\n if (item.maxStock !== null && Math.trunc(item.maxStock) < 1) {\n outcome = { status: 'refused', quantity: 0 }\n return {\n items: state.items.filter((i) => !isSameItem(i, item.productId, item.variantId)),\n }\n }\n\n const requestedQty = existing.quantity + item.quantity\n const newQty = normalizeQuantity(requestedQty, item.maxStock)\n if (newQty < 1) {\n // Invalid delta (NaN/non-positive quantity) — leave the\n // existing, previously-valid line untouched rather than\n // destroying good data because of one bad call.\n outcome = { status: 'refused', quantity: existing.quantity }\n return {}\n }\n\n // REB-839: nothing was gained when stock caps the line at (or,\n // with fresher stock, below) what it already held — report that\n // as 'refused', never as a partial-success 'clamped'. The line is\n // still reconciled below to the fresher maxStock.\n outcome = {\n status:\n newQty <= existing.quantity\n ? 'refused'\n : newQty < requestedQty\n ? 'clamped'\n : 'added',\n quantity: newQty,\n }\n\n // Refresh maxStock with the incoming value on every successful\n // merge — the stale-maxStock finding: a stored line used to keep\n // its ORIGINAL maxStock forever, so a later updateQuantity call\n // clamped against stock data that could be long out of date.\n return {\n items: state.items.map((i) =>\n isSameItem(i, item.productId, item.variantId)\n ? { ...i, quantity: newQty, maxStock: item.maxStock }\n : i,\n ),\n }\n }\n\n const qty = normalizeQuantity(item.quantity, item.maxStock)\n if (qty < 1) {\n // Invalid quantity, or maxStock 0 (out of stock) — never create\n // a line nobody could actually buy.\n outcome = { status: 'refused', quantity: 0 }\n return {}\n }\n\n outcome = { status: qty < item.quantity ? 'clamped' : 'added', quantity: qty }\n return { items: [...state.items, { ...item, quantity: qty }] }\n })\n\n return outcome\n },\n\n removeItem: (productId, variantId) => {\n set((state) => ({\n items: state.items.filter((i) => !isSameItem(i, productId, variantId)),\n }))\n },\n\n updateQuantity: (productId, variantId, quantity) => {\n const existing = get().items.find((i) => isSameItem(i, productId, variantId))\n if (!existing) return\n\n const newQty = normalizeQuantity(quantity, existing.maxStock)\n if (newQty < 1) {\n get().removeItem(productId, variantId)\n return\n }\n\n set((state) => ({\n items: state.items.map((i) =>\n isSameItem(i, productId, variantId) ? { ...i, quantity: newQty } : i,\n ),\n }))\n },\n\n clearCart: () => set({ items: [] }),\n\n getTotal: () => get().items.reduce((sum, item) => sum + item.unitPrice * item.quantity, 0),\n\n getItemCount: () => get().items.reduce((sum, item) => sum + item.quantity, 0),\n }),\n {\n name: CART_STORAGE_KEY,\n version: CART_STORE_PERSIST_VERSION,\n skipHydration: true,\n },\n ),\n )\n}\n\ntype CartStoreApi = ReturnType<typeof createCartStore>\n\n/**\n * Versioned (REB-837 review fix) with {@link CART_STORE_PERSIST_VERSION} —\n * an incompatible shape change bumps that version, which mints a NEW\n * `Symbol.for(...)` registry key, so a stale old-shape singleton (e.g. kept\n * alive across an HMR reload in dev before a code change takes effect)\n * never satisfies the new one.\n */\nconst CART_STORE_GLOBAL_KEY = Symbol.for(\n `@reblu/site-next/cart-store@v${CART_STORE_PERSIST_VERSION}`,\n)\n\ninterface GlobalWithCartStore {\n [CART_STORE_GLOBAL_KEY]?: CartStoreApi\n}\n\nconst globalForCartStore = globalThis as typeof globalThis & GlobalWithCartStore\n\nexport const useCartStore: CartStoreApi =\n globalForCartStore[CART_STORE_GLOBAL_KEY] ??\n (globalForCartStore[CART_STORE_GLOBAL_KEY] = createCartStore())\n\n/**\n * TEST-ONLY (REB-837 review fix). Clears the `globalThis`-keyed slot so the\n * NEXT access to `useCartStore` — in THIS module instance — creates a fresh\n * store. The singleton is intentionally shared process-wide; most tests\n * should keep resetting STATE via `useCartStore.setState(...)` in\n * `beforeEach`, not the instance itself. Reach for this only to prove\n * something about the singleton mechanism (e.g. the cross-entry test in\n * `tests/cart-store-cross-entry-singleton.test.ts`) — it does not and\n * cannot affect an ALREADY-evaluated copy of this module inlined into a\n * different tsup entry's bundle (each such copy owns its own `const\n * globalForCartStore`/`CART_STORE_GLOBAL_KEY` closed over at that copy's\n * own module-evaluation time, same as any other ES module binding).\n */\nexport function __resetCartStoreForTests(): void {\n delete globalForCartStore[CART_STORE_GLOBAL_KEY]\n}\n","'use client'\n\nimport { useSyncExternalStore } from 'react'\n\nimport { useCartStore, type AddItemOutcome, type CartItem } from './store'\n\nexport interface UseCartResult {\n items: CartItem[]\n /** Sum of every line's `unitPrice * quantity`, in integer cents. */\n total: number\n /** Sum of every line's `quantity`. */\n itemCount: number\n /**\n * Whether `CartProvider`'s `persist.rehydrate()` has finished (REB-837).\n * `false` on the server and on the very first client render — `items`\n * (and therefore `itemCount`) jumps from `0` to whatever was persisted the\n * instant hydration finishes, which is NOT a real \"item added\" event. A\n * consumer driving `CartIcon`'s `bumpOnAdd` MUST gate the bump on this\n * flag (see `CartIcon`'s own guard) or every page load with a non-empty\n * cart bumps the badge once for free.\n */\n hydrated: boolean\n addItem: (item: CartItem) => AddItemOutcome\n removeItem: (productId: string, variantId?: string | null) => void\n updateQuantity: (\n productId: string,\n variantId: string | null | undefined,\n quantity: number,\n ) => void\n clearCart: () => void\n}\n\nfunction subscribeHydration(onStoreChange: () => void): () => void {\n return useCartStore.persist.onFinishHydration(onStoreChange)\n}\n\nfunction getHydratedSnapshot(): boolean {\n return useCartStore.persist.hasHydrated()\n}\n\n/** Server snapshot is always `false` — the server never reads `localStorage`. */\nfunction getServerHydratedSnapshot(): boolean {\n return false\n}\n\n/**\n * `useCartHydrated` — standalone so a SITE that only needs the flag (e.g. to\n * gate its own effects) doesn't have to subscribe to the whole cart via\n * `useCart()`.\n */\nexport function useCartHydrated(): boolean {\n return useSyncExternalStore(subscribeHydration, getHydratedSnapshot, getServerHydratedSnapshot)\n}\n\n/**\n * `useCart` — the ergonomic entry point for a SITE's cart UI: a single\n * selector call that re-renders only on `items` changes, with `total`/\n * `itemCount` derived inline (cheap — a plain `reduce` over a typically-small\n * array) rather than via `useCartStore`'s own `getTotal`/`getItemCount`\n * selectors, which are stable function references and would NOT trigger a\n * re-render on their own. A SITE that wants raw store access (existing\n * per-field selectors, e.g. `useCartStore((s) => s.addItem)`) can still\n * import `useCartStore` directly — this hook doesn't replace it.\n */\nexport function useCart(): UseCartResult {\n const items = useCartStore((s) => s.items)\n const addItem = useCartStore((s) => s.addItem)\n const removeItem = useCartStore((s) => s.removeItem)\n const updateQuantity = useCartStore((s) => s.updateQuantity)\n const clearCart = useCartStore((s) => s.clearCart)\n const hydrated = useCartHydrated()\n\n const total = items.reduce((sum, item) => sum + item.unitPrice * item.quantity, 0)\n const itemCount = items.reduce((sum, item) => sum + item.quantity, 0)\n\n return { items, total, itemCount, hydrated, addItem, removeItem, updateQuantity, clearCart }\n}\n"],"mappings":";;;AAEA,SAAS,iBAAiB;;;ACF1B,SAAS,cAAc;AACvB,SAAS,eAAe;AAgBjB,IAAM,mBAAmB;AAWzB,IAAM,6BAA6B;AAiD1C,SAAS,WAAW,GAAa,WAAmB,WAAoC;AACtF,SAAO,EAAE,cAAc,cAAc,EAAE,aAAa,WAAW,aAAa;AAC9E;AAqBA,SAAS,kBAAkB,UAAkB,UAAiC;AAC5E,MAAI,CAAC,OAAO,SAAS,QAAQ,EAAG,QAAO;AACvC,QAAM,YAAY,KAAK,MAAM,QAAQ;AACrC,MAAI,YAAY,EAAG,QAAO;AAC1B,MAAI,aAAa,KAAM,QAAO;AAC9B,QAAM,eAAe,KAAK,MAAM,QAAQ;AACxC,MAAI,eAAe,EAAG,QAAO;AAC7B,SAAO,KAAK,IAAI,WAAW,YAAY;AACzC;AAuBA,SAAS,kBAAkB;AACzB,SAAO,OAAkB;AAAA,IACvB;AAAA,MACE,CAAC,KAAK,SAAS;AAAA,QACb,OAAO,CAAC;AAAA,QAER,SAAS,CAAC,SAAS;AAGjB,cAAI,UAA0B,EAAE,QAAQ,WAAW,UAAU,EAAE;AAE/D,cAAI,CAAC,UAAU;AACb,kBAAM,WAAW,MAAM,MAAM,KAAK,CAAC,MAAM,WAAW,GAAG,KAAK,WAAW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CAAC,CAAC;AAEL,SAAO,gCAAG,UAAS;AACrB;;;AEhBA,SAAS,4BAA4B;AA8BrC,SAAS,mBAAmB,eAAuC;AACjE,SAAO,aAAa,QAAQ,kBAAkB,aAAa;AAC7D;AAEA,SAAS,sBAA+B;AACtC,SAAO,aAAa,QAAQ,YAAY;AAC1C;AAGA,SAAS,4BAAqC;AAC5C,SAAO;AACT;AAOO,SAAS,kBAA2B;AACzC,SAAO,qBAAqB,oBAAoB,qBAAqB,yBAAyB;AAChG;AAYO,SAAS,UAAyB;AACvC,QAAM,QAAQ,aAAa,CAAC,MAAM,EAAE,KAAK;AACzC,QAAM,UAAU,aAAa,CAAC,MAAM,EAAE,OAAO;AAC7C,QAAM,aAAa,aAAa,CAAC,MAAM,EAAE,UAAU;AACnD,QAAM,iBAAiB,aAAa,CAAC,MAAM,EAAE,cAAc;AAC3D,QAAM,YAAY,aAAa,CAAC,MAAM,EAAE,SAAS;AACjD,QAAM,WAAW,gBAAgB;AAEjC,QAAM,QAAQ,MAAM,OAAO,CAAC,KAAK,SAAS,MAAM,KAAK,YAAY,KAAK,UAAU,CAAC;AACjF,QAAM,YAAY,MAAM,OAAO,CAAC,KAAK,SAAS,MAAM,KAAK,UAAU,CAAC;AAEpE,SAAO,EAAE,OAAO,OAAO,WAAW,UAAU,SAAS,YAAY,gBAAgB,UAAU;AAC7F;","names":[]}
1
+ {"version":3,"sources":["../src/cart/provider.tsx","../src/cart/store.ts","../src/cart/use-cart.ts","../src/cart/validate.ts","../src/cart/use-cart-validation.ts"],"sourcesContent":["'use client'\n\nimport { useEffect } from 'react'\nimport { useCartStore } from './store'\n\n/**\n * `CartProvider` — mount this once near the root layout (inside a Client\n * Component boundary). It owns the ONE explicit-hydration call\n * `useCartStore.persist.rehydrate()` requires (`store.ts`'s `skipHydration`\n * doc) — a SITE that forgets to mount it gets an always-empty cart that never\n * reads back whatever a previous visit (or page reload) persisted.\n */\nexport function CartProvider({ children }: { children: React.ReactNode }) {\n useEffect(() => {\n useCartStore.persist.rehydrate()\n }, [])\n\n return <>{children}</>\n}\n","import { create } from 'zustand'\nimport { persist } from 'zustand/middleware'\n\n/**\n * `useCartStore` — the SDK's cart state (REB-829). Ported verbatim (same\n * shape, same quantity-clamping rules) from demo-site's local\n * `lib/store/cart-store.ts`, which every SITE was otherwise expected to\n * hand-copy. `CART_STORAGE_KEY` stays exactly `'shop-cart'` on purpose: a\n * SITE migrating from the local copy keeps its visitors' existing carts.\n *\n * `skipHydration: true` (zustand persist) is load-bearing for SSR: without\n * it, zustand's persist middleware reads `localStorage` synchronously during\n * module evaluation, which throws (or silently desyncs) on the server. The\n * `CartProvider` (`./provider`) calls `useCartStore.persist.rehydrate()`\n * inside a `useEffect`, so hydration only ever happens client-side, after\n * mount — the same explicit-hydration contract the SITE README documents.\n */\nexport const CART_STORAGE_KEY = 'shop-cart'\n\n/**\n * The zustand `persist` schema version for the cart's PERSISTED shape (the\n * `CartItem[]` written to `localStorage` under `CART_STORAGE_KEY`) — bump\n * this (with a `migrate` option) if that shape ever changes incompatibly.\n * Also folded into {@link CART_STORE_GLOBAL_KEY} (REB-837 review fix): a\n * future incompatible shape change should mint a NEW global singleton\n * rather than let a stale, already-evaluated old-shape instance (e.g. kept\n * alive across an HMR reload in dev) silently satisfy the new one.\n */\nexport const CART_STORE_PERSIST_VERSION = 0\n\nexport interface CartItem {\n productId: string\n variantId?: string | null\n name: string\n variantName?: string\n /** Integer cents — every Reblu shop price travels as cents, never a float. */\n unitPrice: number\n quantity: number\n imageUrl?: string\n /** `null` means untracked/unlimited stock — never clamp against it. */\n maxStock: number | null\n /** Basis points, e.g. `2100` = 21%. `null`/`undefined` = unknown or exempt. */\n taxRateBps?: number | null\n taxRateName?: string | null\n}\n\n/**\n * Outcome of `addItem` (REB-837): a SITE's add-to-cart feedback (toast,\n * `AddToCartButton`'s built-in confirmed/error state) needs to know what\n * actually happened, not just fire-and-forget — `'clamped'` only differs\n * from `'added'` in the RESULTING quantity reaching less than what was\n * requested (capped by `maxStock`) while the line still grew; `'refused'`\n * means nothing was added (invalid quantity, out of stock, or the line was\n * already at `maxStock` — REB-839).\n */\nexport type AddItemStatus = 'added' | 'clamped' | 'refused'\n\nexport interface AddItemOutcome {\n status: AddItemStatus\n /** The resulting line quantity after the call (`0` when refused and no line exists). */\n quantity: number\n}\n\nexport interface CartStore {\n items: CartItem[]\n addItem: (item: CartItem) => AddItemOutcome\n removeItem: (productId: string, variantId?: string | null) => void\n updateQuantity: (\n productId: string,\n variantId: string | null | undefined,\n quantity: number,\n ) => void\n clearCart: () => void\n getTotal: () => number\n getItemCount: () => number\n}\n\nfunction isSameItem(a: CartItem, productId: string, variantId?: string | null): boolean {\n return a.productId === productId && (a.variantId ?? null) === (variantId ?? null)\n}\n\n/**\n * REB-829 review finding: neither `addItem` nor `updateQuantity` validated\n * `quantity` — `0`, a negative number, `NaN` (e.g. a stray `parseInt('')`\n * upstream), a non-integer, or `maxStock` itself being `0` (out of stock)\n * all used to leave an invalid line sitting in the cart, silently reaching\n * checkout.\n *\n * Normalizes to a safe POSITIVE INTEGER clamped to `maxStock`. Returns `0`\n * to signal \"not a valid positive quantity\" — callers decide what that\n * means for them: `addItem` ignores the call (never creates/corrupts a\n * line), `updateQuantity` removes the line (same as its pre-existing\n * `quantity <= 0` → remove contract, just now reached by more inputs).\n *\n * `Math.trunc` rounds toward zero (not `Math.floor`, which would round a\n * negative input further negative before the `< 1` check below ever saw it\n * — not a behavioural difference here since any negative result is\n * rejected either way, but `trunc` is the operation that actually means\n * \"drop the fractional part\").\n */\nfunction normalizeQuantity(quantity: number, maxStock: number | null): number {\n if (!Number.isFinite(quantity)) return 0\n const truncated = Math.trunc(quantity)\n if (truncated < 1) return 0\n if (maxStock === null) return truncated\n const maxTruncated = Math.trunc(maxStock)\n if (maxTruncated < 1) return 0\n return Math.min(truncated, maxTruncated)\n}\n\n/**\n * REB-837 cross-entry singleton guard — the mutation that caught it: a\n * single test rendering `useShopOrderStatus` (the `./shop` tsup entry) and\n * asserting on `useCartStore` (the `./cart` entry) saw the order resolve to\n * `paid` but the cart stay non-empty. Root cause: `splitting: false` (R4,\n * `tsup.config.ts`) bundles each entry standalone, so a plain relative\n * import of this file from `./shop` INLINES a SEPARATE copy of this\n * `create(...)` call — a second, disconnected store instance with its own\n * state, not the one `@reblu/site-next/cart` consumers read. `clearCart()`\n * from inside the hook silently cleared the WRONG store.\n *\n * `globalThis` keyed by a `Symbol.for(...)` (same registry entry regardless\n * of which bundle's copy of this module evaluates it first) makes every\n * entry that imports this file — however many times esbuild inlines it —\n * resolve to the SAME store. Verified by mutation: removing this guard\n * (reverting to a bare `export const useCartStore = create(...)`) turns\n * `use-shop-order-status.test.ts`'s cart-clearing assertions red again once\n * the hook is exercised through its OWN entry rather than imported directly\n * within `cart`'s own test file (which never saw the bug, since it only\n * ever touches ONE copy of this module).\n */\nfunction createCartStore() {\n return create<CartStore>()(\n persist(\n (set, get) => ({\n items: [],\n\n addItem: (item) => {\n // REB-837: `set`'s updater can't return a value to the caller, so the\n // outcome is captured in this closure variable and returned after.\n let outcome: AddItemOutcome = { status: 'refused', quantity: 0 }\n\n set((state) => {\n const existing = state.items.find((i) => isSameItem(i, item.productId, item.variantId))\n\n if (existing) {\n // REB-829 review follow-up (a): incoming maxStock is the\n // FRESHEST stock signal available — if it says 0, the product is\n // confirmed out of stock right now, so the existing line is\n // removed outright (same contract as updateQuantity's own\n // \"quantity resolves to <1 → remove\"), not merely left alone.\n if (item.maxStock !== null && Math.trunc(item.maxStock) < 1) {\n outcome = { status: 'refused', quantity: 0 }\n return {\n items: state.items.filter((i) => !isSameItem(i, item.productId, item.variantId)),\n }\n }\n\n const requestedQty = existing.quantity + item.quantity\n const newQty = normalizeQuantity(requestedQty, item.maxStock)\n if (newQty < 1) {\n // Invalid delta (NaN/non-positive quantity) — leave the\n // existing, previously-valid line untouched rather than\n // destroying good data because of one bad call.\n outcome = { status: 'refused', quantity: existing.quantity }\n return {}\n }\n\n // REB-839: nothing was gained when stock caps the line at (or,\n // with fresher stock, below) what it already held — report that\n // as 'refused', never as a partial-success 'clamped'. The line is\n // still reconciled below to the fresher maxStock.\n outcome = {\n status:\n newQty <= existing.quantity\n ? 'refused'\n : newQty < requestedQty\n ? 'clamped'\n : 'added',\n quantity: newQty,\n }\n\n // Refresh maxStock with the incoming value on every successful\n // merge — the stale-maxStock finding: a stored line used to keep\n // its ORIGINAL maxStock forever, so a later updateQuantity call\n // clamped against stock data that could be long out of date.\n return {\n items: state.items.map((i) =>\n isSameItem(i, item.productId, item.variantId)\n ? { ...i, quantity: newQty, maxStock: item.maxStock }\n : i,\n ),\n }\n }\n\n const qty = normalizeQuantity(item.quantity, item.maxStock)\n if (qty < 1) {\n // Invalid quantity, or maxStock 0 (out of stock) — never create\n // a line nobody could actually buy.\n outcome = { status: 'refused', quantity: 0 }\n return {}\n }\n\n outcome = { status: qty < item.quantity ? 'clamped' : 'added', quantity: qty }\n return { items: [...state.items, { ...item, quantity: qty }] }\n })\n\n return outcome\n },\n\n removeItem: (productId, variantId) => {\n set((state) => ({\n items: state.items.filter((i) => !isSameItem(i, productId, variantId)),\n }))\n },\n\n updateQuantity: (productId, variantId, quantity) => {\n const existing = get().items.find((i) => isSameItem(i, productId, variantId))\n if (!existing) return\n\n const newQty = normalizeQuantity(quantity, existing.maxStock)\n if (newQty < 1) {\n get().removeItem(productId, variantId)\n return\n }\n\n set((state) => ({\n items: state.items.map((i) =>\n isSameItem(i, productId, variantId) ? { ...i, quantity: newQty } : i,\n ),\n }))\n },\n\n clearCart: () => set({ items: [] }),\n\n getTotal: () => get().items.reduce((sum, item) => sum + item.unitPrice * item.quantity, 0),\n\n getItemCount: () => get().items.reduce((sum, item) => sum + item.quantity, 0),\n }),\n {\n name: CART_STORAGE_KEY,\n version: CART_STORE_PERSIST_VERSION,\n skipHydration: true,\n },\n ),\n )\n}\n\ntype CartStoreApi = ReturnType<typeof createCartStore>\n\n/**\n * Versioned (REB-837 review fix) with {@link CART_STORE_PERSIST_VERSION} —\n * an incompatible shape change bumps that version, which mints a NEW\n * `Symbol.for(...)` registry key, so a stale old-shape singleton (e.g. kept\n * alive across an HMR reload in dev before a code change takes effect)\n * never satisfies the new one.\n */\nconst CART_STORE_GLOBAL_KEY = Symbol.for(\n `@reblu/site-next/cart-store@v${CART_STORE_PERSIST_VERSION}`,\n)\n\ninterface GlobalWithCartStore {\n [CART_STORE_GLOBAL_KEY]?: CartStoreApi\n}\n\nconst globalForCartStore = globalThis as typeof globalThis & GlobalWithCartStore\n\nexport const useCartStore: CartStoreApi =\n globalForCartStore[CART_STORE_GLOBAL_KEY] ??\n (globalForCartStore[CART_STORE_GLOBAL_KEY] = createCartStore())\n\n/**\n * TEST-ONLY (REB-837 review fix). Clears the `globalThis`-keyed slot so the\n * NEXT access to `useCartStore` — in THIS module instance — creates a fresh\n * store. The singleton is intentionally shared process-wide; most tests\n * should keep resetting STATE via `useCartStore.setState(...)` in\n * `beforeEach`, not the instance itself. Reach for this only to prove\n * something about the singleton mechanism (e.g. the cross-entry test in\n * `tests/cart-store-cross-entry-singleton.test.ts`) — it does not and\n * cannot affect an ALREADY-evaluated copy of this module inlined into a\n * different tsup entry's bundle (each such copy owns its own `const\n * globalForCartStore`/`CART_STORE_GLOBAL_KEY` closed over at that copy's\n * own module-evaluation time, same as any other ES module binding).\n */\nexport function __resetCartStoreForTests(): void {\n delete globalForCartStore[CART_STORE_GLOBAL_KEY]\n}\n","'use client'\n\nimport { useSyncExternalStore } from 'react'\n\nimport { useCartStore, type AddItemOutcome, type CartItem } from './store'\n\nexport interface UseCartResult {\n items: CartItem[]\n /** Sum of every line's `unitPrice * quantity`, in integer cents. */\n total: number\n /** Sum of every line's `quantity`. */\n itemCount: number\n /**\n * Whether `CartProvider`'s `persist.rehydrate()` has finished (REB-837).\n * `false` on the server and on the very first client render — `items`\n * (and therefore `itemCount`) jumps from `0` to whatever was persisted the\n * instant hydration finishes, which is NOT a real \"item added\" event. A\n * consumer driving `CartIcon`'s `bumpOnAdd` MUST gate the bump on this\n * flag (see `CartIcon`'s own guard) or every page load with a non-empty\n * cart bumps the badge once for free.\n */\n hydrated: boolean\n addItem: (item: CartItem) => AddItemOutcome\n removeItem: (productId: string, variantId?: string | null) => void\n updateQuantity: (\n productId: string,\n variantId: string | null | undefined,\n quantity: number,\n ) => void\n clearCart: () => void\n}\n\nfunction subscribeHydration(onStoreChange: () => void): () => void {\n return useCartStore.persist.onFinishHydration(onStoreChange)\n}\n\nfunction getHydratedSnapshot(): boolean {\n return useCartStore.persist.hasHydrated()\n}\n\n/** Server snapshot is always `false` — the server never reads `localStorage`. */\nfunction getServerHydratedSnapshot(): boolean {\n return false\n}\n\n/**\n * `useCartHydrated` — standalone so a SITE that only needs the flag (e.g. to\n * gate its own effects) doesn't have to subscribe to the whole cart via\n * `useCart()`.\n */\nexport function useCartHydrated(): boolean {\n return useSyncExternalStore(subscribeHydration, getHydratedSnapshot, getServerHydratedSnapshot)\n}\n\n/**\n * `useCart` — the ergonomic entry point for a SITE's cart UI: a single\n * selector call that re-renders only on `items` changes, with `total`/\n * `itemCount` derived inline (cheap — a plain `reduce` over a typically-small\n * array) rather than via `useCartStore`'s own `getTotal`/`getItemCount`\n * selectors, which are stable function references and would NOT trigger a\n * re-render on their own. A SITE that wants raw store access (existing\n * per-field selectors, e.g. `useCartStore((s) => s.addItem)`) can still\n * import `useCartStore` directly — this hook doesn't replace it.\n */\nexport function useCart(): UseCartResult {\n const items = useCartStore((s) => s.items)\n const addItem = useCartStore((s) => s.addItem)\n const removeItem = useCartStore((s) => s.removeItem)\n const updateQuantity = useCartStore((s) => s.updateQuantity)\n const clearCart = useCartStore((s) => s.clearCart)\n const hydrated = useCartHydrated()\n\n const total = items.reduce((sum, item) => sum + item.unitPrice * item.quantity, 0)\n const itemCount = items.reduce((sum, item) => sum + item.quantity, 0)\n\n return { items, total, itemCount, hydrated, addItem, removeItem, updateQuantity, clearCart }\n}\n","import type {\n ShopCartValidation,\n ShopCartValidationError,\n ShopValidateCartInput,\n} from '@reblu/site-contracts'\n\nimport { useCartStore, type CartItem } from './store'\n\n/**\n * Cart validation (REB-981). A persisted cart (`localStorage` `shop-cart`)\n * outlives the catalog it was filled from: a product can be deleted,\n * deactivated, sold out or repriced between visits. `validateCart` asks the\n * SITE's validate-cart Route Handler (`createShopValidateCartRoute`) about\n * every line and APPLIES the answer to the store, so the cart page and the\n * checkout never show or submit a line nobody can buy.\n */\n\n/** Calls validate-cart for the given lines. Must reject (or throw) on failure. */\nexport type CartValidator = (input: ShopValidateCartInput) => Promise<ShopCartValidation>\n\nexport interface ValidateCartOptions {\n /**\n * The SITE's validate-cart Route Handler path, used by the default\n * validator. Defaults to `'/api/shop/validate-cart'`.\n */\n endpoint?: string\n /** Replaces the default `fetch`-based validator entirely. */\n validate?: CartValidator\n /**\n * `true` (default) removes lines whose error says `suggestedAction:\n * 'remove'` (`not_found`, `inactive`, `out_of_stock`). `false` leaves them\n * in the cart and only reports them through `lineErrors`.\n */\n removeUnavailable?: boolean\n}\n\n/** A line the validation removed — `name`/`variantName` come from the persisted line. */\nexport interface CartRemovedLine {\n productId: string\n variantId: string | null\n name: string\n variantName?: string\n type: ShopCartValidationError['type']\n message: string\n}\n\n/** A line whose quantity was clamped to the stock still available. */\nexport interface CartQuantityChange {\n productId: string\n variantId: string | null\n name: string\n variantName?: string\n from: number\n to: number\n}\n\n/** A line whose `unitPrice` (integer cents) was refreshed from the live price. */\nexport interface CartPriceChange {\n productId: string\n variantId: string | null\n name: string\n variantName?: string\n from: number\n to: number\n}\n\n/**\n * - `valid` — every line is buyable as it stands; nothing changed.\n * - `adjusted` — the cart was changed (lines removed, quantities clamped or\n * prices refreshed). Show the changes before letting the visitor pay.\n * - `invalid` — problems remain that were not applied (lines flagged with\n * `removeUnavailable: false`, or a cart-wide error).\n * - `empty` — no lines; nothing was sent.\n * - `failed` — the request failed; the cart was left exactly as it was.\n */\nexport type CartValidationStatus = 'valid' | 'adjusted' | 'invalid' | 'empty' | 'failed'\n\nexport interface CartValidationOutcome {\n status: CartValidationStatus\n removed: CartRemovedLine[]\n quantityChanges: CartQuantityChange[]\n priceChanges: CartPriceChange[]\n /** Every line error of the response, keyed by {@link cartLineKey}. */\n lineErrors: Record<string, ShopCartValidationError>\n /** Errors that match no cart line (e.g. `empty_cart`) or were not applied. */\n unresolvedErrors: ShopCartValidationError[]\n /** Set when `status` is `'failed'`. */\n error?: unknown\n}\n\nexport const DEFAULT_VALIDATE_CART_ENDPOINT = '/api/shop/validate-cart'\n\n/** Stable key for a cart line: `productId` + `variantId` (absent and `null` are the same line). */\nexport function cartLineKey(productId: string, variantId?: string | null): string {\n return JSON.stringify([productId, variantId ?? null])\n}\n\nfunction emptyOutcome(status: CartValidationStatus): CartValidationOutcome {\n return {\n status,\n removed: [],\n quantityChanges: [],\n priceChanges: [],\n lineErrors: {},\n unresolvedErrors: [],\n }\n}\n\nfunction isValidation(value: unknown): value is ShopCartValidation {\n if (!value || typeof value !== 'object') return false\n const v = value as Record<string, unknown>\n return typeof v.valid === 'boolean' && Array.isArray(v.errors) && Array.isArray(v.items)\n}\n\nfunction defaultValidator(endpoint: string): CartValidator {\n return async (input) => {\n const res = await fetch(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(input),\n })\n if (!res.ok) {\n throw new Error(`validate-cart failed with HTTP ${res.status}`)\n }\n const json: unknown = await res.json()\n const data = json && typeof json === 'object' ? (json as { data?: unknown }).data : undefined\n if (!isValidation(data)) {\n throw new Error('validate-cart returned an unexpected body')\n }\n return data\n }\n}\n\nfunction waitForHydration(): Promise<void> {\n if (useCartStore.persist.hasHydrated()) return Promise.resolve()\n return new Promise((resolve) => {\n const unsubscribe = useCartStore.persist.onFinishHydration(() => {\n unsubscribe()\n resolve()\n })\n })\n}\n\n/**\n * Pure: applies a validate-cart response to a list of lines. Lines the\n * response does not mention (e.g. added while the request was in flight)\n * are left untouched.\n */\nexport function applyCartValidation(\n items: CartItem[],\n validation: ShopCartValidation,\n { removeUnavailable = true }: Pick<ValidateCartOptions, 'removeUnavailable'> = {},\n): Omit<CartValidationOutcome, 'status' | 'error'> & { items: CartItem[] } {\n const removed: CartRemovedLine[] = []\n const quantityChanges: CartQuantityChange[] = []\n const priceChanges: CartPriceChange[] = []\n const lineErrors: Record<string, ShopCartValidationError> = {}\n const unresolvedErrors: ShopCartValidationError[] = []\n\n const byKey = new Map(items.map((item) => [cartLineKey(item.productId, item.variantId), item]))\n const removeKeys = new Set<string>()\n const newQuantity = new Map<string, number>()\n\n for (const error of validation.errors) {\n const key = cartLineKey(error.productId, error.variantId)\n const line = byKey.get(key)\n if (!line) {\n unresolvedErrors.push(error)\n continue\n }\n lineErrors[key] = error\n if (error.suggestedAction === 'remove' && removeUnavailable) {\n removeKeys.add(key)\n removed.push({\n productId: line.productId,\n variantId: line.variantId ?? null,\n name: line.name,\n ...(line.variantName !== undefined && { variantName: line.variantName }),\n type: error.type,\n message: error.message,\n })\n } else if (error.suggestedAction === 'update_quantity' && typeof error.newQuantity === 'number') {\n newQuantity.set(key, error.newQuantity)\n } else {\n // Flagged but not applied (`removeUnavailable: false`, or an action\n // this version does not know) — the line stays and still blocks.\n unresolvedErrors.push(error)\n }\n }\n\n const live = new Map(\n validation.items.map((item) => [cartLineKey(item.productId, item.variantId), item]),\n )\n\n const next: CartItem[] = []\n for (const line of items) {\n const key = cartLineKey(line.productId, line.variantId)\n if (removeKeys.has(key)) continue\n\n let updated = line\n const liveItem = live.get(key)\n if (liveItem) {\n if (liveItem.unitPrice !== line.unitPrice) {\n priceChanges.push({\n productId: line.productId,\n variantId: line.variantId ?? null,\n name: line.name,\n ...(line.variantName !== undefined && { variantName: line.variantName }),\n from: line.unitPrice,\n to: liveItem.unitPrice,\n })\n updated = { ...updated, unitPrice: liveItem.unitPrice }\n }\n if (liveItem.maxStock !== line.maxStock) {\n updated = { ...updated, maxStock: liveItem.maxStock }\n }\n }\n\n const clampTo = newQuantity.get(key)\n if (clampTo !== undefined) {\n const to = Math.trunc(clampTo)\n if (to < 1) {\n // No stock left at all — treat as unavailable.\n removed.push({\n productId: line.productId,\n variantId: line.variantId ?? null,\n name: line.name,\n ...(line.variantName !== undefined && { variantName: line.variantName }),\n type: 'out_of_stock',\n message: lineErrors[key]?.message ?? '',\n })\n continue\n }\n if (to < line.quantity) {\n quantityChanges.push({\n productId: line.productId,\n variantId: line.variantId ?? null,\n name: line.name,\n ...(line.variantName !== undefined && { variantName: line.variantName }),\n from: line.quantity,\n to,\n })\n updated = { ...updated, quantity: to }\n }\n }\n\n next.push(updated)\n }\n\n return { items: next, removed, quantityChanges, priceChanges, lineErrors, unresolvedErrors }\n}\n\n/**\n * Validates the persisted cart against live product, stock and price data\n * and applies the result to `useCartStore`:\n *\n * 1. removes lines the API says to remove, reporting their persisted names;\n * 2. clamps `insufficient_stock` lines to the quantity still available;\n * 3. refreshes `unitPrice` (and `maxStock`) from the live data.\n *\n * Waits for `CartProvider`'s hydration first, so it never validates the\n * empty pre-hydration cart. Never throws: a failed request resolves to\n * `status: 'failed'` and leaves the cart untouched. Running it again on an\n * already-clean cart is a no-op (`status: 'valid'`).\n */\nexport async function validateCart(options: ValidateCartOptions = {}): Promise<CartValidationOutcome> {\n await waitForHydration()\n\n const items = useCartStore.getState().items\n if (items.length === 0) return emptyOutcome('empty')\n\n const validate = options.validate ?? defaultValidator(options.endpoint ?? DEFAULT_VALIDATE_CART_ENDPOINT)\n\n let validation: ShopCartValidation\n try {\n validation = await validate({\n items: items.map((i) => ({\n productId: i.productId,\n variantId: i.variantId,\n quantity: i.quantity,\n })),\n })\n } catch (error) {\n return { ...emptyOutcome('failed'), error }\n }\n\n // Apply against the CURRENT lines, not the snapshot sent: the visitor may\n // have changed the cart while the request was in flight.\n const applied = applyCartValidation(useCartStore.getState().items, validation, options)\n const { items: nextItems, ...report } = applied\n const changed =\n report.removed.length > 0 || report.quantityChanges.length > 0 || report.priceChanges.length > 0\n const current = useCartStore.getState().items\n // Only write when a line object actually changed (a refreshed `maxStock`\n // alone counts) — an unchanged cart never re-renders its subscribers.\n if (nextItems.length !== current.length || nextItems.some((item, i) => item !== current[i])) {\n useCartStore.setState({ items: nextItems })\n }\n\n const status: CartValidationStatus =\n report.unresolvedErrors.length > 0 ? 'invalid' : changed ? 'adjusted' : 'valid'\n\n return { status, ...report }\n}\n","'use client'\n\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport type { ShopCartValidationError } from '@reblu/site-contracts'\n\nimport { useCartHydrated } from './use-cart'\nimport {\n cartLineKey,\n validateCart,\n type CartValidationOutcome,\n type CartValidationStatus,\n type ValidateCartOptions,\n} from './validate'\n\nexport interface UseCartValidationOptions extends ValidateCartOptions {\n /** Validate once automatically when the cart has hydrated. Defaults to `true`. */\n auto?: boolean\n}\n\nexport interface UseCartValidationResult extends Omit<CartValidationOutcome, 'status'> {\n /** `'idle'` before the first run, `'validating'` while a request is in flight. */\n status: CartValidationStatus | 'idle' | 'validating'\n /** The error the last run reported for this line, if any. */\n getLineError: (productId: string, variantId?: string | null) => ShopCartValidationError | undefined\n /**\n * Runs the validation now (e.g. right before submitting the checkout) and\n * resolves to its outcome. Concurrent calls share the in-flight request.\n */\n revalidate: () => Promise<CartValidationOutcome>\n}\n\nconst IDLE: Omit<CartValidationOutcome, 'status'> = {\n removed: [],\n quantityChanges: [],\n priceChanges: [],\n lineErrors: {},\n unresolvedErrors: [],\n}\n\n/**\n * `useCartValidation` (REB-981) — runs {@link validateCart} once when the\n * cart has hydrated (cart page mount) and exposes the last outcome, so the\n * page can show what was removed or adjusted and mark the offending lines.\n * Call `revalidate()` before checkout. Later cart edits never re-trigger the\n * automatic run, so it cannot loop.\n */\nexport function useCartValidation(options: UseCartValidationOptions = {}): UseCartValidationResult {\n const { auto = true } = options\n const hydrated = useCartHydrated()\n const [status, setStatus] = useState<UseCartValidationResult['status']>('idle')\n const [report, setReport] = useState<Omit<CartValidationOutcome, 'status'>>(IDLE)\n\n // Latest options without re-creating `revalidate` (synced after render,\n // never written during it).\n const optionsRef = useRef(options)\n useEffect(() => {\n optionsRef.current = options\n })\n const inFlight = useRef<Promise<CartValidationOutcome> | null>(null)\n const autoRan = useRef(false)\n\n const revalidate = useCallback((): Promise<CartValidationOutcome> => {\n if (inFlight.current) return inFlight.current\n setStatus('validating')\n const run = validateCart(optionsRef.current).then((outcome) => {\n inFlight.current = null\n const { status: nextStatus, ...rest } = outcome\n setReport(rest)\n setStatus(nextStatus)\n return outcome\n })\n inFlight.current = run\n return run\n }, [])\n\n useEffect(() => {\n if (!auto || !hydrated || autoRan.current) return\n autoRan.current = true\n void revalidate()\n }, [auto, hydrated, revalidate])\n\n const getLineError = useCallback(\n (productId: string, variantId?: string | null) =>\n report.lineErrors[cartLineKey(productId, variantId)],\n [report],\n )\n\n return { status, ...report, getLineError, revalidate }\n}\n"],"mappings":";;;AAEA,SAAS,iBAAiB;;;ACF1B,SAAS,cAAc;AACvB,SAAS,eAAe;AAgBjB,IAAM,mBAAmB;AAWzB,IAAM,6BAA6B;AAiD1C,SAAS,WAAW,GAAa,WAAmB,WAAoC;AACtF,SAAO,EAAE,cAAc,cAAc,EAAE,aAAa,WAAW,aAAa;AAC9E;AAqBA,SAAS,kBAAkB,UAAkB,UAAiC;AAC5E,MAAI,CAAC,OAAO,SAAS,QAAQ,EAAG,QAAO;AACvC,QAAM,YAAY,KAAK,MAAM,QAAQ;AACrC,MAAI,YAAY,EAAG,QAAO;AAC1B,MAAI,aAAa,KAAM,QAAO;AAC9B,QAAM,eAAe,KAAK,MAAM,QAAQ;AACxC,MAAI,eAAe,EAAG,QAAO;AAC7B,SAAO,KAAK,IAAI,WAAW,YAAY;AACzC;AAuBA,SAAS,kBAAkB;AACzB,SAAO,OAAkB;AAAA,IACvB;AAAA,MACE,CAAC,KAAK,SAAS;AAAA,QACb,OAAO,CAAC;AAAA,QAER,SAAS,CAAC,SAAS;AAGjB,cAAI,UAA0B,EAAE,QAAQ,WAAW,UAAU,EAAE;AAE/D,cAAI,CAAC,UAAU;AACb,kBAAM,W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C,WAAU,MAAM;AACd,eAAW,UAAU;AAAA,EACvB,CAAC;AACD,QAAM,WAAW,OAA8C,IAAI;AACnE,QAAM,UAAU,OAAO,KAAK;AAE5B,QAAM,aAAa,YAAY,MAAsC;AACnE,QAAI,SAAS,QAAS,QAAO,SAAS;AACtC,cAAU,YAAY;AACtB,UAAM,MAAM,aAAa,WAAW,OAAO,EAAE,KAAK,CAAC,YAAY;AAC7D,eAAS,UAAU;AACnB,YAAM,EAAE,QAAQ,YAAY,GAAG,KAAK,IAAI;AACxC,gBAAU,IAAI;AACd,gBAAU,UAAU;AACpB,aAAO;AAAA,IACT,CAAC;AACD,aAAS,UAAU;AACnB,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AAEL,EAAAA,WAAU,MAAM;AACd,QAAI,CAAC,QAAQ,CAAC,YAAY,QAAQ,QAAS;AAC3C,YAAQ,UAAU;AAClB,SAAK,WAAW;AAAA,EAClB,GAAG,CAAC,MAAM,UAAU,UAAU,CAAC;AAE/B,QAAM,eAAe;AAAA,IACnB,CAAC,WAAmB,cAClB,OAAO,WAAW,YAAY,WAAW,SAAS,CAAC;AAAA,IACrD,CAAC,MAAM;AAAA,EACT;AAEA,SAAO,EAAE,QAAQ,GAAG,QAAQ,cAAc,WAAW;AACvD;","names":["useEffect","useEffect"]}
package/dist/consent.js CHANGED
@@ -121,7 +121,7 @@ function ConsentGate({ category, children }) {
121
121
  }
122
122
 
123
123
  // src/analytics.tsx
124
- import Script from "next/script";
124
+ import Script from "next/script.js";
125
125
 
126
126
  // src/json-ld.tsx
127
127
  import { jsx as jsx3 } from "react/jsx-runtime";