@wix/himalaya-cli 0.1647.0 → 0.1649.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/builder.d.ts +3 -1
  2. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/schema.d.ts +4 -0
  3. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/validator.d.ts +6 -0
  4. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/wix-sdk/media/src/rendition.d.ts +6 -0
  5. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/core.mjs +1 -0
  6. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/screens.mjs +4 -0
  7. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/sdui.mjs +1 -0
  8. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-events.mjs +4 -0
  9. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-media.mjs +22 -4
  10. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-rich-content.mjs +4 -0
  11. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-stores-collections.mjs +4 -0
  12. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-stores.mjs +4 -0
  13. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-video.mjs +4 -0
  14. package/dist/browser-plane/assets.json +5 -5
  15. package/dist/browser-plane/preview-deferred/{155f61519885c85d61a39fa595197071a3ca07680da56055ccb1dcff2e709cd1.bin → 4ef4d326496b4d7809746936207067b4c921f5db9878ecc7030aa3a9e4d2aaeb.bin} +1 -1
  16. package/dist/browser-plane/sw.js +5 -5
  17. package/dist/cli.mjs +4098 -3351
  18. package/dist/preview-assets.generated.bin +0 -0
  19. package/guides/component-reference.json +1 -1
  20. package/guides/component-reference.md +2 -0
  21. package/guides/designing-himi-screens.md +4 -0
  22. package/guides/himi-skill.md +6 -0
  23. package/guides/image-preview.md +92 -0
  24. package/guides/index.json +7 -0
  25. package/guides/release-notes.md +6 -0
  26. package/guides/sdk-reference.json +9 -2
  27. package/package.json +2 -2
  28. package/template-icons/wholesale-store.png +0 -0
  29. package/templates/beauty-salon-owner/dev/index.ts +7 -0
  30. package/templates/community-club-owner/dev/index.ts +7 -0
  31. package/templates/events-meetups-owner/dev/index.ts +7 -0
  32. package/templates/gym-fitness-owner/dev/index.ts +7 -0
  33. package/templates/nonprofit-cause-owner/dev/index.ts +7 -0
  34. package/templates/owner-lite/dev/index.ts +7 -0
  35. package/templates/podcast-creator-owner/dev/index.ts +7 -0
  36. package/templates/portfolio-creative-owner/dev/index.ts +7 -0
  37. package/templates/restaurant-owner/dev/index.ts +7 -0
  38. package/templates/retail-store-owner/dev/index.ts +7 -0
  39. package/templates/wholesale-store/README.md +53 -0
  40. package/templates/wholesale-store/config.ts +247 -0
  41. package/templates/wholesale-store/dev/index.ts +12194 -0
  42. package/templates/wholesale-store/himalaya.content.json +43 -0
  43. package/templates/wholesale-store/himalaya.template.json +14 -0
  44. package/templates/wholesale-store/icon.png +0 -0
  45. package/templates/wholesale-store/platforms.json +1 -0
  46. package/templates/wholesale-store/tier5-src/_shared/app-locale.ts +61 -0
  47. package/templates/wholesale-store/tier5-src/_shared/branded-lite-hosted.ts +279 -0
  48. package/templates/wholesale-store/tier5-src/_shared/business-chat-copy.ts +40 -0
  49. package/templates/wholesale-store/tier5-src/_shared/business-chat-history.ts +51 -0
  50. package/templates/wholesale-store/tier5-src/_shared/business-chat-message-model.ts +177 -0
  51. package/templates/wholesale-store/tier5-src/_shared/business-chat-model.ts +56 -0
  52. package/templates/wholesale-store/tier5-src/_shared/business-chat-presenter.ts +576 -0
  53. package/templates/wholesale-store/tier5-src/_shared/business-chat-transport.ts +148 -0
  54. package/templates/wholesale-store/tier5-src/_shared/collection-contract.ts +228 -0
  55. package/templates/wholesale-store/tier5-src/_shared/collection-query-legacy.ts +194 -0
  56. package/templates/wholesale-store/tier5-src/_shared/collection-query.ts +252 -0
  57. package/templates/wholesale-store/tier5-src/_shared/collection-service.ts +423 -0
  58. package/templates/wholesale-store/tier5-src/_shared/detail-presence.ts +51 -0
  59. package/templates/wholesale-store/tier5-src/_shared/empty-flags.ts +33 -0
  60. package/templates/wholesale-store/tier5-src/_shared/engine-intl.ts +508 -0
  61. package/templates/wholesale-store/tier5-src/_shared/exclusive-writes.ts +66 -0
  62. package/templates/wholesale-store/tier5-src/_shared/himi-account.ts +164 -0
  63. package/templates/wholesale-store/tier5-src/_shared/himi-copy.ts +89 -0
  64. package/templates/wholesale-store/tier5-src/_shared/himi-store-categories.ts +108 -0
  65. package/templates/wholesale-store/tier5-src/_shared/himi-store-collection.ts +22 -0
  66. package/templates/wholesale-store/tier5-src/_shared/himi-store-saved.ts +57 -0
  67. package/templates/wholesale-store/tier5-src/_shared/himi-store.ts +7 -0
  68. package/templates/wholesale-store/tier5-src/_shared/himi-text.ts +24 -0
  69. package/templates/wholesale-store/tier5-src/_shared/hosted-checkout.ts +70 -0
  70. package/templates/wholesale-store/tier5-src/_shared/iap-presentation.ts +207 -0
  71. package/templates/wholesale-store/tier5-src/_shared/iap-worker.ts +125 -0
  72. package/templates/wholesale-store/tier5-src/_shared/inbox-rooms.ts +68 -0
  73. package/templates/wholesale-store/tier5-src/_shared/live-session.ts +172 -0
  74. package/templates/wholesale-store/tier5-src/_shared/local-preferences.ts +38 -0
  75. package/templates/wholesale-store/tier5-src/_shared/member-access.ts +52 -0
  76. package/templates/wholesale-store/tier5-src/_shared/member-account-routes.ts +52 -0
  77. package/templates/wholesale-store/tier5-src/_shared/member-orders.ts +8 -0
  78. package/templates/wholesale-store/tier5-src/_shared/member-screen.ts +99 -0
  79. package/templates/wholesale-store/tier5-src/_shared/online-actions.ts +76 -0
  80. package/templates/wholesale-store/tier5-src/_shared/owner-editor-value.ts +164 -0
  81. package/templates/wholesale-store/tier5-src/_shared/owner-load-error.ts +348 -0
  82. package/templates/wholesale-store/tier5-src/_shared/payment-setup.ts +6 -0
  83. package/templates/wholesale-store/tier5-src/_shared/read-service.ts +255 -0
  84. package/templates/wholesale-store/tier5-src/_shared/restaurant-ordering.ts +201 -0
  85. package/templates/wholesale-store/tier5-src/_shared/rich-body.ts +78 -0
  86. package/templates/wholesale-store/tier5-src/_shared/rich-content-link.ts +34 -0
  87. package/templates/wholesale-store/tier5-src/_shared/sign-in-sheet.ts +18 -0
  88. package/templates/wholesale-store/tier5-src/_shared/store-order-presentation.ts +56 -0
  89. package/templates/wholesale-store/tier5-src/_shared/store-product-info.ts +50 -0
  90. package/templates/wholesale-store/tier5-src/business-chat/index.ts +724 -0
  91. package/templates/wholesale-store/tier5-src/himi-branded-lite-cart/index.ts +602 -0
  92. package/templates/wholesale-store/tier5-src/himi-branded-lite-order/index.ts +472 -0
  93. package/templates/wholesale-store/tier5-src/himi-branded-lite-orders/index.ts +327 -0
  94. package/templates/wholesale-store/tier5-src/himi-store-account/index.ts +998 -0
  95. package/templates/wholesale-store/tier5-src/himi-store-product/index.ts +889 -0
  96. package/templates/wholesale-store/tier5-src/himi-store-saved/index.ts +68 -0
  97. package/templates/wholesale-store/tier5-src/himi-store-shop/index.ts +150 -0
  98. package/templates/wholesale-store/tier5-src/himi-wholesale-home/index.ts +507 -0
  99. package/templates/wholesale-store/tier5-src/wix-spaces-collection-detail/index.ts +195 -0
  100. package/templates/wholesale-store/tokens.json +340 -0
  101. package/templates/yoga-studio-owner/dev/index.ts +7 -0
@@ -0,0 +1,602 @@
1
+ import { paymentSetupMessage } from "../_shared/payment-setup.js";
2
+ import { withOnlineWrites } from "../_shared/online-actions.js";
3
+ import { defineService as registerState } from "@himalaya/state";
4
+ import { getStoreProduct } from "../_shared/himi-store.js";
5
+ import { RESTAURANTS_ORDERS_APP_ID } from "../_shared/restaurant-ordering.js";
6
+ import { iapPriceCopy } from "../_shared/iap-worker.js";
7
+ import { withIapPresentation } from "../_shared/iap-presentation.js";
8
+ import { type IapCommerce, classifyCart } from "@himalaya/iap-checkout";
9
+ import { addCouponToCurrentCart, calculateCurrentCart, createCheckoutFromCurrentCart, getCurrentCart, removeCouponFromCurrentCart, removeLineItemsFromCurrentCart, updateLineItemsQuantity, type WixCartDetail, type WixCartLineItemDetail } from "@himalaya/wix-ecom";
10
+ import { createRedirectSession } from "@himalaya/wix-redirects";
11
+ import { isPaymentSetupFailure, payCashierOrder } from "@himalaya/checkout";
12
+ import { hostedCheckoutOpener, isHostedWorker } from "../_shared/hosted-checkout.js";
13
+ import { formatCurrency } from "../_shared/engine-intl.js";
14
+
15
+ /** Wix Stores appDefId — the vertical that owns a cart/ecom order, and therefore the
16
+ * `appId` its cashier order is paid under. (Same constant Wix's own tooling uses.) */
17
+ const WIX_STORES_CATALOG_ID = "215238eb-22a5-4c36-9e7b-e7c08025e04e";
18
+ const WIX_STORES_APP_ID = "1380b703-ce81-ff05-f115-39571d94dfcd";
19
+
20
+ import { copyParam, copyTemplate, stashCopy } from "../_shared/himi-copy.js";
21
+ import { getAll, upsert, remove as dbRemove, type DbEntity } from "@himalaya/local-db";
22
+ import { isOfflineFailure, writeMayHaveLanded } from "../_shared/owner-load-error.js";
23
+ import { isProductSaved, readSavedProducts, toggleSavedProduct } from "../_shared/himi-store-saved.js";
24
+
25
+ // Offline-first (data-offline): the cart is READ-THROUGH — paint the last-synced line
26
+ // items from the on-device `cart` entity first (instant, works offline), then
27
+ // revalidate from Wix and refresh the cache.
28
+ // `remove` drops the line from the cache only AFTER Wix confirms it; a failed removal
29
+ // keeps the line on screen and says nothing was removed (no host replays a
30
+ // queued write, so the old "removed offline" promise was a removal that never happened).
31
+ // The checkout redirect path is unchanged. Every local-db call is wrapped so a build
32
+ // without the `local_database` grant behaves exactly as before (online-only).
33
+ const ENTITY = "cart";
34
+ function cachedUnitPrice(total: string, quantity: number): string {
35
+ if (quantity <= 1) return total;
36
+ const match = /\d(?:[\d.,]|[ \u00a0\u202f](?=\d))*/u.exec(total);
37
+ if (!match) return total;
38
+ const raw = match[0];
39
+ const compact = raw.replace(/[ \u00a0\u202f]/g, "");
40
+ const last = Math.max(compact.lastIndexOf("."), compact.lastIndexOf(","));
41
+ const digits = last >= 0 && compact.length - last - 1 <= 2 ? compact.length - last - 1 : 0;
42
+ const decimal = digits ? compact[last] : ".";
43
+ const numeric = digits ? `${compact.slice(0, last).replace(/[,.]/g, "")}.${compact.slice(last + 1)}` : compact.replace(/[,.]/g, "");
44
+ const amount = Number(numeric);
45
+ if (!Number.isFinite(amount)) return total;
46
+ const [whole, fraction] = (amount / quantity).toFixed(digits).split(".");
47
+ const spaceGrouping = raw.match(/[ \u00a0\u202f](?=\d)/u)?.[0];
48
+ const grouped = spaceGrouping ? whole.replace(/\B(?=(\d{3})+(?!\d))/g, spaceGrouping) : whole;
49
+ return total.replace(raw, `${grouped}${digits ? decimal + fraction : ""}`);
50
+ }
51
+ async function readCachedItems(): Promise<Row[]> {
52
+ try {
53
+ return ((await getAll(ENTITY)) as unknown as Row[]).map(item => {
54
+ const quantity = Math.max(1, Math.floor(Number(item.quantity) || 1));
55
+ let saved = false;
56
+ try { saved = isProductSaved(item.catalogReference?.catalogItemId ?? item.productId ?? ""); } catch { /* keep the cached line usable */ }
57
+ const unitPrice = item.unitPrice || cachedUnitPrice(item.total || item.commerceTotal || "", quantity);
58
+ return { ...item, catalogItemId: item.catalogReference?.catalogItemId ?? item.productId ?? "", quantity, quantityLabel: String(quantity), atMinQuantity: quantity <= 1, unitPrice,
59
+ wasPrice: item.wasPrice ?? "", swatches: item.swatches ?? [], option1: item.option1 ?? "", option2: item.option2 ?? "", option3: item.option3 ?? "",
60
+ noOption1: !item.option1, noOption2: !item.option2, noOption3: !item.option3,
61
+ stockMessage: item.stockMessage ?? "", noStockMessage: !item.stockMessage,
62
+ inStockMessage: item.inStockMessage ?? "", noInStockMessage: !item.inStockMessage, saved, notSaved: !saved };
63
+ });
64
+ } catch { return []; }
65
+ }
66
+ /** Mirror the cart Wix returned: upsert its lines and drop any cached line it no longer has
67
+ * (one removed elsewhere, or a removal whose answer was lost), so the offline paint never
68
+ * shows a line that is gone. */
69
+ async function writeCachedItems(rows: Row[]): Promise<void> {
70
+ try {
71
+ const keep = new Set(rows.map((r) => r.id));
72
+ for (const old of (await getAll(ENTITY)) as unknown as Row[]) if (!keep.has(old.id)) await dbRemove(ENTITY, old.id);
73
+ for (const r of rows) await upsert(ENTITY, r as unknown as DbEntity);
74
+ } catch { /* capability not granted → online-only */ }
75
+ }
76
+
77
+ async function cacheDrop(id: string): Promise<void> { try { await dbRemove(ENTITY, id); } catch { /* capability not granted */ } }
78
+
79
+ interface Row {
80
+ catalogReference?: { appId: string; catalogItemId: string; options?: Record<string, unknown> };
81
+ productId?: string;
82
+ catalogItemId?: string;
83
+ id: string;
84
+ name: string;
85
+ title: string;
86
+ subtitle: string;
87
+ /** Numeric line quantity + its display string (the −/+ qty controls). */
88
+ quantity: number;
89
+ quantityLabel: string;
90
+ /** The "−" control at qty 1 removes the line, so it never dead-ends. */
91
+ atMinQuantity: boolean;
92
+ total: string;
93
+ unitPrice: string;
94
+ wasPrice?: string;
95
+ swatches?: string[];
96
+ commerceTotal: string;
97
+ image: string;
98
+ initial: string;
99
+ hasImage: boolean;
100
+ noImage: boolean;
101
+ option1: string; option2: string; option3: string;
102
+ noOption1: boolean; noOption2: boolean; noOption3: boolean;
103
+ stockMessage: string; noStockMessage: boolean;
104
+ inStockMessage: string; noInStockMessage: boolean;
105
+ saved: boolean;
106
+ notSaved: boolean;
107
+ }
108
+ interface State {
109
+ status: "loading" | "ready" | "error";
110
+ errorKind: "offline" | "server" | "";
111
+ items: Row[];
112
+ subtotal: string;
113
+ commerceSubtotal?: string;
114
+ emptyText: string;
115
+ checkoutHint: string;
116
+ itemCount: number;
117
+ promoCode: string;
118
+ promoEditRevision: number;
119
+ appliedCode: string;
120
+ appliedLabel: string;
121
+ couponId: string;
122
+ promoError: string;
123
+ promoBusy: boolean;
124
+ noPromoError: boolean;
125
+ hasCoupon: boolean;
126
+ discount: string;
127
+ noDiscount: boolean;
128
+ noCheckoutHint: boolean;
129
+ showPaidToast: boolean;
130
+ noPaidToast: boolean;
131
+ noCoupon: boolean;
132
+ subtotalLabel: string;
133
+ isLoading: boolean;
134
+ notLoading: boolean;
135
+ /** Standard error quad (the himi-store retryBlock contract): the descriptor
136
+ * gates its error card on notErrored and its content on hideContent, so a
137
+ * failed load shows the retry card instead of a blank list + blank subtotal. */
138
+ isErrored: boolean;
139
+ notErrored: boolean;
140
+ noOfflineError: boolean;
141
+ noServerError: boolean;
142
+ hideContent: boolean;
143
+ noEmpty: boolean;
144
+ noItems: boolean;
145
+ }
146
+
147
+ function itemId(arg: unknown): string {
148
+ if (typeof arg === "string") return arg;
149
+ if (!arg || typeof arg !== "object") return "";
150
+ const payload = arg as {
151
+ id?: string;
152
+ item?: { id?: string };
153
+ args?: { id?: string };
154
+ params?: { id?: string };
155
+ };
156
+ return payload.id ?? payload.item?.id ?? payload.args?.id ?? payload.params?.id ?? "";
157
+ }
158
+
159
+ function mediaUrl(value: unknown): string {
160
+ if (!value || typeof value !== "object") return "";
161
+ const item = value as {
162
+ image?: { url?: string } | string;
163
+ media?: {
164
+ mainMedia?: { image?: { url?: string }; thumbnail?: { url?: string }; url?: string };
165
+ items?: Array<{ image?: { url?: string }; thumbnail?: { url?: string }; url?: string }>;
166
+ };
167
+ product?: {
168
+ image?: { url?: string } | string;
169
+ media?: {
170
+ mainMedia?: { image?: { url?: string }; thumbnail?: { url?: string }; url?: string };
171
+ items?: Array<{ image?: { url?: string }; thumbnail?: { url?: string }; url?: string }>;
172
+ };
173
+ };
174
+ };
175
+ const directImage = typeof item.image === "string" ? item.image : item.image?.url;
176
+ const productImage = typeof item.product?.image === "string" ? item.product.image : item.product?.image?.url;
177
+ return directImage
178
+ ?? item.media?.mainMedia?.image?.url
179
+ ?? item.media?.mainMedia?.thumbnail?.url
180
+ ?? item.media?.mainMedia?.url
181
+ ?? item.media?.items?.[0]?.image?.url
182
+ ?? item.media?.items?.[0]?.thumbnail?.url
183
+ ?? item.media?.items?.[0]?.url
184
+ ?? productImage
185
+ ?? item.product?.media?.mainMedia?.image?.url
186
+ ?? item.product?.media?.mainMedia?.thumbnail?.url
187
+ ?? item.product?.media?.mainMedia?.url
188
+ ?? item.product?.media?.items?.[0]?.image?.url
189
+ ?? item.product?.media?.items?.[0]?.thumbnail?.url
190
+ ?? item.product?.media?.items?.[0]?.url
191
+ ?? "";
192
+ }
193
+
194
+ function row(item: WixCartLineItemDetail, index: number): Row {
195
+ const raw = item as WixCartLineItemDetail & Record<string, unknown>;
196
+ const quantity = item.quantity ?? 1;
197
+ const name = item.productName?.original || copyParam("cart.itemFallbackName", "Cart item");
198
+ const image = mediaUrl(item);
199
+ const lines = Array.isArray(raw.descriptionLines) ? raw.descriptionLines as Array<{ name?: { original?: string }; plainText?: { original?: string }; colorInfo?: { original?: string; code?: string } }> : [];
200
+ const opts = lines.slice(0, 3).map(line => {
201
+ const label = line.name?.original?.trim() ?? "";
202
+ const name = label && label === label.toUpperCase() ? label.charAt(0) + label.slice(1).toLowerCase() : label;
203
+ const value = line.plainText?.original || line.colorInfo?.original || "";
204
+ return [name, value].filter(Boolean).join(": ");
205
+ });
206
+ const inventory = raw.inventory as { quantity?: number } | undefined;
207
+ const availabilityData = raw.availability as { status?: string; quantityAvailable?: number } | undefined;
208
+ const stockCount = Number(availabilityData?.quantityAvailable ?? raw.inventoryQuantity ?? inventory?.quantity);
209
+ const availability = String(availabilityData?.status ?? raw.availabilityStatus ?? "").toUpperCase();
210
+ const stockMessage = availability === "NOT_AVAILABLE" || availability === "NOT_FOUND" || availability.includes("OUT")
211
+ ? copyParam("cart.outOfStock", "Out of stock")
212
+ : availability === "PARTIALLY_AVAILABLE" && Number.isFinite(stockCount) && stockCount > 0
213
+ ? copyTemplate("cart.onlyLeft", "Only {count} left", { count: stockCount }) : "";
214
+ const inStock = !stockMessage && (availability === "AVAILABLE" || availability === "IN_STOCK" || availability === "PARTIALLY_AVAILABLE");
215
+ const total = (raw.lineItemPrice as { formattedAmount?: string } | undefined)?.formattedAmount
216
+ ?? (raw.totalPriceAfterTax as { formattedAmount?: string } | undefined)?.formattedAmount
217
+ ?? (raw.totalPriceBeforeTax as { formattedAmount?: string } | undefined)?.formattedAmount
218
+ ?? item.price?.formattedAmount ?? "";
219
+ const unitPrice = item.price?.formattedAmount ?? "";
220
+ const fullPrice = (raw.fullPrice as { formattedAmount?: string } | undefined)?.formattedAmount ?? "";
221
+ const swatches = lines.map(line => line.colorInfo?.code ?? "").filter(code => /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(code)).slice(0, 5);
222
+ const saved = (() => { try { return isProductSaved(String((item as WixCartLineItemDetail & { catalogReference?: { catalogItemId?: string } }).catalogReference?.catalogItemId ?? "")); } catch { return false; } })();
223
+ return {
224
+ catalogReference: (item as WixCartLineItemDetail & { catalogReference?: Row["catalogReference"] }).catalogReference,
225
+ catalogItemId: (item as WixCartLineItemDetail & { catalogReference?: Row["catalogReference"] }).catalogReference?.catalogItemId ?? "",
226
+ id: item.id || `line-${index}`,
227
+ name,
228
+ title: name,
229
+ subtitle: copyTemplate("cart.quantityLine", "Qty {quantity}", { quantity }),
230
+ quantity,
231
+ quantityLabel: `${quantity}`,
232
+ atMinQuantity: quantity <= 1,
233
+ total,
234
+ unitPrice,
235
+ wasPrice: fullPrice && fullPrice !== unitPrice ? fullPrice : "",
236
+ swatches,
237
+ commerceTotal: total,
238
+ image,
239
+ initial: (name.trim()[0] || "C").toUpperCase(),
240
+ hasImage: Boolean(image),
241
+ noImage: !image,
242
+ option1: opts[0] ?? "", option2: opts[1] ?? "", option3: opts[2] ?? "",
243
+ noOption1: !opts[0], noOption2: !opts[1], noOption3: !opts[2],
244
+ stockMessage, noStockMessage: !stockMessage,
245
+ inStockMessage: inStock ? copyParam("cart.inStock", "In Stock") : "",
246
+ noInStockMessage: !inStock,
247
+ saved,
248
+ notSaved: !saved,
249
+ };
250
+ }
251
+
252
+ /** POST /ecom/v1/carts/{cartId}/update-line-items-quantity via @himalaya/wix-ecom. */
253
+ function updateLineItemQuantity(cartId: string, lineItemId: string, quantity: number): Promise<{ cart?: WixCartDetail }> {
254
+ return updateLineItemsQuantity(cartId, [{ id: lineItemId, quantity: Math.max(1, quantity) }]);
255
+ }
256
+
257
+ function derive(state: State): State {
258
+ let savedIds: Set<string> | null = null;
259
+ try { savedIds = new Set(readSavedProducts().map(row => row.id)); }
260
+ catch { /* saved storage unavailable: retain the saved flags already shown on each row */ }
261
+ const items = savedIds ? state.items.map(item => {
262
+ const productId = item.catalogReference?.catalogItemId ?? item.productId;
263
+ if (!productId) return item;
264
+ const saved = savedIds.has(productId);
265
+ return { ...item, saved, notSaved: !saved };
266
+ }) : state.items;
267
+ const itemCount = items.reduce((n, item) => n + item.quantity, 0);
268
+ return {
269
+ ...state,
270
+ items,
271
+ promoBusy: promoInFlight && state.promoBusy,
272
+ isLoading: state.status === "loading",
273
+ notLoading: state.status !== "loading",
274
+ isErrored: state.status === "error",
275
+ notErrored: state.status !== "error",
276
+ noOfflineError: state.status !== "error" || state.errorKind !== "offline",
277
+ noServerError: state.status !== "error" || state.errorKind !== "server",
278
+ // Exactly one of {content, error card, empty card} renders: content only on
279
+ // "ready" (an errored cart must not paint a blank subtotal), the error card
280
+ // on "error", the empty card on ready + no items.
281
+ hideContent: state.status !== "ready",
282
+ noEmpty: state.status !== "ready" || items.length > 0,
283
+ noItems: items.length === 0,
284
+ itemCount,
285
+ hasCoupon: Boolean(state.appliedCode),
286
+ appliedLabel: state.appliedCode ? copyTemplate("cart.promoApplied", "Promo code {code}", { code: state.appliedCode }) : "",
287
+ noPromoError: !state.promoError,
288
+ noDiscount: !state.discount,
289
+ noCheckoutHint: !state.checkoutHint || state.showPaidToast,
290
+ noPaidToast: !state.showPaidToast,
291
+ noCoupon: !state.appliedCode,
292
+ subtotalLabel: copyTemplate("cart.subtotalCount", "Subtotal ({count})", { count: itemCount }),
293
+ };
294
+ }
295
+
296
+ /** Remove one line (the trash button, and "−" at quantity 1). The cache drops it only once
297
+ * Wix confirms; a failure keeps it on screen and says why. */
298
+ /** Remove one line (the trash button, and "−" at quantity 1). The cache drops it only once
299
+ * Wix confirms; a failure keeps it on screen and says why. */
300
+ async function removeLine(state: State, id: string): Promise<State> {
301
+ try {
302
+ await removeLineItemsFromCurrentCart([id]);
303
+ } catch (e) {
304
+ // The line stays visible (and cached) until a read says otherwise.
305
+ if (isOfflineFailure(e)) {
306
+ return derive({ ...state, checkoutHint: copyParam("cart.removeOfflineFailedMessage", "You’re offline — nothing was removed. Try again when you reconnect.") });
307
+ }
308
+ // It may have landed (mid-request drop, after-send envelope, gateway 5xx): say so,
309
+ // rather than "could not remove".
310
+ if (writeMayHaveLanded(e)) {
311
+ return derive({ ...state, checkoutHint: copyParam("cart.removeUnconfirmedMessage", "The connection dropped, so this item may already be removed. Refresh to check.") });
312
+ }
313
+ return derive({ ...state, checkoutHint: copyParam("cart.removeFailedMessage", "Could not remove this item.") });
314
+ }
315
+ // Wix confirmed it: only now does the line leave the cache, and it stays gone even
316
+ // if the re-fetch below fails.
317
+ await cacheDrop(id);
318
+ const removed = copyParam("cart.itemRemovedMessage", "Item removed.");
319
+ try {
320
+ return await refresh(state, removed);
321
+ } catch {
322
+ // The totals Wix last sent still count the removed line, and the new ones did not
323
+ // arrive: show none rather than a wrong one.
324
+ const items = state.items.filter((it) => it.id !== id);
325
+ return derive({ ...state, status: "ready", items, subtotal: "", commerceSubtotal: "", emptyText: items.length ? "" : copyParam("cart.emptyText", "Your cart is empty."), checkoutHint: removed });
326
+ }
327
+ }
328
+
329
+ async function refresh(state: State, checkoutHint = "", updatedCart?: WixCartDetail, calculatedCart?: unknown): Promise<State> {
330
+ const cart = updatedCart ?? await getCurrentCart();
331
+ const items = (cart.lineItems ?? []).map(row);
332
+ await writeCachedItems(items);
333
+ const rawCart = cart as unknown as Record<string, unknown>;
334
+ const summary = (rawCart.priceSummary ?? rawCart.totals ?? {}) as Record<string, unknown>;
335
+ const discountRaw = (summary.discount ?? summary.discountAmount) as { formattedAmount?: string } | string | undefined;
336
+ const applied = couponDetails(cart);
337
+ let discount = formattedDiscount(typeof discountRaw === "string" ? discountRaw : discountRaw?.formattedAmount ?? "");
338
+ if (applied.code && !discount) {
339
+ const calculated = calculatedCart ?? await calculateCurrentCart().catch(() => null);
340
+ discount = calculatedDiscount(calculated, String(rawCart.currency ?? rawCart.paymentCurrency ?? "")) || (state.appliedCode === applied.code ? state.discount : "");
341
+ }
342
+ return derive({
343
+ ...state,
344
+ status: "ready",
345
+ items,
346
+ subtotal: cart.subtotal?.formattedAmount ?? "",
347
+ commerceSubtotal: cart.subtotal?.formattedAmount ?? "",
348
+ discount,
349
+ appliedCode: applied.code,
350
+ couponId: applied.id,
351
+ emptyText: items.length ? "" : copyParam("cart.emptyText", "Your cart is empty."),
352
+ ...(items.length ? {} : { promoCode: "", appliedCode: "", couponId: "", discount: "", promoError: "" }),
353
+ checkoutHint,
354
+ showPaidToast: false,
355
+ });
356
+ }
357
+
358
+ function formattedDiscount(value: string): string {
359
+ if (!value || !/[1-9]/.test(value)) return "";
360
+ return /^[−-]/.test(value.trim()) ? value : `−${value}`;
361
+ }
362
+
363
+ function calculatedDiscount(result: unknown, currency: string): string {
364
+ const discount = (result as { summary?: { priceSummary?: { discount?: { amount?: string; convertedAmount?: string } } } } | null)?.summary?.priceSummary?.discount;
365
+ const amount = Number(discount?.amount);
366
+ if (!Number.isFinite(amount) || amount === 0 || !currency) return "";
367
+ return formattedDiscount(formatCurrency(Math.abs(amount), currency));
368
+ }
369
+
370
+ function invalidCouponFailure(error: unknown): boolean {
371
+ const status = Number((error as { status?: unknown; statusCode?: unknown } | null)?.status ?? (error as { statusCode?: unknown } | null)?.statusCode);
372
+ const message = String((error as Error | null)?.message ?? error ?? "");
373
+ return status === 400 || status === 422 || /\bHTTP (?:400|422)\b|INVALID_COUPON|COUPON_(?:NOT_FOUND|EXPIRED)/i.test(message);
374
+ }
375
+
376
+ function couponDetails(result: unknown): { id: string; code: string } {
377
+ const envelope = result as { cart?: Record<string, unknown> } | null;
378
+ const cart = envelope?.cart ?? result as Record<string, unknown> | null;
379
+ const discounts = cart?.appliedDiscounts as Array<{ coupon?: { id?: string; code?: string }; id?: string; code?: string }> | { discounts?: Array<{ coupon?: { id?: string; code?: string }; id?: string; code?: string }> } | undefined;
380
+ const coupon = (Array.isArray(discounts) ? discounts : discounts?.discounts)?.find(entry => entry.coupon?.code || entry.code);
381
+ return { id: coupon?.coupon?.id ?? coupon?.id ?? "", code: coupon?.coupon?.code ?? coupon?.code ?? "" };
382
+ }
383
+
384
+ import { withExclusiveWrites } from "../_shared/exclusive-writes.js";
385
+
386
+ let cartPricing: IapCommerce;
387
+ const defineService = withIapPresentation<State>({
388
+ register: withExclusiveWrites<State>(withOnlineWrites(registerState, ["remove", "increment", "decrement", "checkout", "beginPromo", "applyPromo", "removePromo"], { derive, messageFields: action => action.includes("Promo") ? ["promoError"] : ["checkoutHint"] }), ["load", "remove", "increment", "decrement", "checkout", "applyPromo", "removePromo", "save"], {
389
+ prepare: (action, args) => { if (action === "load") stashCopy(args[0]); },
390
+ coalesce: ["load"],
391
+ // Full cart reloads share the transaction, since they also replace rows and
392
+ // reset promo fields. Only setPromo increments the edit revision: beginPromo's internal error reset
393
+ // must not masquerade as a user edit when a rejected code is retried.
394
+ settle: (before, next, live) => {
395
+ if ((before.promoEditRevision ?? 0) === (live.promoEditRevision ?? 0)) return next;
396
+ return derive({ ...next, promoEditRevision: live.promoEditRevision,
397
+ ...(next.items.length ? { promoCode: live.promoCode, promoError: live.promoError } : {}) });
398
+ },
399
+ }),
400
+ onCreate: commerce => { cartPricing = commerce; },
401
+ prefix: "cart", transientKeys: ["items", "subtotal", "promoBusy", "promoEditRevision"], contentActions: ["load", "remove", "increment", "decrement"],
402
+ items: state => state.items.flatMap(row => row.catalogReference?.catalogItemId ? [{ reference: { kind: "storesProduct", id: row.catalogReference.catalogItemId }, commerceDisplayPrice: row.commerceTotal ?? row.total }] : []),
403
+ present: (state, price, allowed) => ({ ...state,
404
+ items: state.items.map(row => ({ ...row, total: row.catalogReference?.catalogItemId ? price(row.catalogReference.catalogItemId, row.commerceTotal ?? row.total) : row.total })),
405
+ subtotal: state.items.length > 0 && state.items.every(row => row.catalogReference?.catalogItemId && allowed(row.catalogReference.catalogItemId)) ? state.commerceSubtotal ?? state.subtotal : "" }),
406
+ });
407
+
408
+ let promoInFlight = false;
409
+ const svc = defineService<State, {
410
+ load: (state: State, arg?: unknown) => Promise<State>;
411
+ setPromo: (state: State, arg?: unknown) => State;
412
+ beginPromo: (state: State) => State;
413
+ applyPromo: (state: State) => Promise<State>;
414
+ removePromo: (state: State) => Promise<State>;
415
+ remove: (state: State, arg?: unknown) => Promise<State>;
416
+ save: (state: State, arg?: unknown) => State;
417
+ increment: (state: State, arg?: unknown) => Promise<State>;
418
+ decrement: (state: State, arg?: unknown) => Promise<State>;
419
+ checkout: (state: State) => Promise<State>;
420
+ }>("himiStoreCart", {
421
+ state: derive({ status: "loading", errorKind: "", items: [], subtotal: "", subtotalLabel: "", emptyText: "", checkoutHint: "", showPaidToast: false, noPaidToast: true, itemCount: 0, promoCode: "", promoEditRevision: 0, appliedCode: "", appliedLabel: "", couponId: "", promoError: "", promoBusy: false, noPromoError: true, hasCoupon: false, discount: "", noDiscount: true, noCheckoutHint: true, noCoupon: true, isLoading: true, notLoading: false, isErrored: false, notErrored: true, noOfflineError: true, noServerError: true, hideContent: true, noEmpty: true, noItems: true }),
422
+ actions: {
423
+ load: async (state, arg) => {
424
+ // 1) Instant paint from the on-device cache (offline-safe; empty on first-ever run).
425
+ const cached = await readCachedItems();
426
+ const base = cached.length
427
+ ? derive({ ...state, status: "ready", items: cached, emptyText: "" })
428
+ : state;
429
+ // 2) Revalidate from Wix and refresh the cache.
430
+ try {
431
+ return await refresh(state);
432
+ } catch (error) {
433
+ // Offline / fetch failure: keep the cached items instead of a blank error state.
434
+ return cached.length
435
+ ? base
436
+ : derive({ ...state, status: "error", errorKind: isOfflineFailure(error) ? "offline" : "server", items: [], subtotal: "", emptyText: copyParam("cart.loadErrorText", "Cart could not load."), checkoutHint: "" });
437
+ }
438
+ },
439
+ setPromo: (state, arg) => derive({ ...state, promoEditRevision: (state.promoEditRevision ?? 0) + 1, promoCode: (typeof arg === "string" ? arg : String((arg as { value?: unknown } | undefined)?.value ?? "")).slice(0, 100), promoError: "" }),
440
+ beginPromo: state => derive({ ...state, promoBusy: true, promoError: "" }),
441
+ applyPromo: async (state): Promise<State> => {
442
+ const code = state.promoCode.trim();
443
+ if (promoInFlight) return svc.getState() as State;
444
+ if (!code) return derive({ ...state, promoError: copyParam("cart.promoEmpty", "Enter a promo code.") });
445
+ promoInFlight = true;
446
+ let added = false;
447
+ try {
448
+ await svc.beginPromo();
449
+ state = svc.getState() as State;
450
+ await addCouponToCurrentCart(code);
451
+ added = true;
452
+ const calculated = await calculateCurrentCart().catch(() => null);
453
+ const refreshed = await refresh(state, "", undefined, calculated);
454
+ return refreshed.appliedCode
455
+ ? derive({ ...refreshed, promoBusy: false, promoCode: "", promoError: "" })
456
+ : derive({ ...refreshed, promoBusy: false, promoCode: state.promoCode, promoError: copyParam("cart.promoInvalid", "This promo code is not valid.") });
457
+ } catch (error) {
458
+ const mayHaveLanded = added || writeMayHaveLanded(error);
459
+ const refreshed = mayHaveLanded ? await refresh(state).catch(() => null) : null;
460
+ if (refreshed?.appliedCode === code) return derive({ ...refreshed, promoBusy: false, promoCode: "", promoError: "" });
461
+ return derive({ ...state, promoBusy: false, promoError: mayHaveLanded
462
+ ? copyParam("cart.promoUnconfirmed", "Could not confirm the promo code. Refresh your cart.")
463
+ : isOfflineFailure(error)
464
+ ? copyParam("cart.promoOffline", "Connect to the internet to use a promo code.")
465
+ : invalidCouponFailure(error)
466
+ ? copyParam("cart.promoInvalid", "This promo code is not valid.")
467
+ : copyParam("cart.promoUnavailable", "Could not apply the promo code. Try again.") });
468
+ } finally {
469
+ promoInFlight = false;
470
+ }
471
+ },
472
+ removePromo: async state => {
473
+ if (!state.couponId) return derive({ ...state, appliedCode: "", discount: "" });
474
+ let removed = false;
475
+ try {
476
+ await removeCouponFromCurrentCart(state.couponId);
477
+ removed = true;
478
+ await calculateCurrentCart().catch(() => null);
479
+ return derive({ ...(await refresh(state)), appliedCode: "", couponId: "", promoError: "" });
480
+ } catch (error) {
481
+ const mayHaveLanded = removed || writeMayHaveLanded(error);
482
+ const refreshed = mayHaveLanded ? await refresh(state).catch(() => null) : null;
483
+ if (refreshed && !refreshed.appliedCode) return derive({ ...refreshed, promoError: "" });
484
+ return derive({ ...state, promoError: mayHaveLanded
485
+ ? copyParam("cart.promoRemoveUnconfirmed", "Could not confirm promo removal. Refresh your cart.")
486
+ : copyParam("cart.promoRemoveFailed", "Could not remove the promo code.") });
487
+ }
488
+ },
489
+ remove: async (state, arg) => {
490
+ const id = itemId(arg);
491
+ if (!id) return state;
492
+ return removeLine(state, id);
493
+ },
494
+ save: (state, arg) => {
495
+ const id = itemId(arg);
496
+ const item = state.items.find(candidate => candidate.id === id);
497
+ const productId = item?.catalogReference?.catalogItemId ?? item?.productId;
498
+ if (!item || !productId) return state;
499
+ try {
500
+ const saved = toggleSavedProduct({ id: productId, name: item.name, price: item.unitPrice, wasPrice: item.wasPrice, image: item.image, swatches: item.swatches });
501
+ return derive({ ...state, items: state.items.map(candidate => (candidate.catalogReference?.catalogItemId ?? candidate.productId) === productId ? { ...candidate, saved, notSaved: !saved } : candidate) });
502
+ } catch { return derive({ ...state, checkoutHint: copyParam("cart.saveError", "Could not save this item.") }); }
503
+ },
504
+ increment: async (state, arg) => {
505
+ const id = itemId(arg);
506
+ const line = state.items.find((candidate) => candidate.id === id);
507
+ if (!line) return state;
508
+ try {
509
+ const cartId = (await getCurrentCart()).id || "";
510
+ const updated = await updateLineItemQuantity(cartId, id, line.quantity + 1);
511
+ return await refresh(state, "", updated.cart);
512
+ } catch {
513
+ return derive({ ...state, checkoutHint: copyParam("cart.quantityFailedMessage", "Could not update the quantity.") });
514
+ }
515
+ },
516
+ decrement: async (state, arg) => {
517
+ const id = itemId(arg);
518
+ const line = state.items.find((candidate) => candidate.id === id);
519
+ if (!line) return state;
520
+ // Qty 1 − ⇒ remove the line (the control never dead-ends), with remove's handling.
521
+ if (line.quantity <= 1) return removeLine(state, id);
522
+ try {
523
+ const cartId = (await getCurrentCart()).id || "";
524
+ const updated = await updateLineItemQuantity(cartId, id, line.quantity - 1);
525
+ return await refresh(state, "", updated.cart);
526
+ } catch {
527
+ return derive({ ...state, checkoutHint: copyParam("cart.quantityFailedMessage", "Could not update the quantity.") });
528
+ }
529
+ },
530
+ // Physical checkout collects shipping before the site's checkout creates the order.
531
+ checkout: async (state) => {
532
+ let validatedLines: WixCartLineItemDetail[] = [];
533
+ const signature = (lines: WixCartLineItemDetail[]) => JSON.stringify(lines.map(line => [line.id, line.quantity, (line as WixCartLineItemDetail & { catalogReference?: Row["catalogReference"] }).catalogReference]));
534
+ try {
535
+ const cart = await getCurrentCart();
536
+ const lines = cart.lineItems ?? [];
537
+ if (!lines.length) return derive({ ...state, checkoutHint: copyParam("cart.checkoutEmptyMessage", "Add an item before checkout.") });
538
+ const commerce = cartPricing;
539
+ const items = lines.map(line => (line as WixCartLineItemDetail & { catalogReference?: Row["catalogReference"] }).catalogReference);
540
+ if (items.some(item => !item?.catalogItemId || !item.appId)) return derive({ ...state, checkoutHint: iapPriceCopy("cart").purchaseUnavailable });
541
+ // Restaurant dishes share this Wix cart but check out on the food order screen; this checkout
542
+ // takes Stores products only, so say which lines are in the way rather than "unavailable".
543
+ if (items.some(item => item!.appId === RESTAURANTS_ORDERS_APP_ID)) {
544
+ return derive({ ...state, checkoutHint: copyParam("cart.restaurantItemsHint", "This cart also has restaurant dishes. Remove them here to check out your store items.") });
545
+ }
546
+ await commerce.loadPrices(items.map((item, index) => ({ reference: { kind: "storesProduct", id: item!.catalogItemId }, commerceDisplayPrice: lines[index].price?.formattedAmount })));
547
+ const classification = classifyCart(items.map((item, index) => ({ route: commerce.pricing.view({ kind: "storesProduct", id: item!.catalogItemId }).route, quantity: lines[index].quantity ?? 1 })));
548
+ if (classification !== "regular") return derive({ ...state, checkoutHint: classification === "mixedRefused" ? copyParam("cart.iapSingleItemOnly", "Buy digital items individually, with quantity 1 and no options.") : iapPriceCopy("cart").purchaseUnavailable });
549
+ const products = await Promise.all(items.map(async item => item!.appId === WIX_STORES_CATALOG_ID ? (await getStoreProduct(item!.catalogItemId)).product : undefined));
550
+ if (products.some(product => product?.productType?.toLowerCase() !== "physical")) return derive({ ...state, checkoutHint: iapPriceCopy("cart").purchaseUnavailable });
551
+ const latest = await getCurrentCart();
552
+ if (signature(latest.lineItems ?? []) !== signature(lines)) return derive({ ...state, checkoutHint: copyParam("cart.changedBeforeCheckout", "Your cart changed. Review it before checking out.") });
553
+ validatedLines = lines;
554
+ } catch { return derive({ ...state, checkoutHint: iapPriceCopy("cart").purchaseUnavailable }); }
555
+
556
+ if (!state.items.length) return derive({ ...state, checkoutHint: copyParam("cart.checkoutEmptyMessage", "Add an item before checkout.") });
557
+ try {
558
+ const checkout = await createCheckoutFromCurrentCart();
559
+ if (!checkout.checkoutId) return derive({ ...state, checkoutHint: copyParam("cart.checkoutIdMissingMessage", "Wix did not return a checkout id.") });
560
+ const checkoutId = checkout.checkoutId;
561
+
562
+ const hosted = isHostedWorker();
563
+ const pay = await payCashierOrder({
564
+ appId: WIX_STORES_APP_ID,
565
+ snapshotId: "",
566
+ msid: "",
567
+ mayCharge: async () => {
568
+ const latest = await getCurrentCart();
569
+ if (signature(latest.lineItems ?? []) !== signature(validatedLines)) return false;
570
+ return validatedLines.every(line => {
571
+ const reference = (line as WixCartLineItemDetail & { catalogReference?: Row["catalogReference"] }).catalogReference;
572
+ return !!reference && cartPricing.pricing.continueCheckoutGuard({ kind: "storesProduct", id: reference.catalogItemId }).allowed;
573
+ });
574
+ },
575
+ // Hosted (Spaces): the host opens the checkout as the lent member — Headless redirect
576
+ // sessions do not take a Member instance.
577
+ ...(hosted ? { openCashier: hostedCheckoutOpener(checkoutId) } : {}),
578
+ cashierUrl: async () => {
579
+ const redirect = await createRedirectSession({
580
+ ecomCheckout: { checkoutId },
581
+ callbacks: { postFlowUrl: "himalaya-himi-branded-lite://screen/himi_cart" },
582
+ });
583
+ return redirect.redirectSession?.fullUrl;
584
+ },
585
+ });
586
+ if (pay.kind === "handoff") {
587
+ // Do NOT clear the cart: payment completes in the cashier and the order is
588
+ // only confirmed once it lands, so the cart must survive a bail-out.
589
+ return derive({ ...state, checkoutHint: copyParam("cart.checkoutOpenedMessage", "Checkout opened.") });
590
+ }
591
+ if (isPaymentSetupFailure(pay)) return derive({ ...state, checkoutHint: paymentSetupMessage("cart") });
592
+ return derive({ ...state, checkoutHint: copyParam("cart.checkoutFailedMessage", "Checkout could not start.") });
593
+ } catch (error) {
594
+ if (isPaymentSetupFailure(error)) return derive({ ...state, checkoutHint: paymentSetupMessage("cart") });
595
+ return derive({ ...state, checkoutHint: copyParam("cart.checkoutFailedMessage", "Checkout could not start.") });
596
+ }
597
+ },
598
+ },
599
+ });
600
+
601
+ svc.load();
602
+ export { svc };