@wix/himalaya-cli 0.1871.0 → 0.1872.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 (180) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/app-module.d.ts +3 -0
  2. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/wix-sdk/portfolio/src/index.d.ts +19 -0
  3. package/dist/cli.mjs +89 -39
  4. package/fixtures/wix-canned.json +8 -0
  5. package/guides/release-notes.md +18 -0
  6. package/guides/sdk-reference.json +8 -1
  7. package/package.json +2 -2
  8. package/template-icons/professional-services.png +0 -0
  9. package/templates/bare-fashion/config.ts +37 -2
  10. package/templates/bare-fashion/dev/index.ts +4006 -48
  11. package/templates/bare-fashion/himalaya.content.json +15 -0
  12. package/templates/bare-fashion/tier5-src/_shared/member-account-routes.ts +56 -0
  13. package/templates/bare-fashion/tier5-src/himi-branded-lite-account-settings/blocked-members.ts +295 -0
  14. package/templates/bare-fashion/tier5-src/himi-branded-lite-account-settings/index.ts +58 -0
  15. package/templates/bare-fashion/tier5-src/himi-branded-lite-account-settings/login-info.ts +274 -0
  16. package/templates/bare-fashion/tier5-src/himi-branded-lite-account-settings/personal-info.ts +881 -0
  17. package/templates/bare-fashion/tier5-src/himi-branded-lite-account-settings/privacy.ts +139 -0
  18. package/templates/bare-fashion/tier5-src/himi-branded-lite-account-settings/shared.ts +136 -0
  19. package/templates/branded-lite/dev/index.ts +2 -1
  20. package/templates/branded-lite/tier5-src/_shared/portfolio-details.ts +70 -0
  21. package/templates/branded-lite/tier5-src/himi-branded-lite-coupons/index.ts +13 -2
  22. package/templates/branded-lite/tier5-src/himi-branded-lite-portfolio/index.ts +90 -9
  23. package/templates/branded-lite/tier5-src/himi-branded-lite-portfolio-project/index.ts +53 -4
  24. package/templates/branded-lite/tier5-src/himi-events-list/index.ts +5 -1
  25. package/templates/community-club/tier5-src/himi-events-list/index.ts +5 -1
  26. package/templates/conference/config.ts +43 -1
  27. package/templates/conference/dev/index.ts +4127 -0
  28. package/templates/conference/himalaya.content.json +18 -0
  29. package/templates/conference/tier5-src/himi-branded-lite-account-settings/blocked-members.ts +295 -0
  30. package/templates/conference/tier5-src/himi-branded-lite-account-settings/index.ts +58 -0
  31. package/templates/conference/tier5-src/himi-branded-lite-account-settings/login-info.ts +274 -0
  32. package/templates/conference/tier5-src/himi-branded-lite-account-settings/personal-info.ts +881 -0
  33. package/templates/conference/tier5-src/himi-branded-lite-account-settings/privacy.ts +139 -0
  34. package/templates/conference/tier5-src/himi-branded-lite-account-settings/shared.ts +136 -0
  35. package/templates/conference/tier5-src/himi-events-list/index.ts +5 -1
  36. package/templates/conference/tier5-src/wix-spaces-delete-account/index.ts +59 -0
  37. package/templates/events-meetups/tier5-src/himi-events-list/index.ts +5 -1
  38. package/templates/gym-fitness/tier5-src/himi-events-list/index.ts +5 -1
  39. package/templates/medical-services/config.ts +42 -0
  40. package/templates/medical-services/dev/index.ts +4136 -0
  41. package/templates/medical-services/himalaya.content.json +18 -0
  42. package/templates/medical-services/tier5-src/himi-branded-lite-account-settings/blocked-members.ts +295 -0
  43. package/templates/medical-services/tier5-src/himi-branded-lite-account-settings/index.ts +58 -0
  44. package/templates/medical-services/tier5-src/himi-branded-lite-account-settings/login-info.ts +274 -0
  45. package/templates/medical-services/tier5-src/himi-branded-lite-account-settings/personal-info.ts +881 -0
  46. package/templates/medical-services/tier5-src/himi-branded-lite-account-settings/privacy.ts +139 -0
  47. package/templates/medical-services/tier5-src/himi-branded-lite-account-settings/shared.ts +136 -0
  48. package/templates/medical-services/tier5-src/wix-spaces-delete-account/index.ts +59 -0
  49. package/templates/nonprofit-cause/tier5-src/himi-events-list/index.ts +5 -1
  50. package/templates/podcast-creator/tier5-src/himi-events-list/index.ts +5 -1
  51. package/templates/portfolio-creative/dev/index.ts +2 -1
  52. package/templates/portfolio-creative/tier5-src/_shared/portfolio-details.ts +70 -0
  53. package/templates/portfolio-creative/tier5-src/himi-branded-lite-portfolio/index.ts +90 -9
  54. package/templates/portfolio-creative/tier5-src/himi-branded-lite-portfolio-project/index.ts +53 -4
  55. package/templates/portfolio-creative/tier5-src/himi-events-list/index.ts +5 -1
  56. package/templates/professional-services/README.md +55 -0
  57. package/templates/professional-services/config.ts +436 -0
  58. package/templates/professional-services/dev/index.ts +44772 -0
  59. package/templates/professional-services/himalaya.content.json +100 -0
  60. package/templates/professional-services/himalaya.template.json +16 -0
  61. package/templates/professional-services/icon.png +0 -0
  62. package/templates/professional-services/platforms.json +1 -0
  63. package/templates/professional-services/tier5-src/_shared/app-locale.ts +70 -0
  64. package/templates/professional-services/tier5-src/_shared/booking-location.ts +147 -0
  65. package/templates/professional-services/tier5-src/_shared/booking-session.ts +224 -0
  66. package/templates/professional-services/tier5-src/_shared/branded-lite-hosted.ts +282 -0
  67. package/templates/professional-services/tier5-src/_shared/branded-load-state.ts +109 -0
  68. package/templates/professional-services/tier5-src/_shared/business-chat-copy.ts +40 -0
  69. package/templates/professional-services/tier5-src/_shared/business-chat-history.ts +51 -0
  70. package/templates/professional-services/tier5-src/_shared/business-chat-message-model.ts +177 -0
  71. package/templates/professional-services/tier5-src/_shared/business-chat-model.ts +56 -0
  72. package/templates/professional-services/tier5-src/_shared/business-chat-presenter.ts +587 -0
  73. package/templates/professional-services/tier5-src/_shared/business-chat-transport.ts +164 -0
  74. package/templates/professional-services/tier5-src/_shared/chat-live.ts +242 -0
  75. package/templates/professional-services/tier5-src/_shared/collection-contract.ts +232 -0
  76. package/templates/professional-services/tier5-src/_shared/collection-query.ts +201 -0
  77. package/templates/professional-services/tier5-src/_shared/collection-service.ts +429 -0
  78. package/templates/professional-services/tier5-src/_shared/detail-presence.ts +51 -0
  79. package/templates/professional-services/tier5-src/_shared/engine-intl.ts +538 -0
  80. package/templates/professional-services/tier5-src/_shared/event-registration.ts +86 -0
  81. package/templates/professional-services/tier5-src/_shared/events-inline-options.ts +77 -0
  82. package/templates/professional-services/tier5-src/_shared/faq-list.ts +405 -0
  83. package/templates/professional-services/tier5-src/_shared/featured-event.ts +63 -0
  84. package/templates/professional-services/tier5-src/_shared/group-member-count.ts +15 -0
  85. package/templates/professional-services/tier5-src/_shared/group-privacy.ts +14 -0
  86. package/templates/professional-services/tier5-src/_shared/guest-sign-in.ts +36 -0
  87. package/templates/professional-services/tier5-src/_shared/himi-account.ts +222 -0
  88. package/templates/professional-services/tier5-src/_shared/himi-blog-hidden.ts +66 -0
  89. package/templates/professional-services/tier5-src/_shared/himi-blog-post-row.ts +214 -0
  90. package/templates/professional-services/tier5-src/_shared/himi-blog-saved.ts +64 -0
  91. package/templates/professional-services/tier5-src/_shared/himi-booking-saved.ts +88 -0
  92. package/templates/professional-services/tier5-src/_shared/himi-bookings.ts +318 -0
  93. package/templates/professional-services/tier5-src/_shared/himi-copy.ts +123 -0
  94. package/templates/professional-services/tier5-src/_shared/himi-events.ts +92 -0
  95. package/templates/professional-services/tier5-src/_shared/himi-media.ts +33 -0
  96. package/templates/professional-services/tier5-src/_shared/himi-store.ts +7 -0
  97. package/templates/professional-services/tier5-src/_shared/himi-text.ts +24 -0
  98. package/templates/professional-services/tier5-src/_shared/host-events.ts +66 -0
  99. package/templates/professional-services/tier5-src/_shared/hosted-checkout.ts +70 -0
  100. package/templates/professional-services/tier5-src/_shared/iap-attendance-form.ts +106 -0
  101. package/templates/professional-services/tier5-src/_shared/iap-attendance-purchase.ts +235 -0
  102. package/templates/professional-services/tier5-src/_shared/iap-attendance.ts +38 -0
  103. package/templates/professional-services/tier5-src/_shared/iap-worker.ts +127 -0
  104. package/templates/professional-services/tier5-src/_shared/inbox-rooms.ts +163 -0
  105. package/templates/professional-services/tier5-src/_shared/local-preferences.ts +38 -0
  106. package/templates/professional-services/tier5-src/_shared/member-access.ts +63 -0
  107. package/templates/professional-services/tier5-src/_shared/member-account-routes.ts +56 -0
  108. package/templates/professional-services/tier5-src/_shared/member-avatar.ts +76 -0
  109. package/templates/professional-services/tier5-src/_shared/member-bookings.ts +107 -0
  110. package/templates/professional-services/tier5-src/_shared/member-read.ts +82 -0
  111. package/templates/professional-services/tier5-src/_shared/member-screen.ts +99 -0
  112. package/templates/professional-services/tier5-src/_shared/notification-target.ts +141 -0
  113. package/templates/professional-services/tier5-src/_shared/offset-page.ts +10 -0
  114. package/templates/professional-services/tier5-src/_shared/online-actions.ts +76 -0
  115. package/templates/professional-services/tier5-src/_shared/owner-load-error.ts +348 -0
  116. package/templates/professional-services/tier5-src/_shared/payment-setup.ts +6 -0
  117. package/templates/professional-services/tier5-src/_shared/portfolio-details.ts +70 -0
  118. package/templates/professional-services/tier5-src/_shared/pricing-plan-display.ts +64 -0
  119. package/templates/professional-services/tier5-src/_shared/relative-time.ts +21 -0
  120. package/templates/professional-services/tier5-src/_shared/result-snackbar.ts +26 -0
  121. package/templates/professional-services/tier5-src/_shared/rich-body.ts +78 -0
  122. package/templates/professional-services/tier5-src/_shared/rich-content-link.ts +34 -0
  123. package/templates/professional-services/tier5-src/_shared/sign-in-sheet.ts +18 -0
  124. package/templates/professional-services/tier5-src/_shared/staff-name.ts +18 -0
  125. package/templates/professional-services/tier5-src/_shared/weekly-goal.ts +111 -0
  126. package/templates/professional-services/tier5-src/_shared/wix-bi.ts +85 -0
  127. package/templates/professional-services/tier5-src/_shared/wix-member-links.ts +114 -0
  128. package/templates/professional-services/tier5-src/_shared/wix-service-price.ts +146 -0
  129. package/templates/professional-services/tier5-src/business-chat/index.ts +797 -0
  130. package/templates/professional-services/tier5-src/business-contact/index.ts +6 -0
  131. package/templates/professional-services/tier5-src/himi-blog-feed/index.ts +444 -0
  132. package/templates/professional-services/tier5-src/himi-blog-post/index.ts +1239 -0
  133. package/templates/professional-services/tier5-src/himi-booking-account/index.ts +278 -0
  134. package/templates/professional-services/tier5-src/himi-booking-bookings/index.ts +475 -0
  135. package/templates/professional-services/tier5-src/himi-booking-service/index.ts +1197 -0
  136. package/templates/professional-services/tier5-src/himi-booking-services/index.ts +795 -0
  137. package/templates/professional-services/tier5-src/himi-booking-time/index.ts +1840 -0
  138. package/templates/professional-services/tier5-src/himi-branded-lite-coupons/index.ts +96 -0
  139. package/templates/professional-services/tier5-src/himi-branded-lite-faq/index.ts +6 -0
  140. package/templates/professional-services/tier5-src/himi-branded-lite-file-share/index.ts +12 -0
  141. package/templates/professional-services/tier5-src/himi-branded-lite-group/index.ts +310 -0
  142. package/templates/professional-services/tier5-src/himi-branded-lite-group-about/index.ts +240 -0
  143. package/templates/professional-services/tier5-src/himi-branded-lite-my-groups/index.ts +237 -0
  144. package/templates/professional-services/tier5-src/himi-branded-lite-notifications/index.ts +263 -0
  145. package/templates/professional-services/tier5-src/himi-branded-lite-plans/index.ts +498 -0
  146. package/templates/professional-services/tier5-src/himi-branded-lite-portfolio/index.ts +136 -0
  147. package/templates/professional-services/tier5-src/himi-branded-lite-portfolio-project/index.ts +198 -0
  148. package/templates/professional-services/tier5-src/himi-events-detail/index.ts +1306 -0
  149. package/templates/professional-services/tier5-src/himi-events-list/index.ts +171 -0
  150. package/templates/professional-services/tier5-src/himi-events-my-events/index.ts +227 -0
  151. package/templates/professional-services/tier5-src/himi-events-rsvp/index.ts +230 -0
  152. package/templates/professional-services/tier5-src/himi-professional-services-community/index.ts +318 -0
  153. package/templates/professional-services/tier5-src/himi-professional-services-home/index.ts +772 -0
  154. package/templates/professional-services/tier5-src/himi-store-account/index.ts +1514 -0
  155. package/templates/professional-services/tier5-src/wix-spaces-coupon-detail/index.ts +43 -0
  156. package/templates/professional-services/tier5-src/wix-spaces-my-subscriptions/index.ts +89 -0
  157. package/templates/professional-services/tier5-src/wix-spaces-subscription-detail/index.ts +139 -0
  158. package/templates/professional-services/tokens.json +456 -0
  159. package/templates/restaurant/tier5-src/himi-events-list/index.ts +5 -1
  160. package/templates/salon-spa/config.ts +42 -0
  161. package/templates/salon-spa/dev/index.ts +4136 -0
  162. package/templates/salon-spa/himalaya.content.json +18 -0
  163. package/templates/salon-spa/tier5-src/himi-branded-lite-account-settings/blocked-members.ts +295 -0
  164. package/templates/salon-spa/tier5-src/himi-branded-lite-account-settings/index.ts +58 -0
  165. package/templates/salon-spa/tier5-src/himi-branded-lite-account-settings/login-info.ts +274 -0
  166. package/templates/salon-spa/tier5-src/himi-branded-lite-account-settings/personal-info.ts +881 -0
  167. package/templates/salon-spa/tier5-src/himi-branded-lite-account-settings/privacy.ts +139 -0
  168. package/templates/salon-spa/tier5-src/himi-branded-lite-account-settings/shared.ts +136 -0
  169. package/templates/salon-spa/tier5-src/wix-spaces-delete-account/index.ts +59 -0
  170. package/templates/wholesale-store/config.ts +43 -1
  171. package/templates/wholesale-store/dev/index.ts +4136 -0
  172. package/templates/wholesale-store/himalaya.content.json +18 -0
  173. package/templates/wholesale-store/tier5-src/himi-branded-lite-account-settings/blocked-members.ts +295 -0
  174. package/templates/wholesale-store/tier5-src/himi-branded-lite-account-settings/index.ts +58 -0
  175. package/templates/wholesale-store/tier5-src/himi-branded-lite-account-settings/login-info.ts +274 -0
  176. package/templates/wholesale-store/tier5-src/himi-branded-lite-account-settings/personal-info.ts +881 -0
  177. package/templates/wholesale-store/tier5-src/himi-branded-lite-account-settings/privacy.ts +139 -0
  178. package/templates/wholesale-store/tier5-src/himi-branded-lite-account-settings/shared.ts +136 -0
  179. package/templates/wholesale-store/tier5-src/wix-spaces-delete-account/index.ts +59 -0
  180. package/templates/yoga-studio/tier5-src/himi-events-list/index.ts +5 -1
@@ -0,0 +1,88 @@
1
+ // Saved (favorite) booking services use the host's durable, app-scoped KV, shared by every
2
+ // screen worker — the service detail toggles a row (himi-booking-service `toggleSaved`), the
3
+ // Favorites list reads them (himi-booking-saved). Same model as _shared/himi-store-saved.ts: a
4
+ // failed write must never claim that a save succeeded.
5
+ export interface SavedService {
6
+ id: string;
7
+ name: string;
8
+ /** The price line as the detail showed it ("$250"), kept so the list paints offline. */
9
+ price: string;
10
+ /** The duration line ("1 hr"). */
11
+ duration: string;
12
+ image: string;
13
+ category: string;
14
+ /** A course: the list's Book passes `course` to the time screen, which then refuses a course
15
+ * whose record failed to load instead of offering its sessions one by one. */
16
+ course?: boolean;
17
+ }
18
+ type StorageLike = { getItem(key: string): string | null; setItem(key: string, value: string): void };
19
+ type Host = { himalaya?: { storage?: StorageLike; input?: Record<string, unknown> }; localStorage?: StorageLike };
20
+ const BASE = "himi-booking:saved-services:v1";
21
+ function storage(): StorageLike {
22
+ const host = globalThis as Host;
23
+ const kv = host.himalaya?.storage ?? host.localStorage;
24
+ if (!kv) throw new Error("Saved-service storage is unavailable");
25
+ return kv;
26
+ }
27
+ const validPart = (value: unknown): value is string => typeof value === "string" && /^[A-Za-z0-9_.:-]{1,128}$/.test(value) && value !== "default";
28
+ /** Saves belong to whoever made them. A signed-in member's live under the host's authenticated
29
+ * account + business — the partition collection preferences use, so a second member on the same
30
+ * device never sees them; a visitor's live on the device. A member's partition, read for the
31
+ * first time, takes the visitor's saves on this device (signing in carries them, like a cart),
32
+ * once — the device list is then emptied. */
33
+ function storeKey(kv: StorageLike): string {
34
+ const input = (globalThis as Host).himalaya?.input;
35
+ const account = input?.__himiPreferenceAccount, business = input?.__himiPreferenceBusiness;
36
+ if (!validPart(account) || !validPart(business)) return BASE;
37
+ const key = `${BASE}.${account}.${encodeURIComponent(business)}`;
38
+ if (kv.getItem(key) === null) {
39
+ const visitor = kv.getItem(BASE);
40
+ if (visitor !== null) {
41
+ kv.setItem(key, visitor);
42
+ // Empty the device list only once the member's copy is confirmed: a web host may swallow a
43
+ // failed write, and clearing then would lose the visitor's saves.
44
+ if (kv.getItem(key) === visitor) kv.setItem(BASE, "[]");
45
+ }
46
+ }
47
+ return key;
48
+ }
49
+ const str = (value: unknown): string => (typeof value === "string" ? value : "");
50
+ export function readSavedServices(): SavedService[] {
51
+ const kv = storage();
52
+ const raw = kv.getItem(storeKey(kv));
53
+ if (!raw) return [];
54
+ const parsed: unknown = JSON.parse(raw);
55
+ if (!Array.isArray(parsed)) throw new Error("Invalid saved-service data");
56
+ const rows = new Map<string, SavedService>();
57
+ for (const value of parsed) {
58
+ if (!value || typeof value !== "object") continue;
59
+ const row = value as Record<string, unknown>;
60
+ if (typeof row.id !== "string" || !row.id.trim() || typeof row.name !== "string") continue;
61
+ rows.set(row.id, { id: row.id, name: row.name, price: str(row.price), duration: str(row.duration), image: str(row.image), category: str(row.category), ...(row.course === true ? { course: true } : {}) });
62
+ }
63
+ return [...rows.values()];
64
+ }
65
+
66
+ export function isServiceSaved(id: string): boolean {
67
+ return readSavedServices().some(row => row.id === id);
68
+ }
69
+ export function writeSavedServices(rows: SavedService[]): void {
70
+ const kv = storage();
71
+ const key = storeKey(kv);
72
+ const value = JSON.stringify(rows);
73
+ kv.setItem(key, value);
74
+ // Web hosts may swallow quota/security errors. Confirm the synchronous write
75
+ // before displaying success; a missing/mismatched read is a failed save.
76
+ if (kv.getItem(key) !== value) throw new Error("Saved-service write did not persist");
77
+ }
78
+ /** Save or unsave; returns the new saved state. The newest save is listed first. */
79
+ export function toggleSavedService(service: SavedService): boolean {
80
+ if (!service.id.trim() || !service.name.trim()) throw new Error("No service to save");
81
+ const rows = readSavedServices();
82
+ const saved = !rows.some(row => row.id === service.id);
83
+ writeSavedServices(saved ? [service, ...rows] : rows.filter(row => row.id !== service.id));
84
+ return saved;
85
+ }
86
+ export function removeSavedService(id: string): void {
87
+ writeSavedServices(readSavedServices().filter(row => row.id !== id));
88
+ }
@@ -0,0 +1,318 @@
1
+ // Shared Wix Bookings shaping for himi workers (branded-lite `bookings`
2
+ // vertical): defensive extraction where the LIVE services payload drifts from
3
+ // the generated client's types. Used by BOTH the services-list worker
4
+ // (himi_services rows) and the service-detail worker so the two screens agree
5
+ // on one shape (the himi-restaurants.ts pattern).
6
+
7
+ /** Human-readable category name. The live services payload carries `category`
8
+ * as a STRUCTURED object (`{ id, name, sortOrder }`) while the generated
9
+ * client types it as a string — joined raw it rendered
10
+ * "[object Object] · 1 hr · $111" in the services rows (production sweep R3).
11
+ * Extract the name member; an id-only/unrecognizable shape yields "" so the
12
+ * caller omits the segment instead of stringifying the object. */
13
+ export function categoryName(value: unknown): string {
14
+ if (typeof value === "string") return value.trim();
15
+ if (!value || typeof value !== "object") return "";
16
+ const name = (value as { name?: unknown }).name;
17
+ return typeof name === "string" ? name.trim() : "";
18
+ }
19
+
20
+ import { businessTimeZone } from "./app-locale.js";
21
+ import { formatDateMedium, formatMonthDay, zoneOffsetAt } from "./engine-intl.js";
22
+ import { formatServiceMoney, formatServicePrice, serviceCurrency } from "./wix-service-price.js";
23
+
24
+ const HAS_OFFSET = /(?:Z|[+-]\d{2}:?\d{2})$/i;
25
+ const LOCAL_TIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?/;
26
+
27
+ /** The instant (ms) a slot starts. Wix may list a slot's `startDate` as a LOCAL wall time with its
28
+ * `timezone` beside it ("2026-11-02T18:30:00" in America/New_York is 23:30Z); a bare `Date.parse`
29
+ * would read that in the device's zone. So a local time is placed in the slot's own zone when this
30
+ * engine has Intl and knows the zone, and read in the device's zone only when it cannot be. */
31
+ export function slotStartInstant(slot: { startDate?: string; timezone?: unknown }): number {
32
+ const start = slot.startDate ?? "";
33
+ if (!start) return NaN;
34
+ const local = LOCAL_TIME.exec(start);
35
+ if (HAS_OFFSET.test(start) || !local || typeof slot.timezone !== "string" || !slot.timezone) return Date.parse(start);
36
+ const wall = Date.UTC(+local[1], +local[2] - 1, +local[3], +local[4], +local[5], +(local[6] ?? 0));
37
+ const offset = zoneOffsetAt(wall, slot.timezone);
38
+ if (!Number.isFinite(offset)) return Date.parse(start);
39
+ // Once more at the corrected instant, so a wall time beside a DST change lands on the right side.
40
+ const again = zoneOffsetAt(wall - offset, slot.timezone);
41
+ return wall - (Number.isFinite(again) ? again : offset);
42
+ }
43
+
44
+ /** `himi_time` reads the next two weeks. A host's `start` past them (an Agenda session weeks
45
+ * ahead) is read on its own — that session's local day only, never everything up to it — so it
46
+ * can be preselected while each read stays bounded. `undefined` when the start is inside the two
47
+ * weeks. */
48
+ export function availabilityBeyond(now: Date, start = ""): { from: Date; until: Date } | undefined {
49
+ const end = now.getTime() + 14 * 86_400_000;
50
+ const at = start ? Date.parse(start) : NaN;
51
+ if (!Number.isFinite(at) || at < end) return undefined;
52
+ const d = new Date(at);
53
+ const dayStart = new Date(d.getFullYear(), d.getMonth(), d.getDate());
54
+ // Never back into the two weeks already read: a slot in both would be listed twice.
55
+ return { from: new Date(Math.max(dayStart.getTime(), end)), until: new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1) };
56
+ }
57
+
58
+ /** The slot a host asked to open at (`himi_time` input `start`, an ISO 8601 instant): the id of the
59
+ * slot that starts at that same instant, or "" when none does (taken since, or out of the window).
60
+ * Compared as instants, so `…T16:30:00Z` finds a slot listed as `…T18:30:00+02:00`, or as a local
61
+ * `…T18:30:00` beside `timezone: "Asia/Jerusalem"`. */
62
+ export function slotIdAt(slots: Iterable<[string, { startDate?: string; timezone?: unknown }]>, start: string): string {
63
+ const at = start ? Date.parse(start) : NaN;
64
+ if (!Number.isFinite(at)) return "";
65
+ for (const [id, slot] of slots) {
66
+ if (slotStartInstant(slot) === at) return id;
67
+ }
68
+ return "";
69
+ }
70
+
71
+ // ---- Courses ----------------------------------------------------------------------
72
+ // One answer for the service screen's course button and the time screen's course booking, so
73
+ // the button never offers a course that the booking step then refuses.
74
+
75
+ type CoursePolicyShape = {
76
+ /** `timeZone`: the business's IANA zone, for a session time Wix lists as a bare local wall time. */
77
+ schedule?: { id?: string; firstSessionStart?: string; lastSessionEnd?: string; timeZone?: string };
78
+ bookingPolicy?: {
79
+ bookAfterStartPolicy?: { enabled?: boolean };
80
+ limitEarlyBookingPolicy?: { enabled?: boolean; earliestBookingInMinutes?: number };
81
+ limitLateBookingPolicy?: { enabled?: boolean; latestBookingInMinutes?: number };
82
+ };
83
+ };
84
+
85
+ /** A bare local wall time placed in `timeZone`, as an instant (ms). NaN when the value is not a bare local
86
+ * time, has an impossible calendar day, or the engine does not know the zone. */
87
+ function placedInstant(value: string, timeZone: string | undefined): number {
88
+ const local = LOCAL_TIME.exec(value);
89
+ if (HAS_OFFSET.test(value) || !local || !timeZone || !validDate(value)) return NaN;
90
+ const wall = Date.UTC(+local[1], +local[2] - 1, +local[3], +local[4], +local[5], +(local[6] ?? 0));
91
+ const offset = zoneOffsetAt(wall, timeZone);
92
+ if (!Number.isFinite(offset)) return NaN;
93
+ // Once more at the corrected instant, so a wall time beside a DST change lands on the right side.
94
+ const again = zoneOffsetAt(wall - offset, timeZone);
95
+ return wall - (Number.isFinite(again) ? again : offset);
96
+ }
97
+
98
+ /** The zone that places a course's bare local session times: the schedule's own, else the app's
99
+ * provisioned business zone. "" when there is none: a zone is never guessed. */
100
+ const courseZone = (schedule: { timeZone?: string } | undefined): string => schedule?.timeZone || businessTimeZone();
101
+
102
+ /** The instant (ms) of a course session time, for the "Ended" label. A time with an offset is exact. A
103
+ * bare local wall time is the BUSINESS's wall time, so it is placed in its zone — never in the device's,
104
+ * which would present another zone's clock as a confirmed instant. No zone, a date-only value, an
105
+ * impossible calendar day or an engine that does not know the zone: unknown (NaN). */
106
+ function sessionInstant(value: string, timeZone: string | undefined): number {
107
+ return HAS_OFFSET.test(value) ? validDate(value)?.getTime() ?? NaN : placedInstant(value, timeZone);
108
+ }
109
+
110
+ /** The same instant for the booking rules (window, read range): a bare local time the business zone can
111
+ * place is placed there, so the list label, the service screen and the time screen agree. Everything else
112
+ * keeps the read they always had (`Date.parse`), so an app with no provisioned zone is unchanged. */
113
+ function courseInstant(value: string | undefined, timeZone: string | undefined): number {
114
+ const text = value ?? "";
115
+ const placed = placedInstant(text, timeZone);
116
+ return Number.isFinite(placed) ? placed : Date.parse(text);
117
+ }
118
+
119
+ /** A completed course, independent of whether bookings are currently allowed. Missing,
120
+ * invalid or reversed dates are unknown, never evidence that a course has ended. A session time
121
+ * without an offset counts only when the schedule names the business's `timeZone`. */
122
+ export function courseHasEnded(service: CoursePolicyShape, now: number): boolean {
123
+ const zone = courseZone(service.schedule);
124
+ const first = sessionInstant(service.schedule?.firstSessionStart ?? "", zone);
125
+ const last = sessionInstant(service.schedule?.lastSessionEnd ?? "", zone);
126
+ return Number.isFinite(now) && Number.isFinite(first) && Number.isFinite(last) && first <= last && last <= now;
127
+ }
128
+
129
+ /** Does this course schedule hold a session time that is a bare local wall time, which only the
130
+ * business's zone can place? A caller reads the zone only when this is true. */
131
+ export function courseNeedsZone(schedule: { firstSessionStart?: string; lastSessionEnd?: string } | undefined): boolean {
132
+ return [schedule?.firstSessionStart, schedule?.lastSessionEnd].some((value) => !!value && !HAS_OFFSET.test(value) && LOCAL_TIME.test(value));
133
+ }
134
+
135
+ /** Whether the business takes course bookings at `now` (ms): the course has not ended, has not
136
+ * started (unless the policy lets people join late), and `now` is inside its booking window —
137
+ * which the early and late limits count from the first session. */
138
+ export function courseWindowOpen(service: CoursePolicyShape, now: number): boolean {
139
+ const zone = courseZone(service.schedule);
140
+ const first = courseInstant(service.schedule?.firstSessionStart, zone);
141
+ const last = courseInstant(service.schedule?.lastSessionEnd, zone);
142
+ if (!Number.isFinite(first) || !Number.isFinite(last) || last <= now) return false;
143
+ const policy = service.bookingPolicy;
144
+ if (first < now && policy?.bookAfterStartPolicy?.enabled !== true) return false;
145
+ const early = policy?.limitEarlyBookingPolicy;
146
+ if (early?.enabled && typeof early.earliestBookingInMinutes === "number" && now < first - early.earliestBookingInMinutes * 60_000) return false;
147
+ const late = policy?.limitLateBookingPolicy;
148
+ if (late?.enabled && typeof late.latestBookingInMinutes === "number" && now > first - late.latestBookingInMinutes * 60_000) return false;
149
+ return true;
150
+ }
151
+
152
+ /** How far ahead a course is read: the whole remaining course, up to a year. Both screens read the
153
+ * same sessions — from the later of its first session and now — so the service screen never
154
+ * offers a course that the booking step then refuses on a session the first did not read. */
155
+ export const COURSE_READ_DAYS = 366;
156
+ const DAY = 86_400_000;
157
+
158
+ /** The 14-day availability windows covering a course's remaining sessions, and whether they reach
159
+ * its last session (`complete`) and start at its first (`fromFirst`, so a count is the whole
160
+ * course). Empty when the course has no usable dates or has ended. */
161
+ export function courseReadWindows(service: CoursePolicyShape, now: number, chunkDays = 14): { windows: Array<[number, number]>; complete: boolean; fromFirst: boolean } {
162
+ const zone = courseZone(service.schedule);
163
+ const first = courseInstant(service.schedule?.firstSessionStart, zone);
164
+ const last = courseInstant(service.schedule?.lastSessionEnd, zone);
165
+ if (!Number.isFinite(first) || !Number.isFinite(last)) return { windows: [], complete: false, fromFirst: false };
166
+ const from = Math.max(first, now);
167
+ const courseEnd = last + DAY;
168
+ const until = Math.min(courseEnd, from + COURSE_READ_DAYS * DAY);
169
+ const windows: Array<[number, number]> = [];
170
+ for (let at = from; at < until; at += chunkDays * DAY) windows.push([at, Math.min(until, at + chunkDays * DAY)]);
171
+ return { windows, complete: courseEnd <= until, fromFirst: from === first };
172
+ }
173
+
174
+ type CourseEntryShape = { slot?: { startDate?: string; timezone?: unknown }; bookable?: boolean; openSpots?: number };
175
+
176
+ /** A course across EVERY upcoming session read: a customer books all of them at once, so the
177
+ * smallest open count is the course's, and one session that cannot be booked closes it. A start
178
+ * is read in the session's own zone (`slotStartInstant`). `found` is false when no upcoming
179
+ * session came back: both screens then treat the course as not bookable. So is a course whose
180
+ * read did not reach its last session (`readComplete`, from `courseReadWindows`): a session
181
+ * past the year read may be full, and the course is booked whole. */
182
+ export function courseSessionsAvailability(entries: readonly CourseEntryShape[], now: number, readComplete = true): { found: boolean; spots: number | undefined; bookable: boolean } {
183
+ const upcoming = entries.filter((entry) => {
184
+ const start = entry.slot ? slotStartInstant(entry.slot as { startDate?: string; timezone?: unknown }) : NaN;
185
+ return Number.isFinite(start) && start >= now;
186
+ });
187
+ if (!upcoming.length) return { found: false, spots: undefined, bookable: false };
188
+ const counts = upcoming.map((entry) => entry.openSpots).filter((n): n is number => typeof n === "number" && Number.isFinite(n) && n >= 0);
189
+ const spots = counts.length ? Math.min(...counts) : undefined;
190
+ return { found: true, spots, bookable: readComplete && upcoming.every((entry) => entry.bookable !== false) && spots !== 0 };
191
+ }
192
+
193
+ // ---- Price, duration and course dates ------------------------------------------------
194
+ // One answer for the services list and the service screen, so a row and the screen it opens
195
+ // say the same price and the same length. Each screen reads its own copy keys: the caller
196
+ // passes a `BookingLabel` reader bound to its prefix ("service." on the service screen,
197
+ // "services." on the list).
198
+
199
+ /** Reads one copy line by its key suffix ("priceFree", "days"). `values` fills {placeholders}. */
200
+ export type BookingLabel = (key: string, fallback: string, values?: Record<string, string | number>) => string;
201
+
202
+ type PricedServiceShape = {
203
+ type?: string;
204
+ duration?: unknown;
205
+ payment?: {
206
+ rateType?: unknown;
207
+ fixed?: { price?: unknown };
208
+ varied?: { minPrice?: unknown; defaultPrice?: unknown };
209
+ custom?: { description?: unknown };
210
+ };
211
+ schedule?: {
212
+ firstSessionStart?: string;
213
+ lastSessionEnd?: string;
214
+ availabilityConstraints?: {
215
+ sessionDurations?: unknown[];
216
+ durations?: Array<{ minutes?: unknown } | undefined>;
217
+ durationRange?: {
218
+ hourOptions?: { minDurationInMinutes?: unknown; maxDurationInMinutes?: unknown };
219
+ dayOptions?: { minDurationInDays?: unknown; maxDurationInDays?: unknown };
220
+ };
221
+ };
222
+ };
223
+ };
224
+
225
+ function trimmed(value: unknown): string {
226
+ return typeof value === "string" ? value.trim() : "";
227
+ }
228
+
229
+ function finiteNumber(value: unknown): number | undefined {
230
+ if (typeof value === "number") return Number.isFinite(value) ? value : undefined;
231
+ if (typeof value === "string" && value.trim()) {
232
+ const n = Number(value);
233
+ return Number.isNaN(n) ? undefined : n;
234
+ }
235
+ return undefined;
236
+ }
237
+
238
+ export interface ServicePriceLine { text: string; unit: string; isText: boolean }
239
+
240
+ /** The price line by rate type. FIXED → the price, no cents on a whole amount; VARIED →
241
+ * "From {price}"; CUSTOM → the owner's description, no unit; NO_FEE → "Free", no unit. */
242
+ export function servicePriceLine(service: PricedServiceShape, label: BookingLabel): ServicePriceLine {
243
+ const payment = service.payment ?? {};
244
+ const rate = trimmed(payment.rateType).toUpperCase();
245
+ const currency = serviceCurrency(service);
246
+ const unit = service.type === "COURSE"
247
+ ? label("unitParticipant", "per participant")
248
+ : label("unitSession", "per session");
249
+ if (rate === "NO_FEE") return { text: label("priceFree", "Free"), unit: "", isText: false };
250
+ if (rate === "CUSTOM") return { text: trimmed(payment.custom?.description), unit: "", isText: true };
251
+ if (rate === "VARIED") {
252
+ const from = formatServiceMoney(payment.varied?.minPrice, currency) || formatServiceMoney(payment.varied?.defaultPrice, currency);
253
+ return { text: from ? label("priceFrom", "From {price}", { price: from }) : "", unit: from ? unit : "", isText: false };
254
+ }
255
+ // FIXED, or a legacy payload with no rate type.
256
+ const text = formatServiceMoney(payment.fixed?.price, currency) || formatServicePrice(service);
257
+ return { text, unit: text ? unit : "", isText: false };
258
+ }
259
+
260
+ function minutesText(minutes: number): string {
261
+ if (minutes < 60) return `${minutes} min`;
262
+ const hours = Math.floor(minutes / 60);
263
+ const rest = minutes % 60;
264
+ return rest ? `${hours} hr ${rest} min` : `${hours} hr`;
265
+ }
266
+
267
+ /** "45 min", "1 hr 30 min"; a service with several lengths, or a flexible range the
268
+ * customer picks from: "30 min - 1 hr", "1 day - 3 days". "" when the record has none. */
269
+ export function serviceDurationText(service: PricedServiceShape, label: BookingLabel): string {
270
+ const constraints = service.schedule?.availabilityConstraints;
271
+ const positive = (values: unknown[]) => values.map(finiteNumber).filter((n): n is number => n != null && n > 0);
272
+ const listed = positive([
273
+ ...(constraints?.sessionDurations ?? []),
274
+ ...(constraints?.durations ?? []).map((d) => d?.minutes),
275
+ ]);
276
+ const hours = constraints?.durationRange?.hourOptions;
277
+ const range = positive([hours?.minDurationInMinutes, hours?.maxDurationInMinutes]);
278
+ const days = constraints?.durationRange?.dayOptions;
279
+ const dayRange = positive([days?.minDurationInDays, days?.maxDurationInDays]);
280
+ if (!listed.length && !range.length && dayRange.length) {
281
+ const dayText = (n: number) => (n === 1 ? label("day", "1 day") : label("days", "{n} days", { n }));
282
+ const first = Math.min(...dayRange);
283
+ const last = Math.max(...dayRange);
284
+ return first === last ? dayText(first) : `${dayText(first)} - ${dayText(last)}`;
285
+ }
286
+ const minutes = listed.length ? listed : range.length ? range : positive([service.duration]);
287
+ if (!minutes.length) return "";
288
+ const min = Math.min(...minutes);
289
+ const max = Math.max(...minutes);
290
+ return min === max ? minutesText(min) : `${minutesText(min)} - ${minutesText(max)}`;
291
+ }
292
+
293
+ function validDate(value: string | undefined): Date | undefined {
294
+ if (!value) return undefined;
295
+ const parts = /^(\d{4})-(\d{2})-(\d{2})(?:T|$)/i.exec(value);
296
+ if (!parts) return undefined;
297
+ const year = Number(parts[1]), month = Number(parts[2]) - 1, day = Number(parts[3]);
298
+ // Date accepts February 30 by rolling into March. Check the stated calendar day first;
299
+ // setUTCFullYear also preserves years 0–99, which Date.UTC would reinterpret as 1900–1999.
300
+ const calendar = new Date(0);
301
+ calendar.setUTCFullYear(year, month, day);
302
+ if (calendar.getUTCFullYear() !== year || calendar.getUTCMonth() !== month || calendar.getUTCDate() !== day) return undefined;
303
+ const date = new Date(value);
304
+ return Number.isFinite(date.getTime()) ? date : undefined;
305
+ }
306
+
307
+ function shortDate(date: Date, year: boolean): string {
308
+ return year ? formatDateMedium(date) : formatMonthDay(date);
309
+ }
310
+
311
+ /** A course's dates, "Nov 3 – Dec 15, 2026" (the year on the first date only when the two
312
+ * differ). "" when the record has no first or last session. */
313
+ export function courseDatesText(service: PricedServiceShape): string {
314
+ const first = validDate(service.schedule?.firstSessionStart);
315
+ const last = validDate(service.schedule?.lastSessionEnd);
316
+ if (!first || !last) return "";
317
+ return `${shortDate(first, first.getFullYear() !== last.getFullYear())} – ${shortDate(last, true)}`;
318
+ }
@@ -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,92 @@
1
+ // Shared himi-events helpers for the app worker bundles.
2
+ //
3
+ // The PURE event display normalizers (normalizeEvent, eventLocation, eventWhen, …)
4
+ // graduated to the SDK (SP-3) — re-exported below so existing bundle imports keep
5
+ // working; new code should import them from "@himalaya/wix-events" directly.
6
+ // Relative for node resolution (see himi-store.ts note); rewritten off-repo.
7
+ export * from "@himalaya/wix-events";
8
+
9
+ // Host-coupled RSVP-persistence + screen-input helpers stay HERE (not in the published
10
+ // @himalaya/wix-events SDK): they read the worker-runtime host globals
11
+ // (`globalThis.himalaya.storage` / `.input`), which a published, brand-scrubbed SDK
12
+ // package must not reference. The himi-events-* bundles import these from this module.
13
+
14
+ import { eventEndMillis, eventStartMillis, type WixEvent } from "@himalaya/wix-events";
15
+
16
+ /** The event's own times, kept on the row the `events` local-db store holds (written by the list AND the detail), so a
17
+ * reader can tell at READ time whether the event has finished. The row's `statusLabel` / `isPast` were decided when the
18
+ * row was written, and the label is localized copy (`events.past`): a row stored the day before its event ended still
19
+ * says "not past" today. ISO strings, "" when the event has no such time. */
20
+ export interface EventCacheTimes { startsAt: string; endsAt: string }
21
+
22
+ export function eventCacheTimes(e: WixEvent): EventCacheTimes {
23
+ const iso = (ms: number | undefined) => (ms === undefined ? "" : new Date(ms).toISOString());
24
+ return { startsAt: iso(eventStartMillis(e)), endsAt: iso(eventEndMillis(e)) };
25
+ }
26
+
27
+ /** Would the live Upcoming read return the event of this CACHED row, at `now`? That read asks for a start or an end at
28
+ * or after now, so: its end when it has one, else its start, not before `now` (the `eventIsPast` rule, inverted), read from
29
+ * the row's own stored times. Everything the live read cannot return is `false`, so a cached paint never shows a row that
30
+ * the live answer then removes: a row written before the times were stored (no `startsAt` / `endsAt`), an undated event
31
+ * (to be announced: no time matches the query), and a time that does not parse. */
32
+ export function cachedEventUpcoming(row: unknown, now: number = Date.now()): boolean {
33
+ const r = (row && typeof row === "object" ? row : {}) as Partial<EventCacheTimes>;
34
+ if (typeof r.startsAt !== "string" || typeof r.endsAt !== "string") return false;
35
+ const at = r.endsAt || r.startsAt;
36
+ if (!at) return false;
37
+ const ms = new Date(at).getTime();
38
+ return !Number.isNaN(ms) && ms >= now;
39
+ }
40
+
41
+ interface StorageLike {
42
+ getItem(key: string): string | null;
43
+ setItem(key: string, value: string): void;
44
+ }
45
+
46
+ const RSVP_KEY = "himi-events.confirmed-rsvps";
47
+
48
+ function storage(): StorageLike | undefined {
49
+ const host = globalThis as unknown as {
50
+ himalaya?: { storage?: StorageLike };
51
+ localStorage?: StorageLike;
52
+ };
53
+ return host.himalaya?.storage ?? host.localStorage;
54
+ }
55
+
56
+ export function currentInputId(prefixes: string[]): string {
57
+ // WS-C — `himalaya.input.id` is the PRIMARY contract: hosts thread the row's
58
+ // `id` nav param (himi.open { screenId: <canonical>, id }) into worker input.
59
+ const input = (globalThis as { himalaya?: { input?: { id?: unknown; screenId?: unknown } } }).himalaya?.input;
60
+ if (typeof input?.id === "string" && input.id) return input.id;
61
+ // #570 back-compat for pre-params releases with baked `<prefix><id>`
62
+ // screenIds — do not author against this.
63
+ const screenId = typeof input?.screenId === "string" ? input.screenId : "";
64
+ for (const prefix of prefixes) {
65
+ if (screenId.startsWith(prefix)) return screenId.slice(prefix.length);
66
+ }
67
+ return "";
68
+ }
69
+
70
+ export function confirmedRsvpIds(): string[] {
71
+ try {
72
+ const raw = storage()?.getItem(RSVP_KEY);
73
+ const parsed = raw ? JSON.parse(raw) : [];
74
+ return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === "string") : [];
75
+ } catch {
76
+ return [];
77
+ }
78
+ }
79
+
80
+ export function rememberRsvp(eventId: string): void {
81
+ if (!eventId) return;
82
+ const ids = confirmedRsvpIds();
83
+ const next = [eventId, ...ids.filter((id) => id !== eventId)].slice(0, 50);
84
+ try { storage()?.setItem(RSVP_KEY, JSON.stringify(next)); } catch { /* best-effort */ }
85
+ }
86
+
87
+ /** Remove a locally confirmed RSVP after Wix confirms its cancellation. */
88
+ export function forgetRsvp(eventId: string): void {
89
+ if (!eventId) return;
90
+ const next = confirmedRsvpIds().filter((id) => id !== eventId);
91
+ try { storage()?.setItem(RSVP_KEY, JSON.stringify(next)); } catch { /* best-effort */ }
92
+ }
@@ -0,0 +1,33 @@
1
+ // Cover selection is shared by list, detail and home so the same Wix object never
2
+ // loses its image on navigation. Relative SDK imports are rewritten by the template generator.
3
+ import { wixMediaUrl, WIX_LIST_IMAGE, type WixImageSize } from "@himalaya/wix-media";
4
+ import type { WixGroup } from "@himalaya/wix-groups";
5
+ import type { WixProgram } from "@himalaya/wix-online-programs";
6
+
7
+ function firstImage(references: unknown[], size: WixImageSize): string {
8
+ for (const reference of references) {
9
+ const image = wixMediaUrl(reference, size);
10
+ if (image) return image;
11
+ }
12
+ return "";
13
+ }
14
+
15
+ export function groupImage(group: WixGroup, size: WixImageSize = WIX_LIST_IMAGE): string {
16
+ const cover = group.coverImage as {
17
+ url?: unknown;
18
+ image?: { url?: unknown; fileUrl?: unknown; mediaId?: unknown; id?: unknown };
19
+ } | undefined;
20
+ return firstImage([cover?.image?.url, cover?.image?.fileUrl, cover?.url, cover?.image?.mediaId, cover?.image?.id], size);
21
+ }
22
+
23
+ export function programImage(program: WixProgram, size: WixImageSize = WIX_LIST_IMAGE): string {
24
+ const cover = (program as { coverImage?: unknown }).coverImage;
25
+ const coverUrl = typeof cover === "string" ? cover : (cover as { url?: unknown } | undefined)?.url;
26
+ const description = (program as { description?: unknown }).description;
27
+ const block = description && typeof description === "object" ? description as { image?: { url?: unknown; id?: unknown }; video?: { posters?: Array<{ url?: unknown }> } } : undefined;
28
+ const nested = block?.image;
29
+ // A program whose description has a video and no image is covered by the video's poster (the source's cover); `seo.imageUrl` is that same cover as the site publishes it.
30
+ const poster = block?.video?.posters?.find((candidate) => typeof candidate?.url === "string" && candidate.url)?.url;
31
+ const published = (program as { seo?: { imageUrl?: unknown } }).seo?.imageUrl;
32
+ return firstImage([coverUrl, program.image, nested?.url, nested?.id, poster, published], size);
33
+ }