@wix/himalaya-cli 0.1648.0 → 0.1650.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 (87) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/sdk/ui/src/index.d.ts +4 -0
  2. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/ui.mjs +1 -0
  3. package/dist/browser-plane/assets.json +5 -5
  4. package/dist/browser-plane/preview-deferred/{4ef4d326496b4d7809746936207067b4c921f5db9878ecc7030aa3a9e4d2aaeb.bin → 6ba3f2eb2ac29f4f9eeebd1294a8003820cd260274c5400149d76833b3171555.bin} +1 -1
  5. package/dist/browser-plane/sw.js +5 -5
  6. package/dist/cli.mjs +45 -40
  7. package/dist/preview-assets.generated.bin +0 -0
  8. package/guides/sdk-reference.json +8 -1
  9. package/package.json +2 -2
  10. package/template-icons/wholesale-store.png +0 -0
  11. package/templates/beauty-salon/config.ts +16 -1
  12. package/templates/branded-lite/config.ts +16 -1
  13. package/templates/branded-lite/dev/index.ts +292 -305
  14. package/templates/branded-lite/l10n/en.json +3 -3
  15. package/templates/branded-lite/tier5-src/_shared/branded-form.ts +22 -4
  16. package/templates/branded-lite/tier5-src/himi-branded-lite-form/index.ts +250 -74
  17. package/templates/community-club/config.ts +16 -1
  18. package/templates/events-meetups/config.ts +16 -1
  19. package/templates/gym-fitness/config.ts +16 -1
  20. package/templates/nonprofit-cause/config.ts +16 -1
  21. package/templates/podcast-creator/config.ts +16 -1
  22. package/templates/portfolio-creative/config.ts +16 -1
  23. package/templates/restaurant/config.ts +16 -1
  24. package/templates/retail-store/config.ts +16 -1
  25. package/templates/wholesale-store/README.md +53 -0
  26. package/templates/wholesale-store/config.ts +247 -0
  27. package/templates/wholesale-store/dev/index.ts +12194 -0
  28. package/templates/wholesale-store/himalaya.content.json +43 -0
  29. package/templates/wholesale-store/himalaya.template.json +14 -0
  30. package/templates/wholesale-store/icon.png +0 -0
  31. package/templates/wholesale-store/platforms.json +1 -0
  32. package/templates/wholesale-store/tier5-src/_shared/app-locale.ts +61 -0
  33. package/templates/wholesale-store/tier5-src/_shared/branded-lite-hosted.ts +279 -0
  34. package/templates/wholesale-store/tier5-src/_shared/business-chat-copy.ts +40 -0
  35. package/templates/wholesale-store/tier5-src/_shared/business-chat-history.ts +51 -0
  36. package/templates/wholesale-store/tier5-src/_shared/business-chat-message-model.ts +177 -0
  37. package/templates/wholesale-store/tier5-src/_shared/business-chat-model.ts +56 -0
  38. package/templates/wholesale-store/tier5-src/_shared/business-chat-presenter.ts +576 -0
  39. package/templates/wholesale-store/tier5-src/_shared/business-chat-transport.ts +148 -0
  40. package/templates/wholesale-store/tier5-src/_shared/collection-contract.ts +228 -0
  41. package/templates/wholesale-store/tier5-src/_shared/collection-query-legacy.ts +194 -0
  42. package/templates/wholesale-store/tier5-src/_shared/collection-query.ts +252 -0
  43. package/templates/wholesale-store/tier5-src/_shared/collection-service.ts +423 -0
  44. package/templates/wholesale-store/tier5-src/_shared/detail-presence.ts +51 -0
  45. package/templates/wholesale-store/tier5-src/_shared/empty-flags.ts +33 -0
  46. package/templates/wholesale-store/tier5-src/_shared/engine-intl.ts +508 -0
  47. package/templates/wholesale-store/tier5-src/_shared/exclusive-writes.ts +66 -0
  48. package/templates/wholesale-store/tier5-src/_shared/himi-account.ts +164 -0
  49. package/templates/wholesale-store/tier5-src/_shared/himi-copy.ts +89 -0
  50. package/templates/wholesale-store/tier5-src/_shared/himi-store-categories.ts +108 -0
  51. package/templates/wholesale-store/tier5-src/_shared/himi-store-collection.ts +22 -0
  52. package/templates/wholesale-store/tier5-src/_shared/himi-store-saved.ts +57 -0
  53. package/templates/wholesale-store/tier5-src/_shared/himi-store.ts +7 -0
  54. package/templates/wholesale-store/tier5-src/_shared/himi-text.ts +24 -0
  55. package/templates/wholesale-store/tier5-src/_shared/hosted-checkout.ts +70 -0
  56. package/templates/wholesale-store/tier5-src/_shared/iap-presentation.ts +207 -0
  57. package/templates/wholesale-store/tier5-src/_shared/iap-worker.ts +125 -0
  58. package/templates/wholesale-store/tier5-src/_shared/inbox-rooms.ts +68 -0
  59. package/templates/wholesale-store/tier5-src/_shared/live-session.ts +172 -0
  60. package/templates/wholesale-store/tier5-src/_shared/local-preferences.ts +38 -0
  61. package/templates/wholesale-store/tier5-src/_shared/member-access.ts +52 -0
  62. package/templates/wholesale-store/tier5-src/_shared/member-account-routes.ts +52 -0
  63. package/templates/wholesale-store/tier5-src/_shared/member-orders.ts +8 -0
  64. package/templates/wholesale-store/tier5-src/_shared/member-screen.ts +99 -0
  65. package/templates/wholesale-store/tier5-src/_shared/online-actions.ts +76 -0
  66. package/templates/wholesale-store/tier5-src/_shared/owner-editor-value.ts +164 -0
  67. package/templates/wholesale-store/tier5-src/_shared/owner-load-error.ts +348 -0
  68. package/templates/wholesale-store/tier5-src/_shared/payment-setup.ts +6 -0
  69. package/templates/wholesale-store/tier5-src/_shared/read-service.ts +255 -0
  70. package/templates/wholesale-store/tier5-src/_shared/restaurant-ordering.ts +201 -0
  71. package/templates/wholesale-store/tier5-src/_shared/rich-body.ts +78 -0
  72. package/templates/wholesale-store/tier5-src/_shared/rich-content-link.ts +34 -0
  73. package/templates/wholesale-store/tier5-src/_shared/sign-in-sheet.ts +18 -0
  74. package/templates/wholesale-store/tier5-src/_shared/store-order-presentation.ts +56 -0
  75. package/templates/wholesale-store/tier5-src/_shared/store-product-info.ts +50 -0
  76. package/templates/wholesale-store/tier5-src/business-chat/index.ts +724 -0
  77. package/templates/wholesale-store/tier5-src/himi-branded-lite-cart/index.ts +602 -0
  78. package/templates/wholesale-store/tier5-src/himi-branded-lite-order/index.ts +472 -0
  79. package/templates/wholesale-store/tier5-src/himi-branded-lite-orders/index.ts +327 -0
  80. package/templates/wholesale-store/tier5-src/himi-store-account/index.ts +998 -0
  81. package/templates/wholesale-store/tier5-src/himi-store-product/index.ts +889 -0
  82. package/templates/wholesale-store/tier5-src/himi-store-saved/index.ts +68 -0
  83. package/templates/wholesale-store/tier5-src/himi-store-shop/index.ts +150 -0
  84. package/templates/wholesale-store/tier5-src/himi-wholesale-home/index.ts +507 -0
  85. package/templates/wholesale-store/tier5-src/wix-spaces-collection-detail/index.ts +195 -0
  86. package/templates/wholesale-store/tokens.json +340 -0
  87. package/templates/yoga-studio/config.ts +16 -1
@@ -0,0 +1,507 @@
1
+ // Tier-5 bundle: himi-wholesale-home — the wholesale-store template's Home and Categories screens.
2
+ //
3
+ // One read of the site's Wix Stores catalog (products page by page, and the categories) feeds
4
+ // both screens: the Home hero (the newest arrival), the round category tiles, the Deals rail (the
5
+ // products with a compare-at price, with their real "% OFF"), the Best sellers rail and the
6
+ // Categories product search. A category without an image of its own shows the photo of its first
7
+ // pictured product, so a customer's catalog shapes the screens with no configuration. Each tile
8
+ // opens the store package's category screen (`himi_collection`), each product the shared product
9
+ // screen (`himi_product`).
10
+ //
11
+ // A failed read is an error with Retry and an empty catalog is an empty state — never sample
12
+ // rows. Prices pass through the shared in-app-purchase presentation, as every store list does.
13
+ // The greeting is read at load time only: the release build hashes the boot state.
14
+ import { defineService as registerState, navigate } from "@himalaya/state";
15
+ import { productImage, productPrice, queryStoreProducts, type StoreProduct } from "../_shared/himi-store.js";
16
+ import { loadStoreCategories, type StoreCategoryCard } from "../_shared/himi-store-categories.js";
17
+ import { readSavedProducts, toggleSavedProduct } from "../_shared/himi-store-saved.js";
18
+ import { withIapPresentation } from "../_shared/iap-presentation.js";
19
+ import { loadMemberProfile, signedInEmail } from "../_shared/himi-account.js";
20
+ import { cleanTitle } from "../_shared/himi-text.js";
21
+ import { stashCopy, copyParam, copyTemplate } from "../_shared/himi-copy.js";
22
+
23
+ export interface ProductRow {
24
+ id: string;
25
+ name: string;
26
+ /** The price shown: the App Store price where the product sells through Apple, else `commercePrice`. */
27
+ price: string;
28
+ /** The price a shopper pays now, as the store formats it — what `price` is presented from. */
29
+ commercePrice: string;
30
+ /** The compare-at price when the product is on sale; "" otherwise. */
31
+ wasPrice: string;
32
+ noWasPrice: boolean;
33
+ /** "25% OFF" from the two amounts; "" when the product is not discounted. */
34
+ offLabel: string;
35
+ noOffLabel: boolean;
36
+ /** The category the search results name under the product. */
37
+ category: string;
38
+ image: string;
39
+ hasImage: boolean;
40
+ noImage: boolean;
41
+ saved: boolean;
42
+ notSaved: boolean;
43
+ /** What a tap on the heart does now ("Save Laptop 13 Go" / "Remove … from saved"). */
44
+ saveLabel: string;
45
+ }
46
+ export interface CategoryRow {
47
+ id: string;
48
+ name: string;
49
+ count: number;
50
+ countLabel: string;
51
+ image: string;
52
+ hasImage: boolean;
53
+ noImage: boolean;
54
+ }
55
+ interface S {
56
+ status: "loading" | "ready" | "error";
57
+ greeting: string;
58
+ firstName: string;
59
+ hasName: boolean;
60
+ noName: boolean;
61
+ isMember: boolean;
62
+ notMember: boolean;
63
+ memberInitials: string;
64
+ memberImage: string;
65
+ hasMemberImage: boolean;
66
+ noMemberImage: boolean;
67
+ /** The hero: the newest arrival, and the New In category Shop Now opens ("" → every product). */
68
+ heroName: string;
69
+ heroImage: string;
70
+ noHero: boolean;
71
+ heroCategoryId: string;
72
+ categories: CategoryRow[];
73
+ deals: ProductRow[];
74
+ bestSellers: ProductRow[];
75
+ query: string;
76
+ /** Categories' search-field focus token: a new value focuses the field (Home's search bar). */
77
+ searchFocus: string;
78
+ matches: ProductRow[];
79
+ noMatches: boolean;
80
+ searching: boolean;
81
+ notSearching: boolean;
82
+ matchesLabel: string;
83
+ noCategories: boolean;
84
+ noDeals: boolean;
85
+ noBestSellers: boolean;
86
+ total: number;
87
+ /** A heart that could not be saved says so here (the heart itself never claims it). */
88
+ saveMessage: string;
89
+ noSaveMessage: boolean;
90
+ emptyText: string;
91
+ errorText: string;
92
+ isLoading: boolean;
93
+ notLoading: boolean;
94
+ errored: boolean;
95
+ notErrored: boolean;
96
+ noEmpty: boolean;
97
+ }
98
+
99
+ const RAIL_MAX = 10;
100
+ const CATALOG_PAGE = 100, CATALOG_MAX = 500;
101
+ const ALL_PRODUCTS = ["all products", "all-products"];
102
+
103
+ /** A raw catalog product with the fields this screen reads beyond the display ones. */
104
+ type Product = StoreProduct & {
105
+ ribbon?: { name?: string } | string;
106
+ createdDate?: string;
107
+ allCategoriesInfo?: { categories?: { id?: string }[] };
108
+ collectionIds?: string[];
109
+ priceData?: { price?: number; discountedPrice?: number; formatted?: { price?: string; discountedPrice?: string } };
110
+ };
111
+
112
+ const numberOf = (value: unknown): number => {
113
+ const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
114
+ return Number.isFinite(n) ? n : NaN;
115
+ };
116
+
117
+ /** The price now, the price before, and the discount, on both catalogs: V3 compare-at range,
118
+ * V1 `discountedPrice`. A "discount" of 0% or less is no discount. */
119
+ export function saleOf(p: Product): { price: string; wasPrice: string; percent: number } {
120
+ const regular = productPrice(p);
121
+ const v3Was = numberOf(p.compareAtPriceRange?.minValue?.amount), v3Now = numberOf(p.actualPriceRange?.minValue?.amount);
122
+ if (v3Was > 0 && v3Now >= 0 && v3Was > v3Now) {
123
+ const wasPrice = productPrice({ ...p, price: undefined, priceData: undefined, actualPriceRange: p.compareAtPriceRange });
124
+ return { price: regular, wasPrice, percent: Math.round((1 - v3Now / v3Was) * 100) };
125
+ }
126
+ const v1Was = numberOf(p.priceData?.price), v1Now = numberOf(p.priceData?.discountedPrice);
127
+ if (v1Was > 0 && v1Now >= 0 && v1Was > v1Now) {
128
+ const now = p.priceData?.formatted?.discountedPrice;
129
+ const price = now ? productPrice({ ...p, priceData: { ...p.priceData, formatted: { ...p.priceData?.formatted, price: now } } } as StoreProduct) : regular;
130
+ return { price, wasPrice: regular, percent: Math.round((1 - v1Now / v1Was) * 100) };
131
+ }
132
+ return { price: regular, wasPrice: "", percent: 0 };
133
+ }
134
+
135
+ const categoryIdsOf = (p: Product): string[] =>
136
+ [...(p.allCategoriesInfo?.categories ?? []).map((c) => c.id ?? ""), ...(p.collectionIds ?? [])].filter(Boolean);
137
+
138
+ const ribbonOf = (p: Product): string => (typeof p.ribbon === "string" ? p.ribbon : p.ribbon?.name ?? "").trim();
139
+
140
+ function saveLabelFor(name: string, saved: boolean): string {
141
+ return saved ? copyTemplate("home.unsaveLabel", "Remove {name} from saved", { name }) : copyTemplate("home.saveLabel", "Save {name}", { name });
142
+ }
143
+
144
+ export function productRow(p: Product, savedIds: ReadonlySet<string>, categoryNames: ReadonlyMap<string, string> = new Map()): ProductRow {
145
+ const name = cleanTitle(p.name) || copyParam("home.productFallbackName", "Product");
146
+ const image = productImage(p);
147
+ const sale = saleOf(p);
148
+ const id = p.id ?? "";
149
+ const saved = savedIds.has(id);
150
+ const category = categoryIdsOf(p).map((c) => categoryNames.get(c) ?? "").find(Boolean) ?? "";
151
+ return {
152
+ id,
153
+ name,
154
+ price: sale.price,
155
+ commercePrice: sale.price,
156
+ wasPrice: sale.wasPrice,
157
+ noWasPrice: !sale.wasPrice,
158
+ offLabel: sale.percent > 0 ? copyTemplate("home.offLabel", "{percent}% OFF", { percent: sale.percent }) : "",
159
+ noOffLabel: sale.percent <= 0,
160
+ category,
161
+ image,
162
+ hasImage: !!image,
163
+ noImage: !image,
164
+ saved,
165
+ notSaved: !saved,
166
+ saveLabel: saveLabelFor(name, saved),
167
+ };
168
+ }
169
+
170
+ const isAllProducts = (c: { id: string; name: string }): boolean =>
171
+ ALL_PRODUCTS.includes(c.name.trim().toLowerCase()) || c.id === "00000000-000000-000000-000000000001";
172
+
173
+ function countLabel(n: number): string {
174
+ return n === 1 ? copyParam("home.productCountOne", "1 product") : copyTemplate("home.productCount", "{count} products", { count: n });
175
+ }
176
+
177
+ /** The category tiles: every browsable category but the system "All Products", in site order,
178
+ * each with its own image or else its first pictured product's, and its product count. */
179
+ export function categoryRows(cards: StoreCategoryCard[], products: Product[]): CategoryRow[] {
180
+ return cards.filter((c) => c.id && c.name && !isAllProducts(c)).map((c) => {
181
+ const inIt = products.filter((p) => categoryIdsOf(p).includes(c.id));
182
+ const image = c.image || inIt.map((p) => productImage(p)).find(Boolean) || "";
183
+ return { id: c.id, name: c.name.trim(), count: inIt.length, countLabel: countLabel(inIt.length), image, hasImage: !!image, noImage: !image };
184
+ });
185
+ }
186
+
187
+ const pictured = (rows: ProductRow[]): ProductRow[] => [...rows].sort((a, b) => Number(b.hasImage) - Number(a.hasImage));
188
+
189
+ /** A category the site names as its new arrivals / best sellers (by slug-like name). */
190
+ const namedCategory = (cards: StoreCategoryCard[], pattern: RegExp): StoreCategoryCard | undefined =>
191
+ cards.find((c) => pattern.test(c.name.trim().toLowerCase()));
192
+
193
+ function matchesOf(all: ProductRow[], query: string): ProductRow[] {
194
+ const q = query.trim().toLocaleLowerCase();
195
+ if (!q) return [];
196
+ return all.filter((row) => [row.name, row.category].some((field) => field.toLocaleLowerCase().includes(q)));
197
+ }
198
+
199
+ function greetingNow(firstName: string): string {
200
+ return firstName
201
+ ? copyTemplate("home.greetingNamed", "Hi, {name}!", { name: firstName })
202
+ : copyParam("home.greetingNeutral", "Welcome");
203
+ }
204
+
205
+ /** The name to greet: the first word of a real name, never an email address. */
206
+ export function firstNameOf(memberName: string): string {
207
+ const name = memberName.trim();
208
+ if (!name || name.includes("@")) return "";
209
+ return name.split(/\s+/)[0] ?? "";
210
+ }
211
+
212
+ // Every product read this session (the search reads it), with the category names it shows.
213
+ let allProducts: Product[] = [];
214
+ let categoryNames = new Map<string, string>();
215
+ let catalogRead = false;
216
+ // The last categories a read returned: a failed category read on a later visit keeps them, rather
217
+ // than wiping the tiles, the New In hero and Best sellers with no error to say why.
218
+ let lastCategories: StoreCategoryCard[] | null = null;
219
+ // The query as typed NOW: the field is live while a load runs (see salon-home for the race).
220
+ let liveQuery: string | null = null;
221
+
222
+ function savedIds(): Set<string> {
223
+ try { return new Set(readSavedProducts().map((row) => row.id)); } catch { return new Set(); }
224
+ }
225
+
226
+ // The catalog's rows, built once per load (and re-marked after a save): a search keystroke
227
+ // filters them, it never maps the whole catalog again (performance H-15).
228
+ let catalogRows: ProductRow[] = [];
229
+
230
+ /** `s` with the matches for its query: computed where the query or the rows change (load,
231
+ * search, clear), never in `derive`, which runs on every action. */
232
+ function withMatches(s: S): S {
233
+ return derive({ ...s, matches: catalogRead ? matchesOf(catalogRows, s.query) : [] });
234
+ }
235
+
236
+ /** Re-mark every row's heart from the saved store (after a toggle, or on a return to the screen). */
237
+ function withSaved(rows: ProductRow[], ids: ReadonlySet<string>): ProductRow[] {
238
+ return rows.map((row) => {
239
+ const saved = ids.has(row.id);
240
+ return saved === row.saved ? row : { ...row, saved, notSaved: !saved, saveLabel: saveLabelFor(row.name, saved) };
241
+ });
242
+ }
243
+
244
+ function derive(s: S): S {
245
+ const loading = s.status === "loading";
246
+ const errored = s.status === "error";
247
+ const searching = !!s.query.trim();
248
+ const matches = s.matches;
249
+ return {
250
+ ...s,
251
+ hasName: !!s.firstName,
252
+ noName: !s.firstName,
253
+ notMember: !s.isMember,
254
+ hasMemberImage: !!s.memberImage,
255
+ noMemberImage: !s.memberImage,
256
+ noHero: !s.heroImage,
257
+ matches,
258
+ searching,
259
+ notSearching: !searching,
260
+ noMatches: !searching || matches.length > 0 || !catalogRead,
261
+ matchesLabel: searching && catalogRead ? countLabel(matches.length) : "",
262
+ noCategories: s.categories.length === 0,
263
+ noDeals: s.deals.length === 0,
264
+ noBestSellers: s.bestSellers.length === 0,
265
+ noSaveMessage: !s.saveMessage,
266
+ isLoading: loading,
267
+ notLoading: !loading,
268
+ errored,
269
+ notErrored: !errored,
270
+ noEmpty: loading || errored || s.total > 0,
271
+ emptyText: copyParam("home.emptyText", "Products will appear here once the store adds them."),
272
+ errorText: copyParam("home.errorText", "The catalog could not be loaded."),
273
+ };
274
+ }
275
+
276
+ const BOOT: S = derive({
277
+ status: "loading",
278
+ greeting: copyParam("home.greetingNeutral", "Welcome"),
279
+ firstName: "", hasName: false, noName: true,
280
+ isMember: false, notMember: true, memberInitials: "", memberImage: "", hasMemberImage: false, noMemberImage: true,
281
+ heroName: "", heroImage: "", noHero: true, heroCategoryId: "",
282
+ categories: [], deals: [], bestSellers: [],
283
+ query: "", searchFocus: "", matches: [], noMatches: true, searching: false, notSearching: true, matchesLabel: "",
284
+ noCategories: true, noDeals: true, noBestSellers: true, total: 0,
285
+ saveMessage: "", noSaveMessage: true,
286
+ emptyText: "", errorText: "",
287
+ isLoading: true, notLoading: false, errored: false, notErrored: true, noEmpty: true,
288
+ });
289
+
290
+ type MemberPart = Pick<S, "isMember" | "firstName" | "memberInitials" | "memberImage">;
291
+ const GUEST_PART: MemberPart = { isMember: false, firstName: "", memberInitials: "", memberImage: "" };
292
+ const MEMBER_BUDGET_MS = 6000;
293
+
294
+ async function memberPart(): Promise<MemberPart> {
295
+ try {
296
+ const profile = await loadMemberProfile("");
297
+ return {
298
+ isMember: profile.isMember,
299
+ firstName: profile.isMember ? firstNameOf(profile.memberName) : "",
300
+ memberInitials: profile.isMember ? profile.memberInitials : "",
301
+ memberImage: profile.isMember ? profile.memberImage : "",
302
+ };
303
+ } catch {
304
+ // An unreadable profile greets a visitor; it never blocks the catalog.
305
+ return GUEST_PART;
306
+ }
307
+ }
308
+
309
+ /** The whole catalog, page by page, capped so a runaway catalog cannot stall Home. */
310
+ async function readProducts(): Promise<Product[]> {
311
+ const products: Product[] = [];
312
+ let cursor: string | undefined;
313
+ while (products.length < CATALOG_MAX) {
314
+ const res = await queryStoreProducts(CATALOG_PAGE, cursor, ["ALL_CATEGORIES_INFO"]);
315
+ products.push(...((res.products ?? []) as Product[]).filter((p) => !!p.id));
316
+ const next = res.pagingMetadata?.cursors?.next;
317
+ if (!next || !res.products?.length) break;
318
+ cursor = next;
319
+ }
320
+ return products;
321
+ }
322
+
323
+ type Catalog = { ok: true; products: Product[]; categories: StoreCategoryCard[] } | { ok: false };
324
+ async function readCatalog(): Promise<Catalog> {
325
+ try {
326
+ const [products, categories] = await Promise.all([
327
+ readProducts(),
328
+ // A failed category read is not a failed catalog: the last good categories stand, and with
329
+ // none yet the tiles hide while the rails stay.
330
+ loadStoreCategories({ includeAllProducts: true }).then((cards) => (lastCategories = cards)).catch(() => lastCategories ?? []),
331
+ ]);
332
+ return { ok: true, products, categories };
333
+ } catch {
334
+ // A failed product read is the error state, never a partial catalog.
335
+ return { ok: false };
336
+ }
337
+ }
338
+
339
+ /** The hero: the newest pictured product of the New In category, else of the catalog. `newIn`
340
+ * says which — Shop Now opens New In only when the hero is one of its products. */
341
+ function heroOf(products: Product[], newIn: StoreCategoryCard | undefined): { product?: Product; newIn: boolean } {
342
+ const pool = newIn ? products.filter((p) => categoryIdsOf(p).includes(newIn.id)) : [];
343
+ const newest = (rows: Product[]) => [...rows].filter((p) => !!productImage(p))
344
+ // ISO timestamps sort as plain strings; no `localeCompare` (watchOS / Wear OS have no ECMA-402).
345
+ .sort((a, b) => { const x = String(a.createdDate ?? ""), y = String(b.createdDate ?? ""); return x < y ? 1 : x > y ? -1 : 0; })[0];
346
+ const fromNewIn = newest(pool);
347
+ return fromNewIn ? { product: fromNewIn, newIn: true } : { product: newest(products), newIn: false };
348
+ }
349
+
350
+ let loadSeq = 0;
351
+
352
+ // Home's search bar opens Categories with a `focus` nonce. Each tap is a new nonce, so a host that
353
+ // hands a pooled worker the same params again (a return, not a tap) never refocuses the field.
354
+ let seenFocus = "";
355
+ let searchTaps = 0;
356
+ function focusFromInput(): string {
357
+ const value = (globalThis as { himalaya?: { input?: Record<string, unknown> } }).himalaya?.input?.focus;
358
+ const focus = typeof value === "string" ? value : "";
359
+ if (!focus || focus === seenFocus) return "";
360
+ seenFocus = focus;
361
+ return focus;
362
+ }
363
+
364
+ async function load(s: S): Promise<S> {
365
+ const mine = ++loadSeq;
366
+ // Read before the awaits; it rides the answer below. "" (no fresh nonce) clears the token.
367
+ const focus = focusFromInput();
368
+ const [member, catalog] = await Promise.all([within(memberPart(), MEMBER_BUDGET_MS, GUEST_PART), readCatalog()]);
369
+ if (mine !== loadSeq) return now();
370
+ const query = liveQuery ?? now().query;
371
+ // A token lives for the visit that asked for it: any other load clears it, so an ordinary
372
+ // return to Categories (a tab, Back) never refocuses the field with an old nonce.
373
+ const searchFocus = focus;
374
+ if (!catalog.ok) return derive({ ...now(), ...member, query, searchFocus, greeting: greetingNow(member.firstName), status: "error" });
375
+ allProducts = catalog.products;
376
+ categoryNames = new Map(catalog.categories.filter((c) => !isAllProducts(c)).map((c) => [c.id, c.name.trim()]));
377
+ catalogRead = true;
378
+ const ids = savedIds();
379
+ const rows = allProducts.map((p) => productRow(p, ids, categoryNames));
380
+ catalogRows = rows;
381
+ const newIn = namedCategory(catalog.categories, /^new( in| arrivals?)?$/);
382
+ const best = namedCategory(catalog.categories, /^best[ -]?sellers?$/);
383
+ const { product: hero, newIn: heroIsNew } = heroOf(allProducts, newIn);
384
+ const byId = new Map(rows.map((row) => [row.id, row]));
385
+ // The first of these that has products: the site's Best Sellers category, its "Best Seller"
386
+ // ribbons, its first products. An empty category does not hide the ribbons.
387
+ const inBest = best ? allProducts.filter((p) => categoryIdsOf(p).includes(best.id)) : [];
388
+ const ribboned = allProducts.filter((p) => /best/i.test(ribbonOf(p)));
389
+ const bestSellers = inBest.length ? inBest.map((p) => byId.get(p.id ?? "")!)
390
+ : ribboned.length ? ribboned.map((p) => byId.get(p.id ?? "")!) : rows;
391
+ return withMatches({
392
+ ...now(),
393
+ ...member,
394
+ query,
395
+ searchFocus,
396
+ greeting: greetingNow(member.firstName),
397
+ status: "ready",
398
+ heroName: hero ? cleanTitle(hero.name) : "",
399
+ heroImage: hero ? productImage(hero) : "",
400
+ heroCategoryId: heroIsNew && newIn ? newIn.id : "",
401
+ categories: categoryRows(catalog.categories, allProducts),
402
+ deals: pictured(rows.filter((row) => !row.noOffLabel)).slice(0, RAIL_MAX),
403
+ bestSellers: pictured(bestSellers.filter(Boolean)).slice(0, RAIL_MAX),
404
+ total: rows.length,
405
+ saveMessage: "",
406
+ });
407
+ }
408
+
409
+ // The newest state an action returned — what a slow action answers from after its await.
410
+ let latest: S = BOOT;
411
+ const commit = (next: S): S => (latest = next);
412
+ /** The state as it is now: the runtime's, which also holds a state a host restored. */
413
+ const now = (): S => (svc.getState?.() as S | undefined) ?? latest;
414
+
415
+ const valueOf = (arg: unknown): string => (typeof arg === "string" ? arg : String((arg as { value?: unknown } | undefined)?.value ?? ""));
416
+
417
+ /** `read`, or `fallback` once `ms` pass, where the engine has a timer (a bare JSContext has none;
418
+ * there it waits, as every read does). `read` must not reject. */
419
+ function within<T>(read: Promise<T>, ms: number, fallback: T): Promise<T> {
420
+ const host = globalThis as { setTimeout?: (fn: () => void, ms: number) => unknown; clearTimeout?: (timer: unknown) => void };
421
+ if (typeof host.setTimeout !== "function") return read;
422
+ return new Promise<T>((resolve) => {
423
+ const timer = host.setTimeout!(() => resolve(fallback), ms);
424
+ void read.then((value) => { host.clearTimeout?.(timer); resolve(value); });
425
+ });
426
+ }
427
+
428
+ const sessionEmail = (ms = 1500): Promise<string> => within(signedInEmail(), ms, "");
429
+ let memberTaps = 0;
430
+
431
+ const defineService = withIapPresentation<S>({
432
+ // Search is a content action: its matches are new rows to price. Each row presents from its own
433
+ // `commercePrice`, never from `price` (which holds the last presentation, e.g. "Loading price…").
434
+ register: registerState, prefix: "home", transientKeys: ["deals", "bestSellers", "matches"], contentActions: ["load", "refresh", "search", "clearSearch"],
435
+ items: (state) => [...state.deals, ...state.bestSellers, ...state.matches]
436
+ .map((row) => ({ reference: { kind: "storesProduct", id: row.id }, commerceDisplayPrice: row.commercePrice })),
437
+ present: (state, price) => ({ ...state,
438
+ deals: state.deals.map((row) => ({ ...row, price: price(row.id, row.commercePrice) })),
439
+ bestSellers: state.bestSellers.map((row) => ({ ...row, price: price(row.id, row.commercePrice) })),
440
+ matches: state.matches.map((row) => ({ ...row, price: price(row.id, row.commercePrice) })),
441
+ }),
442
+ });
443
+
444
+ const svc = defineService<S, {
445
+ load: (s: S, arg?: unknown) => Promise<S>;
446
+ refresh: (s: S, arg?: unknown) => Promise<S>;
447
+ search: (s: S, arg?: unknown) => S;
448
+ clearSearch: (s: S) => S;
449
+ toggleSave: (s: S, arg?: unknown) => S;
450
+ openHero: (s: S) => S;
451
+ openSearch: (s: S) => S;
452
+ openForMember: (s: S, arg?: unknown) => Promise<S>;
453
+ }>("himiWholesaleHome", {
454
+ // A save failure belongs to the visit it happened on.
455
+ // A restored focus token would focus the field again on a return to the screen.
456
+ notHydrated: ["saveMessage", "searchFocus"],
457
+ state: BOOT,
458
+ actions: {
459
+ load: (s, arg) => { stashCopy(arg); return load(s).then(commit); },
460
+ refresh: (s, arg) => { stashCopy(arg); return load(s.status === "error" ? { ...s, status: "loading" } : s).then(commit); },
461
+ // Typing means the focus was used: the token is cleared, so a remount does not refocus.
462
+ search: (s, arg) => { liveQuery = valueOf(arg).slice(0, 120); return commit(withMatches({ ...s, query: liveQuery, searchFocus: "" })); },
463
+ clearSearch: (s) => { liveQuery = ""; return commit(withMatches({ ...s, query: "" })); },
464
+ // The heart on a deal or best-seller card: the shared saved store, which the product screen
465
+ // and the Saved tab read. A failed write leaves every heart as it was and says so.
466
+ toggleSave: (s, arg) => {
467
+ const id = String((arg as { id?: unknown } | undefined)?.id ?? "");
468
+ const row = [...s.deals, ...s.bestSellers, ...s.matches].find((r) => r.id === id);
469
+ if (!row) return s;
470
+ try {
471
+ toggleSavedProduct({ id: row.id, name: row.name, price: row.commercePrice, image: row.image, ...(row.wasPrice ? { wasPrice: row.wasPrice } : {}) });
472
+ } catch {
473
+ return commit(derive({ ...s, saveMessage: copyParam("home.saveError", "Could not update your saved products. Try again.") }));
474
+ }
475
+ const ids = savedIds();
476
+ catalogRows = withSaved(catalogRows, ids);
477
+ return commit(derive({ ...s, saveMessage: "", deals: withSaved(s.deals, ids), bestSellers: withSaved(s.bestSellers, ids), matches: withSaved(s.matches, ids) }));
478
+ },
479
+ // Shop Now: the New In category when the site has one, else every product.
480
+ openHero: (s) => navigate(s, s.heroCategoryId
481
+ ? { screenId: "himi_collection", args: { id: s.heroCategoryId } }
482
+ : { screenId: "himi_shop" }),
483
+ // Home's search bar: Categories, with its field focused (the nonce tells a tap from a return).
484
+ openSearch: (s) => navigate(s, { screenId: "himi_collections", args: { focus: `${Date.now().toString(36)}-${++searchTaps}` } }),
485
+ // A member screen (the chat): a member goes there; a guest gets the sign-in first. The
486
+ // session is asked at the tap, not read from the last load.
487
+ openForMember: async (_s, arg) => {
488
+ const field = (key: string): string => {
489
+ const value = (arg as Record<string, unknown> | undefined)?.[key];
490
+ return typeof value === "string" ? value : "";
491
+ };
492
+ const screenId = field("screenId"), signInScreenId = field("signInScreenId");
493
+ const presentation = field("signInPresentation") === "full_screen" ? "full_screen" : field("signInPresentation") === "sheet" ? "sheet" : "";
494
+ if (!screenId) return now();
495
+ const mine = ++memberTaps;
496
+ const email = signInScreenId ? await sessionEmail() : "";
497
+ if (mine !== memberTaps) return now();
498
+ if (!signInScreenId || email) return navigate(now(), { screenId });
499
+ const args: Record<string, string> = { mode: "signin", returnScreenId: screenId };
500
+ if (!presentation) return navigate(now(), { screenId: signInScreenId, args });
501
+ if (field("returnTab")) args.returnTab = field("returnTab");
502
+ return navigate(now(), { screenId: signInScreenId, presentation, args: { ...args, modal: "1" } });
503
+ },
504
+ },
505
+ });
506
+ // No load at boot: Home and Categories each load on appear, with their copy.
507
+ export { svc };