@wix/himalaya-cli 0.1750.0 → 0.1752.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 (185) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/app-config.d.ts +1 -0
  2. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/app-module.d.ts +3 -0
  3. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/builder.d.ts +3 -0
  4. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/define-app.d.ts +16 -1
  5. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/himi-package.d.ts +478 -0
  6. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/host-compatibility.d.ts +56 -0
  7. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/icon-catalog.generated.d.ts +1 -1
  8. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/schema.d.ts +4 -0
  9. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/site-shell.d.ts +154 -7
  10. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/validator.d.ts +3 -0
  11. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/auth-providers/wix/src/index.d.ts +1 -1
  12. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/auth-providers/wix/src/native-engine.d.ts +49 -3
  13. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/auth/src/copy.generated.d.ts +16 -1
  14. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/auth/src/feedback.d.ts +1 -1
  15. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/screens/src/index.d.ts +2 -0
  16. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/screens/src/podcast-service.d.ts +105 -0
  17. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/screens/src/podcast.d.ts +116 -0
  18. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/auth.mjs +27 -2
  19. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/core.mjs +326 -13
  20. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/screens.mjs +757 -83
  21. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/sdui.mjs +156 -0
  22. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-auth/worker.mjs +133 -13
  23. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/wix-auth.mjs +139 -13
  24. package/dist/browser-plane/assets.json +5 -5
  25. package/dist/browser-plane/preview-deferred/{b40ea5d0d6251898ff5617139fde8be008dd11e99a70b14c1052093685401700.bin → 2671d1cadb15daa5e59440f4c924e30c221ab3d405e8a56a0ab1cdbe4764af3d.bin} +1 -1
  26. package/dist/browser-plane/sw.js +7 -7
  27. package/dist/cli.mjs +37219 -33014
  28. package/dist/preview-assets.generated.bin +0 -0
  29. package/guides/app-config.md +1 -1
  30. package/guides/component-reference.json +1 -1
  31. package/guides/component-reference.md +4 -0
  32. package/guides/designing-himi-screens.md +7 -0
  33. package/guides/getting-started.md +2 -0
  34. package/guides/headless-loop.md +1 -1
  35. package/guides/himi-json-output.md +25 -3
  36. package/guides/himi-skill.md +2 -0
  37. package/guides/index.json +6 -0
  38. package/guides/push-cli-onboarding.md +13 -0
  39. package/guides/qa-builds.md +15 -2
  40. package/guides/recipe-podcast.md +149 -0
  41. package/guides/releasing-with-himi-serve.md +51 -0
  42. package/guides/store-submission.md +46 -1
  43. package/guides/tier-5-add-a-screen.md +16 -2
  44. package/guides/wix-business-context.md +29 -0
  45. package/guides/wix-platform-usage.md +7 -2
  46. package/package.json +10 -10
  47. package/template-icons/fitness-gym.png +0 -0
  48. package/templates/beauty-salon/dev/index.ts +1 -1
  49. package/templates/beauty-salon/l10n/en.json +1 -1
  50. package/templates/beauty-salon/tier5-src/_shared/program-fields.ts +16 -0
  51. package/templates/beauty-salon/tier5-src/_shared/programs-section.ts +5 -8
  52. package/templates/beauty-salon/tier5-src/himi-branded-lite-agenda/index.ts +37 -4
  53. package/templates/branded-lite/dev/index.ts +101 -1
  54. package/templates/branded-lite/l10n/en.json +22 -1
  55. package/templates/branded-lite/l10n/es.json +22 -0
  56. package/templates/branded-lite/l10n/fr.json +18 -0
  57. package/templates/branded-lite/l10n/he.json +15 -0
  58. package/templates/branded-lite/tier5-src/_shared/program-fields.ts +16 -0
  59. package/templates/branded-lite/tier5-src/_shared/programs-section.ts +5 -8
  60. package/templates/branded-lite/tier5-src/himi-branded-lite-agenda/index.ts +37 -4
  61. package/templates/branded-lite/tier5-src/himi-branded-lite-podcasts/index.ts +14 -234
  62. package/templates/brandy/README.md +33 -0
  63. package/templates/brandy/config.ts +51 -7
  64. package/templates/brandy/dev/index.ts +23 -9
  65. package/templates/community-club/l10n/en.json +1 -1
  66. package/templates/community-club/tier5-src/_shared/program-fields.ts +16 -0
  67. package/templates/community-club/tier5-src/_shared/programs-section.ts +5 -8
  68. package/templates/events-meetups/l10n/en.json +1 -1
  69. package/templates/events-meetups/tier5-src/_shared/program-fields.ts +16 -0
  70. package/templates/events-meetups/tier5-src/_shared/programs-section.ts +5 -8
  71. package/templates/fitness-gym/README.md +53 -0
  72. package/templates/fitness-gym/config.ts +560 -0
  73. package/templates/fitness-gym/dev/index.ts +25787 -0
  74. package/templates/fitness-gym/himalaya.content.json +64 -0
  75. package/templates/fitness-gym/himalaya.template.json +15 -0
  76. package/templates/fitness-gym/icon.png +0 -0
  77. package/templates/fitness-gym/platforms.json +1 -0
  78. package/templates/fitness-gym/tier5-src/_shared/app-locale.ts +61 -0
  79. package/templates/fitness-gym/tier5-src/_shared/booking-location.ts +147 -0
  80. package/templates/fitness-gym/tier5-src/_shared/booking-session.ts +224 -0
  81. package/templates/fitness-gym/tier5-src/_shared/branded-lite-hosted.ts +280 -0
  82. package/templates/fitness-gym/tier5-src/_shared/branded-load-state.ts +109 -0
  83. package/templates/fitness-gym/tier5-src/_shared/business-chat-copy.ts +40 -0
  84. package/templates/fitness-gym/tier5-src/_shared/business-chat-history.ts +51 -0
  85. package/templates/fitness-gym/tier5-src/_shared/business-chat-message-model.ts +177 -0
  86. package/templates/fitness-gym/tier5-src/_shared/business-chat-model.ts +56 -0
  87. package/templates/fitness-gym/tier5-src/_shared/business-chat-presenter.ts +576 -0
  88. package/templates/fitness-gym/tier5-src/_shared/business-chat-transport.ts +148 -0
  89. package/templates/fitness-gym/tier5-src/_shared/collection-contract.ts +228 -0
  90. package/templates/fitness-gym/tier5-src/_shared/collection-query.ts +193 -0
  91. package/templates/fitness-gym/tier5-src/_shared/collection-service.ts +400 -0
  92. package/templates/fitness-gym/tier5-src/_shared/detail-presence.ts +51 -0
  93. package/templates/fitness-gym/tier5-src/_shared/engine-intl.ts +523 -0
  94. package/templates/fitness-gym/tier5-src/_shared/himi-account.ts +194 -0
  95. package/templates/fitness-gym/tier5-src/_shared/himi-booking-saved.ts +88 -0
  96. package/templates/fitness-gym/tier5-src/_shared/himi-bookings.ts +318 -0
  97. package/templates/fitness-gym/tier5-src/_shared/himi-copy.ts +116 -0
  98. package/templates/fitness-gym/tier5-src/_shared/himi-media.ts +29 -0
  99. package/templates/fitness-gym/tier5-src/_shared/himi-store.ts +7 -0
  100. package/templates/fitness-gym/tier5-src/_shared/himi-text.ts +24 -0
  101. package/templates/fitness-gym/tier5-src/_shared/host-events.ts +66 -0
  102. package/templates/fitness-gym/tier5-src/_shared/hosted-checkout.ts +70 -0
  103. package/templates/fitness-gym/tier5-src/_shared/iap-attendance-form.ts +106 -0
  104. package/templates/fitness-gym/tier5-src/_shared/iap-attendance-purchase.ts +216 -0
  105. package/templates/fitness-gym/tier5-src/_shared/iap-attendance.ts +38 -0
  106. package/templates/fitness-gym/tier5-src/_shared/iap-worker.ts +127 -0
  107. package/templates/fitness-gym/tier5-src/_shared/inbox-rooms.ts +68 -0
  108. package/templates/fitness-gym/tier5-src/_shared/local-preferences.ts +38 -0
  109. package/templates/fitness-gym/tier5-src/_shared/member-access.ts +63 -0
  110. package/templates/fitness-gym/tier5-src/_shared/member-account-routes.ts +52 -0
  111. package/templates/fitness-gym/tier5-src/_shared/member-bookings.ts +107 -0
  112. package/templates/fitness-gym/tier5-src/_shared/member-screen.ts +99 -0
  113. package/templates/fitness-gym/tier5-src/_shared/notification-target.ts +141 -0
  114. package/templates/fitness-gym/tier5-src/_shared/offset-page.ts +10 -0
  115. package/templates/fitness-gym/tier5-src/_shared/online-actions.ts +76 -0
  116. package/templates/fitness-gym/tier5-src/_shared/owner-load-error.ts +348 -0
  117. package/templates/fitness-gym/tier5-src/_shared/payment-setup.ts +6 -0
  118. package/templates/fitness-gym/tier5-src/_shared/pricing-plan-display.ts +64 -0
  119. package/templates/fitness-gym/tier5-src/_shared/program-description.ts +11 -0
  120. package/templates/fitness-gym/tier5-src/_shared/program-fields.ts +16 -0
  121. package/templates/fitness-gym/tier5-src/_shared/program-standing.ts +46 -0
  122. package/templates/fitness-gym/tier5-src/_shared/rich-body.ts +78 -0
  123. package/templates/fitness-gym/tier5-src/_shared/rich-content-link.ts +34 -0
  124. package/templates/fitness-gym/tier5-src/_shared/sign-in-sheet.ts +18 -0
  125. package/templates/fitness-gym/tier5-src/_shared/staff-name.ts +18 -0
  126. package/templates/fitness-gym/tier5-src/_shared/weekly-goal.ts +107 -0
  127. package/templates/fitness-gym/tier5-src/_shared/wix-bi.ts +85 -0
  128. package/templates/fitness-gym/tier5-src/_shared/wix-member-links.ts +114 -0
  129. package/templates/fitness-gym/tier5-src/_shared/wix-service-price.ts +146 -0
  130. package/templates/fitness-gym/tier5-src/business-chat/index.ts +732 -0
  131. package/templates/fitness-gym/tier5-src/business-contact/index.ts +6 -0
  132. package/templates/fitness-gym/tier5-src/himi-booking-account/index.ts +267 -0
  133. package/templates/fitness-gym/tier5-src/himi-booking-bookings/index.ts +468 -0
  134. package/templates/fitness-gym/tier5-src/himi-booking-service/index.ts +1190 -0
  135. package/templates/fitness-gym/tier5-src/himi-booking-services/index.ts +791 -0
  136. package/templates/fitness-gym/tier5-src/himi-booking-time/index.ts +1729 -0
  137. package/templates/fitness-gym/tier5-src/himi-branded-lite-agenda/index.ts +988 -0
  138. package/templates/fitness-gym/tier5-src/himi-branded-lite-member-programs/index.ts +656 -0
  139. package/templates/fitness-gym/tier5-src/himi-branded-lite-notifications/index.ts +256 -0
  140. package/templates/fitness-gym/tier5-src/himi-branded-lite-plans/index.ts +495 -0
  141. package/templates/fitness-gym/tier5-src/himi-branded-lite-program/facts.ts +52 -0
  142. package/templates/fitness-gym/tier5-src/himi-branded-lite-program/index.ts +845 -0
  143. package/templates/fitness-gym/tier5-src/himi-fitcoach-goal/index.ts +190 -0
  144. package/templates/fitness-gym/tier5-src/himi-fitcoach-home/index.ts +619 -0
  145. package/templates/fitness-gym/tier5-src/himi-store-account/index.ts +1007 -0
  146. package/templates/fitness-gym/tier5-src/wix-spaces-my-subscriptions/index.ts +84 -0
  147. package/templates/fitness-gym/tier5-src/wix-spaces-subscription-detail/index.ts +139 -0
  148. package/templates/fitness-gym/tokens.json +414 -0
  149. package/templates/gym-fitness/dev/index.ts +1 -1
  150. package/templates/gym-fitness/l10n/en.json +1 -1
  151. package/templates/gym-fitness/tier5-src/_shared/program-fields.ts +16 -0
  152. package/templates/gym-fitness/tier5-src/_shared/programs-section.ts +5 -8
  153. package/templates/gym-fitness/tier5-src/himi-branded-lite-agenda/index.ts +37 -4
  154. package/templates/medical-services/dev/index.ts +2 -1
  155. package/templates/medical-services/tier5-src/himi-booking-account/index.ts +16 -1
  156. package/templates/nonprofit-cause/l10n/en.json +1 -1
  157. package/templates/nonprofit-cause/tier5-src/_shared/program-fields.ts +16 -0
  158. package/templates/nonprofit-cause/tier5-src/_shared/programs-section.ts +5 -8
  159. package/templates/personal-fitness-trainer/dev/index.ts +2 -2
  160. package/templates/personal-fitness-trainer/tier5-src/himi-branded-lite-agenda/index.ts +37 -4
  161. package/templates/podcast-creator/dev/index.ts +100 -0
  162. package/templates/podcast-creator/l10n/en.json +22 -1
  163. package/templates/podcast-creator/l10n/es.json +22 -0
  164. package/templates/podcast-creator/l10n/fr.json +18 -0
  165. package/templates/podcast-creator/l10n/he.json +15 -0
  166. package/templates/podcast-creator/tier5-src/_shared/program-fields.ts +16 -0
  167. package/templates/podcast-creator/tier5-src/_shared/programs-section.ts +5 -8
  168. package/templates/podcast-creator/tier5-src/himi-branded-lite-podcasts/index.ts +14 -234
  169. package/templates/portfolio-creative/l10n/en.json +1 -1
  170. package/templates/portfolio-creative/tier5-src/_shared/program-fields.ts +16 -0
  171. package/templates/portfolio-creative/tier5-src/_shared/programs-section.ts +5 -8
  172. package/templates/restaurant/l10n/en.json +1 -1
  173. package/templates/restaurant/tier5-src/_shared/program-fields.ts +16 -0
  174. package/templates/restaurant/tier5-src/_shared/programs-section.ts +5 -8
  175. package/templates/retail-store/l10n/en.json +1 -1
  176. package/templates/retail-store/tier5-src/_shared/program-fields.ts +16 -0
  177. package/templates/retail-store/tier5-src/_shared/programs-section.ts +5 -8
  178. package/templates/salon-spa/dev/index.ts +1 -1
  179. package/templates/salon-spa/tier5-src/himi-booking-account/index.ts +16 -1
  180. package/templates/salon-spa/tier5-src/himi-branded-lite-agenda/index.ts +37 -4
  181. package/templates/yoga-studio/dev/index.ts +1 -1
  182. package/templates/yoga-studio/l10n/en.json +1 -1
  183. package/templates/yoga-studio/tier5-src/_shared/program-fields.ts +16 -0
  184. package/templates/yoga-studio/tier5-src/_shared/programs-section.ts +5 -8
  185. package/templates/yoga-studio/tier5-src/himi-branded-lite-agenda/index.ts +37 -4
@@ -0,0 +1,619 @@
1
+ // Tier-5 bundle: himi-fitcoach-home — the fitness-gym template's Home.
2
+ //
3
+ // One screen for two people. A member asks "what is my next workout, and am I on track?"; a
4
+ // visitor asks "why train here, and how do I start?". The member sections (Up next, Your
5
+ // progress, Quick actions, Your plan) come from the member's own Wix data and collapse fully for
6
+ // a visitor or when their read fails. The catalog sections (goals, challenges, the membership
7
+ // offer) come from visitor reads and show for everyone:
8
+ //
9
+ // - Up next: the member's next CONFIRMED booking (Wix Bookings), with its service's photo.
10
+ // - Your progress: the most recent active challenge (Online Programs participations) — its
11
+ // completion is the ring, "Day 12 of 30" its first row — the member's bookings this week
12
+ // (Monday to Sunday) and the active plan (Pricing Plans orders). Never an invented metric.
13
+ // - Goals: the app's own CMS collection (the collection id arrives as the `goals` param).
14
+ // - Challenges: published programs, a joined one with its progress, the others with a price.
15
+ // - Membership: the site's primary plan, or the member's own plan.
16
+ //
17
+ // Prices of programs and plans go through the shared App Store pricing layer (@himalaya/iap), as
18
+ // every screen that shows such an item does: `disabled` keeps the site's own price.
19
+ //
20
+ // Clock values (this week, "Day N") are computed in `load`, an action the screen's onAppear
21
+ // dispatches, never in the boot state: the release build hashes the boot state.
22
+ import { defineService, navigate } from "@himalaya/state";
23
+ import { queryBookings, queryServices, type WixService } from "@himalaya/wix-bookings";
24
+ import { getProgram, queryPrograms, queryMemberParticipants, participationsByProgram, type WixProgram, type WixProgramFull, type WixParticipant } from "@himalaya/wix-online-programs";
25
+ import { listPublicPlans, listMyPlanOrders, type WixPlan } from "@himalaya/wix-pricing-plans";
26
+ import { queryDataItems } from "@himalaya/wix-data";
27
+ import { getMyMember } from "@himalaya/wix-members";
28
+ import { wixMediaUrl } from "@himalaya/wix-media";
29
+ import { open as openUrl } from "@himalaya/open-url";
30
+ import { iapPriceFields, onlineProgramItem } from "@himalaya/iap";
31
+ import { createIapCommerce } from "@himalaya/iap-checkout";
32
+ import { loadMemberProfile } from "../_shared/himi-account.js";
33
+ import { memberAccess, assertMemberAccess, type MemberAccess } from "../_shared/member-access.js";
34
+ import { memberBookingRow, CANCELLED_STATUSES } from "../_shared/member-bookings.js";
35
+ import { weekStartMs } from "../_shared/weekly-goal.js";
36
+ import { memberScreenOpener } from "../_shared/member-screen.js";
37
+ import { programImage } from "../_shared/himi-media.js";
38
+ import { standingOf } from "../_shared/program-standing.js";
39
+ import { isProgramDraft, isProgramEnded, programName } from "../_shared/program-fields.js";
40
+ import { serviceDurationText, type BookingLabel } from "../_shared/himi-bookings.js";
41
+ import { planDuration } from "../_shared/pricing-plan-display.js";
42
+ import { iapPriceCopy } from "../_shared/iap-worker.js";
43
+ import { formatClock, formatCurrency, formatDateMedium, formatWeekdayMonthDay } from "../_shared/engine-intl.js";
44
+ import { stashCopy, copyParam, copyTemplate } from "../_shared/himi-copy.js";
45
+
46
+ export const SERVICE = "himiFitcoachHome";
47
+ const DAY_MS = 86_400_000;
48
+
49
+ export interface GoalTile { id: string; number: string; title: string; meta: string }
50
+ export interface ChallengeCard {
51
+ id: string; name: string; image: string; hasImage: boolean; noImage: boolean;
52
+ pill: string; joined: boolean; notJoined: boolean;
53
+ priceLine: string; noPrice: boolean;
54
+ progress: number; progressLabel: string; dayLine: string;
55
+ }
56
+ export interface Benefit { id: string; text: string }
57
+ export interface S {
58
+ status: "loading" | "ready" | "error";
59
+ isLoading: boolean; notLoading: boolean; errored: boolean; notErrored: boolean; errorText: string;
60
+ // The member
61
+ isMember: boolean; notMember: boolean;
62
+ greeting: string; memberInitials: string; memberImage: string; hasMemberImage: boolean; noMemberImage: boolean;
63
+ // Up next
64
+ hideUpNext: boolean; hasUpNext: boolean; noUpNext: boolean;
65
+ upNextTitle: string; upNextWhen: string; upNextDuration: string; upNextPlace: string;
66
+ upNextImage: string; upNextHasImage: boolean; upNextNoImage: boolean; upNextA11y: string;
67
+ // Your progress
68
+ hideProgress: boolean; hasChallenge: boolean; noChallenge: boolean;
69
+ ringValue: number; ringLabel: string; challengeLine: string; challengeId: string;
70
+ weekLine: string; planLine: string; hasPlan: boolean; noPlan: boolean;
71
+ startImage: string; startHasImage: boolean; startNoImage: boolean;
72
+ // Quick actions
73
+ membershipCaption: string; membershipScreen: string;
74
+ // Goals
75
+ goals: GoalTile[]; goalLast: GoalTile; hasGoalLast: boolean; noGoalLast: boolean; noGoals: boolean;
76
+ // Challenges
77
+ challenges: ChallengeCard[]; noChallenges: boolean;
78
+ // Membership
79
+ offerName: string; offerBadge: string; noOfferBadge: boolean; offerPrice: string; offerPeriod: string; offerValidity: string;
80
+ offerBenefits: Benefit[]; noOffer: boolean;
81
+ yourPlanName: string; yourPlanLine: string; noYourPlan: boolean;
82
+ /** The outcome line of the last Get in touch link ("" when it opened). */
83
+ linkMessage: string;
84
+ }
85
+
86
+ const BOOT: S = {
87
+ status: "loading", isLoading: true, notLoading: false, errored: false, notErrored: true, errorText: "",
88
+ isMember: false, notMember: true, greeting: "", memberInitials: "", memberImage: "", hasMemberImage: false, noMemberImage: true,
89
+ hideUpNext: true, hasUpNext: false, noUpNext: true,
90
+ upNextTitle: "", upNextWhen: "", upNextDuration: "", upNextPlace: "", upNextImage: "", upNextHasImage: false, upNextNoImage: true, upNextA11y: "",
91
+ hideProgress: true, hasChallenge: false, noChallenge: true, ringValue: 0, ringLabel: "", challengeLine: "", challengeId: "",
92
+ weekLine: "", planLine: "", hasPlan: false, noPlan: true, startImage: "", startHasImage: false, startNoImage: true,
93
+ membershipCaption: "", membershipScreen: "himi_plans",
94
+ goals: [], goalLast: { id: "", number: "", title: "", meta: "" }, hasGoalLast: false, noGoalLast: true, noGoals: true,
95
+ challenges: [], noChallenges: true,
96
+ offerName: "", offerBadge: "", noOfferBadge: true, offerPrice: "", offerPeriod: "", offerValidity: "", offerBenefits: [], noOffer: true,
97
+ yourPlanName: "", yourPlanLine: "", noYourPlan: true,
98
+ linkMessage: "",
99
+ };
100
+
101
+ // ── Reads ────────────────────────────────────────────────────────────────────
102
+
103
+ const clean = (value: unknown): string => (typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "");
104
+ const pad2 = (n: number) => String(n).padStart(2, "0");
105
+ const label: BookingLabel = (key, fallback, values) =>
106
+ values ? copyTemplate(`workout.${key}`, fallback, values) : copyParam(`workout.${key}`, fallback);
107
+
108
+ function firstNameOf(name: string): string {
109
+ const word = clean(name).split(" ")[0] ?? "";
110
+ return word.includes("@") ? "" : word;
111
+ }
112
+
113
+ function serviceImage(service: WixService | undefined): string {
114
+ const media = (service as { media?: { mainMedia?: { image?: { url?: string; id?: string } }; items?: Array<{ image?: { url?: string; id?: string } }> } } | undefined)?.media;
115
+ const image = media?.mainMedia?.image ?? media?.items?.[0]?.image;
116
+ return wixMediaUrl(image?.url || image?.id || "");
117
+ }
118
+
119
+ /** A Wix CMS item's field as text, number or a list of text. */
120
+ const field = (data: Record<string, unknown>, key: string) => data[key];
121
+ const fieldText = (data: Record<string, unknown>, key: string) => clean(field(data, key));
122
+ const fieldNumber = (data: Record<string, unknown>, key: string): number => {
123
+ const n = Number(field(data, key));
124
+ return Number.isFinite(n) && n > 0 ? Math.round(n) : 0;
125
+ };
126
+
127
+ /** "8 sessions · 4 weeks" — the weeks are sessions ÷ per week, rounded up. */
128
+ export function goalMeta(sessions: number, perWeek: number): string {
129
+ if (!sessions) return "";
130
+ const sessionsText = sessions === 1 ? copyParam("home.goalOneSession", "1 session") : copyTemplate("home.goalSessions", "{n} sessions", { n: sessions });
131
+ if (!perWeek) return sessionsText;
132
+ const weeks = Math.ceil(sessions / perWeek);
133
+ const weeksText = weeks === 1 ? copyParam("home.goalOneWeek", "1 week") : copyTemplate("home.goalWeeks", "{n} weeks", { n: weeks });
134
+ return `${sessionsText} · ${weeksText}`;
135
+ }
136
+
137
+ async function readGoals(collectionId: string): Promise<{ ok: boolean; tiles: GoalTile[] }> {
138
+ if (!collectionId) return { ok: true, tiles: [] };
139
+ try {
140
+ const res = await queryDataItems(collectionId, 50, undefined, false, 0, [{ fieldName: "order", order: "ASC" }]);
141
+ const rows = (res.dataItems ?? []).map((item) => (item.data ?? {}) as Record<string, unknown>)
142
+ .filter((data) => fieldText(data, "slug") && fieldText(data, "title"));
143
+ return {
144
+ ok: true,
145
+ tiles: rows.map((data, i) => ({
146
+ id: fieldText(data, "slug"),
147
+ number: pad2(i + 1),
148
+ title: fieldText(data, "title"),
149
+ meta: goalMeta(fieldNumber(data, "sessions"), fieldNumber(data, "perWeek")),
150
+ })),
151
+ };
152
+ } catch {
153
+ // The goals are one section: a failed read collapses it, the rest of Home still shows.
154
+ return { ok: false, tiles: [] };
155
+ }
156
+ }
157
+
158
+ /** `programs`: the open programs Home lists (the first page). `endedIds`: the ended ones on that
159
+ * page, so Home knows them without another read. */
160
+ interface Catalog { programs: WixProgram[]; endedIds: Set<string>; plans: WixPlan[] }
161
+ async function readCatalog(): Promise<{ ok: true; catalog: Catalog } | { ok: false }> {
162
+ try {
163
+ const [all, plans] = await Promise.all([
164
+ queryPrograms({ cursorPaging: { limit: 20 } }).then((r) => (r.programs ?? []).filter((p) => p.id)),
165
+ listPublicPlans().then((r) => (r.plans ?? []).filter((p) => p.id)).catch(() => [] as WixPlan[]),
166
+ ]);
167
+ const endedIds = new Set(all.filter(isProgramEnded).map((p) => p.id));
168
+ return { ok: true, catalog: { programs: all.filter((p) => !isProgramEnded(p) && !isProgramDraft(p)), endedIds, plans } };
169
+ } catch {
170
+ return { ok: false };
171
+ }
172
+ }
173
+
174
+ const durationDays = (p: WixProgram | undefined) => Number((p as WixProgramFull | undefined)?.timeline?.durationInDays ?? 0) || 0;
175
+
176
+ /** The member's part: profile, next booking, this week, participations, active plan. Each read
177
+ * is its own: one that fails collapses its own row or section only. */
178
+ interface MemberPart {
179
+ isMember: boolean; firstName: string; initials: string; image: string;
180
+ next?: { title: string; start: string; serviceId: string; place: string };
181
+ nextFailed: boolean;
182
+ weekCount: number; weekFailed: boolean;
183
+ participants: WixParticipant[]; participantsFailed: boolean;
184
+ planName: string; planEnd: string; planFailed: boolean;
185
+ }
186
+ const GUEST: MemberPart = { isMember: false, firstName: "", initials: "", image: "", nextFailed: false, weekCount: 0, weekFailed: false, participants: [], participantsFailed: false, planName: "", planEnd: "", planFailed: false };
187
+
188
+ async function readMember(nowMs: number): Promise<MemberPart> {
189
+ let member: MemberAccess;
190
+ try { member = await memberAccess(); } catch { return GUEST; }
191
+ if (!member.email) return GUEST;
192
+ const nowIso = new Date(nowMs).toISOString();
193
+ const weekFrom = weekStartMs(nowMs);
194
+ const mine = (b: { contactDetails?: { email?: string } }) => b.contactDetails?.email?.trim().toLowerCase() === member.email;
195
+ const [profile, next, week, participants, plan] = await Promise.all([
196
+ loadMemberProfile("").catch(() => undefined),
197
+ queryBookings({ query: {
198
+ filter: { "contactDetails.email": { $eq: member.email }, startDate: { $gte: nowIso }, status: { $in: ["CONFIRMED"] } },
199
+ sort: [{ fieldName: "startDate", order: "ASC" }], paging: { limit: 5 },
200
+ } }).then((r) => {
201
+ const row = (r.bookings ?? []).filter((b) => b.id && mine(b)).map(memberBookingRow)[0];
202
+ return { ok: true as const, row };
203
+ }).catch(() => ({ ok: false as const, row: undefined })),
204
+ queryBookings({ query: {
205
+ filter: { "contactDetails.email": { $eq: member.email }, startDate: { $gte: new Date(weekFrom).toISOString(), $lt: new Date(weekFrom + 7 * DAY_MS).toISOString() }, status: { $nin: CANCELLED_STATUSES } },
206
+ paging: { limit: 100 },
207
+ } }).then((r) => ({ ok: true as const, count: (r.bookings ?? []).filter((b) => b.id && mine(b)).length }))
208
+ .catch(() => ({ ok: false as const, count: 0 })),
209
+ getMyMember().then(async (m) => {
210
+ const memberId = String(m?.member?.id ?? "");
211
+ if (!memberId) return { ok: true as const, list: [] as WixParticipant[] };
212
+ const res = await queryMemberParticipants({ memberId, limit: 100 });
213
+ return { ok: true as const, list: (res.participants ?? []).filter((p) => p.programId && p.memberId === memberId) };
214
+ }).catch(() => ({ ok: false as const, list: [] as WixParticipant[] })),
215
+ listMyPlanOrders({ statuses: ["ACTIVE"], limit: 10 }).then((r) => {
216
+ const order = (r.orders ?? []).find((o) => o.status === "ACTIVE");
217
+ return { ok: true as const, name: clean(order?.planName), end: order?.endDate ?? "" };
218
+ }).catch(() => ({ ok: false as const, name: "", end: "" })),
219
+ ]);
220
+ // The account must still be the one the reads were made for: a sign-out during them answers as a visitor.
221
+ try { await assertMemberAccess(member); } catch { return GUEST; }
222
+ const name = profile?.isMember ? profile.memberName : "";
223
+ return {
224
+ isMember: true,
225
+ firstName: firstNameOf(name),
226
+ initials: profile?.isMember ? profile.memberInitials : "",
227
+ image: profile?.isMember ? profile.memberImage : "",
228
+ next: next.row ? { title: next.row.title, start: next.row.start, serviceId: next.row.serviceId, place: next.row.placeName } : undefined,
229
+ nextFailed: !next.ok,
230
+ weekCount: week.count, weekFailed: !week.ok,
231
+ participants: participants.list, participantsFailed: !participants.ok,
232
+ planName: plan.name, planEnd: plan.end, planFailed: !plan.ok,
233
+ };
234
+ }
235
+
236
+ const ACTIVE_ENROLLMENT = /^(JOINED|ACTIVE|IN_PROGRESS|RUNNING|)$/;
237
+ /** 0..1 completion of a participation. */
238
+ export function completionOf(p: WixParticipant): number {
239
+ const pct = Number(p.progress?.completionPercentage);
240
+ if (Number.isFinite(pct) && pct >= 0) return Math.min(1, pct / 100);
241
+ const done = Number(p.progress?.totalStepsCompleted ?? 0), total = Number(p.progress?.totalStepsAvailable ?? 0);
242
+ return total > 0 ? Math.min(1, done / total) : 0;
243
+ }
244
+ /** What Home knows of a program: open (listed or read), closed (ended or a draft), or unknown. */
245
+ export type ProgramLifecycle = "open" | "closed" | "unknown";
246
+ /** The member's joined, unfinished participations, the most recently joined first. One per program
247
+ * (the newest, as `participationsByProgram` picks it); a COMPLETED or FAILED progress is out
248
+ * (the shared standing rule), whatever its percentage. */
249
+ function joinedNewestFirst(list: readonly WixParticipant[]): WixParticipant[] {
250
+ return [...participationsByProgram(list).values()]
251
+ .filter((p) => p.programId && ACTIVE_ENROLLMENT.test(String(p.enrollmentStatus ?? "").toUpperCase())
252
+ && standingOf(false, p, undefined) === "joined" && completionOf(p) < 1)
253
+ .sort((a, b) => Date.parse(b.createdDate ?? "") - Date.parse(a.createdDate ?? ""));
254
+ }
255
+ /** The challenge the member is in now: the newest joined participation whose program is open. A
256
+ * closed program is history and is skipped. An unknown program stops the walk with no active
257
+ * challenge: Home cannot tell whether that newer challenge is the member's current one, so it
258
+ * shows no ring rather than an older one. */
259
+ export function activeParticipation(list: readonly WixParticipant[], lifecycle: (programId: string) => ProgramLifecycle = () => "open"): WixParticipant | undefined {
260
+ for (const p of joinedNewestFirst(list)) {
261
+ const state = lifecycle(p.programId ?? "");
262
+ if (state === "open") return p;
263
+ if (state === "unknown") return undefined;
264
+ }
265
+ return undefined;
266
+ }
267
+ /** "Day 12 of 30" from the participation's start, or "Step 4 of 20" for a self-paced program. */
268
+ export function dayLine(p: WixParticipant, program: WixProgram | undefined, nowMs: number): string {
269
+ const days = durationDays(program);
270
+ const started = Date.parse(p.enrollmentInfo?.startDate ?? p.createdDate ?? "");
271
+ if (days > 0 && Number.isFinite(started)) {
272
+ const day = Math.min(days, Math.max(1, Math.floor((nowMs - started) / DAY_MS) + 1));
273
+ return copyTemplate("home.dayOf", "Day {day} of {total}", { day, total: days });
274
+ }
275
+ const done = Number(p.progress?.totalStepsCompleted ?? 0), total = Number(p.progress?.totalStepsAvailable ?? 0);
276
+ return total > 0 ? copyTemplate("home.stepOf", "Step {step} of {total}", { step: Math.min(total, done + 1), total }) : "";
277
+ }
278
+
279
+ function durationPill(p: WixProgram): string {
280
+ const days = durationDays(p);
281
+ if (!days) return "";
282
+ if (days % 7 === 0 && days < 28) return days === 7 ? copyParam("home.oneWeekPill", "1 WEEK") : copyTemplate("home.weeksPill", "{n} WEEKS", { n: days / 7 });
283
+ return copyTemplate("home.daysPill", "{n} DAYS", { n: days });
284
+ }
285
+
286
+ const commercePriceOf = (p: WixProgram): string => {
287
+ const price = (p as WixProgramFull).price;
288
+ const value = Number(price?.value);
289
+ if (!price?.value || !Number.isFinite(value) || value <= 0) return "";
290
+ try { return price.currency ? formatCurrency(value, price.currency) : String(price.value); } catch { return String(price.value); }
291
+ };
292
+
293
+ function planPrice(plan: WixPlan): string {
294
+ const price = plan.pricing?.price;
295
+ const value = Number(price?.value);
296
+ if (price?.value == null || !Number.isFinite(value)) return "";
297
+ try { return price.currency ? formatCurrency(value, price.currency) : String(price.value); } catch { return String(price.value); }
298
+ }
299
+ function planPeriod(plan: WixPlan): string {
300
+ const cycle = plan.pricing?.subscription?.cycleDuration;
301
+ if (!cycle?.count || !cycle.unit) return "";
302
+ const unit = String(cycle.unit).toLowerCase().replace(/s$/, "");
303
+ return cycle.count === 1 ? copyTemplate("home.perUnit", "/{unit}", { unit }) : copyTemplate("home.everyUnits", "every {n} {unit}s", { n: cycle.count, unit });
304
+ }
305
+
306
+ // ── Pricing (the shared App Store layer) ─────────────────────────────────────
307
+
308
+ const commerce = createIapCommerce({ onChange: () => { void svc.publish(); } });
309
+ const pricing = commerce.pricing;
310
+
311
+ function presentedPrice(kind: "onlineProgram" | "pricingPlan", id: string, own: string): string {
312
+ const reference = { kind, id };
313
+ const view = pricing.view(reference);
314
+ if (view.route === "disabled") return own;
315
+ // As the shared programs list does: a route with no text yet (a host that answers late) keeps
316
+ // the site's own price rather than an empty line (iOS showed "/month" with no amount).
317
+ return iapPriceFields(view, iapPriceCopy("home")).priceText || own;
318
+ }
319
+
320
+ async function loadPrices(catalog: Catalog, offerId: string): Promise<void> {
321
+ const items = [
322
+ ...catalog.programs.flatMap((p) => onlineProgramItem({ id: p.id }, commercePriceOf(p)) ?? []),
323
+ ...(offerId ? [{ reference: { kind: "pricingPlan", id: offerId }, commerceDisplayPrice: planPrice(catalog.plans.find((p) => p.id === offerId)!) }] : []),
324
+ ];
325
+ if (!items.length || !pricing.enabled) return;
326
+ await commerce.loadPrices(items as never);
327
+ void svc.publish();
328
+ }
329
+
330
+ // ── Derivation ───────────────────────────────────────────────────────────────
331
+
332
+ /** What the last load read: the state is derived from it, so a price change re-derives it. */
333
+ let last: { member: MemberPart; catalog?: Catalog; memberPrograms: Map<string, WixProgram>; goals: GoalTile[]; services: Map<string, WixService>; nowMs: number } | undefined;
334
+
335
+ const lifecycleOf = (p: WixProgram | undefined): ProgramLifecycle =>
336
+ !p ? "unknown" : isProgramEnded(p) || isProgramDraft(p) ? "closed" : "open";
337
+
338
+ /** The joined programs the catalog page does not hold (Home reads 20), read by id in the order
339
+ * `activeParticipation` walks them — newest first, one and then five at a time — until the walk can end: at an
340
+ * open program, or at one that cannot be read. So the active challenge is always the member's
341
+ * newest open one, however many programs they joined, and most members cost one read or none. */
342
+ async function readMemberPrograms(participants: readonly WixParticipant[], catalog: Catalog | undefined): Promise<Map<string, WixProgram>> {
343
+ const listed = new Map((catalog?.programs ?? []).map((p) => [p.id, p]));
344
+ const ended = catalog?.endedIds ?? new Set<string>();
345
+ const read = new Map<string, WixProgram>();
346
+ const unreadable = new Set<string>();
347
+ const lifecycle = (id: string): ProgramLifecycle =>
348
+ listed.has(id) ? "open" : ended.has(id) ? "closed" : unreadable.has(id) ? "unknown" : read.has(id) ? lifecycleOf(read.get(id)) : "unknown";
349
+ const order = joinedNewestFirst(participants).map((p) => p.programId ?? "");
350
+ for (let i = 0; i < order.length; ) {
351
+ // Walk the known ones; stop at the first open program, or gather the next unread ones.
352
+ const batch: string[] = [];
353
+ for (const size = read.size || unreadable.size ? 5 : 1; i < order.length && batch.length < size; i++) {
354
+ const id = order[i];
355
+ if (listed.has(id)) { if (!batch.length) return read; break; }
356
+ if (ended.has(id)) continue;
357
+ batch.push(id);
358
+ }
359
+ if (!batch.length) break;
360
+ const found = await Promise.all(batch.map((id) => getProgram(id).then((r) => r.program).catch(() => undefined)));
361
+ batch.forEach((id, k) => { const p = found[k]; if (p?.id) read.set(id, p as WixProgram); else unreadable.add(id); });
362
+ if (activeParticipation(participants, lifecycle) || batch.some((id) => lifecycle(id) === "unknown")) return read;
363
+ }
364
+ return read;
365
+ }
366
+
367
+ function derive(base: S): S {
368
+ if (!last) return base;
369
+ const { member, catalog, memberPrograms, goals, services, nowMs } = last;
370
+ const isMember = member.isMember;
371
+ const programs = catalog?.programs ?? [];
372
+ // One record per program: a member who left and rejoined has several.
373
+ const byProgram = participationsByProgram(member.participants);
374
+ const programOf = (id: string) => programs.find((p) => p.id === id) ?? memberPrograms.get(id);
375
+ const ended = catalog?.endedIds ?? new Set<string>();
376
+ const active = activeParticipation(member.participants, (id) => (ended.has(id) ? "closed" : lifecycleOf(programOf(id))));
377
+ const activeProgram = active ? programOf(active.programId ?? "") : undefined;
378
+
379
+ // Up next
380
+ const next = member.next;
381
+ const nextService = next ? services.get(next.serviceId) : undefined;
382
+ const nextDate = next ? new Date(next.start) : undefined;
383
+ const upNextWhen = nextDate && Number.isFinite(nextDate.getTime()) ? `${formatWeekdayMonthDay(nextDate)} · ${formatClock(nextDate)}` : "";
384
+ const upNextImage = serviceImage(nextService);
385
+ const upNextDuration = nextService ? serviceDurationText(nextService, label) : "";
386
+
387
+ // Membership
388
+ const offer = (catalog?.plans ?? []).find((p) => p.primary) ?? catalog?.plans?.[0];
389
+ const hasOwnPlan = isMember && !!member.planName;
390
+ const planEnd = member.planEnd ? new Date(member.planEnd) : undefined;
391
+
392
+ const challenges: ChallengeCard[] = programs.slice(0, 10).map((p) => {
393
+ const part = byProgram.get(p.id);
394
+ const joined = !!part && ACTIVE_ENROLLMENT.test(String(part.enrollmentStatus ?? "").toUpperCase());
395
+ const image = programImage(p);
396
+ const progress = part ? completionOf(part) : 0;
397
+ const priceLine = joined ? "" : presentedPrice("onlineProgram", p.id, commercePriceOf(p)) || copyParam("home.freeChallenge", "Free");
398
+ return {
399
+ id: p.id,
400
+ name: programName(p) || copyParam("home.challengeFallbackName", "Challenge"),
401
+ image, hasImage: !!image, noImage: !image,
402
+ pill: joined ? copyParam("home.joinedPill", "JOINED") : durationPill(p),
403
+ joined, notJoined: !joined,
404
+ priceLine, noPrice: !priceLine,
405
+ progress,
406
+ progressLabel: copyTemplate("home.percent", "{n}%", { n: Math.round(progress * 100) }),
407
+ dayLine: part && joined ? dayLine(part, p, nowMs) : "",
408
+ };
409
+ });
410
+
411
+ const goalsEven = goals.length % 2 === 1 ? goals.slice(0, -1) : goals;
412
+ const goalLast = goals.length % 2 === 1 ? goals[goals.length - 1] : BOOT.goalLast;
413
+ const startProgram = programs.find((p) => !byProgram.has(p.id)) ?? programs[0];
414
+ const startImage = startProgram ? programImage(startProgram) : "";
415
+ const status: S["status"] = catalog ? "ready" : "error";
416
+
417
+ return {
418
+ ...base,
419
+ status,
420
+ isLoading: false, notLoading: true,
421
+ errored: status === "error", notErrored: status !== "error",
422
+ errorText: status === "error" ? copyParam("home.errorText", "Challenges and plans could not be loaded.") : "",
423
+ isMember, notMember: !isMember,
424
+ greeting: member.firstName ? copyTemplate("home.greetingName", "Hello, {name}", { name: member.firstName }) : copyParam("home.greeting", "Hello"),
425
+ memberInitials: member.initials, memberImage: member.image, hasMemberImage: !!member.image, noMemberImage: !member.image,
426
+ // Up next: a failed read collapses the section; no booking shows its empty state.
427
+ hideUpNext: !isMember || member.nextFailed,
428
+ hasUpNext: !!next, noUpNext: !next,
429
+ upNextTitle: next?.title ?? "", upNextWhen, upNextDuration, upNextPlace: next?.place ?? "",
430
+ upNextImage, upNextHasImage: !!upNextImage, upNextNoImage: !upNextImage,
431
+ upNextA11y: next ? copyTemplate("home.upNextA11y", "Open {title}, {when}", { title: next.title, when: upNextWhen }) : "",
432
+ // Your progress: the section collapses when the participations cannot be read.
433
+ hideProgress: !isMember || member.participantsFailed,
434
+ hasChallenge: !!active, noChallenge: !active,
435
+ ringValue: active ? completionOf(active) : 0,
436
+ ringLabel: active ? copyTemplate("home.percent", "{n}%", { n: Math.round(completionOf(active) * 100) }) : "",
437
+ challengeLine: active ? dayLine(active, activeProgram, nowMs) : "",
438
+ challengeId: active?.programId ?? "",
439
+ weekLine: member.weekFailed ? "—" : member.weekCount === 1 ? copyParam("home.oneSession", "1 session") : copyTemplate("home.sessions", "{n} sessions", { n: member.weekCount }),
440
+ planLine: member.planFailed ? "—" : member.planName || copyParam("home.noPlan", "No plan"),
441
+ hasPlan: !!member.planName, noPlan: !member.planName,
442
+ startImage, startHasImage: !!startImage, startNoImage: !startImage,
443
+ membershipCaption: member.planName || copyParam("home.quickPlansCaption", "Plans"),
444
+ membershipScreen: member.planName ? "himi_my_subscriptions" : "himi_plans",
445
+ goals: goalsEven, goalLast, hasGoalLast: !!goalLast.id, noGoalLast: !goalLast.id, noGoals: goals.length === 0,
446
+ challenges, noChallenges: challenges.length === 0,
447
+ offerName: offer?.name ? clean(offer.name) : "",
448
+ offerBadge: offer?.primary ? copyParam("home.bestValue", "BEST VALUE") : "", noOfferBadge: !offer?.primary,
449
+ offerPrice: offer ? presentedPrice("pricingPlan", offer.id, planPrice(offer)) : "",
450
+ offerPeriod: offer ? planPeriod(offer) : "",
451
+ offerValidity: offer ? planDuration(offer.pricing) : "",
452
+ offerBenefits: (offer?.perks?.values ?? []).map((v) => clean(v)).filter(Boolean).slice(0, 3).map((text, i) => ({ id: `${offer!.id}.${i}`, text })),
453
+ noOffer: !offer || hasOwnPlan,
454
+ yourPlanName: member.planName,
455
+ yourPlanLine: planEnd && Number.isFinite(planEnd.getTime()) ? copyTemplate("home.validUntil", "Valid until {date}", { date: formatDateMedium(planEnd) }) : copyParam("home.planActive", "Active"),
456
+ noYourPlan: !hasOwnPlan,
457
+ };
458
+ }
459
+
460
+ // ── Load ─────────────────────────────────────────────────────────────────────
461
+
462
+ let loadSeq = 0;
463
+ let latest: S = BOOT;
464
+ const commit = (next: S): S => (latest = next);
465
+ const now = (): S => (svc.getState?.() as S | undefined) ?? latest;
466
+ const openMemberScreen = memberScreenOpener();
467
+ const strArg = (arg: unknown, key: string): string => {
468
+ const v = (arg as Record<string, unknown> | undefined)?.[key];
469
+ return typeof v === "string" ? v : "";
470
+ };
471
+ let goalsCollection = "";
472
+
473
+ /** Who the member data on screen belongs to (`[email, scope]`, "" for a visitor). */
474
+ let shownIdentity = "";
475
+ const identityOf = (m: MemberAccess | undefined): string => (m?.email ? JSON.stringify([m.email, m.scope]) : "");
476
+
477
+ async function load(s: S): Promise<S> {
478
+ const mine = ++loadSeq;
479
+ const nowMs = Date.now();
480
+ // Another member (or a sign-out) since the last read: the old member's Up next, progress and plan
481
+ // leave the screen BEFORE the new reads, never after them.
482
+ const who = await memberAccess().catch(() => undefined);
483
+ if (shownIdentity && identityOf(who) !== shownIdentity) {
484
+ shownIdentity = "";
485
+ await svc.clearMember();
486
+ s = now();
487
+ }
488
+ const [member, catalog, goals] = await Promise.all([readMember(nowMs), readCatalog(), readGoals(goalsCollection)]);
489
+ if (mine !== loadSeq) return now();
490
+ // The photo and length of the next booking's service.
491
+ const services = new Map<string, WixService>();
492
+ if (member.next?.serviceId) {
493
+ try {
494
+ const res = await queryServices({ query: { filter: { id: { $in: [member.next.serviceId] } }, paging: { limit: 1 } } });
495
+ for (const svcRow of res.services ?? []) if (svcRow.id) services.set(svcRow.id, svcRow);
496
+ } catch { /* the card shows without a photo */ }
497
+ }
498
+ if (mine !== loadSeq) return now();
499
+ shownIdentity = member.isMember ? identityOf(who) : "";
500
+ const memberPrograms = await readMemberPrograms(member.participants, catalog.ok ? catalog.catalog : undefined);
501
+ if (mine !== loadSeq) return now();
502
+ last = { member, catalog: catalog.ok ? catalog.catalog : undefined, memberPrograms, goals: goals.tiles, services, nowMs };
503
+ const derived = derive(s);
504
+ if (catalog.ok) {
505
+ const offer = catalog.catalog.plans.find((p) => p.primary) ?? catalog.catalog.plans[0];
506
+ void loadPrices(catalog.catalog, offer?.id ?? "");
507
+ }
508
+ return derived;
509
+ }
510
+
511
+ /** A call, an email or a map: only these schemes leave the app, and a map only to a maps host.
512
+ * A link the descriptor did not mean to send is refused, never opened. */
513
+ export function allowedLink(raw: string): string {
514
+ const url = raw.trim();
515
+ if (/^(tel|mailto):[^\s]+$/i.test(url)) return url;
516
+ // No `URL`: a bare iOS JSContext (the worker engine floor) has none. https only, no `user@`
517
+ // part, no backslash in the host.
518
+ const match = /^https:\/\/([^/?#:@\s\\]+)(?::\d+)?([/?#]\S*)?$/i.exec(url);
519
+ if (!match) return "";
520
+ const host = match[1].toLowerCase();
521
+ const path = match[2] ?? "";
522
+ // Maps only: never another page of google.com (`/url?q=` is an open redirect) or apple.com.
523
+ if (host === "maps.apple.com" || host === "maps.google.com" || host === "maps.app.goo.gl") return url;
524
+ if ((host === "www.google.com" || host === "google.com") && /^\/maps(?:[/?#]|$)/i.test(path)) return url;
525
+ return "";
526
+ }
527
+
528
+ /** The state keys that come from the member (or a price), dropped from a persisted snapshot. */
529
+ export const MEMBER_KEYS: Array<keyof S> = [
530
+ "linkMessage", "challenges", "offerPrice",
531
+ "isMember", "notMember", "greeting", "memberImage", "memberInitials", "hasMemberImage", "noMemberImage",
532
+ "hideUpNext", "hasUpNext", "noUpNext", "upNextTitle", "upNextWhen", "upNextDuration", "upNextPlace",
533
+ "upNextImage", "upNextHasImage", "upNextNoImage", "upNextA11y",
534
+ "hideProgress", "hasChallenge", "noChallenge", "ringValue", "ringLabel", "challengeLine", "challengeId",
535
+ "weekLine", "planLine", "hasPlan", "noPlan",
536
+ "membershipCaption", "membershipScreen", "noOffer",
537
+ "yourPlanName", "yourPlanLine", "noYourPlan",
538
+ ];
539
+
540
+ const svc = defineService<S, {
541
+ openLink: (s: S, arg?: unknown) => Promise<S | undefined>;
542
+ load: (s: S, arg?: unknown) => Promise<S>;
543
+ refresh: (s: S, arg?: unknown) => Promise<S>;
544
+ startRetry: (s: S) => S;
545
+ clearMember: (s: S) => S;
546
+ publish: (s: S) => S;
547
+ openUpNext: (s: S) => S;
548
+ openTab: (s: S, arg?: unknown) => S;
549
+ openMembership: (s: S) => S;
550
+ openGoal: (s: S, arg?: unknown) => S;
551
+ openForMember: (s: S, arg?: unknown) => Promise<S>;
552
+ }>(SERVICE, {
553
+ // Prices and member data are this run's: a cold start never shows an old amount or another
554
+ // member. Every key `derive` takes from the member is in both lists: `notHydrated` stops the
555
+ // restore, `notPersisted` keeps the member's data off the device. A snapshot boots as a visitor
556
+ // (BOOT's values) until `load` reads the member again.
557
+ notHydrated: MEMBER_KEYS,
558
+ notPersisted: MEMBER_KEYS,
559
+ state: BOOT,
560
+ actions: {
561
+ // Call, email, maps (Get in touch). A failed open shows a line under the list.
562
+ openLink: async (_s, arg) => {
563
+ stashCopy(arg);
564
+ const url = allowedLink(strArg(arg, "url"));
565
+ let opened = false;
566
+ if (url) { try { opened = (await openUrl(url)).opened === true; } catch { opened = false; } }
567
+ const current = now();
568
+ const linkMessage = opened ? "" : copyParam("home.linkFailed", "This link could not be opened.");
569
+ return current.linkMessage === linkMessage ? undefined : commit({ ...current, linkMessage });
570
+ },
571
+ load: (s, arg) => {
572
+ stashCopy(arg);
573
+ goalsCollection = strArg(arg, "goals") || goalsCollection;
574
+ return load(s).then(commit);
575
+ },
576
+ // Retry and pull to refresh: the loading state shows before the reads start.
577
+ refresh: async (s, arg) => {
578
+ stashCopy(arg);
579
+ if (s.status === "error") await svc.startRetry();
580
+ return load(now()).then(commit);
581
+ },
582
+ startRetry: (s) => commit({ ...s, status: "loading", isLoading: true, notLoading: false, errored: false, notErrored: true }),
583
+ // Publishes the visitor's member fields (BOOT's) while the next member's reads run.
584
+ clearMember: (s) => {
585
+ if (last) last = { ...last, member: GUEST };
586
+ const reset = { ...s } as Record<string, unknown>;
587
+ for (const key of MEMBER_KEYS) if (key !== "linkMessage" && key !== "challenges" && key !== "offerPrice") reset[key] = BOOT[key];
588
+ return commit(last ? derive(reset as unknown as S) : (reset as unknown as S));
589
+ },
590
+ publish: (s) => commit(derive(s)),
591
+ // The round play button on Up next: the member's bookings, where the details sheet is.
592
+ openUpNext: (s) => navigate(s, { screenId: "himi_bookings" }),
593
+ // A tab from a tap on Home (the hero CTA, "See challenges"): a tab switch, never a push.
594
+ openTab: (s, arg) => {
595
+ const tab = strArg(arg, "tab");
596
+ return tab ? navigate(s, { tab }) : s;
597
+ },
598
+ // Membership: the member's own plans when they have one, else the plans to choose from.
599
+ openMembership: (s) => navigate(s, { screenId: s.membershipScreen || "himi_plans" }),
600
+ openGoal: (s, arg) => {
601
+ const id = strArg(arg, "id");
602
+ return id ? navigate(s, { screenId: "himi_fit_goal", args: { id } }) : s;
603
+ },
604
+ // A member screen (the chat, My bookings, My plans): a member goes there; a visitor gets the
605
+ // sign-in sheet first (_shared/member-screen.ts), and the screen opens once signed in.
606
+ openForMember: async (_s, arg) => {
607
+ const nav = await openMemberScreen(arg);
608
+ return nav ? navigate(now(), nav) : now();
609
+ },
610
+ },
611
+ });
612
+ // An older iOS or Android runtime ignores both lists and restores the whole snapshot, so put the
613
+ // member keys back to BOOT before any action runs. In place, because on those runtimes
614
+ // getState() IS the stored state.
615
+ if ((globalThis as { himalaya?: { hydrationOptOut?: unknown } }).himalaya?.hydrationOptOut !== true) {
616
+ const live = (svc as { getState?: () => S | undefined }).getState?.();
617
+ if (live && typeof live === "object") for (const key of MEMBER_KEYS) (live as unknown as Record<string, unknown>)[key] = BOOT[key];
618
+ }
619
+ export { svc };