@wix/himalaya-cli 0.1852.0 → 0.1853.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 (149) hide show
  1. package/dist/cli.mjs +95 -32
  2. package/guides/himi-json-output.md +8 -2
  3. package/guides/one-app-section-mappings.md +1 -1
  4. package/guides/one-app-to-himi-app.md +19 -6
  5. package/package.json +2 -2
  6. package/template-icons/bare-fashion.png +0 -0
  7. package/templates/bare-fashion/README.md +52 -0
  8. package/templates/bare-fashion/config.ts +474 -0
  9. package/templates/bare-fashion/dev/index.ts +16526 -0
  10. package/templates/bare-fashion/himalaya.content.json +70 -0
  11. package/templates/bare-fashion/himalaya.template.json +18 -0
  12. package/templates/bare-fashion/icon.png +0 -0
  13. package/templates/bare-fashion/platforms.json +3 -0
  14. package/templates/bare-fashion/tier5-src/_shared/app-locale.ts +70 -0
  15. package/templates/bare-fashion/tier5-src/_shared/bare-fashion-address-book.ts +116 -0
  16. package/templates/bare-fashion/tier5-src/_shared/bare-fashion-address-countries.ts +261 -0
  17. package/templates/bare-fashion/tier5-src/_shared/bare-fashion-bag-count.ts +24 -0
  18. package/templates/bare-fashion/tier5-src/_shared/bare-fashion-categories.ts +48 -0
  19. package/templates/bare-fashion/tier5-src/_shared/bare-fashion-facets.ts +265 -0
  20. package/templates/bare-fashion/tier5-src/_shared/bare-fashion-load-error.ts +38 -0
  21. package/templates/bare-fashion/tier5-src/_shared/bare-fashion-product-card.ts +136 -0
  22. package/templates/bare-fashion/tier5-src/_shared/bare-fashion-store-options.ts +129 -0
  23. package/templates/bare-fashion/tier5-src/_shared/branded-lite-hosted.ts +282 -0
  24. package/templates/bare-fashion/tier5-src/_shared/collection-contract.ts +228 -0
  25. package/templates/bare-fashion/tier5-src/_shared/collection-query.ts +201 -0
  26. package/templates/bare-fashion/tier5-src/_shared/collection-service.ts +429 -0
  27. package/templates/bare-fashion/tier5-src/_shared/engine-intl.ts +529 -0
  28. package/templates/bare-fashion/tier5-src/_shared/himi-account.ts +209 -0
  29. package/templates/bare-fashion/tier5-src/_shared/himi-copy.ts +123 -0
  30. package/templates/bare-fashion/tier5-src/_shared/himi-layouts.ts +142 -0
  31. package/templates/bare-fashion/tier5-src/_shared/himi-store-categories.ts +108 -0
  32. package/templates/bare-fashion/tier5-src/_shared/himi-store-saved.ts +57 -0
  33. package/templates/bare-fashion/tier5-src/_shared/himi-store.ts +7 -0
  34. package/templates/bare-fashion/tier5-src/_shared/himi-text.ts +24 -0
  35. package/templates/bare-fashion/tier5-src/_shared/hosted-checkout.ts +70 -0
  36. package/templates/bare-fashion/tier5-src/_shared/live-session.ts +172 -0
  37. package/templates/bare-fashion/tier5-src/_shared/local-preferences.ts +38 -0
  38. package/templates/bare-fashion/tier5-src/_shared/member-access.ts +63 -0
  39. package/templates/bare-fashion/tier5-src/_shared/member-avatar.ts +76 -0
  40. package/templates/bare-fashion/tier5-src/_shared/member-orders.ts +8 -0
  41. package/templates/bare-fashion/tier5-src/_shared/online-actions.ts +76 -0
  42. package/templates/bare-fashion/tier5-src/_shared/owner-load-error.ts +348 -0
  43. package/templates/bare-fashion/tier5-src/himi-bare-fashion-account/index.ts +127 -0
  44. package/templates/bare-fashion/tier5-src/himi-bare-fashion-address-form/index.ts +367 -0
  45. package/templates/bare-fashion/tier5-src/himi-bare-fashion-addresses/index.ts +202 -0
  46. package/templates/bare-fashion/tier5-src/himi-bare-fashion-appearance/index.ts +73 -0
  47. package/templates/bare-fashion/tier5-src/himi-bare-fashion-cart/index.ts +540 -0
  48. package/templates/bare-fashion/tier5-src/himi-bare-fashion-collection/index.ts +111 -0
  49. package/templates/bare-fashion/tier5-src/himi-bare-fashion-home/index.ts +241 -0
  50. package/templates/bare-fashion/tier5-src/himi-bare-fashion-nav/index.ts +56 -0
  51. package/templates/bare-fashion/tier5-src/himi-bare-fashion-order/index.ts +437 -0
  52. package/templates/bare-fashion/tier5-src/himi-bare-fashion-product/index.ts +650 -0
  53. package/templates/bare-fashion/tier5-src/himi-bare-fashion-products/index.ts +142 -0
  54. package/templates/bare-fashion/tier5-src/himi-bare-fashion-saved/index.ts +45 -0
  55. package/templates/bare-fashion/tier5-src/himi-bare-fashion-search/index.ts +199 -0
  56. package/templates/bare-fashion/tier5-src/himi-bare-fashion-shop/index.ts +79 -0
  57. package/templates/bare-fashion/tier5-src/himi-bare-fashion-sign-in/index.ts +269 -0
  58. package/templates/bare-fashion/tier5-src/himi-bare-fashion-wallet/index.ts +224 -0
  59. package/templates/bare-fashion/tier5-src/himi-branded-lite-info/index.ts +209 -0
  60. package/templates/bare-fashion/tier5-src/himi-branded-lite-orders/index.ts +327 -0
  61. package/templates/bare-fashion/tier5-src/wix-spaces-collections/index.ts +48 -0
  62. package/templates/bare-fashion/tier5-src/wix-spaces-delete-account/index.ts +59 -0
  63. package/templates/bare-fashion/tier5-src/wix-spaces-view-profile/index.ts +119 -0
  64. package/templates/bare-fashion/tokens.json +348 -0
  65. package/templates/beauty-salon/tier5-src/_shared/collection-query.ts +8 -0
  66. package/templates/beauty-salon/tier5-src/_shared/collection-service.ts +7 -1
  67. package/templates/beauty-salon-owner/tier5-src/_shared/collection-query.ts +8 -0
  68. package/templates/beauty-salon-owner/tier5-src/_shared/collection-service.ts +7 -1
  69. package/templates/branded-lite/recipes/upcoming-bookings.json +118 -6
  70. package/templates/branded-lite/tier5-src/_shared/collection-query-legacy.ts +7 -0
  71. package/templates/branded-lite/tier5-src/_shared/collection-query.ts +7 -0
  72. package/templates/branded-lite/tier5-src/_shared/collection-service.ts +7 -1
  73. package/templates/branded-lite/tier5-src/_shared/events-inline-options.ts +55 -3
  74. package/templates/branded-lite/tier5-src/_shared/events-inline.ts +5 -3
  75. package/templates/branded-lite/tier5-src/_shared/upcoming-bookings-section.ts +15 -4
  76. package/templates/branded-lite/tier5-src/himi-events-list/index.ts +17 -0
  77. package/templates/brandy/tier5-src/_shared/collection-query-legacy.ts +7 -0
  78. package/templates/brandy/tier5-src/_shared/collection-query.ts +7 -0
  79. package/templates/brandy/tier5-src/_shared/collection-service.ts +7 -1
  80. package/templates/community-club/tier5-src/_shared/collection-query.ts +8 -0
  81. package/templates/community-club/tier5-src/_shared/collection-service.ts +7 -1
  82. package/templates/community-club/tier5-src/_shared/events-inline-options.ts +77 -0
  83. package/templates/community-club/tier5-src/himi-events-list/index.ts +17 -0
  84. package/templates/community-club-owner/tier5-src/_shared/collection-query.ts +8 -0
  85. package/templates/community-club-owner/tier5-src/_shared/collection-service.ts +7 -1
  86. package/templates/conference/tier5-src/_shared/collection-query.ts +8 -0
  87. package/templates/conference/tier5-src/_shared/collection-service.ts +7 -1
  88. package/templates/conference/tier5-src/_shared/events-inline-options.ts +77 -0
  89. package/templates/conference/tier5-src/himi-events-list/index.ts +17 -0
  90. package/templates/events-meetups/tier5-src/_shared/collection-query.ts +8 -0
  91. package/templates/events-meetups/tier5-src/_shared/collection-service.ts +7 -1
  92. package/templates/events-meetups/tier5-src/_shared/events-inline-options.ts +77 -0
  93. package/templates/events-meetups/tier5-src/himi-events-list/index.ts +17 -0
  94. package/templates/events-meetups-owner/tier5-src/_shared/collection-query.ts +8 -0
  95. package/templates/events-meetups-owner/tier5-src/_shared/collection-service.ts +7 -1
  96. package/templates/fitness-gym/tier5-src/_shared/collection-query.ts +8 -0
  97. package/templates/fitness-gym/tier5-src/_shared/collection-service.ts +7 -1
  98. package/templates/gym-fitness/tier5-src/_shared/collection-query.ts +8 -0
  99. package/templates/gym-fitness/tier5-src/_shared/collection-service.ts +7 -1
  100. package/templates/gym-fitness/tier5-src/_shared/events-inline-options.ts +77 -0
  101. package/templates/gym-fitness/tier5-src/himi-events-list/index.ts +17 -0
  102. package/templates/gym-fitness-owner/tier5-src/_shared/collection-query.ts +8 -0
  103. package/templates/gym-fitness-owner/tier5-src/_shared/collection-service.ts +7 -1
  104. package/templates/medical-services/tier5-src/_shared/collection-query.ts +8 -0
  105. package/templates/medical-services/tier5-src/_shared/collection-service.ts +7 -1
  106. package/templates/nonprofit-cause/tier5-src/_shared/collection-query.ts +8 -0
  107. package/templates/nonprofit-cause/tier5-src/_shared/collection-service.ts +7 -1
  108. package/templates/nonprofit-cause/tier5-src/_shared/events-inline-options.ts +77 -0
  109. package/templates/nonprofit-cause/tier5-src/himi-events-list/index.ts +17 -0
  110. package/templates/nonprofit-cause-owner/tier5-src/_shared/collection-query.ts +8 -0
  111. package/templates/nonprofit-cause-owner/tier5-src/_shared/collection-service.ts +7 -1
  112. package/templates/owner-lite/tier5-src/_shared/collection-query.ts +8 -0
  113. package/templates/owner-lite/tier5-src/_shared/collection-service.ts +7 -1
  114. package/templates/personal-fitness-trainer/tier5-src/_shared/collection-query.ts +8 -0
  115. package/templates/personal-fitness-trainer/tier5-src/_shared/collection-service.ts +7 -1
  116. package/templates/podcast-creator/tier5-src/_shared/collection-query.ts +8 -0
  117. package/templates/podcast-creator/tier5-src/_shared/collection-service.ts +7 -1
  118. package/templates/podcast-creator/tier5-src/_shared/events-inline-options.ts +77 -0
  119. package/templates/podcast-creator/tier5-src/himi-events-list/index.ts +17 -0
  120. package/templates/podcast-creator-owner/tier5-src/_shared/collection-query.ts +8 -0
  121. package/templates/podcast-creator-owner/tier5-src/_shared/collection-service.ts +7 -1
  122. package/templates/portfolio-creative/tier5-src/_shared/collection-query.ts +8 -0
  123. package/templates/portfolio-creative/tier5-src/_shared/collection-service.ts +7 -1
  124. package/templates/portfolio-creative/tier5-src/_shared/events-inline-options.ts +77 -0
  125. package/templates/portfolio-creative/tier5-src/himi-events-list/index.ts +17 -0
  126. package/templates/portfolio-creative-owner/tier5-src/_shared/collection-query.ts +8 -0
  127. package/templates/portfolio-creative-owner/tier5-src/_shared/collection-service.ts +7 -1
  128. package/templates/restaurant/tier5-src/_shared/collection-query.ts +8 -0
  129. package/templates/restaurant/tier5-src/_shared/collection-service.ts +7 -1
  130. package/templates/restaurant/tier5-src/_shared/events-inline-options.ts +77 -0
  131. package/templates/restaurant/tier5-src/himi-events-list/index.ts +17 -0
  132. package/templates/restaurant-owner/tier5-src/_shared/collection-query.ts +8 -0
  133. package/templates/restaurant-owner/tier5-src/_shared/collection-service.ts +7 -1
  134. package/templates/retail-store/tier5-src/_shared/collection-query-legacy.ts +7 -0
  135. package/templates/retail-store/tier5-src/_shared/collection-query.ts +7 -0
  136. package/templates/retail-store/tier5-src/_shared/collection-service.ts +7 -1
  137. package/templates/retail-store-owner/tier5-src/_shared/collection-query.ts +8 -0
  138. package/templates/retail-store-owner/tier5-src/_shared/collection-service.ts +7 -1
  139. package/templates/salon-spa/tier5-src/_shared/collection-query.ts +8 -0
  140. package/templates/salon-spa/tier5-src/_shared/collection-service.ts +7 -1
  141. package/templates/wholesale-store/tier5-src/_shared/collection-query-legacy.ts +7 -0
  142. package/templates/wholesale-store/tier5-src/_shared/collection-query.ts +7 -0
  143. package/templates/wholesale-store/tier5-src/_shared/collection-service.ts +7 -1
  144. package/templates/yoga-studio/tier5-src/_shared/collection-query.ts +8 -0
  145. package/templates/yoga-studio/tier5-src/_shared/collection-service.ts +7 -1
  146. package/templates/yoga-studio/tier5-src/_shared/events-inline-options.ts +77 -0
  147. package/templates/yoga-studio/tier5-src/himi-events-list/index.ts +17 -0
  148. package/templates/yoga-studio-owner/tier5-src/_shared/collection-query.ts +8 -0
  149. package/templates/yoga-studio-owner/tier5-src/_shared/collection-service.ts +7 -1
@@ -0,0 +1,209 @@
1
+ import { dispatch } from "@himalaya/dispatch";
2
+ // Relative for node resolution (see himi-store.ts note); rewritten off-repo.
3
+ import { displayName, getMyData, initials, type WixMyData } from "@himalaya/wix-users";
4
+ import { getMyMember } from "@himalaya/wix-members";
5
+ import { wixMediaUrl } from "@himalaya/wix-media";
6
+ import { formatDateMedium, formatWeekdayDateTime } from "../_shared/engine-intl.js";
7
+ import { copyParam } from "./himi-copy.js";
8
+
9
+ export interface AccountProfile {
10
+ isMember: boolean;
11
+ identityLine: string;
12
+ detailLine: string;
13
+ memberName: string;
14
+ memberEmail: string;
15
+ memberImage: string;
16
+ memberInitials: string;
17
+ hasMemberImage: boolean;
18
+ noMemberImage: boolean;
19
+ }
20
+
21
+ export interface AccountActivityRow {
22
+ id: string;
23
+ title: string;
24
+ subtitle: string;
25
+ meta: string;
26
+ status: string;
27
+ }
28
+
29
+ export function strOf(arg: unknown): string {
30
+ if (typeof arg === "string") return arg;
31
+ const a = arg as { value?: string; text?: string } | undefined;
32
+ return a?.value ?? a?.text ?? "";
33
+ }
34
+
35
+ export function titleCase(value?: string): string {
36
+ return (value || "")
37
+ .toLowerCase()
38
+ .split(/[_\s-]+/)
39
+ .filter(Boolean)
40
+ .map((part) => part[0].toUpperCase() + part.slice(1))
41
+ .join(" ");
42
+ }
43
+
44
+ export function fmtDate(value?: string): string {
45
+ if (!value) return "";
46
+ const date = new Date(value);
47
+ if (Number.isNaN(date.getTime())) return "";
48
+ return formatDateMedium(date);
49
+ }
50
+
51
+ export function fmtDateTime(value?: string): string {
52
+ if (!value) return "";
53
+ const date = new Date(value);
54
+ if (Number.isNaN(date.getTime())) return "";
55
+ return formatWeekdayDateTime(date);
56
+ }
57
+
58
+ function initialsFromName(value: string): string {
59
+ const parts = value.trim().split(/\s+/).filter(Boolean);
60
+ if (!parts.length) return "";
61
+ const first = parts[0]?.[0] ?? "";
62
+ const last = parts.length > 1 ? parts[parts.length - 1]?.[0] ?? "" : "";
63
+ return (first + last).toUpperCase();
64
+ }
65
+
66
+ function profileImage(data: WixMyData): string {
67
+ const profile = data.profile as { profileImage?: string; photo?: { url?: string }; imageUrl?: string } | undefined;
68
+ return profile?.profileImage || profile?.photo?.url || profile?.imageUrl || "";
69
+ }
70
+
71
+ function profileFromData(data: WixMyData, fallbackEmail = ""): AccountProfile {
72
+ const email = fallbackEmail || data.email || data.contactEmail || "";
73
+ const name = displayName(data) || email || "Member";
74
+ const image = profileImage(data);
75
+ return {
76
+ isMember: true,
77
+ identityLine: copyParam("account.signedIn", "Signed in"),
78
+ detailLine: email || name,
79
+ memberName: name,
80
+ memberEmail: email,
81
+ memberImage: image,
82
+ memberInitials: initials(data) || initialsFromName(name) || "M",
83
+ hasMemberImage: !!image,
84
+ noMemberImage: !image,
85
+ };
86
+ }
87
+
88
+ /** The signed-in site member's name and photo from their member record, or undefined when it
89
+ * cannot be read or names nobody (the caller then shows the email). */
90
+ async function siteMemberProfile(email: string): Promise<AccountProfile | undefined> {
91
+ try {
92
+ const member = (await getMyMember({ fieldsets: ["FULL"] }))?.member;
93
+ const name = [member?.contact?.firstName, member?.contact?.lastName].map((part) => (part ?? "").trim()).filter(Boolean).join(" ")
94
+ || (member?.profile?.nickname ?? "").trim();
95
+ if (!name) return undefined;
96
+ const image = wixMediaUrl(member?.profile?.photo?.url) || wixMediaUrl(member?.profile?.photo?.id) || "";
97
+ return {
98
+ isMember: true,
99
+ identityLine: copyParam("account.signedIn", "Signed in"),
100
+ detailLine: email || name,
101
+ memberName: name,
102
+ memberEmail: email || member?.loginEmail || "",
103
+ memberImage: image,
104
+ memberInitials: initialsFromName(name) || "M",
105
+ hasMemberImage: !!image,
106
+ noMemberImage: !image,
107
+ };
108
+ } catch {
109
+ return undefined;
110
+ }
111
+ }
112
+
113
+ export function guestProfile(detailLine: string): AccountProfile {
114
+ return {
115
+ isMember: false,
116
+ identityLine: copyParam("account.guestIdentity", "Browsing as a guest"),
117
+ detailLine,
118
+ memberName: "",
119
+ memberEmail: "",
120
+ memberImage: "",
121
+ memberInitials: "M",
122
+ hasMemberImage: false,
123
+ noMemberImage: true,
124
+ };
125
+ }
126
+
127
+ export interface MemberIdentity {
128
+ email: string;
129
+ signedIn: boolean;
130
+ /** The member's session ended on its own (not their sign-out) and they are a visitor now. */
131
+ sessionEnded: boolean;
132
+ /** That member's email, to pre-fill sign-in; "" when unknown or when `sessionEnded` is false. */
133
+ lastEmail: string;
134
+ }
135
+
136
+ const NO_IDENTITY: MemberIdentity = { email: "", signedIn: false, sessionEnded: false, lastEmail: "" };
137
+
138
+ /** `himi.wix.memberIdentity`: the member's email ("" when none is known) and whether a member is
139
+ * signed in. `signedIn` is true only when the host says so explicitly — native hosts answer it
140
+ * for a member whose email is not known yet (an injected or hosted session before `members/my`
141
+ * answers); hosts that predate it answer the email alone. `sessionEnded` / `lastEmail` come from
142
+ * native hosts only, for a visitor whose member session could not be refreshed. */
143
+ export async function memberIdentity(): Promise<MemberIdentity> {
144
+ try {
145
+ const identity = await dispatch("himi.wix.memberIdentity") as unknown;
146
+ type Answer = { email?: unknown; signedIn?: unknown; sessionEnded?: unknown; lastEmail?: unknown } | null | undefined;
147
+ const direct = identity as Answer;
148
+ const wrapped = (identity as { payload?: Answer } | null)?.payload;
149
+ const field = (key: keyof NonNullable<Answer>) => direct?.[key] ?? wrapped?.[key];
150
+ const text = (value: unknown) => (typeof value === "string" ? value : "");
151
+ const email = text(field("email"));
152
+ const signedIn = field("signedIn") === true || !!email;
153
+ const sessionEnded = !signedIn && field("sessionEnded") === true;
154
+ return { email, signedIn, sessionEnded, lastEmail: sessionEnded ? text(field("lastEmail")) : "" };
155
+ } catch {
156
+ return NO_IDENTITY;
157
+ }
158
+ }
159
+
160
+ export async function signedInEmail(): Promise<string> {
161
+ return (await memberIdentity()).email;
162
+ }
163
+
164
+ /** A signed-in member nothing names yet: signed in, with a neutral label rather than another
165
+ * member's name or the sign-in form. */
166
+ function neutralMemberProfile(): AccountProfile {
167
+ const name = copyParam("account.member", "Member");
168
+ return {
169
+ isMember: true,
170
+ identityLine: copyParam("account.signedIn", "Signed in"),
171
+ detailLine: name,
172
+ memberName: name,
173
+ memberEmail: "",
174
+ memberImage: "",
175
+ memberInitials: "M",
176
+ hasMemberImage: false,
177
+ noMemberImage: true,
178
+ };
179
+ }
180
+
181
+ export async function loadMemberProfile(guestDetailLine: string, known?: MemberIdentity): Promise<AccountProfile> {
182
+ // `himi.wix.memberIdentity` is the session source of truth. Visitor-scoped
183
+ // getMyData can still return a site/account nickname (e.g. apptestercoowner)
184
+ // after sign-out or for anonymous — never treat that as a signed-in member.
185
+ const identity = known ?? await memberIdentity();
186
+ if (!identity.signedIn) return guestProfile(guestDetailLine);
187
+ const storedEmail = identity.email;
188
+ if (!storedEmail) return (await siteMemberProfile("")) ?? neutralMemberProfile();
189
+ try {
190
+ const data = await getMyData();
191
+ return profileFromData(data, storedEmail);
192
+ } catch {
193
+ // The account profile is an owner endpoint: the web host refuses it, and a site member need
194
+ // not have one. The member's own record (the Members API) still names them.
195
+ const member = await siteMemberProfile(storedEmail);
196
+ if (member) return member;
197
+ return {
198
+ isMember: true,
199
+ identityLine: copyParam("account.signedIn", "Signed in"),
200
+ detailLine: storedEmail,
201
+ memberName: storedEmail,
202
+ memberEmail: storedEmail,
203
+ memberImage: "",
204
+ memberInitials: initialsFromName(storedEmail) || "M",
205
+ hasMemberImage: false,
206
+ noMemberImage: true,
207
+ };
208
+ }
209
+ }
@@ -0,0 +1,123 @@
1
+ // Copy-as-configuration for WORKER-emitted strings (`himi docs designing-himi-screens`,
2
+ // §"Copy is configuration"): a worker never hardcodes user-facing copy — the
3
+ // descriptor bakes the provisioned copy-pack overrides relevant to this worker
4
+ // into its onAppear action params as a `copy` JSON object (customer strings or
5
+ // source-matched stock translations, computed at descriptor-build time), and the
6
+ // worker reads every user-facing string through `copyParam(key, fallback)`.
7
+ //
8
+ // STASHED (the stashed appear-params idiom, himi-branded-lite-home): the
9
+ // param-carrying onAppear dispatch updates the stash; later arg-less calls
10
+ // (self-kick refreshes, retry buttons, pull-to-refresh) fall back to it, so
11
+ // resolution order can never drop the pack. With no pack the param is absent
12
+ // and every read returns `fallback` verbatim — routing a worker string through
13
+ // copyParam is byte-for-byte behavior-preserving.
14
+ //
15
+ // Pure + Hermes-safe (no host globals, no Node APIs; its only import is the pure `app-locale` sibling): bundled into
16
+ // every worker that emits user-facing copy, and copied verbatim into the
17
+ // generated templates' tier5-src/_shared/.
18
+
19
+ import { pluralCategory, setAppLocale, setBusinessTimeZone } from "./app-locale.js";
20
+
21
+ /** Customer strings override every read; translated stock is valid only for its
22
+ * original English fallback. Some existing keys serve more than one message. */
23
+ export type CopyPackValue = string | { source: string; translation: string };
24
+
25
+ let stashedCopy: Record<string, CopyPackValue> = Object.create(null);
26
+ /** Stock translations by the English text they replace, from the `textCopy` param. A pinned app's bake
27
+ * names each worker fallback its catalog translates by its text, because a catalog row for worker copy
28
+ * is often keyless. A key's own `copy` entry always wins over this. */
29
+ let stashedByText = new Map<string, string>();
30
+ let copyReceived = false;
31
+
32
+ /** Absorb the `copy` onAppear param (customer strings or stock translation records)
33
+ * from an action arg. Call first in every action that can receive onAppear
34
+ * params (load/refresh). Non-copy args and malformed packs are ignored — the
35
+ * stock fallbacks keep rendering. */
36
+ export function stashCopy(arg: unknown): void {
37
+ if (!arg || typeof arg !== "object") return;
38
+ // A param-carrying dispatch names the app language and business zone too (absent: the English house
39
+ // pattern, and no zone).
40
+ if ("copy" in arg || "locale" in arg || "businessTimeZone" in arg) {
41
+ setAppLocale((arg as Record<string, unknown>).locale);
42
+ setBusinessTimeZone((arg as Record<string, unknown>).businessTimeZone);
43
+ }
44
+ const text = (arg as Record<string, unknown>).textCopy;
45
+ if (typeof text === "string" && text) {
46
+ const parsed = parseTextCopy(text);
47
+ if (parsed) { stashedByText = parsed; copyReceived = true; }
48
+ }
49
+ const raw = (arg as Record<string, unknown>).copy;
50
+ if (typeof raw !== "string" || !raw) return;
51
+ try {
52
+ const parsed = JSON.parse(raw) as unknown;
53
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return;
54
+ const next: Record<string, CopyPackValue> = Object.create(null);
55
+ for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
56
+ if (typeof value === "string") next[key] = value;
57
+ else if (value && typeof value === "object" && !Array.isArray(value)) {
58
+ const row = value as Record<string, unknown>;
59
+ if (typeof row.source === "string" && typeof row.translation === "string") {
60
+ next[key] = { source: row.source, translation: row.translation };
61
+ }
62
+ }
63
+ }
64
+ stashedCopy = next;
65
+ copyReceived = true;
66
+ } catch {
67
+ // Malformed pack param — keep the stock copy rather than dying mid-action.
68
+ }
69
+ }
70
+
71
+ /** `textCopy`: a JSON object from English text to its translation. A malformed one is ignored (the
72
+ * stock copy keeps rendering); an entry that is not a non-empty string is dropped. */
73
+ function parseTextCopy(text: string): Map<string, string> | undefined {
74
+ try {
75
+ const parsed = JSON.parse(text) as unknown;
76
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
77
+ const out = new Map<string, string>();
78
+ for (const [source, translation] of Object.entries(parsed as Record<string, unknown>)) {
79
+ if (typeof translation === "string" && translation !== "") out.set(source, translation);
80
+ }
81
+ return out;
82
+ } catch {
83
+ return undefined;
84
+ }
85
+ }
86
+
87
+ /** The provisioned override for `key`, or `fallback` (the stock copy). An optional
88
+ * restored label survives only until a current copy pack arrives. */
89
+ export function copyParam(key: string, fallback: string, restoredFallback = fallback): string {
90
+ const value = stashedCopy[key];
91
+ // A disk-restored row may paint before onAppear supplies its copy pack. Keep its
92
+ // last label only before a pack arrives; even an empty current pack selects stock copy.
93
+ if (value === undefined) return stashedByText.get(fallback) ?? (copyReceived ? fallback : restoredFallback);
94
+ // A key can serve two messages: a row for another source text, or an empty one, must not hide the stock translation
95
+ // the app's catalog has for the fallback actually passed.
96
+ if (typeof value === "string") return value !== "" ? value : stashedByText.get(fallback) ?? fallback;
97
+ return value?.source === fallback && value.translation !== "" ? value.translation : stashedByText.get(fallback) ?? fallback;
98
+ }
99
+
100
+ /** Interpolate `{name}` placeholders in a (possibly overridden) template:
101
+ * `copyTemplate("plans.joinOnSite", "…join {name}.", { name })`. Unknown
102
+ * placeholders resolve to "" so a typo'd override degrades, never crashes. */
103
+ export function copyTemplate(key: string, fallback: string, values: Record<string, string | number>): string {
104
+ return copyParam(key, fallback).replace(/\{([A-Za-z0-9_]+)\}/g, (_all, name: string) =>
105
+ name in values ? String(values[name]) : "",
106
+ );
107
+ }
108
+
109
+ /** The ICU plural form worker copy uses (`{n, plural, one {# spot} other {# spots}}`). The provisioned copy may
110
+ * translate every branch without adding a second key for the singular, and a language names the branches it has:
111
+ * `=N` for an exact count, else the app language's CLDR category (`few`, `many`, `two` ...), else `other`.
112
+ * Anything that is not such a pattern is a plain template. */
113
+ export function copyPlural(key: string, fallback: string, count: number): string {
114
+ const pattern = copyParam(key, fallback);
115
+ const body = /^\{n, plural, (.*)\}$/.exec(pattern);
116
+ if (!body) return copyTemplate(key, fallback, { n: count });
117
+ const branches = new Map<string, string>();
118
+ const branch = /(=\d+|zero|one|two|few|many|other)\s*\{([^{}]*)\}/g;
119
+ for (let m = branch.exec(body[1]!); m; m = branch.exec(body[1]!)) branches.set(m[1]!, m[2]!);
120
+ const text = branches.get(`=${count}`) ?? branches.get(pluralCategory(count)) ?? branches.get("other");
121
+ if (text === undefined) return copyTemplate(key, fallback, { n: count });
122
+ return text.replace(/#/g, String(count));
123
+ }
@@ -0,0 +1,142 @@
1
+ // himi-branded-lite home Appearance — shared, host-free contract.
2
+ //
3
+ // Pure + Hermes-safe (no host globals, no Node APIs, no imports): bundled into
4
+ // BOTH the home worker and the appearance worker, and imported by the descriptor
5
+ // builders + tests. Single source of truth for the layout ids (== FragmentSlot
6
+ // case ids), the persisted-preference key both workers agree on, the per-vertical
7
+ // availability, and the resolve/recommend logic — so the two workers and the case
8
+ // set cannot drift.
9
+
10
+ /** A home layout preset id. Plain string union — the descriptor binds it via
11
+ * `$service:` and a proto-enum field would hit the strict-enum decode trap
12
+ * (RFC 0045). */
13
+ export type LayoutId =
14
+ | "classic"
15
+ | "storeFirst"
16
+ | "bookingFirst"
17
+ | "editorial"
18
+ | "hub"
19
+ | "showcase"
20
+ | "trainingFirst"
21
+ | "salonLuxe"
22
+ | "calmStudio"
23
+ | "communityPulse"
24
+ | "menuFirst"
25
+ | "eventsFirst"
26
+ | "showcaseFirst"
27
+ | "episodeFirst";
28
+
29
+ /** FragmentSlot case order === Appearance picker order. */
30
+ export const LAYOUT_IDS: readonly LayoutId[] = [
31
+ "classic",
32
+ "storeFirst",
33
+ "bookingFirst",
34
+ "editorial",
35
+ "hub",
36
+ "showcase",
37
+ "trainingFirst",
38
+ "salonLuxe",
39
+ "calmStudio",
40
+ "communityPulse",
41
+ "menuFirst",
42
+ "eventsFirst",
43
+ "showcaseFirst",
44
+ "episodeFirst",
45
+ ];
46
+
47
+ /** Rendered when nothing resolves / an unknown value arrives (also the FragmentSlot defaultCase). */
48
+ export const HARD_DEFAULT: LayoutId = "classic";
49
+
50
+ /** Storage key both workers read/write (namespaced like `himi.brandedLite.onboarded`). */
51
+ export const LAYOUT_KEY = "himi.brandedLite.homeLayout";
52
+
53
+ export function isLayoutId(x: unknown): x is LayoutId {
54
+ return typeof x === "string" && (LAYOUT_IDS as readonly string[]).includes(x);
55
+ }
56
+
57
+ /** Human label + vertical tag + optional gating vertical for the Appearance picker.
58
+ * `requiresVertical` (a plain string matching a BrandedLiteVertical) hides a
59
+ * preset when that vertical isn't installed; generic presets omit it. */
60
+ export const LAYOUT_META: Record<LayoutId, {
61
+ label: string;
62
+ tag: string;
63
+ description: string;
64
+ requiresVertical?: string;
65
+ }> = {
66
+ classic: { label: "Classic", tag: "balanced", description: "Greeting, featured products and an explore grid — the all-rounder." },
67
+ storeFirst: { label: "Storefront", tag: "store", description: "Product-forward. The catalog leads, with quick calls to action.", requiresVertical: "store" },
68
+ bookingFirst: { label: "Scheduler", tag: "booking", description: "Book-first. A prominent booking call to action up top.", requiresVertical: "bookings" },
69
+ editorial: { label: "Editorial", tag: "journal", description: "Magazine feel. A big hero and a single-column featured read.", requiresVertical: "blog" },
70
+ hub: { label: "Hub", tag: "all-in-one", description: "Compact. Every vertical up top, then a tight featured grid." },
71
+ showcase: { label: "Showcase", tag: "minimal", description: "Brand-forward. A centered hero and one clean featured strip." },
72
+ trainingFirst: { label: "Training", tag: "fitness", description: "Train-first. Weekly goal, today's classes and your coaches up top.", requiresVertical: "bookings" },
73
+ salonLuxe: { label: "Salon", tag: "beauty", description: "Elegant. Your stylists, signature treatments and a booking call to action.", requiresVertical: "bookings" },
74
+ calmStudio: { label: "Studio", tag: "wellness", description: "Serene. Today's schedule, your practice and programs at a calm pace.", requiresVertical: "bookings" },
75
+ communityPulse: { label: "Pulse", tag: "community", description: "Together. Members, announcements, events and the latest activity.", requiresVertical: "groups" },
76
+ menuFirst: { label: "Bistro", tag: "dining", description: "Menu-first. Popular dishes, hours and a reserve-a-table call to action.", requiresVertical: "restaurants" },
77
+ eventsFirst: { label: "Meetup", tag: "events", description: "Event-first. The next event up top, the full agenda and the community pulse.", requiresVertical: "events" },
78
+ // Portfolio (§ portfolio-creative): posts double as works — the blog's cover
79
+ // media is the richest anonymously-queryable image source, so the gallery
80
+ // rides the blog vertical.
81
+ showcaseFirst: { label: "Gallery", tag: "portfolio", description: "Work-forward. A full-bleed grid of your latest work leads.", requiresVertical: "blog" },
82
+ // Podcast (§ podcast-creator): posts double as episodes (cover + show notes).
83
+ episodeFirst: { label: "Show", tag: "podcast", description: "Episode-first. The latest episode up top, the full archive below.", requiresVertical: "blog" },
84
+ };
85
+
86
+ /** The presets offered for a given set of installed verticals (order preserved). */
87
+ export function availableLayouts(verticals: readonly string[]): LayoutId[] {
88
+ return LAYOUT_IDS.filter((id) => {
89
+ const req = LAYOUT_META[id].requiresVertical;
90
+ return !req || verticals.includes(req);
91
+ });
92
+ }
93
+
94
+ /** First valid id wins: user override → owner default → content recommendation → hard default. */
95
+ export function resolveLayout(input: {
96
+ userOverride?: string | null;
97
+ ownerDefault?: string | null;
98
+ recommendation?: string | null;
99
+ }): LayoutId {
100
+ for (const candidate of [input.userOverride, input.ownerDefault, input.recommendation]) {
101
+ if (isLayoutId(candidate)) return candidate;
102
+ }
103
+ return HARD_DEFAULT;
104
+ }
105
+
106
+ // ---------------------------------------------------------------------------
107
+ // App color theme. The Appearance screen lets the member pin the app to light or
108
+ // dark, or follow the device ("system"). The worker hands the choice to the host
109
+ // through the `theme.set` action, and the host applies it to the whole app (native
110
+ // chrome and SDUI tokens alike) — a worker cannot rebind tokens itself.
111
+ // ---------------------------------------------------------------------------
112
+ export type ThemeId = "system" | "light" | "dark";
113
+
114
+ /** Radio order on the Appearance screen. */
115
+ export const THEME_IDS: readonly ThemeId[] = ["system", "light", "dark"];
116
+ export const DEFAULT_THEME: ThemeId = "system";
117
+
118
+ /** Worker-side mirror of the choice, so the radios show it even where no host
119
+ * answers `theme.get` (an older binary). */
120
+ export const THEME_KEY = "himi.brandedLite.colorTheme";
121
+
122
+ export function isThemeId(x: unknown): x is ThemeId {
123
+ return typeof x === "string" && (THEME_IDS as readonly string[]).includes(x);
124
+ }
125
+
126
+ /** Content-derived default: booking intent > deep catalog > editorial (blog-forward) > balanced.
127
+ * Cheap signals only — verticals + product count are free from the home refresh;
128
+ * `upcoming` (bookings/events) is optional and defaults to 0. */
129
+ export function recommendLayout(signal: {
130
+ verticals?: readonly string[];
131
+ productCount?: number;
132
+ upcoming?: number;
133
+ }): LayoutId {
134
+ const verticals = signal.verticals ?? [];
135
+ const has = (v: string) => verticals.includes(v);
136
+ const upcoming = signal.upcoming ?? 0;
137
+ const productCount = signal.productCount ?? 0;
138
+ if (has("bookings") && upcoming > 0) return "bookingFirst";
139
+ if (has("store") && productCount >= 6) return "storeFirst";
140
+ if (has("blog") && !has("store")) return "editorial";
141
+ return "classic";
142
+ }
@@ -0,0 +1,108 @@
1
+ // Store categories for the Branded Lite Shop chip row and the Home "Shop by category"
2
+ // rail — one reader, so both list the same categories in the same order.
3
+ //
4
+ // Catalog V3 Categories first, V1 collections only when V3 THROWS (a legacy V1 site):
5
+ // a V3 success with zero rows is an empty catalogue, and V1 on a V3 site answers 428.
6
+ // Same rule as wix-spaces-collections; see the reasoning there.
7
+ import { categoryCount, categoryImage, queryCollections, queryStoreCategories, type StoreCategoriesResponse, type StoreCategory, type WixCollection } from "@himalaya/wix-stores-collections";
8
+ import { wixMediaUrl } from "@himalaya/wix-media";
9
+
10
+ export interface StoreCategoryCard {
11
+ id: string;
12
+ name: string;
13
+ image: string;
14
+ hasImage: boolean;
15
+ noImage: boolean;
16
+ subtitle?: string;
17
+ }
18
+
19
+ /** "All Products" is a Wix system collection — every product is in it, so it is
20
+ * the Shop's own "All" chip, not a category a shopper picks. */
21
+ const SYSTEM_NAMES = ["all products"];
22
+ const SYSTEM_COLLECTION_IDS = ["00000000-000000-000000-000000000001"];
23
+
24
+ function card(id: string, name: string, image: string, subtitle = ""): StoreCategoryCard {
25
+ return { id, name, image, hasImage: !!image, noImage: !image, subtitle };
26
+ }
27
+
28
+ function fromCategory(c: StoreCategory): StoreCategoryCard {
29
+ return card(c.id ?? "", (c.name ?? "").trim(), categoryImage(c), categoryCount(c));
30
+ }
31
+
32
+ function fromCollection(c: WixCollection): StoreCategoryCard {
33
+ const raw = c as unknown as { id?: string; name?: string; media?: { mainMedia?: { image?: { url?: string }; thumbnail?: { url?: string } } } };
34
+ const media = raw.media?.mainMedia;
35
+ return card(raw.id ?? "", (raw.name ?? "").trim(), wixMediaUrl(media?.image?.url ?? media?.thumbnail?.url ?? ""));
36
+ }
37
+
38
+ function visible(rows: StoreCategoryCard[], includeAllProducts = false): StoreCategoryCard[] {
39
+ const seen = new Set<string>();
40
+ return rows.filter((r) => {
41
+ if (!r.id || !r.name || (!includeAllProducts && (SYSTEM_COLLECTION_IDS.includes(r.id) || SYSTEM_NAMES.includes(r.name.toLowerCase()))) || seen.has(r.id)) return false;
42
+ seen.add(r.id);
43
+ return true;
44
+ }).map(row => {
45
+ // Counts belong to the directory opt-in; Home rails and Shop chips retain their
46
+ // established five-field card contract.
47
+ const { subtitle, ...card } = row;
48
+ return includeAllProducts ? row : card;
49
+ });
50
+ }
51
+
52
+ const PAGE_SIZE = 50;
53
+ const MAX_PAGES = 100;
54
+
55
+ async function loadLegacyCategories(includeAllProducts: boolean): Promise<StoreCategoryCard[]> {
56
+ const cards: StoreCategoryCard[] = [];
57
+ const seen = new Set<string>();
58
+ let offset = 0;
59
+ let total: number | undefined;
60
+ for (let page = 0; page < MAX_PAGES; page++) {
61
+ const r = await queryCollections({ query: { paging: { limit: PAGE_SIZE, offset } } });
62
+ const rows = r.collections ?? [];
63
+ const reportedTotal = r.totalResults ?? r.metadata?.total;
64
+ if (reportedTotal != null) total = Math.max(total ?? 0, reportedTotal);
65
+ if (!rows.length) {
66
+ if (total != null && seen.size < total) throw new Error("Category pagination is incomplete");
67
+ return visible(cards, includeAllProducts);
68
+ }
69
+ const priorCount = seen.size;
70
+ rows.forEach(row => { if (row.id) seen.add(row.id); });
71
+ if (page > 0 && seen.size === priorCount) throw new Error("Category pagination made no progress");
72
+ cards.push(...rows.filter(c => c.visible !== false).map(fromCollection));
73
+ offset += rows.length;
74
+ if (total != null ? offset >= total : rows.length < PAGE_SIZE) {
75
+ if (total != null && seen.size < total) throw new Error("Category pagination is incomplete");
76
+ return visible(cards, includeAllProducts);
77
+ }
78
+ }
79
+ throw new Error("Category pagination exceeded the page limit");
80
+ }
81
+
82
+ /** The store's browsable categories in site order. Rejects incomplete reads so callers
83
+ * can retain their last good catalog instead of invalidating a later category. */
84
+ export async function loadStoreCategories({ includeAllProducts = false }: { includeAllProducts?: boolean } = {}): Promise<StoreCategoryCard[]> {
85
+ let r: StoreCategoriesResponse;
86
+ try {
87
+ r = await queryStoreCategories(PAGE_SIZE);
88
+ } catch { return loadLegacyCategories(includeAllProducts); /* Only the initial failure can identify a legacy V1 site. */ }
89
+ const cards: StoreCategoryCard[] = [];
90
+ const cursors = new Set<string>();
91
+ const seen = new Set<string>();
92
+ let total = 0;
93
+ for (let page = 0; page < MAX_PAGES; page++) {
94
+ const categories = r.categories ?? [];
95
+ categories.forEach(c => { if (c.id) seen.add(c.id); });
96
+ total = Math.max(total, r.pagingMetadata?.total ?? 0);
97
+ cards.push(...categories.filter(c => c.visible !== false).map(fromCategory));
98
+ const next = r.pagingMetadata?.cursors?.next;
99
+ if (!next) {
100
+ if (seen.size < total) throw new Error("Category pagination is incomplete");
101
+ return visible(cards, includeAllProducts);
102
+ }
103
+ if (cursors.has(next)) throw new Error("Category pagination repeated a cursor");
104
+ cursors.add(next);
105
+ if (page + 1 < MAX_PAGES) r = await queryStoreCategories(PAGE_SIZE, next);
106
+ }
107
+ throw new Error("Category pagination exceeded the page limit");
108
+ }
@@ -0,0 +1,57 @@
1
+ // Saved products use the host's durable, app-scoped KV, shared by screen workers.
2
+ // Adapted from Hip Shop; a failed write must never claim that a save succeeded.
3
+ export interface SavedProduct {
4
+ id: string;
5
+ name: string;
6
+ price: string;
7
+ image: string;
8
+ wasPrice?: string;
9
+ swatches?: string[];
10
+ }
11
+ type StorageLike = { getItem(key: string): string | null; setItem(key: string, value: string): void };
12
+ const KEY = "himi-store:saved-products:v1";
13
+ function storage(): StorageLike {
14
+ const host = globalThis as { himalaya?: { storage?: StorageLike }; localStorage?: StorageLike };
15
+ const kv = host.himalaya?.storage ?? host.localStorage;
16
+ if (!kv) throw new Error("Saved-product storage is unavailable");
17
+ return kv;
18
+ }
19
+ export function readSavedProducts(): SavedProduct[] {
20
+ const raw = storage().getItem(KEY);
21
+ if (!raw) return [];
22
+ const parsed: unknown = JSON.parse(raw);
23
+ if (!Array.isArray(parsed)) throw new Error("Invalid saved-product data");
24
+ const rows = new Map<string, SavedProduct>();
25
+ for (const value of parsed) {
26
+ if (!value || typeof value !== "object") continue;
27
+ const row = value as Record<string, unknown>;
28
+ if (typeof row.id !== "string" || !row.id.trim() || typeof row.name !== "string") continue;
29
+ const swatches = Array.isArray(row.swatches)
30
+ ? row.swatches.filter((color): color is string => typeof color === "string" && /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(color)).slice(0, 5)
31
+ : [];
32
+ rows.set(row.id, { id: row.id, name: row.name, price: typeof row.price === "string" ? row.price : "", image: typeof row.image === "string" ? row.image : "",
33
+ ...(typeof row.wasPrice === "string" && row.wasPrice ? { wasPrice: row.wasPrice } : {}), ...(swatches.length ? { swatches } : {}) });
34
+ }
35
+ return [...rows.values()];
36
+ }
37
+ export function isProductSaved(id: string): boolean {
38
+ return readSavedProducts().some(row => row.id === id);
39
+ }
40
+ export function writeSavedProducts(rows: SavedProduct[]): void {
41
+ const kv = storage();
42
+ const value = JSON.stringify(rows);
43
+ kv.setItem(KEY, value);
44
+ // Web hosts may swallow quota/security errors. Confirm the synchronous write
45
+ // before displaying success; a missing/mismatched read is a failed save.
46
+ if (kv.getItem(KEY) !== value) throw new Error("Saved-product write did not persist");
47
+ }
48
+ export function toggleSavedProduct(product: SavedProduct): boolean {
49
+ if (!product.id.trim() || !product.name.trim()) throw new Error("No product to save");
50
+ const rows = readSavedProducts();
51
+ const saved = !rows.some(row => row.id === product.id);
52
+ writeSavedProducts(saved ? [product, ...rows] : rows.filter(row => row.id !== product.id));
53
+ return saved;
54
+ }
55
+ export function removeSavedProduct(id: string): void {
56
+ writeSavedProducts(readSavedProducts().filter(row => row.id !== id));
57
+ }
@@ -0,0 +1,7 @@
1
+ // Graduated to the SDK (SP-3): the store display helpers + v3 product query now live in
2
+ // @himalaya/wix-stores. This thin re-export keeps existing bundle imports working; new
3
+ // code should import from "@himalaya/wix-stores" directly.
4
+ // Relative so node (tests importing worker sources) resolves it too — the bare
5
+ // "@himalaya/wix-stores" name exists only in the esbuild alias map / the off-repo
6
+ // umbrella. gen-templates.mts rewrites this back to @himalaya/wix-stores off-repo.
7
+ export * from "@himalaya/wix-stores";