@thebriangao/totem 1.4.4
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.
- package/.dockerignore +23 -0
- package/.env.example +66 -0
- package/CHANGELOG.md +283 -0
- package/CONTRIBUTING.md +149 -0
- package/Dockerfile +53 -0
- package/LICENSE +37 -0
- package/README.md +587 -0
- package/SECURITY.md +79 -0
- package/TOOLS.md +429 -0
- package/WHOOP.md +2673 -0
- package/assets/banner.svg +38 -0
- package/dist/cli/index.js +589 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/cli/setup.js +1127 -0
- package/dist/cli/setup.js.map +1 -0
- package/dist/cli/ui.js +512 -0
- package/dist/cli/ui.js.map +1 -0
- package/dist/cli/update.js +465 -0
- package/dist/cli/update.js.map +1 -0
- package/dist/data/behaviors.js +2777 -0
- package/dist/data/behaviors.js.map +1 -0
- package/dist/data/endpoints.js +320 -0
- package/dist/data/endpoints.js.map +1 -0
- package/dist/data/exercises.js +4863 -0
- package/dist/data/exercises.js.map +1 -0
- package/dist/data/sports.js +212 -0
- package/dist/data/sports.js.map +1 -0
- package/dist/lib/concurrency.js +27 -0
- package/dist/lib/concurrency.js.map +1 -0
- package/dist/lib/dates.js +29 -0
- package/dist/lib/dates.js.map +1 -0
- package/dist/lib/format.js +22 -0
- package/dist/lib/format.js.map +1 -0
- package/dist/lib/stats.js +32 -0
- package/dist/lib/stats.js.map +1 -0
- package/dist/lib/timezone.js +249 -0
- package/dist/lib/timezone.js.map +1 -0
- package/dist/lib/walk.js +396 -0
- package/dist/lib/walk.js.map +1 -0
- package/dist/projections/behavior_impact.js +96 -0
- package/dist/projections/behavior_impact.js.map +1 -0
- package/dist/projections/calendar.js +33 -0
- package/dist/projections/calendar.js.map +1 -0
- package/dist/projections/communities.js +105 -0
- package/dist/projections/communities.js.map +1 -0
- package/dist/projections/cycle.js +81 -0
- package/dist/projections/cycle.js.map +1 -0
- package/dist/projections/hr_zones.js +35 -0
- package/dist/projections/hr_zones.js.map +1 -0
- package/dist/projections/journal.js +56 -0
- package/dist/projections/journal.js.map +1 -0
- package/dist/projections/leaderboard.js +37 -0
- package/dist/projections/leaderboard.js.map +1 -0
- package/dist/projections/lift_exercise.js +22 -0
- package/dist/projections/lift_exercise.js.map +1 -0
- package/dist/projections/lift_history.js +133 -0
- package/dist/projections/lift_history.js.map +1 -0
- package/dist/projections/lift_library.js +71 -0
- package/dist/projections/lift_library.js.map +1 -0
- package/dist/projections/lift_progression.js +138 -0
- package/dist/projections/lift_progression.js.map +1 -0
- package/dist/projections/lift_prs.js +20 -0
- package/dist/projections/lift_prs.js.map +1 -0
- package/dist/projections/live_hr.js +19 -0
- package/dist/projections/live_hr.js.map +1 -0
- package/dist/projections/live_state.js +23 -0
- package/dist/projections/live_state.js.map +1 -0
- package/dist/projections/live_stress.js +11 -0
- package/dist/projections/live_stress.js.map +1 -0
- package/dist/projections/performance_assessment.js +15 -0
- package/dist/projections/performance_assessment.js.map +1 -0
- package/dist/projections/profile.js +59 -0
- package/dist/projections/profile.js.map +1 -0
- package/dist/projections/recovery.js +131 -0
- package/dist/projections/recovery.js.map +1 -0
- package/dist/projections/sleep.js +256 -0
- package/dist/projections/sleep.js.map +1 -0
- package/dist/projections/sleep_need.js +32 -0
- package/dist/projections/sleep_need.js.map +1 -0
- package/dist/projections/smart_alarm.js +45 -0
- package/dist/projections/smart_alarm.js.map +1 -0
- package/dist/projections/strain.js +128 -0
- package/dist/projections/strain.js.map +1 -0
- package/dist/projections/stress.js +86 -0
- package/dist/projections/stress.js.map +1 -0
- package/dist/projections/today.js +129 -0
- package/dist/projections/today.js.map +1 -0
- package/dist/projections/trend.js +149 -0
- package/dist/projections/trend.js.map +1 -0
- package/dist/projections/workout.js +161 -0
- package/dist/projections/workout.js.map +1 -0
- package/dist/projections/workouts.js +37 -0
- package/dist/projections/workouts.js.map +1 -0
- package/dist/schemas/calendar.js +12 -0
- package/dist/schemas/calendar.js.map +1 -0
- package/dist/schemas/coach.js +11 -0
- package/dist/schemas/coach.js.map +1 -0
- package/dist/schemas/communities.js +51 -0
- package/dist/schemas/communities.js.map +1 -0
- package/dist/schemas/compare.js +15 -0
- package/dist/schemas/compare.js.map +1 -0
- package/dist/schemas/escape.js +18 -0
- package/dist/schemas/escape.js.map +1 -0
- package/dist/schemas/journal.js +69 -0
- package/dist/schemas/journal.js.map +1 -0
- package/dist/schemas/leaderboard.js +25 -0
- package/dist/schemas/leaderboard.js.map +1 -0
- package/dist/schemas/live.js +26 -0
- package/dist/schemas/live.js.map +1 -0
- package/dist/schemas/performance.js +12 -0
- package/dist/schemas/performance.js.map +1 -0
- package/dist/schemas/primitives.js +29 -0
- package/dist/schemas/primitives.js.map +1 -0
- package/dist/schemas/profile.js +39 -0
- package/dist/schemas/profile.js.map +1 -0
- package/dist/schemas/recovery.js +27 -0
- package/dist/schemas/recovery.js.map +1 -0
- package/dist/schemas/settings.js +26 -0
- package/dist/schemas/settings.js.map +1 -0
- package/dist/schemas/sleep.js +38 -0
- package/dist/schemas/sleep.js.map +1 -0
- package/dist/schemas/sleep_need.js +15 -0
- package/dist/schemas/sleep_need.js.map +1 -0
- package/dist/schemas/smart_alarm.js +36 -0
- package/dist/schemas/smart_alarm.js.map +1 -0
- package/dist/schemas/strain.js +24 -0
- package/dist/schemas/strain.js.map +1 -0
- package/dist/schemas/strength.js +170 -0
- package/dist/schemas/strength.js.map +1 -0
- package/dist/schemas/stress.js +16 -0
- package/dist/schemas/stress.js.map +1 -0
- package/dist/schemas/today.js +38 -0
- package/dist/schemas/today.js.map +1 -0
- package/dist/schemas/trend.js +50 -0
- package/dist/schemas/trend.js.map +1 -0
- package/dist/schemas/womens_health.js +23 -0
- package/dist/schemas/womens_health.js.map +1 -0
- package/dist/schemas/workouts.js +50 -0
- package/dist/schemas/workouts.js.map +1 -0
- package/dist/scripts/cognito_bootstrap.js +278 -0
- package/dist/scripts/cognito_bootstrap.js.map +1 -0
- package/dist/server-http.js +221 -0
- package/dist/server-http.js.map +1 -0
- package/dist/server.js +74 -0
- package/dist/server.js.map +1 -0
- package/dist/tools/register.js +117 -0
- package/dist/tools/register.js.map +1 -0
- package/dist/tools/v2/activity_create.js +64 -0
- package/dist/tools/v2/activity_create.js.map +1 -0
- package/dist/tools/v2/activity_delete.js +26 -0
- package/dist/tools/v2/activity_delete.js.map +1 -0
- package/dist/tools/v2/behavior_impact.js +36 -0
- package/dist/tools/v2/behavior_impact.js.map +1 -0
- package/dist/tools/v2/calendar.js +28 -0
- package/dist/tools/v2/calendar.js.map +1 -0
- package/dist/tools/v2/coach_ask.js +117 -0
- package/dist/tools/v2/coach_ask.js.map +1 -0
- package/dist/tools/v2/communities.js +60 -0
- package/dist/tools/v2/communities.js.map +1 -0
- package/dist/tools/v2/compare.js +67 -0
- package/dist/tools/v2/compare.js.map +1 -0
- package/dist/tools/v2/cycle.js +23 -0
- package/dist/tools/v2/cycle.js.map +1 -0
- package/dist/tools/v2/cycle_log.js +43 -0
- package/dist/tools/v2/cycle_log.js.map +1 -0
- package/dist/tools/v2/day.js +32 -0
- package/dist/tools/v2/day.js.map +1 -0
- package/dist/tools/v2/endpoints.js +28 -0
- package/dist/tools/v2/endpoints.js.map +1 -0
- package/dist/tools/v2/hidden_metric.js +28 -0
- package/dist/tools/v2/hidden_metric.js.map +1 -0
- package/dist/tools/v2/hr_zones.js +24 -0
- package/dist/tools/v2/hr_zones.js.map +1 -0
- package/dist/tools/v2/hr_zones_set.js +51 -0
- package/dist/tools/v2/hr_zones_set.js.map +1 -0
- package/dist/tools/v2/journal.js +26 -0
- package/dist/tools/v2/journal.js.map +1 -0
- package/dist/tools/v2/journal_autopop.js +19 -0
- package/dist/tools/v2/journal_autopop.js.map +1 -0
- package/dist/tools/v2/journal_catalog.js +44 -0
- package/dist/tools/v2/journal_catalog.js.map +1 -0
- package/dist/tools/v2/journal_log.js +78 -0
- package/dist/tools/v2/journal_log.js.map +1 -0
- package/dist/tools/v2/leaderboard.js +79 -0
- package/dist/tools/v2/leaderboard.js.map +1 -0
- package/dist/tools/v2/lift_catalog.js +47 -0
- package/dist/tools/v2/lift_catalog.js.map +1 -0
- package/dist/tools/v2/lift_custom_exercise.js +108 -0
- package/dist/tools/v2/lift_custom_exercise.js.map +1 -0
- package/dist/tools/v2/lift_exercise.js +31 -0
- package/dist/tools/v2/lift_exercise.js.map +1 -0
- package/dist/tools/v2/lift_history.js +39 -0
- package/dist/tools/v2/lift_history.js.map +1 -0
- package/dist/tools/v2/lift_library.js +22 -0
- package/dist/tools/v2/lift_library.js.map +1 -0
- package/dist/tools/v2/lift_log.js +95 -0
- package/dist/tools/v2/lift_log.js.map +1 -0
- package/dist/tools/v2/lift_progression.js +30 -0
- package/dist/tools/v2/lift_progression.js.map +1 -0
- package/dist/tools/v2/lift_prs.js +21 -0
- package/dist/tools/v2/lift_prs.js.map +1 -0
- package/dist/tools/v2/lift_template_save.js +83 -0
- package/dist/tools/v2/lift_template_save.js.map +1 -0
- package/dist/tools/v2/live_hr.js +21 -0
- package/dist/tools/v2/live_hr.js.map +1 -0
- package/dist/tools/v2/live_state.js +21 -0
- package/dist/tools/v2/live_state.js.map +1 -0
- package/dist/tools/v2/live_stress.js +22 -0
- package/dist/tools/v2/live_stress.js.map +1 -0
- package/dist/tools/v2/performance_assessment.js +38 -0
- package/dist/tools/v2/performance_assessment.js.map +1 -0
- package/dist/tools/v2/profile.js +28 -0
- package/dist/tools/v2/profile.js.map +1 -0
- package/dist/tools/v2/profile_update.js +66 -0
- package/dist/tools/v2/profile_update.js.map +1 -0
- package/dist/tools/v2/raw.js +43 -0
- package/dist/tools/v2/raw.js.map +1 -0
- package/dist/tools/v2/recovery.js +31 -0
- package/dist/tools/v2/recovery.js.map +1 -0
- package/dist/tools/v2/sleep.js +23 -0
- package/dist/tools/v2/sleep.js.map +1 -0
- package/dist/tools/v2/sleep_need.js +21 -0
- package/dist/tools/v2/sleep_need.js.map +1 -0
- package/dist/tools/v2/smart_alarm.js +24 -0
- package/dist/tools/v2/smart_alarm.js.map +1 -0
- package/dist/tools/v2/smart_alarm_set.js +94 -0
- package/dist/tools/v2/smart_alarm_set.js.map +1 -0
- package/dist/tools/v2/sports_catalog.js +26 -0
- package/dist/tools/v2/sports_catalog.js.map +1 -0
- package/dist/tools/v2/strain.js +23 -0
- package/dist/tools/v2/strain.js.map +1 -0
- package/dist/tools/v2/stress.js +23 -0
- package/dist/tools/v2/stress.js.map +1 -0
- package/dist/tools/v2/symptom_log.js +72 -0
- package/dist/tools/v2/symptom_log.js.map +1 -0
- package/dist/tools/v2/today.js +30 -0
- package/dist/tools/v2/today.js.map +1 -0
- package/dist/tools/v2/trend.js +26 -0
- package/dist/tools/v2/trend.js.map +1 -0
- package/dist/tools/v2/workout.js +23 -0
- package/dist/tools/v2/workout.js.map +1 -0
- package/dist/tools/v2/workouts.js +32 -0
- package/dist/tools/v2/workouts.js.map +1 -0
- package/dist/whoop/build_lift_body.js +67 -0
- package/dist/whoop/build_lift_body.js.map +1 -0
- package/dist/whoop/client.js +84 -0
- package/dist/whoop/client.js.map +1 -0
- package/dist/whoop/cognito.js +110 -0
- package/dist/whoop/cognito.js.map +1 -0
- package/dist/whoop/constants.js +4 -0
- package/dist/whoop/constants.js.map +1 -0
- package/dist/whoop/device.js +103 -0
- package/dist/whoop/device.js.map +1 -0
- package/dist/whoop/errors.js +42 -0
- package/dist/whoop/errors.js.map +1 -0
- package/dist/whoop/init_timezone.js +62 -0
- package/dist/whoop/init_timezone.js.map +1 -0
- package/dist/whoop/installation.js +62 -0
- package/dist/whoop/installation.js.map +1 -0
- package/dist/whoop/json_out.js +9 -0
- package/dist/whoop/json_out.js.map +1 -0
- package/dist/whoop/oauth_provider.js +297 -0
- package/dist/whoop/oauth_provider.js.map +1 -0
- package/dist/whoop/session_state.js +34 -0
- package/dist/whoop/session_state.js.map +1 -0
- package/dist/whoop/token_manager.js +60 -0
- package/dist/whoop/token_manager.js.map +1 -0
- package/dist/whoop/token_store.js +47 -0
- package/dist/whoop/token_store.js.map +1 -0
- package/dist/whoop/types.js +82 -0
- package/dist/whoop/types.js.map +1 -0
- package/dist/whoop/write_safety.js +23 -0
- package/dist/whoop/write_safety.js.map +1 -0
- package/package.json +66 -0
- package/src/cli/index.ts +597 -0
- package/src/cli/setup.ts +1106 -0
- package/src/cli/ui.ts +505 -0
- package/src/cli/update.ts +442 -0
- package/src/data/behaviors.ts +2784 -0
- package/src/data/endpoints.ts +319 -0
- package/src/data/exercises.ts +4868 -0
- package/src/data/sports.ts +218 -0
- package/src/lib/concurrency.ts +28 -0
- package/src/lib/dates.ts +35 -0
- package/src/lib/format.ts +27 -0
- package/src/lib/stats.ts +35 -0
- package/src/lib/timezone.ts +269 -0
- package/src/lib/walk.ts +418 -0
- package/src/projections/behavior_impact.ts +98 -0
- package/src/projections/calendar.ts +46 -0
- package/src/projections/communities.ts +135 -0
- package/src/projections/cycle.ts +85 -0
- package/src/projections/hr_zones.ts +43 -0
- package/src/projections/journal.ts +55 -0
- package/src/projections/leaderboard.ts +49 -0
- package/src/projections/lift_exercise.ts +29 -0
- package/src/projections/lift_history.ts +140 -0
- package/src/projections/lift_library.ts +70 -0
- package/src/projections/lift_progression.ts +138 -0
- package/src/projections/lift_prs.ts +23 -0
- package/src/projections/live_hr.ts +21 -0
- package/src/projections/live_state.ts +28 -0
- package/src/projections/live_stress.ts +13 -0
- package/src/projections/performance_assessment.ts +19 -0
- package/src/projections/profile.ts +71 -0
- package/src/projections/recovery.ts +133 -0
- package/src/projections/sleep.ts +276 -0
- package/src/projections/sleep_need.ts +36 -0
- package/src/projections/smart_alarm.ts +70 -0
- package/src/projections/strain.ts +131 -0
- package/src/projections/stress.ts +95 -0
- package/src/projections/today.ts +166 -0
- package/src/projections/trend.ts +149 -0
- package/src/projections/workout.ts +168 -0
- package/src/projections/workouts.ts +36 -0
- package/src/schemas/calendar.ts +13 -0
- package/src/schemas/coach.ts +11 -0
- package/src/schemas/communities.ts +56 -0
- package/src/schemas/compare.ts +17 -0
- package/src/schemas/escape.ts +21 -0
- package/src/schemas/journal.ts +80 -0
- package/src/schemas/leaderboard.ts +26 -0
- package/src/schemas/live.ts +31 -0
- package/src/schemas/performance.ts +13 -0
- package/src/schemas/primitives.ts +35 -0
- package/src/schemas/profile.ts +40 -0
- package/src/schemas/recovery.ts +28 -0
- package/src/schemas/settings.ts +30 -0
- package/src/schemas/sleep.ts +40 -0
- package/src/schemas/sleep_need.ts +16 -0
- package/src/schemas/smart_alarm.ts +40 -0
- package/src/schemas/strain.ts +25 -0
- package/src/schemas/strength.ts +189 -0
- package/src/schemas/stress.ts +17 -0
- package/src/schemas/today.ts +39 -0
- package/src/schemas/trend.ts +53 -0
- package/src/schemas/womens_health.ts +26 -0
- package/src/schemas/workouts.ts +55 -0
- package/src/scripts/cognito_bootstrap.ts +249 -0
- package/src/server-http.ts +241 -0
- package/src/server.ts +85 -0
- package/src/tools/register.ts +120 -0
- package/src/tools/v2/activity_create.ts +74 -0
- package/src/tools/v2/activity_delete.ts +33 -0
- package/src/tools/v2/behavior_impact.ts +39 -0
- package/src/tools/v2/calendar.ts +33 -0
- package/src/tools/v2/coach_ask.ts +131 -0
- package/src/tools/v2/communities.ts +65 -0
- package/src/tools/v2/compare.ts +83 -0
- package/src/tools/v2/cycle.ts +28 -0
- package/src/tools/v2/cycle_log.ts +51 -0
- package/src/tools/v2/day.ts +37 -0
- package/src/tools/v2/endpoints.ts +32 -0
- package/src/tools/v2/hidden_metric.ts +33 -0
- package/src/tools/v2/hr_zones.ts +29 -0
- package/src/tools/v2/hr_zones_set.ts +57 -0
- package/src/tools/v2/journal.ts +31 -0
- package/src/tools/v2/journal_autopop.ts +26 -0
- package/src/tools/v2/journal_catalog.ts +48 -0
- package/src/tools/v2/journal_log.ts +84 -0
- package/src/tools/v2/leaderboard.ts +92 -0
- package/src/tools/v2/lift_catalog.ts +48 -0
- package/src/tools/v2/lift_custom_exercise.ts +117 -0
- package/src/tools/v2/lift_exercise.ts +35 -0
- package/src/tools/v2/lift_history.ts +52 -0
- package/src/tools/v2/lift_library.ts +28 -0
- package/src/tools/v2/lift_log.ts +102 -0
- package/src/tools/v2/lift_progression.ts +34 -0
- package/src/tools/v2/lift_prs.ts +26 -0
- package/src/tools/v2/lift_template_save.ts +89 -0
- package/src/tools/v2/live_hr.ts +26 -0
- package/src/tools/v2/live_state.ts +26 -0
- package/src/tools/v2/live_stress.ts +27 -0
- package/src/tools/v2/performance_assessment.ts +44 -0
- package/src/tools/v2/profile.ts +33 -0
- package/src/tools/v2/profile_update.ts +76 -0
- package/src/tools/v2/raw.ts +50 -0
- package/src/tools/v2/recovery.ts +36 -0
- package/src/tools/v2/sleep.ts +28 -0
- package/src/tools/v2/sleep_need.ts +26 -0
- package/src/tools/v2/smart_alarm.ts +29 -0
- package/src/tools/v2/smart_alarm_set.ts +103 -0
- package/src/tools/v2/sports_catalog.ts +32 -0
- package/src/tools/v2/strain.ts +28 -0
- package/src/tools/v2/stress.ts +28 -0
- package/src/tools/v2/symptom_log.ts +78 -0
- package/src/tools/v2/today.ts +35 -0
- package/src/tools/v2/trend.ts +31 -0
- package/src/tools/v2/workout.ts +28 -0
- package/src/tools/v2/workouts.ts +37 -0
- package/src/whoop/build_lift_body.ts +84 -0
- package/src/whoop/client.ts +118 -0
- package/src/whoop/cognito.ts +150 -0
- package/src/whoop/constants.ts +3 -0
- package/src/whoop/device.ts +106 -0
- package/src/whoop/errors.ts +41 -0
- package/src/whoop/init_timezone.ts +64 -0
- package/src/whoop/installation.ts +58 -0
- package/src/whoop/json_out.ts +9 -0
- package/src/whoop/oauth_provider.ts +377 -0
- package/src/whoop/session_state.ts +41 -0
- package/src/whoop/token_manager.ts +76 -0
- package/src/whoop/token_store.ts +45 -0
- package/src/whoop/types.ts +89 -0
- package/src/whoop/write_safety.ts +30 -0
package/src/cli/ui.ts
ADDED
|
@@ -0,0 +1,505 @@
|
|
|
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, type SpawnOptions } from "node:child_process";
|
|
5
|
+
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
|
+
|
|
11
|
+
export const useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
|
|
12
|
+
// Modern truecolor palette (Tailwind-400-ish) — vivid but easy on a dark terminal.
|
|
13
|
+
const ANSI = {
|
|
14
|
+
reset: "\x1b[0m",
|
|
15
|
+
bold: "\x1b[1m",
|
|
16
|
+
dim: "\x1b[2m",
|
|
17
|
+
brand: "\x1b[38;2;235;235;235m",
|
|
18
|
+
brandDim: "\x1b[38;2;150;150;150m",
|
|
19
|
+
gray: "\x1b[38;2;128;128;128m",
|
|
20
|
+
white: "\x1b[38;2;245;245;245m",
|
|
21
|
+
green: "\x1b[38;2;52;211;153m", // emerald
|
|
22
|
+
red: "\x1b[38;2;248;113;113m", // red
|
|
23
|
+
yellow: "\x1b[38;2;251;191;36m", // amber
|
|
24
|
+
cyan: "\x1b[38;2;34;211;238m", // cyan
|
|
25
|
+
violet: "\x1b[38;2;167;139;250m", // violet
|
|
26
|
+
pink: "\x1b[38;2;244;114;182m", // pink
|
|
27
|
+
};
|
|
28
|
+
function wrap(code: string, s: string): string {
|
|
29
|
+
return useColor ? `${code}${s}${ANSI.reset}` : s;
|
|
30
|
+
}
|
|
31
|
+
export const c = {
|
|
32
|
+
brand: (s: string) => wrap(ANSI.brand, s),
|
|
33
|
+
brandDim: (s: string) => wrap(ANSI.brandDim, s),
|
|
34
|
+
gray: (s: string) => wrap(ANSI.gray, s),
|
|
35
|
+
white: (s: string) => wrap(ANSI.white, s),
|
|
36
|
+
green: (s: string) => wrap(ANSI.green, s),
|
|
37
|
+
red: (s: string) => wrap(ANSI.red, s),
|
|
38
|
+
yellow: (s: string) => wrap(ANSI.yellow, s),
|
|
39
|
+
cyan: (s: string) => wrap(ANSI.cyan, s),
|
|
40
|
+
violet: (s: string) => wrap(ANSI.violet, s),
|
|
41
|
+
pink: (s: string) => wrap(ANSI.pink, s),
|
|
42
|
+
bold: (s: string) => wrap(ANSI.bold, s),
|
|
43
|
+
dim: (s: string) => wrap(ANSI.dim, s),
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
// Spawn a command, inheriting stdio. Resolves with the exit code.
|
|
47
|
+
export function run(cmd: string, args: string[], opts: SpawnOptions = {}): Promise<number> {
|
|
48
|
+
return new Promise((res) => {
|
|
49
|
+
const child = spawn(cmd, args, { stdio: "inherit", ...opts });
|
|
50
|
+
child.on("exit", (code, signal) => {
|
|
51
|
+
if (signal) {
|
|
52
|
+
console.error(c.red(`\nKilled by signal ${signal}`));
|
|
53
|
+
res(128);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
res(code ?? 1);
|
|
57
|
+
});
|
|
58
|
+
child.on("error", (err) => {
|
|
59
|
+
console.error(c.red("Failed to spawn:"), (err as Error).message);
|
|
60
|
+
res(1);
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Run a command and capture stdout (for parsing CLI output like a deploy URL).
|
|
66
|
+
export function capture(cmd: string, args: string[], opts: SpawnOptions = {}): { code: number; stdout: string; stderr: string } {
|
|
67
|
+
const r = spawnSync(cmd, args, { encoding: "utf8", ...opts });
|
|
68
|
+
return { code: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Async sibling of capture(). `capture` uses spawnSync, which BLOCKS the event
|
|
72
|
+
// loop for the whole subprocess — so a spinner (setInterval) can't animate over
|
|
73
|
+
// it. For slow, network-bound lookups (gcloud/railway/fly API calls) run them
|
|
74
|
+
// through this instead and wrap with withSpinner() so the UI stays alive.
|
|
75
|
+
export function captureAsync(
|
|
76
|
+
cmd: string,
|
|
77
|
+
args: string[],
|
|
78
|
+
opts: SpawnOptions & { input?: string } = {},
|
|
79
|
+
): Promise<{ code: number; stdout: string; stderr: string }> {
|
|
80
|
+
const { input, ...spawnOpts } = opts;
|
|
81
|
+
return new Promise((res) => {
|
|
82
|
+
// input set → pipe stdin so secrets can be fed over a pipe (off the argv,
|
|
83
|
+
// which is visible in `ps`/`/proc`); otherwise ignore stdin as before.
|
|
84
|
+
const child = spawn(cmd, args, { stdio: [input !== undefined ? "pipe" : "ignore", "pipe", "pipe"], ...spawnOpts });
|
|
85
|
+
let stdout = "";
|
|
86
|
+
let stderr = "";
|
|
87
|
+
child.stdout?.on("data", (d: Buffer) => (stdout += d.toString()));
|
|
88
|
+
child.stderr?.on("data", (d: Buffer) => (stderr += d.toString()));
|
|
89
|
+
child.on("error", () => res({ code: 1, stdout, stderr }));
|
|
90
|
+
child.on("close", (code) => res({ code: code ?? 1, stdout, stderr }));
|
|
91
|
+
if (input !== undefined) { child.stdin?.write(input); child.stdin?.end(); }
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ── spinner ──────────────────────────────────────────────────────────────
|
|
96
|
+
// A braille spinner for the "thinking" gaps where we do work with no visible
|
|
97
|
+
// output (our own network lookups, HTTP polling, backoff waits). Subprocesses
|
|
98
|
+
// run with inherited stdio print their own progress, so they don't need this.
|
|
99
|
+
// IMPORTANT: a spinner only animates while the event loop is free — pair it
|
|
100
|
+
// with async work (await captureAsync / httpGet / setTimeout), never spawnSync.
|
|
101
|
+
const SPIN_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
102
|
+
export interface Spinner {
|
|
103
|
+
stop: (final?: string) => void;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function spin(message: string | (() => string)): Spinner {
|
|
107
|
+
// Message can be a live function (e.g. an elapsed-time counter), re-evaluated
|
|
108
|
+
// on every frame.
|
|
109
|
+
const msg = (): string => (typeof message === "function" ? message() : message);
|
|
110
|
+
// No TTY (piped/CI): no cursor tricks — print the message once, plainly.
|
|
111
|
+
if (!process.stdout.isTTY) {
|
|
112
|
+
console.log(c.gray(` ${msg()}…`));
|
|
113
|
+
return { stop: (final) => { if (final) console.log(final); } };
|
|
114
|
+
}
|
|
115
|
+
let i = 0;
|
|
116
|
+
process.stdout.write("\x1b[?25l"); // hide cursor
|
|
117
|
+
const draw = (): void => {
|
|
118
|
+
process.stdout.write(`\r\x1b[2K${c.cyan(SPIN_FRAMES[i % SPIN_FRAMES.length]!)} ${c.gray(msg())}`);
|
|
119
|
+
i++;
|
|
120
|
+
};
|
|
121
|
+
draw();
|
|
122
|
+
const timer = setInterval(draw, 80);
|
|
123
|
+
return {
|
|
124
|
+
stop: (final?: string): void => {
|
|
125
|
+
clearInterval(timer);
|
|
126
|
+
process.stdout.write("\r\x1b[2K\x1b[?25h"); // clear line + restore cursor
|
|
127
|
+
if (final) console.log(final);
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Run async work under a spinner; always stops the spinner, even on throw.
|
|
133
|
+
export async function withSpinner<T>(message: string, fn: () => Promise<T>): Promise<T> {
|
|
134
|
+
const s = spin(message);
|
|
135
|
+
try {
|
|
136
|
+
return await fn();
|
|
137
|
+
} finally {
|
|
138
|
+
s.stop();
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// A visible backoff: spin for `ms` so a silent wait doesn't look like a hang.
|
|
143
|
+
export async function pause(ms: number, message: string): Promise<void> {
|
|
144
|
+
const s = spin(message);
|
|
145
|
+
await new Promise((r) => setTimeout(r, ms));
|
|
146
|
+
s.stop();
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Is a CLI tool on PATH? Uses which/where (real executables) rather than the
|
|
150
|
+
// `command -v` shell builtin, so we avoid `shell: true` — which both triggers
|
|
151
|
+
// Node 25's DEP0190 warning and is an injection risk.
|
|
152
|
+
export function commandExists(cmd: string): boolean {
|
|
153
|
+
const probe = process.platform === "win32" ? "where" : "which";
|
|
154
|
+
const r = spawnSync(probe, [cmd], { encoding: "utf8" });
|
|
155
|
+
return (r.status ?? 1) === 0 && (r.stdout ?? "").trim().length > 0;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// 256-bit random hex token (for MCP_AUTH_TOKEN / signing secret).
|
|
159
|
+
export function genToken(): string {
|
|
160
|
+
return randomBytes(32).toString("hex");
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Cryptographically-random password. Rejection sampling over an unambiguous
|
|
164
|
+
// alphabet (no 0/O/1/l/I) plus symbols for entropy — safe to read/retype.
|
|
165
|
+
export function genPassword(len = 18): string {
|
|
166
|
+
const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*-_=+";
|
|
167
|
+
const max = Math.floor(256 / alphabet.length) * alphabet.length; // reject modulo bias
|
|
168
|
+
let out = "";
|
|
169
|
+
while (out.length < len) {
|
|
170
|
+
const b = randomBytes(1)[0]!;
|
|
171
|
+
if (b < max) out += alphabet[b % alphabet.length];
|
|
172
|
+
}
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Best-effort copy to the OS clipboard. Returns true on success, false if no
|
|
177
|
+
// clipboard tool is available (never throws).
|
|
178
|
+
export function copyToClipboard(text: string): boolean {
|
|
179
|
+
const [cmd, args]: [string, string[]] =
|
|
180
|
+
process.platform === "darwin" ? ["pbcopy", []]
|
|
181
|
+
: process.platform === "win32" ? ["clip", []]
|
|
182
|
+
: ["xclip", ["-selection", "clipboard"]];
|
|
183
|
+
try {
|
|
184
|
+
const r = spawnSync(cmd, args, { input: text });
|
|
185
|
+
return (r.status ?? 1) === 0;
|
|
186
|
+
} catch {
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Run a bundled script resiliently. A published install (`npm install -g`)
|
|
192
|
+
// ships the compiled `dist/*.js` and only runtime deps — no `tsx`/`typescript`.
|
|
193
|
+
// A dev checkout has `tsx` + the TypeScript source. Prefer whichever fits:
|
|
194
|
+
// dist+node by default (works everywhere), source+tsx when `preferSource` is set
|
|
195
|
+
// (live dev, picks up edits without a rebuild). `relNoExt` is relative to src/
|
|
196
|
+
// or dist/ without extension, e.g. "scripts/cognito_bootstrap" or "server".
|
|
197
|
+
export function runScript(
|
|
198
|
+
root: string,
|
|
199
|
+
relNoExt: string,
|
|
200
|
+
args: string[] = [],
|
|
201
|
+
opts: { preferSource?: boolean } & SpawnOptions = {},
|
|
202
|
+
): Promise<number> {
|
|
203
|
+
const { preferSource = false, ...spawnOpts } = opts;
|
|
204
|
+
const distJs = resolve(root, "dist", `${relNoExt}.js`);
|
|
205
|
+
const srcTs = resolve(root, "src", `${relNoExt}.ts`);
|
|
206
|
+
const tsx = resolve(root, "node_modules", ".bin", "tsx");
|
|
207
|
+
const viaDist: [string, string] = [process.execPath, distJs];
|
|
208
|
+
const viaTsx: [string, string] = [tsx, srcTs];
|
|
209
|
+
const order = preferSource ? [viaTsx, viaDist] : [viaDist, viaTsx];
|
|
210
|
+
for (const [bin, script] of order) {
|
|
211
|
+
const binOk = bin === process.execPath || existsSync(bin);
|
|
212
|
+
if (binOk && existsSync(script)) return run(bin, [script, ...args], { cwd: root, ...spawnOpts });
|
|
213
|
+
}
|
|
214
|
+
console.error(c.red(`Can't run ${relNoExt}: need either a built dist/ or the tsx dev dependency.`));
|
|
215
|
+
console.error(c.gray("Run ") + c.bold("npm install && totem build") + c.gray(" in a source checkout, or reinstall the published package."));
|
|
216
|
+
return Promise.resolve(1);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Ensure a CLI tool is on PATH; if not, offer to install it (with permission).
|
|
220
|
+
// Tries brew → npm → install script, in that order, based on what's available.
|
|
221
|
+
// Note: a freshly installed tool often isn't on this process's PATH yet, so we
|
|
222
|
+
// re-check and, if still missing, tell the user to re-run in a new shell.
|
|
223
|
+
export async function ensureCli(
|
|
224
|
+
name: string,
|
|
225
|
+
opts: { brewPkg?: string; npmPkg?: string; scriptUrl?: string; manualHint: string },
|
|
226
|
+
): Promise<boolean> {
|
|
227
|
+
if (commandExists(name)) return true;
|
|
228
|
+
console.log(c.yellow(` ${name} isn't installed.`));
|
|
229
|
+
// Collect the install methods that are actually available and try them in
|
|
230
|
+
// order (brew → npm → script), falling THROUGH if one fails (e.g. a brew
|
|
231
|
+
// formula doesn't exist) instead of giving up after the first.
|
|
232
|
+
const methods: Array<[string, string[]]> = [];
|
|
233
|
+
if (opts.brewPkg && commandExists("brew")) methods.push(["brew", ["install", opts.brewPkg]]);
|
|
234
|
+
if (opts.npmPkg && commandExists("npm")) methods.push(["npm", ["install", "-g", opts.npmPkg]]);
|
|
235
|
+
if (opts.scriptUrl) methods.push(["sh", ["-c", `curl -fsSL ${opts.scriptUrl} | sh`]]);
|
|
236
|
+
if (methods.length === 0) {
|
|
237
|
+
console.log(c.gray(` Install it manually: ${opts.manualHint}`));
|
|
238
|
+
return false;
|
|
239
|
+
}
|
|
240
|
+
for (const [cmd, args] of methods) {
|
|
241
|
+
console.log(c.gray(` $ ${cmd} ${args.join(" ")}`));
|
|
242
|
+
if (!(await promptYesNo(`Install ${name} via \`${cmd}\`?`, true))) continue;
|
|
243
|
+
if ((await run(cmd, args)) === 0 && commandExists(name)) return true;
|
|
244
|
+
console.log(c.yellow(` ${cmd} didn't get ${name} working${methods.length > 1 ? " — trying the next method" : ""}.`));
|
|
245
|
+
}
|
|
246
|
+
if (!commandExists(name)) {
|
|
247
|
+
console.log(c.yellow(` ${name} still isn't on this shell's PATH.`));
|
|
248
|
+
console.log(c.gray(` ${opts.manualHint} — or open a new terminal and re-run.`));
|
|
249
|
+
return false;
|
|
250
|
+
}
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// Open a URL in the default browser, cross-platform. Best-effort, never throws.
|
|
255
|
+
export function openUrl(url: string): void {
|
|
256
|
+
const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
|
|
257
|
+
const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
258
|
+
try { spawnSync(cmd, args, { stdio: "ignore" }); } catch { /* best-effort */ }
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// GET a URL, resolve with {status, body}. Used for health + OAuth metadata checks.
|
|
262
|
+
export function httpGet(url: string, timeoutMs = 12_000): Promise<{ status: number; body: string }> {
|
|
263
|
+
return new Promise((res) => {
|
|
264
|
+
const u = new URL(url);
|
|
265
|
+
const req = httpsRequest(
|
|
266
|
+
{ method: "GET", hostname: u.hostname, port: u.port || 443, path: u.pathname + u.search, headers: { "user-agent": "totem-setup" } },
|
|
267
|
+
(response) => {
|
|
268
|
+
let body = "";
|
|
269
|
+
response.setEncoding("utf8");
|
|
270
|
+
response.on("data", (ch: string) => (body += ch));
|
|
271
|
+
response.on("end", () => res({ status: response.statusCode ?? 0, body }));
|
|
272
|
+
},
|
|
273
|
+
);
|
|
274
|
+
req.setTimeout(timeoutMs, () => { req.destroy(); res({ status: 0, body: "" }); });
|
|
275
|
+
req.on("error", () => res({ status: 0, body: "" }));
|
|
276
|
+
req.end();
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export function ping(url: string, timeoutMs = 10_000): Promise<number> {
|
|
281
|
+
return httpGet(url, timeoutMs).then((r) => {
|
|
282
|
+
const ok = r.status >= 200 && r.status < 300;
|
|
283
|
+
const label = ok ? c.green(`✓ ${r.status}`) : c.red(`✗ ${r.status || "timeout"}`);
|
|
284
|
+
const preview = r.body.length > 100 ? r.body.slice(0, 97) + "..." : r.body;
|
|
285
|
+
console.log(`${label} ${url} ${c.gray(preview.replace(/\s+/g, " ").trim())}`);
|
|
286
|
+
return ok ? 0 : 1;
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// ── interactive prompts ─────────────────────────────────────────────────────
|
|
291
|
+
// A fresh readline per question. Long-lived readlines break when a subprocess
|
|
292
|
+
// in between (e.g. the build step) inherits stdin, so we open/close per ask.
|
|
293
|
+
// On EOF (piped input) the question resolves empty instead of throwing.
|
|
294
|
+
async function ask(query: string): Promise<string> {
|
|
295
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
296
|
+
// Ctrl-C during a text prompt: readline swallows SIGINT (emits it on the
|
|
297
|
+
// interface). Handle it here — restore the cursor, drop a line, exit.
|
|
298
|
+
rl.on("SIGINT", () => { process.stderr.write("\x1b[?25h"); process.stdout.write("\n"); process.exit(130); });
|
|
299
|
+
try {
|
|
300
|
+
// Resolve "" if the stream closes (EOF) so the caller falls back to its
|
|
301
|
+
// default instead of hanging.
|
|
302
|
+
return await new Promise<string>((resolve) => {
|
|
303
|
+
rl.once("close", () => resolve(""));
|
|
304
|
+
rl.question(query).then((a) => resolve(a.trim())).catch(() => resolve(""));
|
|
305
|
+
});
|
|
306
|
+
} finally {
|
|
307
|
+
rl.close();
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// Kept for API compatibility; no-op now that prompts are per-call.
|
|
312
|
+
export function closePrompts(): void {}
|
|
313
|
+
|
|
314
|
+
export async function prompt(question: string, fallback = ""): Promise<string> {
|
|
315
|
+
const suffix = fallback ? c.gray(` [${fallback}]`) : "";
|
|
316
|
+
const answer = await ask(`${c.violet("?")} ${c.white(question)}${suffix}${c.gray(" ›")} `);
|
|
317
|
+
return answer || fallback;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// Like `ask`, but typed characters are NOT echoed — standard password-prompt
|
|
321
|
+
// behavior, so a secret never appears on screen (or on camera). The override
|
|
322
|
+
// lets the prompt itself and the commit newline through and swallows every
|
|
323
|
+
// per-character echo; readline still captures the full value in its buffer.
|
|
324
|
+
async function askHidden(query: string): Promise<string> {
|
|
325
|
+
// Explicit raw-mode read: readline's _writeToOutput trick doesn't reliably
|
|
326
|
+
// disable the TERMINAL's own echo, so the secret can still render. Here we set
|
|
327
|
+
// raw mode ourselves (terminal echo off), read char-by-char, and echo nothing
|
|
328
|
+
// — the password never appears on screen. Falls back to a normal line read
|
|
329
|
+
// when there's no TTY to put in raw mode (piped/CI).
|
|
330
|
+
const stdin = process.stdin;
|
|
331
|
+
if (!(stdin.isTTY && typeof stdin.setRawMode === "function")) return ask(query);
|
|
332
|
+
|
|
333
|
+
process.stdout.write(query);
|
|
334
|
+
return new Promise<string>((resolve) => {
|
|
335
|
+
let buf = "";
|
|
336
|
+
const cleanup = (): void => {
|
|
337
|
+
stdin.removeListener("data", onData);
|
|
338
|
+
try { stdin.setRawMode(false); } catch { /* */ }
|
|
339
|
+
stdin.pause();
|
|
340
|
+
};
|
|
341
|
+
const onData = (chunk: string): void => {
|
|
342
|
+
for (const ch of chunk) {
|
|
343
|
+
if (ch === "\r" || ch === "\n" || ch === "\u0004") { cleanup(); process.stdout.write("\n"); resolve(buf.trim()); return; }
|
|
344
|
+
if (ch === "\u0003") { cleanup(); process.stdout.write("\n"); process.exit(130); } // Ctrl-C
|
|
345
|
+
if (ch === "\u007f" || ch === "\b") { buf = buf.slice(0, -1); continue; } // backspace
|
|
346
|
+
if (ch >= " ") buf += ch; // printable: captured, not echoed
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
stdin.setRawMode(true);
|
|
350
|
+
stdin.resume();
|
|
351
|
+
stdin.setEncoding("utf8");
|
|
352
|
+
stdin.on("data", onData);
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// A masked prompt for secrets (the Whoop account password). Same look as
|
|
357
|
+
// `prompt`, but nothing you type is shown.
|
|
358
|
+
export async function promptHidden(question: string): Promise<string> {
|
|
359
|
+
return askHidden(`${c.violet("?")} ${c.white(question)}${c.gray(" ›")} `);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// Enter — and ANY answer that isn't an explicit "no" — proceeds when `defaultYes`
|
|
363
|
+
// is set. To decline you must actually type n / no / N / NO. (When `defaultYes`
|
|
364
|
+
// is false it's the mirror: only an explicit y / yes proceeds.)
|
|
365
|
+
export async function promptYesNo(question: string, defaultYes = true): Promise<boolean> {
|
|
366
|
+
const hint = defaultYes ? `${c.green(c.bold("Y"))}${c.gray("/n")}` : `${c.gray("y/")}${c.red(c.bold("N"))}`;
|
|
367
|
+
const answer = (await ask(`${c.violet("?")} ${c.white(question)} ${c.gray("(")}${hint}${c.gray(")")}${c.gray(" ›")} `)).trim().toLowerCase();
|
|
368
|
+
if (defaultYes) return !/^(n|no)$/.test(answer);
|
|
369
|
+
return /^(y|yes)$/.test(answer);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// Numbered menu. Returns the 0-based index of the choice. Used as the non-TTY
|
|
373
|
+
// fallback for select() (piped stdin can't do raw-mode arrow keys).
|
|
374
|
+
export async function promptChoice(question: string, choices: string[]): Promise<number> {
|
|
375
|
+
console.log(`${c.violet("?")} ${c.bold(c.white(question))}`);
|
|
376
|
+
choices.forEach((ch, i) => console.log(` ${c.cyan(c.bold(String(i + 1)))}${c.gray(".")} ${ch}`));
|
|
377
|
+
for (let attempts = 0; attempts < 100; attempts++) {
|
|
378
|
+
const raw = await ask(` ${c.gray("enter a number")}: `);
|
|
379
|
+
const n = parseInt(raw, 10);
|
|
380
|
+
if (Number.isInteger(n) && n >= 1 && n <= choices.length) return n - 1;
|
|
381
|
+
if (raw === "") return 0; // EOF / piped input → first choice (safe default)
|
|
382
|
+
console.log(c.red(` Please enter 1-${choices.length}.`));
|
|
383
|
+
}
|
|
384
|
+
return 0;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// ── arrow-key selector ──────────────────────────────────────────────────────
|
|
388
|
+
// Up/down (or j/k, or 1-9) to move, Enter to pick, Ctrl-C to cancel. Each choice
|
|
389
|
+
// is a label with an optional dim hint. Returns the 0-based index. Falls back to
|
|
390
|
+
// the numbered prompt when stdin/stdout isn't an interactive TTY (pipes, CI).
|
|
391
|
+
export interface SelectChoice {
|
|
392
|
+
label: string;
|
|
393
|
+
hint?: string | undefined;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
export async function select(
|
|
397
|
+
question: string,
|
|
398
|
+
choices: Array<string | SelectChoice>,
|
|
399
|
+
opts: { defaultIndex?: number } = {},
|
|
400
|
+
): Promise<number> {
|
|
401
|
+
const items = choices.map((ch) => (typeof ch === "string" ? { label: ch } : ch));
|
|
402
|
+
const stdin = process.stdin;
|
|
403
|
+
const interactive = Boolean(stdin.isTTY) && Boolean(process.stdout.isTTY) && typeof stdin.setRawMode === "function";
|
|
404
|
+
if (!interactive) {
|
|
405
|
+
return promptChoice(question, items.map((it) => (it.hint ? `${it.label} ${c.gray(it.hint)}` : it.label)));
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
let idx = Math.min(Math.max(opts.defaultIndex ?? 0, 0), items.length - 1);
|
|
409
|
+
|
|
410
|
+
const render = (first: boolean): void => {
|
|
411
|
+
if (!first) process.stdout.write(`\x1b[${items.length + 1}A`); // back up to the question line
|
|
412
|
+
process.stdout.write(`\r\x1b[2K${c.violet("?")} ${c.bold(c.white(question))} ${c.dim("↑/↓ · enter")}\n`);
|
|
413
|
+
items.forEach((it, i) => {
|
|
414
|
+
const selected = i === idx;
|
|
415
|
+
const pointer = selected ? c.cyan("❯") : " ";
|
|
416
|
+
const label = selected ? c.bold(c.cyan(it.label)) : c.white(it.label);
|
|
417
|
+
const hint = it.hint ? " " + c.dim(it.hint) : "";
|
|
418
|
+
process.stdout.write(`\r\x1b[2K ${pointer} ${label}${hint}\n`);
|
|
419
|
+
});
|
|
420
|
+
};
|
|
421
|
+
|
|
422
|
+
render(true);
|
|
423
|
+
process.stdout.write("\x1b[?25l"); // hide the blinking cursor while the menu is active
|
|
424
|
+
stdin.setRawMode(true);
|
|
425
|
+
stdin.resume();
|
|
426
|
+
stdin.setEncoding("utf8");
|
|
427
|
+
|
|
428
|
+
const n = items.length;
|
|
429
|
+
return new Promise<number>((resolveSel) => {
|
|
430
|
+
const cleanup = (): void => {
|
|
431
|
+
stdin.setRawMode(false);
|
|
432
|
+
stdin.pause();
|
|
433
|
+
stdin.removeListener("data", onData);
|
|
434
|
+
process.stdout.write("\x1b[?25h"); // restore the cursor once a choice is made
|
|
435
|
+
};
|
|
436
|
+
// Scan the chunk left-to-right rather than exact-matching the whole thing:
|
|
437
|
+
// a single read can batch several bytes (a paste, a fast double-press, or a
|
|
438
|
+
// terminal/PTY that delivers the arrow sequence and the Enter together like
|
|
439
|
+
// "\x1b[B\r"). Incomplete escape sequences at a chunk boundary are stashed in
|
|
440
|
+
// `pending` and prepended to the next read so a split "\x1b" + "[B" still works.
|
|
441
|
+
let pending = "";
|
|
442
|
+
const onData = (raw: string): void => {
|
|
443
|
+
const chunk = pending + raw;
|
|
444
|
+
pending = "";
|
|
445
|
+
if (chunk.includes("\x03")) { cleanup(); process.stdout.write("\n"); process.exit(130); }
|
|
446
|
+
let moved = false;
|
|
447
|
+
let i = 0;
|
|
448
|
+
while (i < chunk.length) {
|
|
449
|
+
const rest = chunk.slice(i);
|
|
450
|
+
const ch = rest[0]!;
|
|
451
|
+
if (ch === "\r" || ch === "\n") { cleanup(); if (moved) render(false); resolveSel(idx); return; }
|
|
452
|
+
if (ch === "\x1b") {
|
|
453
|
+
if (rest === "\x1b" || rest === "\x1b[") { pending = rest; break; } // incomplete — wait for more
|
|
454
|
+
if (rest.startsWith("\x1b[A")) { idx = (idx - 1 + n) % n; moved = true; i += 3; continue; }
|
|
455
|
+
if (rest.startsWith("\x1b[B")) { idx = (idx + 1) % n; moved = true; i += 3; continue; }
|
|
456
|
+
i += rest.length >= 3 ? 3 : rest.length; continue; // unknown escape — skip it
|
|
457
|
+
}
|
|
458
|
+
if (ch === "k") { idx = (idx - 1 + n) % n; moved = true; }
|
|
459
|
+
else if (ch === "j") { idx = (idx + 1) % n; moved = true; }
|
|
460
|
+
else if (/[1-9]/.test(ch)) { const x = parseInt(ch, 10) - 1; if (x < n) { idx = x; moved = true; } }
|
|
461
|
+
i += 1;
|
|
462
|
+
}
|
|
463
|
+
if (moved) render(false);
|
|
464
|
+
};
|
|
465
|
+
stdin.on("data", onData);
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// ── confirmation for sensitive actions ──────────────────────────────────────
|
|
470
|
+
// A loud, explicit y/n gate for anything that mutates cloud state, spends money,
|
|
471
|
+
// or changes permissions. Shows exactly what will run + why, so the user is
|
|
472
|
+
// giving informed consent rather than watching it happen.
|
|
473
|
+
export interface ConfirmOpts {
|
|
474
|
+
detail?: string; // one-line consequence ("grants build access to …")
|
|
475
|
+
cmd?: string; // the exact command we're about to run
|
|
476
|
+
defaultYes?: boolean; // Enter = proceed (true) vs Enter = decline (false)
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
export async function confirmStep(summary: string, opts: ConfirmOpts = {}): Promise<boolean> {
|
|
480
|
+
console.log(` ${c.yellow("⚠")} ${c.bold(c.white(summary))}`);
|
|
481
|
+
if (opts.detail) console.log(` ${c.gray(opts.detail)}`);
|
|
482
|
+
if (opts.cmd) console.log(` ${c.dim("$")} ${c.cyan(opts.cmd)}`);
|
|
483
|
+
return promptYesNo(" Proceed?", opts.defaultYes ?? true);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// Redact secret values when echoing a command so tokens/passwords never hit the
|
|
487
|
+
// screen or scrollback. Masks the value of any KEY=value whose key looks
|
|
488
|
+
// sensitive (or whose value is long enough to be a token).
|
|
489
|
+
export function maskArgs(args: string[]): string {
|
|
490
|
+
return args
|
|
491
|
+
.map((a) => {
|
|
492
|
+
const eq = a.indexOf("=");
|
|
493
|
+
if (eq <= 0) return a;
|
|
494
|
+
const key = a.slice(0, eq);
|
|
495
|
+
if (/(_?TOKEN|PASSWORD|_SECRET|BEARER|REFRESH|EMAIL)/i.test(key)) return `${key}=${c.dim("•••")}`;
|
|
496
|
+
return a;
|
|
497
|
+
})
|
|
498
|
+
.join(" ");
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// Section header for the guided flows — a violet rule + step counter + title.
|
|
502
|
+
export function step(n: number, total: number, title: string): void {
|
|
503
|
+
console.log("");
|
|
504
|
+
console.log(`${c.violet("▌")} ${c.violet(c.bold(`${n}/${total}`))} ${c.bold(c.white(title))}`);
|
|
505
|
+
}
|