@thebriangao/totem 1.4.4 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (763) hide show
  1. package/.dev.vars.example +5 -0
  2. package/.dockerignore +5 -0
  3. package/.env.example +29 -20
  4. package/CHANGELOG.md +99 -1
  5. package/CONTRIBUTING.md +48 -116
  6. package/Dockerfile +46 -12
  7. package/README.md +172 -498
  8. package/SECURITY.md +36 -59
  9. package/TOOLS.md +448 -311
  10. package/WHOOP.md +497 -2659
  11. package/assets/brand/SOURCES.md +38 -0
  12. package/assets/brand/totem.png +0 -0
  13. package/assets/brand/totem.svg +13 -0
  14. package/assets/fonts/Manrope-OFL.txt +93 -0
  15. package/assets/fonts/manrope-latin.woff2 +0 -0
  16. package/dist/build_info.js +5 -0
  17. package/dist/build_info.js.map +1 -0
  18. package/dist/cli/app.js +675 -0
  19. package/dist/cli/app.js.map +1 -0
  20. package/dist/cli/auth.js +297 -0
  21. package/dist/cli/auth.js.map +1 -0
  22. package/dist/cli/auth_flow.js +268 -0
  23. package/dist/cli/auth_flow.js.map +1 -0
  24. package/dist/cli/browser_login.js +368 -0
  25. package/dist/cli/browser_login.js.map +1 -0
  26. package/dist/cli/clients.js +403 -0
  27. package/dist/cli/clients.js.map +1 -0
  28. package/dist/cli/deploy_record.js +96 -0
  29. package/dist/cli/deploy_record.js.map +1 -0
  30. package/dist/cli/index.js +39 -575
  31. package/dist/cli/index.js.map +1 -1
  32. package/dist/cli/links.js +28 -0
  33. package/dist/cli/links.js.map +1 -0
  34. package/dist/cli/logo.js +63 -0
  35. package/dist/cli/logo.js.map +1 -0
  36. package/dist/cli/setup.js +1157 -1017
  37. package/dist/cli/setup.js.map +1 -1
  38. package/dist/cli/spawn.js +80 -0
  39. package/dist/cli/spawn.js.map +1 -0
  40. package/dist/cli/sys.js +219 -0
  41. package/dist/cli/sys.js.map +1 -0
  42. package/dist/cli/ui.js +712 -463
  43. package/dist/cli/ui.js.map +1 -1
  44. package/dist/cli/update.js +425 -282
  45. package/dist/cli/update.js.map +1 -1
  46. package/dist/cloudflare/token_store.js +48 -0
  47. package/dist/cloudflare/token_store.js.map +1 -0
  48. package/dist/cloudflare/worker.js +155 -0
  49. package/dist/cloudflare/worker.js.map +1 -0
  50. package/dist/data/behaviors.js +2733 -617
  51. package/dist/data/behaviors.js.map +1 -1
  52. package/dist/data/endpoint_catalog.js +2681 -0
  53. package/dist/data/endpoint_catalog.js.map +1 -0
  54. package/dist/data/exercises.js +373 -4859
  55. package/dist/data/exercises.js.map +1 -1
  56. package/dist/data/garments.js +19 -0
  57. package/dist/data/garments.js.map +1 -0
  58. package/dist/data/sports.js +219 -208
  59. package/dist/data/sports.js.map +1 -1
  60. package/dist/lib/activity_list.js +123 -0
  61. package/dist/lib/activity_list.js.map +1 -0
  62. package/dist/lib/activity_records.js +195 -0
  63. package/dist/lib/activity_records.js.map +1 -0
  64. package/dist/lib/activity_results.js +44 -0
  65. package/dist/lib/activity_results.js.map +1 -0
  66. package/dist/lib/activity_types.js +164 -0
  67. package/dist/lib/activity_types.js.map +1 -0
  68. package/dist/lib/brand.js +63 -0
  69. package/dist/lib/brand.js.map +1 -0
  70. package/dist/lib/clock.js +24 -0
  71. package/dist/lib/clock.js.map +1 -0
  72. package/dist/lib/coach_session.js +345 -0
  73. package/dist/lib/coach_session.js.map +1 -0
  74. package/dist/lib/concurrency.js.map +1 -1
  75. package/dist/lib/dates.js +19 -0
  76. package/dist/lib/dates.js.map +1 -1
  77. package/dist/lib/env_file.js +195 -0
  78. package/dist/lib/env_file.js.map +1 -0
  79. package/dist/lib/health_plans_write.js +44 -0
  80. package/dist/lib/health_plans_write.js.map +1 -0
  81. package/dist/lib/heart_rate.js +34 -0
  82. package/dist/lib/heart_rate.js.map +1 -0
  83. package/dist/lib/highlight.js +81 -0
  84. package/dist/lib/highlight.js.map +1 -0
  85. package/dist/lib/install_links.js +47 -0
  86. package/dist/lib/install_links.js.map +1 -0
  87. package/dist/lib/instant.js +50 -0
  88. package/dist/lib/instant.js.map +1 -0
  89. package/dist/lib/journal_behaviors.js +382 -0
  90. package/dist/lib/journal_behaviors.js.map +1 -0
  91. package/dist/lib/lift_catalog.js +218 -0
  92. package/dist/lib/lift_catalog.js.map +1 -0
  93. package/dist/lib/lift_history.js +66 -0
  94. package/dist/lib/lift_history.js.map +1 -0
  95. package/dist/lib/lift_sets.js +146 -0
  96. package/dist/lib/lift_sets.js.map +1 -0
  97. package/dist/lib/lift_tool.js +20 -0
  98. package/dist/lib/lift_tool.js.map +1 -0
  99. package/dist/lib/profile_settings.js +101 -0
  100. package/dist/lib/profile_settings.js.map +1 -0
  101. package/dist/lib/screen_content.js +44 -0
  102. package/dist/lib/screen_content.js.map +1 -0
  103. package/dist/lib/timezone.js +48 -6
  104. package/dist/lib/timezone.js.map +1 -1
  105. package/dist/lib/walk.js +6 -1
  106. package/dist/lib/walk.js.map +1 -1
  107. package/dist/lib/weight_readings.js +61 -0
  108. package/dist/lib/weight_readings.js.map +1 -0
  109. package/dist/projections/activities.js +193 -0
  110. package/dist/projections/activities.js.map +1 -0
  111. package/dist/projections/alarm_schedule.js +102 -0
  112. package/dist/projections/alarm_schedule.js.map +1 -0
  113. package/dist/projections/coach.js +203 -0
  114. package/dist/projections/coach.js.map +1 -0
  115. package/dist/projections/community.js +165 -0
  116. package/dist/projections/community.js.map +1 -0
  117. package/dist/projections/health_features.js +167 -0
  118. package/dist/projections/health_features.js.map +1 -0
  119. package/dist/projections/hormonal_insights.js +239 -0
  120. package/dist/projections/hormonal_insights.js.map +1 -0
  121. package/dist/projections/journal_v2.js +157 -0
  122. package/dist/projections/journal_v2.js.map +1 -0
  123. package/dist/projections/lift_cards.js +115 -0
  124. package/dist/projections/lift_cards.js.map +1 -0
  125. package/dist/projections/lift_exercise_v2.js +131 -0
  126. package/dist/projections/lift_exercise_v2.js.map +1 -0
  127. package/dist/projections/lift_library_v2.js +67 -0
  128. package/dist/projections/lift_library_v2.js.map +1 -0
  129. package/dist/projections/lift_sessions.js +211 -0
  130. package/dist/projections/lift_sessions.js.map +1 -0
  131. package/dist/projections/memory.js +95 -0
  132. package/dist/projections/memory.js.map +1 -0
  133. package/dist/projections/milestones.js +119 -0
  134. package/dist/projections/milestones.js.map +1 -0
  135. package/dist/projections/profile_v2.js +150 -0
  136. package/dist/projections/profile_v2.js.map +1 -0
  137. package/dist/projections/settings_v2.js +153 -0
  138. package/dist/projections/settings_v2.js.map +1 -0
  139. package/dist/projections/sleep.js +4 -21
  140. package/dist/projections/sleep.js.map +1 -1
  141. package/dist/projections/v2/calendar.js +43 -0
  142. package/dist/projections/v2/calendar.js.map +1 -0
  143. package/dist/projections/v2/core_common.js +86 -0
  144. package/dist/projections/v2/core_common.js.map +1 -0
  145. package/dist/projections/v2/core_home.js +136 -0
  146. package/dist/projections/v2/core_home.js.map +1 -0
  147. package/dist/projections/v2/core_sleep_need.js +23 -0
  148. package/dist/projections/v2/core_sleep_need.js.map +1 -0
  149. package/dist/projections/v2/day.js +92 -0
  150. package/dist/projections/v2/day.js.map +1 -0
  151. package/dist/projections/v2/heart_rate.js +54 -0
  152. package/dist/projections/v2/heart_rate.js.map +1 -0
  153. package/dist/projections/v2/history.js +140 -0
  154. package/dist/projections/v2/history.js.map +1 -0
  155. package/dist/projections/v2/now.js +39 -0
  156. package/dist/projections/v2/now.js.map +1 -0
  157. package/dist/projections/v2/recovery.js +77 -0
  158. package/dist/projections/v2/recovery.js.map +1 -0
  159. package/dist/projections/v2/sleep.js +218 -0
  160. package/dist/projections/v2/sleep.js.map +1 -0
  161. package/dist/projections/v2/strain.js +39 -0
  162. package/dist/projections/v2/strain.js.map +1 -0
  163. package/dist/projections/v2/stress.js +92 -0
  164. package/dist/projections/v2/stress.js.map +1 -0
  165. package/dist/projections/v2/trend.js +205 -0
  166. package/dist/projections/v2/trend.js.map +1 -0
  167. package/dist/projections/weekly_plan.js +66 -0
  168. package/dist/projections/weekly_plan.js.map +1 -0
  169. package/dist/projections/weight_readings.js +57 -0
  170. package/dist/projections/weight_readings.js.map +1 -0
  171. package/dist/projections/workout.js +37 -15
  172. package/dist/projections/workout.js.map +1 -1
  173. package/dist/schemas/activities.js +123 -0
  174. package/dist/schemas/activities.js.map +1 -0
  175. package/dist/schemas/alarm_schedule.js +62 -0
  176. package/dist/schemas/alarm_schedule.js.map +1 -0
  177. package/dist/schemas/coach.js +76 -8
  178. package/dist/schemas/coach.js.map +1 -1
  179. package/dist/schemas/community.js +70 -0
  180. package/dist/schemas/community.js.map +1 -0
  181. package/dist/schemas/health.js +36 -0
  182. package/dist/schemas/health.js.map +1 -0
  183. package/dist/schemas/hormonal_insights.js +90 -0
  184. package/dist/schemas/hormonal_insights.js.map +1 -0
  185. package/dist/schemas/journal.js +4 -0
  186. package/dist/schemas/journal.js.map +1 -1
  187. package/dist/schemas/journal_v2.js +106 -0
  188. package/dist/schemas/journal_v2.js.map +1 -0
  189. package/dist/schemas/memory.js +42 -0
  190. package/dist/schemas/memory.js.map +1 -0
  191. package/dist/schemas/milestones.js +39 -0
  192. package/dist/schemas/milestones.js.map +1 -0
  193. package/dist/schemas/profile_v2.js +60 -0
  194. package/dist/schemas/profile_v2.js.map +1 -0
  195. package/dist/schemas/settings_v2.js +56 -0
  196. package/dist/schemas/settings_v2.js.map +1 -0
  197. package/dist/schemas/sleep.js +8 -1
  198. package/dist/schemas/sleep.js.map +1 -1
  199. package/dist/schemas/strength.js +10 -1
  200. package/dist/schemas/strength.js.map +1 -1
  201. package/dist/schemas/strength_v2.js +190 -0
  202. package/dist/schemas/strength_v2.js.map +1 -0
  203. package/dist/schemas/v2/calendar.js +8 -0
  204. package/dist/schemas/v2/calendar.js.map +1 -0
  205. package/dist/schemas/v2/core_common.js +42 -0
  206. package/dist/schemas/v2/core_common.js.map +1 -0
  207. package/dist/schemas/v2/day.js +73 -0
  208. package/dist/schemas/v2/day.js.map +1 -0
  209. package/dist/schemas/v2/now.js +25 -0
  210. package/dist/schemas/v2/now.js.map +1 -0
  211. package/dist/schemas/v2/recovery.js +35 -0
  212. package/dist/schemas/v2/recovery.js.map +1 -0
  213. package/dist/schemas/v2/sleep.js +44 -0
  214. package/dist/schemas/v2/sleep.js.map +1 -0
  215. package/dist/schemas/v2/strain.js +16 -0
  216. package/dist/schemas/v2/strain.js.map +1 -0
  217. package/dist/schemas/v2/stress.js +20 -0
  218. package/dist/schemas/v2/stress.js.map +1 -0
  219. package/dist/schemas/v2/trend.js +42 -0
  220. package/dist/schemas/v2/trend.js.map +1 -0
  221. package/dist/schemas/weekly_plan.js +31 -0
  222. package/dist/schemas/weekly_plan.js.map +1 -0
  223. package/dist/schemas/weight.js +28 -0
  224. package/dist/schemas/weight.js.map +1 -0
  225. package/dist/scripts/build_behaviors.js +114 -0
  226. package/dist/scripts/build_behaviors.js.map +1 -0
  227. package/dist/scripts/cognito_bootstrap.js +9 -277
  228. package/dist/scripts/cognito_bootstrap.js.map +1 -1
  229. package/dist/scripts/gen_activity_catalogs.js +104 -0
  230. package/dist/scripts/gen_activity_catalogs.js.map +1 -0
  231. package/dist/server-admin.js +156 -0
  232. package/dist/server-admin.js.map +1 -0
  233. package/dist/server-http.js +270 -48
  234. package/dist/server-http.js.map +1 -1
  235. package/dist/server.js +136 -23
  236. package/dist/server.js.map +1 -1
  237. package/dist/tools/annotations.js +15 -0
  238. package/dist/tools/annotations.js.map +1 -0
  239. package/dist/tools/define.js +31 -0
  240. package/dist/tools/define.js.map +1 -0
  241. package/dist/tools/register.js +59 -94
  242. package/dist/tools/register.js.map +1 -1
  243. package/dist/tools/resources.js +70 -0
  244. package/dist/tools/resources.js.map +1 -0
  245. package/dist/tools/slim_schema.js +90 -0
  246. package/dist/tools/slim_schema.js.map +1 -0
  247. package/dist/tools/v2/activity_delete.js +63 -17
  248. package/dist/tools/v2/activity_delete.js.map +1 -1
  249. package/dist/tools/v2/activity_edit.js +396 -0
  250. package/dist/tools/v2/activity_edit.js.map +1 -0
  251. package/dist/tools/v2/activity_log.js +152 -0
  252. package/dist/tools/v2/activity_log.js.map +1 -0
  253. package/dist/tools/v2/calendar.js +19 -21
  254. package/dist/tools/v2/calendar.js.map +1 -1
  255. package/dist/tools/v2/coach_ask.js +74 -110
  256. package/dist/tools/v2/coach_ask.js.map +1 -1
  257. package/dist/tools/v2/coach_history.js +120 -0
  258. package/dist/tools/v2/coach_history.js.map +1 -0
  259. package/dist/tools/v2/community.js +124 -0
  260. package/dist/tools/v2/community.js.map +1 -0
  261. package/dist/tools/v2/cycle.js +63 -15
  262. package/dist/tools/v2/cycle.js.map +1 -1
  263. package/dist/tools/v2/cycle_log.js +289 -32
  264. package/dist/tools/v2/cycle_log.js.map +1 -1
  265. package/dist/tools/v2/day.js +126 -24
  266. package/dist/tools/v2/day.js.map +1 -1
  267. package/dist/tools/v2/health.js +116 -0
  268. package/dist/tools/v2/health.js.map +1 -0
  269. package/dist/tools/v2/hr_zones_set.js +134 -34
  270. package/dist/tools/v2/hr_zones_set.js.map +1 -1
  271. package/dist/tools/v2/journal.js +75 -17
  272. package/dist/tools/v2/journal.js.map +1 -1
  273. package/dist/tools/v2/journal_log.js +306 -65
  274. package/dist/tools/v2/journal_log.js.map +1 -1
  275. package/dist/tools/v2/lift_exercise.js +125 -22
  276. package/dist/tools/v2/lift_exercise.js.map +1 -1
  277. package/dist/tools/v2/lift_exercise_set.js +291 -0
  278. package/dist/tools/v2/lift_exercise_set.js.map +1 -0
  279. package/dist/tools/v2/lift_library.js +51 -12
  280. package/dist/tools/v2/lift_library.js.map +1 -1
  281. package/dist/tools/v2/lift_log.js +309 -72
  282. package/dist/tools/v2/lift_log.js.map +1 -1
  283. package/dist/tools/v2/lift_sessions.js +248 -0
  284. package/dist/tools/v2/lift_sessions.js.map +1 -0
  285. package/dist/tools/v2/lift_template.js +232 -0
  286. package/dist/tools/v2/lift_template.js.map +1 -0
  287. package/dist/tools/v2/memory.js +45 -0
  288. package/dist/tools/v2/memory.js.map +1 -0
  289. package/dist/tools/v2/memory_set.js +107 -0
  290. package/dist/tools/v2/memory_set.js.map +1 -0
  291. package/dist/tools/v2/milestones.js +50 -0
  292. package/dist/tools/v2/milestones.js.map +1 -0
  293. package/dist/tools/v2/now.js +49 -0
  294. package/dist/tools/v2/now.js.map +1 -0
  295. package/dist/tools/v2/preferences.js +51 -0
  296. package/dist/tools/v2/preferences.js.map +1 -0
  297. package/dist/tools/v2/preferences_set.js +388 -0
  298. package/dist/tools/v2/preferences_set.js.map +1 -0
  299. package/dist/tools/v2/profile.js +54 -22
  300. package/dist/tools/v2/profile.js.map +1 -1
  301. package/dist/tools/v2/profile_update.js +167 -55
  302. package/dist/tools/v2/profile_update.js.map +1 -1
  303. package/dist/tools/v2/raw.js +91 -34
  304. package/dist/tools/v2/raw.js.map +1 -1
  305. package/dist/tools/v2/recovery.js +37 -23
  306. package/dist/tools/v2/recovery.js.map +1 -1
  307. package/dist/tools/v2/sleep.js +52 -16
  308. package/dist/tools/v2/sleep.js.map +1 -1
  309. package/dist/tools/v2/smart_alarm.js +54 -20
  310. package/dist/tools/v2/smart_alarm.js.map +1 -1
  311. package/dist/tools/v2/smart_alarm_set.js +264 -86
  312. package/dist/tools/v2/smart_alarm_set.js.map +1 -1
  313. package/dist/tools/v2/strain.js +15 -15
  314. package/dist/tools/v2/strain.js.map +1 -1
  315. package/dist/tools/v2/stress.js +17 -15
  316. package/dist/tools/v2/stress.js.map +1 -1
  317. package/dist/tools/v2/trend.js +56 -20
  318. package/dist/tools/v2/trend.js.map +1 -1
  319. package/dist/tools/v2/weekly_plan.js +30 -0
  320. package/dist/tools/v2/weekly_plan.js.map +1 -0
  321. package/dist/tools/v2/weekly_plan_set.js +134 -0
  322. package/dist/tools/v2/weekly_plan_set.js.map +1 -0
  323. package/dist/tools/v2/weight.js +56 -0
  324. package/dist/tools/v2/weight.js.map +1 -0
  325. package/dist/tools/v2/weight_log.js +188 -0
  326. package/dist/tools/v2/weight_log.js.map +1 -0
  327. package/dist/tools/v2/workouts.js +159 -25
  328. package/dist/tools/v2/workouts.js.map +1 -1
  329. package/dist/version.js +6 -0
  330. package/dist/version.js.map +1 -0
  331. package/dist/whoop/bff.js +94 -0
  332. package/dist/whoop/bff.js.map +1 -0
  333. package/dist/whoop/client.js +392 -18
  334. package/dist/whoop/client.js.map +1 -1
  335. package/dist/whoop/cognito.js +106 -79
  336. package/dist/whoop/cognito.js.map +1 -1
  337. package/dist/whoop/connect_page.js +165 -0
  338. package/dist/whoop/connect_page.js.map +1 -0
  339. package/dist/whoop/consent_font.js +287 -0
  340. package/dist/whoop/consent_font.js.map +1 -0
  341. package/dist/whoop/consent_logos.js +22 -0
  342. package/dist/whoop/consent_logos.js.map +1 -0
  343. package/dist/whoop/consent_page.js +291 -0
  344. package/dist/whoop/consent_page.js.map +1 -0
  345. package/dist/whoop/constants.js +5 -1
  346. package/dist/whoop/constants.js.map +1 -1
  347. package/dist/whoop/device.js +4 -4
  348. package/dist/whoop/device.js.map +1 -1
  349. package/dist/whoop/errors.js +85 -4
  350. package/dist/whoop/errors.js.map +1 -1
  351. package/dist/whoop/init_timezone.js +57 -17
  352. package/dist/whoop/init_timezone.js.map +1 -1
  353. package/dist/whoop/installation.js +15 -10
  354. package/dist/whoop/installation.js.map +1 -1
  355. package/dist/whoop/json_out.js +52 -6
  356. package/dist/whoop/json_out.js.map +1 -1
  357. package/dist/whoop/oauth_provider.js +81 -78
  358. package/dist/whoop/oauth_provider.js.map +1 -1
  359. package/dist/whoop/token_lock.js +331 -0
  360. package/dist/whoop/token_lock.js.map +1 -0
  361. package/dist/whoop/token_manager.js +536 -42
  362. package/dist/whoop/token_manager.js.map +1 -1
  363. package/dist/whoop/token_store.js +303 -36
  364. package/dist/whoop/token_store.js.map +1 -1
  365. package/dist/whoop/units.js +28 -0
  366. package/dist/whoop/units.js.map +1 -0
  367. package/package.json +29 -13
  368. package/scripts/build-mcpb.mjs +72 -0
  369. package/scripts/embed-consent-font.mjs +34 -0
  370. package/scripts/readme-media.ts +195 -0
  371. package/scripts/tools-md.ts +89 -0
  372. package/scripts/whoop-md.ts +119 -0
  373. package/src/build_info.ts +4 -0
  374. package/src/cli/app.ts +696 -0
  375. package/src/cli/auth.ts +350 -0
  376. package/src/cli/auth_flow.ts +356 -0
  377. package/src/cli/browser_login.ts +402 -0
  378. package/src/cli/clients.ts +467 -0
  379. package/src/cli/deploy_record.ts +100 -0
  380. package/src/cli/index.ts +41 -583
  381. package/src/cli/links.ts +43 -0
  382. package/src/cli/logo.ts +64 -0
  383. package/src/cli/setup.ts +1147 -979
  384. package/src/cli/spawn.ts +88 -0
  385. package/src/cli/sys.ts +267 -0
  386. package/src/cli/ui.ts +778 -436
  387. package/src/cli/update.ts +436 -274
  388. package/src/cloudflare/runtime.d.ts +27 -0
  389. package/src/cloudflare/token_store.ts +57 -0
  390. package/src/cloudflare/worker.ts +174 -0
  391. package/src/data/behaviors.ts +2760 -622
  392. package/src/data/endpoint_catalog.ts +2695 -0
  393. package/src/data/exercises.ts +379 -4861
  394. package/src/data/garments.ts +28 -0
  395. package/src/data/sports.ts +239 -211
  396. package/src/lib/activity_list.ts +150 -0
  397. package/src/lib/activity_records.ts +213 -0
  398. package/src/lib/activity_results.ts +51 -0
  399. package/src/lib/activity_types.ts +176 -0
  400. package/src/lib/brand.ts +71 -0
  401. package/src/lib/clock.ts +16 -0
  402. package/src/lib/coach_session.ts +434 -0
  403. package/src/lib/dates.ts +18 -0
  404. package/src/lib/env_file.ts +191 -0
  405. package/src/lib/health_plans_write.ts +53 -0
  406. package/src/lib/heart_rate.ts +42 -0
  407. package/src/lib/highlight.ts +71 -0
  408. package/src/lib/install_links.ts +61 -0
  409. package/src/lib/instant.ts +54 -0
  410. package/src/lib/journal_behaviors.ts +453 -0
  411. package/src/lib/lift_catalog.ts +258 -0
  412. package/src/lib/lift_history.ts +75 -0
  413. package/src/lib/lift_sets.ts +164 -0
  414. package/src/lib/lift_tool.ts +25 -0
  415. package/src/lib/profile_settings.ts +102 -0
  416. package/src/lib/screen_content.ts +40 -0
  417. package/src/lib/timezone.ts +44 -8
  418. package/src/lib/walk.ts +4 -1
  419. package/src/lib/weight_readings.ts +82 -0
  420. package/src/projections/activities.ts +199 -0
  421. package/src/projections/alarm_schedule.ts +98 -0
  422. package/src/projections/coach.ts +218 -0
  423. package/src/projections/community.ts +187 -0
  424. package/src/projections/health_features.ts +191 -0
  425. package/src/projections/hormonal_insights.ts +277 -0
  426. package/src/projections/journal_v2.ts +173 -0
  427. package/src/projections/lift_cards.ts +131 -0
  428. package/src/projections/lift_exercise_v2.ts +147 -0
  429. package/src/projections/lift_library_v2.ts +77 -0
  430. package/src/projections/lift_sessions.ts +250 -0
  431. package/src/projections/memory.ts +100 -0
  432. package/src/projections/milestones.ts +133 -0
  433. package/src/projections/profile_v2.ts +166 -0
  434. package/src/projections/settings_v2.ts +179 -0
  435. package/src/projections/sleep.ts +7 -21
  436. package/src/projections/v2/calendar.ts +48 -0
  437. package/src/projections/v2/core_common.ts +95 -0
  438. package/src/projections/v2/core_home.ts +177 -0
  439. package/src/projections/v2/core_sleep_need.ts +37 -0
  440. package/src/projections/v2/day.ts +162 -0
  441. package/src/projections/v2/heart_rate.ts +73 -0
  442. package/src/projections/v2/history.ts +153 -0
  443. package/src/projections/v2/now.ts +59 -0
  444. package/src/projections/v2/recovery.ts +120 -0
  445. package/src/projections/v2/sleep.ts +281 -0
  446. package/src/projections/v2/strain.ts +63 -0
  447. package/src/projections/v2/stress.ts +111 -0
  448. package/src/projections/v2/trend.ts +242 -0
  449. package/src/projections/weekly_plan.ts +79 -0
  450. package/src/projections/weight_readings.ts +57 -0
  451. package/src/projections/workout.ts +36 -17
  452. package/src/schemas/activities.ts +136 -0
  453. package/src/schemas/alarm_schedule.ts +70 -0
  454. package/src/schemas/coach.ts +98 -8
  455. package/src/schemas/community.ts +77 -0
  456. package/src/schemas/health.ts +36 -0
  457. package/src/schemas/hormonal_insights.ts +108 -0
  458. package/src/schemas/journal.ts +4 -0
  459. package/src/schemas/journal_v2.ts +112 -0
  460. package/src/schemas/memory.ts +48 -0
  461. package/src/schemas/milestones.ts +48 -0
  462. package/src/schemas/profile_v2.ts +63 -0
  463. package/src/schemas/settings_v2.ts +63 -0
  464. package/src/schemas/sleep.ts +9 -1
  465. package/src/schemas/strength.ts +10 -1
  466. package/src/schemas/strength_v2.ts +210 -0
  467. package/src/schemas/v2/calendar.ts +8 -0
  468. package/src/schemas/v2/core_common.ts +50 -0
  469. package/src/schemas/v2/day.ts +79 -0
  470. package/src/schemas/v2/now.ts +25 -0
  471. package/src/schemas/v2/recovery.ts +38 -0
  472. package/src/schemas/v2/sleep.ts +46 -0
  473. package/src/schemas/v2/strain.ts +16 -0
  474. package/src/schemas/v2/stress.ts +20 -0
  475. package/src/schemas/v2/trend.ts +45 -0
  476. package/src/schemas/weekly_plan.ts +36 -0
  477. package/src/schemas/weight.ts +53 -0
  478. package/src/scripts/build_behaviors.ts +116 -0
  479. package/src/scripts/cognito_bootstrap.ts +10 -249
  480. package/src/scripts/gen_activity_catalogs.ts +121 -0
  481. package/src/server-admin.ts +171 -0
  482. package/src/server-http.ts +290 -53
  483. package/src/server.ts +130 -26
  484. package/src/tools/annotations.ts +25 -0
  485. package/src/tools/define.ts +53 -0
  486. package/src/tools/register.ts +64 -94
  487. package/src/tools/resources.ts +92 -0
  488. package/src/tools/slim_schema.ts +102 -0
  489. package/src/tools/v2/activity_delete.ts +61 -23
  490. package/src/tools/v2/activity_edit.ts +378 -0
  491. package/src/tools/v2/activity_log.ts +154 -0
  492. package/src/tools/v2/calendar.ts +22 -21
  493. package/src/tools/v2/coach_ask.ts +83 -119
  494. package/src/tools/v2/coach_history.ts +140 -0
  495. package/src/tools/v2/community.ts +137 -0
  496. package/src/tools/v2/cycle.ts +78 -20
  497. package/src/tools/v2/cycle_log.ts +291 -40
  498. package/src/tools/v2/day.ts +126 -25
  499. package/src/tools/v2/health.ts +114 -0
  500. package/src/tools/v2/hr_zones_set.ts +132 -45
  501. package/src/tools/v2/journal.ts +78 -23
  502. package/src/tools/v2/journal_log.ts +321 -69
  503. package/src/tools/v2/lift_exercise.ts +135 -27
  504. package/src/tools/v2/lift_exercise_set.ts +272 -0
  505. package/src/tools/v2/lift_library.ts +57 -21
  506. package/src/tools/v2/lift_log.ts +325 -83
  507. package/src/tools/v2/lift_sessions.ts +255 -0
  508. package/src/tools/v2/lift_template.ts +229 -0
  509. package/src/tools/v2/memory.ts +54 -0
  510. package/src/tools/v2/memory_set.ts +110 -0
  511. package/src/tools/v2/milestones.ts +59 -0
  512. package/src/tools/v2/now.ts +61 -0
  513. package/src/tools/v2/preferences.ts +61 -0
  514. package/src/tools/v2/preferences_set.ts +403 -0
  515. package/src/tools/v2/profile.ts +56 -26
  516. package/src/tools/v2/profile_update.ts +151 -60
  517. package/src/tools/v2/raw.ts +89 -36
  518. package/src/tools/v2/recovery.ts +44 -25
  519. package/src/tools/v2/sleep.ts +57 -18
  520. package/src/tools/v2/smart_alarm.ts +62 -24
  521. package/src/tools/v2/smart_alarm_set.ts +240 -90
  522. package/src/tools/v2/strain.ts +19 -16
  523. package/src/tools/v2/stress.ts +22 -17
  524. package/src/tools/v2/trend.ts +58 -20
  525. package/src/tools/v2/weekly_plan.ts +38 -0
  526. package/src/tools/v2/weekly_plan_set.ts +132 -0
  527. package/src/tools/v2/weight.ts +61 -0
  528. package/src/tools/v2/weight_log.ts +193 -0
  529. package/src/tools/v2/workouts.ts +156 -26
  530. package/src/version.ts +5 -0
  531. package/src/whoop/bff.ts +84 -0
  532. package/src/whoop/client.ts +448 -18
  533. package/src/whoop/cognito.ts +110 -99
  534. package/src/whoop/connect_page.ts +183 -0
  535. package/src/whoop/consent_font.ts +289 -0
  536. package/src/whoop/consent_logos.ts +24 -0
  537. package/src/whoop/consent_page.ts +326 -0
  538. package/src/whoop/constants.ts +5 -1
  539. package/src/whoop/device.ts +4 -4
  540. package/src/whoop/errors.ts +89 -4
  541. package/src/whoop/init_timezone.ts +57 -16
  542. package/src/whoop/installation.ts +16 -7
  543. package/src/whoop/json_out.ts +51 -6
  544. package/src/whoop/oauth_provider.ts +84 -91
  545. package/src/whoop/token_lock.ts +345 -0
  546. package/src/whoop/token_manager.ts +580 -53
  547. package/src/whoop/token_store.ts +341 -32
  548. package/src/whoop/units.ts +35 -0
  549. package/wrangler.jsonc +17 -0
  550. package/assets/banner.svg +0 -38
  551. package/dist/data/endpoints.js +0 -320
  552. package/dist/data/endpoints.js.map +0 -1
  553. package/dist/lib/format.js +0 -22
  554. package/dist/lib/format.js.map +0 -1
  555. package/dist/lib/stats.js +0 -32
  556. package/dist/lib/stats.js.map +0 -1
  557. package/dist/projections/calendar.js +0 -33
  558. package/dist/projections/calendar.js.map +0 -1
  559. package/dist/projections/communities.js +0 -105
  560. package/dist/projections/communities.js.map +0 -1
  561. package/dist/projections/cycle.js +0 -81
  562. package/dist/projections/cycle.js.map +0 -1
  563. package/dist/projections/hr_zones.js +0 -35
  564. package/dist/projections/hr_zones.js.map +0 -1
  565. package/dist/projections/journal.js +0 -56
  566. package/dist/projections/journal.js.map +0 -1
  567. package/dist/projections/leaderboard.js +0 -37
  568. package/dist/projections/leaderboard.js.map +0 -1
  569. package/dist/projections/lift_exercise.js +0 -22
  570. package/dist/projections/lift_exercise.js.map +0 -1
  571. package/dist/projections/lift_history.js +0 -133
  572. package/dist/projections/lift_history.js.map +0 -1
  573. package/dist/projections/lift_library.js +0 -71
  574. package/dist/projections/lift_library.js.map +0 -1
  575. package/dist/projections/lift_progression.js +0 -138
  576. package/dist/projections/lift_progression.js.map +0 -1
  577. package/dist/projections/lift_prs.js +0 -20
  578. package/dist/projections/lift_prs.js.map +0 -1
  579. package/dist/projections/live_hr.js +0 -19
  580. package/dist/projections/live_hr.js.map +0 -1
  581. package/dist/projections/live_state.js +0 -23
  582. package/dist/projections/live_state.js.map +0 -1
  583. package/dist/projections/live_stress.js +0 -11
  584. package/dist/projections/live_stress.js.map +0 -1
  585. package/dist/projections/performance_assessment.js +0 -15
  586. package/dist/projections/performance_assessment.js.map +0 -1
  587. package/dist/projections/profile.js +0 -59
  588. package/dist/projections/profile.js.map +0 -1
  589. package/dist/projections/recovery.js +0 -131
  590. package/dist/projections/recovery.js.map +0 -1
  591. package/dist/projections/sleep_need.js +0 -32
  592. package/dist/projections/sleep_need.js.map +0 -1
  593. package/dist/projections/smart_alarm.js +0 -45
  594. package/dist/projections/smart_alarm.js.map +0 -1
  595. package/dist/projections/strain.js +0 -128
  596. package/dist/projections/strain.js.map +0 -1
  597. package/dist/projections/stress.js +0 -86
  598. package/dist/projections/stress.js.map +0 -1
  599. package/dist/projections/today.js +0 -129
  600. package/dist/projections/today.js.map +0 -1
  601. package/dist/projections/trend.js +0 -149
  602. package/dist/projections/trend.js.map +0 -1
  603. package/dist/projections/workouts.js +0 -37
  604. package/dist/projections/workouts.js.map +0 -1
  605. package/dist/schemas/calendar.js +0 -12
  606. package/dist/schemas/calendar.js.map +0 -1
  607. package/dist/schemas/communities.js +0 -51
  608. package/dist/schemas/communities.js.map +0 -1
  609. package/dist/schemas/compare.js +0 -15
  610. package/dist/schemas/compare.js.map +0 -1
  611. package/dist/schemas/leaderboard.js +0 -25
  612. package/dist/schemas/leaderboard.js.map +0 -1
  613. package/dist/schemas/live.js +0 -26
  614. package/dist/schemas/live.js.map +0 -1
  615. package/dist/schemas/performance.js +0 -12
  616. package/dist/schemas/performance.js.map +0 -1
  617. package/dist/schemas/profile.js +0 -39
  618. package/dist/schemas/profile.js.map +0 -1
  619. package/dist/schemas/recovery.js +0 -27
  620. package/dist/schemas/recovery.js.map +0 -1
  621. package/dist/schemas/settings.js +0 -26
  622. package/dist/schemas/settings.js.map +0 -1
  623. package/dist/schemas/sleep_need.js +0 -15
  624. package/dist/schemas/sleep_need.js.map +0 -1
  625. package/dist/schemas/smart_alarm.js +0 -36
  626. package/dist/schemas/smart_alarm.js.map +0 -1
  627. package/dist/schemas/strain.js +0 -24
  628. package/dist/schemas/strain.js.map +0 -1
  629. package/dist/schemas/stress.js +0 -16
  630. package/dist/schemas/stress.js.map +0 -1
  631. package/dist/schemas/today.js +0 -38
  632. package/dist/schemas/today.js.map +0 -1
  633. package/dist/schemas/trend.js +0 -50
  634. package/dist/schemas/trend.js.map +0 -1
  635. package/dist/schemas/womens_health.js +0 -23
  636. package/dist/schemas/womens_health.js.map +0 -1
  637. package/dist/tools/v2/activity_create.js +0 -64
  638. package/dist/tools/v2/activity_create.js.map +0 -1
  639. package/dist/tools/v2/behavior_impact.js +0 -36
  640. package/dist/tools/v2/behavior_impact.js.map +0 -1
  641. package/dist/tools/v2/communities.js +0 -60
  642. package/dist/tools/v2/communities.js.map +0 -1
  643. package/dist/tools/v2/compare.js +0 -67
  644. package/dist/tools/v2/compare.js.map +0 -1
  645. package/dist/tools/v2/endpoints.js +0 -28
  646. package/dist/tools/v2/endpoints.js.map +0 -1
  647. package/dist/tools/v2/hidden_metric.js +0 -28
  648. package/dist/tools/v2/hidden_metric.js.map +0 -1
  649. package/dist/tools/v2/hr_zones.js +0 -24
  650. package/dist/tools/v2/hr_zones.js.map +0 -1
  651. package/dist/tools/v2/journal_autopop.js +0 -19
  652. package/dist/tools/v2/journal_autopop.js.map +0 -1
  653. package/dist/tools/v2/journal_catalog.js +0 -44
  654. package/dist/tools/v2/journal_catalog.js.map +0 -1
  655. package/dist/tools/v2/leaderboard.js +0 -79
  656. package/dist/tools/v2/leaderboard.js.map +0 -1
  657. package/dist/tools/v2/lift_catalog.js +0 -47
  658. package/dist/tools/v2/lift_catalog.js.map +0 -1
  659. package/dist/tools/v2/lift_custom_exercise.js +0 -108
  660. package/dist/tools/v2/lift_custom_exercise.js.map +0 -1
  661. package/dist/tools/v2/lift_history.js +0 -39
  662. package/dist/tools/v2/lift_history.js.map +0 -1
  663. package/dist/tools/v2/lift_progression.js +0 -30
  664. package/dist/tools/v2/lift_progression.js.map +0 -1
  665. package/dist/tools/v2/lift_prs.js +0 -21
  666. package/dist/tools/v2/lift_prs.js.map +0 -1
  667. package/dist/tools/v2/lift_template_save.js +0 -83
  668. package/dist/tools/v2/lift_template_save.js.map +0 -1
  669. package/dist/tools/v2/live_hr.js +0 -21
  670. package/dist/tools/v2/live_hr.js.map +0 -1
  671. package/dist/tools/v2/live_state.js +0 -21
  672. package/dist/tools/v2/live_state.js.map +0 -1
  673. package/dist/tools/v2/live_stress.js +0 -22
  674. package/dist/tools/v2/live_stress.js.map +0 -1
  675. package/dist/tools/v2/performance_assessment.js +0 -38
  676. package/dist/tools/v2/performance_assessment.js.map +0 -1
  677. package/dist/tools/v2/sleep_need.js +0 -21
  678. package/dist/tools/v2/sleep_need.js.map +0 -1
  679. package/dist/tools/v2/sports_catalog.js +0 -26
  680. package/dist/tools/v2/sports_catalog.js.map +0 -1
  681. package/dist/tools/v2/symptom_log.js +0 -72
  682. package/dist/tools/v2/symptom_log.js.map +0 -1
  683. package/dist/tools/v2/today.js +0 -30
  684. package/dist/tools/v2/today.js.map +0 -1
  685. package/dist/tools/v2/workout.js +0 -23
  686. package/dist/tools/v2/workout.js.map +0 -1
  687. package/dist/whoop/build_lift_body.js +0 -67
  688. package/dist/whoop/build_lift_body.js.map +0 -1
  689. package/dist/whoop/session_state.js +0 -34
  690. package/dist/whoop/session_state.js.map +0 -1
  691. package/dist/whoop/types.js +0 -82
  692. package/dist/whoop/types.js.map +0 -1
  693. package/src/data/endpoints.ts +0 -319
  694. package/src/lib/format.ts +0 -27
  695. package/src/lib/stats.ts +0 -35
  696. package/src/projections/calendar.ts +0 -46
  697. package/src/projections/communities.ts +0 -135
  698. package/src/projections/cycle.ts +0 -85
  699. package/src/projections/hr_zones.ts +0 -43
  700. package/src/projections/journal.ts +0 -55
  701. package/src/projections/leaderboard.ts +0 -49
  702. package/src/projections/lift_exercise.ts +0 -29
  703. package/src/projections/lift_history.ts +0 -140
  704. package/src/projections/lift_library.ts +0 -70
  705. package/src/projections/lift_progression.ts +0 -138
  706. package/src/projections/lift_prs.ts +0 -23
  707. package/src/projections/live_hr.ts +0 -21
  708. package/src/projections/live_state.ts +0 -28
  709. package/src/projections/live_stress.ts +0 -13
  710. package/src/projections/performance_assessment.ts +0 -19
  711. package/src/projections/profile.ts +0 -71
  712. package/src/projections/recovery.ts +0 -133
  713. package/src/projections/sleep_need.ts +0 -36
  714. package/src/projections/smart_alarm.ts +0 -70
  715. package/src/projections/strain.ts +0 -131
  716. package/src/projections/stress.ts +0 -95
  717. package/src/projections/today.ts +0 -166
  718. package/src/projections/trend.ts +0 -149
  719. package/src/projections/workouts.ts +0 -36
  720. package/src/schemas/calendar.ts +0 -13
  721. package/src/schemas/communities.ts +0 -56
  722. package/src/schemas/compare.ts +0 -17
  723. package/src/schemas/leaderboard.ts +0 -26
  724. package/src/schemas/live.ts +0 -31
  725. package/src/schemas/performance.ts +0 -13
  726. package/src/schemas/profile.ts +0 -40
  727. package/src/schemas/recovery.ts +0 -28
  728. package/src/schemas/settings.ts +0 -30
  729. package/src/schemas/sleep_need.ts +0 -16
  730. package/src/schemas/smart_alarm.ts +0 -40
  731. package/src/schemas/strain.ts +0 -25
  732. package/src/schemas/stress.ts +0 -17
  733. package/src/schemas/today.ts +0 -39
  734. package/src/schemas/trend.ts +0 -53
  735. package/src/schemas/womens_health.ts +0 -26
  736. package/src/tools/v2/activity_create.ts +0 -74
  737. package/src/tools/v2/behavior_impact.ts +0 -39
  738. package/src/tools/v2/communities.ts +0 -65
  739. package/src/tools/v2/compare.ts +0 -83
  740. package/src/tools/v2/endpoints.ts +0 -32
  741. package/src/tools/v2/hidden_metric.ts +0 -33
  742. package/src/tools/v2/hr_zones.ts +0 -29
  743. package/src/tools/v2/journal_autopop.ts +0 -26
  744. package/src/tools/v2/journal_catalog.ts +0 -48
  745. package/src/tools/v2/leaderboard.ts +0 -92
  746. package/src/tools/v2/lift_catalog.ts +0 -48
  747. package/src/tools/v2/lift_custom_exercise.ts +0 -117
  748. package/src/tools/v2/lift_history.ts +0 -52
  749. package/src/tools/v2/lift_progression.ts +0 -34
  750. package/src/tools/v2/lift_prs.ts +0 -26
  751. package/src/tools/v2/lift_template_save.ts +0 -89
  752. package/src/tools/v2/live_hr.ts +0 -26
  753. package/src/tools/v2/live_state.ts +0 -26
  754. package/src/tools/v2/live_stress.ts +0 -27
  755. package/src/tools/v2/performance_assessment.ts +0 -44
  756. package/src/tools/v2/sleep_need.ts +0 -26
  757. package/src/tools/v2/sports_catalog.ts +0 -32
  758. package/src/tools/v2/symptom_log.ts +0 -78
  759. package/src/tools/v2/today.ts +0 -35
  760. package/src/tools/v2/workout.ts +0 -28
  761. package/src/whoop/build_lift_body.ts +0 -84
  762. package/src/whoop/session_state.ts +0 -41
  763. package/src/whoop/types.ts +0 -89
package/dist/cli/ui.js CHANGED
@@ -1,512 +1,761 @@
1
- // Shared CLI primitives: colors, subprocess runner, HTTP ping, interactive
2
- // prompts, and small helpers used by both the command dispatcher (index.ts)
3
- // and the guided setup flows (setup.ts).
4
- import { spawn, spawnSync } from "node:child_process";
1
+ // The CLI's visual language: one small set of primitives every screen is built
2
+ // from, so `totem local`, `totem cloud`, `totem auth`, `totem update` and the
3
+ // rest read as one tool. It is plain on purpose, like the CLIs people already
4
+ // use (gh, fly, vercel): text first, colour as a seasoning, no boxes or rails.
5
+ // The one picture is the logo, at the top of the big flows.
6
+ //
7
+ // banner the logo (rasterized from the SVG) beside a title: home, cloud, local
8
+ // header "totem <command>" and a one-line purpose, at the top of a command
9
+ // step "[2/6] Secrets": where you are in a flow
10
+ // section a bold title inside a screen
11
+ // ok/warn/fail/info one-line results, each led by a mark: "✓ Deployed [1m 42s]"
12
+ // para/hint wrapped prose: what is happening, what to do now
13
+ // rows aligned "Key: value" facts
14
+ // code something to paste, alone on its line
15
+ // next "Next" and what to do now
16
+ // problem what went wrong + the exact commands that fix it
17
+ // task a spinner with elapsed time for anything slow
18
+ // select/confirm/text/hidden the four prompts
19
+ //
20
+ // Rendering is separate from effects. `kit(style)` returns pure functions that
21
+ // turn data into lines; `Ui` writes those lines somewhere and asks questions.
22
+ // A screen can therefore be rendered in a test with a fixed Style and no
23
+ // terminal. Nothing here spawns a process or touches the network (see sys.ts).
24
+ //
25
+ // Rules the primitives enforce:
26
+ // - 80 columns at most, less on a narrow terminal; prose wraps, pasteable
27
+ // lines never get a border or a prefix.
28
+ // - Colour is decoration only: every state is also a glyph and a word. It
29
+ // is off for NO_COLOR, TERM=dumb and anything that isn't a terminal. The
30
+ // logo is only drawn where there is colour.
31
+ // - One icy palette (see "colour"), bold and dim, nothing else. Exact where
32
+ // the terminal draws 24-bit colour, the nearest of 256 otherwise, the basic
33
+ // colours nearest in meaning on a basic terminal, and darker when the
34
+ // terminal says its background is light.
35
+ // - ASCII glyphs where Unicode can't be trusted (legacy Windows consoles,
36
+ // TERM=dumb/linux, a non-UTF-8 locale).
5
37
  import { createInterface } from "node:readline/promises";
6
- import { randomBytes } from "node:crypto";
7
- import { request as httpsRequest } from "node:https";
8
- import { existsSync } from "node:fs";
9
- import { resolve } from "node:path";
10
- export const useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
11
- // Modern truecolor palette (Tailwind-400-ish) — vivid but easy on a dark terminal.
12
- const ANSI = {
13
- reset: "\x1b[0m",
14
- bold: "\x1b[1m",
15
- dim: "\x1b[2m",
16
- brand: "\x1b[38;2;235;235;235m",
17
- brandDim: "\x1b[38;2;150;150;150m",
18
- gray: "\x1b[38;2;128;128;128m",
19
- white: "\x1b[38;2;245;245;245m",
20
- green: "\x1b[38;2;52;211;153m", // emerald
21
- red: "\x1b[38;2;248;113;113m", // red
22
- yellow: "\x1b[38;2;251;191;36m", // amber
23
- cyan: "\x1b[38;2;34;211;238m", // cyan
24
- violet: "\x1b[38;2;167;139;250m", // violet
25
- pink: "\x1b[38;2;244;114;182m", // pink
38
+ import { Writable } from "node:stream";
39
+ import { stripVTControlCharacters } from "node:util";
40
+ import { logoPixels } from "./logo.js";
41
+ const set = (v) => v !== undefined && v !== "";
42
+ export function detectStyle(stream = process.stdout, env = process.env, platform = process.platform) {
43
+ const color = set(env.NO_COLOR) ? false
44
+ : set(env.FORCE_COLOR) && env.FORCE_COLOR !== "0" ? true
45
+ : env.TERM === "dumb" ? false
46
+ : Boolean(stream.isTTY);
47
+ const locale = env.LC_ALL || env.LC_CTYPE || env.LANG || "";
48
+ const unicode = env.TOTEM_ASCII === "1" ? false
49
+ : env.TERM === "dumb" || env.TERM === "linux" ? false
50
+ // Windows: only terminals known to render UTF-8 (Windows Terminal, VS Code,
51
+ // ConEmu, anything that sets TERM). The legacy console gets ASCII.
52
+ : platform === "win32" ? Boolean(env.WT_SESSION || env.TERM_PROGRAM || env.ConEmuTask || env.TERM)
53
+ : locale === "" || /utf-?8/i.test(locale);
54
+ const columns = stream.isTTY && stream.columns ? stream.columns : 80;
55
+ const palette = /^(truecolor|24bit)$/i.test(env.COLORTERM ?? "") || TRUECOLOR_APPS.has(env.TERM_PROGRAM ?? "") || set(env.WT_SESSION) ? "truecolor"
56
+ : /256/.test(env.TERM ?? "") ? "256"
57
+ : "basic";
58
+ // COLORFGBG is "fg;bg" (sometimes "fg;default;bg"); 7 and 15 are the light greys and white.
59
+ const bg = (env.COLORFGBG ?? "").split(";").pop();
60
+ return { color, unicode, width: Math.max(40, Math.min(80, columns)), palette, light: bg === "7" || bg === "15" };
61
+ }
62
+ /** Terminals that draw 24-bit colour without saying so in COLORTERM. */
63
+ const TRUECOLOR_APPS = new Set(["iTerm.app", "WezTerm", "ghostty", "vscode", "Hyper"]);
64
+ export const PLAIN = { color: false, unicode: true, width: 80 };
65
+ const UNICODE = {
66
+ ok: "✓", fail: "✗", warn: "!", info: "•", arrow: "→", pointer: "›", ask: "?", dot: "·", ellipsis: "…", dash: "–",
67
+ spinner: ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"],
68
+ };
69
+ const ASCII = {
70
+ ok: "+", fail: "x", warn: "!", info: "-", arrow: ">", pointer: ">", ask: "?", dot: "-", ellipsis: "...", dash: "-",
71
+ spinner: ["-", "\\", "|", "/"],
26
72
  };
27
- function wrap(code, s) {
28
- return useColor ? `${code}${s}${ANSI.reset}` : s;
73
+ export const glyphs = (style) => (style.unicode ? UNICODE : ASCII);
74
+ // [r, g, b] and the nearest xterm-256 colour, on a dark and on a light background.
75
+ const SHADES = {
76
+ dark: { ice: ["183;211;242", 153, 94], fold: ["122;156;198", 110, 34] },
77
+ light: { ice: ["122;156;198", 110, 34], fold: ["79;111;153", 67, 34] },
78
+ };
79
+ /** The SGR code for a brand shade: ice #B7D3F2 (default) or fold #7A9CC6, a step darker on a light background. `bg` paints the cell behind. */
80
+ export function brandSgr(style, shade = "ice", bg = false) {
81
+ const [rgb, x256, basic] = SHADES[style.light ? "light" : "dark"][shade];
82
+ if (style.palette === "truecolor")
83
+ return `${bg ? 48 : 38};2;${rgb}`;
84
+ if (style.palette === "256")
85
+ return `${bg ? 48 : 38};5;${x256}`;
86
+ return String(bg ? basic + 10 : basic);
29
87
  }
30
- export const c = {
31
- brand: (s) => wrap(ANSI.brand, s),
32
- brandDim: (s) => wrap(ANSI.brandDim, s),
33
- gray: (s) => wrap(ANSI.gray, s),
34
- white: (s) => wrap(ANSI.white, s),
35
- green: (s) => wrap(ANSI.green, s),
36
- red: (s) => wrap(ANSI.red, s),
37
- yellow: (s) => wrap(ANSI.yellow, s),
38
- cyan: (s) => wrap(ANSI.cyan, s),
39
- violet: (s) => wrap(ANSI.violet, s),
40
- pink: (s) => wrap(ANSI.pink, s),
41
- bold: (s) => wrap(ANSI.bold, s),
42
- dim: (s) => wrap(ANSI.dim, s),
88
+ /**
89
+ * The palette: glacier colours beside the brand's ice, chosen in OKLCH so
90
+ * their lightness is even and no one colour shouts over the others. Warnings
91
+ * and failures stay warm, so a problem still reads as one. The terminal gets
92
+ * these hues at a lightness it can read: lighter on a dark background
93
+ * (onDark), darker on a light one (onLight).
94
+ */
95
+ export const PALETTE = {
96
+ lead: "#71C9FA", // glacier blue
97
+ command: "#72DEE4", // arctic cyan
98
+ link: "#B2B8F7", // frost lavender
99
+ secret: "#E5F4FE", // snow
100
+ ok: "#88E1D0", // glacial mint
101
+ warn: "#F0D49B", // winter sun
102
+ fail: "#EB8A99", // frostbite rose
43
103
  };
44
- // Spawn a command, inheriting stdio. Resolves with the exit code.
45
- export function run(cmd, args, opts = {}) {
46
- return new Promise((res) => {
47
- const child = spawn(cmd, args, { stdio: "inherit", ...opts });
48
- child.on("exit", (code, signal) => {
49
- if (signal) {
50
- console.error(c.red(`\nKilled by signal ${signal}`));
51
- res(128);
52
- return;
53
- }
54
- res(code ?? 1);
55
- });
56
- child.on("error", (err) => {
57
- console.error(c.red("Failed to spawn:"), err.message);
58
- res(1);
59
- });
60
- });
104
+ /** A basic terminal has eight colours and its own idea of them: the nearest by meaning. */
105
+ const BASIC_ROLE = { lead: 36, command: 37, link: 36, secret: 37, ok: 32, warn: 33, fail: 31 };
106
+ const hexRgb = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));
107
+ /** Relative luminance (WCAG): 0 for black, 1 for white. */
108
+ const luminance = (rgb) => {
109
+ const [r, g, b] = rgb.map((v) => { const c = v / 255; return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; });
110
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
111
+ };
112
+ /** WCAG contrast between two luminances: 1 (none) to 21 (black on white). */
113
+ const contrast = (a, b) => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
114
+ /** The dark background colours are judged against: #1E1E1E, a typical dark terminal theme. */
115
+ const DARK_BG = luminance([30, 30, 30]);
116
+ /**
117
+ * The same hue at the first lightness, walking from its own in steps of
118
+ * `step`, that has 4.5:1 contrast with a background of luminance `bg`
119
+ * (WCAG's bar for text).
120
+ */
121
+ function readableOn([r, g, b], bg, step) {
122
+ const [R, G, B] = [r / 255, g / 255, b / 255];
123
+ const max = Math.max(R, G, B), min = Math.min(R, G, B), l = (max + min) / 2, d = max - min;
124
+ const s = d === 0 ? 0 : d / (1 - Math.abs(2 * l - 1));
125
+ // The hue as a sixth of the circle, 0 to 6 (a remainder in JS keeps its sign, so wrap it).
126
+ const h = d === 0 ? 0 : max === R ? (((G - B) / d) % 6 + 6) % 6 : max === G ? (B - R) / d + 2 : (R - G) / d + 4;
127
+ const fromHsl = (L) => {
128
+ const C = (1 - Math.abs(2 * L - 1)) * s, X = C * (1 - Math.abs((h % 2) - 1)), m = L - C / 2;
129
+ const [r1, g1, b1] = h < 1 ? [C, X, 0] : h < 2 ? [X, C, 0] : h < 3 ? [0, C, X] : h < 4 ? [0, X, C] : h < 5 ? [X, 0, C] : [C, 0, X];
130
+ return [r1, g1, b1].map((v) => Math.round((v + m) * 255));
131
+ };
132
+ for (let L = l; L >= 0 && L <= 1; L += step) {
133
+ const out = fromHsl(L);
134
+ if (contrast(luminance(out), bg) >= 4.5)
135
+ return out;
136
+ }
137
+ return step < 0 ? [0, 0, 0] : [255, 255, 255];
61
138
  }
62
- // Run a command and capture stdout (for parsing CLI output like a deploy URL).
63
- export function capture(cmd, args, opts = {}) {
64
- const r = spawnSync(cmd, args, { encoding: "utf8", ...opts });
65
- return { code: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
139
+ /** Dark enough to read on white. Yellow and lime come down much further than violet. */
140
+ export const onLight = (rgb) => readableOn(rgb, 1, -0.01);
141
+ /** Light enough to read on a dark terminal. Electric indigo comes up to a lavender. */
142
+ export const onDark = (rgb) => readableOn(rgb, DARK_BG, 0.01);
143
+ /** The nearest of xterm's 256 colours: the 6×6×6 cube or the grey ramp. */
144
+ export function xterm256([r, g, b]) {
145
+ const levels = [0, 95, 135, 175, 215, 255];
146
+ const near = (v) => levels.reduce((best, l, i) => (Math.abs(l - v) < Math.abs(levels[best] - v) ? i : best), 0);
147
+ const [ri, gi, bi] = [near(r), near(g), near(b)];
148
+ const grey = Math.max(0, Math.min(23, Math.round(((r + g + b) / 3 - 8) / 10)));
149
+ const dist = (x) => (x[0] - r) ** 2 + (x[1] - g) ** 2 + (x[2] - b) ** 2;
150
+ const cube = [levels[ri], levels[gi], levels[bi]];
151
+ const g8 = 8 + 10 * grey;
152
+ return dist(cube) <= dist([g8, g8, g8]) ? 16 + 36 * ri + 6 * gi + bi : 232 + grey;
66
153
  }
67
- // Async sibling of capture(). `capture` uses spawnSync, which BLOCKS the event
68
- // loop for the whole subprocess — so a spinner (setInterval) can't animate over
69
- // it. For slow, network-bound lookups (gcloud/railway/fly API calls) run them
70
- // through this instead and wrap with withSpinner() so the UI stays alive.
71
- export function captureAsync(cmd, args, opts = {}) {
72
- const { input, ...spawnOpts } = opts;
73
- return new Promise((res) => {
74
- // input set → pipe stdin so secrets can be fed over a pipe (off the argv,
75
- // which is visible in `ps`/`/proc`); otherwise ignore stdin as before.
76
- const child = spawn(cmd, args, { stdio: [input !== undefined ? "pipe" : "ignore", "pipe", "pipe"], ...spawnOpts });
77
- let stdout = "";
78
- let stderr = "";
79
- child.stdout?.on("data", (d) => (stdout += d.toString()));
80
- child.stderr?.on("data", (d) => (stderr += d.toString()));
81
- child.on("error", () => res({ code: 1, stdout, stderr }));
82
- child.on("close", (code) => res({ code: code ?? 1, stdout, stderr }));
83
- if (input !== undefined) {
84
- child.stdin?.write(input);
85
- child.stdin?.end();
86
- }
87
- });
154
+ /** The SGR code for one of the palette's colours. */
155
+ export function roleSgr(style, role) {
156
+ if (style.palette !== "truecolor" && style.palette !== "256")
157
+ return String(BASIC_ROLE[role]);
158
+ const base = hexRgb(PALETTE[role]);
159
+ const rgb = style.light ? onLight(base) : onDark(base);
160
+ return style.palette === "truecolor" ? `38;2;${rgb.join(";")}` : `38;5;${xterm256(rgb)}`;
88
161
  }
89
- // ── spinner ──────────────────────────────────────────────────────────────
90
- // A braille spinner for the "thinking" gaps where we do work with no visible
91
- // output (our own network lookups, HTTP polling, backoff waits). Subprocesses
92
- // run with inherited stdio print their own progress, so they don't need this.
93
- // IMPORTANT: a spinner only animates while the event loop is free — pair it
94
- // with async work (await captureAsync / httpGet / setTimeout), never spawnSync.
95
- const SPIN_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
96
- export function spin(message) {
97
- // Message can be a live function (e.g. an elapsed-time counter), re-evaluated
98
- // on every frame.
99
- const msg = () => (typeof message === "function" ? message() : message);
100
- // No TTY (piped/CI): no cursor tricks — print the message once, plainly.
101
- if (!process.stdout.isTTY) {
102
- console.log(c.gray(` ${msg()}…`));
103
- return { stop: (final) => { if (final)
104
- console.log(final); } };
105
- }
106
- let i = 0;
107
- process.stdout.write("\x1b[?25l"); // hide cursor
108
- const draw = () => {
109
- process.stdout.write(`\r\x1b[2K${c.cyan(SPIN_FRAMES[i % SPIN_FRAMES.length])} ${c.gray(msg())}`);
110
- i++;
111
- };
112
- draw();
113
- const timer = setInterval(draw, 80);
162
+ export function paint(style) {
163
+ const sgr = (open, close) => (s) => (style.color && s ? `\x1b[${open}m${s}\x1b[${close}m` : s);
164
+ const role = (r) => sgr(roleSgr(style, r), 39);
114
165
  return {
115
- stop: (final) => {
116
- clearInterval(timer);
117
- process.stdout.write("\r\x1b[2K\x1b[?25h"); // clear line + restore cursor
118
- if (final)
119
- console.log(final);
120
- },
166
+ bold: sgr(1, 22), dim: sgr(2, 22), red: role("fail"), green: role("ok"), yellow: role("warn"),
167
+ brand: sgr(brandSgr(style), 39),
168
+ accent: role("command"), ask: role("lead"), link: role("link"), secret: sgr(`1;${roleSgr(style, "secret")}`, "39;22"),
121
169
  };
122
170
  }
123
- // Run async work under a spinner; always stops the spinner, even on throw.
124
- export async function withSpinner(message, fn) {
125
- const s = spin(message);
126
- try {
127
- return await fn();
128
- }
129
- finally {
130
- s.stop();
171
+ // ── text ────────────────────────────────────────────────────────────────────
172
+ /** Columns a string takes on screen (escape sequences don't count). */
173
+ export const visibleWidth = (s) => [...stripVTControlCharacters(s)].length;
174
+ export const padEnd = (s, width) => s + " ".repeat(Math.max(0, width - visibleWidth(s)));
175
+ /**
176
+ * Word-wrap to `width` columns. A word longer than the line (a URL, a path, a
177
+ * command) stays whole on its own line: it is never cut, because a cut value
178
+ * can't be pasted.
179
+ */
180
+ export function wrap(text, width) {
181
+ const out = [];
182
+ for (const paragraph of text.split("\n")) {
183
+ let line = "";
184
+ for (const word of paragraph.split(/\s+/).filter(Boolean)) {
185
+ if (line === "")
186
+ line = word;
187
+ else if (visibleWidth(line) + 1 + visibleWidth(word) <= width)
188
+ line += " " + word;
189
+ else {
190
+ out.push(line);
191
+ line = word;
192
+ }
193
+ }
194
+ out.push(line);
131
195
  }
196
+ return out;
132
197
  }
133
- // A visible backoff: spin for `ms` so a silent wait doesn't look like a hang.
134
- export async function pause(ms, message) {
135
- const s = spin(message);
136
- await new Promise((r) => setTimeout(r, ms));
137
- s.stop();
198
+ /**
199
+ * wrap(), keeping a list marker hanging: the lines after "1. " or "- " start
200
+ * under the text, not under the marker.
201
+ */
202
+ export function wrapHanging(text, width) {
203
+ const marker = text.match(/^(\d+\.|[-*])\s+/)?.[0];
204
+ if (!marker)
205
+ return wrap(text, width);
206
+ const pad = " ".repeat(marker.length);
207
+ return wrap(text.slice(marker.length), width - marker.length).map((l, i) => (i === 0 ? marker + l : pad + l));
138
208
  }
139
- // Is a CLI tool on PATH? Uses which/where (real executables) rather than the
140
- // `command -v` shell builtin, so we avoid `shell: true` — which both triggers
141
- // Node 25's DEP0190 warning and is an injection risk.
142
- export function commandExists(cmd) {
143
- const probe = process.platform === "win32" ? "where" : "which";
144
- const r = spawnSync(probe, [cmd], { encoding: "utf8" });
145
- return (r.status ?? 1) === 0 && (r.stdout ?? "").trim().length > 0;
209
+ /** Cut to `width` columns with an ellipsis: for output that must stay one line per line. */
210
+ export function truncate(text, width, ellipsis = "…") {
211
+ return visibleWidth(text) <= width ? text : [...text].slice(0, Math.max(0, width - ellipsis.length)).join("") + ellipsis;
146
212
  }
147
- // 256-bit random hex token (for MCP_AUTH_TOKEN / signing secret).
148
- export function genToken() {
149
- return randomBytes(32).toString("hex");
213
+ /** "a", "a and b", "a, b and c". */
214
+ export function listOf(items) {
215
+ return items.length <= 1 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
150
216
  }
151
- // Cryptographically-random password. Rejection sampling over an unambiguous
152
- // alphabet (no 0/O/1/l/I) plus symbols for entropy — safe to read/retype.
153
- export function genPassword(len = 18) {
154
- const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*-_=+";
155
- const max = Math.floor(256 / alphabet.length) * alphabet.length; // reject modulo bias
156
- let out = "";
157
- while (out.length < len) {
158
- const b = randomBytes(1)[0];
159
- if (b < max)
160
- out += alphabet[b % alphabet.length];
161
- }
162
- return out;
217
+ /** "42s", "1m 42s"; empty under a second. */
218
+ export function duration(ms) {
219
+ const s = Math.round(ms / 1000);
220
+ if (s < 1)
221
+ return "";
222
+ return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, "0")}s`;
163
223
  }
164
- // Best-effort copy to the OS clipboard. Returns true on success, false if no
165
- // clipboard tool is available (never throws).
166
- export function copyToClipboard(text) {
167
- const [cmd, args] = process.platform === "darwin" ? ["pbcopy", []]
168
- : process.platform === "win32" ? ["clip", []]
169
- : ["xclip", ["-selection", "clipboard"]];
170
- try {
171
- const r = spawnSync(cmd, args, { input: text });
172
- return (r.status ?? 1) === 0;
173
- }
174
- catch {
175
- return false;
176
- }
224
+ /** An ISO timestamp as "2026-11-21 23:10 UTC" (the same on every machine). */
225
+ export function when(iso) {
226
+ if (!iso)
227
+ return "unknown";
228
+ const t = new Date(iso);
229
+ return Number.isNaN(t.getTime()) ? iso : `${t.toISOString().slice(0, 16).replace("T", " ")} UTC`;
177
230
  }
178
- // Run a bundled script resiliently. A published install (`npm install -g`)
179
- // ships the compiled `dist/*.js` and only runtime deps — no `tsx`/`typescript`.
180
- // A dev checkout has `tsx` + the TypeScript source. Prefer whichever fits:
181
- // dist+node by default (works everywhere), source+tsx when `preferSource` is set
182
- // (live dev, picks up edits without a rebuild). `relNoExt` is relative to src/
183
- // or dist/ without extension, e.g. "scripts/cognito_bootstrap" or "server".
184
- export function runScript(root, relNoExt, args = [], opts = {}) {
185
- const { preferSource = false, ...spawnOpts } = opts;
186
- const distJs = resolve(root, "dist", `${relNoExt}.js`);
187
- const srcTs = resolve(root, "src", `${relNoExt}.ts`);
188
- const tsx = resolve(root, "node_modules", ".bin", "tsx");
189
- const viaDist = [process.execPath, distJs];
190
- const viaTsx = [tsx, srcTs];
191
- const order = preferSource ? [viaTsx, viaDist] : [viaDist, viaTsx];
192
- for (const [bin, script] of order) {
193
- const binOk = bin === process.execPath || existsSync(bin);
194
- if (binOk && existsSync(script))
195
- return run(bin, [script, ...args], { cwd: root, ...spawnOpts });
231
+ /** A path as one shell word: quoted when it has a space or a quote in it. */
232
+ export const shellPath = (p) => (/[\s'"]/.test(p) ? `"${p.replace(/"/g, '\\"')}"` : p);
233
+ /**
234
+ * One shell command as lines of at most `width` columns, split between
235
+ * arguments with a trailing backslash so the block still pastes as one
236
+ * command. Windows shells have no shared continuation character, so there the
237
+ * command stays on one line.
238
+ */
239
+ export function shellLines(words, width, platform = process.platform) {
240
+ const one = words.join(" ");
241
+ if (platform === "win32" || visibleWidth(one) <= width)
242
+ return [one];
243
+ const lines = [];
244
+ let line = "";
245
+ for (const word of words) {
246
+ const candidate = line === "" ? word : `${line} ${word}`;
247
+ // Leave room for the " \" that marks a continued line.
248
+ if (line !== "" && visibleWidth(candidate) + 2 > width) {
249
+ lines.push(line);
250
+ line = " " + word;
251
+ }
252
+ else
253
+ line = candidate;
196
254
  }
197
- console.error(c.red(`Can't run ${relNoExt}: need either a built dist/ or the tsx dev dependency.`));
198
- console.error(c.gray("Run ") + c.bold("npm install && totem build") + c.gray(" in a source checkout, or reinstall the published package."));
199
- return Promise.resolve(1);
255
+ lines.push(line);
256
+ return lines.map((l, i) => (i < lines.length - 1 ? `${l} \\` : l));
200
257
  }
201
- // Ensure a CLI tool is on PATH; if not, offer to install it (with permission).
202
- // Tries brew → npm → install script, in that order, based on what's available.
203
- // Note: a freshly installed tool often isn't on this process's PATH yet, so we
204
- // re-check and, if still missing, tell the user to re-run in a new shell.
205
- export async function ensureCli(name, opts) {
206
- if (commandExists(name))
207
- return true;
208
- console.log(c.yellow(` ${name} isn't installed.`));
209
- // Collect the install methods that are actually available and try them in
210
- // order (brew → npm → script), falling THROUGH if one fails (e.g. a brew
211
- // formula doesn't exist) instead of giving up after the first.
212
- const methods = [];
213
- if (opts.brewPkg && commandExists("brew"))
214
- methods.push(["brew", ["install", opts.brewPkg]]);
215
- if (opts.npmPkg && commandExists("npm"))
216
- methods.push(["npm", ["install", "-g", opts.npmPkg]]);
217
- if (opts.scriptUrl)
218
- methods.push(["sh", ["-c", `curl -fsSL ${opts.scriptUrl} | sh`]]);
219
- if (methods.length === 0) {
220
- console.log(c.gray(` Install it manually: ${opts.manualHint}`));
221
- return false;
222
- }
223
- for (const [cmd, args] of methods) {
224
- console.log(c.gray(` $ ${cmd} ${args.join(" ")}`));
225
- if (!(await promptYesNo(`Install ${name} via \`${cmd}\`?`, true)))
226
- continue;
227
- if ((await run(cmd, args)) === 0 && commandExists(name))
228
- return true;
229
- console.log(c.yellow(` ${cmd} didn't get ${name} working${methods.length > 1 ? " — trying the next method" : ""}.`));
230
- }
231
- if (!commandExists(name)) {
232
- console.log(c.yellow(` ${name} still isn't on this shell's PATH.`));
233
- console.log(c.gray(` ${opts.manualHint} — or open a new terminal and re-run.`));
234
- return false;
235
- }
236
- return true;
258
+ /** Columns the logo takes, and the gap after it. */
259
+ const LOGO_COLS = 12;
260
+ const LOGO_ROWS = 5;
261
+ const LOGO_GAP = 3;
262
+ /** An http(s) address inside prose, without trailing punctuation. Capturing, so split() keeps it. */
263
+ const URL_IN_TEXT = /(https?:\/\/[^\s)]*[^\s).,;:'"])/;
264
+ /** A time a step took ("4s", "1m 42s"): shown in brackets, the rest of a detail in parentheses. */
265
+ const TIME = /^\d+(m \d{2})?s$/;
266
+ export function kit(style) {
267
+ const g = glyphs(style);
268
+ const c = paint(style);
269
+ const W = style.width;
270
+ const symbol = { ok: c.green(g.ok), fail: c.red(g.fail), warn: c.yellow(g.warn), info: c.dim(g.info) };
271
+ const logo = (style.logo ?? (style.color && style.unicode)) && style.unicode && W >= 56;
272
+ // Addresses in the link colour wherever they turn up, the rest in `rest`.
273
+ // Text that already carries colour is left as it is.
274
+ const urls = (text, rest = (s) => s) => text.includes("\x1b[") ? text : text.split(URL_IN_TEXT).map((part, i) => (i % 2 ? c.link(part) : part ? rest(part) : "")).join("");
275
+ // Commands inside prose in the command colour: "…: totem status", "run: codex mcp login whoop".
276
+ const commands = (text) => text.replace(/(: |run: )(totem [a-z][\w -]*|[a-z]+ mcp [\w -]+)(?=\)|\.?$)/, (_m, lead, cmd) => `${lead}${c.accent(cmd.trimEnd())}`);
277
+ const mark = (kind, text, detail) => {
278
+ const lines = wrap(text, W - 2).map((line, i) => `${i === 0 ? symbol[kind] : " "} ${line}`);
279
+ if (!detail)
280
+ return lines;
281
+ // "✓ Deployed [1m 42s]", "✓ Signed in to Fly (you@example.com)"; on its own line when it doesn't fit.
282
+ const tail = TIME.test(detail) ? `[${detail}]` : `(${detail})`;
283
+ const last = lines[lines.length - 1];
284
+ if (visibleWidth(last) + 1 + visibleWidth(tail) <= W)
285
+ lines[lines.length - 1] = `${last} ${urls(tail, c.dim)}`;
286
+ else
287
+ for (const d of wrap(detail, W - 2))
288
+ lines.push(` ${urls(d, c.dim)}`);
289
+ return lines;
290
+ };
291
+ const rows = (pairs, indent = 2) => {
292
+ const keyWidth = Math.max(...pairs.map(([k]) => visibleWidth(k))) + 3;
293
+ const pad = " ".repeat(indent);
294
+ return pairs.flatMap(([key, value]) => {
295
+ const lines = wrap(value, Math.max(16, W - indent - keyWidth));
296
+ return lines.map((line, i) => `${pad}${i === 0 ? c.dim(padEnd(`${key}:`, keyWidth)) : " ".repeat(keyWidth)}${urls(line)}`);
297
+ });
298
+ };
299
+ // "totem cloud": the brand word in ice, the whole title bold.
300
+ const name = (title) => {
301
+ const [brandWord, ...rest] = title.split(" ");
302
+ return c.bold(`${c.brand(brandWord)}${rest.length ? ` ${rest.join(" ")}` : ""}`);
303
+ };
304
+ const header = (title, subtitle) => [name(title), ...(subtitle ? wrap(subtitle, W).map((l) => c.dim(l)) : [])];
305
+ // Two pixels a cell: the upper in the foreground of a half block, the lower behind it.
306
+ const logoRows = () => {
307
+ const px = logoPixels(LOGO_COLS, LOGO_ROWS * 2);
308
+ const fg = (p, ch) => (style.color ? `\x1b[${brandSgr(style, p)}m${ch}\x1b[39m` : ch);
309
+ const cell = (top, bottom) => {
310
+ if (!top && !bottom)
311
+ return " ";
312
+ if (!top)
313
+ return fg(bottom, "▄");
314
+ if (!bottom)
315
+ return fg(top, "▀");
316
+ if (top === bottom)
317
+ return fg(top, "█");
318
+ return style.color ? `\x1b[${brandSgr(style, top)};${brandSgr(style, bottom, true)}m▀\x1b[39;49m` : "▀";
319
+ };
320
+ return Array.from({ length: LOGO_ROWS }, (_, r) => px[2 * r].map((top, x) => cell(top, px[2 * r + 1][x])).join(""));
321
+ };
322
+ return {
323
+ style, g, c, logo,
324
+ banner: (title, subtitle, meta) => {
325
+ if (!logo)
326
+ return header(title, subtitle);
327
+ const textWidth = W - 1 - LOGO_COLS - LOGO_GAP;
328
+ // The title on the logo's second row, the purpose and meta under it.
329
+ const text = ["", name(title), ...(subtitle ? wrap(subtitle, textWidth).map((l) => c.dim(l)) : []), ...(meta ? [c.dim(meta)] : [])];
330
+ const art = logoRows();
331
+ return Array.from({ length: Math.max(art.length, text.length) }, (_, i) => {
332
+ const left = ` ${art[i] ?? " ".repeat(LOGO_COLS)}`;
333
+ return text[i] ? `${left}${" ".repeat(LOGO_GAP)}${text[i]}` : art[i] ? left : "";
334
+ });
335
+ },
336
+ header,
337
+ step: (n, total, title) => [`${c.dim(`[${n}/${total}]`)} ${c.bold(title)}`],
338
+ section: (title) => [title.includes("\x1b[") ? c.bold(title) : urls(title, c.bold)],
339
+ question: (question, suffix = "") => `${c.ask(g.ask)} ${c.bold(question)}${suffix ? " " + c.dim(suffix) : ""}`,
340
+ answered: (question, answer) => `${c.ask(g.ask)} ${c.bold(question)} ${c.ask(answer)}`,
341
+ mark,
342
+ para: (text, indent = 0) => wrapHanging(text, W - indent).map((l) => " ".repeat(indent) + l),
343
+ hint: (text, indent = 2) => wrap(text, W - indent).map((l) => " ".repeat(indent) + c.dim(l)),
344
+ rows,
345
+ code: (lines, indent = 2) => lines.map((l) => " ".repeat(indent) + c.accent(l)),
346
+ next: (lines, title = "Next") => {
347
+ // Numbered steps keep their number in the lead colour, commands in theirs.
348
+ const body = lines.flatMap((l) => (l === "" ? [""] : wrapHanging(commands(urls(l)), W - 2).map((w) => w.replace(/^(\d+\.)(?= )/, (m) => c.ask(m)))));
349
+ return [c.bold(title), ...body.map((l) => (l === "" ? "" : ` ${l}`))];
350
+ },
351
+ problem: (what, opts = {}, indent = 0) => {
352
+ const pad = " ".repeat(indent);
353
+ const head = wrap(what, W - indent - 2).map((l, i) => `${pad}${i === 0 ? c.red(g.fail) : " "} ${c.bold(l)}`);
354
+ // A string is prose and wraps. An array is a command's own output, line by
355
+ // line: a long line continues indented, so where each one starts stays
356
+ // visible and nothing (the exit code at the end, say) is cut off.
357
+ const details = (Array.isArray(opts.detail)
358
+ ? opts.detail.flatMap((d) => wrap(d, W - indent - 4).map((l, i) => (i === 0 ? l : ` ${l}`)))
359
+ : opts.detail ? wrap(opts.detail, W - indent - 2) : [])
360
+ .map((l) => `${pad} ${c.dim(l)}`);
361
+ const fix = opts.fix ?? [];
362
+ const labelWidth = fix.length ? Math.max(...fix.map(([label]) => visibleWidth(label))) + 3 : 0;
363
+ const fixes = fix.map(([label, command]) => `${pad} ${padEnd(label, labelWidth)}${c.accent(command)}`);
364
+ return [...head, ...details, ...fixes];
365
+ },
366
+ };
237
367
  }
238
- // Open a URL in the default browser, cross-platform. Best-effort, never throws.
239
- export function openUrl(url) {
240
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
241
- const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
242
- try {
243
- spawnSync(cmd, args, { stdio: "ignore" });
368
+ // ── prompts ─────────────────────────────────────────────────────────────────
369
+ /**
370
+ * A question was asked and the input ended before an answer came (stdin closed
371
+ * or redirected from /dev/null, Ctrl-D at the prompt).
372
+ *
373
+ * No answer is not an answer: it must never be read as "take the default"
374
+ * (`totem cloud < /dev/null` once said yes to every deploy gate). Every prompt
375
+ * throws this instead, and the command stops.
376
+ */
377
+ export class InputClosedError extends Error {
378
+ question;
379
+ constructor(question) {
380
+ super("Input ended before the question was answered.");
381
+ this.question = question;
382
+ this.name = "InputClosedError";
244
383
  }
245
- catch { /* best-effort */ }
246
384
  }
247
- // GET a URL, resolve with {status, body}. Used for health + OAuth metadata checks.
248
- export function httpGet(url, timeoutMs = 12_000) {
249
- return new Promise((res) => {
250
- const u = new URL(url);
251
- const req = httpsRequest({ method: "GET", hostname: u.hostname, port: u.port || 443, path: u.pathname + u.search, headers: { "user-agent": "totem-setup" } }, (response) => {
252
- let body = "";
253
- response.setEncoding("utf8");
254
- response.on("data", (ch) => (body += ch));
255
- response.on("end", () => res({ status: response.statusCode ?? 0, body }));
256
- });
257
- req.setTimeout(timeoutMs, () => { req.destroy(); res({ status: 0, body: "" }); });
258
- req.on("error", () => res({ status: 0, body: "" }));
259
- req.end();
385
+ const pipedReaders = new WeakMap();
386
+ function pipedLine(signal) {
387
+ const stdin = process.stdin;
388
+ let state = pipedReaders.get(stdin);
389
+ if (!state) {
390
+ const fresh = { lines: [], waiters: [], ended: false };
391
+ const rl = createInterface({ input: stdin, terminal: false });
392
+ rl.on("line", (line) => { const w = fresh.waiters.shift(); if (w)
393
+ w(line);
394
+ else
395
+ fresh.lines.push(line); });
396
+ rl.on("close", () => { fresh.ended = true; for (const w of fresh.waiters.splice(0))
397
+ w(null); });
398
+ pipedReaders.set(stdin, fresh);
399
+ state = fresh;
400
+ }
401
+ if (signal?.aborted)
402
+ return Promise.resolve(null);
403
+ if (state.lines.length)
404
+ return Promise.resolve(state.lines.shift());
405
+ if (state.ended)
406
+ return Promise.resolve(null);
407
+ const waiting = state;
408
+ return new Promise((resolve) => {
409
+ // A withdrawn question gives up its place, so its line goes to the next one.
410
+ const take = (line) => { signal?.removeEventListener("abort", drop); resolve(line); };
411
+ const drop = () => { const i = waiting.waiters.indexOf(take); if (i >= 0)
412
+ waiting.waiters.splice(i, 1); resolve(null); };
413
+ waiting.waiters.push(take);
414
+ signal?.addEventListener("abort", drop, { once: true });
260
415
  });
261
416
  }
262
- export function ping(url, timeoutMs = 10_000) {
263
- return httpGet(url, timeoutMs).then((r) => {
264
- const ok = r.status >= 200 && r.status < 300;
265
- const label = ok ? c.green(`✓ ${r.status}`) : c.red(`✗ ${r.status || "timeout"}`);
266
- const preview = r.body.length > 100 ? r.body.slice(0, 97) + "..." : r.body;
267
- console.log(`${label} ${url} ${c.gray(preview.replace(/\s+/g, " ").trim())}`);
268
- return ok ? 0 : 1;
269
- });
417
+ /** A question taken back before anyone answered it (see Ui.confirmUntil). */
418
+ class Withdrawn extends Error {
270
419
  }
271
- // ── interactive prompts ─────────────────────────────────────────────────────
272
- // A fresh readline per question. Long-lived readlines break when a subprocess
273
- // in between (e.g. the build step) inherits stdin, so we open/close per ask.
274
- // On EOF (piped input) the question resolves empty instead of throwing.
275
- async function ask(query) {
276
- const rl = createInterface({ input: process.stdin, output: process.stdout });
277
- // Ctrl-C during a text prompt: readline swallows SIGINT (emits it on the
278
- // interface). Handle it here — restore the cursor, drop a line, exit.
279
- rl.on("SIGINT", () => { process.stderr.write("\x1b[?25h"); process.stdout.write("\n"); process.exit(130); });
280
- try {
281
- // Resolve "" if the stream closes (EOF) so the caller falls back to its
282
- // default instead of hanging.
283
- return await new Promise((resolve) => {
284
- rl.once("close", () => resolve(""));
285
- rl.question(query).then((a) => resolve(a.trim())).catch(() => resolve(""));
286
- });
420
+ const SHOW_CURSOR = "\x1b[?25h";
421
+ const HIDE_CURSOR = "\x1b[?25l";
422
+ const CLEAR_LINE = "\r\x1b[2K";
423
+ export class Ui {
424
+ style;
425
+ live;
426
+ canAsk;
427
+ write;
428
+ writeErr;
429
+ now;
430
+ kit;
431
+ constructor(opts = {}) {
432
+ this.style = opts.style ?? detectStyle();
433
+ this.kit = kit(this.style);
434
+ this.write = opts.write ?? ((text) => { process.stdout.write(text); });
435
+ this.writeErr = opts.writeErr ?? ((text) => { process.stderr.write(text); });
436
+ this.live = opts.live ?? (Boolean(process.stdout.isTTY) && Boolean(process.stdin.isTTY) && process.env.TERM !== "dumb");
437
+ this.canAsk = opts.canAsk ?? Boolean(process.stdin.isTTY);
438
+ this.now = opts.now ?? Date.now;
287
439
  }
288
- finally {
289
- rl.close();
440
+ // output ────────────────────────────────────────────────────────────────
441
+ blank = false;
442
+ /** One line. Two blank lines in a row become one, so primitives can each ask for air. */
443
+ line(text = "") {
444
+ if (text === "" && this.blank)
445
+ return;
446
+ this.blank = text === "";
447
+ this.write(text + "\n");
290
448
  }
291
- }
292
- // Kept for API compatibility; no-op now that prompts are per-call.
293
- export function closePrompts() { }
294
- export async function prompt(question, fallback = "") {
295
- const suffix = fallback ? c.gray(` [${fallback}]`) : "";
296
- const answer = await ask(`${c.violet("?")} ${c.white(question)}${suffix}${c.gray(" ›")} `);
297
- return answer || fallback;
298
- }
299
- // Like `ask`, but typed characters are NOT echoed — standard password-prompt
300
- // behavior, so a secret never appears on screen (or on camera). The override
301
- // lets the prompt itself and the commit newline through and swallows every
302
- // per-character echo; readline still captures the full value in its buffer.
303
- async function askHidden(query) {
304
- // Explicit raw-mode read: readline's _writeToOutput trick doesn't reliably
305
- // disable the TERMINAL's own echo, so the secret can still render. Here we set
306
- // raw mode ourselves (terminal echo off), read char-by-char, and echo nothing
307
- // — the password never appears on screen. Falls back to a normal line read
308
- // when there's no TTY to put in raw mode (piped/CI).
309
- const stdin = process.stdin;
310
- if (!(stdin.isTTY && typeof stdin.setRawMode === "function"))
311
- return ask(query);
312
- process.stdout.write(query);
313
- return new Promise((resolve) => {
314
- let buf = "";
315
- const cleanup = () => {
316
- stdin.removeListener("data", onData);
449
+ lines(lines) { for (const l of lines)
450
+ this.line(l); }
451
+ /** The logo and a title, at the top of a big flow. */
452
+ banner(title, subtitle, meta) { this.lines(["", ...this.kit.banner(title, subtitle, meta), ""]); }
453
+ header(title, subtitle) { this.lines(["", ...this.kit.header(title, subtitle), ""]); }
454
+ step(n, total, title) { this.lines(["", ...this.kit.step(n, total, title)]); }
455
+ section(title) { this.lines(["", ...this.kit.section(title)]); }
456
+ ok(text, detail) { this.lines(this.kit.mark("ok", text, detail)); }
457
+ warn(text, detail) { this.lines(this.kit.mark("warn", text, detail)); }
458
+ fail(text, detail) { this.lines(this.kit.mark("fail", text, detail)); }
459
+ info(text, detail) { this.lines(this.kit.mark("info", text, detail)); }
460
+ para(text, indent) { this.lines(this.kit.para(text, indent)); }
461
+ hint(text, indent) { this.lines(this.kit.hint(text, indent)); }
462
+ rows(pairs, indent) { this.lines(this.kit.rows(pairs, indent)); }
463
+ code(lines, indent) { this.lines(this.kit.code(lines, indent)); }
464
+ /** "Next" and what to do now. */
465
+ next(lines, title) { this.lines(["", ...this.kit.next(lines, title)]); }
466
+ /** What went wrong and how to fix it, inside a flow. */
467
+ problem(what, opts) {
468
+ this.lines(this.kit.problem(what, opts));
469
+ }
470
+ /** A problem that ends the command: goes to stderr. */
471
+ error(what, opts) {
472
+ for (const l of this.kit.problem(what, opts))
473
+ this.writeErr(l + "\n");
474
+ }
475
+ // progress ──────────────────────────────────────────────────────────────
476
+ /**
477
+ * Run slow work under a spinner that counts the seconds, so a wait never
478
+ * looks like a hang. `set(detail)` shows the latest thing happening (the
479
+ * last line a subprocess printed). The spinner line disappears when the work
480
+ * ends; the caller then prints the result with ok()/fail().
481
+ *
482
+ * Without a terminal there is nothing to animate: `slow` work gets one
483
+ * plain "started" line so a log shows what it is waiting on.
484
+ */
485
+ async task(label, work, opts = {}) {
486
+ const { g, c } = this.kit;
487
+ if (!this.live) {
488
+ if (opts.slow)
489
+ this.lines(this.kit.mark("info", c.dim(label + g.ellipsis)));
490
+ return work(() => { });
491
+ }
492
+ const started = this.now();
493
+ let detail = "";
494
+ let frame = 0;
495
+ const draw = () => {
496
+ const ms = this.now() - started;
497
+ const clock = ms >= 3000 ? ` ${c.dim(`[${duration(ms)}]`)}` : "";
498
+ const head = `${c.ask(g.spinner[frame++ % g.spinner.length])} ${label}`;
499
+ const room = this.style.width - visibleWidth(head) - visibleWidth(clock) - 3;
500
+ const tail = detail && room > 8 ? ` ${c.dim(detail.length > room ? detail.slice(0, room - 1) + g.ellipsis : detail)}` : "";
501
+ this.write(`${CLEAR_LINE}${head}${tail}${clock}`);
502
+ };
503
+ this.write(HIDE_CURSOR);
504
+ draw();
505
+ const timer = setInterval(draw, 90);
506
+ try {
507
+ return await work((d) => { detail = stripVTControlCharacters(d).replace(/\s+/g, " ").trim(); });
508
+ }
509
+ finally {
510
+ clearInterval(timer);
511
+ this.write(`${CLEAR_LINE}${SHOW_CURSOR}`);
512
+ }
513
+ }
514
+ // prompts ───────────────────────────────────────────────────────────────
515
+ /** One line of input, or InputClosedError when the input ended instead. */
516
+ async answer(query, question, signal) {
517
+ let line;
518
+ if (!process.stdin.isTTY) {
519
+ this.write(query);
520
+ line = await pipedLine(signal);
521
+ this.write("\n");
522
+ if (signal?.aborted)
523
+ throw new Withdrawn();
524
+ }
525
+ else {
526
+ // A fresh readline per question: a long-lived one breaks when a
527
+ // subprocess in between (a login, a build) inherits stdin.
528
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
529
+ // readline swallows Ctrl-C; turn it back into a clean exit.
530
+ rl.on("SIGINT", () => { process.stdout.write(`${SHOW_CURSOR}\n`); process.exit(130); });
317
531
  try {
318
- stdin.setRawMode(false);
532
+ line = await new Promise((resolve) => {
533
+ rl.once("close", () => resolve(null));
534
+ rl.question(query, signal ? { signal } : {}).then(resolve).catch(() => resolve(null));
535
+ });
536
+ }
537
+ finally {
538
+ rl.close();
539
+ }
540
+ // Taken back: the question leaves the screen, as if never asked.
541
+ if (signal?.aborted) {
542
+ this.write(CLEAR_LINE);
543
+ throw new Withdrawn();
319
544
  }
320
- catch { /* */ }
545
+ }
546
+ this.blank = false;
547
+ if (line === null)
548
+ throw new InputClosedError(question);
549
+ return line.trim();
550
+ }
551
+ q(question, suffix = "") {
552
+ return this.kit.question(question, suffix);
553
+ }
554
+ /**
555
+ * Yes or no. Enter takes the default; y/yes and n/no are the only other
556
+ * answers. Anything else is asked again, then counts as no: a stray key is
557
+ * not consent.
558
+ */
559
+ async confirm(question, defaultYes = true) {
560
+ return this.yesNo(question, defaultYes);
561
+ }
562
+ /**
563
+ * confirm(), unless `until` aborts first: something else settled it while
564
+ * totem was still asking (a sign-in finished from a link pasted elsewhere).
565
+ * Then the question leaves the screen and the answer is null.
566
+ */
567
+ async confirmUntil(question, until, defaultYes = true) {
568
+ try {
569
+ return await this.yesNo(question, defaultYes, until);
570
+ }
571
+ catch (error) {
572
+ if (error instanceof Withdrawn)
573
+ return null;
574
+ throw error;
575
+ }
576
+ }
577
+ async yesNo(question, defaultYes, signal) {
578
+ for (let attempt = 0; attempt < 3; attempt++) {
579
+ const a = (await this.answer(`${this.q(question, defaultYes ? "(Y/n)" : "(y/N)")} `, question, signal)).toLowerCase();
580
+ if (a === "")
581
+ return defaultYes;
582
+ if (a === "y" || a === "yes")
583
+ return true;
584
+ if (a === "n" || a === "no")
585
+ return false;
586
+ this.hint("Answer y or n.");
587
+ }
588
+ return false;
589
+ }
590
+ /** Free text; Enter takes `fallback`. */
591
+ async text(question, fallback = "") {
592
+ const a = await this.answer(`${this.q(question, fallback ? `(${fallback})` : "")}${this.kit.c.dim(":")} `, question);
593
+ return a || fallback;
594
+ }
595
+ /**
596
+ * A secret: nothing typed is shown, and nothing is trimmed. Readline does the
597
+ * editing (paste markers, backspace, Ctrl-U) on a muted stream, so not even
598
+ * its redraws reach the screen. Answers "" when the input ends.
599
+ */
600
+ async hidden(question) {
601
+ const query = `${this.q(question, "(hidden)")}${this.kit.c.dim(":")} `;
602
+ const stdin = process.stdin;
603
+ this.blank = false;
604
+ if (!stdin.isTTY) {
605
+ this.write(query);
606
+ const line = await pipedLine();
607
+ this.write("\n");
608
+ return line ?? "";
609
+ }
610
+ const wasRaw = stdin.isRaw;
611
+ const muted = new Writable({ write(_chunk, _encoding, done) { done(); } });
612
+ const rl = createInterface({ input: stdin, output: muted, terminal: true });
613
+ rl.on("SIGINT", () => { rl.close(); process.stdout.write("\n"); process.exit(130); });
614
+ this.write(query);
615
+ try {
616
+ return await new Promise((resolve) => {
617
+ rl.once("close", () => resolve(""));
618
+ rl.question("").then(resolve).catch(() => resolve(""));
619
+ });
620
+ }
621
+ finally {
622
+ rl.close();
623
+ if (typeof stdin.setRawMode === "function")
624
+ stdin.setRawMode(Boolean(wasRaw));
321
625
  stdin.pause();
322
- };
323
- const onData = (chunk) => {
324
- for (const ch of chunk) {
325
- if (ch === "\r" || ch === "\n" || ch === "\u0004") {
326
- cleanup();
327
- process.stdout.write("\n");
328
- resolve(buf.trim());
329
- return;
330
- }
331
- if (ch === "\u0003") {
332
- cleanup();
333
- process.stdout.write("\n");
334
- process.exit(130);
335
- } // Ctrl-C
336
- if (ch === "\u007f" || ch === "\b") {
337
- buf = buf.slice(0, -1);
338
- continue;
339
- } // backspace
340
- if (ch >= " ")
341
- buf += ch; // printable: captured, not echoed
626
+ muted.end();
627
+ this.write("\n");
628
+ }
629
+ }
630
+ /** The menu as it looks with `selected` chosen: what stays on screen after a choice. */
631
+ menu(question, choices, selected, active = false) {
632
+ const { c, g } = this.kit;
633
+ const labelWidth = Math.max(...choices.map((ch) => visibleWidth(ch.label))) + 3;
634
+ const room = this.style.width - 4 - labelWidth;
635
+ return [
636
+ this.q(question, active ? `(${this.style.unicode ? "↑↓" : "up/down"}, Enter)` : ""),
637
+ ...choices.map((ch, i) => {
638
+ const on = i === selected;
639
+ const hint = ch.hint && room >= 12 ? c.dim(ch.hint.length > room ? ch.hint.slice(0, room - 1) + g.ellipsis : ch.hint) : "";
640
+ const label = hint ? padEnd(ch.label, labelWidth) : ch.label;
641
+ return ` ${on ? c.ask(g.pointer) : " "} ${on ? c.ask(label) : label}${hint}`;
642
+ }),
643
+ ];
644
+ }
645
+ /**
646
+ * Pick one. On a terminal: arrows (or j/k, or a digit) move, Enter chooses.
647
+ * Piped: a numbered list, answered with a number (Enter = the default).
648
+ * Returns the index.
649
+ */
650
+ async select(question, choices, defaultIndex = 0) {
651
+ const n = choices.length;
652
+ let idx = Math.min(Math.max(defaultIndex, 0), n - 1);
653
+ const stdin = process.stdin;
654
+ if (!this.live || typeof stdin.setRawMode !== "function") {
655
+ const { c } = this.kit;
656
+ const labelWidth = Math.max(...choices.map((ch) => visibleWidth(ch.label))) + 3;
657
+ this.line(this.q(question));
658
+ choices.forEach((ch, i) => this.line(` ${c.ask(String(i + 1))}. ${ch.hint ? padEnd(ch.label, labelWidth) + c.dim(ch.hint) : ch.label}`));
659
+ for (let attempt = 0; attempt < 3; attempt++) {
660
+ const raw = await this.answer(` ${c.dim(`Number (${idx + 1}):`)} `, question);
661
+ if (raw === "")
662
+ return idx;
663
+ const picked = Number(raw);
664
+ if (Number.isInteger(picked) && picked >= 1 && picked <= n)
665
+ return picked - 1;
666
+ this.hint(`Enter a number from 1 to ${n}.`);
342
667
  }
668
+ throw new InputClosedError(question);
669
+ }
670
+ const render = (first, active) => {
671
+ if (!first)
672
+ this.write(`\x1b[${n + 1}A`);
673
+ for (const l of this.menu(question, choices, idx, active))
674
+ this.write(`${CLEAR_LINE}${l}\n`);
343
675
  };
676
+ render(true, true);
677
+ this.blank = false;
678
+ this.write(HIDE_CURSOR);
344
679
  stdin.setRawMode(true);
345
680
  stdin.resume();
346
681
  stdin.setEncoding("utf8");
347
- stdin.on("data", onData);
348
- });
349
- }
350
- // A masked prompt for secrets (the Whoop account password). Same look as
351
- // `prompt`, but nothing you type is shown.
352
- export async function promptHidden(question) {
353
- return askHidden(`${c.violet("?")} ${c.white(question)}${c.gray(" ›")} `);
354
- }
355
- // Enter — and ANY answer that isn't an explicit "no" — proceeds when `defaultYes`
356
- // is set. To decline you must actually type n / no / N / NO. (When `defaultYes`
357
- // is false it's the mirror: only an explicit y / yes proceeds.)
358
- export async function promptYesNo(question, defaultYes = true) {
359
- const hint = defaultYes ? `${c.green(c.bold("Y"))}${c.gray("/n")}` : `${c.gray("y/")}${c.red(c.bold("N"))}`;
360
- const answer = (await ask(`${c.violet("?")} ${c.white(question)} ${c.gray("(")}${hint}${c.gray(")")}${c.gray(" ›")} `)).trim().toLowerCase();
361
- if (defaultYes)
362
- return !/^(n|no)$/.test(answer);
363
- return /^(y|yes)$/.test(answer);
364
- }
365
- // Numbered menu. Returns the 0-based index of the choice. Used as the non-TTY
366
- // fallback for select() (piped stdin can't do raw-mode arrow keys).
367
- export async function promptChoice(question, choices) {
368
- console.log(`${c.violet("?")} ${c.bold(c.white(question))}`);
369
- choices.forEach((ch, i) => console.log(` ${c.cyan(c.bold(String(i + 1)))}${c.gray(".")} ${ch}`));
370
- for (let attempts = 0; attempts < 100; attempts++) {
371
- const raw = await ask(` ${c.gray("enter a number")}: `);
372
- const n = parseInt(raw, 10);
373
- if (Number.isInteger(n) && n >= 1 && n <= choices.length)
374
- return n - 1;
375
- if (raw === "")
376
- return 0; // EOF / piped input → first choice (safe default)
377
- console.log(c.red(` Please enter 1-${choices.length}.`));
378
- }
379
- return 0;
380
- }
381
- export async function select(question, choices, opts = {}) {
382
- const items = choices.map((ch) => (typeof ch === "string" ? { label: ch } : ch));
383
- const stdin = process.stdin;
384
- const interactive = Boolean(stdin.isTTY) && Boolean(process.stdout.isTTY) && typeof stdin.setRawMode === "function";
385
- if (!interactive) {
386
- return promptChoice(question, items.map((it) => (it.hint ? `${it.label} ${c.gray(it.hint)}` : it.label)));
387
- }
388
- let idx = Math.min(Math.max(opts.defaultIndex ?? 0, 0), items.length - 1);
389
- const render = (first) => {
390
- if (!first)
391
- process.stdout.write(`\x1b[${items.length + 1}A`); // back up to the question line
392
- process.stdout.write(`\r\x1b[2K${c.violet("?")} ${c.bold(c.white(question))} ${c.dim("↑/↓ · enter")}\n`);
393
- items.forEach((it, i) => {
394
- const selected = i === idx;
395
- const pointer = selected ? c.cyan("❯") : " ";
396
- const label = selected ? c.bold(c.cyan(it.label)) : c.white(it.label);
397
- const hint = it.hint ? " " + c.dim(it.hint) : "";
398
- process.stdout.write(`\r\x1b[2K ${pointer} ${label}${hint}\n`);
399
- });
400
- };
401
- render(true);
402
- process.stdout.write("\x1b[?25l"); // hide the blinking cursor while the menu is active
403
- stdin.setRawMode(true);
404
- stdin.resume();
405
- stdin.setEncoding("utf8");
406
- const n = items.length;
407
- return new Promise((resolveSel) => {
408
- const cleanup = () => {
409
- stdin.setRawMode(false);
410
- stdin.pause();
411
- stdin.removeListener("data", onData);
412
- process.stdout.write("\x1b[?25h"); // restore the cursor once a choice is made
413
- };
414
- // Scan the chunk left-to-right rather than exact-matching the whole thing:
415
- // a single read can batch several bytes (a paste, a fast double-press, or a
416
- // terminal/PTY that delivers the arrow sequence and the Enter together like
417
- // "\x1b[B\r"). Incomplete escape sequences at a chunk boundary are stashed in
418
- // `pending` and prepended to the next read so a split "\x1b" + "[B" still works.
419
- let pending = "";
420
- const onData = (raw) => {
421
- const chunk = pending + raw;
422
- pending = "";
423
- if (chunk.includes("\x03")) {
424
- cleanup();
425
- process.stdout.write("\n");
426
- process.exit(130);
427
- }
428
- let moved = false;
429
- let i = 0;
430
- while (i < chunk.length) {
431
- const rest = chunk.slice(i);
432
- const ch = rest[0];
433
- if (ch === "\r" || ch === "\n") {
682
+ return new Promise((resolve) => {
683
+ const cleanup = () => {
684
+ stdin.setRawMode(false);
685
+ stdin.pause();
686
+ stdin.removeListener("data", onData);
687
+ this.write(SHOW_CURSOR);
688
+ };
689
+ // Scan each chunk left to right: one read can carry several keys (a fast
690
+ // double press, or an arrow and Enter together), and an escape sequence
691
+ // can be split across two reads.
692
+ let pending = "";
693
+ const onData = (raw) => {
694
+ const chunk = pending + raw;
695
+ pending = "";
696
+ if (chunk.includes("\x03")) {
434
697
  cleanup();
435
- if (moved)
436
- render(false);
437
- resolveSel(idx);
438
- return;
698
+ this.write("\n");
699
+ process.exit(130);
439
700
  }
440
- if (ch === "\x1b") {
441
- if (rest === "\x1b" || rest === "\x1b[") {
442
- pending = rest;
443
- break;
444
- } // incomplete — wait for more
445
- if (rest.startsWith("\x1b[A")) {
446
- idx = (idx - 1 + n) % n;
447
- moved = true;
448
- i += 3;
449
- continue;
701
+ if (chunk.includes("\x04")) {
702
+ cleanup();
703
+ this.write("\n");
704
+ process.exit(130);
705
+ }
706
+ let i = 0;
707
+ while (i < chunk.length) {
708
+ const rest = chunk.slice(i);
709
+ const ch = rest[0];
710
+ if (ch === "\r" || ch === "\n") {
711
+ // The menu folds into one line: the question and what was chosen.
712
+ cleanup();
713
+ this.write(`\x1b[${n + 1}A`);
714
+ for (let k = 0; k <= n; k++)
715
+ this.write(`${CLEAR_LINE}\n`);
716
+ this.write(`\x1b[${n + 1}A${CLEAR_LINE}${this.kit.answered(question, choices[idx].label)}\n`);
717
+ resolve(idx);
718
+ return;
450
719
  }
451
- if (rest.startsWith("\x1b[B")) {
452
- idx = (idx + 1) % n;
453
- moved = true;
454
- i += 3;
720
+ if (ch === "\x1b") {
721
+ if (rest === "\x1b" || rest === "\x1b[") {
722
+ pending = rest;
723
+ break;
724
+ }
725
+ if (rest.startsWith("\x1b[A")) {
726
+ idx = (idx - 1 + n) % n;
727
+ i += 3;
728
+ continue;
729
+ }
730
+ if (rest.startsWith("\x1b[B")) {
731
+ idx = (idx + 1) % n;
732
+ i += 3;
733
+ continue;
734
+ }
735
+ i += Math.min(rest.length, 3);
455
736
  continue;
456
737
  }
457
- i += rest.length >= 3 ? 3 : rest.length;
458
- continue; // unknown escape — skip it
459
- }
460
- if (ch === "k") {
461
- idx = (idx - 1 + n) % n;
462
- moved = true;
463
- }
464
- else if (ch === "j") {
465
- idx = (idx + 1) % n;
466
- moved = true;
467
- }
468
- else if (/[1-9]/.test(ch)) {
469
- const x = parseInt(ch, 10) - 1;
470
- if (x < n) {
471
- idx = x;
472
- moved = true;
473
- }
738
+ if (ch === "k")
739
+ idx = (idx - 1 + n) % n;
740
+ else if (ch === "j")
741
+ idx = (idx + 1) % n;
742
+ else if (/[1-9]/.test(ch) && Number(ch) <= n)
743
+ idx = Number(ch) - 1;
744
+ i += 1;
474
745
  }
475
- i += 1;
476
- }
477
- if (moved)
478
- render(false);
479
- };
480
- stdin.on("data", onData);
481
- });
482
- }
483
- export async function confirmStep(summary, opts = {}) {
484
- console.log(` ${c.yellow("⚠")} ${c.bold(c.white(summary))}`);
485
- if (opts.detail)
486
- console.log(` ${c.gray(opts.detail)}`);
487
- if (opts.cmd)
488
- console.log(` ${c.dim("$")} ${c.cyan(opts.cmd)}`);
489
- return promptYesNo(" Proceed?", opts.defaultYes ?? true);
746
+ render(false, true);
747
+ };
748
+ stdin.on("data", onData);
749
+ });
750
+ }
490
751
  }
491
- // Redact secret values when echoing a command so tokens/passwords never hit the
492
- // screen or scrollback. Masks the value of any KEY=value whose key looks
493
- // sensitive (or whose value is long enough to be a token).
494
- export function maskArgs(args) {
752
+ /** Mask the value of any KEY=value whose key names a secret, for showing a command. */
753
+ export function maskSecrets(args) {
495
754
  return args
496
755
  .map((a) => {
497
756
  const eq = a.indexOf("=");
498
- if (eq <= 0)
499
- return a;
500
- const key = a.slice(0, eq);
501
- if (/(_?TOKEN|PASSWORD|_SECRET|BEARER|REFRESH|EMAIL)/i.test(key))
502
- return `${key}=${c.dim("•••")}`;
503
- return a;
757
+ return eq > 0 && /(TOKEN|PASSWORD|SECRET|BEARER|REFRESH)/i.test(a.slice(0, eq)) ? `${a.slice(0, eq)}=***` : a;
504
758
  })
505
759
  .join(" ");
506
760
  }
507
- // Section header for the guided flows — a violet rule + step counter + title.
508
- export function step(n, total, title) {
509
- console.log("");
510
- console.log(`${c.violet("▌")} ${c.violet(c.bold(`${n}/${total}`))} ${c.bold(c.white(title))}`);
511
- }
512
761
  //# sourceMappingURL=ui.js.map