@composable-os/cli 0.1.0-beta.11 → 0.1.0-beta.13

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 (166) hide show
  1. package/dist/{accounts-UHYLCLEY.js → accounts-GOCNY6WI.js} +17 -13
  2. package/dist/app-RPRZMLU5.js +43 -0
  3. package/dist/app-upload-YJVEKZC6.js +198 -0
  4. package/dist/{blocks-5IFU25J6.js → blocks-DE4RRWPJ.js} +207 -25
  5. package/dist/{chunk-XIDLW3EP.js → chunk-2B6YUYZV.js} +23499 -11766
  6. package/dist/{run-7P4RQALH.js → chunk-2CCHB37H.js} +9 -146
  7. package/dist/{chunk-DU6OIFOU.js → chunk-3OGDWKJ3.js} +530 -434
  8. package/dist/{chunk-DHS2CV2M.js → chunk-5D7BDF4Y.js} +15 -13
  9. package/dist/{chunk-ZAWES2UD.js → chunk-6CM3WZG5.js} +13 -2483
  10. package/dist/{chunk-7D4GKZOX.js → chunk-CIBJGB5H.js} +422 -75
  11. package/dist/chunk-EPDTPGZJ.js +330 -0
  12. package/dist/{chunk-LAAL4YGR.js → chunk-HAYF4G5V.js} +66 -23
  13. package/dist/chunk-HCG6T53D.js +61904 -0
  14. package/dist/{chunk-K34UKWEI.js → chunk-JX4IFWNT.js} +64 -32
  15. package/dist/{chunk-6XTU2MTP.js → chunk-KFHKNXGH.js} +632 -418
  16. package/dist/chunk-KMFMD52Z.js +13276 -0
  17. package/dist/{chunk-E4WCYTCT.js → chunk-LX2TTLVY.js} +174 -55
  18. package/dist/{chunk-GYTEW66E.js → chunk-O3R4FS2J.js} +1 -1
  19. package/dist/{chunk-E64SG24J.js → chunk-Q6Y45DY6.js} +25 -2
  20. package/dist/{chunk-MBIKVRAC.js → chunk-QJZGYJVV.js} +823 -44
  21. package/dist/{chunk-PDD2ETVF.js → chunk-QQ3YSL5F.js} +172 -16
  22. package/dist/chunk-RGKJKC5T.js +876 -0
  23. package/dist/{chunk-YFTLIEWU.js → chunk-RSEWEFAV.js} +12 -2
  24. package/dist/{chunk-2ABSVMGB.js → chunk-SMJZIK2O.js} +1 -1
  25. package/dist/{chunk-LO6WGU5Y.js → chunk-U72NEGCT.js} +8089 -3464
  26. package/dist/{chunk-P6UWZ6QQ.js → chunk-Z4IKF23A.js} +11 -7
  27. package/dist/{chunk-2IVEVPMY.js → chunk-Z7OVQ6BC.js} +105 -61
  28. package/dist/{chunk-6UWRT4VM.js → chunk-ZJSFX4RD.js} +175 -3
  29. package/dist/{cli-5UNY5G5L.js → cli-OKQHHSOE.js} +17 -25
  30. package/dist/{cli-UYZMVQMR.js → cli-VYSD2S4Z.js} +227 -81
  31. package/dist/cli.js +5 -5
  32. package/dist/{client-repo-SE4EKG6W.js → client-repo-NNUCHQ2Y.js} +7 -5
  33. package/dist/create.js +5 -5
  34. package/dist/{fields-FTWWMD7N.js → fields-GTHE6TTS.js} +27 -3
  35. package/dist/gateway-DPPEQZT4.js +25 -0
  36. package/dist/grants-6JY4XZO7.js +27 -0
  37. package/dist/invoke-MRONRZ5Q.js +33 -0
  38. package/dist/moves-UAUCMWL5.js +36 -0
  39. package/dist/{order-U4KZLLSJ.js → order-RKLGT74L.js} +2 -2
  40. package/dist/{person-UHLVBVLR.js → person-YOZTFV4Q.js} +11 -10
  41. package/dist/plan-on-sale-H4F26YIN.js +26 -0
  42. package/dist/platform/migrations/0730_practitioners.sql +79 -0
  43. package/dist/platform/migrations/0750_routine_mail.sql +98 -0
  44. package/dist/platform/migrations/0770_clear_fixed_role_grants.sql +64 -0
  45. package/dist/platform/migrations/0810_recurrence_exceptions.sql +66 -0
  46. package/dist/platform/migrations/0811_staff_time.sql +109 -0
  47. package/dist/platform/migrations/0812_staff_offers.sql +112 -0
  48. package/dist/platform/migrations/0813_pay_periods.sql +241 -0
  49. package/dist/platform/migrations/0814_staff_feed.sql +47 -0
  50. package/dist/platform/migrations/0815_checklists.sql +237 -0
  51. package/dist/platform/migrations/0816_checklist_schedules.sql +121 -0
  52. package/dist/platform/migrations/0817_checklist_day_window.sql +35 -0
  53. package/dist/platform/migrations/0850_agreements.sql +271 -0
  54. package/dist/platform/migrations/0851_agreement_acceptances.sql +387 -0
  55. package/dist/platform/migrations/0853_agreement_enforcement.sql +58 -0
  56. package/dist/platform/migrations/0854_agreement_copy.sql +149 -0
  57. package/dist/platform/migrations/0855_agreement_retention.sql +279 -0
  58. package/dist/platform/migrations/0856_subscription_cooling_off.sql +159 -0
  59. package/dist/platform/migrations/0857_agreement_copy_guardian.sql +337 -0
  60. package/dist/platform/migrations/0858_agreement_desk.sql +175 -0
  61. package/dist/platform/migrations/0910_routine_messages.sql +99 -0
  62. package/dist/platform/migrations/0911_texts.sql +60 -0
  63. package/dist/platform/migrations/0913_contact_consent.sql +93 -0
  64. package/dist/platform/migrations/0916_contact_mailbox_index.sql +29 -0
  65. package/dist/platform/migrations/0930_stock_movements.sql +95 -0
  66. package/dist/platform/migrations/0931_stock_low.sql +25 -0
  67. package/dist/platform/migrations/0932_order_delivery.sql +78 -0
  68. package/dist/platform/migrations/0950_order_adjustments.sql +111 -0
  69. package/dist/platform/migrations/0951_order_price_guards.sql +33 -0
  70. package/dist/platform/migrations/0952_order_paid_another_way.sql +194 -0
  71. package/dist/platform/migrations/0953_discount_uses.sql +183 -0
  72. package/dist/platform/migrations/0955_folded_addresses.sql +92 -0
  73. package/dist/platform/migrations/0970_published_text.sql +59 -0
  74. package/dist/platform/migrations/0971_publish_acks.sql +68 -0
  75. package/dist/platform/migrations/0990_customer_email_change.sql +65 -0
  76. package/dist/platform/migrations/1010_intake_links.sql +148 -0
  77. package/dist/platform/migrations/1030_invoices.sql +747 -0
  78. package/dist/platform/migrations/1031_invoice_orders.sql +327 -0
  79. package/dist/platform/migrations/1050_inbox_conversations.sql +83 -0
  80. package/dist/platform/migrations/1090_staff_hours.sql +43 -0
  81. package/dist/platform/migrations/1091_staff_time_margins.sql +12 -0
  82. package/dist/platform/migrations/1092_client_guard.sql +26 -0
  83. package/dist/platform/migrations/1095_thing_time.sql +70 -0
  84. package/dist/platform/migrations/1130_devices.sql +162 -0
  85. package/dist/platform/migrations/1135_person_codes.sql +88 -0
  86. package/dist/platform/migrations/1150_finance_periods.sql +316 -0
  87. package/dist/platform/migrations/1151_payouts.sql +202 -0
  88. package/dist/platform/migrations/1153_finance_money_dates.sql +18 -0
  89. package/dist/platform/migrations/1170_journeys.sql +318 -0
  90. package/dist/platform/migrations/1171_person_birthday.sql +52 -0
  91. package/dist/platform/migrations/1175_person_signals.sql +29 -0
  92. package/dist/platform/migrations/1190_restricted_values.sql +25 -0
  93. package/dist/platform/migrations/1230_note_levels.sql +113 -0
  94. package/dist/platform/migrations/1231_person_carers.sql +33 -0
  95. package/dist/platform/migrations/1232_note_kinds.sql +122 -0
  96. package/dist/platform/migrations/1270_time_entries.sql +145 -0
  97. package/dist/platform/migrations/1271_leave.sql +249 -0
  98. package/dist/platform/migrations/1273_time_entry_reopened.sql +21 -0
  99. package/dist/platform/migrations/1330_accounting.sql +260 -0
  100. package/dist/platform/migrations/1350_customer_feed.sql +24 -0
  101. package/dist/platform/migrations/1390_locations.sql +77 -0
  102. package/dist/platform/migrations/1410_outside_copy.sql +213 -0
  103. package/dist/platform/migrations/1430_inbox_activities.sql +231 -0
  104. package/dist/platform/migrations/1450_wrong_guesses.sql +23 -0
  105. package/dist/platform/sdk/acknowledge.ts +100 -0
  106. package/dist/platform/sdk/agreements.ts +185 -0
  107. package/dist/platform/sdk/allowance.ts +98 -8
  108. package/dist/platform/sdk/automation-check.ts +120 -9
  109. package/dist/platform/sdk/automation.ts +78 -10
  110. package/dist/platform/sdk/behaviour.ts +26 -6
  111. package/dist/platform/sdk/calendar-entry.ts +258 -0
  112. package/dist/platform/sdk/capacity.ts +1 -2
  113. package/dist/platform/sdk/checklists.ts +118 -0
  114. package/dist/platform/sdk/contract.ts +489 -27
  115. package/dist/platform/sdk/discount.ts +408 -0
  116. package/dist/platform/sdk/document.ts +4 -2
  117. package/dist/platform/sdk/field-types.ts +5 -0
  118. package/dist/platform/sdk/formula/compile.ts +10 -0
  119. package/dist/platform/sdk/index.ts +17 -0
  120. package/dist/platform/sdk/intake.ts +380 -0
  121. package/dist/platform/sdk/journey-signals.ts +215 -0
  122. package/dist/platform/sdk/manifest.ts +1236 -65
  123. package/dist/platform/sdk/mine.ts +161 -0
  124. package/dist/platform/sdk/occupies.ts +192 -0
  125. package/dist/platform/sdk/questions.ts +681 -0
  126. package/dist/platform/sdk/recurring.ts +90 -9
  127. package/dist/platform/sdk/restricted-fields.ts +129 -0
  128. package/dist/platform/sdk/rich-text.ts +112 -0
  129. package/dist/platform/sdk/routine-mail.ts +1272 -0
  130. package/dist/platform/sdk/runtime.ts +25 -12
  131. package/dist/platform/sdk/screens.ts +91 -0
  132. package/dist/platform/sdk/sellable.ts +344 -0
  133. package/dist/platform/sdk/slug.ts +7 -2
  134. package/dist/platform/sdk/staffed.ts +474 -0
  135. package/dist/platform/sdk/states.ts +68 -26
  136. package/dist/platform/sdk/stock.ts +332 -0
  137. package/dist/platform/sdk/team.ts +83 -0
  138. package/dist/platform/sdk/testing.ts +70 -6
  139. package/dist/platform/sdk/worked-on.ts +134 -0
  140. package/dist/{products-2H5DR232.js → products-GCQLSZ3U.js} +2 -2
  141. package/dist/run-7ID64RA6.js +65 -0
  142. package/dist/run-FH7OGGTV.js +131 -0
  143. package/dist/run-OYZIAP6M.js +3363 -0
  144. package/dist/{run-ZCGFMEZF.js → run-QOFRRSZV.js} +41 -60
  145. package/dist/{run-PO3W5BFA.js → run-TJAEWR5U.js} +21 -51
  146. package/dist/{src-I3IJ4NKC.js → src-52VERUPK.js} +306 -4
  147. package/dist/src-PHRELWN5.js +40 -0
  148. package/dist/{visibility-TVXZ67FD.js → visibility-SZCINPP4.js} +21 -4
  149. package/package.json +2 -2
  150. package/dist/chunk-2TWV3SVB.js +0 -349
  151. package/dist/chunk-2XC5JLBO.js +0 -1931
  152. package/dist/chunk-324WJXNP.js +0 -320
  153. package/dist/chunk-6ELZRNUU.js +0 -116
  154. package/dist/chunk-6WGFA2IV.js +0 -643
  155. package/dist/chunk-7CQGMVDO.js +0 -63
  156. package/dist/chunk-7OGCMQXG.js +0 -284
  157. package/dist/chunk-FJIZGS5Q.js +0 -698
  158. package/dist/chunk-UB4I2QKR.js +0 -31575
  159. package/dist/chunk-WHKJGF36.js +0 -2418
  160. package/dist/chunk-YNUZRTPH.js +0 -182
  161. package/dist/chunk-ZZFWMVJO.js +0 -704
  162. package/dist/grants-LOW6TSWD.js +0 -32
  163. package/dist/invoke-6KVT6WJI.js +0 -41
  164. package/dist/moves-E2HKYCTK.js +0 -41
  165. package/dist/plan-on-sale-TJPFCNL7.js +0 -26
  166. package/dist/src-CRO35DYY.js +0 -46
@@ -0,0 +1,3363 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ personFor
4
+ } from "./chunk-2CCHB37H.js";
5
+ import {
6
+ realDate
7
+ } from "./chunk-EPDTPGZJ.js";
8
+ import {
9
+ parseCsv
10
+ } from "./chunk-Z4IKF23A.js";
11
+ import {
12
+ importRecords,
13
+ outcomeLines,
14
+ sessionHost,
15
+ signInForRun
16
+ } from "./chunk-LX2TTLVY.js";
17
+ import {
18
+ OpsCallError,
19
+ defineExtension,
20
+ defineTool,
21
+ external_exports,
22
+ validateDocument
23
+ } from "./chunk-U72NEGCT.js";
24
+ import "./chunk-5KSXSK7Y.js";
25
+
26
+ // src/programs-import/run.ts
27
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
28
+ import { join, resolve } from "node:path";
29
+
30
+ // ../../packs/programs/dashboards.ts
31
+ var IN = (column) => `${column} >= :date_from AND ${column} < :date_to`;
32
+ var WEEK = (column) => `date(${column}, '-' || ((strftime('%w', ${column}) + 6) % 7) || ' days')`;
33
+ var training = {
34
+ title: "Training",
35
+ description: "Sessions planned against done, sets logged by week, the most used exercises, and clients with nothing logged in two weeks.",
36
+ filters: [{ type: "dateRange", id: "date", label: "Dates", default: "this_quarter" }],
37
+ widgets: [
38
+ {
39
+ id: "planned",
40
+ type: "kpi",
41
+ title: "Sessions planned",
42
+ description: "Clients' own sessions dated in the period (classes not counted).",
43
+ sql: `SELECT count(*) AS value FROM rec_x_programs_session s
44
+ WHERE s.kind = 'personal' AND ${IN("s.date")}`,
45
+ mapping: { value: "value" },
46
+ options: { compare: true },
47
+ clickThrough: {
48
+ object: "programs.session",
49
+ filter: {
50
+ and: [
51
+ { field: "kind", op: "eq", value: "personal" },
52
+ { field: "date", op: "gte", value: { $param: "date_from" } },
53
+ { field: "date", op: "lt", value: { $param: "date_to" } }
54
+ ]
55
+ }
56
+ },
57
+ layout: { w: 3, h: 1 }
58
+ },
59
+ {
60
+ id: "done",
61
+ type: "kpi",
62
+ title: "Sessions done",
63
+ description: "Of those, the ones marked done.",
64
+ sql: `SELECT count(*) AS value FROM rec_x_programs_session s
65
+ WHERE s.kind = 'personal' AND s.state = 'done' AND ${IN("s.date")}`,
66
+ mapping: { value: "value" },
67
+ options: { compare: true },
68
+ clickThrough: {
69
+ object: "programs.session",
70
+ filter: {
71
+ and: [
72
+ { field: "kind", op: "eq", value: "personal" },
73
+ { field: "state", op: "eq", value: "done" },
74
+ { field: "date", op: "gte", value: { $param: "date_from" } },
75
+ { field: "date", op: "lt", value: { $param: "date_to" } }
76
+ ]
77
+ }
78
+ },
79
+ layout: { w: 3, h: 1 }
80
+ },
81
+ {
82
+ id: "sets",
83
+ type: "kpi",
84
+ title: "Sets logged",
85
+ description: "Sets logged on sessions dated in the period, by clients and in classes.",
86
+ sql: `SELECT count(*) AS value FROM rec_x_programs_log l WHERE ${IN("l.date")}`,
87
+ mapping: { value: "value" },
88
+ options: { compare: true },
89
+ clickThrough: {
90
+ object: "programs.log",
91
+ filter: {
92
+ and: [
93
+ { field: "date", op: "gte", value: { $param: "date_from" } },
94
+ { field: "date", op: "lt", value: { $param: "date_to" } }
95
+ ]
96
+ }
97
+ },
98
+ layout: { w: 3, h: 1 }
99
+ },
100
+ {
101
+ id: "quiet-count",
102
+ type: "kpi",
103
+ title: "Clients quiet for two weeks",
104
+ description: "Clients with an active program and no set logged in the last 14 days.",
105
+ sql: `SELECT count(DISTINCT a.person) AS value FROM rec_x_programs_assignment a
106
+ WHERE a.kind = 'personal' AND a.state = 'active' AND NOT EXISTS (
107
+ SELECT 1 FROM rec_x_programs_log l WHERE l.person = a.person AND l.date >= date(:today, '-14 days'))`,
108
+ mapping: { value: "value" },
109
+ options: { compare: false },
110
+ layout: { w: 3, h: 1 }
111
+ },
112
+ {
113
+ id: "planned-done",
114
+ type: "bar",
115
+ title: "Planned and done, by week",
116
+ description: "Clients' own sessions per week of the period: planned, done and skipped.",
117
+ sql: `SELECT ${WEEK("s.date")} AS week, count(*) AS planned,
118
+ sum(CASE WHEN s.state = 'done' THEN 1 ELSE 0 END) AS done,
119
+ sum(CASE WHEN s.state = 'skipped' THEN 1 ELSE 0 END) AS skipped
120
+ FROM rec_x_programs_session s WHERE s.kind = 'personal' AND ${IN("s.date")}
121
+ GROUP BY week ORDER BY week`,
122
+ mapping: { x: "week", y: ["planned", "done", "skipped"] },
123
+ layout: { w: 6, h: 2 }
124
+ },
125
+ {
126
+ id: "sets-by-week",
127
+ type: "line",
128
+ title: "Sets logged by week",
129
+ description: "Sets logged per week of the period, by their session's date.",
130
+ sql: `SELECT ${WEEK("l.date")} AS week, count(*) AS sets
131
+ FROM rec_x_programs_log l WHERE ${IN("l.date")} GROUP BY week ORDER BY week`,
132
+ mapping: { x: "week", y: ["sets"] },
133
+ layout: { w: 6, h: 2 }
134
+ },
135
+ {
136
+ id: "exercises",
137
+ type: "leaderboard",
138
+ title: "Most used exercises",
139
+ description: "Exercises by sets logged in the period.",
140
+ sql: `SELECT e.id AS exercise_id, e.name AS label, count(*) AS value
141
+ FROM rec_x_programs_log l JOIN rec_x_programs_exercise e ON e.id = l.exercise
142
+ WHERE ${IN("l.date")} GROUP BY e.id, e.name ORDER BY value DESC, label LIMIT 10`,
143
+ mapping: { label: "label", value: "value" },
144
+ clickThrough: {
145
+ object: "programs.log",
146
+ filter: {
147
+ and: [
148
+ { field: "exercise", op: "eq", value: { $row: "exercise_id" } },
149
+ { field: "date", op: "gte", value: { $param: "date_from" } },
150
+ { field: "date", op: "lt", value: { $param: "date_to" } }
151
+ ]
152
+ }
153
+ },
154
+ layout: { w: 6, h: 2 }
155
+ },
156
+ {
157
+ id: "quiet",
158
+ type: "table",
159
+ title: "Nothing logged in two weeks",
160
+ description: "Clients with an active program and no set logged in the last 14 days, with their last set.",
161
+ sql: `SELECT p.id AS id, p.display_name AS client, a.title AS program,
162
+ (SELECT max(l.date) FROM rec_x_programs_log l WHERE l.person = a.person) AS last_logged
163
+ FROM rec_x_programs_assignment a JOIN rec_person p ON p.id = a.person
164
+ WHERE a.kind = 'personal' AND a.state = 'active' AND NOT EXISTS (
165
+ SELECT 1 FROM rec_x_programs_log l WHERE l.person = a.person AND l.date >= date(:today, '-14 days'))
166
+ ORDER BY last_logged, client LIMIT 50`,
167
+ mapping: { columns: ["client", "program", "last_logged"] },
168
+ clickThrough: { object: "person", filter: { field: "id", op: "eq", value: { $row: "id" } } },
169
+ layout: { w: 6, h: 2 }
170
+ }
171
+ ]
172
+ };
173
+ var programsDashboards = { training };
174
+
175
+ // ../../packs/programs/layout.ts
176
+ var LOAD = {
177
+ type: "number",
178
+ min: 0,
179
+ max: 1e3,
180
+ step: 0.25,
181
+ optional: true,
182
+ description: "Kilograms, added to the body"
183
+ };
184
+ var TEMPO = {
185
+ type: "text",
186
+ min: 4,
187
+ max: 4,
188
+ chars: "0123456789X",
189
+ optional: true,
190
+ description: "Four characters, down-pause-up-pause: 32X1"
191
+ };
192
+ var REST = {
193
+ type: "number",
194
+ min: 0,
195
+ max: 1800,
196
+ integer: true,
197
+ optional: true,
198
+ description: "Seconds of rest after the set"
199
+ };
200
+ var SET = {
201
+ type: "union",
202
+ tag: "kind",
203
+ description: "One set's target",
204
+ variants: {
205
+ reps: {
206
+ type: "object",
207
+ fields: {
208
+ reps: { type: "number", min: 1, max: 999, integer: true },
209
+ repsMax: {
210
+ type: "number",
211
+ min: 1,
212
+ max: 999,
213
+ integer: true,
214
+ optional: true,
215
+ description: "The top of a range: 8 to 12"
216
+ },
217
+ load: LOAD,
218
+ tempo: TEMPO,
219
+ rest: REST
220
+ }
221
+ },
222
+ time: {
223
+ type: "object",
224
+ fields: {
225
+ seconds: { type: "number", min: 1, max: 7200, integer: true },
226
+ load: LOAD,
227
+ rest: REST
228
+ }
229
+ },
230
+ hold: {
231
+ type: "object",
232
+ fields: {
233
+ seconds: { type: "number", min: 1, max: 600, integer: true, description: "Each hold" },
234
+ holds: {
235
+ type: "number",
236
+ min: 2,
237
+ max: 10,
238
+ integer: true,
239
+ optional: true,
240
+ description: "Holds in the set (one when left out)"
241
+ },
242
+ load: LOAD,
243
+ rest: REST
244
+ }
245
+ }
246
+ }
247
+ };
248
+ var PRESCRIPTION = {
249
+ type: "object",
250
+ fields: {
251
+ exercise: { type: "ref", to: "programs.exercise" },
252
+ sets: { type: "array", min: 1, max: 12, of: { type: "use", def: "set" } },
253
+ note: {
254
+ type: "text",
255
+ max: 300,
256
+ optional: true,
257
+ description: "The coach's wording beside the numbers: legs as straight as possible"
258
+ }
259
+ }
260
+ };
261
+ var NOTE = {
262
+ type: "object",
263
+ description: "For coaches only unless marked as shown to members",
264
+ fields: {
265
+ text: { type: "text", min: 1, max: 800, multiline: true },
266
+ members: { type: "boolean", optional: true, description: "Shown to members" }
267
+ },
268
+ private: { unless: "members" }
269
+ };
270
+ var NOTES = {
271
+ type: "array",
272
+ max: 10,
273
+ optional: true,
274
+ of: { type: "use", def: "note" }
275
+ };
276
+ var EXERCISES = (min) => ({
277
+ type: "array",
278
+ min,
279
+ max: 3,
280
+ of: { type: "use", def: "prescription" }
281
+ });
282
+ var LEVEL = {
283
+ type: "union",
284
+ tag: "mode",
285
+ description: "One exercise, several done together, or alternatives",
286
+ variants: {
287
+ one: {
288
+ type: "object",
289
+ fields: {
290
+ level: { type: "number", min: 1, max: 5, integer: true },
291
+ exercise: { type: "use", def: "prescription" }
292
+ }
293
+ },
294
+ together: {
295
+ type: "object",
296
+ fields: {
297
+ level: { type: "number", min: 1, max: 5, integer: true },
298
+ exercises: EXERCISES(2)
299
+ }
300
+ },
301
+ alternatives: {
302
+ type: "object",
303
+ fields: {
304
+ level: { type: "number", min: 1, max: 5, integer: true },
305
+ exercises: EXERCISES(2)
306
+ }
307
+ }
308
+ }
309
+ };
310
+ var ITEM = {
311
+ type: "union",
312
+ tag: "kind",
313
+ variants: {
314
+ all: {
315
+ type: "object",
316
+ description: "For everyone: one exercise, or several done together",
317
+ fields: {
318
+ label: { type: "text", min: 1, max: 6 },
319
+ exercises: EXERCISES(1),
320
+ notes: NOTES
321
+ }
322
+ },
323
+ levels: {
324
+ type: "object",
325
+ description: "Up to five levels, possibly sparse (only 1 and 5), and optionally exercises for everyone",
326
+ fields: {
327
+ label: { type: "text", min: 1, max: 6 },
328
+ exercises: {
329
+ ...EXERCISES(1),
330
+ optional: true,
331
+ description: "Done by everyone, whatever level they take"
332
+ },
333
+ levels: {
334
+ type: "array",
335
+ min: 1,
336
+ max: 5,
337
+ unique: "level",
338
+ of: { type: "use", def: "level" }
339
+ },
340
+ notes: NOTES
341
+ }
342
+ }
343
+ }
344
+ };
345
+ var BLOCK = {
346
+ type: "object",
347
+ fields: {
348
+ label: { type: "text", min: 1, max: 4, description: "A, B, \u2026" },
349
+ rounds: { type: "number", min: 1, max: 50, integer: true, optional: true },
350
+ items: { type: "array", min: 1, max: 12, unique: "label", of: { type: "use", def: "item" } },
351
+ notes: NOTES
352
+ }
353
+ };
354
+ var SESSION = {
355
+ type: "object",
356
+ fields: {
357
+ name: { type: "text", min: 1, max: 60 },
358
+ focus: { type: "text", max: 200, optional: true, description: "What the session is about" },
359
+ day: {
360
+ type: "number",
361
+ min: 1,
362
+ max: 7,
363
+ integer: true,
364
+ description: "Day of its week, 1 to 7: a session is dated from the start date with it"
365
+ },
366
+ warmup: {
367
+ type: "object",
368
+ optional: true,
369
+ fields: {
370
+ text: { type: "text", max: 1200, multiline: true, optional: true },
371
+ exercises: {
372
+ type: "array",
373
+ max: 15,
374
+ optional: true,
375
+ of: { type: "use", def: "prescription" }
376
+ }
377
+ }
378
+ },
379
+ blocks: { type: "array", max: 10, unique: "label", of: { type: "use", def: "block" } },
380
+ notes: NOTES
381
+ }
382
+ };
383
+ var DEFS = {
384
+ set: SET,
385
+ prescription: PRESCRIPTION,
386
+ note: NOTE,
387
+ level: LEVEL,
388
+ item: ITEM,
389
+ block: BLOCK
390
+ };
391
+ var MAX_WEEKS = 52;
392
+ var MAX_SESSIONS_PER_WEEK = 14;
393
+ var LAYOUT_SCHEMA = {
394
+ defs: { ...DEFS, session: SESSION },
395
+ root: {
396
+ type: "object",
397
+ fields: {
398
+ weeks: {
399
+ type: "array",
400
+ min: 1,
401
+ max: MAX_WEEKS,
402
+ of: {
403
+ type: "object",
404
+ fields: {
405
+ label: { type: "text", max: 60, optional: true },
406
+ sessions: {
407
+ type: "array",
408
+ max: MAX_SESSIONS_PER_WEEK,
409
+ of: { type: "use", def: "session" }
410
+ }
411
+ }
412
+ }
413
+ },
414
+ notes: NOTES
415
+ }
416
+ }
417
+ };
418
+ var SESSION_PLAN_SCHEMA = { defs: DEFS, root: SESSION };
419
+ function levelExercises(level) {
420
+ return level.mode === "one" ? [level.exercise] : level.exercises;
421
+ }
422
+ function prescriptions(session) {
423
+ const out = [];
424
+ for (const block of session.blocks) {
425
+ for (const item of block.items) {
426
+ if (item.kind === "all") {
427
+ for (const p of item.exercises)
428
+ out.push({ item: item.label, level: null, prescription: p });
429
+ } else {
430
+ for (const p of item.exercises ?? []) {
431
+ out.push({ item: item.label, level: null, prescription: p });
432
+ }
433
+ for (const level of item.levels) {
434
+ for (const p of levelExercises(level)) {
435
+ out.push({ item: item.label, level: level.level, prescription: p });
436
+ }
437
+ }
438
+ }
439
+ }
440
+ }
441
+ return out;
442
+ }
443
+
444
+ // ../../packs/programs/authoring.ts
445
+ var norm = (name) => name.toLowerCase().replace(/[’'"“”]/g, "").replace(/[^a-z0-9]+/g, " ").trim();
446
+ var WEEKDAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
447
+ function bankIndex(bank) {
448
+ const byName = /* @__PURE__ */ new Map();
449
+ for (const e of bank) byName.set(norm(e.name), e);
450
+ return (name) => {
451
+ const n = norm(name);
452
+ return byName.get(n) ?? byName.get(n.replace(/s$/, "")) ?? byName.get(`${n}s`);
453
+ };
454
+ }
455
+ function readTarget(rx, measure, count) {
456
+ const text2 = (rx ?? "").trim();
457
+ const sets = (target) => Array.from({ length: Math.max(1, Math.min(count, 12)) }, () => ({ ...target }));
458
+ const extra = (used) => {
459
+ const rest = text2.replace(used, "").replace(/^[\s,;:-]+|[\s,;:-]+$/g, "");
460
+ return rest ? { note: text2.length <= 300 ? text2 : text2.slice(0, 300) } : {};
461
+ };
462
+ if (!text2) {
463
+ if (measure === "time" || measure === "hold") return "no time given";
464
+ return "no reps or time given";
465
+ }
466
+ const hold = /(\d+)\s*(?:-\s*\d+\s*)?(?:s|sec|secs|seconds)\s+hold/i.exec(text2);
467
+ const reps = /^(\d+)(?:\s*-\s*(\d+))?(?:\s*(?:reps?|each|\/))?/i.exec(text2);
468
+ const secs = /^(\d+)(?:\s*-\s*(\d+))?\s*(?:s|sec|secs|seconds)\b/i.exec(text2);
469
+ const mins = /^(\d+)(?:\s*-\s*(\d+))?\s*(?:min|mins|minutes)\b/i.exec(text2);
470
+ if (secs) {
471
+ const seconds = Math.min(Number(secs[1]), 7200);
472
+ if (seconds < 1) return "a time of 0";
473
+ const target = measure === "hold" ? { kind: "hold", seconds: Math.min(seconds, 600) } : { kind: "time", seconds };
474
+ return { sets: sets(target), ...extra(secs[0]) };
475
+ }
476
+ if (mins) {
477
+ const seconds = Math.min(Number(mins[1]) * 60, 7200);
478
+ return { sets: sets({ kind: "time", seconds }), ...extra(mins[0]) };
479
+ }
480
+ if (reps) {
481
+ const count1 = Number(reps[1]);
482
+ if (count1 < 1 || count1 > 999) return `${count1} reps is not a number of reps`;
483
+ const top = reps[2] ? Number(reps[2]) : void 0;
484
+ const target = {
485
+ kind: "reps",
486
+ reps: count1,
487
+ ...top && top > count1 && top <= 999 ? { repsMax: top } : {}
488
+ };
489
+ return { sets: sets(target), ...hold || text2 !== reps[0] ? extra(reps[0]) : {} };
490
+ }
491
+ return `"${text2.slice(0, 60)}" has no number of reps or seconds`;
492
+ }
493
+ function splitExercise(raw) {
494
+ let s = raw.replace(/<\s*https?:\/\/[^>\s]+\s*>/gi, " ");
495
+ let tempo;
496
+ s = s.replace(/[\s,]*\(\s*([0-9xX]{4})\s*\)[\s,]*$/, (_m, t) => {
497
+ tempo = t.toUpperCase();
498
+ return " ";
499
+ });
500
+ s = s.replace(/\s+/g, " ").replace(/[\s,]+$/, "").trim();
501
+ const sep = /\s+[x×]\s+/gi;
502
+ for (let hit = sep.exec(s); hit; hit = sep.exec(s)) {
503
+ if (/[a-z]/i.test(s.slice(0, hit.index))) {
504
+ return {
505
+ name: s.slice(0, hit.index).trim(),
506
+ rx: s.slice(hit.index + hit[0].length).trim(),
507
+ ...tempo ? { tempo } : {}
508
+ };
509
+ }
510
+ }
511
+ return { name: s, ...tempo ? { tempo } : {} };
512
+ }
513
+ var RE = {
514
+ title: /^title\s*:\s*(.*)$/i,
515
+ kind: /^kind\s*:\s*(.*)$/i,
516
+ guidance: /^guidance\s*:\s*(.*)$/i,
517
+ week: /^week\s*:?\s*(\d+)\s*(?::\s*(.*))?$/i,
518
+ session: /^session\s*:\s*(.*)$/i,
519
+ focus: /^focus\s*:\s*(.*)$/i,
520
+ warmup: /^warm[\s-]?up\s*:?\s*(.*)$/i,
521
+ block: /^block\s+([A-Za-z0-9]{1,4})\s*(?::\s*(.*))?$/i,
522
+ loading: /^loading\s*:\s*(.*)$/i,
523
+ item: /^([A-Z][0-9]{1,2}[a-z]?)\s*[:.]\s*(.*)$/,
524
+ level: /^(?:level\s*|l)?([0-9])\s*[:.]\s*(.*)$/i,
525
+ dash: /^[-•]\s+(.*)$/,
526
+ coachNote: /^\*+\s*(.*)$/,
527
+ memberNote: /^(?:tv|members?)\s*:\s*(.*)$/i
528
+ };
529
+ function readProgramText(text2, bank) {
530
+ const find = bankIndex(bank);
531
+ const unread = [];
532
+ let title = null;
533
+ let kind2 = null;
534
+ let guidance = null;
535
+ const weeks = [];
536
+ let week = null;
537
+ let session = null;
538
+ let block = null;
539
+ let item = null;
540
+ let rounds = 1;
541
+ let continueTo = null;
542
+ const lines = text2.replace(/\r\n?/g, "\n").split("\n");
543
+ const skip = (n, raw, reason) => {
544
+ unread.push({ line: n, text: raw.trim().slice(0, 300), reason });
545
+ };
546
+ const notesHere = () => {
547
+ const owner = item ?? block ?? session;
548
+ if (!owner) return null;
549
+ owner.notes = owner.notes ?? [];
550
+ return owner.notes;
551
+ };
552
+ const prescriptionsOf = (raw) => {
553
+ const joiner = /\s\|\s/.test(raw) ? "|" : /\s\+\s/.test(raw) ? "+" : null;
554
+ const parts = raw.split(/\s+[+|]\s+/).filter((p) => p.trim());
555
+ const list2 = [];
556
+ for (const part of parts) {
557
+ const { name, rx, tempo } = splitExercise(part);
558
+ const exercise = find(name);
559
+ if (!exercise) return `no exercise in the bank is called "${name.slice(0, 80)}"`;
560
+ const target = readTarget(rx, exercise.measure, rounds);
561
+ if (typeof target === "string") return `${exercise.name}: ${target}`;
562
+ if (tempo && target.sets[0]?.kind === "reps") {
563
+ for (const set of target.sets) if (set.kind === "reps") set.tempo = tempo;
564
+ }
565
+ list2.push({
566
+ exercise: exercise.id,
567
+ sets: target.sets,
568
+ ...target.note ? { note: target.note } : {}
569
+ });
570
+ }
571
+ if (list2.length > 3) return "more than three exercises in one line";
572
+ return { list: list2, joiner };
573
+ };
574
+ const needWeek = () => {
575
+ if (!week) {
576
+ week = { sessions: [] };
577
+ weeks.push(week);
578
+ }
579
+ return week;
580
+ };
581
+ const readLine = (rawLine, index) => {
582
+ const n = index + 1;
583
+ if (!rawLine.trim()) {
584
+ continueTo = null;
585
+ return;
586
+ }
587
+ const indented = /^\s/.test(rawLine);
588
+ const line = rawLine.trim();
589
+ let m;
590
+ m = RE.coachNote.exec(line) ?? RE.memberNote.exec(line);
591
+ if (m) {
592
+ const note = {
593
+ text: (m[1] ?? "").trim().slice(0, 800),
594
+ ...RE.memberNote.test(line) ? { members: true } : {}
595
+ };
596
+ if (!note.text) return;
597
+ const target = notesHere();
598
+ if (!target) return skip(n, rawLine, "a note before any session");
599
+ if (target.length >= 10) return skip(n, rawLine, "more than ten notes in one place");
600
+ target.push(note);
601
+ return;
602
+ }
603
+ if (indented && continueTo && !RE.level.test(line) && !RE.dash.test(line)) {
604
+ continueTo(line);
605
+ return;
606
+ }
607
+ m = RE.title.exec(line);
608
+ if (m) {
609
+ title = (m[1] ?? "").trim().slice(0, 200) || null;
610
+ continueTo = null;
611
+ return;
612
+ }
613
+ m = RE.kind.exec(line);
614
+ if (m) {
615
+ const said = norm(m[1] ?? "");
616
+ continueTo = null;
617
+ if (said === "class" || said === "client" || said === "course") {
618
+ kind2 = said;
619
+ return;
620
+ }
621
+ return skip(n, rawLine, "a kind is class, client or course");
622
+ }
623
+ m = RE.guidance.exec(line);
624
+ if (m) {
625
+ guidance = (m[1] ?? "").trim();
626
+ continueTo = (more) => {
627
+ guidance = `${guidance}
628
+ ${more}`;
629
+ };
630
+ return;
631
+ }
632
+ m = RE.week.exec(line);
633
+ if (m) {
634
+ week = { ...m[2] ? { label: m[2].trim().slice(0, 60) } : {}, sessions: [] };
635
+ weeks.push(week);
636
+ session = block = item = null;
637
+ return;
638
+ }
639
+ m = RE.session.exec(line);
640
+ if (m) {
641
+ const name = (m[1] ?? "").trim().slice(0, 60) || "Session";
642
+ const w = needWeek();
643
+ if (w.sessions.length >= MAX_SESSIONS_PER_WEEK)
644
+ return skip(n, rawLine, "more than fourteen sessions in a week");
645
+ const weekday = WEEKDAYS.findIndex((d) => norm(name).split(" ").includes(d));
646
+ const used = new Set(w.sessions.map((s2) => s2.day));
647
+ const day = weekday >= 0 ? weekday + 1 : [1, 2, 3, 4, 5, 6, 7].find((d) => !used.has(d)) ?? 7;
648
+ session = { name, day, blocks: [] };
649
+ w.sessions.push(session);
650
+ block = item = null;
651
+ continueTo = null;
652
+ return;
653
+ }
654
+ if (!session) return skip(n, rawLine, 'put a "Session: \u2026" line first');
655
+ const s = session;
656
+ m = RE.focus.exec(line);
657
+ if (m) {
658
+ s.focus = (m[1] ?? "").trim().slice(0, 200);
659
+ return;
660
+ }
661
+ m = RE.warmup.exec(line);
662
+ if (m) {
663
+ s.warmup = { ...m[1]?.trim() ? { text: m[1].trim().slice(0, 1200) } : {} };
664
+ block = item = null;
665
+ continueTo = (more) => {
666
+ const w = s.warmup ?? {};
667
+ w.text = `${w.text ? `${w.text}
668
+ ` : ""}${more}`.slice(0, 1200);
669
+ s.warmup = w;
670
+ };
671
+ return;
672
+ }
673
+ m = RE.dash.exec(line);
674
+ if (m && !block && s.warmup) {
675
+ const found = prescriptionsOf(m[1] ?? "");
676
+ const w = s.warmup;
677
+ if (typeof found === "string") {
678
+ w.text = `${w.text ? `${w.text}
679
+ ` : ""}- ${m[1]}`.slice(0, 1200);
680
+ return skip(n, rawLine, `kept as warm-up text: ${found}`);
681
+ }
682
+ w.exercises = [...w.exercises ?? [], ...found.list].slice(0, 15);
683
+ return;
684
+ }
685
+ m = RE.block.exec(line);
686
+ if (m) {
687
+ const label = (m[1] ?? "").toUpperCase();
688
+ if (s.blocks.some((b) => b.label === label))
689
+ return skip(n, rawLine, `block ${label} is there twice`);
690
+ const about = (m[2] ?? "").trim();
691
+ const count = /(\d+)\s*(?:-\s*\d+\s*)?rounds?/i.exec(about) ?? /rounds?\s*:?\s*(\d+)/i.exec(about);
692
+ rounds = count ? Math.min(Math.max(Number(count[1]), 1), 12) : 1;
693
+ block = {
694
+ label,
695
+ ...count ? { rounds: Math.min(Number(count[1]), 50) } : {},
696
+ items: [],
697
+ ...about ? { notes: [{ text: about.slice(0, 800), members: true }] } : {}
698
+ };
699
+ s.blocks.push(block);
700
+ item = null;
701
+ continueTo = null;
702
+ return;
703
+ }
704
+ m = RE.loading.exec(line);
705
+ if (m && block) {
706
+ block.notes = block.notes ?? [];
707
+ const notes = block.notes;
708
+ const note = { text: (m[1] ?? "").trim().slice(0, 800), members: true };
709
+ if (notes.length >= 10) return skip(n, rawLine, "more than ten notes in one place");
710
+ notes.push(note);
711
+ continueTo = (more) => {
712
+ note.text = `${note.text}
713
+ ${more}`.slice(0, 800);
714
+ };
715
+ return;
716
+ }
717
+ m = RE.item.exec(line);
718
+ if (m) {
719
+ if (!block) {
720
+ block = { label: (m[1] ?? "A").charAt(0), items: [] };
721
+ s.blocks.push(block);
722
+ }
723
+ const label = m[1];
724
+ if (block.items.some((i) => i.label === label))
725
+ return skip(n, rawLine, `item ${label} is there twice`);
726
+ const rest = (m[2] ?? "").trim();
727
+ const found = rest ? prescriptionsOf(rest) : "an item with nothing after its label";
728
+ if (typeof found !== "string") {
729
+ item = { kind: "all", label, exercises: found.list };
730
+ block.items.push(item);
731
+ return;
732
+ }
733
+ const looksLikeHead = rest && !/\s[x×]\s/i.test(rest);
734
+ if (looksLikeHead || !rest) {
735
+ item = {
736
+ kind: "levels",
737
+ label,
738
+ levels: [],
739
+ ...rest ? { notes: [{ text: rest.slice(0, 800), members: true }] } : {}
740
+ };
741
+ block.items.push(item);
742
+ return;
743
+ }
744
+ item = null;
745
+ return skip(n, rawLine, found);
746
+ }
747
+ m = RE.level.exec(line);
748
+ if (m && item?.kind === "all" && block) {
749
+ const at = block.items.indexOf(item);
750
+ const both = {
751
+ kind: "levels",
752
+ label: item.label,
753
+ exercises: item.exercises,
754
+ levels: [],
755
+ ...item.notes ? { notes: item.notes } : {}
756
+ };
757
+ block.items[at] = both;
758
+ item = both;
759
+ }
760
+ if (m && item?.kind === "levels") {
761
+ const number = Number(m[1]);
762
+ if (number < 1 || number > 5) return skip(n, rawLine, "a level is 1 to 5");
763
+ if (item.levels.some((l) => l.level === number))
764
+ return skip(n, rawLine, `level ${number} is there twice`);
765
+ const found = prescriptionsOf(m[2] ?? "");
766
+ if (typeof found === "string") return skip(n, rawLine, found);
767
+ const level = found.list.length === 1 ? { mode: "one", level: number, exercise: found.list[0] } : {
768
+ mode: found.joiner === "|" ? "alternatives" : "together",
769
+ level: number,
770
+ exercises: found.list
771
+ };
772
+ item.levels.push(level);
773
+ item.levels.sort((a, b) => a.level - b.level);
774
+ return;
775
+ }
776
+ if (indented && continueTo) {
777
+ continueTo(line);
778
+ return;
779
+ }
780
+ skip(n, rawLine, "not a line the import knows");
781
+ };
782
+ for (const [index, rawLine] of lines.entries()) readLine(rawLine, index);
783
+ for (const w of weeks) {
784
+ for (const s of w.sessions) {
785
+ for (const b of s.blocks) {
786
+ b.items = b.items.map(
787
+ (i) => i.kind === "levels" && !i.levels.length && i.exercises?.length ? {
788
+ kind: "all",
789
+ label: i.label,
790
+ exercises: i.exercises,
791
+ ...i.notes ? { notes: i.notes } : {}
792
+ } : i
793
+ );
794
+ const kept = b.items.filter((i) => i.kind === "all" || i.levels.length > 0);
795
+ for (const dropped of b.items.filter((i) => !kept.includes(i))) {
796
+ unread.push({
797
+ line: 0,
798
+ text: `${s.name} \u203A ${dropped.label}`,
799
+ reason: "no level of this item could be read"
800
+ });
801
+ }
802
+ b.items = kept;
803
+ }
804
+ const blocks = s.blocks.filter((b) => b.items.length > 0);
805
+ for (const dropped of s.blocks.filter((b) => !blocks.includes(b))) {
806
+ unread.push({
807
+ line: 0,
808
+ text: `${s.name} \u203A block ${dropped.label}`,
809
+ reason: "no item of this block could be read"
810
+ });
811
+ }
812
+ s.blocks = blocks;
813
+ }
814
+ }
815
+ if (!weeks.length) weeks.push({ sessions: [] });
816
+ unread.sort((a, b) => a.line - b.line);
817
+ return {
818
+ title,
819
+ kind: kind2,
820
+ guidance: guidance ? guidance.slice(0, 5e3) : null,
821
+ layout: { weeks },
822
+ unread
823
+ };
824
+ }
825
+ function readBrief(brief) {
826
+ const weeks = /(\d+)\s*-?\s*weeks?/i.exec(brief);
827
+ const perWeek = /(\d+)\s*(?:sessions?|days?|x)\s*(?:a|per|\/)\s*week/i.exec(brief) ?? /(\d+)\s*(?:sessions?|days?)\b/i.exec(brief);
828
+ const focus = norm(brief).split(" ").filter((word) => word.length > 3 && !/^\d+$/.test(word) && !STOP.has(word));
829
+ return {
830
+ weeks: clamp(weeks ? Number(weeks[1]) : 4, 1, MAX_WEEKS),
831
+ sessionsPerWeek: clamp(perWeek ? Number(perWeek[1]) : 3, 1, 7),
832
+ focus: [...new Set(focus)]
833
+ };
834
+ }
835
+ var STOP = /* @__PURE__ */ new Set([
836
+ "week",
837
+ "weeks",
838
+ "session",
839
+ "sessions",
840
+ "with",
841
+ "that",
842
+ "this",
843
+ "from",
844
+ "into",
845
+ "program",
846
+ "programme",
847
+ "client",
848
+ "class",
849
+ "days",
850
+ "each",
851
+ "some",
852
+ "focus",
853
+ "build",
854
+ "make",
855
+ "about",
856
+ "they",
857
+ "their",
858
+ "them",
859
+ "work",
860
+ "working"
861
+ ]);
862
+ var clamp = (n, low, high) => Math.min(Math.max(Math.round(n), low), high);
863
+ function pickExercises(bank, focus) {
864
+ const score = (e) => {
865
+ const words = new Set(norm(`${e.name} ${e.theme ?? ""} ${e.level ?? ""}`).split(" "));
866
+ return focus.filter(
867
+ (f) => words.has(f) || [...words].some((w) => w.startsWith(f) || f.startsWith(w))
868
+ ).length;
869
+ };
870
+ const scored = bank.map((e) => ({ e, s: score(e) })).filter((x) => x.s > 0);
871
+ scored.sort((a, b) => b.s - a.s || a.e.name.localeCompare(b.e.name));
872
+ return scored.length ? scored.map((x) => x.e) : [...bank];
873
+ }
874
+ function defaultSets(measure) {
875
+ const one = measure === "time" ? { kind: "time", seconds: 30, rest: 60 } : measure === "hold" ? { kind: "hold", seconds: 20, rest: 60 } : { kind: "reps", reps: 8, rest: 90 };
876
+ return [one, { ...one }, { ...one }];
877
+ }
878
+ function draftLayout(plan, chosen) {
879
+ const days = [
880
+ [1],
881
+ [1, 4],
882
+ [1, 3, 5],
883
+ [1, 2, 4, 5],
884
+ [1, 2, 3, 4, 5],
885
+ [1, 2, 3, 4, 5, 6],
886
+ [1, 2, 3, 4, 5, 6, 7]
887
+ ][plan.sessionsPerWeek - 1];
888
+ let next = 0;
889
+ const take = () => {
890
+ const e = chosen[next % chosen.length];
891
+ next += 1;
892
+ return { exercise: e.id, sets: defaultSets(e.measure) };
893
+ };
894
+ const sessionsOfWeek = days.map((day, s) => ({
895
+ name: `Session ${String.fromCharCode(65 + s)}`,
896
+ day,
897
+ blocks: chosen.length ? ["A", "B"].map((label) => ({
898
+ label,
899
+ rounds: 3,
900
+ items: [1, 2].map((k) => ({
901
+ kind: "all",
902
+ label: `${label}${k}`,
903
+ exercises: [take()]
904
+ }))
905
+ })) : []
906
+ }));
907
+ return {
908
+ weeks: Array.from({ length: plan.weeks }, (_, w) => ({
909
+ label: `Week ${w + 1}`,
910
+ sessions: JSON.parse(JSON.stringify(sessionsOfWeek))
911
+ }))
912
+ };
913
+ }
914
+
915
+ // ../../packs/programs/tools.ts
916
+ var EXERCISE = "programs.exercise";
917
+ var PROGRAM = "programs.program";
918
+ var ASSIGNMENT = "programs.assignment";
919
+ var SESSION2 = "programs.session";
920
+ var LOG = "programs.log";
921
+ var COACH = "programs:coach";
922
+ var SESSIONS_PER_BATCH = 50;
923
+ var SETS_READ_MAX = 2e3;
924
+ var id = external_exports.string().min(1).max(64);
925
+ var date = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/, "A date: YYYY-MM-DD");
926
+ var text = (value) => value === null || value === void 0 ? null : String(value);
927
+ var num = (value) => typeof value === "number" ? value : value == null ? null : Number(value);
928
+ var isCustomer = (ctx) => ctx.caller?.kind === "customer";
929
+ function list(ctx, object, input) {
930
+ return ctx.ops.call(isCustomer(ctx) ? "my.list" : "record.list", { object, ...input });
931
+ }
932
+ function get(ctx, object, recordId) {
933
+ return ctx.ops.call(isCustomer(ctx) ? "my.get" : "record.get", {
934
+ object,
935
+ id: recordId
936
+ });
937
+ }
938
+ async function all(ctx, object, filter, sort, cap) {
939
+ const items = [];
940
+ let cursor;
941
+ do {
942
+ const page = await list(ctx, object, {
943
+ ...filter ? { filter } : {},
944
+ sort,
945
+ limit: 200,
946
+ ...cursor ? { cursor } : {}
947
+ });
948
+ items.push(...page.items);
949
+ cursor = page.nextCursor ?? void 0;
950
+ } while (cursor && items.length < cap);
951
+ return { items: items.slice(0, cap), capped: Boolean(cursor) || items.length > cap };
952
+ }
953
+ function personFilter(ctx, personId) {
954
+ if (isCustomer(ctx)) {
955
+ if (personId)
956
+ throw new OpsCallError(
957
+ "invalid_input",
958
+ "A member never names a person: it is always themselves"
959
+ );
960
+ return null;
961
+ }
962
+ if (!personId) throw new OpsCallError("invalid_input", "Name the person (personId)");
963
+ return { field: "person", op: "eq", value: personId };
964
+ }
965
+ function addDays(day, days) {
966
+ const at = /* @__PURE__ */ new Date(`${day}T00:00:00Z`);
967
+ at.setUTCDate(at.getUTCDate() + days);
968
+ return at.toISOString().slice(0, 10);
969
+ }
970
+ var todayUtc = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
971
+ var and = (...filters) => {
972
+ const kept = filters.filter((f) => Boolean(f));
973
+ return kept.length === 0 ? void 0 : kept.length === 1 ? kept[0] : { and: kept };
974
+ };
975
+ var assign = defineTool({
976
+ description: "Give a published program to a person or to a class type from a start date: pins the program's current published version and makes one dated session per session of its layout (week w's session on day d is dated start + 7(w-1) + (d-1)). Editing the program later changes none of them; publish a new version and assign again. Refused when the program has never been published. Safe to call again with the same program, person or class type and start date: it finishes what an interrupted call began.",
977
+ input: external_exports.object({
978
+ programId: id,
979
+ personId: id.optional().describe("A person: a client program"),
980
+ classTypeId: id.optional().describe("A class type: a class program"),
981
+ startDate: date
982
+ }).refine((v) => Boolean(v.personId) !== Boolean(v.classTypeId), {
983
+ message: "Name a person or a class type, not both"
984
+ }),
985
+ output: external_exports.object({
986
+ assignmentId: external_exports.string(),
987
+ programVersion: external_exports.number(),
988
+ sessions: external_exports.number(),
989
+ startDate: external_exports.string(),
990
+ endDate: external_exports.string()
991
+ }),
992
+ // Many sessions in one call.
993
+ risk: "bulk-write",
994
+ async handler(input, ctx) {
995
+ const program = await ctx.ops.call("record.get", {
996
+ object: PROGRAM,
997
+ id: input.programId
998
+ });
999
+ let version;
1000
+ try {
1001
+ version = await ctx.ops.call("record.version", { object: PROGRAM, id: input.programId });
1002
+ } catch (error) {
1003
+ if (error instanceof OpsCallError && error.code === "not_found") {
1004
+ throw new OpsCallError(
1005
+ "invalid_input",
1006
+ "This program has not been published: a person with the publish permission publishes it first",
1007
+ { programId: input.programId }
1008
+ );
1009
+ }
1010
+ throw error;
1011
+ }
1012
+ const layout = version.values.layout;
1013
+ const weeks = layout.weeks.length;
1014
+ const endDate = addDays(input.startDate, weeks * 7 - 1);
1015
+ const kind2 = input.personId ? "personal" : "class";
1016
+ const programTitle = text(version.values.title) ?? program.title ?? "Program";
1017
+ const forWhom = input.personId ? text(
1018
+ (await ctx.ops.call("person.get", {
1019
+ id: input.personId
1020
+ })).displayName
1021
+ ) : text(
1022
+ (await ctx.ops.call("record.get", {
1023
+ object: "programs.classtype",
1024
+ id: input.classTypeId
1025
+ })).title
1026
+ );
1027
+ const who = input.personId ? { field: "person", value: input.personId } : { field: "classType", value: input.classTypeId };
1028
+ const earlier = await ctx.ops.call("record.list", {
1029
+ object: ASSIGNMENT,
1030
+ filter: {
1031
+ and: [
1032
+ { field: "program", op: "eq", value: input.programId },
1033
+ { field: who.field, op: "eq", value: who.value },
1034
+ { field: "startDate", op: "eq", value: input.startDate },
1035
+ { field: "programVersion", op: "eq", value: version.version },
1036
+ { field: "state", op: "eq", value: "generating" }
1037
+ ]
1038
+ },
1039
+ limit: 1
1040
+ });
1041
+ const assignmentId = earlier.items[0]?.id ?? (await ctx.ops.call("record.create", {
1042
+ object: ASSIGNMENT,
1043
+ values: {
1044
+ title: `${programTitle}${forWhom ? ` for ${forWhom}` : ""}`,
1045
+ program: input.programId,
1046
+ programVersion: version.version,
1047
+ kind: kind2,
1048
+ [who.field]: who.value,
1049
+ startDate: input.startDate,
1050
+ endDate,
1051
+ ...ctx.caller?.kind === "staff" ? { assignedBy: ctx.caller.userId, assignedByName: ctx.caller.name } : {}
1052
+ }
1053
+ })).id;
1054
+ const made = new Set(
1055
+ (await all(
1056
+ ctx,
1057
+ SESSION2,
1058
+ { field: "assignment", op: "eq", value: assignmentId },
1059
+ { field: "date", direction: "asc" },
1060
+ 1e4
1061
+ )).items.map((s) => text(s.values.key))
1062
+ );
1063
+ const wanted = [];
1064
+ layout.weeks.forEach((week, w) => {
1065
+ week.sessions.forEach((session, position) => {
1066
+ const key = `${assignmentId}:${w + 1}:${position}`;
1067
+ if (made.has(key)) return;
1068
+ wanted.push({
1069
+ name: session.name,
1070
+ assignment: assignmentId,
1071
+ program: input.programId,
1072
+ programVersion: version.version,
1073
+ kind: kind2,
1074
+ [who.field]: who.value,
1075
+ date: addDays(input.startDate, w * 7 + session.day - 1),
1076
+ week: w + 1,
1077
+ day: session.day,
1078
+ position,
1079
+ key,
1080
+ ...session.focus ? { focus: session.focus } : {},
1081
+ plan: session,
1082
+ programTitle,
1083
+ ...who.field === "classType" && forWhom ? { classTypeName: forWhom } : {}
1084
+ });
1085
+ });
1086
+ });
1087
+ for (let start = 0; start < wanted.length; start += SESSIONS_PER_BATCH) {
1088
+ await ctx.ops.call("record.createMany", {
1089
+ object: SESSION2,
1090
+ records: wanted.slice(start, start + SESSIONS_PER_BATCH)
1091
+ });
1092
+ }
1093
+ const sessions = made.size + wanted.length;
1094
+ try {
1095
+ await ctx.ops.call("record.update", {
1096
+ object: ASSIGNMENT,
1097
+ id: assignmentId,
1098
+ from: "generating",
1099
+ values: { state: "active", sessionCount: sessions }
1100
+ });
1101
+ } catch (error) {
1102
+ if (!(error instanceof OpsCallError) || error.code !== "conflict") throw error;
1103
+ }
1104
+ return {
1105
+ assignmentId,
1106
+ programVersion: version.version,
1107
+ sessions,
1108
+ startDate: input.startDate,
1109
+ endDate
1110
+ };
1111
+ }
1112
+ });
1113
+ var lastSet = external_exports.object({
1114
+ date: external_exports.string().nullable(),
1115
+ reps: external_exports.number().nullable(),
1116
+ seconds: external_exports.number().nullable(),
1117
+ load: external_exports.number().nullable(),
1118
+ rpe: external_exports.number().nullable(),
1119
+ level: external_exports.number().nullable()
1120
+ });
1121
+ var exerciseOut = external_exports.object({
1122
+ id: external_exports.string(),
1123
+ name: external_exports.string().nullable(),
1124
+ video: external_exports.string().nullable(),
1125
+ cues: external_exports.string().nullable(),
1126
+ measure: external_exports.string().nullable(),
1127
+ last: external_exports.array(lastSet).describe("The sets of the last time this person did it, before this session")
1128
+ });
1129
+ var loggedSet = external_exports.object({
1130
+ id: external_exports.string(),
1131
+ item: external_exports.string().nullable(),
1132
+ exercise: external_exports.string().nullable(),
1133
+ setNumber: external_exports.number().nullable(),
1134
+ level: external_exports.number().nullable(),
1135
+ target: external_exports.object({
1136
+ reps: external_exports.number().nullable(),
1137
+ seconds: external_exports.number().nullable(),
1138
+ load: external_exports.number().nullable()
1139
+ }),
1140
+ actual: external_exports.object({
1141
+ reps: external_exports.number().nullable(),
1142
+ seconds: external_exports.number().nullable(),
1143
+ load: external_exports.number().nullable()
1144
+ }),
1145
+ rpe: external_exports.number().nullable(),
1146
+ note: external_exports.string().nullable(),
1147
+ recordedAs: external_exports.string().nullable(),
1148
+ recordedByName: external_exports.string().nullable(),
1149
+ exerciseName: external_exports.string().nullable().describe("The exercise's name, as it was when logged")
1150
+ });
1151
+ var sessionOut = external_exports.object({
1152
+ id: external_exports.string(),
1153
+ name: external_exports.string().nullable(),
1154
+ date: external_exports.string().nullable(),
1155
+ week: external_exports.number().nullable(),
1156
+ day: external_exports.number().nullable(),
1157
+ kind: external_exports.string().nullable(),
1158
+ classType: external_exports.string().nullable(),
1159
+ assignment: external_exports.string().nullable(),
1160
+ programVersion: external_exports.number().nullable(),
1161
+ programTitle: external_exports.string().nullable(),
1162
+ classTypeName: external_exports.string().nullable(),
1163
+ focus: external_exports.string().nullable(),
1164
+ state: external_exports.string().nullable(),
1165
+ plan: external_exports.record(external_exports.string(), external_exports.unknown()).nullable().describe("The session of the layout: blocks, items, levels and typed sets")
1166
+ });
1167
+ function sessionOf(record) {
1168
+ const v = record.values;
1169
+ return {
1170
+ id: record.id,
1171
+ name: text(v.name),
1172
+ date: text(v.date),
1173
+ week: num(v.week),
1174
+ day: num(v.day),
1175
+ kind: text(v.kind),
1176
+ classType: text(v.classType),
1177
+ assignment: text(v.assignment),
1178
+ programVersion: num(v.programVersion),
1179
+ programTitle: text(v.programTitle),
1180
+ classTypeName: text(v.classTypeName),
1181
+ focus: text(v.focus),
1182
+ state: text(v.state),
1183
+ plan: v.plan ?? null
1184
+ };
1185
+ }
1186
+ function loggedOf(record) {
1187
+ const v = record.values;
1188
+ return {
1189
+ id: record.id,
1190
+ item: text(v.item),
1191
+ exercise: text(v.exercise),
1192
+ setNumber: num(v.setNumber),
1193
+ level: num(v.level),
1194
+ target: { reps: num(v.targetReps), seconds: num(v.targetSeconds), load: num(v.targetLoad) },
1195
+ actual: { reps: num(v.actualReps), seconds: num(v.actualSeconds), load: num(v.actualLoad) },
1196
+ rpe: num(v.rpe),
1197
+ note: text(v.note),
1198
+ recordedAs: text(v.recordedAs),
1199
+ recordedByName: text(v.recordedByName),
1200
+ exerciseName: text(v.exerciseName)
1201
+ };
1202
+ }
1203
+ async function exercisesFor(ctx, session, person) {
1204
+ const plan = session.plan;
1205
+ if (!plan) return [];
1206
+ const ids = [
1207
+ .../* @__PURE__ */ new Set([
1208
+ ...(plan.warmup?.exercises ?? []).map((p) => p.exercise),
1209
+ ...prescriptions(plan).map((p) => p.prescription.exercise)
1210
+ ])
1211
+ ];
1212
+ if (!ids.length) return [];
1213
+ const bank = await list(ctx, EXERCISE, {
1214
+ filter: { field: "id", op: "in", value: ids },
1215
+ limit: 200
1216
+ });
1217
+ const earlier = person === false ? { items: [] } : await all(
1218
+ ctx,
1219
+ LOG,
1220
+ and(
1221
+ { field: "exercise", op: "in", value: ids },
1222
+ { field: "session", op: "neq", value: session.id },
1223
+ session.date ? { field: "date", op: "lte", value: session.date } : null,
1224
+ person
1225
+ ),
1226
+ { field: "date", direction: "desc" },
1227
+ 400
1228
+ );
1229
+ return ids.map((exerciseId) => {
1230
+ const found = bank.items.find((e) => e.id === exerciseId);
1231
+ const mine = earlier.items.filter((l) => l.values.exercise === exerciseId);
1232
+ const lastSession = mine[0]?.values.session;
1233
+ return {
1234
+ id: exerciseId,
1235
+ name: text(found?.values.name),
1236
+ video: text(found?.values.video),
1237
+ cues: text(found?.values.cues),
1238
+ measure: text(found?.values.measure),
1239
+ last: mine.filter((l) => l.values.session === lastSession).sort((a, b) => (num(a.values.setNumber) ?? 0) - (num(b.values.setNumber) ?? 0)).map((l) => ({
1240
+ date: text(l.values.date),
1241
+ reps: num(l.values.actualReps),
1242
+ seconds: num(l.values.actualSeconds),
1243
+ load: num(l.values.actualLoad),
1244
+ rpe: num(l.values.rpe),
1245
+ level: num(l.values.level)
1246
+ }))
1247
+ };
1248
+ });
1249
+ }
1250
+ var personInput = id.optional().describe("Staff: the person. A member is always themselves.");
1251
+ var today = defineTool({
1252
+ description: "A person's own sessions on a date (default today, UTC: pass the person's local date), each with its plan (blocks, items, levels and typed targets), the bank exercises it uses and the numbers of the last time they did each. A member sees their own; staff name the person. A class type's sessions are programs.classToday. Read-only.",
1253
+ input: external_exports.object({ date: date.optional(), personId: personInput }),
1254
+ output: external_exports.object({
1255
+ date: external_exports.string(),
1256
+ sessions: external_exports.array(sessionOut.extend({ exercises: external_exports.array(exerciseOut) }))
1257
+ }),
1258
+ risk: "read",
1259
+ audiences: ["staff", "customer"],
1260
+ permission: COACH,
1261
+ async handler(input, ctx) {
1262
+ const day = input.date ?? todayUtc();
1263
+ const person = personFilter(ctx, input.personId);
1264
+ const page = await list(ctx, SESSION2, {
1265
+ filter: and(
1266
+ { field: "date", op: "eq", value: day },
1267
+ { field: "kind", op: "eq", value: "personal" },
1268
+ person
1269
+ ),
1270
+ sort: { field: "week", direction: "asc" },
1271
+ limit: 50
1272
+ });
1273
+ const sessions = [];
1274
+ for (const record of page.items) {
1275
+ const session = sessionOf(record);
1276
+ sessions.push({ ...session, exercises: await exercisesFor(ctx, session, person) });
1277
+ }
1278
+ return { date: day, sessions };
1279
+ }
1280
+ });
1281
+ var sessionGet = defineTool({
1282
+ description: "One session: its plan, the bank exercises it uses with the person's last numbers at each, and the sets logged on it so far. A member reads their own sessions and their class types' (where `personId` is never given); staff read any, and name the person for a class session's logs. Read-only.",
1283
+ input: external_exports.object({ sessionId: id, personId: personInput }),
1284
+ output: external_exports.object({
1285
+ session: sessionOut,
1286
+ exercises: external_exports.array(exerciseOut),
1287
+ logged: external_exports.array(loggedSet)
1288
+ }),
1289
+ risk: "read",
1290
+ audiences: ["staff", "customer"],
1291
+ permission: COACH,
1292
+ async handler(input, ctx) {
1293
+ const record = await get(ctx, SESSION2, input.sessionId);
1294
+ const session = sessionOf(record);
1295
+ const owner = sessionPerson(ctx, record, input.personId);
1296
+ const person = owner ? { field: "person", op: "eq", value: owner } : isCustomer(ctx) ? null : false;
1297
+ const logged = await all(
1298
+ ctx,
1299
+ LOG,
1300
+ and({ field: "session", op: "eq", value: input.sessionId }, person || null),
1301
+ { field: "setNumber", direction: "asc" },
1302
+ 400
1303
+ );
1304
+ return {
1305
+ session,
1306
+ exercises: await exercisesFor(ctx, session, person),
1307
+ logged: logged.items.map(loggedOf)
1308
+ };
1309
+ }
1310
+ });
1311
+ function sessionPerson(ctx, record, personId) {
1312
+ if (isCustomer(ctx)) {
1313
+ if (personId) {
1314
+ throw new OpsCallError(
1315
+ "invalid_input",
1316
+ "A member never names a person: it is always themselves"
1317
+ );
1318
+ }
1319
+ return null;
1320
+ }
1321
+ if (record.values.kind === "class") return personId ?? null;
1322
+ const own = text(record.values.person);
1323
+ if (personId && personId !== own) {
1324
+ throw new OpsCallError(
1325
+ "invalid_input",
1326
+ "This session is another person's: leave personId out, or name its person"
1327
+ );
1328
+ }
1329
+ return own;
1330
+ }
1331
+ var classToday = defineTool({
1332
+ description: "A class type's sessions on a date (default today, UTC), with their plans: every level of every item, typed targets, and the bank exercises. What a coach runs a class from and a member reads before it. Notes for coaches only are left out for members. Read-only.",
1333
+ input: external_exports.object({ classTypeId: id, date: date.optional() }),
1334
+ output: external_exports.object({
1335
+ date: external_exports.string(),
1336
+ sessions: external_exports.array(sessionOut.extend({ exercises: external_exports.array(exerciseOut) }))
1337
+ }),
1338
+ risk: "read",
1339
+ audiences: ["staff", "customer"],
1340
+ async handler(input, ctx) {
1341
+ const day = input.date ?? todayUtc();
1342
+ const page = await list(ctx, SESSION2, {
1343
+ filter: {
1344
+ and: [
1345
+ { field: "date", op: "eq", value: day },
1346
+ { field: "kind", op: "eq", value: "class" },
1347
+ { field: "classType", op: "eq", value: input.classTypeId }
1348
+ ]
1349
+ },
1350
+ sort: { field: "week", direction: "asc" },
1351
+ limit: 20
1352
+ });
1353
+ const sessions = [];
1354
+ for (const record of page.items) {
1355
+ const session = sessionOf(record);
1356
+ sessions.push({
1357
+ ...session,
1358
+ exercises: await exercisesFor(ctx, session, isCustomer(ctx) ? null : false)
1359
+ });
1360
+ }
1361
+ return { date: day, sessions };
1362
+ }
1363
+ });
1364
+ function targetIn(plan, item, exercise, level, setNumber) {
1365
+ const found = prescriptions(plan).filter((p) => p.item === item);
1366
+ if (!found.length) {
1367
+ throw new OpsCallError("invalid_input", `This session has no item ${item}`, { item });
1368
+ }
1369
+ const levels = [...new Set(found.map((p) => p.level))];
1370
+ const everyone = found.filter((p) => p.level === null);
1371
+ if (levels.some((l) => l !== null) && level === void 0 && !everyone.length) {
1372
+ throw new OpsCallError("invalid_input", `Item ${item} has levels: say which was taken`, {
1373
+ item,
1374
+ levels
1375
+ });
1376
+ }
1377
+ if (level !== void 0 && !levels.includes(level)) {
1378
+ throw new OpsCallError("invalid_input", `Item ${item} has no level ${level}`, { item, levels });
1379
+ }
1380
+ const atLevel = level === void 0 ? levels.some((l) => l !== null) ? everyone : found : [...found.filter((p) => p.level === level), ...everyone];
1381
+ const match = exercise ? atLevel.filter((p) => p.prescription.exercise === exercise) : atLevel;
1382
+ if (!match.length || !exercise && match.length > 1) {
1383
+ throw new OpsCallError(
1384
+ "invalid_input",
1385
+ exercise ? `Item ${item}${level ? ` at level ${level}` : ""} does not have that exercise` : `Item ${item} has more than one exercise: say which`,
1386
+ { item, exercises: atLevel.map((p) => p.prescription.exercise) }
1387
+ );
1388
+ }
1389
+ const chosen = match[0];
1390
+ return {
1391
+ prescription: chosen.prescription,
1392
+ target: chosen.prescription.sets[setNumber - 1] ?? null,
1393
+ // An exercise for everyone keeps the level the person took, when they say it.
1394
+ level: chosen.level ?? level ?? null
1395
+ };
1396
+ }
1397
+ var actual = external_exports.object({
1398
+ reps: external_exports.number().int().min(0).max(999).optional(),
1399
+ seconds: external_exports.number().int().min(0).max(7200).optional(),
1400
+ load: external_exports.number().min(0).max(1e3).optional().describe("Kilograms")
1401
+ });
1402
+ var rpe = external_exports.number().min(1).max(10).refine((n) => Number.isInteger(n * 2), "In halves: 7 or 7.5").optional().describe("How hard it felt, 1 to 10 in halves");
1403
+ var setKeyOf = (sessionId, item, exercise, setNumber) => `${sessionId}/${item}/${exercise}/${setNumber}`;
1404
+ async function setRows(ctx, set, person) {
1405
+ const page = await list(ctx, LOG, {
1406
+ filter: and(
1407
+ { field: "session", op: "eq", value: set.sessionId },
1408
+ { field: "item", op: "eq", value: set.item },
1409
+ { field: "exercise", op: "eq", value: set.exercise },
1410
+ { field: "setNumber", op: "eq", value: set.setNumber },
1411
+ person ? { field: "person", op: "eq", value: person } : null
1412
+ ),
1413
+ sort: { field: "setNumber", direction: "asc" },
1414
+ limit: 20
1415
+ });
1416
+ return page.items;
1417
+ }
1418
+ var logAdd = defineTool({
1419
+ description: "Log one set done on a session: the item (A1), the exercise when the item has more than one, the level taken when it has levels, which set (1, 2, \u2026), what was done (reps, seconds, load) and how hard it felt (RPE). The target is taken from the session's plan, and who recorded it is the caller. A member logs on their own sessions and their class types'; a coach logs for a client (on a class session, naming them). Nobody logs on a session that is not theirs. A set already logged (a retried save, a second device) is not logged twice: its numbers and effort become these, and its note is kept unless one is given. Returns the set.",
1420
+ input: external_exports.object({
1421
+ sessionId: id,
1422
+ item: external_exports.string().min(1).max(6),
1423
+ exerciseId: id.optional(),
1424
+ level: external_exports.number().int().min(1).max(5).optional(),
1425
+ setNumber: external_exports.number().int().min(1).max(30),
1426
+ actual,
1427
+ rpe,
1428
+ note: external_exports.string().max(500).optional(),
1429
+ personId: personInput
1430
+ }),
1431
+ output: loggedSet,
1432
+ risk: "write",
1433
+ audiences: ["staff", "customer"],
1434
+ permission: COACH,
1435
+ customerFields: {
1436
+ [LOG]: [
1437
+ "label",
1438
+ "exerciseName",
1439
+ "session",
1440
+ "assignment",
1441
+ "exercise",
1442
+ "item",
1443
+ "setNumber",
1444
+ "level",
1445
+ "date",
1446
+ "targetReps",
1447
+ "targetSeconds",
1448
+ "targetLoad",
1449
+ "recordedAs",
1450
+ "setKey"
1451
+ ]
1452
+ },
1453
+ async handler(input, ctx) {
1454
+ const record = await get(ctx, SESSION2, input.sessionId);
1455
+ const session = sessionOf(record);
1456
+ const person = sessionPerson(ctx, record, input.personId);
1457
+ if (!isCustomer(ctx) && !person) {
1458
+ throw new OpsCallError("invalid_input", "A class session: name the person (personId)");
1459
+ }
1460
+ if (!session.plan) throw new OpsCallError("invalid_input", "This session has no plan");
1461
+ const { prescription, target, level } = targetIn(
1462
+ session.plan,
1463
+ input.item,
1464
+ input.exerciseId,
1465
+ input.level,
1466
+ input.setNumber
1467
+ );
1468
+ const values = {
1469
+ label: `${input.item} set ${input.setNumber}`,
1470
+ session: input.sessionId,
1471
+ assignment: session.assignment,
1472
+ exercise: prescription.exercise,
1473
+ exerciseName: text((await get(ctx, EXERCISE, prescription.exercise)).values.name),
1474
+ item: input.item,
1475
+ setNumber: input.setNumber,
1476
+ level,
1477
+ date: session.date,
1478
+ targetReps: target?.kind === "reps" ? target.reps : null,
1479
+ targetSeconds: target && target.kind !== "reps" ? target.seconds : null,
1480
+ targetLoad: target?.load ?? null,
1481
+ actualReps: input.actual.reps ?? null,
1482
+ actualSeconds: input.actual.seconds ?? null,
1483
+ actualLoad: input.actual.load ?? null,
1484
+ rpe: input.rpe ?? null,
1485
+ note: input.note ?? null,
1486
+ recordedAs: isCustomer(ctx) ? "self" : "staff",
1487
+ setKey: setKeyOf(input.sessionId, input.item, prescription.exercise, input.setNumber)
1488
+ };
1489
+ const set = {
1490
+ sessionId: input.sessionId,
1491
+ item: input.item,
1492
+ exercise: prescription.exercise,
1493
+ setNumber: input.setNumber
1494
+ };
1495
+ const again = async () => {
1496
+ const [row] = await setRows(ctx, set, person);
1497
+ if (!row) return null;
1498
+ return loggedOf(
1499
+ await ctx.ops.call(isCustomer(ctx) ? "my.update" : "record.update", {
1500
+ object: LOG,
1501
+ id: row.id,
1502
+ values: {
1503
+ level,
1504
+ actualReps: values.actualReps,
1505
+ actualSeconds: values.actualSeconds,
1506
+ actualLoad: values.actualLoad,
1507
+ rpe: values.rpe,
1508
+ ...input.note !== void 0 ? { note: input.note } : {}
1509
+ }
1510
+ })
1511
+ );
1512
+ };
1513
+ const logged = await again();
1514
+ if (logged) return logged;
1515
+ const caller = ctx.caller?.kind === "staff" ? ctx.caller : null;
1516
+ try {
1517
+ if (isCustomer(ctx)) {
1518
+ return loggedOf(await ctx.ops.call("my.create", { object: LOG, values }));
1519
+ }
1520
+ return loggedOf(
1521
+ await ctx.ops.call("record.create", {
1522
+ object: LOG,
1523
+ values: {
1524
+ ...values,
1525
+ person,
1526
+ ...caller ? { recordedBy: caller.userId, recordedByName: caller.name } : {}
1527
+ }
1528
+ })
1529
+ );
1530
+ } catch (error) {
1531
+ if (!(error instanceof OpsCallError) || error.code !== "conflict") throw error;
1532
+ const changed = await again();
1533
+ if (!changed) throw error;
1534
+ return changed;
1535
+ }
1536
+ }
1537
+ });
1538
+ var logUpdate = defineTool({
1539
+ description: "Change a logged set's numbers, effort or note. A member changes their own sets only; staff any. The target, the exercise and who recorded it stay as they were. Returns the set.",
1540
+ input: external_exports.object({
1541
+ logId: id,
1542
+ actual: actual.optional(),
1543
+ rpe,
1544
+ note: external_exports.string().max(500).nullable().optional()
1545
+ }),
1546
+ output: loggedSet,
1547
+ risk: "write",
1548
+ audiences: ["staff", "customer"],
1549
+ permission: COACH,
1550
+ async handler(input, ctx) {
1551
+ const values = {
1552
+ ...input.actual?.reps !== void 0 ? { actualReps: input.actual.reps } : {},
1553
+ ...input.actual?.seconds !== void 0 ? { actualSeconds: input.actual.seconds } : {},
1554
+ ...input.actual?.load !== void 0 ? { actualLoad: input.actual.load } : {},
1555
+ ...input.rpe !== void 0 ? { rpe: input.rpe } : {},
1556
+ ...input.note !== void 0 ? { note: input.note } : {}
1557
+ };
1558
+ if (!Object.keys(values).length) {
1559
+ return loggedOf(await get(ctx, LOG, input.logId));
1560
+ }
1561
+ return loggedOf(
1562
+ await ctx.ops.call(isCustomer(ctx) ? "my.update" : "record.update", {
1563
+ object: LOG,
1564
+ id: input.logId,
1565
+ values
1566
+ })
1567
+ );
1568
+ }
1569
+ });
1570
+ var logRemove = defineTool({
1571
+ description: "Take back a set logged by mistake (un-tick it): the set with this number of a session's item and exercise. A member takes back their own; a coach a client's (on a class session, naming them). A set that is not logged changes nothing, so a retried call is safe. The row goes to the Trash, where staff can restore it. For staff the Trash is an extension's delete, so the org's approval policy may hold it for a person: `waiting` counts those. Returns how many rows were taken back.",
1572
+ input: external_exports.object({
1573
+ sessionId: id,
1574
+ item: external_exports.string().min(1).max(6),
1575
+ exerciseId: id,
1576
+ setNumber: external_exports.number().int().min(1).max(30),
1577
+ personId: personInput
1578
+ }),
1579
+ output: external_exports.object({
1580
+ removed: external_exports.number().int(),
1581
+ waiting: external_exports.number().int().describe("Staff: rows whose removal waits for a person's approval")
1582
+ }),
1583
+ risk: "write",
1584
+ audiences: ["staff", "customer"],
1585
+ permission: COACH,
1586
+ async handler(input, ctx) {
1587
+ const record = await get(ctx, SESSION2, input.sessionId);
1588
+ const person = sessionPerson(ctx, record, input.personId);
1589
+ if (!isCustomer(ctx) && !person) {
1590
+ throw new OpsCallError("invalid_input", "A class session: name the person (personId)");
1591
+ }
1592
+ const rows = await setRows(
1593
+ ctx,
1594
+ {
1595
+ sessionId: input.sessionId,
1596
+ item: input.item,
1597
+ exercise: input.exerciseId,
1598
+ setNumber: input.setNumber
1599
+ },
1600
+ person
1601
+ );
1602
+ let removed = 0;
1603
+ let waiting = 0;
1604
+ for (const row of rows) {
1605
+ try {
1606
+ await ctx.ops.call(isCustomer(ctx) ? "my.delete" : "record.delete", {
1607
+ object: LOG,
1608
+ id: row.id
1609
+ });
1610
+ removed += 1;
1611
+ } catch (error) {
1612
+ if (!(error instanceof OpsCallError) || error.code !== "pending_approval") throw error;
1613
+ waiting += 1;
1614
+ }
1615
+ }
1616
+ return { removed, waiting };
1617
+ }
1618
+ });
1619
+ var sessionComplete = defineTool({
1620
+ description: "Mark one of a person's sessions done or skipped (or back to planned). A member marks their own; staff any personal session. A class type's sessions are not marked by members. Made from the session's current state, so two marks at once count once. Returns the session.",
1621
+ input: external_exports.object({
1622
+ sessionId: id,
1623
+ state: external_exports.enum(["done", "skipped", "planned"]).default("done")
1624
+ }),
1625
+ output: external_exports.object({ changed: external_exports.boolean(), session: sessionOut }),
1626
+ risk: "write",
1627
+ audiences: ["staff", "customer"],
1628
+ permission: COACH,
1629
+ customerFields: { [SESSION2]: ["state", "completedAt"] },
1630
+ async handler(input, ctx) {
1631
+ const current = sessionOf(await get(ctx, SESSION2, input.sessionId));
1632
+ if (current.state === input.state) return { changed: false, session: current };
1633
+ const from = current.state ?? "planned";
1634
+ const marked = input.state === "planned" ? { completedAt: null } : { completedAt: (/* @__PURE__ */ new Date()).toISOString() };
1635
+ const caller = ctx.caller?.kind === "staff" ? ctx.caller : null;
1636
+ try {
1637
+ const after = await ctx.ops.call(
1638
+ isCustomer(ctx) ? "my.update" : "record.update",
1639
+ {
1640
+ object: SESSION2,
1641
+ id: input.sessionId,
1642
+ from,
1643
+ values: {
1644
+ state: input.state,
1645
+ ...marked,
1646
+ ...caller ? input.state === "planned" ? { completedBy: null, completedByName: null } : { completedBy: caller.userId, completedByName: caller.name } : {}
1647
+ }
1648
+ }
1649
+ );
1650
+ return { changed: true, session: sessionOf(after) };
1651
+ } catch (error) {
1652
+ if (!(error instanceof OpsCallError) || error.code !== "conflict") throw error;
1653
+ return { changed: false, session: sessionOf(await get(ctx, SESSION2, input.sessionId)) };
1654
+ }
1655
+ }
1656
+ });
1657
+ var best = external_exports.object({
1658
+ load: external_exports.number().nullable().describe("Heaviest load in one set"),
1659
+ reps: external_exports.number().nullable().describe("Most reps in one set"),
1660
+ seconds: external_exports.number().nullable().describe("Longest time in one set")
1661
+ });
1662
+ function bestOf(sets) {
1663
+ const max = (field) => {
1664
+ const values = sets.map((s) => num(s.values[field])).filter((n) => n !== null);
1665
+ return values.length ? Math.max(...values) : null;
1666
+ };
1667
+ return { load: max("actualLoad"), reps: max("actualReps"), seconds: max("actualSeconds") };
1668
+ }
1669
+ var history = defineTool({
1670
+ description: "Every set a person logged of one exercise, oldest first (date, set, level, target and what was done, effort), and their bests at it (heaviest load, most reps, longest time). A member reads their own; staff name the person. At most 2,000 sets; `capped` says when there were more. Read-only.",
1671
+ input: external_exports.object({
1672
+ exerciseId: id,
1673
+ personId: personInput,
1674
+ from: date.optional(),
1675
+ until: date.optional()
1676
+ }),
1677
+ output: external_exports.object({
1678
+ exercise: external_exports.object({ id: external_exports.string(), name: external_exports.string().nullable() }),
1679
+ sets: external_exports.array(loggedSet.extend({ date: external_exports.string().nullable() })),
1680
+ best,
1681
+ capped: external_exports.boolean()
1682
+ }),
1683
+ risk: "read",
1684
+ audiences: ["staff", "customer"],
1685
+ permission: COACH,
1686
+ async handler(input, ctx) {
1687
+ const person = personFilter(ctx, input.personId);
1688
+ const exercise = await get(ctx, EXERCISE, input.exerciseId);
1689
+ const sets = await all(
1690
+ ctx,
1691
+ LOG,
1692
+ and(
1693
+ { field: "exercise", op: "eq", value: input.exerciseId },
1694
+ person,
1695
+ input.from ? { field: "date", op: "gte", value: input.from } : null,
1696
+ input.until ? { field: "date", op: "lte", value: input.until } : null
1697
+ ),
1698
+ { field: "date", direction: "asc" },
1699
+ SETS_READ_MAX
1700
+ );
1701
+ return {
1702
+ exercise: { id: exercise.id, name: text(exercise.values.name) },
1703
+ sets: sets.items.map((s) => ({ ...loggedOf(s), date: text(s.values.date) })),
1704
+ best: bestOf(sets.items),
1705
+ capped: sets.capped
1706
+ };
1707
+ }
1708
+ });
1709
+ var progress = defineTool({
1710
+ description: "A person's training at a glance: for each exercise they logged, how many sets, the first and last date, and their bests; and for each of their assignments, sessions planned, done and skipped. Optionally only one assignment. A member reads their own; staff name the person. Worked out over at most 2,000 sets (`capped`). Read-only.",
1711
+ input: external_exports.object({ personId: personInput, assignmentId: id.optional() }),
1712
+ output: external_exports.object({
1713
+ exercises: external_exports.array(
1714
+ external_exports.object({
1715
+ id: external_exports.string(),
1716
+ name: external_exports.string().nullable(),
1717
+ sets: external_exports.number(),
1718
+ first: external_exports.string().nullable(),
1719
+ last: external_exports.string().nullable(),
1720
+ best
1721
+ })
1722
+ ),
1723
+ assignments: external_exports.array(
1724
+ external_exports.object({
1725
+ id: external_exports.string(),
1726
+ title: external_exports.string().nullable(),
1727
+ sessions: external_exports.number(),
1728
+ done: external_exports.number(),
1729
+ skipped: external_exports.number(),
1730
+ planned: external_exports.number()
1731
+ })
1732
+ ),
1733
+ capped: external_exports.boolean()
1734
+ }),
1735
+ risk: "read",
1736
+ audiences: ["staff", "customer"],
1737
+ permission: COACH,
1738
+ async handler(input, ctx) {
1739
+ const person = personFilter(ctx, input.personId);
1740
+ const only = input.assignmentId ? { field: "assignment", op: "eq", value: input.assignmentId } : null;
1741
+ const sets = await all(
1742
+ ctx,
1743
+ LOG,
1744
+ and(person, only),
1745
+ { field: "date", direction: "asc" },
1746
+ SETS_READ_MAX
1747
+ );
1748
+ const byExercise = /* @__PURE__ */ new Map();
1749
+ for (const set of sets.items) {
1750
+ const exercise = text(set.values.exercise);
1751
+ if (exercise) byExercise.set(exercise, [...byExercise.get(exercise) ?? [], set]);
1752
+ }
1753
+ const ids = [...byExercise.keys()];
1754
+ const names = /* @__PURE__ */ new Map();
1755
+ for (let start = 0; start < ids.length; start += 200) {
1756
+ const page = await list(ctx, EXERCISE, {
1757
+ filter: { field: "id", op: "in", value: ids.slice(start, start + 200) },
1758
+ limit: 200
1759
+ });
1760
+ for (const e of page.items) names.set(e.id, text(e.values.name));
1761
+ }
1762
+ const assignments = await all(
1763
+ ctx,
1764
+ ASSIGNMENT,
1765
+ and(
1766
+ person,
1767
+ { field: "kind", op: "eq", value: "personal" },
1768
+ input.assignmentId ? { field: "id", op: "eq", value: input.assignmentId } : null
1769
+ ),
1770
+ { field: "startDate", direction: "asc" },
1771
+ 100
1772
+ );
1773
+ const summaries = [];
1774
+ for (const assignment of assignments.items) {
1775
+ const sessions = await all(
1776
+ ctx,
1777
+ SESSION2,
1778
+ { field: "assignment", op: "eq", value: assignment.id },
1779
+ { field: "date", direction: "asc" },
1780
+ 1e3
1781
+ );
1782
+ const count = (state) => sessions.items.filter((s) => s.values.state === state).length;
1783
+ summaries.push({
1784
+ id: assignment.id,
1785
+ title: text(assignment.values.title),
1786
+ sessions: sessions.items.length,
1787
+ done: count("done"),
1788
+ skipped: count("skipped"),
1789
+ planned: count("planned")
1790
+ });
1791
+ }
1792
+ return {
1793
+ exercises: ids.map((exerciseId) => {
1794
+ const mine = byExercise.get(exerciseId) ?? [];
1795
+ return {
1796
+ id: exerciseId,
1797
+ name: names.get(exerciseId) ?? null,
1798
+ sets: mine.length,
1799
+ first: text(mine[0]?.values.date),
1800
+ last: text(mine.at(-1)?.values.date),
1801
+ best: bestOf(mine)
1802
+ };
1803
+ }),
1804
+ assignments: summaries,
1805
+ capped: sets.capped
1806
+ };
1807
+ }
1808
+ });
1809
+ async function bankOf(ctx) {
1810
+ const rows = await all(ctx, EXERCISE, void 0, { field: "name", direction: "asc" }, 2e3);
1811
+ return rows.items.map((e) => ({
1812
+ id: e.id,
1813
+ name: text(e.values.name) ?? "",
1814
+ measure: text(e.values.measure),
1815
+ theme: text(e.values.theme),
1816
+ level: text(e.values.level)
1817
+ }));
1818
+ }
1819
+ var workingCopy = external_exports.object({
1820
+ programId: external_exports.string(),
1821
+ title: external_exports.string(),
1822
+ weeks: external_exports.number(),
1823
+ sessions: external_exports.number(),
1824
+ published: external_exports.literal(false).describe("Always false: a person publishes it")
1825
+ });
1826
+ var draft = defineTool({
1827
+ description: 'Draft a program from a brief ("12 weeks of handstand strength, 3 sessions a week") as a working copy for a coach to edit: weeks of sessions of blocks of exercises taken only from the bank, with default sets. The assistant reads the brief with the extract model role when the deployment has AI, and the numbers and words in it otherwise. It never publishes: a person with the publish permission does, after editing. Returns the new program.',
1828
+ input: external_exports.object({
1829
+ brief: external_exports.string().trim().min(3).max(2e3),
1830
+ title: external_exports.string().trim().min(1).max(200).optional(),
1831
+ kind: external_exports.enum(["class", "client", "course"]).default("client")
1832
+ }),
1833
+ output: workingCopy.extend({
1834
+ exercises: external_exports.array(external_exports.object({ id: external_exports.string(), name: external_exports.string() }))
1835
+ }),
1836
+ risk: "write",
1837
+ async handler(input, ctx) {
1838
+ const bank = await bankOf(ctx);
1839
+ if (!bank.length) {
1840
+ throw new OpsCallError("invalid_input", "The exercise bank is empty: add exercises first");
1841
+ }
1842
+ const floor = readBrief(input.brief);
1843
+ let plan = floor;
1844
+ try {
1845
+ const read = await ctx.ai.extract(input.brief, {
1846
+ weeks: "How many weeks the program runs, a whole number",
1847
+ sessionsPerWeek: "How many sessions a week, a whole number from 1 to 7",
1848
+ focus: "The themes, body areas or moves it is about, as a comma-separated list"
1849
+ });
1850
+ const weeks = Number(read.weeks);
1851
+ const perWeek = Number(read.sessionsPerWeek);
1852
+ const focus = typeof read.focus === "string" ? read.focus.toLowerCase().split(/[,;]/) : [];
1853
+ plan = {
1854
+ weeks: Number.isInteger(weeks) && weeks >= 1 && weeks <= 52 ? weeks : floor.weeks,
1855
+ sessionsPerWeek: Number.isInteger(perWeek) && perWeek >= 1 && perWeek <= 7 ? perWeek : floor.sessionsPerWeek,
1856
+ focus: [.../* @__PURE__ */ new Set([...focus.map((f) => f.trim()).filter(Boolean), ...floor.focus])]
1857
+ };
1858
+ } catch {
1859
+ }
1860
+ const chosen = pickExercises(bank, plan.focus).slice(0, 12);
1861
+ const layout = draftLayout(plan, chosen);
1862
+ const title = input.title ?? `Draft: ${input.brief.slice(0, 60)}`;
1863
+ const created = await ctx.ops.call("record.create", {
1864
+ object: PROGRAM,
1865
+ values: {
1866
+ title,
1867
+ kind: input.kind,
1868
+ guidance: `Drafted from the brief: ${input.brief}`.slice(0, 5e3),
1869
+ layout
1870
+ }
1871
+ });
1872
+ return {
1873
+ programId: created.id,
1874
+ title,
1875
+ weeks: layout.weeks.length,
1876
+ sessions: layout.weeks.reduce((n, w) => n + w.sessions.length, 0),
1877
+ published: false,
1878
+ exercises: chosen.map((e) => ({ id: e.id, name: e.name }))
1879
+ };
1880
+ }
1881
+ });
1882
+ function canonical(value) {
1883
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
1884
+ if (value && typeof value === "object") {
1885
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0 && v !== null).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1886
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
1887
+ }
1888
+ return JSON.stringify(value ?? null);
1889
+ }
1890
+ function contentHash(text2) {
1891
+ const one = (seed) => {
1892
+ let h1 = 3735928559 ^ seed;
1893
+ let h2 = 1103547991 ^ seed;
1894
+ for (let i = 0; i < text2.length; i += 1) {
1895
+ const c = text2.charCodeAt(i);
1896
+ h1 = Math.imul(h1 ^ c, 2654435761);
1897
+ h2 = Math.imul(h2 ^ c, 1597334677);
1898
+ }
1899
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
1900
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
1901
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, "0");
1902
+ };
1903
+ return `${one(1)}${one(2)}`;
1904
+ }
1905
+ function importedHashOf(values) {
1906
+ return contentHash(
1907
+ canonical({
1908
+ title: values.title,
1909
+ kind: values.kind,
1910
+ guidance: values.guidance,
1911
+ layout: values.layout
1912
+ })
1913
+ );
1914
+ }
1915
+ var importText = defineTool({
1916
+ description: `Turn pasted program shorthand, or a document's text, into a working copy with structured targets: Title:, Kind:, Guidance:, Week:, Session: (a weekday names its day), Focus:, Warm-up: with - lines, Block A: with its rounds, items A1: with an exercise (for everyone), with level lines 1: to 5: ("+" done together, "|" alternatives), or with both, * notes for coaches and TV: notes shown to members. Exercises are matched to the bank by name. Every line it could not read is listed with why, for the coach to fix; nothing is guessed. With a key (the text's name in its source), running it again changes the same program: updated while it still holds what the import last wrote, unchanged when the text is the same, and a conflict, left alone, when someone has edited it since. dryRun reads and checks the text and says what would happen, writing nothing. Never publishes. Returns the program and the unread lines.`,
1917
+ input: external_exports.object({
1918
+ text: external_exports.string().min(1).max(2e5),
1919
+ title: external_exports.string().trim().min(1).max(200).optional(),
1920
+ kind: external_exports.enum(["class", "client", "course"]).optional().describe("Left out: what a Kind: line says, else class"),
1921
+ key: external_exports.string().trim().min(1).max(200).optional().describe("The text's import key (its file name in the source): one program per key"),
1922
+ dryRun: external_exports.boolean().default(false).describe("Read and check only; write nothing")
1923
+ }),
1924
+ output: workingCopy.extend({
1925
+ programId: external_exports.string().nullable().describe("Null only for a dry run that would create one"),
1926
+ outcome: external_exports.enum(["created", "updated", "unchanged", "conflict", "invalid"]),
1927
+ items: external_exports.number(),
1928
+ unread: external_exports.array(external_exports.object({ line: external_exports.number(), text: external_exports.string(), reason: external_exports.string() })),
1929
+ faults: external_exports.array(external_exports.object({ path: external_exports.string(), message: external_exports.string() })).describe("Where the layout breaks the schema (a dry run's check; a write is refused)")
1930
+ }),
1931
+ risk: "write",
1932
+ async handler(input, ctx) {
1933
+ const bank = await bankOf(ctx);
1934
+ const read = readProgramText(input.text, bank);
1935
+ const title = input.title ?? read.title ?? "Imported program";
1936
+ const values = {
1937
+ title,
1938
+ kind: input.kind ?? read.kind ?? "class",
1939
+ // Null when the text has none, so an update clears what an earlier text said.
1940
+ guidance: read.guidance,
1941
+ layout: read.layout
1942
+ };
1943
+ const sessions = read.layout.weeks.flatMap((w) => w.sessions);
1944
+ const summary = {
1945
+ title,
1946
+ weeks: read.layout.weeks.length,
1947
+ sessions: sessions.length,
1948
+ items: sessions.reduce((n, s) => n + s.blocks.reduce((m, b) => m + b.items.length, 0), 0),
1949
+ published: false,
1950
+ unread: read.unread
1951
+ };
1952
+ const checked = validateDocument(LAYOUT_SCHEMA, read.layout);
1953
+ const faults = checked.ok ? [] : checked.issues.map((i) => ({ path: ["layout", ...i.path].join("."), message: i.message }));
1954
+ const hash = importedHashOf(values);
1955
+ const existing = input.key ? (await ctx.ops.call("record.list", {
1956
+ object: PROGRAM,
1957
+ filter: { field: "importKey", op: "eq", value: input.key },
1958
+ limit: 1
1959
+ })).items[0] : void 0;
1960
+ const edited = existing !== void 0 && importedHashOf(existing.values) !== text(existing.values.importedHash);
1961
+ const outcome = existing ? edited ? "conflict" : hash === text(existing.values.importedHash) ? "unchanged" : "updated" : "created";
1962
+ const answer = (programId, said) => ({
1963
+ ...summary,
1964
+ programId,
1965
+ outcome: said,
1966
+ faults
1967
+ });
1968
+ if (input.dryRun) return answer(existing?.id ?? null, faults.length ? "invalid" : outcome);
1969
+ if (existing && outcome !== "updated") return answer(existing.id, outcome);
1970
+ const imported = input.key ? { importKey: input.key, importedHash: hash } : {};
1971
+ if (existing) {
1972
+ await ctx.ops.call("record.update", {
1973
+ object: PROGRAM,
1974
+ id: existing.id,
1975
+ values: { ...values, importedHash: hash }
1976
+ });
1977
+ return answer(existing.id, "updated");
1978
+ }
1979
+ const created = await ctx.ops.call("record.create", {
1980
+ object: PROGRAM,
1981
+ values: { ...values, ...imported }
1982
+ });
1983
+ return answer(created.id, "created");
1984
+ }
1985
+ });
1986
+
1987
+ // ../../packs/programs/index.ts
1988
+ var source = {
1989
+ type: "select",
1990
+ label: "Where it came from",
1991
+ description: "Imported: brought in from before the platform; it started nothing when it was.",
1992
+ options: [{ value: "import", label: "Imported" }]
1993
+ };
1994
+ var kind = {
1995
+ type: "select",
1996
+ label: "For",
1997
+ readOnly: true,
1998
+ description: "A person's own, or a class type's (read by every signed-in member).",
1999
+ options: [
2000
+ { value: "personal", label: "A person" },
2001
+ { value: "class", label: "A class type" }
2002
+ ]
2003
+ };
2004
+ var programs_default = defineExtension({
2005
+ id: "programs",
2006
+ version: "0.1.0",
2007
+ contractVersion: 1,
2008
+ label: "Programs",
2009
+ description: "An exercise bank, programs built from it as one layout (weeks, sessions, blocks, items, levels, typed sets), published versions, assignments to a person or a class type as dated sessions, and a log of every set against its target.",
2010
+ permissions: {
2011
+ // person.get: the name an assignment is titled with.
2012
+ read: ["person"],
2013
+ modules: ["ops", "ai"]
2014
+ },
2015
+ objects: {
2016
+ exercise: {
2017
+ label: "Exercise",
2018
+ plural: "Exercises",
2019
+ icon: "dumbbell",
2020
+ titleField: "name",
2021
+ description: "One exercise of the bank every program is built from.",
2022
+ navigation: "main",
2023
+ navigationOrder: 20,
2024
+ fields: {
2025
+ name: { type: "text", label: "Name", required: true },
2026
+ video: { type: "url", label: "Demo video" },
2027
+ cues: { type: "longText", label: "Coaching cues" },
2028
+ theme: {
2029
+ type: "select",
2030
+ label: "Theme",
2031
+ editableOptions: true,
2032
+ options: [
2033
+ { value: "mobility", label: "Mobility" },
2034
+ { value: "strength", label: "Strength" },
2035
+ { value: "handstands", label: "Handstands" },
2036
+ { value: "skill", label: "Skill" },
2037
+ { value: "conditioning", label: "Conditioning" }
2038
+ ]
2039
+ },
2040
+ level: {
2041
+ type: "select",
2042
+ label: "Level",
2043
+ options: [
2044
+ { value: "beginner", label: "Beginner" },
2045
+ { value: "intermediate", label: "Intermediate" },
2046
+ { value: "advanced", label: "Advanced" }
2047
+ ]
2048
+ },
2049
+ equipment: {
2050
+ type: "multiSelect",
2051
+ label: "Equipment",
2052
+ editableOptions: true,
2053
+ options: [
2054
+ { value: "none", label: "None" },
2055
+ { value: "rings", label: "Rings" },
2056
+ { value: "bar", label: "Bar" },
2057
+ { value: "parallettes", label: "Parallettes" },
2058
+ { value: "kettlebell", label: "Kettlebell" },
2059
+ { value: "dumbbell", label: "Dumbbell" },
2060
+ { value: "barbell", label: "Barbell" },
2061
+ { value: "band", label: "Band" },
2062
+ { value: "box", label: "Box" }
2063
+ ]
2064
+ },
2065
+ bodyAreas: {
2066
+ type: "multiSelect",
2067
+ label: "Body areas",
2068
+ editableOptions: true,
2069
+ options: [
2070
+ { value: "shoulders", label: "Shoulders" },
2071
+ { value: "wrists", label: "Wrists" },
2072
+ { value: "spine", label: "Spine" },
2073
+ { value: "hips", label: "Hips" },
2074
+ { value: "legs", label: "Legs" },
2075
+ { value: "core", label: "Core" },
2076
+ { value: "upper", label: "Upper body" }
2077
+ ]
2078
+ },
2079
+ measure: {
2080
+ type: "select",
2081
+ label: "Measured by",
2082
+ required: true,
2083
+ default: "reps",
2084
+ description: "What one set of it records.",
2085
+ options: [
2086
+ { value: "weight_reps", label: "Weight and reps" },
2087
+ { value: "reps", label: "Reps" },
2088
+ { value: "time", label: "Time" },
2089
+ { value: "hold", label: "Hold" }
2090
+ ]
2091
+ },
2092
+ easier: {
2093
+ type: "relation",
2094
+ label: "Easier versions",
2095
+ to: "programs.exercise",
2096
+ many: true
2097
+ },
2098
+ harder: {
2099
+ type: "relation",
2100
+ label: "Harder versions",
2101
+ to: "programs.exercise",
2102
+ many: true
2103
+ }
2104
+ },
2105
+ // Every signed-in member reads the bank a program of theirs is built from.
2106
+ signedIn: {
2107
+ read: [
2108
+ "name",
2109
+ "video",
2110
+ "cues",
2111
+ "theme",
2112
+ "level",
2113
+ "equipment",
2114
+ "bodyAreas",
2115
+ "measure",
2116
+ "easier",
2117
+ "harder"
2118
+ ]
2119
+ },
2120
+ indexes: [["theme"], ["measure"]]
2121
+ },
2122
+ program: {
2123
+ label: "Program",
2124
+ plural: "Programs",
2125
+ icon: "clipboard-list",
2126
+ titleField: "title",
2127
+ description: "A plan of weeks of sessions, built from the bank: a class program, a client's own, or the sessions of an online course. Coaches edit the working copy; people are given a published version.",
2128
+ navigation: "main",
2129
+ navigationOrder: 21,
2130
+ fields: {
2131
+ title: { type: "text", label: "Title", required: true },
2132
+ kind: {
2133
+ type: "select",
2134
+ label: "Kind",
2135
+ required: true,
2136
+ default: "client",
2137
+ options: [
2138
+ { value: "class", label: "Class" },
2139
+ { value: "client", label: "Client" },
2140
+ { value: "course", label: "Course" }
2141
+ ]
2142
+ },
2143
+ theme: { type: "text", label: "Theme" },
2144
+ guidance: {
2145
+ type: "longText",
2146
+ label: "Guidance for coaches",
2147
+ description: "For whoever runs it. Never shown to members."
2148
+ },
2149
+ layout: {
2150
+ type: "document",
2151
+ label: "Layout",
2152
+ required: true,
2153
+ description: "Weeks of sessions of blocks of items, each item bank exercises with typed sets, or up to five levels; notes for coaches unless marked as shown to members.",
2154
+ schema: LAYOUT_SCHEMA,
2155
+ maxBytes: 524288,
2156
+ paths: { weekCount: { label: "Weeks", path: "weeks", count: true } }
2157
+ },
2158
+ importKey: {
2159
+ type: "text",
2160
+ label: "Import key",
2161
+ readOnly: true,
2162
+ description: "The name its text had where it came from: one program per key."
2163
+ },
2164
+ importedHash: {
2165
+ type: "text",
2166
+ label: "Imported content",
2167
+ readOnly: true,
2168
+ description: "What the text import last wrote, so a re-run never overwrites an edit."
2169
+ }
2170
+ },
2171
+ publishable: { content: ["title", "kind", "theme", "guidance", "layout"] },
2172
+ // `x.programs.importText` with a key: one live program per key, however many run at once.
2173
+ unique: [{ fields: ["importKey"] }],
2174
+ indexes: [["kind"]]
2175
+ },
2176
+ classtype: {
2177
+ label: "Class type",
2178
+ plural: "Class types",
2179
+ icon: "users",
2180
+ titleField: "name",
2181
+ description: "A kind of class (Mobility, Handstands): what a class program is assigned to.",
2182
+ navigation: "settings",
2183
+ fields: {
2184
+ name: { type: "text", label: "Name", required: true },
2185
+ order: { type: "number", label: "Order" }
2186
+ },
2187
+ signedIn: { read: ["name", "order"] }
2188
+ },
2189
+ assignment: {
2190
+ label: "Assignment",
2191
+ plural: "Assignments",
2192
+ icon: "calendar-range",
2193
+ titleField: "title",
2194
+ description: "A published version of a program given to a person or to a class type from a start date: its dated sessions are made from that version and keep it.",
2195
+ navigation: "main",
2196
+ navigationOrder: 22,
2197
+ fields: {
2198
+ title: { type: "text", label: "Title", required: true },
2199
+ program: { type: "relation", label: "Program", to: "programs.program", required: true },
2200
+ programVersion: {
2201
+ type: "number",
2202
+ label: "Version",
2203
+ readOnly: true,
2204
+ description: "The program's published version this follows."
2205
+ },
2206
+ kind,
2207
+ person: { type: "relation", label: "Person", to: "person" },
2208
+ classType: { type: "relation", label: "Class type", to: "programs.classtype" },
2209
+ startDate: { type: "date", label: "Starts", required: true },
2210
+ endDate: { type: "date", label: "Ends" },
2211
+ sessionCount: { type: "number", label: "Sessions", readOnly: true, min: 0, step: 1 },
2212
+ state: {
2213
+ type: "select",
2214
+ label: "State",
2215
+ track: "timeline",
2216
+ options: [
2217
+ { value: "generating", label: "Making sessions" },
2218
+ { value: "active", label: "Active" },
2219
+ { value: "ended", label: "Ended" },
2220
+ { value: "cancelled", label: "Cancelled" }
2221
+ ]
2222
+ },
2223
+ assignedBy: { type: "user", label: "Assigned by" },
2224
+ assignedByName: { type: "text", label: "Assigned by (name)" },
2225
+ coach: {
2226
+ type: "user",
2227
+ label: "Coach",
2228
+ description: "Who looks after this client on it. With the coach role, they see and log this person's training while it is active, and no one else's. A person chooses it: anyone else's change waits for a person.",
2229
+ // Who reaches whose training is access (ADR 0889): a person's to set.
2230
+ personApproves: true
2231
+ }
2232
+ },
2233
+ requireOneOf: [["person", "classType"]],
2234
+ // Who looks after whom (ADR 0831): a client's coach while their program is live. What the
2235
+ // coach role reaches through it is the host's (`roles.coach.looksAfter`, ADR 0889).
2236
+ team: { person: "person", staff: ["coach"], live: ["generating", "active"] },
2237
+ states: {
2238
+ field: "state",
2239
+ initial: "generating",
2240
+ moves: [
2241
+ { from: "generating", to: "active", by: ["staff"] },
2242
+ { from: "active", to: "ended", by: ["staff"], final: true },
2243
+ { from: ["generating", "active"], to: "cancelled", by: ["staff"], final: true }
2244
+ ]
2245
+ },
2246
+ customer: {
2247
+ field: "person",
2248
+ read: ["title", "programVersion", "kind", "classType", "startDate", "endDate", "state"],
2249
+ write: []
2250
+ },
2251
+ signedIn: {
2252
+ read: ["title", "programVersion", "kind", "classType", "startDate", "endDate", "state"],
2253
+ when: { field: "kind", in: ["class"] }
2254
+ },
2255
+ timelineLinks: ["person"],
2256
+ // A member reads their own (person) or the shared (kind): one index for each side of the OR.
2257
+ // The coach's People are read on every call of the coach role: one index for it.
2258
+ indexes: [
2259
+ ["person", "state"],
2260
+ ["kind", "state"],
2261
+ ["classType", "state"],
2262
+ ["program"],
2263
+ ["coach", "state"]
2264
+ ]
2265
+ },
2266
+ session: {
2267
+ label: "Session",
2268
+ plural: "Sessions",
2269
+ icon: "calendar-check",
2270
+ titleField: "name",
2271
+ description: "One dated session of an assignment: its plan as the assigned version had it, and whether it was done. Or one done before the platform, brought in by an import.",
2272
+ navigation: "none",
2273
+ fields: {
2274
+ name: { type: "text", label: "Name", required: true },
2275
+ assignment: {
2276
+ type: "relation",
2277
+ label: "Assignment",
2278
+ to: "programs.assignment",
2279
+ description: "Every session but an imported one is an assignment's."
2280
+ },
2281
+ program: { type: "relation", label: "Program", to: "programs.program" },
2282
+ programVersion: { type: "number", label: "Version", readOnly: true },
2283
+ kind,
2284
+ person: { type: "relation", label: "Person", to: "person" },
2285
+ classType: { type: "relation", label: "Class type", to: "programs.classtype" },
2286
+ programTitle: {
2287
+ type: "text",
2288
+ label: "Program",
2289
+ readOnly: true,
2290
+ description: "The program's title in the assigned version, so a member reads it with the session."
2291
+ },
2292
+ classTypeName: { type: "text", label: "Class type (name)", readOnly: true },
2293
+ date: { type: "date", label: "Date", required: true },
2294
+ week: { type: "number", label: "Week", readOnly: true, min: 1, max: 52, step: 1 },
2295
+ day: { type: "number", label: "Day of the week", readOnly: true, min: 1, max: 7, step: 1 },
2296
+ position: {
2297
+ type: "number",
2298
+ label: "Place in its week",
2299
+ readOnly: true,
2300
+ description: "The session's index in its week of the layout, from 0."
2301
+ },
2302
+ key: {
2303
+ type: "text",
2304
+ label: "Key",
2305
+ readOnly: true,
2306
+ description: "Assignment, week and place: one session per place."
2307
+ },
2308
+ focus: { type: "text", label: "Focus" },
2309
+ plan: {
2310
+ type: "document",
2311
+ label: "Plan",
2312
+ readOnly: true,
2313
+ description: "The session of the layout, as the assigned version had it.",
2314
+ schema: SESSION_PLAN_SCHEMA,
2315
+ maxBytes: 65536
2316
+ },
2317
+ state: {
2318
+ type: "select",
2319
+ label: "State",
2320
+ options: [
2321
+ { value: "planned", label: "Planned" },
2322
+ { value: "done", label: "Done" },
2323
+ { value: "skipped", label: "Skipped" }
2324
+ ]
2325
+ },
2326
+ completedAt: { type: "datetime", label: "Marked at" },
2327
+ completedBy: { type: "user", label: "Marked by" },
2328
+ completedByName: { type: "text", label: "Marked by (name)" },
2329
+ source,
2330
+ // Done before the platform: only staff move it back (a member reopening it is not theirs).
2331
+ imported: {
2332
+ type: "formula",
2333
+ label: "Imported",
2334
+ expression: 'coalesce(source, "") = "import"'
2335
+ }
2336
+ },
2337
+ // An assignment's, or brought in from before (`source: import`).
2338
+ requireOneOf: [["assignment", "source"]],
2339
+ states: {
2340
+ field: "state",
2341
+ initial: "planned",
2342
+ moves: [
2343
+ { from: "planned", to: "done", by: ["staff", "customer"] },
2344
+ { from: "planned", to: "skipped", by: ["staff", "customer"] },
2345
+ {
2346
+ from: ["done", "skipped"],
2347
+ to: "planned",
2348
+ by: ["staff", "customer"],
2349
+ staffOnly: "imported"
2350
+ }
2351
+ ]
2352
+ },
2353
+ customer: {
2354
+ field: "person",
2355
+ read: [
2356
+ "name",
2357
+ "assignment",
2358
+ // Stage 42: which program it is, so a course's session lesson finds the student's own.
2359
+ "program",
2360
+ "programVersion",
2361
+ "kind",
2362
+ "classType",
2363
+ "programTitle",
2364
+ "classTypeName",
2365
+ "date",
2366
+ "week",
2367
+ "day",
2368
+ "position",
2369
+ "focus",
2370
+ "plan",
2371
+ "state",
2372
+ "completedAt",
2373
+ "source"
2374
+ ],
2375
+ write: []
2376
+ },
2377
+ // A class type's sessions are read by every signed-in member; marking one done is not theirs.
2378
+ signedIn: {
2379
+ read: [
2380
+ "name",
2381
+ "assignment",
2382
+ "programVersion",
2383
+ "kind",
2384
+ "classType",
2385
+ "programTitle",
2386
+ "classTypeName",
2387
+ "date",
2388
+ "week",
2389
+ "day",
2390
+ "position",
2391
+ "focus",
2392
+ "plan"
2393
+ ],
2394
+ when: { field: "kind", in: ["class"] }
2395
+ },
2396
+ indexes: [
2397
+ ["person", "date"],
2398
+ ["kind", "date"],
2399
+ ["classType", "date"],
2400
+ ["assignment", "week"],
2401
+ ["key"]
2402
+ ]
2403
+ },
2404
+ log: {
2405
+ label: "Logged set",
2406
+ plural: "Logged sets",
2407
+ icon: "list-checks",
2408
+ titleField: "label",
2409
+ description: "One set someone did: the exercise, the target and what was done, how hard it felt, the level taken, and who recorded it. The table training data comes from.",
2410
+ navigation: "main",
2411
+ navigationOrder: 23,
2412
+ fields: {
2413
+ label: { type: "text", label: "Set", required: true },
2414
+ person: { type: "relation", label: "Person", to: "person", required: true },
2415
+ session: { type: "relation", label: "Session", to: "programs.session", required: true },
2416
+ assignment: { type: "relation", label: "Assignment", to: "programs.assignment" },
2417
+ exercise: { type: "relation", label: "Exercise", to: "programs.exercise", required: true },
2418
+ exerciseName: {
2419
+ type: "text",
2420
+ label: "Exercise (name)",
2421
+ description: "The exercise's name when the set was logged, so a member reads it with the set."
2422
+ },
2423
+ item: { type: "text", label: "Item", description: "The item's label: A1." },
2424
+ setNumber: { type: "number", label: "Set number", min: 1, max: 30, step: 1 },
2425
+ level: { type: "number", label: "Level taken", min: 1, max: 5, step: 1 },
2426
+ date: { type: "date", label: "Date", required: true },
2427
+ targetReps: { type: "number", label: "Target reps", min: 0, max: 999, step: 1 },
2428
+ targetSeconds: { type: "number", label: "Target seconds", min: 0, max: 7200, step: 1 },
2429
+ targetLoad: { type: "number", label: "Target load (kg)", min: 0, max: 1e3, step: 0.25 },
2430
+ actualReps: { type: "number", label: "Reps", min: 0, max: 999, step: 1 },
2431
+ actualSeconds: { type: "number", label: "Seconds", min: 0, max: 7200, step: 1 },
2432
+ actualLoad: { type: "number", label: "Load (kg)", min: 0, max: 1e3, step: 0.25 },
2433
+ rpe: {
2434
+ type: "number",
2435
+ label: "Effort (RPE)",
2436
+ description: "1 to 10, in halves.",
2437
+ min: 1,
2438
+ max: 10,
2439
+ step: 0.5
2440
+ },
2441
+ note: { type: "text", label: "Note" },
2442
+ recordedAs: {
2443
+ type: "select",
2444
+ label: "Recorded by",
2445
+ options: [
2446
+ { value: "self", label: "Themselves" },
2447
+ { value: "staff", label: "A coach" }
2448
+ ]
2449
+ },
2450
+ recordedBy: { type: "user", label: "Recorded by (coach)" },
2451
+ recordedByName: { type: "text", label: "Recorded by (name)" },
2452
+ setKey: {
2453
+ type: "text",
2454
+ label: "Set key",
2455
+ description: "Session, item, exercise and set number: one row per set and person, however many saves of it arrive."
2456
+ },
2457
+ source
2458
+ },
2459
+ // One row per set and person (ADR 0448, amended 2026-11-24): a retried save, or two at once,
2460
+ // changes the set instead of logging it twice. Rows logged before the key have none and are
2461
+ // not counted; `x.programs.logAdd` finds those by their fields.
2462
+ unique: [{ fields: ["person", "setKey"] }],
2463
+ customer: {
2464
+ field: "person",
2465
+ read: [
2466
+ "label",
2467
+ "session",
2468
+ "assignment",
2469
+ "exercise",
2470
+ "exerciseName",
2471
+ "item",
2472
+ "setNumber",
2473
+ "level",
2474
+ "date",
2475
+ "targetReps",
2476
+ "targetSeconds",
2477
+ "targetLoad",
2478
+ "actualReps",
2479
+ "actualSeconds",
2480
+ "actualLoad",
2481
+ "rpe",
2482
+ "note",
2483
+ "recordedAs",
2484
+ "recordedByName",
2485
+ "source"
2486
+ ],
2487
+ write: ["actualReps", "actualSeconds", "actualLoad", "rpe", "note"],
2488
+ // A set ticked by mistake is taken back (`x.programs.logRemove`): to the Trash.
2489
+ delete: true
2490
+ },
2491
+ timelineLinks: ["person"],
2492
+ indexes: [
2493
+ ["person", "exercise", "date"],
2494
+ ["session"],
2495
+ ["exercise", "date"],
2496
+ ["person", "date"]
2497
+ ]
2498
+ }
2499
+ },
2500
+ views: {
2501
+ bankByTheme: {
2502
+ label: "Bank by theme",
2503
+ object: "programs.exercise",
2504
+ type: "board",
2505
+ groupBy: "theme",
2506
+ cardFields: ["measure", "level", "equipment"]
2507
+ },
2508
+ programsPublished: {
2509
+ label: "Published programs",
2510
+ object: "programs.program",
2511
+ filter: { field: "publishedVersion", op: "is_not_null" },
2512
+ sort: { field: "publishedAt", direction: "desc" },
2513
+ columns: ["title", "kind", "weekCount", "publishedVersion", "publishedAt"]
2514
+ },
2515
+ activeAssignments: {
2516
+ label: "Active assignments",
2517
+ object: "programs.assignment",
2518
+ filter: { field: "state", op: "eq", value: "active" },
2519
+ sort: { field: "startDate", direction: "desc" },
2520
+ columns: ["title", "kind", "person", "classType", "startDate", "endDate", "sessionCount"]
2521
+ },
2522
+ sessionsThisWeek: {
2523
+ label: "Sessions this week",
2524
+ object: "programs.session",
2525
+ filter: {
2526
+ and: [
2527
+ { field: "date", op: "gte", value: { $relative: "startOfWeek" } },
2528
+ { field: "date", op: "lt", value: { $relative: "startOfNextWeek" } }
2529
+ ]
2530
+ },
2531
+ sort: { field: "date", direction: "asc" },
2532
+ columns: ["name", "date", "kind", "person", "classType", "state"]
2533
+ },
2534
+ sessionsCalendar: {
2535
+ label: "Sessions calendar",
2536
+ object: "programs.session",
2537
+ type: "calendar",
2538
+ dateField: "date",
2539
+ mode: "week",
2540
+ cardFields: ["person", "classType", "state"]
2541
+ },
2542
+ setsThisWeek: {
2543
+ label: "Sets logged this week",
2544
+ object: "programs.log",
2545
+ filter: {
2546
+ and: [
2547
+ { field: "date", op: "gte", value: { $relative: "startOfWeek" } },
2548
+ { field: "date", op: "lt", value: { $relative: "startOfNextWeek" } }
2549
+ ]
2550
+ },
2551
+ sort: { field: "date", direction: "desc" },
2552
+ columns: [
2553
+ "person",
2554
+ "exercise",
2555
+ "label",
2556
+ "level",
2557
+ "targetReps",
2558
+ "actualReps",
2559
+ "targetLoad",
2560
+ "actualLoad",
2561
+ "actualSeconds",
2562
+ "rpe",
2563
+ "recordedAs"
2564
+ ]
2565
+ }
2566
+ },
2567
+ dashboards: programsDashboards,
2568
+ // A client's Person page: their sets (the Training tab), their assignments and their sessions.
2569
+ recordTabs: {
2570
+ personTraining: {
2571
+ label: "Training",
2572
+ on: "person",
2573
+ view: {
2574
+ type: "table",
2575
+ object: "programs.log",
2576
+ relation: "person",
2577
+ columns: [
2578
+ "date",
2579
+ "exercise",
2580
+ "label",
2581
+ "level",
2582
+ "targetReps",
2583
+ "actualReps",
2584
+ "targetLoad",
2585
+ "actualLoad",
2586
+ "actualSeconds",
2587
+ "rpe",
2588
+ "recordedAs"
2589
+ ],
2590
+ sort: { field: "date", direction: "desc" }
2591
+ },
2592
+ order: 40
2593
+ }
2594
+ },
2595
+ recordPanels: {
2596
+ personAssignments: {
2597
+ label: "Programs",
2598
+ on: "person",
2599
+ view: {
2600
+ type: "table",
2601
+ object: "programs.assignment",
2602
+ relation: "person",
2603
+ columns: ["title", "startDate", "endDate", "state"],
2604
+ sort: { field: "startDate", direction: "desc" }
2605
+ },
2606
+ order: 40
2607
+ },
2608
+ personSessions: {
2609
+ label: "Sessions",
2610
+ on: "person",
2611
+ view: {
2612
+ type: "table",
2613
+ object: "programs.session",
2614
+ relation: "person",
2615
+ columns: ["name", "date", "state"],
2616
+ sort: { field: "date", direction: "desc" }
2617
+ },
2618
+ order: 41
2619
+ }
2620
+ },
2621
+ // The coach role (ADR 0889): a coach's own clients, in the app: their sessions and sets, logging
2622
+ // and marking for them, their history and progress. Only the People an active assignment names
2623
+ // them coach of; nothing else: no class sessions, no programs or the builder, no assigning, no
2624
+ // people, no settings.
2625
+ roles: {
2626
+ coach: {
2627
+ label: "Coach",
2628
+ description: "Sees the clients they coach (an active program naming them their coach): their sessions, sets, history and progress, and logs sets and marks sessions for them. Nothing else: no other clients, no class sessions, no programs, no assigning, no people.",
2629
+ permissions: ["programs:coach"],
2630
+ read: ["programs.assignment", "programs.session"],
2631
+ looksAfter: {
2632
+ "programs.assignment": "person",
2633
+ "programs.session": "person",
2634
+ "programs.log": "person"
2635
+ }
2636
+ }
2637
+ },
2638
+ tools: {
2639
+ assign,
2640
+ today,
2641
+ sessionGet,
2642
+ classToday,
2643
+ logAdd,
2644
+ logRemove,
2645
+ logUpdate,
2646
+ sessionComplete,
2647
+ history,
2648
+ progress,
2649
+ draft,
2650
+ importText
2651
+ },
2652
+ // Staff screens in the product's admin (stage 47, ADR 0660), each gated by what it writes or
2653
+ // calls: the bank its exercises and the builder its programs (core record writes: any member,
2654
+ // never a viewer or a pack role), the builder's import too; the client view, a tab on Person, by
2655
+ // logging and completing a client's sessions (`programs:coach`, which the coach role holds too,
2656
+ // ADR 0889; the role never opens a Person's page).
2657
+ screens: {
2658
+ bank: {
2659
+ label: "Exercise bank",
2660
+ block: "programs-bank",
2661
+ export: "ExerciseBank",
2662
+ nav: { group: "Programs", order: 10 },
2663
+ writes: ["programs.exercise"]
2664
+ },
2665
+ builder: {
2666
+ label: "Program builder",
2667
+ block: "programs-builder",
2668
+ export: "ProgramWorkspace",
2669
+ nav: { group: "Programs", order: 20 },
2670
+ opens: ["importText"],
2671
+ writes: ["programs.program"]
2672
+ },
2673
+ client: {
2674
+ label: "Programs",
2675
+ block: "programs-coach-client",
2676
+ export: "CoachClient",
2677
+ opens: ["logAdd", "logRemove", "sessionComplete"],
2678
+ record: { object: "person", as: "personId" }
2679
+ }
2680
+ },
2681
+ // Its section of My account (stage 48, ADR 0710): a member's progress, shown once they have a
2682
+ // program or a logged set.
2683
+ portal: {
2684
+ training: {
2685
+ label: "Training",
2686
+ web: { block: "programs-progress", export: "Progress" },
2687
+ native: { block: "programs-native-progress", export: "ProgressScreen" },
2688
+ order: 50,
2689
+ has: ["programs.assignment", "programs.log"]
2690
+ }
2691
+ }
2692
+ });
2693
+
2694
+ // src/programs-import/format.ts
2695
+ var EXERCISE2 = "programs.exercise";
2696
+ var CLASSTYPE = "programs.classtype";
2697
+ var PROGRAM2 = "programs.program";
2698
+ var SESSION3 = "programs.session";
2699
+ var LOG2 = "programs.log";
2700
+ var MEASURES = ["weight_reps", "reps", "time", "hold"];
2701
+ var SESSION_NAME_MAX = 100;
2702
+ function table(text2, name, problems) {
2703
+ const rows = parseCsv(text2.replace(/^/, ""));
2704
+ const header = rows[0];
2705
+ if (!header) {
2706
+ problems.push({ file: name, message: "the file is empty" });
2707
+ return null;
2708
+ }
2709
+ const names = header.cells.map(
2710
+ (c) => c.trim().toLowerCase().replace(/[\s-]+/g, "_")
2711
+ );
2712
+ const column = (...options) => names.findIndex((n) => options.includes(n));
2713
+ return { header, names, column, rows: rows.slice(1) };
2714
+ }
2715
+ var listOf = (cell) => cell.split(";").map((c) => c.trim()).filter(Boolean);
2716
+ var numberOf = (cell) => cell.trim() === "" ? void 0 : Number(cell.trim());
2717
+ var today2 = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2718
+ function readProgramsFolder(folder) {
2719
+ const problems = [];
2720
+ const plan = {
2721
+ exercises: [],
2722
+ classTypes: [],
2723
+ programs: [],
2724
+ training: [],
2725
+ problems
2726
+ };
2727
+ if (folder.exercises !== null) {
2728
+ const name = "exercises.csv";
2729
+ const t = table(folder.exercises, name, problems);
2730
+ if (t) {
2731
+ const col = {
2732
+ key: t.column("key", "id"),
2733
+ name: t.column("name"),
2734
+ measure: t.column("measure", "measured_by"),
2735
+ video: t.column("video", "demo_video"),
2736
+ cues: t.column("cues", "coaching_cues"),
2737
+ theme: t.column("theme"),
2738
+ level: t.column("level"),
2739
+ equipment: t.column("equipment"),
2740
+ bodyAreas: t.column("body_areas", "bodyareas"),
2741
+ easier: t.column("easier"),
2742
+ harder: t.column("harder")
2743
+ };
2744
+ if (col.name < 0) {
2745
+ problems.push({ file: `${name}:${t.header.line}`, message: "the header must name name" });
2746
+ } else {
2747
+ const seen = /* @__PURE__ */ new Set();
2748
+ for (const { line, cells } of t.rows) {
2749
+ const cell = (i) => i >= 0 ? (cells[i] ?? "").trim() : "";
2750
+ const at = `${name}:${line}`;
2751
+ const exerciseName = cell(col.name);
2752
+ const key = cell(col.key) || exerciseName;
2753
+ if (!exerciseName) {
2754
+ problems.push({ file: at, message: "no name" });
2755
+ continue;
2756
+ }
2757
+ if (seen.has(key)) {
2758
+ problems.push({ file: at, message: `the key "${key}" is there twice` });
2759
+ continue;
2760
+ }
2761
+ seen.add(key);
2762
+ const measure = cell(col.measure) || "reps";
2763
+ if (!MEASURES.includes(measure)) {
2764
+ problems.push({
2765
+ file: at,
2766
+ message: `measure is ${MEASURES.join(", ")}, not "${measure}"`
2767
+ });
2768
+ continue;
2769
+ }
2770
+ const values = { name: exerciseName, measure };
2771
+ const put = (field, value) => {
2772
+ if (value !== "" && !(Array.isArray(value) && !value.length)) values[field] = value;
2773
+ };
2774
+ put("video", cell(col.video));
2775
+ put("cues", cell(col.cues));
2776
+ put("theme", cell(col.theme));
2777
+ put("level", cell(col.level));
2778
+ put("equipment", listOf(cell(col.equipment)));
2779
+ put("bodyAreas", listOf(cell(col.bodyAreas)));
2780
+ plan.exercises.push({
2781
+ key,
2782
+ file: at,
2783
+ name: exerciseName,
2784
+ values,
2785
+ easier: listOf(cell(col.easier)),
2786
+ harder: listOf(cell(col.harder))
2787
+ });
2788
+ }
2789
+ for (const e of plan.exercises) {
2790
+ for (const other of [...e.easier, ...e.harder]) {
2791
+ if (other === e.key) {
2792
+ problems.push({
2793
+ file: e.file,
2794
+ message: "an exercise is not its own easier or harder version"
2795
+ });
2796
+ } else if (!seen.has(other)) {
2797
+ problems.push({
2798
+ file: e.file,
2799
+ message: `no row of exercises.csv has the key "${other}"`
2800
+ });
2801
+ }
2802
+ }
2803
+ }
2804
+ }
2805
+ }
2806
+ }
2807
+ if (folder.classTypes !== null) {
2808
+ const name = "classtypes.csv";
2809
+ const t = table(folder.classTypes, name, problems);
2810
+ if (t) {
2811
+ const col = { key: t.column("key", "id"), name: t.column("name"), order: t.column("order") };
2812
+ if (col.name < 0) {
2813
+ problems.push({ file: `${name}:${t.header.line}`, message: "the header must name name" });
2814
+ } else {
2815
+ const seen = /* @__PURE__ */ new Set();
2816
+ for (const { line, cells } of t.rows) {
2817
+ const cell = (i) => i >= 0 ? (cells[i] ?? "").trim() : "";
2818
+ const at = `${name}:${line}`;
2819
+ const typeName = cell(col.name);
2820
+ const key = cell(col.key) || typeName;
2821
+ if (!typeName) {
2822
+ problems.push({ file: at, message: "no name" });
2823
+ continue;
2824
+ }
2825
+ if (seen.has(key)) {
2826
+ problems.push({ file: at, message: `the key "${key}" is there twice` });
2827
+ continue;
2828
+ }
2829
+ seen.add(key);
2830
+ const order = numberOf(cell(col.order));
2831
+ if (order !== void 0 && !Number.isFinite(order)) {
2832
+ problems.push({ file: at, message: `the order is not a number: "${cell(col.order)}"` });
2833
+ continue;
2834
+ }
2835
+ plan.classTypes.push({
2836
+ key,
2837
+ file: at,
2838
+ values: { name: typeName, ...order !== void 0 ? { order } : {} }
2839
+ });
2840
+ }
2841
+ }
2842
+ }
2843
+ }
2844
+ for (const [file, text2] of [...folder.programs].sort(([a], [b]) => a.localeCompare(b))) {
2845
+ if (!/\.txt$/i.test(file)) {
2846
+ problems.push({ file: `programs/${file}`, message: "a program is a .txt file of shorthand" });
2847
+ continue;
2848
+ }
2849
+ if (!text2.trim()) {
2850
+ problems.push({ file: `programs/${file}`, message: "the file is empty" });
2851
+ continue;
2852
+ }
2853
+ plan.programs.push({ key: file.replace(/\.txt$/i, ""), file: `programs/${file}`, text: text2 });
2854
+ }
2855
+ if (folder.training !== null) {
2856
+ const name = "training.csv";
2857
+ const t = table(folder.training, name, problems);
2858
+ if (t) {
2859
+ const col = {
2860
+ email: t.column("email"),
2861
+ date: t.column("date"),
2862
+ session: t.column("session", "session_name"),
2863
+ exercise: t.column("exercise"),
2864
+ set: t.column("set", "set_number"),
2865
+ reps: t.column("reps", "actual_reps"),
2866
+ seconds: t.column("seconds", "actual_seconds"),
2867
+ load: t.column("load", "actual_load", "kg"),
2868
+ rpe: t.column("rpe", "effort"),
2869
+ note: t.column("note"),
2870
+ item: t.column("item"),
2871
+ level: t.column("level"),
2872
+ program: t.column("program"),
2873
+ targetReps: t.column("target_reps"),
2874
+ targetSeconds: t.column("target_seconds"),
2875
+ targetLoad: t.column("target_load")
2876
+ };
2877
+ const missing = ["email", "date", "exercise"].filter((c) => col[c] < 0);
2878
+ if (missing.length) {
2879
+ problems.push({
2880
+ file: `${name}:${t.header.line}`,
2881
+ message: `the header must name ${missing.join(", ")}`
2882
+ });
2883
+ } else {
2884
+ const programKeys = new Set(plan.programs.map((p) => p.key));
2885
+ for (const { line, cells } of t.rows) {
2886
+ const cell = (i) => i >= 0 ? (cells[i] ?? "").trim() : "";
2887
+ const at = `${name}:${line}`;
2888
+ const problem = (message) => problems.push({ file: at, message });
2889
+ const email = cell(col.email).toLowerCase();
2890
+ const date2 = cell(col.date);
2891
+ const session = cell(col.session) || "Training";
2892
+ const exercise = cell(col.exercise);
2893
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
2894
+ problem(`not an email address: "${cell(col.email)}"`);
2895
+ continue;
2896
+ }
2897
+ if (!realDate(date2)) {
2898
+ problem(`the date is not a real date (YYYY-MM-DD): "${date2}"`);
2899
+ continue;
2900
+ }
2901
+ if (date2 > today2()) {
2902
+ problem(`${date2} is after today: only past training is imported`);
2903
+ continue;
2904
+ }
2905
+ if (!exercise) {
2906
+ problem("no exercise");
2907
+ continue;
2908
+ }
2909
+ if (session.length > SESSION_NAME_MAX) {
2910
+ problem(`the session's name is longer than ${SESSION_NAME_MAX} characters`);
2911
+ continue;
2912
+ }
2913
+ const program = cell(col.program) || null;
2914
+ if (program && !programKeys.has(program)) {
2915
+ problem(`no file of programs/ is "${program}.txt"`);
2916
+ continue;
2917
+ }
2918
+ const numbers = {
2919
+ actualReps: numberOf(cell(col.reps)),
2920
+ actualSeconds: numberOf(cell(col.seconds)),
2921
+ actualLoad: numberOf(cell(col.load)),
2922
+ rpe: numberOf(cell(col.rpe)),
2923
+ targetReps: numberOf(cell(col.targetReps)),
2924
+ targetSeconds: numberOf(cell(col.targetSeconds)),
2925
+ targetLoad: numberOf(cell(col.targetLoad))
2926
+ };
2927
+ const level = numberOf(cell(col.level));
2928
+ const set = numberOf(cell(col.set));
2929
+ const bad = Object.entries({ ...numbers, level, set }).find(
2930
+ ([, v]) => v !== void 0 && !Number.isFinite(v)
2931
+ );
2932
+ if (bad) {
2933
+ problem(`${bad[0]} is not a number`);
2934
+ continue;
2935
+ }
2936
+ if (numbers.actualReps === void 0 && numbers.actualSeconds === void 0 && numbers.actualLoad === void 0) {
2937
+ problem("nothing done: give reps, seconds or load");
2938
+ continue;
2939
+ }
2940
+ const item = cell(col.item) || null;
2941
+ if (item && !/^[A-Za-z0-9]{1,6}$/.test(item)) {
2942
+ problem(`an item is a label such as A1, not "${item}"`);
2943
+ continue;
2944
+ }
2945
+ const setNumber = set ?? null;
2946
+ const note = cell(col.note);
2947
+ plan.training.push({
2948
+ file: at,
2949
+ email,
2950
+ date: date2,
2951
+ session,
2952
+ exercise,
2953
+ setNumber,
2954
+ item,
2955
+ level: level ?? null,
2956
+ program,
2957
+ values: Object.fromEntries(
2958
+ Object.entries({ ...numbers, ...note ? { note } : {} }).filter(
2959
+ ([, v]) => v !== void 0
2960
+ )
2961
+ )
2962
+ });
2963
+ }
2964
+ }
2965
+ }
2966
+ }
2967
+ if (!problems.length && !plan.exercises.length && !plan.classTypes.length && !plan.programs.length && !plan.training.length) {
2968
+ problems.push({
2969
+ file: "",
2970
+ message: "nothing to import: the folder has no exercises.csv, classtypes.csv, programs/ or training.csv rows"
2971
+ });
2972
+ }
2973
+ return plan;
2974
+ }
2975
+
2976
+ // src/programs-import/engine.ts
2977
+ var norm2 = (name) => name.toLowerCase().replace(/[’'"“”]/g, "").replace(/[^a-z0-9]+/g, " ").trim();
2978
+ async function hostBank(host) {
2979
+ const out = [];
2980
+ let cursor;
2981
+ do {
2982
+ const page = await host.call("record.list", {
2983
+ object: EXERCISE2,
2984
+ limit: 200,
2985
+ ...cursor ? { cursor } : {}
2986
+ });
2987
+ for (const e of page.items) {
2988
+ out.push({
2989
+ id: e.id,
2990
+ name: String(e.values.name ?? ""),
2991
+ measure: typeof e.values.measure === "string" ? e.values.measure : null
2992
+ });
2993
+ }
2994
+ cursor = page.nextCursor;
2995
+ } while (cursor);
2996
+ return out;
2997
+ }
2998
+ var Stopped = class extends Error {
2999
+ };
3000
+ var IMPORT_KEY_MAX = 200;
3001
+ var sessionKey = (person, row) => `${person}|${row.date}|${row.session}`;
3002
+ async function runProgramsImport(plan, host, options = {}) {
3003
+ const report = {
3004
+ problems: [...plan.problems],
3005
+ records: [],
3006
+ unmatched: [],
3007
+ notes: [],
3008
+ wroteNothing: true
3009
+ };
3010
+ if (report.problems.length) return report;
3011
+ const say = options.progress ?? (() => {
3012
+ });
3013
+ const bank = await hostBank(host);
3014
+ const folderExercise = new Map(plan.exercises.map((e) => [e.key, e]));
3015
+ const bankByName = /* @__PURE__ */ new Map();
3016
+ for (const e of bank) bankByName.set(norm2(e.name), [...bankByName.get(norm2(e.name)) ?? [], e]);
3017
+ const folderByName = new Map(plan.exercises.map((e) => [norm2(e.name), e.key]));
3018
+ const exerciseKeyOf = (row) => folderExercise.has(row.exercise) ? row.exercise : folderByName.get(norm2(row.exercise));
3019
+ const onHost = /* @__PURE__ */ new Map();
3020
+ for (const row of plan.training) {
3021
+ if (exerciseKeyOf(row) || onHost.has(row.exercise)) continue;
3022
+ const hits = bankByName.get(norm2(row.exercise)) ?? [];
3023
+ if (hits.length === 1) onHost.set(row.exercise, hits[0]);
3024
+ else {
3025
+ report.problems.push({
3026
+ file: row.file,
3027
+ message: hits.length ? `${hits.length} exercises on the host are called "${row.exercise}": give it a row of exercises.csv` : `"${row.exercise}" is no key of exercises.csv and no exercise on the host`
3028
+ });
3029
+ }
3030
+ }
3031
+ if (report.problems.length) return report;
3032
+ const people = /* @__PURE__ */ new Map();
3033
+ for (const email of new Set(plan.training.map((r) => r.email))) {
3034
+ people.set(email, await personFor(host, email));
3035
+ }
3036
+ const found = plan.training.flatMap((row) => {
3037
+ const who = people.get(row.email);
3038
+ if (!who || "problem" in who) {
3039
+ report.unmatched.push({ file: row.file, message: who?.problem ?? "No person" });
3040
+ return [];
3041
+ }
3042
+ return [{ row, person: who.id }];
3043
+ });
3044
+ const counted = /* @__PURE__ */ new Map();
3045
+ const seen = /* @__PURE__ */ new Map();
3046
+ const training2 = [];
3047
+ for (const { row, person } of found) {
3048
+ const folderKey = exerciseKeyOf(row);
3049
+ const exercise = folderKey ? `key:${folderKey}` : `id:${onHost.get(row.exercise)?.id}`;
3050
+ const group = [sessionKey(person, row), row.item ?? "", exercise].join("\0");
3051
+ const setNumber = row.setNumber ?? (counted.get(group) ?? 0) + 1;
3052
+ counted.set(group, Math.max(counted.get(group) ?? 0, setNumber));
3053
+ const one = `${group}\0${setNumber}`;
3054
+ const other = seen.get(one);
3055
+ if (other) {
3056
+ report.problems.push({
3057
+ file: row.file,
3058
+ message: `set ${setNumber} of ${row.exercise} on ${row.date} is the same set as ${other}'s: give each set its own number`
3059
+ });
3060
+ continue;
3061
+ }
3062
+ seen.set(one, row.file);
3063
+ training2.push({ row, person, setNumber });
3064
+ }
3065
+ if (report.problems.length) return report;
3066
+ const batches = async (dryRun) => {
3067
+ let n = 0;
3068
+ const placeholders = /* @__PURE__ */ new Map();
3069
+ const idOf = (results, what) => {
3070
+ const ids = /* @__PURE__ */ new Map();
3071
+ for (const r of results) {
3072
+ if (r.id) ids.set(r.key, r.id);
3073
+ else if (dryRun && r.outcome !== "invalid") {
3074
+ const at = `${what}:${r.key}`;
3075
+ if (!placeholders.has(at)) placeholders.set(at, `rec_importplaceholder${++n}`);
3076
+ ids.set(r.key, placeholders.get(at));
3077
+ }
3078
+ }
3079
+ return ids;
3080
+ };
3081
+ const options2 = { dryRun, checkReferences: !dryRun };
3082
+ const out = [];
3083
+ const step = async (object, label, records) => {
3084
+ if (!records.length) return [];
3085
+ const keys = /* @__PURE__ */ new Map();
3086
+ let refused = false;
3087
+ for (const r of records) {
3088
+ if (r.key.length > IMPORT_KEY_MAX) {
3089
+ refused = true;
3090
+ report.problems.push({
3091
+ file: r.file ?? r.key,
3092
+ message: `its import key is ${r.key.length} characters, at most ${IMPORT_KEY_MAX}: shorten the session's name or the key`
3093
+ });
3094
+ } else if (keys.has(r.key)) {
3095
+ refused = true;
3096
+ report.problems.push({
3097
+ file: r.file ?? r.key,
3098
+ message: `the same record as ${keys.get(r.key) ?? "another row"} (its import key is the same)`
3099
+ });
3100
+ }
3101
+ keys.set(r.key, r.file);
3102
+ }
3103
+ if (refused) throw new Stopped();
3104
+ if (!dryRun) say(`${label}: ${records.length}\u2026`);
3105
+ const results = await importRecords(host, object, records, options2);
3106
+ out.push(...results);
3107
+ return results;
3108
+ };
3109
+ await step(
3110
+ CLASSTYPE,
3111
+ "Class types",
3112
+ plan.classTypes.map((c) => ({ key: c.key, file: c.file, values: c.values }))
3113
+ );
3114
+ const exerciseResults = await step(
3115
+ EXERCISE2,
3116
+ "Exercises",
3117
+ plan.exercises.map((e) => ({ key: e.key, file: e.file, values: e.values }))
3118
+ );
3119
+ const exerciseIds = idOf(exerciseResults, "exercise");
3120
+ const linked = plan.exercises.filter((e) => e.easier.length || e.harder.length);
3121
+ const versions = (e) => ({
3122
+ ...e.easier.length ? { easier: e.easier.map((k) => exerciseIds.get(k)) } : {},
3123
+ ...e.harder.length ? { harder: e.harder.map((k) => exerciseIds.get(k)) } : {}
3124
+ });
3125
+ const ready = linked.filter(
3126
+ (e) => [e.key, ...e.easier, ...e.harder].every((k) => exerciseIds.has(k))
3127
+ );
3128
+ if (dryRun) {
3129
+ const checked = await importRecords(
3130
+ host,
3131
+ EXERCISE2,
3132
+ ready.map((e) => ({ key: e.key, file: e.file, values: { ...e.values, ...versions(e) } })),
3133
+ options2
3134
+ );
3135
+ for (const r of checked) if (r.outcome === "invalid") out.push(r);
3136
+ } else {
3137
+ await step(
3138
+ EXERCISE2,
3139
+ "Easier and harder versions",
3140
+ ready.map((e) => ({ key: e.key, file: e.file, values: versions(e) }))
3141
+ );
3142
+ }
3143
+ const readBank = [
3144
+ ...bank,
3145
+ ...plan.exercises.flatMap((e) => {
3146
+ const id2 = exerciseIds.get(e.key);
3147
+ return id2 ? [{ id: id2, name: e.name, measure: String(e.values.measure) }] : [];
3148
+ })
3149
+ ];
3150
+ const programRecords = [];
3151
+ const titles = /* @__PURE__ */ new Map();
3152
+ for (const p of plan.programs) {
3153
+ const read = readProgramText(p.text, readBank);
3154
+ for (const u of read.unread) {
3155
+ const where = u.line ? `${p.file}:${u.line}` : p.file;
3156
+ if (u.reason.startsWith("kept as warm-up text")) {
3157
+ if (dryRun) report.notes.push({ file: where, message: `${u.text} (${u.reason})` });
3158
+ continue;
3159
+ }
3160
+ report.problems.push({ file: where, message: `${u.text}: ${u.reason}` });
3161
+ }
3162
+ const title = read.title ?? p.key;
3163
+ titles.set(p.key, title);
3164
+ programRecords.push({
3165
+ key: p.key,
3166
+ file: p.file,
3167
+ values: {
3168
+ title,
3169
+ kind: read.kind ?? "class",
3170
+ guidance: read.guidance,
3171
+ layout: read.layout
3172
+ }
3173
+ });
3174
+ }
3175
+ if (report.problems.length) return out;
3176
+ const programIds = idOf(await step(PROGRAM2, "Programs", programRecords), "program");
3177
+ const sessions = /* @__PURE__ */ new Map();
3178
+ for (const { row, person } of training2) {
3179
+ const key = sessionKey(person, row);
3180
+ const program = row.program ? programIds.get(row.program) : void 0;
3181
+ const had = sessions.get(key);
3182
+ if (had) {
3183
+ if (program && !had.values.program) had.values.program = program;
3184
+ continue;
3185
+ }
3186
+ sessions.set(key, {
3187
+ key,
3188
+ file: row.file,
3189
+ values: {
3190
+ name: row.session,
3191
+ person,
3192
+ date: row.date,
3193
+ state: "done",
3194
+ source: "import",
3195
+ ...program ? { program } : {}
3196
+ }
3197
+ });
3198
+ }
3199
+ const sessionIds = idOf(
3200
+ await step(SESSION3, "Past sessions", [...sessions.values()]),
3201
+ "session"
3202
+ );
3203
+ const logs = training2.flatMap(({ row, person, setNumber }) => {
3204
+ const session = sessionIds.get(sessionKey(person, row));
3205
+ const folderKey = exerciseKeyOf(row);
3206
+ const exercise = folderKey ? exerciseIds.get(folderKey) : onHost.get(row.exercise)?.id;
3207
+ if (!session || !exercise) return [];
3208
+ const name = folderKey ? folderExercise.get(folderKey)?.name : onHost.get(row.exercise)?.name;
3209
+ return [
3210
+ {
3211
+ key: `${sessionKey(person, row)}|${row.item ?? ""}|${exercise}|${setNumber}`,
3212
+ file: row.file,
3213
+ values: {
3214
+ label: `${row.item ?? name ?? "Set"} set ${setNumber}`,
3215
+ person,
3216
+ session,
3217
+ exercise,
3218
+ ...name ? { exerciseName: name } : {},
3219
+ ...row.item ? { item: row.item } : {},
3220
+ setNumber,
3221
+ ...row.level !== null ? { level: row.level } : {},
3222
+ date: row.date,
3223
+ ...row.values,
3224
+ source: "import"
3225
+ }
3226
+ }
3227
+ ];
3228
+ });
3229
+ await step(LOG2, "Logged sets", logs);
3230
+ return out;
3231
+ };
3232
+ const dry = await batches(true).catch((error) => {
3233
+ if (error instanceof Stopped) return [];
3234
+ throw error;
3235
+ });
3236
+ for (const r of dry) {
3237
+ if (r.outcome === "invalid") {
3238
+ for (const message of r.problems) report.problems.push({ file: r.file ?? r.key, message });
3239
+ }
3240
+ }
3241
+ if (report.problems.length || options.dryRun) {
3242
+ report.records = dry.filter((r) => r.outcome !== "invalid");
3243
+ return report;
3244
+ }
3245
+ report.records = await batches(false);
3246
+ for (const r of report.records) {
3247
+ if (r.outcome === "invalid") {
3248
+ for (const message of r.problems) report.problems.push({ file: r.file ?? r.key, message });
3249
+ }
3250
+ }
3251
+ if (report.records.some((r) => r.outcome === "created" || r.outcome === "updated")) {
3252
+ report.wroteNothing = false;
3253
+ }
3254
+ return report;
3255
+ }
3256
+ function programsReportLines(report, dryRun) {
3257
+ const lines = [];
3258
+ if (report.problems.length) {
3259
+ lines.push(
3260
+ `${report.wroteNothing ? "Nothing was written" : "Stopped"}: ${report.problems.length} problem(s).`
3261
+ );
3262
+ for (const p of report.problems) lines.push(` ${p.file}: ${p.message}`);
3263
+ return lines;
3264
+ }
3265
+ const by = (object) => report.records.filter((r) => r.object === object);
3266
+ for (const [object, label] of [
3267
+ [CLASSTYPE, "Class types"],
3268
+ [EXERCISE2, "Exercises"],
3269
+ [PROGRAM2, "Programs"],
3270
+ [SESSION3, "Past sessions"],
3271
+ [LOG2, "Logged sets"]
3272
+ ]) {
3273
+ const records = by(object);
3274
+ if (!records.length) continue;
3275
+ lines.push(`${label}:`);
3276
+ for (const line of outcomeLines(records, dryRun)) lines.push(` ${line}`);
3277
+ }
3278
+ if (report.unmatched.length) {
3279
+ lines.push(`${report.unmatched.length} row(s) matched nothing and were left out:`);
3280
+ for (const u of report.unmatched) lines.push(` ${u.file}: ${u.message}`);
3281
+ }
3282
+ for (const note of report.notes) lines.push(` ${note.file}: ${note.message}`);
3283
+ lines.push(
3284
+ dryRun ? "Dry run: nothing was written. Run again without --dry-run to import." : "Done. Programs are working copies: a person with the publish permission publishes them."
3285
+ );
3286
+ return lines;
3287
+ }
3288
+
3289
+ // src/programs-import/run.ts
3290
+ var PROGRAMS_USAGE = "Usage: cos programs import <folder> --host <url> [--email <you>] [--dry-run]";
3291
+ function readProgramsDisk(dir) {
3292
+ const root = resolve(dir);
3293
+ if (!existsSync(root) || !statSync(root).isDirectory()) throw new Error(`${dir} is not a folder`);
3294
+ const text2 = (name) => existsSync(join(root, name)) ? readFileSync(join(root, name), "utf8") : null;
3295
+ const programsDir = join(root, "programs");
3296
+ return {
3297
+ exercises: text2("exercises.csv"),
3298
+ classTypes: text2("classtypes.csv"),
3299
+ programs: new Map(
3300
+ existsSync(programsDir) ? readdirSync(programsDir).filter((n) => statSync(join(programsDir, n)).isFile() && !n.startsWith(".")).map((n) => [n, readFileSync(join(programsDir, n), "utf8")]) : []
3301
+ ),
3302
+ training: text2("training.csv")
3303
+ };
3304
+ }
3305
+ async function programsImport(positional, flags, io) {
3306
+ const dir = positional[0];
3307
+ if (!dir) {
3308
+ io.err(
3309
+ `${PROGRAMS_USAGE}
3310
+
3311
+ The folder: exercises.csv, classtypes.csv, programs/*.txt (the shorthand), training.csv (past sets). See docs/importing.md.`
3312
+ );
3313
+ return 2;
3314
+ }
3315
+ const host = flags.host?.replace(/\/+$/, "");
3316
+ if (!host || !/^https?:\/\//.test(host)) {
3317
+ io.err("--host is the host's address, e.g. https://admin.example.com");
3318
+ return 2;
3319
+ }
3320
+ let plan;
3321
+ try {
3322
+ plan = readProgramsFolder(readProgramsDisk(dir));
3323
+ } catch (error) {
3324
+ io.err(error.message);
3325
+ return 2;
3326
+ }
3327
+ if (plan.problems.length) {
3328
+ io.err(`Nothing was written: ${plan.problems.length} problem(s) in ${dir}.`);
3329
+ for (const p of plan.problems) io.err(` ${p.file ? `${p.file}: ` : ""}${p.message}`);
3330
+ return 1;
3331
+ }
3332
+ io.out(
3333
+ `${plan.exercises.length} exercise(s), ${plan.classTypes.length} class type(s), ${plan.programs.length} program(s) and ${plan.training.length} logged set(s) in ${dir}.${flags.dryRun ? " A dry run: nothing is written." : ""}`
3334
+ );
3335
+ let session;
3336
+ try {
3337
+ session = await signInForRun(host, flags.email, io, "cos programs import");
3338
+ } catch (error) {
3339
+ io.err(`Could not sign in: ${error.message}`);
3340
+ return 1;
3341
+ }
3342
+ try {
3343
+ const report = await runProgramsImport(
3344
+ plan,
3345
+ sessionHost(host, () => session.headers()),
3346
+ { dryRun: Boolean(flags.dryRun), progress: (line) => io.out(line) }
3347
+ );
3348
+ for (const line of programsReportLines(report, Boolean(flags.dryRun))) {
3349
+ (report.problems.length ? io.err : io.out)(line);
3350
+ }
3351
+ return report.problems.length ? 1 : 0;
3352
+ } catch (error) {
3353
+ io.err(`Error: ${error.message}`);
3354
+ return 1;
3355
+ } finally {
3356
+ await session.signOut();
3357
+ }
3358
+ }
3359
+ export {
3360
+ PROGRAMS_USAGE,
3361
+ programsImport,
3362
+ readProgramsDisk
3363
+ };