@wix/himalaya-cli 0.1781.0 → 0.1782.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.
@@ -3418,6 +3418,10 @@ export interface TopBarAction {
3418
3418
  /** "screen" opts into screen-worker visibility. Unset/unknown retains navigation ownership.
3419
3419
  * App-level topBarDefault actions always retain navigation ownership when inherited. */
3420
3420
  hiddenPathScope?: string;
3421
+ /** RFC 0070 §1.2 — fail-closed `hiddenPath`, as on `NavTabItem`: hidden until the nav worker
3422
+ * resolves the path to a scalar, and hidden if it never does. Older runtimes ignore it and
3423
+ * fail open. */
3424
+ hiddenUntilResolved?: boolean;
3421
3425
  }
3422
3426
  /** Splash layout discriminator. Single-line string-literal union (house style,
3423
3427
  * like `NavKind`); unknown values coalesce to "centered" in the shell. */
@@ -470,7 +470,12 @@ export interface SiteShellCheckOptions {
470
470
  /** Throws with a legible message on a site description no shell can build from. */
471
471
  export declare function assertSiteShellConfig(site: SiteShellConfig, opts?: SiteShellCheckOptions): void;
472
472
  /** A rewriter for one contract's site: rewrites every dead tap in a descriptor, in place on a copy. */
473
- export declare function siteShellLinks(site: SiteShellConfig): (descriptor: ScreenDescriptor) => ScreenDescriptor;
473
+ export interface SiteShellLinkOptions {
474
+ /** The shell serves the native MEMBER cart (`himi_cart`, RFC 0079 §10 amendment 2026-11-16b): a tap into
475
+ * it, and an order's Reorder that fills it, are kept rather than removed. */
476
+ nativeCart?: boolean;
477
+ }
478
+ export declare function siteShellLinks(site: SiteShellConfig, options?: SiteShellLinkOptions): (descriptor: ScreenDescriptor) => ScreenDescriptor;
474
479
  /**
475
480
  * Where a tapped Wix member notification opens in a site shell: on the customer's own site. Wix Ping
476
481
  * delivers Wix MOBILE links (`wix:/my-account/<msid>/stores/orders/<id>`, `https://m-<msid>.branded.wix.app/…`),
@@ -798,6 +798,9 @@ export declare const screenDescriptorSchema: {
798
798
  readonly hiddenPathScope: {
799
799
  readonly type: "string";
800
800
  };
801
+ readonly hiddenUntilResolved: {
802
+ readonly type: "boolean";
803
+ };
801
804
  };
802
805
  };
803
806
  readonly navBadge: {
@@ -2377,6 +2380,9 @@ export declare const widgetSnapshotSchema: {
2377
2380
  readonly hiddenPathScope: {
2378
2381
  readonly type: "string";
2379
2382
  };
2383
+ readonly hiddenUntilResolved: {
2384
+ readonly type: "boolean";
2385
+ };
2380
2386
  };
2381
2387
  };
2382
2388
  readonly navBadge: {
@@ -9408,7 +9408,9 @@ var screenDescriptorSchema = {
9408
9408
  hiddenPath: { type: "string" },
9409
9409
  labelPath: { type: "string" },
9410
9410
  iconPath: { type: "string" },
9411
- hiddenPathScope: { type: "string" }
9411
+ hiddenPathScope: { type: "string" },
9412
+ // Hidden until hiddenPath first resolves (fail closed): the Brandy cart icon pair.
9413
+ hiddenUntilResolved: { type: "boolean" }
9412
9414
  }
9413
9415
  },
9414
9416
  navBadge: {
@@ -16063,6 +16065,7 @@ var SITE_STAND_INS = {
16063
16065
  };
16064
16066
  var ALWAYS_HIDDEN_TARGETS = ["himi_cart", "himi_new_message"];
16065
16067
  var HIDDEN_ACTIONS = ["tier5.himiBrandedOrder.reorder"];
16068
+ var UNTAPPED_TARGETS = ["himi_product"];
16066
16069
  var LABEL_FOR = { action: "actionLabel", cta: "ctaLabel" };
16067
16070
  function standInActions(site) {
16068
16071
  const tapFor = (id, target) => siteTopBarDefault({ ...site, topBar: { actions: [{ id, icon: "globe", label: id, target }] } })?.actions?.[0]?.onTap;
@@ -16078,17 +16081,19 @@ function standInActions(site) {
16078
16081
  }
16079
16082
  return taps;
16080
16083
  }
16081
- function siteShellLinks(site) {
16084
+ function siteShellLinks(site, options = {}) {
16082
16085
  const standIns = standInActions(site);
16086
+ const hiddenTargets = options.nativeCart ? ALWAYS_HIDDEN_TARGETS.filter((id) => id !== "himi_cart") : ALWAYS_HIDDEN_TARGETS;
16087
+ const hiddenActions = options.nativeCart ? [] : HIDDEN_ACTIONS;
16083
16088
  const verdict = (action) => {
16084
16089
  if (!action || typeof action !== "object") return "keep";
16085
16090
  const a = action;
16086
- if (HIDDEN_ACTIONS.includes(a.actionId)) return "hide";
16091
+ if (hiddenActions.includes(a.actionId)) return "hide";
16087
16092
  if (a.actionId !== "himi.open") return "keep";
16088
16093
  const target = a.params?.screenId;
16089
16094
  if (!target) return "keep";
16090
16095
  if (standIns.has(target)) return standIns.get(target);
16091
- if (ALWAYS_HIDDEN_TARGETS.includes(target) || target in SITE_STAND_INS) return "hide";
16096
+ if (hiddenTargets.includes(target) || target in SITE_STAND_INS) return "hide";
16092
16097
  return "keep";
16093
16098
  };
16094
16099
  const visit = (node) => {
@@ -16112,6 +16117,8 @@ function siteShellLinks(site) {
16112
16117
  }
16113
16118
  const modifiers = n.modifiers;
16114
16119
  if (modifiers) {
16120
+ const tapTarget = modifiers.onTap?.params?.screenId;
16121
+ if (modifiers.onTap?.actionId === "himi.open" && tapTarget && UNTAPPED_TARGETS.includes(tapTarget)) delete modifiers.onTap;
16115
16122
  const v = verdict(modifiers.onTap);
16116
16123
  if (v === "hide") return false;
16117
16124
  if (v !== "keep") modifiers.onTap = { ...v };
@@ -7420,7 +7420,9 @@ var screenDescriptorSchema = {
7420
7420
  hiddenPath: { type: "string" },
7421
7421
  labelPath: { type: "string" },
7422
7422
  iconPath: { type: "string" },
7423
- hiddenPathScope: { type: "string" }
7423
+ hiddenPathScope: { type: "string" },
7424
+ // Hidden until hiddenPath first resolves (fail closed): the Brandy cart icon pair.
7425
+ hiddenUntilResolved: { type: "boolean" }
7424
7426
  }
7425
7427
  },
7426
7428
  navBadge: {
package/dist/cli.mjs CHANGED
@@ -19164,7 +19164,9 @@ var init_validator = __esm({
19164
19164
  hiddenPath: { type: "string" },
19165
19165
  labelPath: { type: "string" },
19166
19166
  iconPath: { type: "string" },
19167
- hiddenPathScope: { type: "string" }
19167
+ hiddenPathScope: { type: "string" },
19168
+ // Hidden until hiddenPath first resolves (fail closed): the Brandy cart icon pair.
19169
+ hiddenUntilResolved: { type: "boolean" }
19168
19170
  }
19169
19171
  },
19170
19172
  navBadge: {
@@ -328,7 +328,7 @@ Three optional parts of a site shell's `site` block add or trim native chrome wi
328
328
  A target that is a tab switches to that tab (`himi.tab`). Any other target opens its screen (`himi.open`), and so does every target under the `drawer` and `single` layouts, which have no tab bar. Under `menuSource: "runtime"`, a site page target is always opened rather than switched to, because the site's own menu may move that page out of the tab bar on a later launch. On the page or native screen an icon opens, the bar leaves that icon out, so tapping it cannot push a second copy of it. A native screen that draws a top bar of its own keeps it as the author wrote it. A `url` with a `.` or `..` path segment is refused.
329
329
  - **`nativePages`**: the author's own Tier-5 screens as rows. Each one is a `tab`, `drawer` or `overflow` entry (an `overflow` entry is linkable only). They join the tab bar, drawer and rail with the site's pages, after the page named by `after` (default: after all of them, and never before `home`). Tabs count toward the four-tab limit together with the site's tabs. The WebView keep-alive cap only concerns site tabs, because a native tab keeps no WebView. Every native page is in `linkableScreens`. It is private by default: a link from outside the app (a website link, another app) to `<scheme>://screen/<screenId>` opens it only when the page sets `"public": true`. `"requiresAuth": true` implies public and signs the user in first. It needs a sign-in that gates deep links, which today means a Wix member binding. Any other app refuses it, a Base44 site included, rather than open the screen signed out. A native page that places the built-in Notifications or Account screen stays public unless it sets `"public": false`, which turns off outside links to that screen. A public native page opens on its tab when it has one. Under the `drawer`, `single` and one-tab `auto` layouts, where there is no tab to select, the link pushes it instead. Account deletion (`himi_delete_account`) cannot be placed. An id must differ from every site page's id and must not start with `drawer_`. A `screenId` must not start with `site_`.
330
330
 
331
- **Member screens (Brandy, `wix` binding).** A Brandy app, or a `himi init --template brandy` package, whose contract binds a Wix member client (`wix`) also serves Branded Lite's own member screens, with Branded Lite's builders and workers: the activity feed `himi_notifications`, the inbox `himi_inbox`, My Orders `himi_orders` and My Subscriptions `himi_my_subscriptions`. A native page may place any of them, and a `{ screen }` icon may open one that a native page places (an `overflow` page adds no row). The Account screen links to all of them. The screens they open (an order, a thread, a subscription, the sign-in form) are served too but cannot be placed. A visitor-only contract refuses a native page or icon that names a member screen, saying a `wix` binding is missing. Cart and checkout are not served yet: they need a visitor session shared with the website. The wishlist (`himi_saved_products`) is not served: it lists products saved on native product screens, which a site shell does not have. Inside these screens, a link to a screen a site shell does not serve goes to the website instead: Chat with us opens the site's contact page, Browse the shop and Browse plans open the site's shop and plans pages (a tab is switched to), and each is removed when the site has no such page. Reorder, which fills the native cart, is removed. A sensible default for a member app is Account and Notifications as drawer rows and a bell that opens Notifications:
331
+ **Member screens (Brandy, `wix` binding).** A Brandy app, or a `himi init --template brandy` package, whose contract binds a Wix member client (`wix`) also serves Branded Lite's own member screens, with Branded Lite's builders and workers: the activity feed `himi_notifications`, the inbox `himi_inbox`, My Orders `himi_orders` and My Subscriptions `himi_my_subscriptions`. A native page may place any of them, and a `{ screen }` icon may open one that a native page places (an `overflow` page adds no row). The Account screen links to all of them. The screens they open (an order, a thread, a subscription, the sign-in form) are served too but cannot be placed. A visitor-only contract refuses a native page or icon that names a member screen, saying a `wix` binding is missing. **Cart and checkout, members only:** a native page may place the cart `himi_cart` (it must set `"requiresAuth": true`) and a `{ screen: "himi_cart" }` icon may open it; checkout is the cart's own button, through the Wix cashier. A signed-in member's cart is the website's own cart, so a change on either side shows on the other (the icon's count refreshes at launch, on sign-in or sign-out and when the app returns to the foreground; a website tab on its next load). Signed out, the cart shows a sign-in prompt and reads no cart. A visitor keeps the website's cart: when the site block declares the site's cart page (id `cart`, or path `/cart` or `/cart-page`, an `overflow` page is fine), the icon opens that page for a visitor and the native cart for a member, and the visitor's icon shows no count. A visitor-only contract that names `himi_cart` is refused. The wishlist (`himi_saved_products`) is not served: it lists products saved on native product screens, which a site shell does not have. Inside these screens, a link to a screen a site shell does not serve goes to the website instead: Chat with us opens the site's contact page, Browse the shop and Browse plans open the site's shop and plans pages (a tab is switched to), and each is removed when the site has no such page. Reorder, which fills the native cart, is removed unless the contract places the cart. A sensible default for a member app is Account and Notifications as drawer rows and a bell that opens Notifications:
332
332
 
333
333
  ```json
334
334
  "nativePages": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wix/himalaya-cli",
3
- "version": "0.1781.0",
3
+ "version": "0.1782.0",
4
4
  "type": "module",
5
5
  "description": "himi — the Himalaya authoring CLI. Build a Tier-5 content package on your own machine, push it to the production serve as a draft, preview it on web + Himi Player, and read worker logs back — the remote dev loop. Wraps @himalaya/serve-cli for transport.",
6
6
  "keywords": [
@@ -82,5 +82,5 @@
82
82
  "artifactId": "himalaya-cli"
83
83
  }
84
84
  },
85
- "falconPackageHash": "68c1b1ae0a2436ea0e591a36d1ddd5a5dc609b950e7cccdc4a4e7b5b"
85
+ "falconPackageHash": "b0741e23207d689e0d13d2c1ac0d2d208be5b86cc03877eed0733f2a"
86
86
  }
@@ -12,6 +12,32 @@ import { isPaymentSetupFailure, payCashierOrder } from "@himalaya/checkout";
12
12
  import { hostedCheckoutOpener, isHostedWorker } from "../_shared/hosted-checkout.js";
13
13
  import { formatCurrency } from "../_shared/engine-intl.js";
14
14
  import { logBi, wixErrorCode } from "../_shared/wix-bi.js";
15
+ import { hostSessionFromGlobal } from "@himalaya/iap";
16
+
17
+ /** The host's session clock (a signed-out stub on a host without one). */
18
+ const hostSession = hostSessionFromGlobal();
19
+ /** A web host has no session clock (the stub above always reads signed out): it delivers sign-in and sign-out
20
+ * through the reserved `onIdentityChange` action instead. `undefined` until it first does. Each delivery is a new
21
+ * identity, so it also bumps the generation the members-only cart's rows are checked against. */
22
+ let webSignedIn: boolean | undefined;
23
+ let webGeneration = 0;
24
+ const signedInMember = (): boolean => hostSession.current().kind === "member" || webSignedIn === true;
25
+ /** The members-only cart. Known at BOOT when the screen's bundle is the members-only entry
26
+ * (`himi-branded-lite-member-cart`, which sets the flag before this module runs), so even the boot load never
27
+ * reads a signed-out shopper's cart; also set by a load that names `memberOnly`. */
28
+ let memberOnlyCart = (globalThis as { __himiMemberOnlyCart?: boolean }).__himiMemberOnlyCart === true;
29
+ /** The session generation the rows on show were read under. A members-only cart shows rows only for the CURRENT
30
+ * generation: a member switch while a read or write is in flight never lands the previous member's rows. */
31
+ let rowsGeneration = -1;
32
+ const sessionGeneration = (): number => hostSession.current().generation + webGeneration;
33
+ const memberOnlyArg = (arg: unknown): boolean => (arg as { memberOnly?: unknown } | undefined)?.memberOnly === "1";
34
+ /** Where the in-app cashier returns after payment: this app's own scheme. Another content package on this shell
35
+ * (a Brandy site shell registers its contract's scheme) passes its own on load; only `<scheme>://screen/himi_cart`. */
36
+ let cashierReturnUrl = "himalaya-himi-branded-lite://screen/himi_cart";
37
+ function takeReturnUrl(arg: unknown): void {
38
+ const url = (arg as { returnUrl?: unknown } | undefined)?.returnUrl;
39
+ if (typeof url === "string" && /^[a-z][a-z0-9+.-]*:\/\/screen\/himi_cart$/.test(url)) cashierReturnUrl = url;
40
+ }
15
41
 
16
42
  /** Wix Stores appDefId — the vertical that owns a cart/ecom order, and therefore the
17
43
  * `appId` its cashier order is paid under. (Same constant Wix's own tooling uses.) */
@@ -50,6 +76,9 @@ function cachedUnitPrice(total: string, quantity: number): string {
50
76
  return total.replace(raw, `${grouped}${digits ? decimal + fraction : ""}`);
51
77
  }
52
78
  async function readCachedItems(): Promise<Row[]> {
79
+ // A members-only cart keeps no on-device copy: the cart entity is app-scoped, so one member's rows would show to
80
+ // the next member offline.
81
+ if (memberOnlyCart) return [];
53
82
  try {
54
83
  return ((await getAll(ENTITY)) as unknown as Row[]).map(item => {
55
84
  const quantity = Math.max(1, Math.floor(Number(item.quantity) || 1));
@@ -68,6 +97,7 @@ async function readCachedItems(): Promise<Row[]> {
68
97
  * (one removed elsewhere, or a removal whose answer was lost), so the offline paint never
69
98
  * shows a line that is gone. */
70
99
  async function writeCachedItems(rows: Row[]): Promise<void> {
100
+ if (memberOnlyCart) return;
71
101
  try {
72
102
  const keep = new Set(rows.map((r) => r.id));
73
103
  for (const old of (await getAll(ENTITY)) as unknown as Row[]) if (!keep.has(old.id)) await dbRemove(ENTITY, old.id);
@@ -143,6 +173,12 @@ interface State {
143
173
  hideContent: boolean;
144
174
  noEmpty: boolean;
145
175
  noItems: boolean;
176
+ /** A site shell serves this cart to MEMBERS only (`memberOnly` on load):
177
+ * a native visitor cart is not the website's visitor cart, so a signed-out shopper sees the sign-in gate
178
+ * (`needsSignIn`) instead of a second, separate cart. Absent in Branded Lite, where the visitor cart is native. */
179
+ memberOnly?: boolean;
180
+ needsSignIn?: boolean;
181
+ noSignIn?: boolean;
146
182
  }
147
183
 
148
184
  function itemId(arg: unknown): string {
@@ -256,6 +292,16 @@ function updateLineItemQuantity(cartId: string, lineItemId: string, quantity: nu
256
292
  }
257
293
 
258
294
  function derive(state: State): State {
295
+ // Every state a members-only cart commits passes here, a write's result included: a sign-out while a write was
296
+ // in flight (its identity reload dropped as a concurrent action) still lands on the gate, never the member's rows.
297
+ if (memberOnlyCart && !signedInMember()) {
298
+ state = { ...state, memberOnly: true, needsSignIn: true, status: "ready", errorKind: "", items: [], subtotal: "", commerceSubtotal: "", emptyText: "", checkoutHint: "" };
299
+ } else if (memberOnlyCart && rowsGeneration !== sessionGeneration() && state.items.length > 0) {
300
+ // Rows read under another member (a write's result that landed after the switch): hold a loading state, and
301
+ // reload for this member once the write has settled.
302
+ state = { ...state, memberOnly: true, needsSignIn: false, status: "loading", items: [], subtotal: "", commerceSubtotal: "", checkoutHint: "" };
303
+ queueSessionReload();
304
+ }
259
305
  let savedIds: Set<string> | null = null;
260
306
  try { savedIds = new Set(readSavedProducts().map(row => row.id)); }
261
307
  catch { /* saved storage unavailable: retain the saved flags already shown on each row */ }
@@ -291,6 +337,9 @@ function derive(state: State): State {
291
337
  noPaidToast: !state.showPaidToast,
292
338
  noCoupon: !state.appliedCode,
293
339
  subtotalLabel: copyTemplate("cart.subtotalCount", "Subtotal ({count})", { count: itemCount }),
340
+ noSignIn: !state.needsSignIn,
341
+ // Gated: no content, no empty card, no error card, no checkout footer — only the sign-in gate.
342
+ ...(state.needsSignIn ? { hideContent: true, noEmpty: true, noItems: true, isErrored: false, notErrored: true, noOfflineError: true, noServerError: true, noCheckoutHint: true } : {}),
294
343
  };
295
344
  }
296
345
 
@@ -387,7 +436,7 @@ import { withExclusiveWrites } from "../_shared/exclusive-writes.js";
387
436
  let cartPricing: IapCommerce;
388
437
  const defineService = withIapPresentation<State>({
389
438
  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"], {
390
- prepare: (action, args) => { if (action === "load") stashCopy(args[0]); },
439
+ prepare: (action, args) => { if (action === "load") { stashCopy(args[0]); if (memberOnlyArg(args[0])) memberOnlyCart = true; takeReturnUrl(args[0]); } },
391
440
  coalesce: ["load"],
392
441
  // Full cart reloads share the transaction, since they also replace rows and
393
442
  // reset promo fields. Only setPromo increments the edit revision: beginPromo's internal error reset
@@ -418,10 +467,36 @@ const svc = defineService<State, {
418
467
  increment: (state: State, arg?: unknown) => Promise<State>;
419
468
  decrement: (state: State, arg?: unknown) => Promise<State>;
420
469
  checkout: (state: State) => Promise<State>;
470
+ dropForSession: (state: State) => State;
471
+ onIdentityChange: (state: State, change?: unknown) => State;
421
472
  }>("himiStoreCart", {
422
- 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 }),
473
+ 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, memberOnly: false, needsSignIn: false, noSignIn: true }),
423
474
  actions: {
475
+ // Not a write: it runs even while one is in flight, so a member switch clears the previous member's rows AT ONCE.
476
+ dropForSession: (state) => derive(state),
477
+ // The web host's identity hook (see `webSignedIn`): a members-only cart follows it as it follows the native clock.
478
+ onIdentityChange: (state, change) => {
479
+ webSignedIn = (change as { signedIn?: unknown } | undefined)?.signedIn === true;
480
+ webGeneration++;
481
+ if (memberOnlyCart) queueSessionReload();
482
+ return derive(state);
483
+ },
424
484
  load: async (state, arg) => {
485
+ // A members-only cart (a site shell) never shows a signed-out shopper's native cart. `prepare` sets the flag
486
+ // before coalescing, so a load already in flight (the boot load) re-checks it before it lands.
487
+ if (memberOnlyArg(arg)) memberOnlyCart = true;
488
+ const gated = (): State => derive({ ...state, memberOnly: true, needsSignIn: true, status: "ready", errorKind: "", items: [], subtotal: "", commerceSubtotal: "", emptyText: "", checkoutHint: "" });
489
+ if (memberOnlyCart && !signedInMember()) return gated();
490
+ if (memberOnlyCart) state = { ...state, memberOnly: true, needsSignIn: false };
491
+ const readUnder = sessionGeneration();
492
+ // This read is for the current member: rows it derives stand until the generation moves on.
493
+ if (memberOnlyCart) rowsGeneration = readUnder;
494
+ const landed = (next: State): State => {
495
+ if (!memberOnlyCart) return next;
496
+ if (!signedInMember()) return gated();
497
+ if (sessionGeneration() !== readUnder) { reloadForSession(); return derive({ ...next, memberOnly: true, needsSignIn: false, status: "loading", items: [] }); }
498
+ return derive({ ...next, memberOnly: true, needsSignIn: false });
499
+ };
425
500
  // 1) Instant paint from the on-device cache (offline-safe; empty on first-ever run).
426
501
  const cached = await readCachedItems();
427
502
  const base = cached.length
@@ -429,12 +504,12 @@ const svc = defineService<State, {
429
504
  : state;
430
505
  // 2) Revalidate from Wix and refresh the cache.
431
506
  try {
432
- return await refresh(state);
507
+ return landed(await refresh(state));
433
508
  } catch (error) {
434
509
  // Offline / fetch failure: keep the cached items instead of a blank error state.
435
- return cached.length
510
+ return landed(cached.length
436
511
  ? base
437
- : derive({ ...state, status: "error", errorKind: isOfflineFailure(error) ? "offline" : "server", items: [], subtotal: "", emptyText: copyParam("cart.loadErrorText", "Cart could not load."), checkoutHint: "" });
512
+ : derive({ ...state, status: "error", errorKind: isOfflineFailure(error) ? "offline" : "server", items: [], subtotal: "", emptyText: copyParam("cart.loadErrorText", "Cart could not load."), checkoutHint: "" }));
438
513
  }
439
514
  },
440
515
  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: "" }),
@@ -587,7 +662,7 @@ const svc = defineService<State, {
587
662
  cashierUrl: async () => {
588
663
  const redirect = await createRedirectSession({
589
664
  ecomCheckout: { checkoutId },
590
- callbacks: { postFlowUrl: "himalaya-himi-branded-lite://screen/himi_cart" },
665
+ callbacks: { postFlowUrl: cashierReturnUrl },
591
666
  });
592
667
  return redirect.redirectSession?.fullUrl;
593
668
  },
@@ -607,5 +682,22 @@ const svc = defineService<State, {
607
682
  },
608
683
  });
609
684
 
685
+ /** Reload until the rows on show are this session generation's. A load that coalesces into one already in flight
686
+ * (or is dropped behind a write) returns before reading, so try again once it settles (a coalesced call resolves when the load in flight completes); a few tries bound it. */
687
+ /** From `derive`: reload after the commit in progress has settled (a few promise turns later). Once per stale streak. */
688
+ let sessionReloadQueued = false;
689
+ function queueSessionReload(): void {
690
+ if (sessionReloadQueued) return;
691
+ sessionReloadQueued = true;
692
+ void Promise.resolve().then(() => undefined).then(() => undefined).then(() => { sessionReloadQueued = false; reloadForSession(); });
693
+ }
694
+ function reloadForSession(tries = 4): void {
695
+ void Promise.resolve(svc.load()).finally(() => {
696
+ if (tries > 1 && memberOnlyCart && signedInMember() && rowsGeneration !== sessionGeneration()) reloadForSession(tries - 1);
697
+ });
698
+ }
610
699
  svc.load();
700
+ // A members-only cart follows the signed-in identity: a sign-in shows the member's cart, a sign-out the gate.
701
+ // The host clock notifies at once on subscribe, which the boot load above already covers.
702
+ hostSession.subscribe(() => { if (memberOnlyCart) { void svc.dropForSession(); reloadForSession(); } });
611
703
  export { svc };
@@ -12,6 +12,32 @@ import { isPaymentSetupFailure, payCashierOrder } from "@himalaya/checkout";
12
12
  import { hostedCheckoutOpener, isHostedWorker } from "../_shared/hosted-checkout.js";
13
13
  import { formatCurrency } from "../_shared/engine-intl.js";
14
14
  import { logBi, wixErrorCode } from "../_shared/wix-bi.js";
15
+ import { hostSessionFromGlobal } from "@himalaya/iap";
16
+
17
+ /** The host's session clock (a signed-out stub on a host without one). */
18
+ const hostSession = hostSessionFromGlobal();
19
+ /** A web host has no session clock (the stub above always reads signed out): it delivers sign-in and sign-out
20
+ * through the reserved `onIdentityChange` action instead. `undefined` until it first does. Each delivery is a new
21
+ * identity, so it also bumps the generation the members-only cart's rows are checked against. */
22
+ let webSignedIn: boolean | undefined;
23
+ let webGeneration = 0;
24
+ const signedInMember = (): boolean => hostSession.current().kind === "member" || webSignedIn === true;
25
+ /** The members-only cart. Known at BOOT when the screen's bundle is the members-only entry
26
+ * (`himi-branded-lite-member-cart`, which sets the flag before this module runs), so even the boot load never
27
+ * reads a signed-out shopper's cart; also set by a load that names `memberOnly`. */
28
+ let memberOnlyCart = (globalThis as { __himiMemberOnlyCart?: boolean }).__himiMemberOnlyCart === true;
29
+ /** The session generation the rows on show were read under. A members-only cart shows rows only for the CURRENT
30
+ * generation: a member switch while a read or write is in flight never lands the previous member's rows. */
31
+ let rowsGeneration = -1;
32
+ const sessionGeneration = (): number => hostSession.current().generation + webGeneration;
33
+ const memberOnlyArg = (arg: unknown): boolean => (arg as { memberOnly?: unknown } | undefined)?.memberOnly === "1";
34
+ /** Where the in-app cashier returns after payment: this app's own scheme. Another content package on this shell
35
+ * (a Brandy site shell registers its contract's scheme) passes its own on load; only `<scheme>://screen/himi_cart`. */
36
+ let cashierReturnUrl = "himalaya-himi-branded-lite://screen/himi_cart";
37
+ function takeReturnUrl(arg: unknown): void {
38
+ const url = (arg as { returnUrl?: unknown } | undefined)?.returnUrl;
39
+ if (typeof url === "string" && /^[a-z][a-z0-9+.-]*:\/\/screen\/himi_cart$/.test(url)) cashierReturnUrl = url;
40
+ }
15
41
 
16
42
  /** Wix Stores appDefId — the vertical that owns a cart/ecom order, and therefore the
17
43
  * `appId` its cashier order is paid under. (Same constant Wix's own tooling uses.) */
@@ -50,6 +76,9 @@ function cachedUnitPrice(total: string, quantity: number): string {
50
76
  return total.replace(raw, `${grouped}${digits ? decimal + fraction : ""}`);
51
77
  }
52
78
  async function readCachedItems(): Promise<Row[]> {
79
+ // A members-only cart keeps no on-device copy: the cart entity is app-scoped, so one member's rows would show to
80
+ // the next member offline.
81
+ if (memberOnlyCart) return [];
53
82
  try {
54
83
  return ((await getAll(ENTITY)) as unknown as Row[]).map(item => {
55
84
  const quantity = Math.max(1, Math.floor(Number(item.quantity) || 1));
@@ -68,6 +97,7 @@ async function readCachedItems(): Promise<Row[]> {
68
97
  * (one removed elsewhere, or a removal whose answer was lost), so the offline paint never
69
98
  * shows a line that is gone. */
70
99
  async function writeCachedItems(rows: Row[]): Promise<void> {
100
+ if (memberOnlyCart) return;
71
101
  try {
72
102
  const keep = new Set(rows.map((r) => r.id));
73
103
  for (const old of (await getAll(ENTITY)) as unknown as Row[]) if (!keep.has(old.id)) await dbRemove(ENTITY, old.id);
@@ -143,6 +173,12 @@ interface State {
143
173
  hideContent: boolean;
144
174
  noEmpty: boolean;
145
175
  noItems: boolean;
176
+ /** A site shell serves this cart to MEMBERS only (`memberOnly` on load):
177
+ * a native visitor cart is not the website's visitor cart, so a signed-out shopper sees the sign-in gate
178
+ * (`needsSignIn`) instead of a second, separate cart. Absent in Branded Lite, where the visitor cart is native. */
179
+ memberOnly?: boolean;
180
+ needsSignIn?: boolean;
181
+ noSignIn?: boolean;
146
182
  }
147
183
 
148
184
  function itemId(arg: unknown): string {
@@ -256,6 +292,16 @@ function updateLineItemQuantity(cartId: string, lineItemId: string, quantity: nu
256
292
  }
257
293
 
258
294
  function derive(state: State): State {
295
+ // Every state a members-only cart commits passes here, a write's result included: a sign-out while a write was
296
+ // in flight (its identity reload dropped as a concurrent action) still lands on the gate, never the member's rows.
297
+ if (memberOnlyCart && !signedInMember()) {
298
+ state = { ...state, memberOnly: true, needsSignIn: true, status: "ready", errorKind: "", items: [], subtotal: "", commerceSubtotal: "", emptyText: "", checkoutHint: "" };
299
+ } else if (memberOnlyCart && rowsGeneration !== sessionGeneration() && state.items.length > 0) {
300
+ // Rows read under another member (a write's result that landed after the switch): hold a loading state, and
301
+ // reload for this member once the write has settled.
302
+ state = { ...state, memberOnly: true, needsSignIn: false, status: "loading", items: [], subtotal: "", commerceSubtotal: "", checkoutHint: "" };
303
+ queueSessionReload();
304
+ }
259
305
  let savedIds: Set<string> | null = null;
260
306
  try { savedIds = new Set(readSavedProducts().map(row => row.id)); }
261
307
  catch { /* saved storage unavailable: retain the saved flags already shown on each row */ }
@@ -291,6 +337,9 @@ function derive(state: State): State {
291
337
  noPaidToast: !state.showPaidToast,
292
338
  noCoupon: !state.appliedCode,
293
339
  subtotalLabel: copyTemplate("cart.subtotalCount", "Subtotal ({count})", { count: itemCount }),
340
+ noSignIn: !state.needsSignIn,
341
+ // Gated: no content, no empty card, no error card, no checkout footer — only the sign-in gate.
342
+ ...(state.needsSignIn ? { hideContent: true, noEmpty: true, noItems: true, isErrored: false, notErrored: true, noOfflineError: true, noServerError: true, noCheckoutHint: true } : {}),
294
343
  };
295
344
  }
296
345
 
@@ -387,7 +436,7 @@ import { withExclusiveWrites } from "../_shared/exclusive-writes.js";
387
436
  let cartPricing: IapCommerce;
388
437
  const defineService = withIapPresentation<State>({
389
438
  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"], {
390
- prepare: (action, args) => { if (action === "load") stashCopy(args[0]); },
439
+ prepare: (action, args) => { if (action === "load") { stashCopy(args[0]); if (memberOnlyArg(args[0])) memberOnlyCart = true; takeReturnUrl(args[0]); } },
391
440
  coalesce: ["load"],
392
441
  // Full cart reloads share the transaction, since they also replace rows and
393
442
  // reset promo fields. Only setPromo increments the edit revision: beginPromo's internal error reset
@@ -418,10 +467,36 @@ const svc = defineService<State, {
418
467
  increment: (state: State, arg?: unknown) => Promise<State>;
419
468
  decrement: (state: State, arg?: unknown) => Promise<State>;
420
469
  checkout: (state: State) => Promise<State>;
470
+ dropForSession: (state: State) => State;
471
+ onIdentityChange: (state: State, change?: unknown) => State;
421
472
  }>("himiStoreCart", {
422
- 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 }),
473
+ 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, memberOnly: false, needsSignIn: false, noSignIn: true }),
423
474
  actions: {
475
+ // Not a write: it runs even while one is in flight, so a member switch clears the previous member's rows AT ONCE.
476
+ dropForSession: (state) => derive(state),
477
+ // The web host's identity hook (see `webSignedIn`): a members-only cart follows it as it follows the native clock.
478
+ onIdentityChange: (state, change) => {
479
+ webSignedIn = (change as { signedIn?: unknown } | undefined)?.signedIn === true;
480
+ webGeneration++;
481
+ if (memberOnlyCart) queueSessionReload();
482
+ return derive(state);
483
+ },
424
484
  load: async (state, arg) => {
485
+ // A members-only cart (a site shell) never shows a signed-out shopper's native cart. `prepare` sets the flag
486
+ // before coalescing, so a load already in flight (the boot load) re-checks it before it lands.
487
+ if (memberOnlyArg(arg)) memberOnlyCart = true;
488
+ const gated = (): State => derive({ ...state, memberOnly: true, needsSignIn: true, status: "ready", errorKind: "", items: [], subtotal: "", commerceSubtotal: "", emptyText: "", checkoutHint: "" });
489
+ if (memberOnlyCart && !signedInMember()) return gated();
490
+ if (memberOnlyCart) state = { ...state, memberOnly: true, needsSignIn: false };
491
+ const readUnder = sessionGeneration();
492
+ // This read is for the current member: rows it derives stand until the generation moves on.
493
+ if (memberOnlyCart) rowsGeneration = readUnder;
494
+ const landed = (next: State): State => {
495
+ if (!memberOnlyCart) return next;
496
+ if (!signedInMember()) return gated();
497
+ if (sessionGeneration() !== readUnder) { reloadForSession(); return derive({ ...next, memberOnly: true, needsSignIn: false, status: "loading", items: [] }); }
498
+ return derive({ ...next, memberOnly: true, needsSignIn: false });
499
+ };
425
500
  // 1) Instant paint from the on-device cache (offline-safe; empty on first-ever run).
426
501
  const cached = await readCachedItems();
427
502
  const base = cached.length
@@ -429,12 +504,12 @@ const svc = defineService<State, {
429
504
  : state;
430
505
  // 2) Revalidate from Wix and refresh the cache.
431
506
  try {
432
- return await refresh(state);
507
+ return landed(await refresh(state));
433
508
  } catch (error) {
434
509
  // Offline / fetch failure: keep the cached items instead of a blank error state.
435
- return cached.length
510
+ return landed(cached.length
436
511
  ? base
437
- : derive({ ...state, status: "error", errorKind: isOfflineFailure(error) ? "offline" : "server", items: [], subtotal: "", emptyText: copyParam("cart.loadErrorText", "Cart could not load."), checkoutHint: "" });
512
+ : derive({ ...state, status: "error", errorKind: isOfflineFailure(error) ? "offline" : "server", items: [], subtotal: "", emptyText: copyParam("cart.loadErrorText", "Cart could not load."), checkoutHint: "" }));
438
513
  }
439
514
  },
440
515
  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: "" }),
@@ -587,7 +662,7 @@ const svc = defineService<State, {
587
662
  cashierUrl: async () => {
588
663
  const redirect = await createRedirectSession({
589
664
  ecomCheckout: { checkoutId },
590
- callbacks: { postFlowUrl: "himalaya-himi-branded-lite://screen/himi_cart" },
665
+ callbacks: { postFlowUrl: cashierReturnUrl },
591
666
  });
592
667
  return redirect.redirectSession?.fullUrl;
593
668
  },
@@ -607,5 +682,22 @@ const svc = defineService<State, {
607
682
  },
608
683
  });
609
684
 
685
+ /** Reload until the rows on show are this session generation's. A load that coalesces into one already in flight
686
+ * (or is dropped behind a write) returns before reading, so try again once it settles (a coalesced call resolves when the load in flight completes); a few tries bound it. */
687
+ /** From `derive`: reload after the commit in progress has settled (a few promise turns later). Once per stale streak. */
688
+ let sessionReloadQueued = false;
689
+ function queueSessionReload(): void {
690
+ if (sessionReloadQueued) return;
691
+ sessionReloadQueued = true;
692
+ void Promise.resolve().then(() => undefined).then(() => undefined).then(() => { sessionReloadQueued = false; reloadForSession(); });
693
+ }
694
+ function reloadForSession(tries = 4): void {
695
+ void Promise.resolve(svc.load()).finally(() => {
696
+ if (tries > 1 && memberOnlyCart && signedInMember() && rowsGeneration !== sessionGeneration()) reloadForSession(tries - 1);
697
+ });
698
+ }
610
699
  svc.load();
700
+ // A members-only cart follows the signed-in identity: a sign-in shows the member's cart, a sign-out the gate.
701
+ // The host clock notifies at once on subscribe, which the boot load above already covers.
702
+ hostSession.subscribe(() => { if (memberOnlyCart) { void svc.dropForSession(); reloadForSession(); } });
611
703
  export { svc };
@@ -9,30 +9,62 @@
9
9
  // header badges is unchanged.
10
10
 
11
11
  import { defineService } from "@himalaya/state";
12
+ import { hostSessionFromGlobal } from "@himalaya/iap";
12
13
  import { HEADER_BADGE_KEYS, headerBadges, type HeaderBadgeActionSignatures, type HeaderBadges, type HeaderBadgeState } from "../_shared/header-badges.js";
13
14
 
14
- type State = HeaderBadgeState;
15
+ /** `memberCartHidden` / `visitorCartHidden`: which of a site shell's two cart icons shows
16
+ * — the native member cart for a signed-in member, the website's cart page for anyone else. Read from
17
+ * the host session clock, the same identity the cart count and the cart screen follow. A host with no clock reads
18
+ * signed out, so it shows the website's cart. */
19
+ /** `memberCartBadge`: `cartBadge` for a signed-in member, null for anyone else, for a cart icon that opens a members-only
20
+ * cart. A visitor's own cart count is a different cart, and must not ride an icon whose tap asks them to sign in. */
21
+ type State = HeaderBadgeState & { memberCartHidden: boolean; visitorCartHidden: boolean; memberCartBadge: number | null };
22
+ const MEMBER_KEYS: ("memberCartHidden" | "visitorCartHidden" | "memberCartBadge")[] = ["memberCartHidden", "visitorCartHidden", "memberCartBadge"];
23
+ const session = hostSessionFromGlobal();
24
+ /** A web host has no session clock (the stub reads signed out): its sign-in arrives through `onIdentityChange`. */
25
+ let webSignedIn = false;
26
+ const isMember = (): boolean => session.current().kind === "member" || webSignedIn;
27
+ const memberFlags = () => { const member = isMember(); return { memberCartHidden: !member, visitorCartHidden: member }; };
28
+
29
+ /** Recomputed after every update, so a count or a session change both reach it. */
30
+ function withMemberCartBadge(s: State): State {
31
+ return { ...s, memberCartBadge: isMember() ? s.cartBadge : null };
32
+ }
15
33
 
16
34
  // State changes await native work; overlapping actions must use the preceding result.
17
35
  let stateQueue: Promise<State> | undefined;
18
36
  function updateInOrder(s: State, update: (current: State) => Promise<State>): Promise<State> {
19
37
  const previous = stateQueue ?? Promise.resolve(s);
20
- const result = previous.then(update);
38
+ const result = previous.then(update).then(withMemberCartBadge);
21
39
  stateQueue = result.catch(() => previous);
22
40
  return result;
23
41
  }
24
42
 
25
43
  const badges: HeaderBadges<State> = headerBadges<State>(updateInOrder, () => svc);
26
44
 
27
- const svc = defineService<State, HeaderBadgeActionSignatures<State>>("brandedLiteNav", {
45
+ const svc = defineService<State, HeaderBadgeActionSignatures<State> & {
46
+ syncMember: (s: State) => Promise<State>;
47
+ onIdentityChange: (s: State, change?: unknown) => Promise<State>;
48
+ }>("brandedLiteNav", {
28
49
  // Every count unavailable until the first read lands, and no failure to report.
29
- state: { notificationsBadge: null, chatBadge: null, cartBadge: null, errorText: "" },
50
+ state: { notificationsBadge: null, chatBadge: null, cartBadge: null, errorText: "", memberCartBadge: null, ...memberFlags() },
30
51
  // The counts describe THIS run (see _shared/header-badges.ts): never stored, never restored.
31
- notPersisted: HEADER_BADGE_KEYS,
32
- notHydrated: HEADER_BADGE_KEYS,
33
- actions: badges.actions,
52
+ notPersisted: [...HEADER_BADGE_KEYS, ...MEMBER_KEYS],
53
+ notHydrated: [...HEADER_BADGE_KEYS, ...MEMBER_KEYS],
54
+ actions: {
55
+ ...badges.actions,
56
+ syncMember: async (s) => updateInOrder(s, async (current) => ({ ...current, ...memberFlags() })),
57
+ // The web host's identity hook: record who is signed in BEFORE the shared piece drops and re-reads the counts,
58
+ // so the cart icons' visibility and the member count follow it as they follow the native clock.
59
+ onIdentityChange: async (s: State, change?: unknown) => {
60
+ webSignedIn = (change as { signedIn?: unknown } | undefined)?.signedIn === true;
61
+ const next = await badges.actions.onIdentityChange(s);
62
+ return updateInOrder(next, async (current) => ({ ...current, ...memberFlags() }));
63
+ },
64
+ },
34
65
  });
35
66
 
36
67
  export { svc };
37
68
 
38
69
  badges.start();
70
+ session.subscribe(() => { void svc.syncMember(); });