@wix/himalaya-cli 0.1945.0 → 0.1947.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 (116) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/motion.mjs +1 -0
  2. package/dist/browser-plane/assets.json +5 -5
  3. package/dist/browser-plane/preview-deferred/{e113c7cdcf8f56ad861b2564505fab2a1975c7a995f92d2f999f9c4ce1a09a40.bin → da958a2a47eef7082c7892c1cc755a58bbeefcb4b617b47fde87f1ce567b3e64.bin} +1 -1
  4. package/dist/browser-plane/sw.js +7 -7
  5. package/dist/cli.mjs +811 -283
  6. package/dist/preview-assets.generated.bin +0 -0
  7. package/guides/himi-json-output.md +7 -0
  8. package/guides/himi-test.md +31 -0
  9. package/package.json +2 -2
  10. package/templates/bare-fashion/tier5-src/_shared/engine-intl.ts +65 -0
  11. package/templates/beauty-salon/dev/index.ts +1 -0
  12. package/templates/beauty-salon/tier5-src/_shared/engine-intl.ts +65 -0
  13. package/templates/beauty-salon/tier5-src/_shared/weekly-goal.ts +28 -12
  14. package/templates/beauty-salon/tier5-src/himi-booking-bookings/index.ts +7 -2
  15. package/templates/beauty-salon/tier5-src/himi-branded-lite-home/index.ts +8 -8
  16. package/templates/beauty-salon-owner/tier5-src/_shared/engine-intl.ts +65 -0
  17. package/templates/branded-lite/dev/index.ts +4 -2
  18. package/templates/branded-lite/l10n/ar.json +5 -5
  19. package/templates/branded-lite/l10n/cs.json +5 -5
  20. package/templates/branded-lite/l10n/da.json +5 -5
  21. package/templates/branded-lite/l10n/de.json +5 -5
  22. package/templates/branded-lite/l10n/el.json +5 -5
  23. package/templates/branded-lite/l10n/es.json +5 -5
  24. package/templates/branded-lite/l10n/fi.json +5 -5
  25. package/templates/branded-lite/l10n/fr.json +5 -5
  26. package/templates/branded-lite/l10n/he.json +4 -4
  27. package/templates/branded-lite/l10n/hu.json +5 -5
  28. package/templates/branded-lite/l10n/id.json +5 -5
  29. package/templates/branded-lite/l10n/it.json +5 -5
  30. package/templates/branded-lite/l10n/ja.json +5 -5
  31. package/templates/branded-lite/l10n/ko.json +5 -5
  32. package/templates/branded-lite/l10n/lt.json +5 -5
  33. package/templates/branded-lite/l10n/nl.json +5 -5
  34. package/templates/branded-lite/l10n/no.json +5 -5
  35. package/templates/branded-lite/l10n/pl.json +5 -5
  36. package/templates/branded-lite/l10n/pt.json +5 -5
  37. package/templates/branded-lite/l10n/ru.json +5 -5
  38. package/templates/branded-lite/l10n/sv.json +5 -5
  39. package/templates/branded-lite/l10n/th.json +5 -5
  40. package/templates/branded-lite/l10n/tr.json +5 -5
  41. package/templates/branded-lite/l10n/uk.json +5 -5
  42. package/templates/branded-lite/l10n/vi.json +5 -5
  43. package/templates/branded-lite/l10n/zh.json +5 -5
  44. package/templates/branded-lite/tier5-src/_shared/engine-intl.ts +65 -0
  45. package/templates/branded-lite/tier5-src/_shared/performance-tracker-section.ts +24 -16
  46. package/templates/branded-lite/tier5-src/_shared/performance-tracker-weeks.ts +27 -20
  47. package/templates/branded-lite/tier5-src/_shared/weekly-goal.ts +28 -12
  48. package/templates/branded-lite/tier5-src/himi-booking-bookings/index.ts +7 -2
  49. package/templates/branded-lite/tier5-src/himi-branded-lite-home/index.ts +8 -8
  50. package/templates/brandy/tier5-src/_shared/engine-intl.ts +65 -0
  51. package/templates/community-club/dev/index.ts +1 -0
  52. package/templates/community-club/tier5-src/_shared/engine-intl.ts +65 -0
  53. package/templates/community-club/tier5-src/_shared/weekly-goal.ts +28 -12
  54. package/templates/community-club/tier5-src/himi-branded-lite-home/index.ts +8 -8
  55. package/templates/community-club-owner/tier5-src/_shared/engine-intl.ts +65 -0
  56. package/templates/conference/tier5-src/_shared/engine-intl.ts +65 -0
  57. package/templates/events-meetups/dev/index.ts +1 -0
  58. package/templates/events-meetups/tier5-src/_shared/engine-intl.ts +65 -0
  59. package/templates/events-meetups/tier5-src/_shared/weekly-goal.ts +28 -12
  60. package/templates/events-meetups/tier5-src/himi-branded-lite-home/index.ts +8 -8
  61. package/templates/events-meetups-owner/tier5-src/_shared/engine-intl.ts +65 -0
  62. package/templates/fitness-gym/tier5-src/_shared/engine-intl.ts +65 -0
  63. package/templates/fitness-gym/tier5-src/_shared/weekly-goal.ts +28 -12
  64. package/templates/fitness-gym/tier5-src/himi-booking-bookings/index.ts +7 -2
  65. package/templates/fitness-gym/tier5-src/himi-fitcoach-home/index.ts +3 -2
  66. package/templates/gym-fitness/dev/index.ts +3 -1
  67. package/templates/gym-fitness/tier5-src/_shared/engine-intl.ts +65 -0
  68. package/templates/gym-fitness/tier5-src/_shared/weekly-goal.ts +28 -12
  69. package/templates/gym-fitness/tier5-src/himi-booking-bookings/index.ts +7 -2
  70. package/templates/gym-fitness/tier5-src/himi-branded-lite-home/index.ts +8 -8
  71. package/templates/gym-fitness-owner/tier5-src/_shared/engine-intl.ts +65 -0
  72. package/templates/medical-services/tier5-src/_shared/engine-intl.ts +65 -0
  73. package/templates/medical-services/tier5-src/_shared/weekly-goal.ts +28 -12
  74. package/templates/medical-services/tier5-src/himi-booking-bookings/index.ts +7 -2
  75. package/templates/nonprofit-cause/dev/index.ts +1 -0
  76. package/templates/nonprofit-cause/tier5-src/_shared/engine-intl.ts +65 -0
  77. package/templates/nonprofit-cause/tier5-src/_shared/weekly-goal.ts +28 -12
  78. package/templates/nonprofit-cause/tier5-src/himi-branded-lite-home/index.ts +8 -8
  79. package/templates/nonprofit-cause-owner/tier5-src/_shared/engine-intl.ts +65 -0
  80. package/templates/owner-lite/tier5-src/_shared/engine-intl.ts +65 -0
  81. package/templates/personal-fitness-trainer/tier5-src/_shared/engine-intl.ts +65 -0
  82. package/templates/personal-fitness-trainer/tier5-src/_shared/weekly-goal.ts +28 -12
  83. package/templates/personal-fitness-trainer/tier5-src/himi-booking-bookings/index.ts +7 -2
  84. package/templates/podcast-creator/dev/index.ts +1 -0
  85. package/templates/podcast-creator/tier5-src/_shared/engine-intl.ts +65 -0
  86. package/templates/podcast-creator/tier5-src/_shared/weekly-goal.ts +28 -12
  87. package/templates/podcast-creator/tier5-src/himi-branded-lite-home/index.ts +8 -8
  88. package/templates/podcast-creator-owner/tier5-src/_shared/engine-intl.ts +65 -0
  89. package/templates/portfolio-creative/dev/index.ts +1 -0
  90. package/templates/portfolio-creative/tier5-src/_shared/engine-intl.ts +65 -0
  91. package/templates/portfolio-creative/tier5-src/_shared/weekly-goal.ts +28 -12
  92. package/templates/portfolio-creative/tier5-src/himi-branded-lite-home/index.ts +8 -8
  93. package/templates/portfolio-creative-owner/tier5-src/_shared/engine-intl.ts +65 -0
  94. package/templates/professional-services/tier5-src/_shared/engine-intl.ts +65 -0
  95. package/templates/professional-services/tier5-src/_shared/weekly-goal.ts +28 -12
  96. package/templates/professional-services/tier5-src/himi-booking-bookings/index.ts +7 -2
  97. package/templates/restaurant/dev/index.ts +1 -0
  98. package/templates/restaurant/tier5-src/_shared/engine-intl.ts +65 -0
  99. package/templates/restaurant/tier5-src/_shared/weekly-goal.ts +28 -12
  100. package/templates/restaurant/tier5-src/himi-branded-lite-home/index.ts +8 -8
  101. package/templates/restaurant-owner/tier5-src/_shared/engine-intl.ts +65 -0
  102. package/templates/retail-store/dev/index.ts +1 -0
  103. package/templates/retail-store/tier5-src/_shared/engine-intl.ts +65 -0
  104. package/templates/retail-store/tier5-src/_shared/weekly-goal.ts +28 -12
  105. package/templates/retail-store/tier5-src/himi-branded-lite-home/index.ts +8 -8
  106. package/templates/retail-store-owner/tier5-src/_shared/engine-intl.ts +65 -0
  107. package/templates/salon-spa/tier5-src/_shared/engine-intl.ts +65 -0
  108. package/templates/salon-spa/tier5-src/_shared/weekly-goal.ts +28 -12
  109. package/templates/salon-spa/tier5-src/himi-booking-bookings/index.ts +7 -2
  110. package/templates/wholesale-store/tier5-src/_shared/engine-intl.ts +65 -0
  111. package/templates/yoga-studio/dev/index.ts +3 -1
  112. package/templates/yoga-studio/tier5-src/_shared/engine-intl.ts +65 -0
  113. package/templates/yoga-studio/tier5-src/_shared/weekly-goal.ts +28 -12
  114. package/templates/yoga-studio/tier5-src/himi-booking-bookings/index.ts +7 -2
  115. package/templates/yoga-studio/tier5-src/himi-branded-lite-home/index.ts +8 -8
  116. package/templates/yoga-studio-owner/tier5-src/_shared/engine-intl.ts +65 -0
@@ -2,7 +2,9 @@
2
2
  // (this week's range, "N of G sessions this week", a progress ring), their weeks of meeting the goal and their sessions in total. The source
3
3
  // reads a private fitness service; this reads the same member-scoped bookings as My Bookings (himi_bookings) and counts with the
4
4
  // same rule as its "This week" card (`weekly-goal.ts`: a CONFIRMED booking that already took place; Wix attendance is owner-scoped,
5
- // so a no-show still counts), so a guest or a refused member gets the sign-in state instead of a read.
5
+ // so a no-show still counts), so a guest or a refused member gets the sign-in state instead of a read. Because no number here is
6
+ // attendance, the all-time row reads "All-time sessions", never the source's "Sessions attended in total".
7
+ // The week starts on the app language's first day (`resolveFirstWeekday`), as the source's does; a load's `firstWeekday` pins another.
6
8
  // goal -> the default weekly goal (the source's `defaultWeeklyGoal`). A member picks their own from 1 to 14 in a sheet with a number wheel, as in
7
9
  // the source; it is kept on this device under the member's key (`performance-tracker-goal.ts`), because the source's goal lives in a
8
10
  // private service a member's session cannot call. A visitor keeps the default and is asked to sign in to change it,
@@ -10,11 +12,11 @@
10
12
  // A page worker registers it under a service name; the descriptor binds `$service:<serviceName>.*` (recipe performance-tracker.json).
11
13
  import { defineService } from "@himalaya/state";
12
14
  import { hostSessionFromGlobal } from "@himalaya/iap";
13
- import { copyPlural, stashCopy } from "./himi-copy.js";
15
+ import { copyParam, copyPlural, stashCopy } from "./himi-copy.js";
14
16
  import { formatNumber } from "./engine-intl.js";
15
17
  import { fetchMemberBookings } from "./member-bookings.js";
16
18
  import { memberAccess, memberAccessDenied, memberChanged } from "./member-access.js";
17
- import { parseWeeklyGoal, weeklyGoalProgress } from "./weekly-goal.js";
19
+ import { parseWeeklyGoal, resolveFirstWeekday, weeklyGoalProgress, type Weekday } from "./weekly-goal.js";
18
20
  import { canKeepGoal, goalChoices, goalOwner, pickableGoal, readMemberGoal, saveMemberGoal, type GoalStore } from "./performance-tracker-goal.js";
19
21
  import { DEFAULT_WEEKLY_GOAL, MAX_ALL_TIME_SESSIONS, MAX_PAGES, allTimeSessions, sessionsInWeek, streakMayBeLonger, weekRange, weeklyStreak } from "./performance-tracker-weeks.js";
20
22
  import type { MemberBookingRow } from "./member-bookings.js";
@@ -32,7 +34,7 @@ export interface PerformanceTrackerState {
32
34
  status: "loading" | "ready" | "error";
33
35
  /** A guest, or a member Wix refused: the section asks to sign in instead of reading. */
34
36
  signedOut: boolean;
35
- /** "Nov 16 - Nov 22". */
37
+ /** "Nov 22 - Nov 28": the week's first to last day. */
36
38
  weekRange: string;
37
39
  /** "1 of 2 sessions this week". */
38
40
  goalLabel: string;
@@ -50,7 +52,7 @@ export interface PerformanceTrackerState {
50
52
  goalLocked: boolean; goalUnlocked: boolean;
51
53
  /** "Weeks of meeting my goal": the count, then its label ("Week of..." for one). */
52
54
  streak: string; streakLabel: string;
53
- /** "500+" past the source's cap, then "Sessions attended in total". */
55
+ /** "500+" past the source's cap, then "All-time sessions" (booked and held, not attended: no check-in is readable). */
54
56
  total: string; totalLabel: string;
55
57
  notLoading: boolean; notErrored: boolean; notSignedOut: boolean;
56
58
  /** Nothing to show yet: loading, failed or signed out. */
@@ -64,17 +66,18 @@ export function registerPerformanceTrackerSection(serviceName: string, options:
64
66
  const showTotal = options.showTotal !== false;
65
67
  const sessionsLabel = (n: number): string => copyPlural("performanceTracker.goalSessions", "{n, plural, one {# Session} other {# Sessions}}", n);
66
68
  const weeksLabel = (n: number): string => copyPlural("performanceTracker.weeksMeetingGoal", "{n, plural, one {Week of meeting my goal} other {Weeks of meeting my goal}}", n);
67
- const attendedLabel = (n: number): string => copyPlural("performanceTracker.sessionsAttended", "{n, plural, one {Session attended in total} other {Sessions attended in total}}", n);
69
+ // Not the source's "Sessions attended in total": the count is of sessions booked and held, and a member cannot read a check-in.
70
+ const totalSessionsLabel = (): string => copyParam("performanceTracker.allTimeSessions", "All-time sessions");
68
71
  const blank = {
69
72
  goalLabel: "", remainingLabel: "", progress: 0, ringText: "", streak: "", total: "",
70
73
  goalOptions: [] as GoalOption[], goalDraft: "", goalValue: "", goalSessions: "", goalOpen: false, goalLocked: false, goalUnlocked: true,
71
74
  streakLabel: "", totalLabel: "",
72
75
  };
73
- const view = (status: PerformanceTrackerState["status"], signedOut: boolean, fields: Partial<typeof blank> = {}, now?: number): PerformanceTrackerState => {
76
+ const view = (status: PerformanceTrackerState["status"], signedOut: boolean, fields: Partial<typeof blank> = {}, week?: { now: number; firstWeekday: Weekday }): PerformanceTrackerState => {
74
77
  const noContent = !(status === "ready" && !signedOut);
75
78
  return {
76
79
  // No clock read at registration (a worker boots deterministically): the range is set by the load.
77
- status, signedOut, weekRange: now === undefined ? "" : weekRange(now), ...blank, ...fields,
80
+ status, signedOut, weekRange: week === undefined ? "" : weekRange(week.now, week.firstWeekday), ...blank, ...fields,
78
81
  notLoading: status !== "loading", notErrored: status !== "error", notSignedOut: !signedOut,
79
82
  noContent, noTotal: noContent || !showTotal,
80
83
  };
@@ -85,33 +88,38 @@ export function registerPerformanceTrackerSection(serviceName: string, options:
85
88
  try { return host.himalaya?.storage ?? host.localStorage; } catch { return undefined; }
86
89
  };
87
90
  // What the last read found, so choosing a goal repaints this week's numbers without reading the bookings again.
88
- let found: { rows: MemberBookingRow[]; now: number; unreadRemain: boolean; owner: string; locked: boolean } | undefined;
91
+ let found: { rows: MemberBookingRow[]; now: number; firstWeekday: Weekday; unreadRemain: boolean; owner: string; locked: boolean } | undefined;
89
92
  const ready = (read: NonNullable<typeof found>, goal: number): PerformanceTrackerState => {
90
- const { rows, now, unreadRemain } = read;
91
- const progress = weeklyGoalProgress(sessionsInWeek(rows, now, 0), goal);
93
+ const { rows, now, firstWeekday, unreadRemain } = read;
94
+ const progress = weeklyGoalProgress(sessionsInWeek(rows, now, 0, firstWeekday), goal);
92
95
  const total = allTimeSessions(rows, now);
93
- const streak = weeklyStreak(rows, now, goal);
96
+ const streak = weeklyStreak(rows, now, goal, firstWeekday);
94
97
  return view("ready", false, {
95
98
  goalLabel: progress.label, remainingLabel: progress.remainingLabel, progress: progress.fraction,
96
99
  ringText: `${formatNumber(progress.done)}/${formatNumber(progress.goal)}`,
97
100
  goalOptions: goalChoices(progress.goal).map((n) => ({ id: String(n), label: formatNumber(n) })),
98
101
  goalDraft: String(progress.goal), goalValue: String(progress.goal), goalSessions: sessionsLabel(progress.goal),
99
102
  goalLocked: read.locked, goalUnlocked: !read.locked,
100
- streak: `${formatNumber(streak)}${streakMayBeLonger(rows, now, goal, streak, unreadRemain) ? "+" : ""}`, streakLabel: weeksLabel(streak),
103
+ streak: `${formatNumber(streak)}${streakMayBeLonger(rows, now, goal, streak, unreadRemain, firstWeekday) ? "+" : ""}`, streakLabel: weeksLabel(streak),
101
104
  total: total > MAX_ALL_TIME_SESSIONS ? `${formatNumber(MAX_ALL_TIME_SESSIONS)}+` : `${formatNumber(total)}${unreadRemain ? "+" : ""}`,
102
- totalLabel: attendedLabel(Math.min(total, MAX_ALL_TIME_SESSIONS)),
103
- }, now);
105
+ totalLabel: totalSessionsLabel(),
106
+ }, { now, firstWeekday });
104
107
  };
105
108
  // A guest, or a member Wix refused, keeps the default goal and is asked to sign in to change it.
106
109
  const signedOut = () => view("ready", true, { goalSessions: sessionsLabel(defaultGoal) });
107
110
  // Only the newest load may answer: a guest read that finishes after the member signed in must not overwrite the member's progress.
108
111
  let sequence = 0;
112
+ let pinnedFirstWeekday: unknown;
109
113
  const initial = view("loading", false);
110
114
  // The member changed: the progress already published is the previous member's, so it goes at once.
111
115
  const restart = () => { void service.clear(); void service.load(); };
112
116
  type State = PerformanceTrackerState;
113
117
  const load = async (_state: State, arg?: unknown): Promise<State | undefined> => {
114
118
  stashCopy(arg);
119
+ // A pinned first day is kept for the Refresh and sign-in reloads, which carry no params. After the copy is stashed: the app
120
+ // language it carries decides the first day otherwise.
121
+ if (arg && typeof arg === "object" && "firstWeekday" in arg) pinnedFirstWeekday = (arg as { firstWeekday?: unknown }).firstWeekday;
122
+ const firstWeekday = resolveFirstWeekday(pinnedFirstWeekday);
115
123
  const seq = ++sequence;
116
124
  let member: Awaited<ReturnType<typeof memberAccess>> | undefined;
117
125
  try {
@@ -128,7 +136,7 @@ export function registerPerformanceTrackerSection(serviceName: string, options:
128
136
  const unreadRemain = Boolean(page.nextCursor);
129
137
  if (seq !== sequence) return undefined;
130
138
  const owner = goalOwner(member);
131
- found = { rows, now, unreadRemain, owner, locked: !canKeepGoal(goalStore(), owner) };
139
+ found = { rows, now, firstWeekday, unreadRemain, owner, locked: !canKeepGoal(goalStore(), owner) };
132
140
  return ready(found, readMemberGoal(goalStore(), owner) || defaultGoal);
133
141
  } catch (error) {
134
142
  if (seq !== sequence) return undefined;
@@ -1,9 +1,13 @@
1
1
  // What a performance tracker counts, as pure functions over a member's bookings (no network, no clock read: `now` is an argument), so
2
2
  // the rules are unit-tested directly. A session is what My Bookings' "This week" card counts (`isHeldSession` in `weekly-goal.ts`):
3
- // the section and that card can never disagree.
3
+ // the section and that card can never disagree. Every week starts on `firstWeekday` (`resolveFirstWeekday` in `weekly-goal.ts`), so the
4
+ // range the section shows and the weeks it counts are the same days.
5
+ //
6
+ // A held session is not an attended one: a member's booking carries no check-in (Wix attendance is owner-scoped), so the all-time
7
+ // number is of sessions booked that already took place, and is labelled so.
4
8
  import { formatMonthDay } from "./engine-intl.js";
5
9
  import type { MemberBookingRow } from "./member-bookings.js";
6
- import { isHeldSession, weekStartMs, weeklySessionsDone } from "./weekly-goal.js";
10
+ import { isHeldSession, sessionKey, weekStartMs, weeklySessionsDone, type Weekday } from "./weekly-goal.js";
7
11
 
8
12
  /** The source's default weekly goal. */
9
13
  export const DEFAULT_WEEKLY_GOAL = 2;
@@ -14,28 +18,31 @@ export const STREAK_WEEKS = 52;
14
18
  /** 11 pages of 50 past bookings: enough to tell "500 or fewer" from "more", and to reach a year back. */
15
19
  export const MAX_PAGES = 11;
16
20
 
17
- /** Monday 00:00 local, `weeksBack` weeks before the week `now` is in (DST-safe: calendar days, not 7 * 24 h). */
18
- const weekStartBack = (now: number, weeksBack: number): number => {
19
- const d = new Date(weekStartMs(now));
21
+ /** The week's first day 00:00 local, `weeksBack` weeks before the week `now` is in (DST-safe: calendar days, not 7 * 24 h). Each
22
+ * week's start is found again from noon of a day in it: where a clock change skips midnight (Santiago, Havana, Beirut change on a
23
+ * Sunday), that week starts at 01:00, and stepping back from 01:00 would put every older week an hour late. */
24
+ const weekStartBack = (now: number, weeksBack: number, firstWeekday: Weekday): number => {
25
+ const d = new Date(weekStartMs(now, firstWeekday));
26
+ d.setHours(12, 0, 0, 0);
20
27
  d.setDate(d.getDate() - 7 * weeksBack);
21
- return d.getTime();
28
+ return weekStartMs(d.getTime(), firstWeekday);
22
29
  };
23
30
 
24
31
  /** Sessions held in the week `weeksBack` weeks before `now`'s (0 = this week, up to `now`). */
25
- export function sessionsInWeek(rows: readonly MemberBookingRow[], now: number, weeksBack: number): number {
26
- // A millisecond before the next Monday is still in that week, and `weeklySessionsDone` takes its week from the instant it is given.
27
- return weeklySessionsDone(rows, weeksBack === 0 ? now : weekStartBack(now, weeksBack - 1) - 1);
32
+ export function sessionsInWeek(rows: readonly MemberBookingRow[], now: number, weeksBack: number, firstWeekday: Weekday): number {
33
+ // A millisecond before the next week starts is still in that week, and `weeklySessionsDone` takes its week from the instant it is given.
34
+ return weeklySessionsDone(rows, weeksBack === 0 ? now : weekStartBack(now, weeksBack - 1, firstWeekday) - 1, firstWeekday);
28
35
  }
29
36
 
30
37
  /**
31
38
  * Consecutive weeks that met `goal`, newest first. The week still running counts once it has met the goal and never breaks the
32
39
  * streak while it has not: the member still has days left.
33
40
  */
34
- export function weeklyStreak(rows: readonly MemberBookingRow[], now: number, goal: number): number {
35
- const current = sessionsInWeek(rows, now, 0);
41
+ export function weeklyStreak(rows: readonly MemberBookingRow[], now: number, goal: number, firstWeekday: Weekday): number {
42
+ const current = sessionsInWeek(rows, now, 0, firstWeekday);
36
43
  let streak = 0;
37
44
  for (let back = current >= goal ? 0 : 1; back < STREAK_WEEKS; back++) {
38
- if ((back === 0 ? current : sessionsInWeek(rows, now, back)) < goal) break;
45
+ if ((back === 0 ? current : sessionsInWeek(rows, now, back, firstWeekday)) < goal) break;
39
46
  streak++;
40
47
  }
41
48
  return streak;
@@ -45,26 +52,26 @@ export function weeklyStreak(rows: readonly MemberBookingRow[], now: number, goa
45
52
  * Whether `streak` may be longer than the rows show: the read stopped at the page cap with older bookings unread, and the run of weeks
46
53
  * reaches the oldest week those rows cover (an older week the rows do not hold looks empty and would end the run early).
47
54
  */
48
- export function streakMayBeLonger(rows: readonly MemberBookingRow[], now: number, goal: number, streak: number, unreadRemain: boolean): boolean {
55
+ export function streakMayBeLonger(rows: readonly MemberBookingRow[], now: number, goal: number, streak: number, unreadRemain: boolean, firstWeekday: Weekday): boolean {
49
56
  if (!unreadRemain) return false;
50
57
  const starts = rows.map((row) => Date.parse(row.start)).filter(Number.isFinite);
51
58
  if (!starts.length) return false;
52
59
  const week = 7 * 24 * 3600 * 1000;
53
- const oldestBack = Math.round((weekStartMs(now) - weekStartMs(Math.min(...starts))) / week);
54
- const firstWeek = sessionsInWeek(rows, now, 0) >= goal ? 0 : 1;
60
+ const oldestBack = Math.round((weekStartMs(now, firstWeekday) - weekStartMs(Math.min(...starts), firstWeekday)) / week);
61
+ const firstWeek = sessionsInWeek(rows, now, 0, firstWeekday) >= goal ? 0 : 1;
55
62
  // A run that ended at the 52-week look-back ended by the source's own limit: older bookings cannot lengthen it.
56
63
  if (firstWeek + streak >= STREAK_WEEKS) return false;
57
64
  return firstWeek + streak >= oldestBack;
58
65
  }
59
66
 
60
- /** Sessions held, all time (one per booking id). */
67
+ /** Sessions booked that already took place, all time (one per booking id). NOT sessions attended: see the file header. */
61
68
  export function allTimeSessions(rows: readonly MemberBookingRow[], now: number): number {
62
- return new Set(rows.filter((row) => isHeldSession(row, now)).map((row) => row.id || `${row.start}|${row.title}`)).size;
69
+ return new Set(rows.filter((row) => isHeldSession(row, now)).map(sessionKey)).size;
63
70
  }
64
71
 
65
- /** "Nov 16 - Nov 22" (the source's `{startDate} - {endDate}`): Monday to Sunday of the week `now` is in. */
66
- export function weekRange(now: number): string {
67
- const start = new Date(weekStartMs(now));
72
+ /** "Nov 22 - Nov 28" (the source's `{startDate} - {endDate}`): the first to the last day of the week `now` is in. */
73
+ export function weekRange(now: number, firstWeekday: Weekday): string {
74
+ const start = new Date(weekStartMs(now, firstWeekday));
68
75
  const end = new Date(start);
69
76
  end.setDate(end.getDate() + 6);
70
77
  return `${formatMonthDay(start)} - ${formatMonthDay(end)}`;
@@ -3,19 +3,28 @@
3
3
  // card (himi-booking-bookings), so the two can never count differently.
4
4
  //
5
5
  // WHAT COUNTS as a session toward the goal: a CONFIRMED booking whose start falls in the CURRENT
6
- // calendar week (Monday 00:00 local → now) and is already in the past. An allow-list, not a
6
+ // calendar week (its first day 00:00 local → now) and is already in the past. An allow-list, not a
7
7
  // deny-list: CREATED (checkout never completed), PENDING / PENDING_APPROVAL / PENDING_CHECKOUT,
8
8
  // WAITING_LIST, CANCELED and DECLINED — and any status Wix adds later — do not count. That is
9
9
  // "booked and it happened", not verified
10
10
  // attendance: the member-scoped queryBookings row carries no attendance/check-in field (the Wix
11
11
  // Attendance API is owner-scoped), so a no-show still counts. Future bookings this week do not
12
- // count — they have not happened yet.
12
+ // count — they have not happened yet. So every count here is of HELD sessions, never of attendance:
13
+ // a label that shows one must not say "attended".
14
+ //
15
+ // THE WEEK starts on the first day of the app language's region (CLDR week data: Sunday for "en" /
16
+ // "en-US", Monday for "en-GB" or "de", Saturday for "ar-EG"), as the migrated source starts it. A
17
+ // screen may pin another day with a `firstWeekday` onAppear param (0 = Sunday … 6 = Saturday).
18
+ // `firstWeekdayOf` reads ECMA-402 week info where the engine has it and a CLDR table where it has
19
+ // not, so iOS, Android and web agree on the same week.
13
20
  //
14
21
  // DETERMINISM: nothing here runs at worker boot; every clock read is an argument. PURE (no network,
15
22
  // no bridge) so the rules are unit-tested directly; the read lives with its caller.
16
23
 
17
24
  import type { MemberBookingRow } from "./member-bookings.js";
18
25
  import { copyParam, copyTemplate } from "./himi-copy.js";
26
+ import type { Weekday } from "./engine-intl.js";
27
+ export { MONDAY, firstWeekdayOf, resolveFirstWeekday, type Weekday } from "./engine-intl.js";
19
28
 
20
29
  export const MAX_WEEKLY_SESSION_GOAL = 21;
21
30
 
@@ -32,27 +41,33 @@ export function parseWeeklyGoal(raw: unknown): number {
32
41
  return Number.isInteger(n) && n >= 1 ? Math.min(n, MAX_WEEKLY_SESSION_GOAL) : 0;
33
42
  }
34
43
 
35
- /** Monday 00:00 local of `now`'s week, epoch ms. */
36
- export function weekStartMs(now: number): number {
44
+ /** 00:00 local of the first day (`firstWeekday`) of `now`'s week, epoch ms. */
45
+ export function weekStartMs(now: number, firstWeekday: Weekday): number {
37
46
  const d = new Date(now);
38
47
  d.setHours(0, 0, 0, 0);
39
- d.setDate(d.getDate() - ((d.getDay() + 6) % 7));
48
+ d.setDate(d.getDate() - ((d.getDay() - firstWeekday + 7) % 7));
40
49
  return d.getTime();
41
50
  }
42
51
 
43
- /** Is `row` a session that was booked and already held at `now`? The one rule every count here uses. */
52
+ /** Is `row` a session that was booked and already held at `now`? The one rule every count here uses.
53
+ * Held, not attended: the member's booking row carries no check-in. */
44
54
  export function isHeldSession(row: MemberBookingRow, now: number): boolean {
45
55
  const start = Date.parse(row.start);
46
56
  return Number.isFinite(start) && start < now && COUNTS_AS_SESSION.test((row.status || "").trim().toUpperCase());
47
57
  }
48
58
 
59
+ /** The key one booking counts under: a booking read twice (two pages, a retry) counts once. */
60
+ export function sessionKey(row: MemberBookingRow): string {
61
+ return row.id || `${row.start}|${row.title}`;
62
+ }
63
+
49
64
  /** Sessions toward the goal among `rows` — see the file header for what counts. */
50
- export function weeklySessionsDone(rows: readonly MemberBookingRow[], now: number): number {
51
- const from = weekStartMs(now);
65
+ export function weeklySessionsDone(rows: readonly MemberBookingRow[], now: number, firstWeekday: Weekday): number {
66
+ const from = weekStartMs(now, firstWeekday);
52
67
  const seen = new Set<string>();
53
68
  for (const row of rows) {
54
69
  if (Date.parse(row.start) < from || !isHeldSession(row, now)) continue;
55
- seen.add(row.id || `${row.start}|${row.title}`);
70
+ seen.add(sessionKey(row));
56
71
  }
57
72
  return seen.size;
58
73
  }
@@ -64,14 +79,15 @@ export interface BookingsPage {
64
79
 
65
80
  /** Sessions toward the goal from PAST bookings read newest-first: `first` is the first page, and
66
81
  * `next(cursor)` reads more only while the oldest row so far is still inside this week (a page of
67
- * 50 almost always reaches back before Monday). Bounded to MAX_WEEKLY_PAGES reads; a failing
82
+ * 50 almost always reaches back before the week's first day). Bounded to MAX_WEEKLY_PAGES reads; a failing
68
83
  * read rejects, so the caller hides the count rather than under-counting. */
69
84
  export async function weeklySessionsFromPages(
70
85
  first: BookingsPage,
71
86
  next: (cursor: string) => Promise<BookingsPage>,
72
87
  now: number,
88
+ firstWeekday: Weekday,
73
89
  ): Promise<number> {
74
- const from = weekStartMs(now);
90
+ const from = weekStartMs(now, firstWeekday);
75
91
  const rows = [...first.items];
76
92
  let page = first;
77
93
  for (let read = 1; read < MAX_WEEKLY_PAGES && page.nextCursor; read++) {
@@ -80,7 +96,7 @@ export async function weeklySessionsFromPages(
80
96
  page = await next(page.nextCursor);
81
97
  rows.push(...page.items);
82
98
  }
83
- return weeklySessionsDone(rows, now);
99
+ return weeklySessionsDone(rows, now, firstWeekday);
84
100
  }
85
101
 
86
102
  export interface WeeklyGoalProgress {
@@ -10,7 +10,7 @@ import { memberAccess, assertMemberAccess, memberAccessChanged, memberAccessDeni
10
10
  import { fetchMemberBookings, CANCELLED_STATUSES, UNCONFIRMED_STATUSES, type MemberBookingRow } from "../_shared/member-bookings.js";
11
11
  import { emitHostEvent } from "../_shared/host-events.js";
12
12
  import { formatClock, formatClockRange, formatDateMedium, formatMonthDay, formatWeekdayMonthDay, formatWeekdayMonthDayLong } from "../_shared/engine-intl.js";
13
- import { parseWeeklyGoal, weeklyGoalProgress, weeklySessionsFromPages } from "../_shared/weekly-goal.js";
13
+ import { parseWeeklyGoal, resolveFirstWeekday, weeklyGoalProgress, weeklySessionsFromPages } from "../_shared/weekly-goal.js";
14
14
 
15
15
  // My Bookings: Upcoming / Past / Canceled tabs over the member's own bookings, a booking sheet with
16
16
  // the details and the actions (add to calendar, directions, Book Again, Cancel Booking with a
@@ -50,6 +50,9 @@ let consumedBookingId = "";
50
50
  // count comes from a dedicated read of this week's PAST bookings on each first-page fetch, NOT
51
51
  // from `rows` (those follow the list's tab — Upcoming by default — and would read 0).
52
52
  let weeklyGoal = 0;
53
+ /** The onAppear `firstWeekday` param when the screen pins one; absent, the week starts on the app
54
+ * language's first day (`resolveFirstWeekday`), the rule every weekly count shares. */
55
+ let firstWeekdayParam: unknown;
53
56
  /** The count of the page that APPLIED — set in `apply`, never by a fetch, so a superseded fetch
54
57
  * (another member, a refresh) cannot overwrite it: it travels in that page's metadata and is
55
58
  * dropped with it. */
@@ -66,7 +69,7 @@ async function fetchWeeklySessionsDone(member: MemberAccess, now: number): Promi
66
69
  try {
67
70
  const nowIso = new Date(now).toISOString();
68
71
  const read = (cursor: string) => fetchMemberBookings({ query: "", filter: "value:Past", sort: "za", savedIds: [] }, cursor, nowIso, member);
69
- return await weeklySessionsFromPages(await read(""), read, now);
72
+ return await weeklySessionsFromPages(await read(""), read, now, resolveFirstWeekday(firstWeekdayParam));
70
73
  } catch {
71
74
  return null;
72
75
  }
@@ -304,6 +307,8 @@ const svc = defineBackendCollection<S, MemberBookingRow>("himiBookingBookings",
304
307
  readResultSnackbar(arg);
305
308
  const goal = parseWeeklyGoal((arg as Record<string, unknown> | undefined)?.weeklyGoal);
306
309
  if (goal) weeklyGoal = goal;
310
+ const pinnedWeekday = (arg as Record<string, unknown> | undefined)?.firstWeekday;
311
+ if (pinnedWeekday !== undefined) firstWeekdayParam = pinnedWeekday;
307
312
  // A deep link (the home "next booking", the place summary) names a booking: open its sheet once
308
313
  // its row is on the first page. `date` alone does nothing now (there is no day view).
309
314
  const linked = runtime()?.input?.bookingId;
@@ -30,7 +30,7 @@ import { cleanTitle, initials } from "../_shared/himi-text.js";
30
30
  import { LAYOUT_KEY, type LayoutId, recommendLayout, resolveLayout } from "../_shared/himi-layouts.js";
31
31
  import { copyParam, copyTemplate, stashCopy } from "../_shared/himi-copy.js";
32
32
  import { groupMemberCount } from "../_shared/group-member-count.js";
33
- import { parseWeeklyGoal, weeklyGoalProgress, weeklySessionsFromPages } from "../_shared/weekly-goal.js";
33
+ import { parseWeeklyGoal, resolveFirstWeekday, weekStartMs, weeklyGoalProgress, weeklySessionsFromPages, type Weekday } from "../_shared/weekly-goal.js";
34
34
  import { isBridgeUnavailable } from "../_shared/owner-load-error.js";
35
35
  import { formatDateMedium } from "../_shared/engine-intl.js";
36
36
  import { listSavedProducts, type SavedProduct } from "../_shared/himi-store-saved.js";
@@ -1316,11 +1316,9 @@ async function refreshPublic(state: State, arg?: unknown): Promise<State | undef
1316
1316
 
1317
1317
  let personalGeneration = 0;
1318
1318
  let shopCategoryActivation = 0;
1319
- function memberSchedule(rows: MemberBookingRow[], now = new Date()): { label: string; fraction: number } {
1320
- const weekStart = new Date(now);
1321
- const day = (weekStart.getDay() + 6) % 7;
1322
- weekStart.setDate(weekStart.getDate() - day);
1323
- weekStart.setHours(0, 0, 0, 0);
1319
+ function memberSchedule(rows: MemberBookingRow[], now: Date, firstWeekday: Weekday): { label: string; fraction: number } {
1320
+ // The same week as the weekly-goal Gauge beside it (`weekly-goal.ts`).
1321
+ const weekStart = new Date(weekStartMs(now.getTime(), firstWeekday));
1324
1322
  const weekEnd = new Date(weekStart);
1325
1323
  weekEnd.setDate(weekEnd.getDate() + 7);
1326
1324
  const current = rows.filter((row) => {
@@ -1344,6 +1342,8 @@ async function refreshPersonal(generation: number, arg?: unknown): Promise<void>
1344
1342
  const weeklyGoal = parseWeeklyGoal(paramValue(arg, "weeklyGoal"));
1345
1343
  if (member.email && parseVerticals(arg).includes("bookings")) {
1346
1344
  const now = new Date();
1345
+ // The week starts on the screen's `firstWeekday` (the app's language, set by the descriptor), else the worker's language.
1346
+ const firstWeekday = resolveFirstWeekday(typeof arg === "string" ? undefined : paramValue(arg, "firstWeekday"));
1347
1347
  const [upcoming, past] = await Promise.allSettled([
1348
1348
  fetchMemberBookings({ query: "", filter: "value:Upcoming", sort: "default", savedIds: [] }, "", now.toISOString(), member),
1349
1349
  fetchMemberBookings({ query: "", filter: "value:Past", sort: "za", savedIds: [] }, "", now.toISOString(), member),
@@ -1357,7 +1357,7 @@ async function refreshPersonal(generation: number, arg?: unknown): Promise<void>
1357
1357
  if (upcoming.status === "fulfilled" && past.status === "fulfilled") {
1358
1358
  // A schedule total needs both halves. Hide it rather than under-counting
1359
1359
  // when either query failed.
1360
- progress = memberSchedule([...upcoming.value.items, ...past.value.items], now);
1360
+ progress = memberSchedule([...upcoming.value.items, ...past.value.items], now, firstWeekday);
1361
1361
  }
1362
1362
  if (weeklyGoal > 0 && past.status === "fulfilled") {
1363
1363
  // The goal counts sessions that already HAPPENED this week (_shared/weekly-goal.ts). A
@@ -1367,7 +1367,7 @@ async function refreshPersonal(generation: number, arg?: unknown): Promise<void>
1367
1367
  try {
1368
1368
  const readPast = (cursor: string) =>
1369
1369
  fetchMemberBookings({ query: "", filter: "value:Past", sort: "za", savedIds: [] }, cursor, now.toISOString(), member);
1370
- const goal = weeklyGoalProgress(await weeklySessionsFromPages(past.value, readPast, now.getTime()), weeklyGoal);
1370
+ const goal = weeklyGoalProgress(await weeklySessionsFromPages(past.value, readPast, now.getTime(), firstWeekday), weeklyGoal);
1371
1371
  weekly = { count: goal.done, fraction: goal.fraction, label: goal.label };
1372
1372
  } catch {
1373
1373
  weekly = null;
@@ -27,6 +27,21 @@ export function hasIntl(): boolean {
27
27
  return typeof Intl !== "undefined";
28
28
  }
29
29
 
30
+ /** ECMA-402's first day of the week for `locale` (1 = Monday … 7 = Sunday), or undefined where this engine has no
31
+ * `Intl.Locale` week info (QuickJS has no `Intl`; older JSC / V8 / Hermes have no week info). Callers keep a CLDR table for
32
+ * that case, so every engine starts the same week (`weekly-goal.ts` `firstWeekdayOf`). */
33
+ export function intlFirstDayOfWeek(locale: string): number | undefined {
34
+ try {
35
+ // The guard form `worker-globals:check` reads as guarded: the `Intl` use sits inside the `typeof` test's block.
36
+ if (typeof Intl !== "undefined" && typeof Intl.Locale === "function") {
37
+ const loc = new Intl.Locale(locale) as Intl.Locale & { getWeekInfo?: () => { firstDay?: number }; weekInfo?: { firstDay?: number } };
38
+ const firstDay = (typeof loc.getWeekInfo === "function" ? loc.getWeekInfo() : loc.weekInfo)?.firstDay;
39
+ if (typeof firstDay === "number" && Number.isInteger(firstDay) && firstDay >= 1 && firstDay <= 7) return firstDay;
40
+ }
41
+ } catch { /* a malformed tag */ }
42
+ return undefined;
43
+ }
44
+
30
45
  /** The device's IANA time zone, or "UTC" where this engine has no ECMA-402 or no zone data. */
31
46
  export function deviceTimeZone(): string {
32
47
  try {
@@ -536,3 +551,53 @@ export function formatTimeZoneLabel(date: Date, timeZone: string, locale = "en")
536
551
  }
537
552
  return "";
538
553
  }
554
+
555
+ // ── The first day of the week ──────────────────────────────────────────────────────────────────────────────────────────────
556
+ // 0 = Sunday … 6 = Saturday, for the app language: the one rule every weekly count and every week a screen shows uses
557
+ // (`weekly-goal.ts`, the performance tracker, the Agenda's descriptor, the one-app generator). CLDR week data: Sunday for "en" /
558
+ // "en-US", Monday for "en-GB" or "de", Saturday for "ar-EG". ECMA-402 week info where the engine has it (`intlFirstDayOfWeek`),
559
+ // a CLDR table where it has not, so iOS, Android, web and a build host agree. It lives here rather than in its own file because
560
+ // every generated template already ships this module, and the public catalog's manifest lists each template file.
561
+
562
+ /** 0 = Sunday … 6 = Saturday, as `Date.prototype.getDay`. */
563
+ export type Weekday = 0 | 1 | 2 | 3 | 4 | 5 | 6;
564
+ export const MONDAY: Weekday = 1;
565
+
566
+ // CLDR `weekData.firstDay` (supplemental data), by region: every region not listed starts on Monday.
567
+ const SUNDAY_REGIONS = new Set("AG AS BD BR BS BT BW BZ CA CN CO DM DO ET GT GU HK HN ID IL IN JM JP KE KH KR LA MH MM MO MT MX MZ NI NP PA PE PH PK PR PT PY SA SG SV TH TT TW UM US VE VI WS YE ZA ZW".split(" "));
568
+ const SATURDAY_REGIONS = new Set("AE AF BH DJ DZ EG IQ IR JO KW LY OM QA SD SY".split(" "));
569
+ const FRIDAY_REGIONS = new Set(["MV"]);
570
+ // The region CLDR's likely subtags give a bare language, for the languages whose region does not start on Monday.
571
+ const LIKELY_REGION: Record<string, string> = {
572
+ en: "US", he: "IL", iw: "IL", ar: "EG", pt: "BR", ja: "JP", zh: "CN", ko: "KR", hi: "IN", bn: "BD", th: "TH", id: "ID",
573
+ fa: "IR", ur: "PK", my: "MM", km: "KH", lo: "LA", ne: "NP", am: "ET", mr: "IN", ta: "IN", te: "IN", gu: "IN", kn: "IN",
574
+ ml: "IN", pa: "IN", fil: "PH", tl: "PH", zu: "ZA", dz: "BT", dv: "MV", ps: "AF",
575
+ };
576
+
577
+ /** The region of a language tag ("en-GB" → "GB", "zh-Hant-TW" → "TW"), else its language's likely region, else "". */
578
+ function regionOf(locale: string): string {
579
+ const parts = locale.split(/[-_]/);
580
+ const region = parts.slice(1).find((p) => /^(?:[A-Za-z]{2}|\d{3})$/.test(p));
581
+ if (region) return region.toUpperCase();
582
+ // A script with no region: Traditional Chinese is Taiwan's.
583
+ if (parts[0]?.toLowerCase() === "zh" && parts.some((p) => p.toLowerCase() === "hant")) return "TW";
584
+ return LIKELY_REGION[(parts[0] ?? "").toLowerCase()] ?? "";
585
+ }
586
+
587
+ /** The first day of the week for `locale` (the app language by default). */
588
+ export function firstWeekdayOf(locale: string = appLocale()): Weekday {
589
+ // ECMA-402 numbers the days 1 = Monday … 7 = Sunday. A malformed tag or an engine without week info: the CLDR table below.
590
+ const firstDay = intlFirstDayOfWeek(locale);
591
+ if (firstDay !== undefined) return (firstDay % 7) as Weekday;
592
+ const region = regionOf(locale);
593
+ if (SUNDAY_REGIONS.has(region)) return 0;
594
+ if (SATURDAY_REGIONS.has(region)) return 6;
595
+ if (FRIDAY_REGIONS.has(region)) return 5;
596
+ return MONDAY;
597
+ }
598
+
599
+ /** A screen's `firstWeekday` param (0..6, or its text) when it pins one, else the app language's first day. */
600
+ export function resolveFirstWeekday(raw?: unknown, locale: string = appLocale()): Weekday {
601
+ const n = typeof raw === "number" ? raw : typeof raw === "string" && raw.trim() !== "" ? Number(raw) : NaN;
602
+ return Number.isInteger(n) && n >= 0 && n <= 6 ? (n as Weekday) : firstWeekdayOf(locale);
603
+ }
@@ -2403,6 +2403,7 @@ const SCREENS = runtimeSetting({
2403
2403
  "verticals": "[\"feed\",\"events\",\"blog\",\"groups\",\"cms\"]",
2404
2404
  "homeModules": "[{\"id\":\"saved\",\"label\":\"Saved on this device\",\"dataSource\":\"device.saved_items\",\"emptyWhen\":[\"noSavedContent\"]},{\"id\":\"section_0\",\"label\":\"Discover 1\",\"dataSource\":\"communityPulse.section0\",\"emptyWhen\":[\"noMemberAvatars\"]},{\"id\":\"section_1\",\"label\":\"Announcement\",\"dataSource\":\"communityPulse.section1\",\"emptyWhen\":[\"noAnnouncement\",\"noUpcomingEvents\"]},{\"id\":\"section_2\",\"label\":\"Groups\",\"dataSource\":\"communityPulse.section2\",\"emptyWhen\":[\"noGroupCards\"]},{\"id\":\"section_3\",\"label\":\"Latest activity\",\"dataSource\":\"communityPulse.section3\"}]",
2405
2405
  "ownerDefaultLayout": "communityPulse",
2406
+ "firstWeekday": "0",
2406
2407
  "copy": "{\"home.activityTitle\":\"Latest activity\",\"home.announcementCaption\":\"Announcement\",\"home.eventsTitle\":\"Upcoming events\",\"home.groupsSubtitle\":\"Find your people.\",\"home.groupsTitle\":\"Groups\",\"home.membersCaption\":\"Our members\",\"home.onboardingBody\":\"Join groups, RSVP to events, and keep up with the community feed — all in one place.\",\"home.profileBody\":\"Sign in for RSVPs, groups and saved posts.\"}"
2407
2408
  }
2408
2409
  }
@@ -27,6 +27,21 @@ export function hasIntl(): boolean {
27
27
  return typeof Intl !== "undefined";
28
28
  }
29
29
 
30
+ /** ECMA-402's first day of the week for `locale` (1 = Monday … 7 = Sunday), or undefined where this engine has no
31
+ * `Intl.Locale` week info (QuickJS has no `Intl`; older JSC / V8 / Hermes have no week info). Callers keep a CLDR table for
32
+ * that case, so every engine starts the same week (`weekly-goal.ts` `firstWeekdayOf`). */
33
+ export function intlFirstDayOfWeek(locale: string): number | undefined {
34
+ try {
35
+ // The guard form `worker-globals:check` reads as guarded: the `Intl` use sits inside the `typeof` test's block.
36
+ if (typeof Intl !== "undefined" && typeof Intl.Locale === "function") {
37
+ const loc = new Intl.Locale(locale) as Intl.Locale & { getWeekInfo?: () => { firstDay?: number }; weekInfo?: { firstDay?: number } };
38
+ const firstDay = (typeof loc.getWeekInfo === "function" ? loc.getWeekInfo() : loc.weekInfo)?.firstDay;
39
+ if (typeof firstDay === "number" && Number.isInteger(firstDay) && firstDay >= 1 && firstDay <= 7) return firstDay;
40
+ }
41
+ } catch { /* a malformed tag */ }
42
+ return undefined;
43
+ }
44
+
30
45
  /** The device's IANA time zone, or "UTC" where this engine has no ECMA-402 or no zone data. */
31
46
  export function deviceTimeZone(): string {
32
47
  try {
@@ -536,3 +551,53 @@ export function formatTimeZoneLabel(date: Date, timeZone: string, locale = "en")
536
551
  }
537
552
  return "";
538
553
  }
554
+
555
+ // ── The first day of the week ──────────────────────────────────────────────────────────────────────────────────────────────
556
+ // 0 = Sunday … 6 = Saturday, for the app language: the one rule every weekly count and every week a screen shows uses
557
+ // (`weekly-goal.ts`, the performance tracker, the Agenda's descriptor, the one-app generator). CLDR week data: Sunday for "en" /
558
+ // "en-US", Monday for "en-GB" or "de", Saturday for "ar-EG". ECMA-402 week info where the engine has it (`intlFirstDayOfWeek`),
559
+ // a CLDR table where it has not, so iOS, Android, web and a build host agree. It lives here rather than in its own file because
560
+ // every generated template already ships this module, and the public catalog's manifest lists each template file.
561
+
562
+ /** 0 = Sunday … 6 = Saturday, as `Date.prototype.getDay`. */
563
+ export type Weekday = 0 | 1 | 2 | 3 | 4 | 5 | 6;
564
+ export const MONDAY: Weekday = 1;
565
+
566
+ // CLDR `weekData.firstDay` (supplemental data), by region: every region not listed starts on Monday.
567
+ const SUNDAY_REGIONS = new Set("AG AS BD BR BS BT BW BZ CA CN CO DM DO ET GT GU HK HN ID IL IN JM JP KE KH KR LA MH MM MO MT MX MZ NI NP PA PE PH PK PR PT PY SA SG SV TH TT TW UM US VE VI WS YE ZA ZW".split(" "));
568
+ const SATURDAY_REGIONS = new Set("AE AF BH DJ DZ EG IQ IR JO KW LY OM QA SD SY".split(" "));
569
+ const FRIDAY_REGIONS = new Set(["MV"]);
570
+ // The region CLDR's likely subtags give a bare language, for the languages whose region does not start on Monday.
571
+ const LIKELY_REGION: Record<string, string> = {
572
+ en: "US", he: "IL", iw: "IL", ar: "EG", pt: "BR", ja: "JP", zh: "CN", ko: "KR", hi: "IN", bn: "BD", th: "TH", id: "ID",
573
+ fa: "IR", ur: "PK", my: "MM", km: "KH", lo: "LA", ne: "NP", am: "ET", mr: "IN", ta: "IN", te: "IN", gu: "IN", kn: "IN",
574
+ ml: "IN", pa: "IN", fil: "PH", tl: "PH", zu: "ZA", dz: "BT", dv: "MV", ps: "AF",
575
+ };
576
+
577
+ /** The region of a language tag ("en-GB" → "GB", "zh-Hant-TW" → "TW"), else its language's likely region, else "". */
578
+ function regionOf(locale: string): string {
579
+ const parts = locale.split(/[-_]/);
580
+ const region = parts.slice(1).find((p) => /^(?:[A-Za-z]{2}|\d{3})$/.test(p));
581
+ if (region) return region.toUpperCase();
582
+ // A script with no region: Traditional Chinese is Taiwan's.
583
+ if (parts[0]?.toLowerCase() === "zh" && parts.some((p) => p.toLowerCase() === "hant")) return "TW";
584
+ return LIKELY_REGION[(parts[0] ?? "").toLowerCase()] ?? "";
585
+ }
586
+
587
+ /** The first day of the week for `locale` (the app language by default). */
588
+ export function firstWeekdayOf(locale: string = appLocale()): Weekday {
589
+ // ECMA-402 numbers the days 1 = Monday … 7 = Sunday. A malformed tag or an engine without week info: the CLDR table below.
590
+ const firstDay = intlFirstDayOfWeek(locale);
591
+ if (firstDay !== undefined) return (firstDay % 7) as Weekday;
592
+ const region = regionOf(locale);
593
+ if (SUNDAY_REGIONS.has(region)) return 0;
594
+ if (SATURDAY_REGIONS.has(region)) return 6;
595
+ if (FRIDAY_REGIONS.has(region)) return 5;
596
+ return MONDAY;
597
+ }
598
+
599
+ /** A screen's `firstWeekday` param (0..6, or its text) when it pins one, else the app language's first day. */
600
+ export function resolveFirstWeekday(raw?: unknown, locale: string = appLocale()): Weekday {
601
+ const n = typeof raw === "number" ? raw : typeof raw === "string" && raw.trim() !== "" ? Number(raw) : NaN;
602
+ return Number.isInteger(n) && n >= 0 && n <= 6 ? (n as Weekday) : firstWeekdayOf(locale);
603
+ }