@rotorsoft/act-diagram 0.3.9 → 0.4.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 (80) hide show
  1. package/README.md +27 -1
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/@types/cli/colors.d.ts +19 -0
  4. package/dist/@types/cli/colors.d.ts.map +1 -0
  5. package/dist/@types/cli/contract-index.d.ts +57 -0
  6. package/dist/@types/cli/contract-index.d.ts.map +1 -0
  7. package/dist/@types/cli/format.d.ts +22 -0
  8. package/dist/@types/cli/format.d.ts.map +1 -0
  9. package/dist/@types/cli/index.d.ts +32 -0
  10. package/dist/@types/cli/index.d.ts.map +1 -0
  11. package/dist/@types/cli/json-schema.d.ts +13 -0
  12. package/dist/@types/cli/json-schema.d.ts.map +1 -0
  13. package/dist/@types/cli/load-project.d.ts +15 -0
  14. package/dist/@types/cli/load-project.d.ts.map +1 -0
  15. package/dist/@types/cli/markdown.d.ts +3 -0
  16. package/dist/@types/cli/markdown.d.ts.map +1 -0
  17. package/dist/@types/cli/open-editor.d.ts +23 -0
  18. package/dist/@types/cli/open-editor.d.ts.map +1 -0
  19. package/dist/@types/cli/repl.d.ts +3 -0
  20. package/dist/@types/cli/repl.d.ts.map +1 -0
  21. package/dist/@types/cli/vim-keys.d.ts +34 -0
  22. package/dist/@types/cli/vim-keys.d.ts.map +1 -0
  23. package/dist/@types/client/components/ActDiagram.d.ts +17 -0
  24. package/dist/@types/client/components/ActDiagram.d.ts.map +1 -0
  25. package/dist/@types/client/components/AiBar.d.ts +11 -0
  26. package/dist/@types/client/components/AiBar.d.ts.map +1 -0
  27. package/dist/@types/client/components/CodePreview.d.ts +10 -0
  28. package/dist/@types/client/components/CodePreview.d.ts.map +1 -0
  29. package/dist/@types/client/components/Diagram.d.ts +11 -0
  30. package/dist/@types/client/components/Diagram.d.ts.map +1 -0
  31. package/dist/@types/client/components/Logo.d.ts +6 -0
  32. package/dist/@types/client/components/Logo.d.ts.map +1 -0
  33. package/dist/@types/client/components/Tooltip.d.ts +16 -0
  34. package/dist/@types/client/components/Tooltip.d.ts.map +1 -0
  35. package/dist/@types/client/data/prompts.d.ts +5 -0
  36. package/dist/@types/client/data/prompts.d.ts.map +1 -0
  37. package/dist/@types/client/data/sample-files.d.ts +4 -0
  38. package/dist/@types/client/data/sample-files.d.ts.map +1 -0
  39. package/dist/@types/client/lib/build-model.d.ts +21 -0
  40. package/dist/@types/client/lib/build-model.d.ts.map +1 -0
  41. package/dist/@types/client/lib/evaluate.d.ts +10 -0
  42. package/dist/@types/client/lib/evaluate.d.ts.map +1 -0
  43. package/dist/@types/client/lib/layout.d.ts +82 -0
  44. package/dist/@types/client/lib/layout.d.ts.map +1 -0
  45. package/dist/@types/client/lib/mock-builders.d.ts +18 -0
  46. package/dist/@types/client/lib/mock-builders.d.ts.map +1 -0
  47. package/dist/@types/client/lib/navigate.d.ts +16 -0
  48. package/dist/@types/client/lib/navigate.d.ts.map +1 -0
  49. package/dist/@types/client/lib/schema-extract.d.ts +37 -0
  50. package/dist/@types/client/lib/schema-extract.d.ts.map +1 -0
  51. package/dist/@types/client/lib/sort.d.ts +4 -0
  52. package/dist/@types/client/lib/sort.d.ts.map +1 -0
  53. package/dist/@types/client/lib/strip-fences.d.ts +11 -0
  54. package/dist/@types/client/lib/strip-fences.d.ts.map +1 -0
  55. package/dist/@types/client/lib/validate.d.ts +4 -0
  56. package/dist/@types/client/lib/validate.d.ts.map +1 -0
  57. package/dist/@types/client/main.d.ts +2 -0
  58. package/dist/@types/client/main.d.ts.map +1 -0
  59. package/dist/@types/client/types/domain-model.d.ts +85 -0
  60. package/dist/@types/client/types/domain-model.d.ts.map +1 -0
  61. package/dist/@types/client/types/file-tab.d.ts +5 -0
  62. package/dist/@types/client/types/file-tab.d.ts.map +1 -0
  63. package/dist/@types/client/types/index.d.ts +5 -0
  64. package/dist/@types/client/types/index.d.ts.map +1 -0
  65. package/dist/@types/client/types/protocol.d.ts +29 -0
  66. package/dist/@types/client/types/protocol.d.ts.map +1 -0
  67. package/dist/@types/index.d.ts +17 -0
  68. package/dist/@types/index.d.ts.map +1 -0
  69. package/dist/@types/server/ai.d.ts +19 -0
  70. package/dist/@types/server/ai.d.ts.map +1 -0
  71. package/dist/@types/server/server.d.ts +2 -0
  72. package/dist/@types/server/server.d.ts.map +1 -0
  73. package/dist/cli/act.js +3324 -0
  74. package/dist/cli/act.js.map +1 -0
  75. package/dist/index.cjs +3268 -0
  76. package/dist/index.cjs.map +1 -0
  77. package/dist/index.js +3235 -0
  78. package/dist/index.js.map +1 -0
  79. package/dist/styles.css +2 -0
  80. package/package.json +17 -7
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js","../../../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js","../../src/cli/index.ts","../../src/client/lib/evaluate.ts","../../src/client/lib/schema-extract.ts","../../src/client/lib/build-model.ts","../../src/client/lib/mock-builders.ts","../../src/client/lib/sort.ts","../../src/cli/contract-index.ts","../../src/cli/colors.ts","../../src/cli/format.ts","../../src/cli/json-schema.ts","../../src/cli/load-project.ts","../../src/cli/markdown.ts","../../src/cli/repl.ts","../../../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/utils.js","../../../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/index.js","../../../../node_modules/.pnpm/fast-string-width@3.0.2/node_modules/fast-string-width/dist/index.js","../../../../node_modules/.pnpm/fast-wrap-ansi@0.2.0/node_modules/fast-wrap-ansi/src/main.ts","../../../../node_modules/.pnpm/@clack+core@1.3.1/node_modules/@clack/core/src/utils/cursor.ts","../../../../node_modules/.pnpm/@clack+core@1.3.1/node_modules/@clack/core/src/utils/settings.ts","../../../../node_modules/.pnpm/@clack+core@1.3.1/node_modules/@clack/core/src/utils/string.ts","../../../../node_modules/.pnpm/@clack+core@1.3.1/node_modules/@clack/core/src/utils/index.ts","../../../../node_modules/.pnpm/@clack+core@1.3.1/node_modules/@clack/core/src/prompts/prompt.ts","../../../../node_modules/.pnpm/@clack+core@1.3.1/node_modules/@clack/core/src/prompts/autocomplete.ts","../../../../node_modules/.pnpm/@clack+core@1.3.1/node_modules/@clack/core/src/prompts/confirm.ts","../../../../node_modules/.pnpm/@clack+core@1.3.1/node_modules/@clack/core/src/prompts/date.ts","../../../../node_modules/.pnpm/@clack+core@1.3.1/node_modules/@clack/core/src/prompts/group-multiselect.ts","../../../../node_modules/.pnpm/@clack+core@1.3.1/node_modules/@clack/core/src/prompts/multi-line.ts","../../../../node_modules/.pnpm/@clack+core@1.3.1/node_modules/@clack/core/src/prompts/multi-select.ts","../../../../node_modules/.pnpm/@clack+core@1.3.1/node_modules/@clack/core/src/prompts/password.ts","../../../../node_modules/.pnpm/@clack+core@1.3.1/node_modules/@clack/core/src/prompts/select.ts","../../../../node_modules/.pnpm/@clack+core@1.3.1/node_modules/@clack/core/src/prompts/select-key.ts","../../../../node_modules/.pnpm/@clack+core@1.3.1/node_modules/@clack/core/src/prompts/text.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/node_modules/.pnpm/is-unicode-supported@1.3.0/node_modules/is-unicode-supported/index.js","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/common.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/limit-options.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/autocomplete.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/box.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/confirm.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/date.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/group.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/group-multi-select.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/log.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/messages.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/multi-line.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/multi-select.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/note.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/password.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/path.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/spinner.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/progress-bar.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/select.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/select-key.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/stream.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/task.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/task-log.ts","../../../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/src/text.ts","../../src/cli/open-editor.ts","../../src/cli/vim-keys.ts"],"sourcesContent":["let p = process || {}, argv = p.argv || [], env = p.env || {}\nlet isColorSupported =\n\t!(!!env.NO_COLOR || argv.includes(\"--no-color\")) &&\n\t(!!env.FORCE_COLOR || argv.includes(\"--color\") || p.platform === \"win32\" || ((p.stdout || {}).isTTY && env.TERM !== \"dumb\") || !!env.CI)\n\nlet formatter = (open, close, replace = open) =>\n\tinput => {\n\t\tlet string = \"\" + input, index = string.indexOf(close, open.length)\n\t\treturn ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close\n\t}\n\nlet replaceClose = (string, close, replace, index) => {\n\tlet result = \"\", cursor = 0\n\tdo {\n\t\tresult += string.substring(cursor, index) + replace\n\t\tcursor = index + close.length\n\t\tindex = string.indexOf(close, cursor)\n\t} while (~index)\n\treturn result + string.substring(cursor)\n}\n\nlet createColors = (enabled = isColorSupported) => {\n\tlet f = enabled ? formatter : () => String\n\treturn {\n\t\tisColorSupported: enabled,\n\t\treset: f(\"\\x1b[0m\", \"\\x1b[0m\"),\n\t\tbold: f(\"\\x1b[1m\", \"\\x1b[22m\", \"\\x1b[22m\\x1b[1m\"),\n\t\tdim: f(\"\\x1b[2m\", \"\\x1b[22m\", \"\\x1b[22m\\x1b[2m\"),\n\t\titalic: f(\"\\x1b[3m\", \"\\x1b[23m\"),\n\t\tunderline: f(\"\\x1b[4m\", \"\\x1b[24m\"),\n\t\tinverse: f(\"\\x1b[7m\", \"\\x1b[27m\"),\n\t\thidden: f(\"\\x1b[8m\", \"\\x1b[28m\"),\n\t\tstrikethrough: f(\"\\x1b[9m\", \"\\x1b[29m\"),\n\n\t\tblack: f(\"\\x1b[30m\", \"\\x1b[39m\"),\n\t\tred: f(\"\\x1b[31m\", \"\\x1b[39m\"),\n\t\tgreen: f(\"\\x1b[32m\", \"\\x1b[39m\"),\n\t\tyellow: f(\"\\x1b[33m\", \"\\x1b[39m\"),\n\t\tblue: f(\"\\x1b[34m\", \"\\x1b[39m\"),\n\t\tmagenta: f(\"\\x1b[35m\", \"\\x1b[39m\"),\n\t\tcyan: f(\"\\x1b[36m\", \"\\x1b[39m\"),\n\t\twhite: f(\"\\x1b[37m\", \"\\x1b[39m\"),\n\t\tgray: f(\"\\x1b[90m\", \"\\x1b[39m\"),\n\n\t\tbgBlack: f(\"\\x1b[40m\", \"\\x1b[49m\"),\n\t\tbgRed: f(\"\\x1b[41m\", \"\\x1b[49m\"),\n\t\tbgGreen: f(\"\\x1b[42m\", \"\\x1b[49m\"),\n\t\tbgYellow: f(\"\\x1b[43m\", \"\\x1b[49m\"),\n\t\tbgBlue: f(\"\\x1b[44m\", \"\\x1b[49m\"),\n\t\tbgMagenta: f(\"\\x1b[45m\", \"\\x1b[49m\"),\n\t\tbgCyan: f(\"\\x1b[46m\", \"\\x1b[49m\"),\n\t\tbgWhite: f(\"\\x1b[47m\", \"\\x1b[49m\"),\n\n\t\tblackBright: f(\"\\x1b[90m\", \"\\x1b[39m\"),\n\t\tredBright: f(\"\\x1b[91m\", \"\\x1b[39m\"),\n\t\tgreenBright: f(\"\\x1b[92m\", \"\\x1b[39m\"),\n\t\tyellowBright: f(\"\\x1b[93m\", \"\\x1b[39m\"),\n\t\tblueBright: f(\"\\x1b[94m\", \"\\x1b[39m\"),\n\t\tmagentaBright: f(\"\\x1b[95m\", \"\\x1b[39m\"),\n\t\tcyanBright: f(\"\\x1b[96m\", \"\\x1b[39m\"),\n\t\twhiteBright: f(\"\\x1b[97m\", \"\\x1b[39m\"),\n\n\t\tbgBlackBright: f(\"\\x1b[100m\", \"\\x1b[49m\"),\n\t\tbgRedBright: f(\"\\x1b[101m\", \"\\x1b[49m\"),\n\t\tbgGreenBright: f(\"\\x1b[102m\", \"\\x1b[49m\"),\n\t\tbgYellowBright: f(\"\\x1b[103m\", \"\\x1b[49m\"),\n\t\tbgBlueBright: f(\"\\x1b[104m\", \"\\x1b[49m\"),\n\t\tbgMagentaBright: f(\"\\x1b[105m\", \"\\x1b[49m\"),\n\t\tbgCyanBright: f(\"\\x1b[106m\", \"\\x1b[49m\"),\n\t\tbgWhiteBright: f(\"\\x1b[107m\", \"\\x1b[49m\"),\n\t}\n}\n\nmodule.exports = createColors()\nmodule.exports.createColors = createColors\n","'use strict';\n\nconst ESC = '\\x1B';\nconst CSI = `${ESC}[`;\nconst beep = '\\u0007';\n\nconst cursor = {\n to(x, y) {\n if (!y) return `${CSI}${x + 1}G`;\n return `${CSI}${y + 1};${x + 1}H`;\n },\n move(x, y) {\n let ret = '';\n\n if (x < 0) ret += `${CSI}${-x}D`;\n else if (x > 0) ret += `${CSI}${x}C`;\n\n if (y < 0) ret += `${CSI}${-y}A`;\n else if (y > 0) ret += `${CSI}${y}B`;\n\n return ret;\n },\n up: (count = 1) => `${CSI}${count}A`,\n down: (count = 1) => `${CSI}${count}B`,\n forward: (count = 1) => `${CSI}${count}C`,\n backward: (count = 1) => `${CSI}${count}D`,\n nextLine: (count = 1) => `${CSI}E`.repeat(count),\n prevLine: (count = 1) => `${CSI}F`.repeat(count),\n left: `${CSI}G`,\n hide: `${CSI}?25l`,\n show: `${CSI}?25h`,\n save: `${ESC}7`,\n restore: `${ESC}8`\n}\n\nconst scroll = {\n up: (count = 1) => `${CSI}S`.repeat(count),\n down: (count = 1) => `${CSI}T`.repeat(count)\n}\n\nconst erase = {\n screen: `${CSI}2J`,\n up: (count = 1) => `${CSI}1J`.repeat(count),\n down: (count = 1) => `${CSI}J`.repeat(count),\n line: `${CSI}2K`,\n lineEnd: `${CSI}K`,\n lineStart: `${CSI}1K`,\n lines(count) {\n let clear = '';\n for (let i = 0; i < count; i++)\n clear += this.line + (i < count - 1 ? cursor.up() : '');\n if (count)\n clear += cursor.left;\n return clear;\n }\n}\n\nmodule.exports = { cursor, scroll, erase, beep };\n","#!/usr/bin/env node\n/**\n * `act` — interactive Act-app contracts explorer.\n *\n * Walks the project for TypeScript sources, feeds them through the\n * same `extractModel` parser the diagram uses, and lets you navigate\n * the domain model: category → entry → formatted detail → optional\n * jump-to-source in $EDITOR.\n *\n * Run with `pnpm act [dir]` from the repo root or\n * `pnpm -F @rotorsoft/act-diagram act [dir]` from anywhere.\n */\nimport { resolve } from \"node:path\";\nimport { extractModel } from \"../client/lib/evaluate.js\";\nimport { buildContractIndex, search } from \"./contract-index.js\";\nimport { formatDetail, formatMatches } from \"./format.js\";\nimport { formatJsonSchema } from \"./json-schema.js\";\nimport { loadProject } from \"./load-project.js\";\nimport { formatMarkdown } from \"./markdown.js\";\nimport { runInteractive } from \"./repl.js\";\n\nexport type CliArgs = {\n cwd?: string;\n help: boolean;\n version: boolean;\n maxFiles?: number;\n /** Non-interactive: print detail for the named entity and exit. */\n query?: string;\n /** Non-interactive: print the full registry as Markdown and exit. */\n markdown?: boolean;\n /** Non-interactive: print the full registry as JSON Schema and exit. */\n jsonSchema?: boolean;\n};\n\nexport function parseArgs(argv: readonly string[]): CliArgs {\n let cwd: string | undefined;\n let help = false;\n let version = false;\n let maxFiles: number | undefined;\n let query: string | undefined;\n let markdown = false;\n let jsonSchema = false;\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i];\n if (a === \"-h\" || a === \"--help\") help = true;\n else if (a === \"-v\" || a === \"--version\") version = true;\n else if (a === \"--cwd\") cwd = argv[++i] ?? cwd;\n else if (a === \"-q\" || a === \"--query\") query = argv[++i] ?? query;\n else if (a === \"-m\" || a === \"--markdown\" || a === \"--md\") markdown = true;\n else if (a === \"-j\" || a === \"--json-schema\" || a === \"--json\")\n jsonSchema = true;\n else if (a === \"--max-files\") {\n const n = Number.parseInt(argv[++i] ?? \"\", 10);\n if (Number.isFinite(n) && n > 0) maxFiles = n;\n } else if (!a.startsWith(\"-\")) cwd = a;\n }\n return { cwd, help, version, maxFiles, query, markdown, jsonSchema };\n}\n\nconst USAGE = [\n \"Usage: act [dir] [-q <name>] [-m | -j] [--cwd <dir>] [--max-files <n>] [--help] [--version]\",\n \"\",\n \"Interactive mode (default):\",\n \" pnpm act # explore the current project\",\n \" pnpm act packages/foo # explore a specific package\",\n \"\",\n \"Non-interactive (scripts, CI):\",\n \" pnpm act -q OrderPlaced # print the detail for OrderPlaced and exit\",\n \" pnpm act -m > EVENTS.md # emit the full registry as Markdown\",\n \" pnpm act -j > contracts.json # emit per-event JSON Schema (machine-readable)\",\n \"\",\n \"In interactive mode you pick a category (events, actions, slices, …),\",\n \"then an entry, then view its neighborhood. From the detail view you\",\n \"can jump straight to the source file in $EDITOR. The top menu also\",\n \"offers an `Export` action that writes Markdown or JSON Schema to a\",\n \"file path you choose.\",\n].join(\"\\n\");\n\nexport type RunDeps = {\n input: NodeJS.ReadableStream;\n output: NodeJS.WritableStream;\n errorOutput: NodeJS.WritableStream;\n isTTY: boolean;\n argv: readonly string[];\n versionString: string;\n defaultDir?: string;\n /**\n * Override for the interactive flow. Defaults to `runInteractive`.\n * Exposed so tests can drive the non-`-q` code path without hanging\n * on real clack prompts.\n */\n runInteractive?: (\n idx: ReturnType<typeof buildContractIndex>,\n rootDir: string\n ) => Promise<void>;\n};\n\nexport async function main(deps: RunDeps): Promise<number> {\n const args = parseArgs(deps.argv);\n if (args.help) {\n deps.output.write(USAGE + \"\\n\");\n return 0;\n }\n if (args.version) {\n deps.output.write(deps.versionString + \"\\n\");\n return 0;\n }\n\n const rootDir = resolve(args.cwd ?? deps.defaultDir ?? \".\");\n const { files, truncated } = await loadProject(rootDir, {\n maxFiles: args.maxFiles,\n });\n if (files.length === 0) {\n deps.errorOutput.write(\n `act: no TypeScript source files found under ${rootDir}\\n`\n );\n return 1;\n }\n if (truncated) {\n deps.errorOutput.write(\n \"act: scan was truncated (file cap reached); some sources may be missing.\\n\"\n );\n }\n const { model, error } = extractModel(files);\n /* c8 ignore start — extractModel only sets `error` when every file\n fails to evaluate; hard to synthesize in unit tests. */\n if (error) {\n deps.errorOutput.write(`act: parse error — ${error}\\n`);\n }\n /* c8 ignore stop */\n\n const idx = buildContractIndex(model);\n\n // Non-interactive Markdown registry: dump the full model and exit.\n // Pipe-friendly for `pnpm act -m > docs/EVENTS.md` and PR comments.\n if (args.markdown) {\n deps.output.write(`${formatMarkdown(idx)}\\n`);\n return 0;\n }\n\n // Non-interactive JSON Schema export: machine-readable per-event\n // schemas plus the producer/consumer graph. Cross-service consumers\n // can `Ajv.compile()` the event schemas to validate payloads.\n if (args.jsonSchema) {\n deps.output.write(`${formatJsonSchema(idx)}\\n`);\n return 0;\n }\n\n // Non-interactive scripted query: print the detail for the matching\n // entity and exit. Used by CI smoke tests and by power users in pipes.\n if (args.query) {\n const matches = search(idx, args.query);\n if (matches.length === 0) {\n deps.errorOutput.write(`act: no matches for \"${args.query}\"\\n`);\n return 1;\n }\n const exact = matches.filter(\n (m) => m.name.toLowerCase() === args.query!.toLowerCase()\n );\n // Two entries with identical (kind, name, qualifier) describe the\n // same logical entity declared in different files (e.g. a `Counter`\n // state defined in two demo entrypoints). Collapse them so `-q`\n // surfaces a detail view instead of an ambiguity menu.\n const equivKey = (m: (typeof matches)[number]) =>\n `${m.kind}\\x00${m.name}\\x00${m.qualifier ?? \"\"}`;\n const uniqExact = Array.from(\n new Map(exact.map((m) => [equivKey(m), m])).values()\n );\n if (uniqExact.length === 1) {\n deps.output.write(formatDetail(idx, uniqExact[0]) + \"\\n\");\n return 0;\n }\n const uniqMatches = Array.from(\n new Map(matches.map((m) => [equivKey(m), m])).values()\n );\n if (uniqMatches.length === 1) {\n deps.output.write(formatDetail(idx, uniqMatches[0]) + \"\\n\");\n return 0;\n }\n deps.output.write(formatMatches(args.query, uniqMatches) + \"\\n\");\n return 0;\n }\n\n // Default interactive flow ships in `repl.ts`; tests inject a stub\n // so the non-`-q` branch is exercised without the clack prompts.\n await (deps.runInteractive ?? runInteractive)(idx, rootDir);\n return 0;\n}\n\n/* c8 ignore start */\nconst isMain = (() => {\n try {\n if (typeof process === \"undefined\" || !process.argv?.[1]) return false;\n const entry = process.argv[1];\n return (\n import.meta.url === `file://${entry}` ||\n import.meta.url.endsWith(entry) ||\n entry.endsWith(\"/act\") ||\n entry.endsWith(\"/act.js\")\n );\n } catch {\n return false;\n }\n})();\n\nif (isMain) {\n main({\n input: process.stdin,\n output: process.stdout,\n errorOutput: process.stderr,\n isTTY: !!process.stdout.isTTY,\n argv: process.argv.slice(2),\n versionString: \"act (act-diagram)\",\n defaultDir: process.env.INIT_CWD ?? process.cwd(),\n }).then(\n (code) => process.exit(code),\n (err) => {\n process.stderr.write(\n `act: fatal — ${err instanceof Error ? err.message : String(err)}\\n`\n );\n process.exit(2);\n }\n );\n}\n/* c8 ignore stop */\n","/**\n * Evaluates Act builder code by executing it with mock builders,\n * then extracts the domain model for the diagram.\n */\nimport { transform } from \"sucrase\";\nimport type { DomainModel, FileTab } from \"../types/index.js\";\nimport { buildModel, type ExecuteResult } from \"./build-model.js\";\nimport { MODULES, unknownModuleProxy } from \"./mock-builders.js\";\nimport { topoSort } from \"./sort.js\";\n\n/** Replace non-executable content with same-length whitespace (preserving offsets).\n * `level: \"full\"` strips comments + strings + template literals (for scanning).\n * `level: \"nav\"` strips comments + template literals only (for navigation). */\nexport const stripNonCode = (src: string, level: \"full\" | \"nav\" = \"full\") => {\n const blank = (m: string) => m.replace(/[^\\n]/g, \" \");\n let result = src\n .replace(/\\/\\/[^\\n]*/g, blank) // line comments\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, blank) // block comments\n .replace(/`(?:\\\\[\\s\\S]|[^`\\\\])*`/g, blank); // template literals\n if (level === \"full\") {\n result = result\n .replace(/\"(?:\\\\[\\s\\S]|[^\"\\\\])*\"/g, blank) // double-quoted strings\n .replace(/'(?:\\\\[\\s\\S]|[^'\\\\])*'/g, blank); // single-quoted strings\n }\n return result;\n};\n\n/** Source file filter — excludes tests, declarations, and non-TS files */\nconst isSourceFile = (f: FileTab) =>\n f.path.endsWith(\".ts\") &&\n !f.path.endsWith(\".d.ts\") &&\n !f.path.endsWith(\".tsx\") &&\n !f.path.endsWith(\".spec.ts\") &&\n !f.path.endsWith(\".test.ts\") &&\n !f.path.includes(\"node_modules/\") &&\n !f.path.includes(\"__tests__/\") &&\n !f.path.includes(\"/test/\") &&\n !f.path.startsWith(\"test/\");\n\n// ─── Code transpilation ─────────────────────────────────────────────\n\nfunction transpile(code: string): string {\n try {\n const safe = code.replace(/\\bimport\\.meta\\.\\w+/g, \"'__import_meta__'\");\n const { code: js } = transform(safe, {\n transforms: [\"typescript\", \"imports\"],\n });\n // Strip top-level runtime invocations — we only need builder definitions.\n return js.replace(\n /^(?:void\\s+|await\\s+)?(?:main|run|start|bootstrap|seed)\\s*\\([^)]*\\)(?:\\s*\\.catch\\([^)]*\\))?;?\\s*$/gm,\n \"/* stripped runtime call */\"\n );\n } catch {\n return code;\n }\n}\n\n// ─── Per-file module execution ──────────────────────────────────────\n\nfunction execute(\n files: FileTab[]\n): ExecuteResult & { expectedSlices: Map<string, string> } {\n const result = {\n states: [] as any[],\n slices: [] as any[],\n projections: [] as any[],\n acts: [] as any[],\n error: undefined as string | undefined,\n fileErrors: new Map<string, string>(),\n expectedSlices: new Map<string, string>(),\n };\n\n try {\n const __built__: Record<string, any[]> = {\n states: [],\n slices: [],\n projections: [],\n acts: [],\n };\n\n let _currentFile = \"\";\n const capture = (type: string) => (info: any) => {\n info._sourceFile = _currentFile;\n __built__[type + \"s\"].push(info);\n };\n\n const actModule = { ...MODULES[\"@rotorsoft/act\"] };\n actModule.state = (entry: any) =>\n (MODULES[\"@rotorsoft/act\"].state as any)(entry, capture(\"state\"));\n actModule.slice = () =>\n (MODULES[\"@rotorsoft/act\"].slice as any)(capture(\"slice\"));\n actModule.projection = (target: any) =>\n (MODULES[\"@rotorsoft/act\"].projection as any)(\n target,\n capture(\"projection\")\n );\n actModule.act = () =>\n (MODULES[\"@rotorsoft/act\"].act as any)(capture(\"act\"));\n\n const pkgModules: Record<string, any> = {\n ...MODULES,\n \"@rotorsoft/act\": actModule,\n };\n\n // Per-file exports: each file gets its own exports object\n const fileExports = new Map<string, Record<string, any>>();\n\n const strip = (p: string) => p.replace(/\\.tsx?$/, \"\");\n\n const resolveModule = (\n mod: string,\n fromPath: string\n ): Record<string, any> => {\n if (pkgModules[mod]) return pkgModules[mod];\n\n if (mod.startsWith(\".\")) {\n const dir = fromPath.includes(\"/\")\n ? fromPath.slice(0, fromPath.lastIndexOf(\"/\"))\n : \"\";\n const parts = (dir ? dir + \"/\" + mod : mod).split(\"/\");\n const resolved: string[] = [];\n for (const p of parts) {\n if (p === \".\" || p === \"\") continue;\n if (p === \"..\") resolved.pop();\n else resolved.push(p);\n }\n const rp = resolved.join(\"/\").replace(/\\.js$/, \"\").replace(/\\.ts$/, \"\");\n return fileExports.get(rp) ?? fileExports.get(rp + \"/index\") ?? {};\n }\n\n if (mod.startsWith(\"@\") && !mod.startsWith(\"@rotorsoft/\")) {\n const pkgName = mod.split(\"/\")[1];\n const subPath = mod.split(\"/\").slice(2).join(\"/\");\n if (pkgName) {\n const suffix = subPath\n ? `/${subPath.replace(/\\.js$/, \"\")}`\n : \"/src/index\";\n return (\n fileExports.get(`packages/${pkgName}${suffix}`) ??\n fileExports.get(`${pkgName}${suffix}`) ??\n fileExports.get(`packages/${pkgName}/src/index`) ??\n fileExports.get(`${pkgName}/src/index`) ??\n fileExports.get(`${pkgName}/index`) ??\n fileExports.get(pkgName) ??\n unknownModuleProxy()\n );\n }\n }\n\n return unknownModuleProxy();\n };\n\n // Evaluate each file in topo order, each in its own scope\n const sorted = topoSort(files.filter(isSourceFile));\n\n for (const file of sorted) {\n _currentFile = file.path;\n const js = transpile(file.content);\n const key = strip(file.path);\n const fileExp: Record<string, any> = {};\n fileExports.set(key, fileExp);\n\n // Pre-scan: capture slice variable names before eval\n const sliceNamesInAct: string[] = [];\n const wsRe = /\\.withSlice\\(\\s*(?:\\w+\\.)*(\\w+)\\s*\\)/g;\n let wsm: RegExpExecArray | null;\n const codeOnly = stripNonCode(js);\n while ((wsm = wsRe.exec(codeOnly)) !== null) {\n if (!sliceNamesInAct.includes(wsm[1])) sliceNamesInAct.push(wsm[1]);\n }\n\n // Inventory: detect slice declarations in executable code\n // sucrase may emit slice() or slice.call(void 0, )\n for (const m of codeOnly.matchAll(\n /(?:exports\\.)?(\\w+)\\s*=\\s*(?:\\w+\\.)?slice(?:\\s*\\(\\s*\\)|\\.call\\(void 0,\\s*\\))/g\n )) {\n result.expectedSlices.set(m[1], file.path);\n }\n\n const fileRequire = Object.assign(\n (mod: string) => resolveModule(mod, key),\n { resolve: (mod: string) => mod, cache: {}, main: undefined }\n );\n\n try {\n // Strip __dirname/__filename declarations that would conflict with our injected vars\n const cleanJs = js\n .replace(/\\bconst\\s+__dirname\\b/g, \"var __dirname\")\n .replace(/\\bconst\\s+__filename\\b/g, \"var __filename\");\n // Security: new Function() is intentional — this executes the user's own\n // local project files (selected via folder picker or passed as props) to\n // extract Act builder structure. Same trust model as VS Code, Jupyter, or\n // any tool that runs user code. No HTTP input or untrusted data is evaluated.\n // eslint-disable-next-line @typescript-eslint/no-implied-eval\n const fn = new Function(\n // lgtm[js/code-injection]\n \"require\",\n \"exports\",\n \"module\",\n `\n \"use strict\";\n var __filename = ${JSON.stringify(file.path)};\n var __dirname = \".\";\n var process = { env: {}, cwd: function() { return \"/\"; }, exit: function() {}, on: function() {}, off: function() {} };\n var Buffer = { from: function() { return \"\"; } };\n var console = { log: function() {}, error: function() {}, warn: function() {}, info: function() {}, debug: function() {} };\n ${cleanJs}\n `\n );\n fn(fileRequire, fileExp, { exports: fileExp });\n } catch (evalErr: unknown) {\n // Just record the error — Step 3 creates placeholders for missing slices\n const errMsg =\n evalErr instanceof Error ? evalErr.message : String(evalErr);\n result.fileErrors.set(file.path, errMsg);\n }\n\n // Tag slices with names from .withSlice(VAR) — only for acts built in THIS file\n if (sliceNamesInAct.length > 0) {\n for (const actObj of __built__.acts) {\n if ((actObj._sourceFile as string) !== file.path) continue;\n const actSlices = actObj.slices as any[];\n for (\n let ai = 0;\n ai < Math.min(sliceNamesInAct.length, actSlices.length);\n ai++\n ) {\n if (actSlices[ai]) {\n actSlices[ai]._varName = sliceNamesInAct[ai];\n }\n }\n }\n }\n }\n\n result.states = __built__.states;\n result.slices = __built__.slices;\n result.projections = __built__.projections;\n result.acts = __built__.acts;\n } catch (e: unknown) {\n result.error = e instanceof Error ? e.message : String(e);\n }\n\n return result;\n}\n\n// ─── Model extraction ───────────────────────────────────────────────\n\nexport function extractModel(files: FileTab[]): {\n model: DomainModel;\n error?: string;\n} {\n const result = execute(files);\n return buildModel(result, files, result.expectedSlices);\n}\n","/**\n * Best-effort capture of Zod schema source text for each event declared\n * in `.emits({ ... })` blocks. The extractor walks the original source\n * (not the transpiled JS), tracks strings/comments/templates, and slices\n * out each value expression by balanced-bracket matching.\n *\n * Returned text is whatever the user wrote — `z.object({...})`,\n * `z.string()`, `OrderPlacedSchema`, even a multi-line expression. The\n * intent is fidelity to author intent rather than canonical form.\n */\n\ntype Entry = { key: string; valueStart: number; valueEnd: number };\n\nconst isWS = (c: string | undefined) =>\n c === \" \" || c === \"\\t\" || c === \"\\n\" || c === \"\\r\";\nconst isIdent = (c: string | undefined) => !!c && /[\\w$]/.test(c);\n\n/** Skip whitespace and comments starting at `from`. Returns new index. */\nfunction skipTrivia(src: string, from: number): number {\n let i = from;\n while (i < src.length) {\n const c = src[i];\n if (isWS(c)) {\n i++;\n continue;\n }\n if (c === \"/\" && src[i + 1] === \"/\") {\n while (i < src.length && src[i] !== \"\\n\") i++;\n continue;\n }\n if (c === \"/\" && src[i + 1] === \"*\") {\n i += 2;\n while (i < src.length && !(src[i - 1] === \"*\" && src[i] === \"/\")) i++;\n i++;\n continue;\n }\n break;\n }\n return i;\n}\n\n/**\n * Consume one value expression starting at `start`. Stops at a top-level\n * `,` or the closing `}` of the enclosing emits object. Returns the index\n * of that stop character.\n */\nfunction readValue(src: string, start: number): number {\n let i = start;\n let depth = 0;\n while (i < src.length) {\n const c = src[i];\n // String literals\n if (c === '\"' || c === \"'\") {\n const q = c;\n i++;\n while (i < src.length && src[i] !== q) {\n if (src[i] === \"\\\\\") {\n i += 2;\n continue;\n }\n i++;\n }\n i++;\n continue;\n }\n // Template literal — track `${...}` nesting for brace balance\n if (c === \"`\") {\n i++;\n while (i < src.length && src[i] !== \"`\") {\n if (src[i] === \"\\\\\") {\n i += 2;\n continue;\n }\n if (src[i] === \"$\" && src[i + 1] === \"{\") {\n let td = 1;\n i += 2;\n while (i < src.length && td > 0) {\n if (src[i] === \"{\") td++;\n else if (src[i] === \"}\") td--;\n if (td > 0) i++;\n }\n i++;\n continue;\n }\n i++;\n }\n i++;\n continue;\n }\n // Comments\n if (c === \"/\" && src[i + 1] === \"/\") {\n while (i < src.length && src[i] !== \"\\n\") i++;\n continue;\n }\n if (c === \"/\" && src[i + 1] === \"*\") {\n i += 2;\n while (i < src.length && !(src[i - 1] === \"*\" && src[i] === \"/\")) i++;\n i++;\n continue;\n }\n if (c === \"(\" || c === \"{\" || c === \"[\") {\n depth++;\n i++;\n continue;\n }\n if (c === \")\" || c === \"]\") {\n depth--;\n i++;\n continue;\n }\n if (c === \"}\") {\n if (depth === 0) return i;\n depth--;\n i++;\n continue;\n }\n if (c === \",\" && depth === 0) return i;\n i++;\n }\n return i;\n}\n\n/**\n * Parse the object literal whose opening `{` is at `startBrace`.\n * Returns the top-level entries and the index of the matching `}`,\n * or null if the literal was malformed.\n */\nfunction parseObjectLiteral(\n src: string,\n startBrace: number\n): { entries: Entry[]; endBrace: number } | null {\n const entries: Entry[] = [];\n let i = startBrace + 1;\n\n while (i < src.length) {\n i = skipTrivia(src, i);\n if (src[i] === \"}\") return { entries, endBrace: i };\n\n // Key — identifier or quoted string\n let key = \"\";\n let keyStart = i;\n let keyEnd = i;\n let keyWasIdentifier = false;\n if (src[i] === '\"' || src[i] === \"'\") {\n const q = src[i];\n keyStart = ++i;\n while (i < src.length && src[i] !== q) {\n if (src[i] === \"\\\\\") {\n i += 2;\n continue;\n }\n i++;\n }\n key = src.slice(keyStart, i);\n keyEnd = i;\n i++;\n } else if (isIdent(src[i])) {\n keyStart = i;\n while (isIdent(src[i])) i++;\n key = src.slice(keyStart, i);\n keyEnd = i;\n keyWasIdentifier = true;\n } else {\n // Unknown token — bail to keep extraction robust\n return null;\n }\n\n i = skipTrivia(src, i);\n if (src[i] !== \":\") {\n // Shorthand (`{ Foo, Bar }`) — value is the identifier itself.\n // This is the common case for `.emits({ TicketOpened })` patterns\n // where the schema is imported under the same name as the event.\n if (keyWasIdentifier) {\n entries.push({ key, valueStart: keyStart, valueEnd: keyEnd });\n }\n while (i < src.length && src[i] !== \",\" && src[i] !== \"}\") i++;\n if (src[i] === \",\") i++;\n continue;\n }\n i++; // \":\"\n i = skipTrivia(src, i);\n\n const valueStart = i;\n const valueEnd = readValue(src, i);\n entries.push({ key, valueStart, valueEnd });\n i = valueEnd;\n if (src[i] === \",\") i++;\n }\n return null;\n}\n\n/**\n * Consume one top-level expression starting at `start`. Stops at `;`\n * at depth 0, or end-of-file. Mirrors `readValue` but operates outside\n * an object literal — used to extract the right-hand side of\n * `const IDENT = <expr>;`.\n */\nfunction readTopLevelExpression(src: string, start: number): number {\n let i = start;\n let depth = 0;\n while (i < src.length) {\n const c = src[i];\n if (c === '\"' || c === \"'\") {\n const q = c;\n i++;\n while (i < src.length && src[i] !== q) {\n if (src[i] === \"\\\\\") {\n i += 2;\n continue;\n }\n i++;\n }\n i++;\n continue;\n }\n if (c === \"`\") {\n i++;\n while (i < src.length && src[i] !== \"`\") {\n if (src[i] === \"\\\\\") {\n i += 2;\n continue;\n }\n if (src[i] === \"$\" && src[i + 1] === \"{\") {\n let td = 1;\n i += 2;\n while (i < src.length && td > 0) {\n if (src[i] === \"{\") td++;\n else if (src[i] === \"}\") td--;\n if (td > 0) i++;\n }\n i++;\n continue;\n }\n i++;\n }\n i++;\n continue;\n }\n if (c === \"/\" && src[i + 1] === \"/\") {\n while (i < src.length && src[i] !== \"\\n\") i++;\n continue;\n }\n if (c === \"/\" && src[i + 1] === \"*\") {\n i += 2;\n while (i < src.length && !(src[i - 1] === \"*\" && src[i] === \"/\")) i++;\n i++;\n continue;\n }\n if (c === \"(\" || c === \"{\" || c === \"[\") {\n depth++;\n i++;\n continue;\n }\n if (c === \")\" || c === \"}\" || c === \"]\") {\n depth--;\n i++;\n continue;\n }\n if (c === \";\" && depth === 0) return i;\n i++;\n }\n return i;\n}\n\n/**\n * Build a map of every top-level identifier assignment in `src`.\n *\n * const Foo = z.object({...}); → Foo → \"z.object({...})\"\n * export const Bar: T = someExpr; → Bar → \"someExpr\"\n * let Baz = \"literal\"; → Baz → \"\\\"literal\\\"\"\n *\n * Used so cross-file shorthand `.emits({ TicketOpened })` can resolve\n * to the actual Zod expression defined in another module.\n */\nexport function extractIdentifierAssignments(src: string): Map<string, string> {\n const out = new Map<string, string>();\n // The type-annotation arm is line-bounded (`[^=\\n;]`) and explicitly\n // capped at 256 chars so the inner `+` can't drive O(N²) backtracking\n // across pathological inputs like many `#let $:` repetitions without\n // a closing `=`. Real TS type annotations on a top-level binding are\n // dramatically shorter than 256 chars — a binding with a longer one\n // simply isn't captured here, which is fine for the cross-file lookup.\n const re =\n /(?:^|[^\\w$])(?:export\\s+)?(?:const|let|var)\\s+([A-Za-z_$][\\w$]*)\\s*(?::[^=\\n;]{1,256})?=\\s*/gm;\n let m: RegExpExecArray | null;\n while ((m = re.exec(src)) !== null) {\n const ident = m[1];\n if (out.has(ident)) {\n // Keep the first assignment; later reassignments are uncommon\n // and would just confuse the lookup.\n continue;\n }\n const start = m.index + m[0].length;\n const end = readTopLevelExpression(src, start);\n const text = src.slice(start, end).trim();\n if (text) out.set(ident, text);\n re.lastIndex = end;\n }\n return out;\n}\n\n/**\n * Locate the object literal a top-level identifier points at. Handles:\n *\n * const Events = { Foo: z.string(), Bar: z.number() };\n * const Events: EventMap = { ... };\n * let Events = { ... };\n *\n * Returns the index of the opening `{`, or -1 if the identifier can't\n * be resolved to an inline object literal.\n */\nfunction findIdentifierObjectLiteral(src: string, ident: string): number {\n // Match `const/let/var IDENT [: T] =` followed by optional whitespace.\n // The capture stops just before whatever the value is. See\n // `extractIdentifierAssignments` for why the type-annotation arm\n // uses `[^=\\n;]+` (greedy, no inner `\\s*`) — same ReDoS hazard.\n const re = new RegExp(\n `(?:^|[^\\\\w$])(?:const|let|var)\\\\s+${ident}\\\\b\\\\s*(?::[^=\\\\n;]+)?=\\\\s*`,\n \"m\"\n );\n const m = re.exec(src);\n if (!m) return -1;\n const after = m.index + m[0].length;\n const skipped = skipTrivia(src, after);\n return src[skipped] === \"{\" ? skipped : -1;\n}\n\n/** Bare-identifier matcher; used to decide whether to chase a value. */\nconst BARE_IDENT_RE = /^[A-Za-z_$][\\w$]*$/;\n\n/**\n * Find every `.emits( ... )` call in `src` and extract the Zod source\n * text for any event name in `eventNames`. Resolves three indirection\n * patterns:\n *\n * .emits({ Foo: z.object(...) }) → direct value capture\n * .emits({ Foo }) → shorthand → chase `Foo` to its\n * definition, locally or via\n * `external` (cross-file)\n * .emits(EventsObj) → chase the identifier to its\n * `const EventsObj = { ... }`\n *\n * Returns a map keyed by event name; missing events stay absent.\n */\nexport function extractSchemasFromSource(\n src: string,\n eventNames: Set<string>,\n external?: Map<string, string>\n): Map<string, string> {\n const out = new Map<string, string>();\n if (!src || eventNames.size === 0) return out;\n // Same-file identifier map, scanned once for the shorthand case.\n const localIdents = extractIdentifierAssignments(src);\n const deref = (text: string): string =>\n BARE_IDENT_RE.test(text)\n ? (localIdents.get(text) ?? external?.get(text) ?? text)\n : text;\n const emitsRe = /\\.emits\\s*\\(/g;\n let m: RegExpExecArray | null;\n while ((m = emitsRe.exec(src)) !== null) {\n let i = skipTrivia(src, emitsRe.lastIndex);\n // `.emits(IDENT)` — chase the identifier to its object literal.\n if (isIdent(src[i])) {\n const start = i;\n while (isIdent(src[i])) i++;\n const ident = src.slice(start, i);\n const objStart = findIdentifierObjectLiteral(src, ident);\n if (objStart < 0) continue;\n i = objStart;\n }\n if (src[i] !== \"{\") continue;\n const parsed = parseObjectLiteral(src, i);\n if (!parsed) continue;\n for (const e of parsed.entries) {\n if (!eventNames.has(e.key)) continue;\n const raw = src.slice(e.valueStart, e.valueEnd).trim();\n const text = deref(raw);\n if (text) out.set(e.key, text);\n }\n emitsRe.lastIndex = Math.max(emitsRe.lastIndex, parsed.endBrace + 1);\n }\n return out;\n}\n","/**\n * Bottom-up model builder: inventory → states → slices → act\n *\n * 1. Scan source for all state/slice/projection/act declarations (inventory)\n * 2. Try to build each item independently from the raw mock results\n * 3. Always show every item — with diagram on success, error on failure\n */\nimport type {\n ActionNode,\n ActNode,\n DomainModel,\n EventNode,\n FileTab,\n ReactionNode,\n StateNode,\n} from \"../types/index.js\";\nimport {\n extractIdentifierAssignments,\n extractSchemasFromSource,\n} from \"./schema-extract.js\";\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\nlet _stateIdx = 0;\n\n/** Convert a raw mock state to a StateNode. Returns error string on validation failure. */\nfunction buildState(\n model: DomainModel,\n st: any\n): { key: string; node: StateNode } | { error: string } {\n // Validate: detect corrupted imports (undefined schemas)\n const events = (st.events ?? {}) as Record<string, unknown>;\n for (const [name, schema] of Object.entries(events)) {\n if (schema === undefined)\n return { error: `Event \"${name}\" has undefined schema` };\n }\n const rawActions = (st.actions ?? {}) as Record<string, unknown>;\n for (const [name, schema] of Object.entries(rawActions)) {\n if (name.startsWith(\"__emits_\")) continue;\n if (schema === undefined)\n return { error: `Action \"${name}\" has undefined schema` };\n }\n\n const domainName = st.name as string;\n const uniqueKey = `${domainName}:${_stateIdx++}`;\n\n const eventNodes: EventNode[] = [];\n for (const eventName of Object.keys(events)) {\n eventNodes.push({\n name: eventName,\n hasCustomPatch: st.patches?.has(eventName) ?? false,\n // Stash the runtime Zod schema so the JSON Schema exporter can\n // call `z.toJSONSchema(zod)` later without re-running the parser.\n zod: events[eventName],\n });\n }\n\n const actionNodes: ActionNode[] = [];\n for (const actionName of Object.keys(rawActions)) {\n if (actionName.startsWith(\"__emits_\")) continue;\n const emits: string[] =\n (rawActions[`__emits_${actionName}`] as string[]) ?? [];\n const invariants = (st.given?.[actionName] ?? []).map(\n (inv: any) => inv.description ?? \"\"\n );\n actionNodes.push({ name: actionName, emits, invariants });\n }\n\n const node: StateNode = {\n name: domainName,\n varName: uniqueKey,\n events: eventNodes,\n actions: actionNodes,\n file: st._sourceFile as string | undefined,\n };\n model.states.push(node);\n st._modelKey = uniqueKey;\n return { key: uniqueKey, node };\n}\n\nfunction fixupReactions(\n reactions: ReactionNode[],\n files: FileTab[],\n sourceFile?: string\n) {\n const fallbacks = reactions.filter((r) => r.handlerName.startsWith(\"on \"));\n if (fallbacks.length === 0) return;\n const src = sourceFile\n ? files.find((f) => f.path === sourceFile)?.content\n : files.map((f) => f.content).join(\"\\n\");\n if (!src) return;\n const doRe =\n /\\.on\\(\\s*[\"'`](\\w+)[\"'`]\\s*\\)\\s*\\.do\\(\\s*(?:async\\s+)?(?:function\\s+(\\w+)|(?:\\w+\\.)?(\\w+))?/g;\n let dm: RegExpExecArray | null;\n while ((dm = doRe.exec(src)) !== null) {\n const eventName = dm[1];\n const handlerName = dm[2] || dm[3];\n if (!handlerName) continue;\n const r = fallbacks.find(\n (r) => r.event === eventName && r.handlerName === `on ${eventName}`\n );\n if (r) r.handlerName = handlerName;\n }\n}\n\n// ── Types ───────────────────────────────────────────────────────────\n\nexport type ExecuteResult = {\n states: any[];\n slices: any[];\n projections: any[];\n acts: any[];\n error?: string;\n fileErrors: Map<string, string>;\n};\n\n// ── Bottom-up model builder ─────────────────────────────────────────\n\nexport function buildModel(\n result: ExecuteResult,\n files: FileTab[],\n expectedSlices: Map<string, string>\n): { model: DomainModel; error?: string } {\n const rawStates = result.states.filter((s: any) => s && s._tag === \"State\");\n const rawSlices = result.slices.filter((s: any) => s && s._tag === \"Slice\");\n const rawProjections = result.projections.filter(\n (p: any) => p && p._tag === \"Projection\"\n );\n const rawActs = result.acts.filter((a: any) => a && a._tag === \"Act\");\n\n // Maps from raw mock ref → built result or error\n const stateByRef = new Map<\n any,\n { key: string; node: StateNode } | { error: string }\n >();\n\n const model: DomainModel = {\n entries: [],\n states: [],\n slices: [],\n projections: [],\n reactions: [],\n };\n\n // ── Step 1: Build each state independently ────────────────────────\n for (const st of rawStates) {\n if (stateByRef.has(st)) continue;\n try {\n stateByRef.set(st, buildState(model, st));\n } catch (e) {\n stateByRef.set(st, {\n error: e instanceof Error ? e.message : String(e),\n });\n }\n }\n // Also states from act builders\n for (const a of rawActs) {\n for (const st of a.states ?? []) {\n if (!st || st._tag !== \"State\" || stateByRef.has(st)) continue;\n try {\n stateByRef.set(st, buildState(model, st));\n } catch (e) {\n stateByRef.set(st, {\n error: e instanceof Error ? e.message : String(e),\n });\n }\n }\n }\n\n // ── Step 2: Build each slice independently ────────────────────────\n const builtSliceNames = new Set<string>();\n\n for (const s of rawSlices) {\n const sliceName = (s._varName ?? \"slice\") as string;\n builtSliceNames.add(sliceName);\n\n try {\n try {\n fixupReactions(s.reactions as ReactionNode[], files);\n } catch {\n /* ignore fixup errors */\n }\n\n const sliceStateKeys: string[] = [];\n const errors: string[] = [];\n\n for (const st of s.states ?? []) {\n if (!st || typeof st !== \"object\") {\n // Find which file caused this — check all file errors\n const fileErr = [...result.fileErrors.values()][0];\n errors.push(fileErr ?? \"Missing state (broken import)\");\n continue;\n }\n const built = stateByRef.get(st);\n if (built) {\n if (\"error\" in built) {\n errors.push(built.error);\n } else {\n sliceStateKeys.push(built.key);\n }\n } else {\n // State not seen before — try building it now\n try {\n const result = buildState(model, st);\n stateByRef.set(st, result);\n if (\"error\" in result) {\n errors.push(result.error);\n } else {\n sliceStateKeys.push(result.key);\n }\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n stateByRef.set(st, { error: msg });\n errors.push(msg);\n }\n }\n }\n\n const projNames: string[] = [];\n for (const p of s.projections ?? []) {\n if (p && p._tag === \"Projection\") projNames.push(p.target as string);\n }\n\n const sliceFile = s._sourceFile as string | undefined;\n model.slices.push({\n name: sliceName,\n states: sliceStateKeys,\n stateVars: sliceStateKeys,\n projections: projNames,\n reactions: ((s.reactions as ReactionNode[]) ?? []).map((r) => ({\n ...r,\n file: r.file ?? sliceFile,\n })),\n file: sliceFile,\n error: errors.length > 0 ? errors.join(\"; \") : undefined,\n });\n } catch (e: unknown) {\n const msg = e instanceof Error ? e.message : String(e);\n model.slices.push({\n name: sliceName,\n states: [],\n stateVars: [],\n projections: [],\n reactions: [],\n error: msg,\n file: s._sourceFile as string | undefined,\n });\n }\n }\n\n // Always show expected slices that weren't built (from inventory)\n for (const [name, filePath] of expectedSlices) {\n if (!builtSliceNames.has(name)) {\n model.slices.push({\n name,\n states: [],\n stateVars: [],\n projections: [],\n reactions: [],\n error:\n result.fileErrors.get(filePath) ??\n result.error ??\n \"Failed to build slice\",\n file: filePath,\n });\n }\n }\n\n // ── Step 2b: Capture best-effort Zod schema text per event ────────\n // Re-scan each state's source file for `.emits({...})` and slice out\n // the value expression for every known event name. The captured text\n // feeds both the act-contracts CLI and the diagram tooltips.\n //\n // Build a cross-file identifier map first so `.emits({ TicketOpened })`\n // resolves to the `export const TicketOpened = z.object(...)` that\n // lives in another module. First definition wins on collision — Act\n // codebases don't reassign event-schema identifiers.\n const sourceByPath = new Map<string, string>();\n const externalIdents = new Map<string, string>();\n for (const f of files) {\n sourceByPath.set(f.path, f.content);\n for (const [ident, expr] of extractIdentifierAssignments(f.content)) {\n if (!externalIdents.has(ident)) externalIdents.set(ident, expr);\n }\n }\n for (const stNode of model.states) {\n if (!stNode.file) continue;\n // `stNode.file` came from `_sourceFile`, which was set during file\n // evaluation — so it's always present in `files`. The `!` and\n // v8-ignore acknowledge the type-level optionality without paying\n // for an unreachable branch.\n /* v8 ignore next */\n const src = sourceByPath.get(stNode.file)!;\n const names = new Set(stNode.events.map((e) => e.name));\n if (names.size === 0) continue;\n const schemas = extractSchemasFromSource(src, names, externalIdents);\n for (const ev of stNode.events) {\n // Set unconditionally — `undefined` is a valid value for the\n // optional schema field and matches the \"not captured\" state.\n ev.schema = schemas.get(ev.name);\n }\n }\n\n // ── Step 3: Build projections ─────────────────────────────────────\n for (const p of rawProjections) {\n model.projections.push({\n name: p.target,\n varName: p.target,\n handles: p.handles,\n file: p._sourceFile as string | undefined,\n });\n }\n\n // ── Step 4: Compose act ───────────────────────────────────────────\n const statesInSlices = new Set(model.slices.flatMap((s) => s.states));\n const globalStateKeys = model.states\n .filter((s) => !statesInSlices.has(s.varName))\n .map((s) => s.varName);\n\n for (const a of rawActs) {\n try {\n fixupReactions(\n (a.reactions as ReactionNode[]) ?? [],\n files,\n a._sourceFile as string | undefined\n );\n } catch {\n /* ignore */\n }\n\n model.orchestrator = {\n slices: model.slices.map((s) => s.name),\n projections: model.projections.map((p) => p.name),\n states: model.states.map((s) => s.name),\n } as ActNode;\n\n const actFile = a._sourceFile as string | undefined;\n for (const r of (a.reactions as ReactionNode[]) ?? []) {\n model.reactions.push({ ...r, file: r.file ?? actFile });\n }\n\n const entryPath = (a._sourceFile ?? \"app.ts\") as string;\n\n // Filter to items owned by this act builder\n const actSliceNames = new Set<string>(\n ((a.slices as any[]) ?? [])\n .filter((s: any) => s != null)\n .map((s: any) => s._varName ?? \"\")\n .filter(Boolean)\n );\n // Also include error placeholder slices from files referenced by this act\n for (const sl of model.slices) {\n if (sl.error && !actSliceNames.has(sl.name)) {\n // Check if this act's source file references this slice name\n const actSrc = files.find((f) => f.path === entryPath)?.content ?? \"\";\n if (actSrc.includes(sl.name)) {\n actSliceNames.add(sl.name);\n }\n }\n }\n\n const entrySlices = model.slices.filter((s) => actSliceNames.has(s.name));\n const sliceStateKeys = new Set(entrySlices.flatMap((s) => s.states));\n\n const actStateKeys = new Set<string>();\n for (const s of (a.states as any[]) ?? []) {\n try {\n if (s && s._tag === \"State\") {\n actStateKeys.add((s._modelKey ?? s.name) as string);\n }\n } catch {\n /* skip corrupt state */\n }\n }\n const allStateKeys = new Set([...actStateKeys, ...sliceStateKeys]);\n\n const actProjNames = new Set<string>(\n ((a.projections as any[]) ?? [])\n .filter((p: any) => p && p._tag === \"Projection\")\n .map((p: any) => p.target as string)\n );\n // Include projections embedded in slices\n for (const sl of entrySlices) {\n for (const pn of sl.projections) actProjNames.add(pn);\n }\n\n model.entries.push({\n path: entryPath,\n states: model.states.filter((s) => allStateKeys.has(s.varName)),\n slices: entrySlices,\n projections: model.projections.filter((p) => actProjNames.has(p.name)),\n reactions: (a.reactions as ReactionNode[]) ?? [],\n });\n }\n\n // Global slice for standalone states/reactions\n if (globalStateKeys.length > 0 || model.reactions.length > 0) {\n model.slices.push({\n name: \"global\",\n states: globalStateKeys,\n stateVars: globalStateKeys,\n projections: model.projections.map((p) => p.name),\n reactions: model.reactions,\n });\n }\n\n // Fallback entry if no act() found\n if (\n model.entries.length === 0 &&\n (model.states.length > 0 || model.slices.length > 0)\n ) {\n model.entries.push({\n path: \"app\",\n states: model.states,\n slices: model.slices,\n projections: model.projections,\n reactions: model.reactions,\n });\n }\n\n if (result.error && model.states.length === 0 && model.slices.length === 0) {\n return { model, error: result.error };\n }\n return { model };\n}\n","/**\n * Mock Act framework builders that capture domain model structure\n * (state names, events, actions, reactions, invariants) without\n * needing the real framework runtime.\n */\nimport { z } from \"zod\";\nimport type { ReactionNode } from \"../types/index.js\";\n\n/** Shared no-op function used as Proxy targets (body is never reached through the proxy) */\nexport function proxyTarget() {}\n\nfunction attachEmit(\n info: { actions: Record<string, any>; events: Record<string, any> },\n actionName: string,\n handler: any\n) {\n const emits: string[] = [];\n if (typeof handler === \"string\") {\n emits.push(handler);\n } else if (typeof handler === \"function\") {\n // Strategy 1: string search for event names in handler source\n const src = String(handler);\n for (const eventName of Object.keys(info.events)) {\n if (\n src.includes(`\"${eventName}\"`) ||\n src.includes(`'${eventName}'`) ||\n src.includes(`\\`${eventName}\\``)\n ) {\n emits.push(eventName);\n }\n }\n\n // Strategy 2: if string search found nothing, try safe-executing\n // the handler with Proxy-based dummy args to capture event name\n if (emits.length === 0) {\n try {\n const deepProxy: any = new Proxy(\n {},\n {\n get: () => deepProxy,\n has: () => true,\n }\n );\n const proxyFn = new Proxy(proxyTarget, {\n get: () => deepProxy,\n apply: () => deepProxy,\n });\n const dummyArg = new Proxy(\n {},\n {\n get: (_t, prop) => {\n if (typeof prop === \"string\") return proxyFn;\n return undefined;\n },\n }\n );\n const result = handler(dummyArg, dummyArg, dummyArg);\n if (Array.isArray(result) && typeof result[0] === \"string\") {\n emits.push(result[0]);\n }\n } catch {\n // Proxy execution failed — keep emits empty\n }\n }\n }\n (info.actions as any)[`__emits_${actionName}`] = emits;\n}\n\nexport function mockState(\n entry: Record<string, any>,\n onBuild?: (info: any) => void\n) {\n const name = Object.keys(entry)[0];\n const info = {\n name,\n events: {} as Record<string, any>,\n actions: {} as Record<string, any>,\n given: {} as Record<string, any[]>,\n patches: new Set<string>(),\n _tag: \"State\" as const,\n };\n\n const actionBuilder = (_currentAction?: string): any => ({\n on(actionEntry: Record<string, any>) {\n const actionName = Object.keys(actionEntry)[0];\n info.actions[actionName] = actionEntry[actionName];\n return {\n given(rules?: any[]) {\n if (rules) info.given[actionName] = rules;\n return {\n emit(handler: any) {\n attachEmit(info, actionName, handler);\n return actionBuilder(actionName);\n },\n };\n },\n emit(handler: any) {\n attachEmit(info, actionName, handler);\n return actionBuilder(actionName);\n },\n };\n },\n snap: () => actionBuilder(_currentAction),\n build: () => {\n onBuild?.(info);\n return info;\n },\n });\n\n return {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n init: (_initFn?: any) => ({\n emits(events: Record<string, any>) {\n info.events = events ?? {};\n return {\n ...actionBuilder(),\n patch(patches?: Record<string, any>) {\n if (patches)\n for (const k of Object.keys(patches)) info.patches.add(k);\n return actionBuilder();\n },\n };\n },\n }),\n };\n}\n\n/**\n * Extract dispatched action names from a reaction handler.\n * First tries runtime execution with a mock app; if the handler has\n * conditional branches that prevent reaching app.do(), falls back to\n * parsing the handler source for `.do(\"ActionName\")` calls.\n */\nfunction captureDispatches(handler: any): string[] {\n const dispatches: string[] = [];\n if (typeof handler !== \"function\") return dispatches;\n\n // Strategy 1: execute handler with mock app to capture app.do() calls\n try {\n const safeProxy = (): any =>\n new Proxy({} as Record<string, unknown>, { get: () => \"\" });\n const mockApp = {\n do: (actionName: string) => {\n if (typeof actionName === \"string\" && !dispatches.includes(actionName))\n dispatches.push(actionName);\n return Promise.resolve([]);\n },\n load: () => Promise.resolve({ state: safeProxy(), version: 0 }),\n query: () => Promise.resolve({ count: 0 }),\n query_array: () => Promise.resolve([]),\n };\n const mockEvent = new Proxy({} as Record<string, unknown>, {\n get: (_, prop) =>\n prop === \"stream\"\n ? \"mock\"\n : prop === \"data\"\n ? new Proxy({}, { get: () => \"\" })\n : \"\",\n });\n const result = handler(mockEvent, \"mock\", mockApp);\n // Swallow async rejections (handlers that access db, etc.)\n if (result && typeof result.catch === \"function\") {\n result.catch(() => {});\n }\n } catch {\n // handler threw — dispatches stays as captured so far\n }\n\n // Strategy 2: if runtime missed dispatches (e.g. conditional branches),\n // parse the handler source for .do(\"ActionName\") calls as fallback\n if (dispatches.length === 0) {\n const src = String(handler);\n const re = /\\.do\\(\\s*[\"'](\\w+)[\"']/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(src)) !== null) {\n if (!dispatches.includes(m[1])) dispatches.push(m[1]);\n }\n }\n\n return dispatches;\n}\n\nexport function mockSlice(onBuild?: (info: any) => void) {\n const info = {\n _tag: \"Slice\" as const,\n states: [] as any[],\n projections: [] as any[],\n reactions: [] as ReactionNode[],\n };\n\n const builder: any = {\n withState(s: any) {\n info.states.push(s ?? null);\n return builder;\n },\n withProjection(p: any) {\n if (p) info.projections.push(p);\n return builder;\n },\n on(eventName: string) {\n return {\n do(handler: any) {\n const dispatches = captureDispatches(handler);\n const reaction: ReactionNode = {\n event: eventName,\n handlerName:\n (typeof handler?.name === \"string\" && handler.name) ||\n `on ${eventName}`,\n dispatches,\n };\n info.reactions.push(reaction);\n return {\n ...builder,\n to() {\n return builder;\n },\n };\n },\n };\n },\n build: () => {\n onBuild?.(info);\n return info;\n },\n };\n return builder;\n}\n\nexport function mockProjection(target?: string, onBuild?: (info: any) => void) {\n const info = {\n _tag: \"Projection\" as const,\n target: target || \"projection\",\n handles: [] as string[],\n };\n\n const builder: any = {\n on(eventEntry: Record<string, any>) {\n const eventName = Object.keys(eventEntry)[0];\n info.handles.push(eventName);\n return {\n do() {\n return {\n ...builder,\n to(resolver: any) {\n if (typeof resolver === \"string\") info.target = resolver;\n return builder;\n },\n };\n },\n };\n },\n build: () => {\n onBuild?.(info);\n return info;\n },\n };\n return builder;\n}\n\nexport function mockAct(onBuild?: (info: any) => void) {\n const info = {\n _tag: \"Act\" as const,\n states: [] as any[],\n slices: [] as any[],\n projections: [] as any[],\n reactions: [] as ReactionNode[],\n };\n\n const builder: any = {\n withState(s: any) {\n info.states.push(s ?? null);\n return builder;\n },\n withSlice(s: any) {\n // Always push (even null/undefined) to preserve positional alignment\n // with slice variable names extracted from .withSlice(VAR) in source\n info.slices.push(s ?? null);\n return builder;\n },\n withProjection(p: any) {\n if (p) info.projections.push(p);\n return builder;\n },\n withActor: () => builder,\n on(eventName: string) {\n return {\n do(handler: any) {\n const dispatches = captureDispatches(handler);\n const reaction: ReactionNode = {\n event: eventName,\n handlerName:\n (typeof handler?.name === \"string\" && handler.name) ||\n `on ${eventName}`,\n dispatches,\n };\n info.reactions.push(reaction);\n return {\n ...builder,\n to() {\n return builder;\n },\n };\n },\n };\n },\n build: () => {\n const noop = () => actStub;\n const actStub: any = {\n ...info,\n on: () => actStub,\n do: () => Promise.resolve([]),\n load: () => Promise.resolve({}),\n drain: () => Promise.resolve(),\n correlate: () => Promise.resolve({ subscribed: 0, last_id: 0 }),\n settle: noop,\n start_correlations: noop,\n query_array: () => Promise.resolve([]),\n };\n onBuild?.(actStub);\n return actStub;\n },\n };\n return builder;\n}\n\nclass InvariantError extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"InvariantError\";\n }\n}\n\nconst cryptoMock = { randomUUID: () => \"mock-uuid\" };\n\n/** Module map for the evaluator's require() */\nexport const MODULES: Record<string, Record<string, unknown>> = {\n \"@rotorsoft/act\": {\n state: mockState,\n slice: mockSlice,\n projection: mockProjection,\n act: mockAct,\n store: () => ({\n seed: () => Promise.resolve(),\n drop: () => Promise.resolve(),\n commit: () => Promise.resolve([]),\n query: () => Promise.resolve(0),\n dispose: () => Promise.resolve(),\n }),\n dispose: () => () => Promise.resolve(),\n ZodEmpty: z.record(z.string(), z.never()),\n InvariantError,\n },\n zod: { z, ...z },\n crypto: cryptoMock,\n \"node:crypto\": cryptoMock,\n};\n\n/**\n * Returns a deep Proxy for unknown modules — any property access\n * returns a no-op function that also acts as a Proxy.\n */\nexport function unknownModuleProxy(): Record<string, unknown> {\n const handler: ProxyHandler<any> = {\n get(_target, prop) {\n if (prop === Symbol.toPrimitive) return () => \"\";\n if (prop === \"default\") return proxy;\n return proxy;\n },\n apply() {\n return proxy;\n },\n construct() {\n return proxy;\n },\n has() {\n return true;\n },\n };\n const proxy: any = new Proxy(proxyTarget, handler);\n return proxy;\n}\n","import type { FileTab } from \"../types/index.js\";\n\n/** Topological sort: files that are imported come before files that import them */\nexport function topoSort(tsFiles: FileTab[]): FileTab[] {\n if (tsFiles.length <= 1) return tsFiles;\n\n const strip = (p: string) => p.replace(/\\.tsx?$/, \"\");\n\n // Build lookup\n const byKey = new Map<string, FileTab>();\n for (const f of tsFiles) {\n byKey.set(strip(f.path), f);\n }\n\n // Build adjacency: file → set of files it depends on\n const deps = new Map<string, Set<string>>();\n for (const f of tsFiles) {\n const key = strip(f.path);\n const fileDeps = new Set<string>();\n deps.set(key, fileDeps);\n\n const fromRe = /from\\s+[\"']([^\"']+)[\"']/g;\n let m: RegExpExecArray | null;\n while ((m = fromRe.exec(f.content)) !== null) {\n const imp = m[1];\n const resolved = resolve(imp, key, byKey);\n if (resolved && byKey.has(resolved)) fileDeps.add(resolved);\n }\n }\n\n // Kahn's algorithm (iterative topological sort)\n const inDegree = new Map<string, number>();\n for (const f of tsFiles) inDegree.set(strip(f.path), 0);\n for (const [, fileDeps] of deps) {\n for (const dep of fileDeps) {\n inDegree.set(dep, inDegree.get(dep)! + 1);\n }\n }\n\n // Start with files that nobody depends on (leaves)\n // Actually for topo sort: start with files that have NO deps (sources)\n const queue: string[] = [];\n for (const [key, _deg] of inDegree) {\n if (deps.get(key)?.size === 0) queue.push(key);\n }\n\n const order: string[] = [];\n while (queue.length > 0) {\n const key = queue.shift()!;\n order.push(key);\n // For each file that depends on this one, reduce its pending count\n for (const [other, fileDeps] of deps) {\n if (fileDeps.has(key)) {\n fileDeps.delete(key);\n if (fileDeps.size === 0) queue.push(other);\n }\n }\n }\n\n // Add any remaining files (circular deps) at the end\n for (const f of tsFiles) {\n const key = strip(f.path);\n if (!order.includes(key)) order.push(key);\n }\n\n return order.map((k) => byKey.get(k)!).filter(Boolean);\n}\n\nfunction resolve(\n imp: string,\n fromPath: string,\n byKey?: Map<string, any>\n): string | undefined {\n if (imp.startsWith(\".\")) {\n const dir = fromPath.includes(\"/\")\n ? fromPath.slice(0, fromPath.lastIndexOf(\"/\"))\n : \"\";\n const parts = (dir ? dir + \"/\" + imp : imp).split(\"/\");\n const resolved: string[] = [];\n for (const p of parts) {\n if (p === \".\" || p === \"\") continue;\n if (p === \"..\") resolved.pop();\n else resolved.push(p);\n }\n return resolved.join(\"/\").replace(/\\.js$/, \"\").replace(/\\.ts$/, \"\");\n }\n if (imp.startsWith(\"@\") && !imp.startsWith(\"@rotorsoft/\")) {\n const pkgName = imp.split(\"/\")[1];\n if (pkgName) {\n // Try multiple patterns for monorepo workspace packages\n // Folder may be opened at project root (packages/pkg/src/index)\n // or at packages/ level (pkg/src/index)\n for (const candidate of [\n `packages/${pkgName}/src/index`,\n `${pkgName}/src/index`,\n `${pkgName}/index`,\n ]) {\n if (byKey?.has(candidate)) return candidate;\n }\n return `packages/${pkgName}/src/index`;\n }\n }\n return undefined;\n}\n","/**\n * Search index built from a parsed DomainModel.\n *\n * Walks the model once, materializes one IndexEntry per discoverable\n * symbol (events, actions, slices, projections, states, reactions),\n * and exposes a fuzzy lookup over them.\n *\n * Event status is derived from the `_v<digits>` convention documented\n * in CLAUDE.md and ACT-403: an event `Foo` is deprecated when any\n * `Foo_v<n>` with a higher version exists.\n */\nimport type { DomainModel } from \"../client/types/index.js\";\n\nexport type Kind =\n | \"event\"\n | \"action\"\n | \"slice\"\n | \"projection\"\n | \"state\"\n | \"reaction\";\n\nexport type IndexEntry = {\n kind: Kind;\n name: string;\n /** Disambiguator when names repeat across kinds or scopes. */\n qualifier?: string;\n file?: string;\n line?: number;\n};\n\nexport type ContractIndex = {\n entries: IndexEntry[];\n model: DomainModel;\n /** All event names that appear anywhere in the model. */\n allEventNames: Set<string>;\n};\n\n/** Strip `_v<digits>` suffix and return logical (base, version). */\nexport function decomposeEventName(name: string): {\n base: string;\n version: number;\n} {\n const m = name.match(/^(.+)_v(\\d+)$/);\n if (m) return { base: m[1], version: Number.parseInt(m[2], 10) };\n return { base: name, version: 1 };\n}\n\nexport type EventStatus = {\n status: \"active\" | \"deprecated\";\n supersededBy?: string;\n};\n\n/**\n * Return active/deprecated for an event name given the universe of\n * known event names. `Foo` is deprecated if any `Foo_v<n>` with a\n * higher version exists; the latest version wins.\n */\nexport function eventStatus(\n name: string,\n allNames: Iterable<string>\n): EventStatus {\n const me = decomposeEventName(name);\n let bestVersion = me.version;\n let bestName: string | undefined;\n for (const other of allNames) {\n if (other === name) continue;\n const dec = decomposeEventName(other);\n if (dec.base === me.base && dec.version > bestVersion) {\n bestVersion = dec.version;\n bestName = other;\n }\n }\n return bestName\n ? { status: \"deprecated\", supersededBy: bestName }\n : { status: \"active\" };\n}\n\nexport function buildContractIndex(model: DomainModel): ContractIndex {\n const entries: IndexEntry[] = [];\n const allEventNames = new Set<string>();\n\n for (const st of model.states) {\n entries.push({\n kind: \"state\",\n name: st.name,\n file: st.file,\n line: st.line,\n });\n for (const ev of st.events) {\n allEventNames.add(ev.name);\n entries.push({\n kind: \"event\",\n name: ev.name,\n qualifier: st.name,\n file: st.file,\n line: ev.line,\n });\n }\n for (const act of st.actions) {\n entries.push({\n kind: \"action\",\n name: act.name,\n qualifier: st.name,\n file: st.file,\n line: act.line,\n });\n }\n }\n for (const sl of model.slices) {\n entries.push({\n kind: \"slice\",\n name: sl.name,\n file: sl.file,\n line: sl.line,\n });\n for (const r of sl.reactions) {\n allEventNames.add(r.event);\n entries.push({\n kind: \"reaction\",\n name: r.handlerName,\n qualifier: `${sl.name}::${r.event}`,\n file: r.file ?? sl.file,\n line: r.line,\n });\n }\n }\n for (const pr of model.projections) {\n entries.push({\n kind: \"projection\",\n name: pr.name,\n file: pr.file,\n line: pr.line,\n });\n for (const ev of pr.handles) allEventNames.add(ev);\n }\n for (const r of model.reactions) {\n allEventNames.add(r.event);\n entries.push({\n kind: \"reaction\",\n name: r.handlerName,\n qualifier: `*::${r.event}`,\n file: r.file,\n line: r.line,\n });\n }\n\n return { entries, model, allEventNames };\n}\n\n/**\n * Map a category keyword (typed at the REPL prompt) to its kind.\n * Accepts singular and plural forms.\n */\nexport const CATEGORY_KEYWORDS: Record<string, Kind> = {\n event: \"event\",\n events: \"event\",\n action: \"action\",\n actions: \"action\",\n state: \"state\",\n states: \"state\",\n slice: \"slice\",\n slices: \"slice\",\n projection: \"projection\",\n projections: \"projection\",\n reaction: \"reaction\",\n reactions: \"reaction\",\n};\n\n/** Return every entry of a given kind, sorted by name. */\nexport function listByKind(idx: ContractIndex, kind: Kind): IndexEntry[] {\n return idx.entries\n .filter((e) => e.kind === kind)\n .sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/**\n * Fuzzy substring search across the index. Case-insensitive. Ranks\n * exact matches above prefix matches above generic substring matches.\n * Returns up to `limit` entries (default 20).\n */\nexport function search(\n idx: ContractIndex,\n query: string,\n limit = 20\n): IndexEntry[] {\n const q = query.trim().toLowerCase();\n if (!q) return [];\n const scored: Array<{ entry: IndexEntry; score: number }> = [];\n for (const entry of idx.entries) {\n const name = entry.name.toLowerCase();\n let score: number;\n if (name === q) score = 0;\n else if (name.startsWith(q)) score = 1;\n else if (name.includes(q)) score = 2;\n else continue;\n scored.push({ entry, score });\n }\n scored.sort((a, b) => {\n if (a.score !== b.score) return a.score - b.score;\n if (a.entry.kind !== b.entry.kind)\n return a.entry.kind.localeCompare(b.entry.kind);\n return a.entry.name.localeCompare(b.entry.name);\n });\n return scored.slice(0, limit).map((s) => s.entry);\n}\n","/**\n * Tiny color helpers. Wraps picocolors for the common 8-color palette\n * and adds 256-color escapes for the kind-specific accents (orange,\n * violet, pink/fuchsia, etc.) that picocolors doesn't ship with.\n *\n * All helpers respect picocolors' `isColorSupported` flag so output\n * stays readable when stdout is piped, NO_COLOR is set, etc.\n *\n * ## Color strategy\n *\n * Each kind has one signature color, used consistently across the\n * detail views, the match list, and the category selector. The\n * palette is picked from 256-color slots so the same hue lands the\n * same regardless of terminal theme:\n *\n * event orange (208)\n * action cornflower (33) — clear blue, no purple cast\n * state amber (220)\n * slice violet (141)\n * projection emerald (41)\n * reaction fuchsia (207)\n *\n * Status / meaning:\n * green → active / success\n * red → deprecated / error\n * muted → secondary metadata (file paths, counts, hints) — color 248\n *\n * `muted` is *not* the SGR-2 \"dim\" attribute. The dim attribute reads\n * as washed-out grey on most terminals; we use a neutral light-grey\n * 256-color slot instead, which keeps secondary info legible.\n *\n * Inside @clack/prompts selects, every kind label is prefixed with\n * \"cancel dim\" (`\\x1b[22m`) so the inactive-row dimming clack applies\n * doesn't wash out our intended kind color.\n */\nimport pc from \"picocolors\";\n\nconst supported = pc.isColorSupported;\n\n/** Cancel any active dim attribute so clack's outer dim wrap doesn't\n * steal saturation from inactive option labels. */\nconst CANCEL_DIM = \"\\x1b[22m\";\n\nconst ext = (code: number, s: string): string =>\n supported ? `${CANCEL_DIM}\\x1b[38;5;${code}m${s}\\x1b[39m` : s;\n\nexport const bold = pc.bold;\nexport const red = pc.red;\nexport const green = pc.green;\nexport const cyan = pc.cyan;\n/** Secondary metadata. Brighter than SGR-2 dim so detail dialogs stay legible. */\nexport const muted = (s: string): string =>\n supported ? `\\x1b[38;5;248m${s}\\x1b[39m` : s;\n/** Compat alias — older callers still import `dim`; map it to `muted`. */\nexport const dim = muted;\n\nexport const orange = (s: string): string => ext(208, s);\nexport const cornflower = (s: string): string => ext(33, s);\nexport const amber = (s: string): string => ext(220, s);\nexport const violet = (s: string): string => ext(141, s);\nexport const emerald = (s: string): string => ext(41, s);\nexport const fuchsia = (s: string): string => ext(207, s);\n/** Backwards-compat: legacy aliases pointing at the action color. */\nexport const lilac = cornflower;\nexport const pink = cornflower;\n\nexport const kindColor: Record<\n \"event\" | \"action\" | \"state\" | \"slice\" | \"projection\" | \"reaction\",\n (s: string) => string\n> = {\n event: orange,\n action: cornflower,\n state: amber,\n slice: violet,\n projection: emerald,\n reaction: fuchsia,\n};\n","/**\n * Pretty-printers for the `act` CLI.\n *\n * Each detail view returns a multi-line string. Colors are applied\n * unconditionally — picocolors no-ops when stdout doesn't support color,\n * so test snapshots can drop ANSI escapes if needed.\n */\n\nimport type { DomainModel } from \"../client/types/index.js\";\nimport {\n amber,\n bold,\n dim,\n emerald,\n fuchsia,\n green,\n kindColor,\n orange,\n pink,\n red,\n violet,\n} from \"./colors.js\";\nimport {\n type ContractIndex,\n eventStatus,\n type IndexEntry,\n} from \"./contract-index.js\";\n\nconst loc = (file?: string, line?: number): string => {\n if (!file) return \"\";\n return line ? `${file}:${line}` : file;\n};\n\nconst fileNote = (file?: string, line?: number): string => {\n const l = loc(file, line);\n return l ? ` ${dim(l)}` : \"\";\n};\n\nconst kindLabel = (kind: string): string => {\n const k = kindColor[kind as keyof typeof kindColor];\n return (k ?? dim)(kind.padEnd(10));\n};\n\n/** Format a \"matches\" list view (multiple search results). */\nexport function formatMatches(query: string, matches: IndexEntry[]): string {\n if (matches.length === 0) return dim(`no matches for \"${query}\"`);\n const head = dim(`matches (${matches.length}) — type a number to pick:`);\n const width = String(matches.length).length;\n const lines = matches.map((m, i) => {\n const idx = dim(`[${String(i + 1).padStart(width)}]`);\n const where = loc(m.file, m.line);\n const q = m.qualifier ? dim(` (${m.qualifier})`) : \"\";\n const w = where ? ` ${dim(where)}` : \"\";\n return ` ${idx} ${kindLabel(m.kind)} ${m.name}${q}${w}`;\n });\n return [head, ...lines].join(\"\\n\");\n}\n\nconst findActionsEmitting = (\n model: DomainModel,\n eventName: string\n): Array<{\n state: string;\n action: string;\n file?: string;\n line?: number;\n}> => {\n const out: Array<{\n state: string;\n action: string;\n file?: string;\n line?: number;\n }> = [];\n for (const st of model.states) {\n for (const act of st.actions) {\n if (act.emits.includes(eventName)) {\n out.push({\n state: st.name,\n action: act.name,\n file: st.file,\n line: act.line,\n });\n }\n }\n }\n return out;\n};\n\nconst findReactionsFor = (\n model: DomainModel,\n eventName: string\n): Array<{\n slice?: string;\n handler: string;\n dispatches: string[];\n file?: string;\n line?: number;\n}> => {\n const out: Array<{\n slice?: string;\n handler: string;\n dispatches: string[];\n file?: string;\n line?: number;\n }> = [];\n for (const sl of model.slices) {\n for (const r of sl.reactions) {\n if (r.event === eventName) {\n out.push({\n slice: sl.name,\n handler: r.handlerName,\n dispatches: r.dispatches,\n file: r.file ?? sl.file,\n line: r.line,\n });\n }\n }\n }\n for (const r of model.reactions) {\n if (r.event === eventName) {\n out.push({\n handler: r.handlerName,\n dispatches: r.dispatches,\n file: r.file,\n line: r.line,\n });\n }\n }\n return out;\n};\n\nconst findProjectionsFor = (\n model: DomainModel,\n eventName: string\n): Array<{ name: string; file?: string }> =>\n model.projections\n .filter((p) => p.handles.includes(eventName))\n .map((p) => ({ name: p.name, file: p.file }));\n\n/** Detailed event view: schema, producers, consumers, deprecation. */\nexport function formatEvent(idx: ContractIndex, entry: IndexEntry): string {\n const model = idx.model;\n let schema: string | undefined;\n let owningState: { name: string; file?: string } | undefined;\n for (const st of model.states) {\n const ev = st.events.find((e) => e.name === entry.name);\n if (ev) {\n schema = ev.schema;\n owningState = { name: st.name, file: st.file };\n break;\n }\n }\n const file = entry.file ?? owningState?.file;\n\n const status = eventStatus(entry.name, idx.allEventNames);\n const statusLine =\n status.status === \"active\"\n ? green(\"active\")\n : // `supersededBy` is always set on deprecated entries — see eventStatus.\n `${red(\"deprecated\")} (superseded by ${orange(status.supersededBy as string)})`;\n\n const lines: string[] = [];\n lines.push(bold(orange(entry.name)));\n if (file) lines.push(` in: ${dim(loc(file, entry.line))}`);\n if (owningState && owningState.name !== entry.name)\n lines.push(` on: ${amber(owningState.name)}`);\n lines.push(` schema: ${schema ?? dim(\"(not captured)\")}`);\n lines.push(` status: ${statusLine}`);\n\n const producers = findActionsEmitting(model, entry.name);\n if (producers.length > 0) {\n lines.push(\" producers:\");\n for (const p of producers) {\n lines.push(\n ` - ${pink(p.action)} ${dim(`(on ${p.state})`)}${fileNote(p.file, p.line)}`\n );\n }\n } else {\n lines.push(` producers: ${dim(\"(none)\")}`);\n }\n\n const reactions = findReactionsFor(model, entry.name);\n const projections = findProjectionsFor(model, entry.name);\n if (reactions.length === 0 && projections.length === 0) {\n lines.push(` consumers: ${dim(\"(none)\")}`);\n } else {\n lines.push(\" consumers:\");\n for (const r of reactions) {\n const slice = r.slice ? `${violet(r.slice)}${dim(\"::\")}` : \"\";\n const triggers =\n r.dispatches.length > 0\n ? ` → ${r.dispatches.map((d) => pink(d)).join(\", \")}`\n : \"\";\n lines.push(\n ` - ${slice}${fuchsia(r.handler)}${triggers}${fileNote(r.file, r.line)}`\n );\n }\n for (const p of projections) {\n lines.push(` - ${emerald(p.name)}${fileNote(p.file)}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function formatAction(idx: ContractIndex, entry: IndexEntry): string {\n const model = idx.model;\n const ownerName = entry.qualifier;\n let action:\n | { name: string; emits: string[]; invariants: string[]; line?: number }\n | undefined;\n let stateFile: string | undefined;\n for (const st of model.states) {\n if (ownerName && st.name !== ownerName) continue;\n const a = st.actions.find((x) => x.name === entry.name);\n if (a) {\n action = a;\n stateFile = st.file;\n break;\n }\n }\n const lines: string[] = [];\n lines.push(bold(pink(entry.name)));\n if (ownerName) lines.push(` on: ${amber(ownerName)}`);\n if (stateFile)\n lines.push(` in: ${dim(loc(stateFile, action?.line ?? entry.line))}`);\n if (action) {\n if (action.invariants.length > 0) {\n lines.push(\" invariants:\");\n for (const inv of action.invariants) lines.push(` - ${inv}`);\n }\n if (action.emits.length > 0) {\n lines.push(\" emits:\");\n for (const e of action.emits) lines.push(` - ${orange(e)}`);\n } else {\n lines.push(` emits: ${dim(\"(none)\")}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\nexport function formatState(idx: ContractIndex, entry: IndexEntry): string {\n const st = idx.model.states.find((s) => s.name === entry.name);\n const lines: string[] = [];\n lines.push(bold(amber(entry.name)));\n if (entry.file) lines.push(` in: ${dim(loc(entry.file, entry.line))}`);\n if (!st) return lines.join(\"\\n\");\n if (st.actions.length > 0) {\n lines.push(\" actions:\");\n for (const a of st.actions) {\n const emits = a.emits.length > 0 ? ` → ${a.emits.join(\", \")}` : \"\";\n lines.push(` - ${pink(a.name)}${emits}`);\n }\n }\n if (st.events.length > 0) {\n lines.push(\" events:\");\n for (const e of st.events) {\n const schema = e.schema ? ` ${dim(e.schema)}` : \"\";\n lines.push(` - ${orange(e.name)}${schema}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\nexport function formatSlice(idx: ContractIndex, entry: IndexEntry): string {\n const sl = idx.model.slices.find((s) => s.name === entry.name);\n const lines: string[] = [];\n lines.push(bold(violet(entry.name)));\n if (entry.file) lines.push(` in: ${dim(loc(entry.file, entry.line))}`);\n if (!sl) return lines.join(\"\\n\");\n if (sl.error) lines.push(` ${red(\"error: \" + sl.error)}`);\n if (sl.states.length > 0) {\n lines.push(\" states:\");\n for (const s of sl.states) lines.push(` - ${amber(s)}`);\n }\n if (sl.projections.length > 0) {\n lines.push(\" projections:\");\n for (const p of sl.projections) lines.push(` - ${emerald(p)}`);\n }\n if (sl.reactions.length > 0) {\n lines.push(\" reactions:\");\n for (const r of sl.reactions) {\n const triggers =\n r.dispatches.length > 0\n ? ` → ${r.dispatches.map((d) => pink(d)).join(\", \")}`\n : \"\";\n lines.push(\n ` - ${orange(r.event)} → ${fuchsia(r.handlerName)}${triggers}${fileNote(r.file, r.line)}`\n );\n }\n }\n return lines.join(\"\\n\");\n}\n\nexport function formatProjection(\n idx: ContractIndex,\n entry: IndexEntry\n): string {\n const pr = idx.model.projections.find((p) => p.name === entry.name);\n const lines: string[] = [];\n lines.push(bold(emerald(entry.name)));\n if (pr?.file) lines.push(` in: ${dim(loc(pr.file, pr.line))}`);\n if (!pr) return lines.join(\"\\n\");\n if (pr.handles.length > 0) {\n lines.push(\" handles:\");\n for (const h of pr.handles) lines.push(` - ${orange(h)}`);\n }\n return lines.join(\"\\n\");\n}\n\nexport function formatReaction(idx: ContractIndex, entry: IndexEntry): string {\n const [sliceName, eventName] = (entry.qualifier ?? \"::\").split(\"::\");\n const lines: string[] = [];\n const slice = sliceName && sliceName !== \"*\" ? violet(sliceName) : \"\";\n // Compact header: ReactionName (in SliceName) — the slice prefix gets\n // baked into the title so we don't burn a separate `in: <slice>` line.\n const header = slice\n ? `${bold(fuchsia(entry.name))} ${dim(`(in ${slice})`)}`\n : bold(fuchsia(entry.name));\n lines.push(header);\n if (eventName) lines.push(` on: ${orange(eventName)}`);\n if (entry.file) lines.push(` in: ${dim(loc(entry.file, entry.line))}`);\n\n // Find the reaction in the model to enrich with producer/dispatch info.\n const sliceReaction = idx.model.slices\n .find((s) => s.name === sliceName)\n ?.reactions.find(\n (r) => r.handlerName === entry.name && r.event === eventName\n );\n const orchReaction = idx.model.reactions.find(\n (r) => r.handlerName === entry.name && r.event === eventName\n );\n const r = sliceReaction ?? orchReaction;\n\n if (eventName) {\n const producers = findActionsEmitting(idx.model, eventName);\n if (producers.length > 0) {\n lines.push(\" producers (of triggering event):\");\n for (const p of producers) {\n lines.push(\n ` - action ${pink(p.action)} (state ${p.state})${fileNote(p.file, p.line)}`\n );\n }\n }\n }\n if (r && r.dispatches.length > 0) {\n lines.push(\" triggers:\");\n for (const d of r.dispatches) lines.push(` - action ${pink(d)}`);\n }\n return lines.join(\"\\n\");\n}\n\nexport const formatters: Record<\n string,\n (idx: ContractIndex, entry: IndexEntry) => string\n> = {\n event: formatEvent,\n action: formatAction,\n state: formatState,\n slice: formatSlice,\n projection: formatProjection,\n reaction: formatReaction,\n};\n\nexport function formatDetail(idx: ContractIndex, entry: IndexEntry): string {\n const fmt = formatters[entry.kind];\n return fmt ? fmt(idx, entry) : \"\";\n}\n\n/** Header summary printed once at CLI startup. */\nexport function formatSummary(idx: ContractIndex): string {\n const m = idx.model;\n const parts = [\n `${m.states.length} ${m.states.length === 1 ? \"state\" : \"states\"}`,\n `${m.slices.length} ${m.slices.length === 1 ? \"slice\" : \"slices\"}`,\n `${m.projections.length} ${\n m.projections.length === 1 ? \"projection\" : \"projections\"\n }`,\n `${idx.allEventNames.size} ${\n idx.allEventNames.size === 1 ? \"event\" : \"events\"\n }`,\n ];\n return dim(`loaded ${parts.join(\", \")}`);\n}\n","/**\n * Emit each event's Zod schema as JSON Schema, plus the producer/consumer\n * graph in a stable JSON shape. Consumers in other services can:\n *\n * const ajv = new Ajv({ strict: false });\n * const validate = ajv.compile(report.events.OrderPlaced.schema);\n * if (!validate(payload)) throw new Error(JSON.stringify(validate.errors));\n *\n * The output is intentionally machine-readable, not pretty: pipe it to\n * `jq` or commit it under `contracts/` for downstream consumption.\n *\n * `z.toJSONSchema()` (Zod v4) does the heavy lifting; we wrap each call\n * in a try/catch because not every Zod schema (e.g. those with custom\n * transforms) has a clean JSON representation.\n */\nimport { z } from \"zod\";\nimport type { DomainModel } from \"../client/types/index.js\";\nimport { type ContractIndex, eventStatus } from \"./contract-index.js\";\n\ntype EventReport = {\n name: string;\n file?: string;\n line?: number;\n status: \"active\" | \"deprecated\";\n supersededBy?: string;\n schemaText?: string;\n schema?: unknown;\n schemaError?: string;\n producers: Array<{\n action: string;\n state: string;\n file?: string;\n line?: number;\n }>;\n consumers: Array<\n | {\n type: \"reaction\";\n slice?: string;\n handler: string;\n dispatches: string[];\n file?: string;\n line?: number;\n }\n | { type: \"projection\"; name: string; file?: string }\n >;\n};\n\ntype Report = {\n $schema: string;\n generator: string;\n generatedAt: string;\n counts: {\n states: number;\n slices: number;\n projections: number;\n events: number;\n };\n events: Record<string, EventReport>;\n};\n\nconst findProducers = (model: DomainModel, eventName: string) => {\n const out: EventReport[\"producers\"] = [];\n for (const st of model.states) {\n for (const act of st.actions) {\n if (act.emits.includes(eventName)) {\n out.push({\n action: act.name,\n state: st.name,\n file: st.file,\n line: act.line,\n });\n }\n }\n }\n return out;\n};\n\nconst findConsumers = (\n model: DomainModel,\n eventName: string\n): EventReport[\"consumers\"] => {\n const out: EventReport[\"consumers\"] = [];\n for (const sl of model.slices) {\n for (const r of sl.reactions) {\n if (r.event === eventName) {\n out.push({\n type: \"reaction\",\n slice: sl.name,\n handler: r.handlerName,\n dispatches: r.dispatches,\n file: r.file ?? sl.file,\n line: r.line,\n });\n }\n }\n }\n for (const r of model.reactions) {\n if (r.event === eventName) {\n out.push({\n type: \"reaction\",\n handler: r.handlerName,\n dispatches: r.dispatches,\n file: r.file,\n line: r.line,\n });\n }\n }\n for (const p of model.projections) {\n if (p.handles.includes(eventName)) {\n out.push({ type: \"projection\", name: p.name, file: p.file });\n }\n }\n return out;\n};\n\n/**\n * Best-effort Zod → JSON Schema conversion. Returns either a schema or\n * an error string; never throws.\n */\nexport function toJsonSchemaSafe(\n zod: unknown\n): { schema: unknown; error?: undefined } | { error: string } {\n if (!zod || typeof zod !== \"object\") {\n return { error: \"no zod schema captured\" };\n }\n try {\n const schema = z.toJSONSchema(zod as z.ZodType);\n return { schema };\n } catch (err) {\n // The `String(err)` arm only fires when something non-Error is\n // thrown, which Zod never does in practice — ignore for coverage.\n /* v8 ignore start */\n return { error: err instanceof Error ? err.message : String(err) };\n /* v8 ignore stop */\n }\n}\n\nexport function formatJsonSchema(idx: ContractIndex): string {\n const m = idx.model;\n const events: Record<string, EventReport> = {};\n\n for (const st of m.states) {\n for (const ev of st.events) {\n const status = eventStatus(ev.name, idx.allEventNames);\n const conv = toJsonSchemaSafe(ev.zod);\n const report: EventReport = {\n name: ev.name,\n file: st.file,\n line: ev.line,\n status: status.status,\n supersededBy: status.supersededBy,\n schemaText: ev.schema,\n producers: findProducers(m, ev.name),\n consumers: findConsumers(m, ev.name),\n };\n if (\"schema\" in conv) report.schema = conv.schema;\n else report.schemaError = conv.error;\n events[ev.name] = report;\n }\n }\n\n const out: Report = {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n generator: \"act-diagram/act-contracts\",\n generatedAt: new Date().toISOString(),\n counts: {\n states: m.states.length,\n slices: m.slices.length,\n projections: m.projections.length,\n events: idx.allEventNames.size,\n },\n events,\n };\n return JSON.stringify(out, null, 2);\n}\n","/**\n * Filesystem walker for the act-contracts CLI.\n * Recursively reads TypeScript source files from a project root and\n * returns a FileTab[] in the same shape `extractModel` already consumes.\n */\nimport type { Dirent } from \"node:fs\";\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport { posix } from \"node:path\";\nimport type { FileTab } from \"../client/types/file-tab.js\";\n\nconst SKIP_DIRS = new Set([\n \"node_modules\",\n \"dist\",\n \"coverage\",\n \"build\",\n \".git\",\n \".turbo\",\n \".next\",\n \".vercel\",\n // tests\n \"__tests__\",\n \"test\",\n \"tests\",\n \"e2e\",\n // benchmarks\n \"bench\",\n \"benches\",\n \"benchmark\",\n \"benchmarks\",\n \"perf\",\n // build-time scripts and generated artifacts\n \"scripts\",\n]);\n\nconst SKIP_FILE_RE = /\\.(?:d\\.ts|tsx|test\\.ts|spec\\.ts|bench\\.ts|perf\\.ts)$/;\n\nexport type LoadOptions = {\n /** Maximum number of files to read. Default 5000 — protects against runaway scans. */\n maxFiles?: number;\n};\n\nexport type LoadResult = {\n files: FileTab[];\n truncated: boolean;\n};\n\n/**\n * Walk `rootDir` and return every `.ts` file that survives the skip rules.\n * Returned `FileTab.path` values are project-relative (POSIX separators).\n */\nexport async function loadProject(\n rootDir: string,\n opts: LoadOptions = {}\n): Promise<LoadResult> {\n const max = opts.maxFiles ?? 5000;\n const files: FileTab[] = [];\n let truncated = false;\n\n const visit = async (absDir: string, relDir: string): Promise<void> => {\n let entries: Dirent[];\n try {\n entries = (await readdir(absDir, { withFileTypes: true })) as Dirent[];\n /* c8 ignore start — defensive against perms/removed-dir races. */\n } catch {\n return;\n }\n /* c8 ignore stop */\n for (const entry of entries) {\n if (files.length >= max) {\n truncated = true;\n return;\n }\n const name = entry.name;\n if (name.startsWith(\".\") && name !== \".\") continue;\n const absPath = posix.join(absDir.replace(/\\\\/g, \"/\"), name);\n const relPath = relDir ? posix.join(relDir, name) : name;\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(name)) continue;\n await visit(absPath, relPath);\n continue;\n }\n // Defensive against symlinks / FIFOs / devices.\n /* c8 ignore start */\n if (!entry.isFile()) continue;\n /* c8 ignore stop */\n if (!name.endsWith(\".ts\")) continue;\n if (SKIP_FILE_RE.test(name)) continue;\n try {\n const content = await readFile(absPath, \"utf8\");\n files.push({ path: relPath, content });\n } catch {\n // unreadable file — skip\n }\n }\n };\n\n const rootStat = await stat(rootDir).catch(() => null);\n if (!rootStat || !rootStat.isDirectory()) {\n return { files, truncated };\n }\n await visit(rootDir.replace(/\\\\/g, \"/\"), \"\");\n return { files, truncated };\n}\n","/**\n * Render the full contract index as a Markdown registry. One section\n * per kind, one subsection per entity. Used by `act --markdown` for\n * pipe-friendly output that diffs cleanly between branches.\n *\n * Output is plain ASCII (no ANSI escapes) regardless of `picocolors`\n * settings — readers expect Markdown to be paste-able into a PR body\n * or a static doc file.\n */\nimport type { DomainModel } from \"../client/types/index.js\";\nimport {\n type ContractIndex,\n eventStatus,\n listByKind,\n} from \"./contract-index.js\";\n\nconst loc = (file?: string, line?: number): string => {\n if (!file) return \"\";\n return line ? `${file}:${line}` : file;\n};\n\nconst findActionsEmitting = (\n model: DomainModel,\n eventName: string\n): Array<{ state: string; action: string; file?: string; line?: number }> => {\n const out: Array<{\n state: string;\n action: string;\n file?: string;\n line?: number;\n }> = [];\n for (const st of model.states) {\n for (const act of st.actions) {\n if (act.emits.includes(eventName)) {\n out.push({\n state: st.name,\n action: act.name,\n file: st.file,\n line: act.line,\n });\n }\n }\n }\n return out;\n};\n\nconst findReactionsFor = (\n model: DomainModel,\n eventName: string\n): Array<{\n slice?: string;\n handler: string;\n dispatches: string[];\n file?: string;\n line?: number;\n}> => {\n const out: Array<{\n slice?: string;\n handler: string;\n dispatches: string[];\n file?: string;\n line?: number;\n }> = [];\n for (const sl of model.slices) {\n for (const r of sl.reactions) {\n if (r.event === eventName) {\n out.push({\n slice: sl.name,\n handler: r.handlerName,\n dispatches: r.dispatches,\n file: r.file ?? sl.file,\n line: r.line,\n });\n }\n }\n }\n for (const r of model.reactions) {\n if (r.event === eventName) {\n out.push({\n handler: r.handlerName,\n dispatches: r.dispatches,\n file: r.file,\n line: r.line,\n });\n }\n }\n return out;\n};\n\nconst findProjectionsFor = (\n model: DomainModel,\n eventName: string\n): Array<{ name: string; file?: string }> =>\n model.projections\n .filter((p) => p.handles.includes(eventName))\n .map((p) => ({ name: p.name, file: p.file }));\n\nconst fileSuffix = (file?: string, line?: number): string => {\n const l = loc(file, line);\n return l ? ` *(${l})*` : \"\";\n};\n\n/** Render a captured Zod expression. Single-line goes inline with\n * backticks; multi-line gets a fenced code block so newlines survive. */\nconst renderSchema = (s: string | undefined): string => {\n if (!s) return \"_(not captured)_\";\n if (!s.includes(\"\\n\")) return `\\`${s}\\``;\n const indented = s\n .split(\"\\n\")\n .map((l) => ` ${l}`)\n .join(\"\\n\");\n return `\\n\\n \\`\\`\\`ts\\n${indented}\\n \\`\\`\\``;\n};\n\nexport function formatMarkdown(idx: ContractIndex): string {\n const m = idx.model;\n const lines: string[] = [];\n\n lines.push(\"# Act Contracts Registry\");\n lines.push(\"\");\n lines.push(\n `_Generated by \\`act --markdown\\`. ${m.states.length} states, ${m.slices.length} slices, ${m.projections.length} projections, ${idx.allEventNames.size} events._`\n );\n lines.push(\"\");\n\n // ── Events ──────────────────────────────────────────────────────────\n lines.push(\"## Events\");\n lines.push(\"\");\n const events = listByKind(idx, \"event\");\n if (events.length === 0) lines.push(\"_(none)_\\n\");\n for (const e of events) {\n let schema: string | undefined;\n let owningState: string | undefined;\n for (const st of m.states) {\n const ev = st.events.find((x) => x.name === e.name);\n if (ev) {\n schema = ev.schema;\n owningState = st.name;\n break;\n }\n }\n const status = eventStatus(e.name, idx.allEventNames);\n const statusLabel =\n status.status === \"active\"\n ? \"active\"\n : `deprecated — superseded by **${status.supersededBy}**`;\n lines.push(`### \\`${e.name}\\``);\n // `e.file` always carries the state's source file via buildContractIndex.\n if (e.file) lines.push(`- **defined in:** \\`${loc(e.file, e.line)}\\``);\n if (owningState && owningState !== e.name)\n lines.push(`- **on state:** \\`${owningState}\\``);\n lines.push(`- **schema:** ${renderSchema(schema)}`);\n lines.push(`- **status:** ${statusLabel}`);\n\n const producers = findActionsEmitting(m, e.name);\n if (producers.length > 0) {\n lines.push(\"- **producers:**\");\n for (const p of producers)\n lines.push(\n ` - \\`${p.action}\\` (state \\`${p.state}\\`)${fileSuffix(p.file, p.line)}`\n );\n } else {\n lines.push(\"- **producers:** _(none)_\");\n }\n const reactions = findReactionsFor(m, e.name);\n const projections = findProjectionsFor(m, e.name);\n if (reactions.length === 0 && projections.length === 0) {\n lines.push(\"- **consumers:** _(none)_\");\n } else {\n lines.push(\"- **consumers:**\");\n for (const r of reactions) {\n const slice = r.slice ? `\\`${r.slice}\\`::` : \"\";\n const triggers =\n r.dispatches.length > 0\n ? ` → triggers ${r.dispatches.map((d) => `\\`${d}\\``).join(\", \")}`\n : \"\";\n lines.push(\n ` - reaction ${slice}\\`${r.handler}\\`${triggers}${fileSuffix(r.file, r.line)}`\n );\n }\n for (const p of projections)\n lines.push(` - projection \\`${p.name}\\`${fileSuffix(p.file)}`);\n }\n lines.push(\"\");\n }\n\n // ── Actions ─────────────────────────────────────────────────────────\n lines.push(\"## Actions\");\n lines.push(\"\");\n const actions = listByKind(idx, \"action\");\n if (actions.length === 0) lines.push(\"_(none)_\\n\");\n for (const a of actions) {\n let action:\n | { name: string; emits: string[]; invariants: string[]; line?: number }\n | undefined;\n let stateFile: string | undefined;\n for (const st of m.states) {\n if (a.qualifier && st.name !== a.qualifier) continue;\n const found = st.actions.find((x) => x.name === a.name);\n if (found) {\n action = found;\n stateFile = st.file;\n break;\n }\n }\n lines.push(`### \\`${a.name}\\``);\n if (a.qualifier) lines.push(`- **on state:** \\`${a.qualifier}\\``);\n if (stateFile)\n lines.push(\n `- **defined in:** \\`${loc(stateFile, action?.line ?? a.line)}\\``\n );\n if (action) {\n if (action.invariants.length > 0) {\n lines.push(\"- **invariants:**\");\n for (const inv of action.invariants) lines.push(` - ${inv}`);\n }\n if (action.emits.length > 0) {\n lines.push(\"- **emits:**\");\n for (const ev of action.emits) lines.push(` - \\`${ev}\\``);\n } else {\n lines.push(\"- **emits:** _(none)_\");\n }\n }\n lines.push(\"\");\n }\n\n // ── States ──────────────────────────────────────────────────────────\n lines.push(\"## States\");\n lines.push(\"\");\n const states = listByKind(idx, \"state\");\n if (states.length === 0) lines.push(\"_(none)_\\n\");\n for (const s of states) {\n const st = m.states.find((x) => x.name === s.name);\n lines.push(`### \\`${s.name}\\``);\n if (s.file) lines.push(`- **defined in:** \\`${loc(s.file, s.line)}\\``);\n if (st) {\n if (st.actions.length > 0)\n lines.push(\n `- **actions:** ${st.actions.map((x) => `\\`${x.name}\\``).join(\", \")}`\n );\n if (st.events.length > 0)\n lines.push(\n `- **events:** ${st.events.map((x) => `\\`${x.name}\\``).join(\", \")}`\n );\n }\n lines.push(\"\");\n }\n\n // ── Slices ──────────────────────────────────────────────────────────\n lines.push(\"## Slices\");\n lines.push(\"\");\n const slices = listByKind(idx, \"slice\");\n if (slices.length === 0) lines.push(\"_(none)_\\n\");\n for (const s of slices) {\n const sl = m.slices.find((x) => x.name === s.name);\n lines.push(`### \\`${s.name}\\``);\n if (s.file) lines.push(`- **defined in:** \\`${loc(s.file, s.line)}\\``);\n if (sl) {\n if (sl.error) lines.push(`- **error:** ${sl.error}`);\n if (sl.states.length > 0)\n lines.push(\n `- **states:** ${sl.states.map((x) => `\\`${x}\\``).join(\", \")}`\n );\n if (sl.projections.length > 0)\n lines.push(\n `- **projections:** ${sl.projections.map((x) => `\\`${x}\\``).join(\", \")}`\n );\n if (sl.reactions.length > 0) {\n lines.push(\"- **reactions:**\");\n for (const r of sl.reactions) {\n const triggers =\n r.dispatches.length > 0\n ? ` → ${r.dispatches.map((d) => `\\`${d}\\``).join(\", \")}`\n : \"\";\n lines.push(\n ` - \\`${r.event}\\` → \\`${r.handlerName}\\`${triggers}${fileSuffix(r.file, r.line)}`\n );\n }\n }\n }\n lines.push(\"\");\n }\n\n // ── Projections ─────────────────────────────────────────────────────\n lines.push(\"## Projections\");\n lines.push(\"\");\n const projections = listByKind(idx, \"projection\");\n if (projections.length === 0) lines.push(\"_(none)_\\n\");\n for (const p of projections) {\n const pr = m.projections.find((x) => x.name === p.name);\n lines.push(`### \\`${p.name}\\``);\n if (pr?.file) lines.push(`- **defined in:** \\`${loc(pr.file, pr.line)}\\``);\n if (pr && pr.handles.length > 0)\n lines.push(\n `- **handles:** ${pr.handles.map((x) => `\\`${x}\\``).join(\", \")}`\n );\n lines.push(\"\");\n }\n\n // ── Reactions ───────────────────────────────────────────────────────\n lines.push(\"## Reactions\");\n lines.push(\"\");\n const reactions = listByKind(idx, \"reaction\");\n if (reactions.length === 0) lines.push(\"_(none)_\\n\");\n for (const r of reactions) {\n const [sliceName, eventName] = (r.qualifier ?? \"::\").split(\"::\");\n lines.push(`### \\`${r.name}\\``);\n if (sliceName && sliceName !== \"*\")\n lines.push(`- **in slice:** \\`${sliceName}\\``);\n if (eventName) lines.push(`- **on event:** \\`${eventName}\\``);\n if (r.file) lines.push(`- **defined in:** \\`${loc(r.file, r.line)}\\``);\n const sliceReaction = m.slices\n .find((x) => x.name === sliceName)\n ?.reactions.find(\n (rr) => rr.handlerName === r.name && rr.event === eventName\n );\n const orchReaction = m.reactions.find(\n (rr) => rr.handlerName === r.name && rr.event === eventName\n );\n const inner = sliceReaction ?? orchReaction;\n if (inner && inner.dispatches.length > 0) {\n lines.push(\n `- **triggers:** ${inner.dispatches.map((d) => `\\`${d}\\``).join(\", \")}`\n );\n }\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n","/**\n * Interactive flow for the `act` CLI, powered by @clack/prompts.\n *\n * Loop: pick a category (or \"search by name\") → pick an entry → view\n * formatted detail → loop. Ctrl-C / `Quit` exits cleanly.\n */\nimport { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { intro, isCancel, log, outro, select, text } from \"@clack/prompts\";\nimport { dim, kindColor } from \"./colors.js\";\nimport {\n CATEGORY_KEYWORDS,\n type ContractIndex,\n type IndexEntry,\n type Kind,\n listByKind,\n search,\n} from \"./contract-index.js\";\nimport { formatDetail, formatSummary } from \"./format.js\";\nimport { formatJsonSchema } from \"./json-schema.js\";\nimport { formatMarkdown } from \"./markdown.js\";\nimport { openInEditor, pickEditor } from \"./open-editor.js\";\nimport { enableVimKeys, type VimKeysHandle } from \"./vim-keys.js\";\n\n/** Module-level handle so searchByName can pause/resume around text input. */\nlet vimKeys: VimKeysHandle | null = null;\n/** Set when `/` is pressed in a select; the surrounding loop catches it. */\nlet searchRequested = false;\n\ntype CategoryChoice = Kind | \"export\";\n\n/** Single-line nav legend appended to every select prompt. */\nconst NAV_LEGEND = dim(\"j/k or ↑/↓ move · enter pick · / search · esc/q back\");\n\nconst KIND_LABELS: Record<Kind, string> = {\n event: \"events\",\n action: \"actions\",\n state: \"states\",\n slice: \"slices\",\n projection: \"projections\",\n reaction: \"reactions\",\n};\n\nconst KIND_ORDER: Kind[] = [\n \"event\",\n \"action\",\n \"state\",\n \"slice\",\n \"projection\",\n \"reaction\",\n];\n\nconst countByKind = (idx: ContractIndex, kind: Kind): number => {\n if (kind === \"event\") return idx.allEventNames.size;\n return idx.entries.filter((e) => e.kind === kind).length;\n};\n\nconst labelEntry = (e: IndexEntry): string => {\n const loc = e.file ? `${e.file}${e.line ? `:${e.line}` : \"\"}` : \"\";\n const where = loc ? ` ${dim(loc)}` : \"\";\n const qual = e.qualifier ? dim(` (${e.qualifier})`) : \"\";\n // `e.kind` is a Kind union and `kindColor` has every Kind as a key,\n // so the lookup is total.\n const colored = kindColor[e.kind](e.name);\n return `${colored}${qual}${where}`;\n};\n\nasync function pickFromList(\n idx: ContractIndex,\n rootDir: string,\n message: string,\n entries: IndexEntry[]\n): Promise<void> {\n if (entries.length === 0) {\n log.warn(\"nothing to show.\");\n return;\n }\n const pick = await select<IndexEntry>({\n message: `${message} ${NAV_LEGEND}`,\n options: entries.map((e) => ({\n value: e,\n label: labelEntry(e),\n hint: e.kind,\n })),\n maxItems: 12,\n });\n if (isCancel(pick)) return;\n await showDetail(idx, rootDir, pick);\n}\n\nasync function showDetail(\n idx: ContractIndex,\n rootDir: string,\n entry: IndexEntry\n): Promise<void> {\n // log.message keeps our ANSI colors intact; `note()` would wrap each\n // line in a dim attribute that washes the kind colors out. The first\n // line of formatDetail is already the colored bold name, so no extra\n // title prefix.\n log.message(formatDetail(idx, entry));\n if (!entry.file) return;\n const editor = pickEditor(process.env);\n const action = await select<\"open\">({\n message: `now what? ${NAV_LEGEND}`,\n options: [\n {\n value: \"open\" as const,\n label: `open in ${editor}`,\n hint: `${entry.file}${entry.line ? `:${entry.line}` : \"\"}`,\n },\n ],\n });\n if (isCancel(action)) return;\n const result = await openInEditor(entry.file, entry.line, { rootDir });\n if (!result.ok) log.warn(`editor exited: ${result.reason ?? \"unknown\"}`);\n}\n\ntype ExportFormat = \"markdown\" | \"json-schema\";\n\nconst DEFAULT_PATHS: Record<ExportFormat, string> = {\n markdown: \"act-contracts.md\",\n \"json-schema\": \"act-contracts.schema.json\",\n};\n\nasync function exportRegistry(\n idx: ContractIndex,\n rootDir: string\n): Promise<void> {\n const format = await select<ExportFormat>({\n message: `Export as ${NAV_LEGEND}`,\n options: [\n {\n value: \"markdown\" as const,\n label: \"Markdown\",\n hint: \"human-readable registry, pipe to docs/EVENTS.md\",\n },\n {\n value: \"json-schema\" as const,\n label: \"JSON Schema\",\n hint: \"machine-readable; consumers can Ajv.compile() each event\",\n },\n ],\n });\n if (isCancel(format)) return;\n\n vimKeys?.pause();\n const path = await text({\n message: `Save to (relative to ${dim(rootDir)}) ${dim(\"(esc to cancel)\")}`,\n placeholder: DEFAULT_PATHS[format],\n initialValue: DEFAULT_PATHS[format],\n });\n vimKeys?.resume();\n if (isCancel(path) || !path || !path.trim()) return;\n\n const content =\n format === \"markdown\" ? formatMarkdown(idx) : formatJsonSchema(idx);\n const abs = resolve(rootDir, path.trim());\n try {\n await writeFile(abs, `${content}\\n`, \"utf8\");\n log.success(`wrote ${abs}`);\n } catch (err) {\n log.error(\n /* c8 ignore next — the `String(err)` arm fires only on non-Error\n throws, which Node fs.writeFile doesn't produce. */\n `could not write ${abs}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n}\n\nasync function searchByName(\n idx: ContractIndex,\n rootDir: string\n): Promise<void> {\n // Pause the vim-keys patch so j/k are typed as letters in the input\n // box. esc/q still cancel via clack's built-in handling (esc) or as\n // literal \"q\" if the user wants to search for that.\n vimKeys?.pause();\n const q = await text({\n message: `Partial name to search ${dim(\"(esc to cancel)\")}`,\n placeholder: \"e.g. order, ticket, place\",\n });\n vimKeys?.resume();\n if (isCancel(q) || !q || !q.trim()) return;\n const lower = q.trim().toLowerCase();\n const kind = CATEGORY_KEYWORDS[lower];\n if (kind) {\n await pickFromList(\n idx,\n rootDir,\n `${KIND_LABELS[kind]}`,\n listByKind(idx, kind)\n );\n return;\n }\n const matches = search(idx, q.trim(), 200);\n if (matches.length === 0) {\n log.warn(`no matches for \"${q}\"`);\n return;\n }\n await pickFromList(idx, rootDir, `matches for \"${q}\"`, matches);\n}\n\nexport async function runInteractive(\n idx: ContractIndex,\n rootDir: string\n): Promise<void> {\n // j/k → arrows, q → esc, / → request-search. Loops below catch the\n // searchRequested flag when clack cancels and jump to search.\n vimKeys = enableVimKeys(process.stdin);\n const unsub = vimKeys.onSlash(() => {\n searchRequested = true;\n });\n try {\n await driveInteractive(idx, rootDir);\n } finally {\n unsub();\n vimKeys.restore();\n vimKeys = null;\n searchRequested = false;\n }\n}\n\nasync function driveInteractive(\n idx: ContractIndex,\n rootDir: string\n): Promise<void> {\n intro(\"act — contracts explorer\");\n log.message(formatSummary(idx));\n\n while (true) {\n // `/` anywhere in the flow cancels the active prompt and sets this\n // flag; checking at the top of the loop is enough for every screen\n // because each sub-flow returns control here.\n if (searchRequested) {\n searchRequested = false;\n await searchByName(idx, rootDir);\n continue;\n }\n const choice = await select<CategoryChoice>({\n message: `What do you want to inspect? ${NAV_LEGEND}`,\n options: [\n ...KIND_ORDER.map((k) => ({\n value: k as CategoryChoice,\n label: kindColor[k](KIND_LABELS[k]),\n hint: `${countByKind(idx, k)}`,\n })),\n {\n value: \"export\" as const,\n label: \"export\",\n hint: \"Markdown / JSON Schema\",\n },\n ],\n maxItems: 10,\n });\n if (isCancel(choice)) {\n if (searchRequested) continue; // `/` was pressed — loop will pick it up\n outro(\"bye.\");\n return;\n }\n if (choice === \"export\") {\n await exportRegistry(idx, rootDir);\n continue;\n }\n await pickFromList(\n idx,\n rootDir,\n `${KIND_LABELS[choice]}`,\n listByKind(idx, choice)\n );\n }\n}\n","/* MAIN */\nconst getCodePointsLength = (() => {\n const SURROGATE_PAIR_RE = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g;\n return (input) => {\n let surrogatePairsNr = 0;\n SURROGATE_PAIR_RE.lastIndex = 0;\n while (SURROGATE_PAIR_RE.test(input)) {\n surrogatePairsNr += 1;\n }\n return input.length - surrogatePairsNr;\n };\n})();\nconst isFullWidth = (x) => {\n return x === 0x3000 || x >= 0xFF01 && x <= 0xFF60 || x >= 0xFFE0 && x <= 0xFFE6;\n};\nconst isWideNotCJKTNotEmoji = (x) => {\n return x === 0x231B || x === 0x2329 || x >= 0x2FF0 && x <= 0x2FFF || x >= 0x3001 && x <= 0x303E || x >= 0x3099 && x <= 0x30FF || x >= 0x3105 && x <= 0x312F || x >= 0x3131 && x <= 0x318E || x >= 0x3190 && x <= 0x31E3 || x >= 0x31EF && x <= 0x321E || x >= 0x3220 && x <= 0x3247 || x >= 0x3250 && x <= 0x4DBF || x >= 0xFE10 && x <= 0xFE19 || x >= 0xFE30 && x <= 0xFE52 || x >= 0xFE54 && x <= 0xFE66 || x >= 0xFE68 && x <= 0xFE6B || x >= 0x1F200 && x <= 0x1F202 || x >= 0x1F210 && x <= 0x1F23B || x >= 0x1F240 && x <= 0x1F248 || x >= 0x20000 && x <= 0x2FFFD || x >= 0x30000 && x <= 0x3FFFD;\n};\n/* EXPORT */\nexport { getCodePointsLength, isFullWidth, isWideNotCJKTNotEmoji };\n","/* IMPORT */\nimport { getCodePointsLength, isFullWidth, isWideNotCJKTNotEmoji } from './utils.js';\n/* HELPERS */\nconst ANSI_RE = /[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\\u001b\\]8;[^;]*;.*?(?:\\u0007|\\u001b\\u005c)/y;\nconst CONTROL_RE = /[\\x00-\\x08\\x0A-\\x1F\\x7F-\\x9F]{1,1000}/y;\nconst CJKT_WIDE_RE = /(?:(?![\\uFF61-\\uFF9F\\uFF00-\\uFFEF])[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}\\p{Script=Tangut}]){1,1000}/yu;\nconst TAB_RE = /\\t{1,1000}/y;\nconst EMOJI_RE = /[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*/yu;\nconst LATIN_RE = /(?:[\\x20-\\x7E\\xA0-\\xFF](?!\\uFE0F)){1,1000}/y;\nconst MODIFIER_RE = /\\p{M}+/gu;\nconst NO_TRUNCATION = { limit: Infinity, ellipsis: '' };\n/* MAIN */\nconst getStringTruncatedWidth = (input, truncationOptions = {}, widthOptions = {}) => {\n /* CONSTANTS */\n const LIMIT = truncationOptions.limit ?? Infinity;\n const ELLIPSIS = truncationOptions.ellipsis ?? '';\n const ELLIPSIS_WIDTH = truncationOptions?.ellipsisWidth ?? (ELLIPSIS ? getStringTruncatedWidth(ELLIPSIS, NO_TRUNCATION, widthOptions).width : 0);\n const ANSI_WIDTH = 0;\n const CONTROL_WIDTH = widthOptions.controlWidth ?? 0;\n const TAB_WIDTH = widthOptions.tabWidth ?? 8;\n const EMOJI_WIDTH = widthOptions.emojiWidth ?? 2;\n const FULL_WIDTH_WIDTH = 2;\n const REGULAR_WIDTH = widthOptions.regularWidth ?? 1;\n const WIDE_WIDTH = widthOptions.wideWidth ?? FULL_WIDTH_WIDTH;\n const PARSE_BLOCKS = [\n [LATIN_RE, REGULAR_WIDTH],\n [ANSI_RE, ANSI_WIDTH],\n [CONTROL_RE, CONTROL_WIDTH],\n [TAB_RE, TAB_WIDTH],\n [EMOJI_RE, EMOJI_WIDTH],\n [CJKT_WIDE_RE, WIDE_WIDTH],\n ];\n /* STATE */\n let indexPrev = 0;\n let index = 0;\n let length = input.length;\n let lengthExtra = 0;\n let truncationEnabled = false;\n let truncationIndex = length;\n let truncationLimit = Math.max(0, LIMIT - ELLIPSIS_WIDTH);\n let unmatchedStart = 0;\n let unmatchedEnd = 0;\n let width = 0;\n let widthExtra = 0;\n /* PARSE LOOP */\n outer: while (true) {\n /* UNMATCHED */\n if ((unmatchedEnd > unmatchedStart) || (index >= length && index > indexPrev)) {\n const unmatched = input.slice(unmatchedStart, unmatchedEnd) || input.slice(indexPrev, index);\n lengthExtra = 0;\n for (const char of unmatched.replaceAll(MODIFIER_RE, '')) {\n const codePoint = char.codePointAt(0) || 0;\n if (isFullWidth(codePoint)) {\n widthExtra = FULL_WIDTH_WIDTH;\n }\n else if (isWideNotCJKTNotEmoji(codePoint)) {\n widthExtra = WIDE_WIDTH;\n }\n else {\n widthExtra = REGULAR_WIDTH;\n }\n if ((width + widthExtra) > truncationLimit) {\n truncationIndex = Math.min(truncationIndex, Math.max(unmatchedStart, indexPrev) + lengthExtra);\n }\n if ((width + widthExtra) > LIMIT) {\n truncationEnabled = true;\n break outer;\n }\n lengthExtra += char.length;\n width += widthExtra;\n }\n unmatchedStart = unmatchedEnd = 0;\n }\n /* EXITING */\n if (index >= length) {\n break outer;\n }\n /* PARSE BLOCKS */\n for (let i = 0, l = PARSE_BLOCKS.length; i < l; i++) {\n const [BLOCK_RE, BLOCK_WIDTH] = PARSE_BLOCKS[i];\n BLOCK_RE.lastIndex = index;\n if (BLOCK_RE.test(input)) {\n lengthExtra = BLOCK_RE === CJKT_WIDE_RE ? getCodePointsLength(input.slice(index, BLOCK_RE.lastIndex)) : BLOCK_RE === EMOJI_RE ? 1 : BLOCK_RE.lastIndex - index;\n widthExtra = lengthExtra * BLOCK_WIDTH;\n if ((width + widthExtra) > truncationLimit) {\n truncationIndex = Math.min(truncationIndex, index + Math.floor((truncationLimit - width) / BLOCK_WIDTH));\n }\n if ((width + widthExtra) > LIMIT) {\n truncationEnabled = true;\n break outer;\n }\n width += widthExtra;\n unmatchedStart = indexPrev;\n unmatchedEnd = index;\n index = indexPrev = BLOCK_RE.lastIndex;\n continue outer;\n }\n }\n /* UNMATCHED INDEX */\n index += 1;\n }\n /* RETURN */\n return {\n width: truncationEnabled ? truncationLimit : width,\n index: truncationEnabled ? truncationIndex : length,\n truncated: truncationEnabled,\n ellipsed: truncationEnabled && LIMIT >= ELLIPSIS_WIDTH\n };\n};\n/* EXPORT */\nexport default getStringTruncatedWidth;\n","/* IMPORT */\nimport fastStringTruncatedWidth from 'fast-string-truncated-width';\n/* HELPERS */\nconst NO_TRUNCATION = {\n limit: Infinity,\n ellipsis: '',\n ellipsisWidth: 0,\n};\n/* MAIN */\nconst fastStringWidth = (input, options = {}) => {\n return fastStringTruncatedWidth(input, NO_TRUNCATION, options).width;\n};\n/* EXPORT */\nexport default fastStringWidth;\n",null,"export function findCursor<T extends { disabled?: boolean }>(\n\tcursor: number,\n\tdelta: number,\n\toptions: T[]\n) {\n\tconst hasEnabledOptions = options.some((opt) => !opt.disabled);\n\tif (!hasEnabledOptions) {\n\t\treturn cursor;\n\t}\n\tconst newCursor = cursor + delta;\n\tconst maxCursor = Math.max(options.length - 1, 0);\n\tconst clampedCursor = newCursor < 0 ? maxCursor : newCursor > maxCursor ? 0 : newCursor;\n\tconst newOption = options[clampedCursor];\n\tif (newOption.disabled) {\n\t\treturn findCursor(clampedCursor, delta < 0 ? -1 : 1, options);\n\t}\n\treturn clampedCursor;\n}\n\nexport function findTextCursor(\n\tcursor: number,\n\tdeltaX: number,\n\tdeltaY: number,\n\tvalue: string\n): number {\n\tconst lines = value.split('\\n');\n\tlet cursorY = 0;\n\tlet cursorX = cursor;\n\n\tfor (const line of lines) {\n\t\tif (cursorX <= line.length) {\n\t\t\tbreak;\n\t\t}\n\t\tcursorX -= line.length + 1;\n\t\tcursorY++;\n\t}\n\n\tcursorY = Math.max(0, Math.min(lines.length - 1, cursorY + deltaY));\n\n\tcursorX = Math.min(cursorX, lines[cursorY].length) + deltaX;\n\twhile (cursorX < 0 && cursorY > 0) {\n\t\tcursorY--;\n\t\tcursorX += lines[cursorY].length + 1;\n\t}\n\twhile (cursorX > lines[cursorY].length && cursorY < lines.length - 1) {\n\t\tcursorX -= lines[cursorY].length + 1;\n\t\tcursorY++;\n\t}\n\tcursorX = Math.max(0, Math.min(lines[cursorY].length, cursorX));\n\n\tlet newCursor = 0;\n\tfor (let i = 0; i < cursorY; i++) {\n\t\tnewCursor += lines[i].length + 1;\n\t}\n\treturn newCursor + cursorX;\n}\n","const actions = ['up', 'down', 'left', 'right', 'space', 'enter', 'cancel'] as const;\nexport type Action = (typeof actions)[number];\n\nconst DEFAULT_MONTH_NAMES = [\n\t'January',\n\t'February',\n\t'March',\n\t'April',\n\t'May',\n\t'June',\n\t'July',\n\t'August',\n\t'September',\n\t'October',\n\t'November',\n\t'December',\n];\n\n/** Global settings for Clack programs, stored in memory */\ninterface InternalClackSettings {\n\tactions: Set<Action>;\n\taliases: Map<string, Action>;\n\tmessages: {\n\t\tcancel: string;\n\t\terror: string;\n\t};\n\twithGuide: boolean;\n\tdate: {\n\t\tmonthNames: string[];\n\t\tmessages: {\n\t\t\tinvalidMonth: string;\n\t\t\trequired: string;\n\t\t\tinvalidDay: (days: number, month: string) => string;\n\t\t\tafterMin: (min: Date) => string;\n\t\t\tbeforeMax: (max: Date) => string;\n\t\t};\n\t};\n}\n\nexport const settings: InternalClackSettings = {\n\tactions: new Set(actions),\n\taliases: new Map<string, Action>([\n\t\t// vim support\n\t\t['k', 'up'],\n\t\t['j', 'down'],\n\t\t['h', 'left'],\n\t\t['l', 'right'],\n\t\t['\\x03', 'cancel'],\n\t\t// opinionated defaults!\n\t\t['escape', 'cancel'],\n\t]),\n\tmessages: {\n\t\tcancel: 'Canceled',\n\t\terror: 'Something went wrong',\n\t},\n\twithGuide: true,\n\tdate: {\n\t\tmonthNames: [...DEFAULT_MONTH_NAMES],\n\t\tmessages: {\n\t\t\trequired: 'Please enter a valid date',\n\t\t\tinvalidMonth: 'There are only 12 months in a year',\n\t\t\tinvalidDay: (days, month) => `There are only ${days} days in ${month}`,\n\t\t\tafterMin: (min) => `Date must be on or after ${min.toISOString().slice(0, 10)}`,\n\t\t\tbeforeMax: (max) => `Date must be on or before ${max.toISOString().slice(0, 10)}`,\n\t\t},\n\t},\n};\n\nexport interface ClackSettings {\n\t/**\n\t * Set custom global aliases for the default actions.\n\t * This will not overwrite existing aliases, it will only add new ones!\n\t *\n\t * @param aliases - An object that maps aliases to actions\n\t * @default { k: 'up', j: 'down', h: 'left', l: 'right', '\\x03': 'cancel', 'escape': 'cancel' }\n\t */\n\taliases?: Record<string, Action>;\n\n\t/**\n\t * Custom messages for prompts\n\t */\n\tmessages?: {\n\t\t/**\n\t\t * Custom message to display when a spinner is cancelled\n\t\t * @default \"Canceled\"\n\t\t */\n\t\tcancel?: string;\n\t\t/**\n\t\t * Custom message to display when a spinner encounters an error\n\t\t * @default \"Something went wrong\"\n\t\t */\n\t\terror?: string;\n\t};\n\n\twithGuide?: boolean;\n\n\t/**\n\t * Date prompt localization\n\t */\n\tdate?: {\n\t\t/** Month names for validation messages (January, February, ...) */\n\t\tmonthNames?: string[];\n\t\tmessages?: {\n\t\t\t/** Shown when date is missing */\n\t\t\trequired?: string;\n\t\t\t/** Shown when month > 12 */\n\t\t\tinvalidMonth?: string;\n\t\t\t/** (days, monthName) => message for invalid day */\n\t\t\tinvalidDay?: (days: number, month: string) => string;\n\t\t\t/** (min) => message when date is before minDate */\n\t\t\tafterMin?: (min: Date) => string;\n\t\t\t/** (max) => message when date is after maxDate */\n\t\t\tbeforeMax?: (max: Date) => string;\n\t\t};\n\t};\n}\n\nexport function updateSettings(updates: ClackSettings) {\n\t// Handle each property in the updates\n\tif (updates.aliases !== undefined) {\n\t\tconst aliases = updates.aliases;\n\t\tfor (const alias in aliases) {\n\t\t\tif (!Object.hasOwn(aliases, alias)) continue;\n\n\t\t\tconst action = aliases[alias];\n\t\t\tif (!settings.actions.has(action)) continue;\n\n\t\t\tif (!settings.aliases.has(alias)) {\n\t\t\t\tsettings.aliases.set(alias, action);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (updates.messages !== undefined) {\n\t\tconst messages = updates.messages;\n\t\tif (messages.cancel !== undefined) {\n\t\t\tsettings.messages.cancel = messages.cancel;\n\t\t}\n\t\tif (messages.error !== undefined) {\n\t\t\tsettings.messages.error = messages.error;\n\t\t}\n\t}\n\n\tif (updates.withGuide !== undefined) {\n\t\tsettings.withGuide = updates.withGuide !== false;\n\t}\n\n\tif (updates.date !== undefined) {\n\t\tconst date = updates.date;\n\t\tif (date.monthNames !== undefined) {\n\t\t\tsettings.date.monthNames = [...date.monthNames];\n\t\t}\n\t\tif (date.messages !== undefined) {\n\t\t\tif (date.messages.required !== undefined) {\n\t\t\t\tsettings.date.messages.required = date.messages.required;\n\t\t\t}\n\t\t\tif (date.messages.invalidMonth !== undefined) {\n\t\t\t\tsettings.date.messages.invalidMonth = date.messages.invalidMonth;\n\t\t\t}\n\t\t\tif (date.messages.invalidDay !== undefined) {\n\t\t\t\tsettings.date.messages.invalidDay = date.messages.invalidDay;\n\t\t\t}\n\t\t\tif (date.messages.afterMin !== undefined) {\n\t\t\t\tsettings.date.messages.afterMin = date.messages.afterMin;\n\t\t\t}\n\t\t\tif (date.messages.beforeMax !== undefined) {\n\t\t\t\tsettings.date.messages.beforeMax = date.messages.beforeMax;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Check if a key is an alias for a default action\n * @param key - The raw key which might match to an action\n * @param action - The action to match\n * @returns boolean\n */\nexport function isActionKey(key: string | Array<string | undefined>, action: Action) {\n\tif (typeof key === 'string') {\n\t\treturn settings.aliases.get(key) === action;\n\t}\n\n\tfor (const value of key) {\n\t\tif (value === undefined) continue;\n\t\tif (isActionKey(value, action)) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n","export function diffLines(a: string, b: string) {\n\tif (a === b) return;\n\n\tconst aLines = a.split('\\n');\n\tconst bLines = b.split('\\n');\n\tconst numLines = Math.max(aLines.length, bLines.length);\n\tconst diff: number[] = [];\n\n\tfor (let i = 0; i < numLines; i++) {\n\t\tif (aLines[i] !== bLines[i]) diff.push(i);\n\t}\n\n\treturn {\n\t\tlines: diff,\n\t\tnumLinesBefore: aLines.length,\n\t\tnumLinesAfter: bLines.length,\n\t\tnumLines,\n\t};\n}\n","import { stdin, stdout } from 'node:process';\nimport type { Key } from 'node:readline';\nimport * as readline from 'node:readline';\nimport type { Readable, Writable } from 'node:stream';\nimport { ReadStream } from 'node:tty';\nimport { wrapAnsi } from 'fast-wrap-ansi';\nimport { cursor } from 'sisteransi';\nimport { isActionKey } from './settings.js';\n\nexport * from './settings.js';\nexport * from './string.js';\n\nconst isWindows = globalThis.process.platform.startsWith('win');\n\nexport const CANCEL_SYMBOL = Symbol('clack:cancel');\n\nexport function isCancel(value: unknown): value is symbol {\n\treturn value === CANCEL_SYMBOL;\n}\n\nexport function setRawMode(input: Readable, value: boolean) {\n\tconst i = input as typeof stdin;\n\n\tif (i.isTTY) i.setRawMode(value);\n}\n\ninterface BlockOptions {\n\tinput?: Readable;\n\toutput?: Writable;\n\toverwrite?: boolean;\n\thideCursor?: boolean;\n}\n\nexport function block({\n\tinput = stdin,\n\toutput = stdout,\n\toverwrite = true,\n\thideCursor = true,\n}: BlockOptions = {}) {\n\tconst rl = readline.createInterface({\n\t\tinput,\n\t\toutput,\n\t\tprompt: '',\n\t\ttabSize: 1,\n\t});\n\treadline.emitKeypressEvents(input, rl);\n\n\tif (input instanceof ReadStream && input.isTTY) {\n\t\tinput.setRawMode(true);\n\t}\n\n\tconst clear = (data: Buffer, { name, sequence }: Key) => {\n\t\tconst str = String(data);\n\t\tif (isActionKey([str, name, sequence], 'cancel')) {\n\t\t\tif (hideCursor) output.write(cursor.show);\n\t\t\tprocess.exit(0);\n\t\t\treturn;\n\t\t}\n\t\tif (!overwrite) return;\n\t\tconst dx = name === 'return' ? 0 : -1;\n\t\tconst dy = name === 'return' ? -1 : 0;\n\n\t\treadline.moveCursor(output, dx, dy, () => {\n\t\t\treadline.clearLine(output, 1, () => {\n\t\t\t\tinput.once('keypress', clear);\n\t\t\t});\n\t\t});\n\t};\n\tif (hideCursor) output.write(cursor.hide);\n\tinput.once('keypress', clear);\n\n\treturn () => {\n\t\tinput.off('keypress', clear);\n\t\tif (hideCursor) output.write(cursor.show);\n\n\t\t// Prevent Windows specific issues: https://github.com/bombshell-dev/clack/issues/176\n\t\tif (input instanceof ReadStream && input.isTTY && !isWindows) {\n\t\t\tinput.setRawMode(false);\n\t\t}\n\n\t\t// @ts-expect-error fix for https://github.com/nodejs/node/issues/31762#issuecomment-1441223907\n\t\trl.terminal = false;\n\t\trl.close();\n\t};\n}\n\nexport const getColumns = (output: Writable): number => {\n\tif ('columns' in output && typeof output.columns === 'number') {\n\t\treturn output.columns;\n\t}\n\treturn 80;\n};\n\nexport const getRows = (output: Writable): number => {\n\tif ('rows' in output && typeof output.rows === 'number') {\n\t\treturn output.rows;\n\t}\n\treturn 20;\n};\n\nexport function wrapTextWithPrefix(\n\toutput: Writable | undefined,\n\ttext: string,\n\tprefix: string,\n\tstartPrefix: string = prefix,\n\tendPrefix: string = prefix,\n\tlineFormatter?: (line: string, index: number) => string\n): string {\n\tconst columns = getColumns(output ?? stdout);\n\tconst wrapped = wrapAnsi(text, columns - prefix.length, {\n\t\thard: true,\n\t\ttrim: false,\n\t});\n\tconst lines = wrapped\n\t\t.split('\\n')\n\t\t.map((line, index, arr) => {\n\t\t\tconst lineString = lineFormatter ? lineFormatter(line, index) : line;\n\t\t\tif (index === 0) {\n\t\t\t\treturn `${startPrefix}${lineString}`;\n\t\t\t} else if (index === arr.length - 1) {\n\t\t\t\treturn `${endPrefix}${lineString}`;\n\t\t\t}\n\t\t\treturn `${prefix}${lineString}`;\n\t\t})\n\t\t.join('\\n');\n\treturn lines;\n}\n","import { stdin, stdout } from 'node:process';\nimport readline, { type Key, type ReadLine } from 'node:readline';\nimport type { Readable, Writable } from 'node:stream';\nimport { wrapAnsi } from 'fast-wrap-ansi';\nimport { cursor, erase } from 'sisteransi';\nimport type { ClackEvents, ClackState } from '../types.js';\nimport type { Action } from '../utils/index.js';\nimport {\n\tCANCEL_SYMBOL,\n\tdiffLines,\n\tgetRows,\n\tisActionKey,\n\tsetRawMode,\n\tsettings,\n} from '../utils/index.js';\n\nexport interface PromptOptions<TValue, Self extends Prompt<TValue>> {\n\trender(this: Omit<Self, 'prompt'>): string | undefined;\n\tinitialValue?: any;\n\tinitialUserInput?: string;\n\tvalidate?: ((value: TValue | undefined) => string | Error | undefined) | undefined;\n\tinput?: Readable;\n\toutput?: Writable;\n\tsignal?: AbortSignal;\n}\n\nexport default class Prompt<TValue> {\n\tprotected input: Readable;\n\tprotected output: Writable;\n\tprivate _abortSignal?: AbortSignal;\n\n\tprivate rl: ReadLine | undefined;\n\tprivate opts: Omit<PromptOptions<TValue, Prompt<TValue>>, 'render' | 'input' | 'output'>;\n\tprivate _render: (context: Omit<Prompt<TValue>, 'prompt'>) => string | undefined;\n\tprivate _track = false;\n\tprivate _prevFrame = '';\n\tprivate _subscribers = new Map<string, { cb: (...args: any) => any; once?: boolean }[]>();\n\tprotected _cursor = 0;\n\n\tpublic state: ClackState = 'initial';\n\tpublic error = '';\n\tpublic value: TValue | undefined;\n\tpublic userInput = '';\n\n\tconstructor(options: PromptOptions<TValue, Prompt<TValue>>, trackValue = true) {\n\t\tconst { input = stdin, output = stdout, render, signal, ...opts } = options;\n\n\t\tthis.opts = opts;\n\t\tthis.onKeypress = this.onKeypress.bind(this);\n\t\tthis.close = this.close.bind(this);\n\t\tthis.render = this.render.bind(this);\n\t\tthis._render = render.bind(this);\n\t\tthis._track = trackValue;\n\t\tthis._abortSignal = signal;\n\n\t\tthis.input = input;\n\t\tthis.output = output;\n\t}\n\n\t/**\n\t * Unsubscribe all listeners\n\t */\n\tprotected unsubscribe() {\n\t\tthis._subscribers.clear();\n\t}\n\n\t/**\n\t * Set a subscriber with opts\n\t * @param event - The event name\n\t */\n\tprivate setSubscriber<T extends keyof ClackEvents<TValue>>(\n\t\tevent: T,\n\t\topts: { cb: ClackEvents<TValue>[T]; once?: boolean }\n\t) {\n\t\tconst params = this._subscribers.get(event) ?? [];\n\t\tparams.push(opts);\n\t\tthis._subscribers.set(event, params);\n\t}\n\n\t/**\n\t * Subscribe to an event\n\t * @param event - The event name\n\t * @param cb - The callback\n\t */\n\tpublic on<T extends keyof ClackEvents<TValue>>(event: T, cb: ClackEvents<TValue>[T]) {\n\t\tthis.setSubscriber(event, { cb });\n\t}\n\n\t/**\n\t * Subscribe to an event once\n\t * @param event - The event name\n\t * @param cb - The callback\n\t */\n\tpublic once<T extends keyof ClackEvents<TValue>>(event: T, cb: ClackEvents<TValue>[T]) {\n\t\tthis.setSubscriber(event, { cb, once: true });\n\t}\n\n\t/**\n\t * Emit an event with data\n\t * @param event - The event name\n\t * @param data - The data to pass to the callback\n\t */\n\tpublic emit<T extends keyof ClackEvents<TValue>>(\n\t\tevent: T,\n\t\t...data: Parameters<ClackEvents<TValue>[T]>\n\t) {\n\t\tconst cbs = this._subscribers.get(event) ?? [];\n\t\tconst cleanup: (() => void)[] = [];\n\n\t\tfor (const subscriber of cbs) {\n\t\t\tsubscriber.cb(...data);\n\n\t\t\tif (subscriber.once) {\n\t\t\t\tcleanup.push(() => cbs.splice(cbs.indexOf(subscriber), 1));\n\t\t\t}\n\t\t}\n\n\t\tfor (const cb of cleanup) {\n\t\t\tcb();\n\t\t}\n\t}\n\n\tpublic prompt() {\n\t\treturn new Promise<TValue | symbol | undefined>((resolve) => {\n\t\t\tif (this._abortSignal) {\n\t\t\t\tif (this._abortSignal.aborted) {\n\t\t\t\t\tthis.state = 'cancel';\n\n\t\t\t\t\tthis.close();\n\t\t\t\t\treturn resolve(CANCEL_SYMBOL);\n\t\t\t\t}\n\n\t\t\t\tthis._abortSignal.addEventListener(\n\t\t\t\t\t'abort',\n\t\t\t\t\t() => {\n\t\t\t\t\t\tthis.state = 'cancel';\n\t\t\t\t\t\tthis.close();\n\t\t\t\t\t},\n\t\t\t\t\t{ once: true }\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthis.rl = readline.createInterface({\n\t\t\t\tinput: this.input,\n\t\t\t\ttabSize: 2,\n\t\t\t\tprompt: '',\n\t\t\t\tescapeCodeTimeout: 50,\n\t\t\t\tterminal: true,\n\t\t\t});\n\t\t\tthis.rl.prompt();\n\n\t\t\tif (this.opts.initialUserInput !== undefined) {\n\t\t\t\tthis._setUserInput(this.opts.initialUserInput, true);\n\t\t\t}\n\n\t\t\tthis.input.on('keypress', this.onKeypress);\n\t\t\tsetRawMode(this.input, true);\n\t\t\tthis.output.on('resize', this.render);\n\n\t\t\tthis.render();\n\n\t\t\tthis.once('submit', () => {\n\t\t\t\tthis.output.write(cursor.show);\n\t\t\t\tthis.output.off('resize', this.render);\n\t\t\t\tsetRawMode(this.input, false);\n\t\t\t\tresolve(this.value);\n\t\t\t});\n\t\t\tthis.once('cancel', () => {\n\t\t\t\tthis.output.write(cursor.show);\n\t\t\t\tthis.output.off('resize', this.render);\n\t\t\t\tsetRawMode(this.input, false);\n\t\t\t\tresolve(CANCEL_SYMBOL);\n\t\t\t});\n\t\t});\n\t}\n\n\tprotected _isActionKey(char: string | undefined, _key: Key): boolean {\n\t\treturn char === '\\t';\n\t}\n\n\tprotected _shouldSubmit(_char: string | undefined, _key: Key): boolean {\n\t\treturn true;\n\t}\n\n\tprotected _setValue(value: TValue | undefined): void {\n\t\tthis.value = value;\n\t\tthis.emit('value', this.value);\n\t}\n\n\tprotected _setUserInput(value: string | undefined, write?: boolean): void {\n\t\tthis.userInput = value ?? '';\n\t\tthis.emit('userInput', this.userInput);\n\t\tif (write && this._track && this.rl) {\n\t\t\tthis.rl.write(this.userInput);\n\t\t\tthis._cursor = this.rl.cursor;\n\t\t}\n\t}\n\n\tprotected _clearUserInput(): void {\n\t\tthis.rl?.write(null, { ctrl: true, name: 'u' });\n\t\tthis._setUserInput('');\n\t}\n\n\tprivate onKeypress(char: string | undefined, key: Key) {\n\t\tif (this._track && key.name !== 'return') {\n\t\t\tif (key.name && this._isActionKey(char, key)) {\n\t\t\t\tthis.rl?.write(null, { ctrl: true, name: 'h' });\n\t\t\t}\n\t\t\tthis._cursor = this.rl?.cursor ?? 0;\n\t\t\tthis._setUserInput(this.rl?.line);\n\t\t}\n\n\t\tif (this.state === 'error') {\n\t\t\tthis.state = 'active';\n\t\t}\n\t\tif (key?.name) {\n\t\t\tif (!this._track && settings.aliases.has(key.name)) {\n\t\t\t\tthis.emit('cursor', settings.aliases.get(key.name));\n\t\t\t}\n\t\t\tif (settings.actions.has(key.name as Action)) {\n\t\t\t\tthis.emit('cursor', key.name as Action);\n\t\t\t}\n\t\t}\n\t\tif (char && (char.toLowerCase() === 'y' || char.toLowerCase() === 'n')) {\n\t\t\tthis.emit('confirm', char.toLowerCase() === 'y');\n\t\t}\n\n\t\t// Call the key event handler and emit the key event\n\t\tthis.emit('key', char?.toLowerCase(), key);\n\n\t\tif (key?.name === 'return' && this._shouldSubmit(char, key)) {\n\t\t\tif (this.opts.validate) {\n\t\t\t\tconst problem = this.opts.validate(this.value);\n\t\t\t\tif (problem) {\n\t\t\t\t\tthis.error = problem instanceof Error ? problem.message : problem;\n\t\t\t\t\tthis.state = 'error';\n\t\t\t\t\tthis.rl?.write(this.userInput);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this.state !== 'error') {\n\t\t\t\tthis.state = 'submit';\n\t\t\t}\n\t\t}\n\n\t\tif (isActionKey([char, key?.name, key?.sequence], 'cancel')) {\n\t\t\tthis.state = 'cancel';\n\t\t}\n\n\t\tif (this.state === 'submit' || this.state === 'cancel') {\n\t\t\tthis.emit('finalize');\n\t\t}\n\t\tthis.render();\n\t\tif (this.state === 'submit' || this.state === 'cancel') {\n\t\t\tthis.close();\n\t\t}\n\t}\n\n\tprotected close() {\n\t\tthis.input.unpipe();\n\t\tthis.input.removeListener('keypress', this.onKeypress);\n\t\tthis.output.write('\\n');\n\t\tsetRawMode(this.input, false);\n\t\tthis.rl?.close();\n\t\tthis.rl = undefined;\n\t\tthis.emit(`${this.state}`, this.value);\n\t\tthis.unsubscribe();\n\t}\n\n\tprivate restoreCursor() {\n\t\tconst lines =\n\t\t\twrapAnsi(this._prevFrame, process.stdout.columns, { hard: true, trim: false }).split('\\n')\n\t\t\t\t.length - 1;\n\t\tthis.output.write(cursor.move(-999, lines * -1));\n\t}\n\n\tprivate render() {\n\t\tconst frame = wrapAnsi(this._render(this) ?? '', process.stdout.columns, {\n\t\t\thard: true,\n\t\t\ttrim: false,\n\t\t});\n\t\tif (frame === this._prevFrame) return;\n\n\t\tif (this.state === 'initial') {\n\t\t\tthis.output.write(cursor.hide);\n\t\t} else {\n\t\t\tconst diff = diffLines(this._prevFrame, frame);\n\t\t\tconst rows = getRows(this.output);\n\t\t\tthis.restoreCursor();\n\t\t\tif (diff) {\n\t\t\t\tconst diffOffsetAfter = Math.max(0, diff.numLinesAfter - rows);\n\t\t\t\tconst diffOffsetBefore = Math.max(0, diff.numLinesBefore - rows);\n\t\t\t\tlet diffLine = diff.lines.find((line) => line >= diffOffsetAfter);\n\n\t\t\t\tif (diffLine === undefined) {\n\t\t\t\t\tthis._prevFrame = frame;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// If a single line has changed, only update that line\n\t\t\t\tif (diff.lines.length === 1) {\n\t\t\t\t\tthis.output.write(cursor.move(0, diffLine - diffOffsetBefore));\n\t\t\t\t\tthis.output.write(erase.lines(1));\n\t\t\t\t\tconst lines = frame.split('\\n');\n\t\t\t\t\tthis.output.write(lines[diffLine]);\n\t\t\t\t\tthis._prevFrame = frame;\n\t\t\t\t\tthis.output.write(cursor.move(0, lines.length - diffLine - 1));\n\t\t\t\t\treturn;\n\t\t\t\t\t// If many lines have changed, rerender everything past the first line\n\t\t\t\t} else if (diff.lines.length > 1) {\n\t\t\t\t\tif (diffOffsetAfter < diffOffsetBefore) {\n\t\t\t\t\t\tdiffLine = diffOffsetAfter;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst adjustedDiffLine = diffLine - diffOffsetBefore;\n\t\t\t\t\t\tif (adjustedDiffLine > 0) {\n\t\t\t\t\t\t\tthis.output.write(cursor.move(0, adjustedDiffLine));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tthis.output.write(erase.down());\n\t\t\t\t\tconst lines = frame.split('\\n');\n\t\t\t\t\tconst newLines = lines.slice(diffLine);\n\t\t\t\t\tthis.output.write(newLines.join('\\n'));\n\t\t\t\t\tthis._prevFrame = frame;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.output.write(erase.down());\n\t\t}\n\n\t\tthis.output.write(frame);\n\t\tif (this.state === 'initial') {\n\t\t\tthis.state = 'active';\n\t\t}\n\t\tthis._prevFrame = frame;\n\t}\n}\n","import type { Key } from 'node:readline';\nimport { styleText } from 'node:util';\nimport { findCursor } from '../utils/cursor.js';\nimport Prompt, { type PromptOptions } from './prompt.js';\n\ninterface OptionLike {\n\tvalue: unknown;\n\tlabel?: string;\n\tdisabled?: boolean;\n}\n\ntype FilterFunction<T extends OptionLike> = (search: string, opt: T) => boolean;\n\nfunction getCursorForValue<T extends OptionLike>(\n\tselected: T['value'] | undefined,\n\titems: T[]\n): number {\n\tif (selected === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst currLength = items.length;\n\n\t// If filtering changed the available options, update cursor\n\tif (currLength === 0) {\n\t\treturn 0;\n\t}\n\n\t// Try to maintain the same selected item\n\tconst index = items.findIndex((item) => item.value === selected);\n\treturn index !== -1 ? index : 0;\n}\n\nfunction defaultFilter<T extends OptionLike>(input: string, option: T): boolean {\n\tconst label = option.label ?? String(option.value);\n\treturn label.toLowerCase().includes(input.toLowerCase());\n}\n\nfunction normalisedValue<T>(multiple: boolean, values: T[] | undefined): T | T[] | undefined {\n\tif (!values) {\n\t\treturn undefined;\n\t}\n\tif (multiple) {\n\t\treturn values;\n\t}\n\treturn values[0];\n}\n\nexport interface AutocompleteOptions<T extends OptionLike>\n\textends PromptOptions<T['value'] | T['value'][], AutocompletePrompt<T>> {\n\toptions: T[] | ((this: AutocompletePrompt<T>) => T[]);\n\tfilter?: FilterFunction<T>;\n\tmultiple?: boolean;\n\t/**\n\t * When set (non-empty), pressing Tab with no input fills the field with this value\n\t * and runs the normal filter/selection logic so the user can confirm with Enter.\n\t * Tab only fills the input when the placeholder matches at least one option under\n\t * the prompt's filter (so the value remains selectable).\n\t */\n\tplaceholder?: string;\n}\n\nexport default class AutocompletePrompt<T extends OptionLike> extends Prompt<\n\tT['value'] | T['value'][]\n> {\n\tfilteredOptions: T[];\n\tmultiple: boolean;\n\tisNavigating = false;\n\tselectedValues: Array<T['value']> = [];\n\n\tfocusedValue: T['value'] | undefined;\n\t#cursor = 0;\n\t#lastUserInput = '';\n\t#filterFn: FilterFunction<T> | undefined;\n\t#options: T[] | (() => T[]);\n\t#placeholder: string | undefined;\n\n\tget cursor(): number {\n\t\treturn this.#cursor;\n\t}\n\n\tget userInputWithCursor() {\n\t\tif (!this.userInput) {\n\t\t\treturn styleText(['inverse', 'hidden'], '_');\n\t\t}\n\t\tif (this._cursor >= this.userInput.length) {\n\t\t\treturn `${this.userInput}█`;\n\t\t}\n\t\tconst s1 = this.userInput.slice(0, this._cursor);\n\t\tconst [s2, ...s3] = this.userInput.slice(this._cursor);\n\t\treturn `${s1}${styleText('inverse', s2)}${s3.join('')}`;\n\t}\n\n\tget options(): T[] {\n\t\tif (typeof this.#options === 'function') {\n\t\t\treturn this.#options();\n\t\t}\n\t\treturn this.#options;\n\t}\n\n\tconstructor(opts: AutocompleteOptions<T>) {\n\t\tsuper(opts);\n\n\t\tthis.#options = opts.options;\n\t\tthis.#placeholder = opts.placeholder;\n\t\tconst options = this.options;\n\t\tthis.filteredOptions = [...options];\n\t\tthis.multiple = opts.multiple === true;\n\t\tthis.#filterFn =\n\t\t\ttypeof opts.options === 'function' ? opts.filter : (opts.filter ?? defaultFilter);\n\t\tlet initialValues: unknown[] | undefined;\n\t\tif (opts.initialValue && Array.isArray(opts.initialValue)) {\n\t\t\tif (this.multiple) {\n\t\t\t\tinitialValues = opts.initialValue;\n\t\t\t} else {\n\t\t\t\tinitialValues = opts.initialValue.slice(0, 1);\n\t\t\t}\n\t\t} else {\n\t\t\tif (!this.multiple && this.options.length > 0) {\n\t\t\t\tinitialValues = [this.options[0].value];\n\t\t\t}\n\t\t}\n\n\t\tif (initialValues) {\n\t\t\tfor (const selectedValue of initialValues) {\n\t\t\t\tconst selectedIndex = options.findIndex((opt) => opt.value === selectedValue);\n\t\t\t\tif (selectedIndex !== -1) {\n\t\t\t\t\tthis.toggleSelected(selectedValue);\n\t\t\t\t\tthis.#cursor = selectedIndex;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.focusedValue = this.options[this.#cursor]?.value;\n\n\t\tthis.on('key', (char, key) => this.#onKey(char, key));\n\t\tthis.on('userInput', (value) => this.#onUserInputChanged(value));\n\t}\n\n\tprotected override _isActionKey(char: string | undefined, key: Key): boolean {\n\t\treturn (\n\t\t\tchar === '\\t' ||\n\t\t\t(this.multiple &&\n\t\t\t\tthis.isNavigating &&\n\t\t\t\tkey.name === 'space' &&\n\t\t\t\tchar !== undefined &&\n\t\t\t\tchar !== '')\n\t\t);\n\t}\n\n\t#onKey(_char: string | undefined, key: Key): void {\n\t\tconst isUpKey = key.name === 'up';\n\t\tconst isDownKey = key.name === 'down';\n\t\tconst isReturnKey = key.name === 'return';\n\n\t\t// Tab with empty input and placeholder: fill input with placeholder to trigger autocomplete\n\t\t// Only when the placeholder matches at least one (non-disabled) option so the value remains selectable\n\t\tconst isEmptyOrOnlyTab = this.userInput === '' || this.userInput === '\\t';\n\t\tconst placeholder = this.#placeholder;\n\t\tconst options = this.options;\n\t\tconst placeholderMatchesOption =\n\t\t\tplaceholder !== undefined &&\n\t\t\tplaceholder !== '' &&\n\t\t\toptions.some(\n\t\t\t\t(opt) => !opt.disabled && (this.#filterFn ? this.#filterFn(placeholder, opt) : true)\n\t\t\t);\n\t\tif (key.name === 'tab' && isEmptyOrOnlyTab && placeholderMatchesOption) {\n\t\t\tif (this.userInput === '\\t') {\n\t\t\t\tthis._clearUserInput();\n\t\t\t}\n\t\t\tthis._setUserInput(placeholder, true);\n\t\t\tthis.isNavigating = false;\n\t\t\treturn;\n\t\t}\n\n\t\t// Start navigation mode with up/down arrows\n\t\tif (isUpKey || isDownKey) {\n\t\t\tthis.#cursor = findCursor(this.#cursor, isUpKey ? -1 : 1, this.filteredOptions);\n\t\t\tthis.focusedValue = this.filteredOptions[this.#cursor]?.value;\n\t\t\tif (!this.multiple) {\n\t\t\t\tthis.selectedValues = [this.focusedValue];\n\t\t\t}\n\t\t\tthis.isNavigating = true;\n\t\t} else if (isReturnKey) {\n\t\t\tthis.value = normalisedValue(this.multiple, this.selectedValues);\n\t\t} else {\n\t\t\tif (this.multiple) {\n\t\t\t\tif (\n\t\t\t\t\tthis.focusedValue !== undefined &&\n\t\t\t\t\t(key.name === 'tab' || (this.isNavigating && key.name === 'space'))\n\t\t\t\t) {\n\t\t\t\t\tthis.toggleSelected(this.focusedValue);\n\t\t\t\t} else {\n\t\t\t\t\tthis.isNavigating = false;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (this.focusedValue) {\n\t\t\t\t\tthis.selectedValues = [this.focusedValue];\n\t\t\t\t}\n\t\t\t\tthis.isNavigating = false;\n\t\t\t}\n\t\t}\n\t}\n\n\tdeselectAll() {\n\t\tthis.selectedValues = [];\n\t}\n\n\ttoggleSelected(value: T['value']) {\n\t\tif (this.filteredOptions.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.multiple) {\n\t\t\tif (this.selectedValues.includes(value)) {\n\t\t\t\tthis.selectedValues = this.selectedValues.filter((v) => v !== value);\n\t\t\t} else {\n\t\t\t\tthis.selectedValues = [...this.selectedValues, value];\n\t\t\t}\n\t\t} else {\n\t\t\tthis.selectedValues = [value];\n\t\t}\n\t}\n\n\t#onUserInputChanged(value: string): void {\n\t\tif (value !== this.#lastUserInput) {\n\t\t\tthis.#lastUserInput = value;\n\n\t\t\tconst options = this.options;\n\n\t\t\tif (value && this.#filterFn) {\n\t\t\t\tthis.filteredOptions = options.filter((opt) => this.#filterFn?.(value, opt));\n\t\t\t} else {\n\t\t\t\tthis.filteredOptions = [...options];\n\t\t\t}\n\t\t\tconst valueCursor = getCursorForValue(this.focusedValue, this.filteredOptions);\n\t\t\tthis.#cursor = findCursor(valueCursor, 0, this.filteredOptions);\n\t\t\tconst focusedOption = this.filteredOptions[this.#cursor];\n\t\t\tif (focusedOption && !focusedOption.disabled) {\n\t\t\t\tthis.focusedValue = focusedOption.value;\n\t\t\t} else {\n\t\t\t\tthis.focusedValue = undefined;\n\t\t\t}\n\t\t\tif (!this.multiple) {\n\t\t\t\tif (this.focusedValue !== undefined) {\n\t\t\t\t\tthis.toggleSelected(this.focusedValue);\n\t\t\t\t} else {\n\t\t\t\t\tthis.deselectAll();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n","import { cursor } from 'sisteransi';\nimport Prompt, { type PromptOptions } from './prompt.js';\n\nexport interface ConfirmOptions extends PromptOptions<boolean, ConfirmPrompt> {\n\tactive: string;\n\tinactive: string;\n\tinitialValue?: boolean;\n}\n\nexport default class ConfirmPrompt extends Prompt<boolean> {\n\tget cursor() {\n\t\treturn this.value ? 0 : 1;\n\t}\n\n\tprivate get _value() {\n\t\treturn this.cursor === 0;\n\t}\n\n\tconstructor(opts: ConfirmOptions) {\n\t\tsuper(opts, false);\n\t\tthis.value = !!opts.initialValue;\n\n\t\tthis.on('userInput', () => {\n\t\t\tthis.value = this._value;\n\t\t});\n\n\t\tthis.on('confirm', (confirm) => {\n\t\t\tthis.output.write(cursor.move(0, -1));\n\t\t\tthis.value = confirm;\n\t\t\tthis.state = 'submit';\n\t\t\tthis.close();\n\t\t});\n\n\t\tthis.on('cursor', () => {\n\t\t\tthis.value = !this.value;\n\t\t});\n\t}\n}\n","import type { Key } from 'node:readline';\nimport { settings } from '../utils/settings.js';\nimport Prompt, { type PromptOptions } from './prompt.js';\n\ninterface SegmentConfig {\n\ttype: 'year' | 'month' | 'day';\n\tlen: number;\n}\n\nexport interface DateParts {\n\tyear: string;\n\tmonth: string;\n\tday: string;\n}\n\nexport type DateFormat = 'YMD' | 'MDY' | 'DMY';\n\nconst SEGMENTS: Record<string, SegmentConfig> = {\n\tY: { type: 'year', len: 4 },\n\tM: { type: 'month', len: 2 },\n\tD: { type: 'day', len: 2 },\n} as const;\n\nfunction segmentsFor(fmt: DateFormat): SegmentConfig[] {\n\treturn [...fmt].map((c) => SEGMENTS[c as keyof typeof SEGMENTS]);\n}\n\nfunction detectLocaleFormat(locale?: string): { segments: SegmentConfig[]; separator: string } {\n\tconst fmt = new Intl.DateTimeFormat(locale, {\n\t\tyear: 'numeric',\n\t\tmonth: '2-digit',\n\t\tday: '2-digit',\n\t});\n\tconst parts = fmt.formatToParts(new Date(2000, 0, 15));\n\tconst segments: SegmentConfig[] = [];\n\tlet separator = '/';\n\tfor (const p of parts) {\n\t\tif (p.type === 'literal') {\n\t\t\tseparator = p.value.trim() || p.value;\n\t\t} else if (p.type === 'year' || p.type === 'month' || p.type === 'day') {\n\t\t\tsegments.push({ type: p.type, len: p.type === 'year' ? 4 : 2 });\n\t\t}\n\t}\n\treturn { segments, separator };\n}\n\n/** Parse string segment values to numbers, treating blanks as 0 */\nfunction parseSegmentToNum(s: string): number {\n\treturn Number.parseInt((s || '0').replace(/_/g, '0'), 10) || 0;\n}\n\nfunction parse(parts: DateParts): { year: number; month: number; day: number } {\n\treturn {\n\t\tyear: parseSegmentToNum(parts.year),\n\t\tmonth: parseSegmentToNum(parts.month),\n\t\tday: parseSegmentToNum(parts.day),\n\t};\n}\n\nfunction daysInMonth(year: number, month: number): number {\n\treturn new Date(year || 2001, month || 1, 0).getDate();\n}\n\n/** Validate and return calendar parts, or undefined if invalid */\nfunction validParts(parts: DateParts): { year: number; month: number; day: number } | undefined {\n\tconst { year, month, day } = parse(parts);\n\tif (!year || year < 0 || year > 9999) return undefined;\n\tif (!month || month < 1 || month > 12) return undefined;\n\tif (!day || day < 1) return undefined;\n\tconst d = new Date(Date.UTC(year, month - 1, day));\n\tif (d.getUTCFullYear() !== year || d.getUTCMonth() !== month - 1 || d.getUTCDate() !== day)\n\t\treturn undefined;\n\treturn { year, month, day };\n}\n\nfunction toDate(parts: DateParts): Date | undefined {\n\tconst p = validParts(parts);\n\treturn p ? new Date(Date.UTC(p.year, p.month - 1, p.day)) : undefined;\n}\n\nfunction segmentBounds(\n\ttype: 'year' | 'month' | 'day',\n\tctx: { year: number; month: number },\n\tminDate: Date | undefined,\n\tmaxDate: Date | undefined\n): { min: number; max: number } {\n\tconst minP = minDate\n\t\t? {\n\t\t\t\tyear: minDate.getUTCFullYear(),\n\t\t\t\tmonth: minDate.getUTCMonth() + 1,\n\t\t\t\tday: minDate.getUTCDate(),\n\t\t\t}\n\t\t: null;\n\tconst maxP = maxDate\n\t\t? {\n\t\t\t\tyear: maxDate.getUTCFullYear(),\n\t\t\t\tmonth: maxDate.getUTCMonth() + 1,\n\t\t\t\tday: maxDate.getUTCDate(),\n\t\t\t}\n\t\t: null;\n\n\tif (type === 'year') {\n\t\treturn { min: minP?.year ?? 1, max: maxP?.year ?? 9999 };\n\t}\n\tif (type === 'month') {\n\t\treturn {\n\t\t\tmin: minP && ctx.year === minP.year ? minP.month : 1,\n\t\t\tmax: maxP && ctx.year === maxP.year ? maxP.month : 12,\n\t\t};\n\t}\n\treturn {\n\t\tmin: minP && ctx.year === minP.year && ctx.month === minP.month ? minP.day : 1,\n\t\tmax:\n\t\t\tmaxP && ctx.year === maxP.year && ctx.month === maxP.month\n\t\t\t\t? maxP.day\n\t\t\t\t: daysInMonth(ctx.year, ctx.month),\n\t};\n}\n\nexport interface DateOptions extends PromptOptions<Date, DatePrompt> {\n\tformat?: DateFormat;\n\tlocale?: string;\n\tseparator?: string;\n\tdefaultValue?: Date;\n\tinitialValue?: Date;\n\tminDate?: Date;\n\tmaxDate?: Date;\n}\n\nexport default class DatePrompt extends Prompt<Date> {\n\t#segments: SegmentConfig[];\n\t#separator: string;\n\t#segmentValues: DateParts;\n\t#minDate: Date | undefined;\n\t#maxDate: Date | undefined;\n\t#cursor = { segmentIndex: 0, positionInSegment: 0 };\n\t#segmentSelected = true;\n\t#pendingTensDigit: string | null = null;\n\n\tinlineError = '';\n\n\tget segmentCursor() {\n\t\treturn { ...this.#cursor };\n\t}\n\n\tget segmentValues(): DateParts {\n\t\treturn { ...this.#segmentValues };\n\t}\n\n\tget segments(): readonly SegmentConfig[] {\n\t\treturn this.#segments;\n\t}\n\n\tget separator(): string {\n\t\treturn this.#separator;\n\t}\n\n\tget formattedValue(): string {\n\t\treturn this.#format(this.#segmentValues);\n\t}\n\n\t#format(parts: DateParts): string {\n\t\treturn this.#segments.map((s) => parts[s.type]).join(this.#separator);\n\t}\n\n\t#refresh() {\n\t\tthis._setUserInput(this.#format(this.#segmentValues));\n\t\tthis._setValue(toDate(this.#segmentValues) ?? undefined);\n\t}\n\n\tconstructor(opts: DateOptions) {\n\t\tconst detected = opts.format\n\t\t\t? { segments: segmentsFor(opts.format), separator: opts.separator ?? '/' }\n\t\t\t: detectLocaleFormat(opts.locale);\n\t\tconst sep = opts.separator ?? detected.separator;\n\t\tconst segments = opts.format ? segmentsFor(opts.format) : detected.segments;\n\n\t\tconst initialDate = opts.initialValue ?? opts.defaultValue;\n\t\tconst segmentValues: DateParts = initialDate\n\t\t\t? {\n\t\t\t\t\tyear: String(initialDate.getUTCFullYear()).padStart(4, '0'),\n\t\t\t\t\tmonth: String(initialDate.getUTCMonth() + 1).padStart(2, '0'),\n\t\t\t\t\tday: String(initialDate.getUTCDate()).padStart(2, '0'),\n\t\t\t\t}\n\t\t\t: { year: '____', month: '__', day: '__' };\n\n\t\tconst initialDisplay = segments.map((s) => segmentValues[s.type]).join(sep);\n\n\t\tsuper({ ...opts, initialUserInput: initialDisplay }, false);\n\t\tthis.#segments = segments;\n\t\tthis.#separator = sep;\n\t\tthis.#segmentValues = segmentValues;\n\t\tthis.#minDate = opts.minDate;\n\t\tthis.#maxDate = opts.maxDate;\n\t\tthis.#refresh();\n\n\t\tthis.on('cursor', (key) => this.#onCursor(key));\n\t\tthis.on('key', (char, key) => this.#onKey(char, key));\n\t\tthis.on('finalize', () => this.#onFinalize(opts));\n\t}\n\n\t#seg(): { segment: SegmentConfig; index: number } | undefined {\n\t\tconst index = Math.max(0, Math.min(this.#cursor.segmentIndex, this.#segments.length - 1));\n\t\tconst segment = this.#segments[index];\n\t\tif (!segment) return undefined;\n\t\tthis.#cursor.positionInSegment = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.#cursor.positionInSegment, segment.len - 1)\n\t\t);\n\t\treturn { segment, index };\n\t}\n\n\t#navigate(direction: 1 | -1) {\n\t\tthis.inlineError = '';\n\t\tthis.#pendingTensDigit = null;\n\t\tconst ctx = this.#seg();\n\t\tif (!ctx) return;\n\t\tthis.#cursor.segmentIndex = Math.max(\n\t\t\t0,\n\t\t\tMath.min(this.#segments.length - 1, ctx.index + direction)\n\t\t);\n\t\tthis.#cursor.positionInSegment = 0;\n\t\tthis.#segmentSelected = true;\n\t}\n\n\t#adjust(direction: 1 | -1) {\n\t\tconst ctx = this.#seg();\n\t\tif (!ctx) return;\n\t\tconst { segment } = ctx;\n\t\tconst raw = this.#segmentValues[segment.type];\n\t\tconst isBlank = !raw || raw.replace(/_/g, '') === '';\n\t\tconst num = Number.parseInt((raw || '0').replace(/_/g, '0'), 10) || 0;\n\t\tconst bounds = segmentBounds(\n\t\t\tsegment.type,\n\t\t\tparse(this.#segmentValues),\n\t\t\tthis.#minDate,\n\t\t\tthis.#maxDate\n\t\t);\n\n\t\tlet next: number;\n\t\tif (isBlank) {\n\t\t\tnext = direction === 1 ? bounds.min : bounds.max;\n\t\t} else {\n\t\t\tnext = Math.max(Math.min(bounds.max, num + direction), bounds.min);\n\t\t}\n\n\t\tthis.#segmentValues = {\n\t\t\t...this.#segmentValues,\n\t\t\t[segment.type]: next.toString().padStart(segment.len, '0'),\n\t\t};\n\t\tthis.#segmentSelected = true;\n\t\tthis.#pendingTensDigit = null;\n\t\tthis.#refresh();\n\t}\n\n\t#onCursor(key?: string) {\n\t\tif (!key) return;\n\t\tswitch (key) {\n\t\t\tcase 'right':\n\t\t\t\treturn this.#navigate(1);\n\t\t\tcase 'left':\n\t\t\t\treturn this.#navigate(-1);\n\t\t\tcase 'up':\n\t\t\t\treturn this.#adjust(1);\n\t\t\tcase 'down':\n\t\t\t\treturn this.#adjust(-1);\n\t\t}\n\t}\n\n\t#onKey(char: string | undefined, key: Key) {\n\t\t// Backspace\n\t\tconst isBackspace =\n\t\t\tkey?.name === 'backspace' ||\n\t\t\tkey?.sequence === '\\x7f' ||\n\t\t\tkey?.sequence === '\\b' ||\n\t\t\tchar === '\\x7f' ||\n\t\t\tchar === '\\b';\n\t\tif (isBackspace) {\n\t\t\tthis.inlineError = '';\n\t\t\tconst ctx = this.#seg();\n\t\t\tif (!ctx) return;\n\t\t\tif (!this.#segmentValues[ctx.segment.type].replace(/_/g, '')) {\n\t\t\t\tthis.#navigate(-1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.#segmentValues[ctx.segment.type] = '_'.repeat(ctx.segment.len);\n\t\t\tthis.#segmentSelected = true;\n\t\t\tthis.#cursor.positionInSegment = 0;\n\t\t\tthis.#refresh();\n\t\t\treturn;\n\t\t}\n\n\t\t// Tab navigation\n\t\tif (key?.name === 'tab') {\n\t\t\tthis.inlineError = '';\n\t\t\tconst ctx = this.#seg();\n\t\t\tif (!ctx) return;\n\t\t\tconst dir = key.shift ? -1 : 1;\n\t\t\tconst next = ctx.index + dir;\n\t\t\tif (next >= 0 && next < this.#segments.length) {\n\t\t\t\tthis.#cursor.segmentIndex = next;\n\t\t\t\tthis.#cursor.positionInSegment = 0;\n\t\t\t\tthis.#segmentSelected = true;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Digit input\n\t\tif (char && /^[0-9]$/.test(char)) {\n\t\t\tconst ctx = this.#seg();\n\t\t\tif (!ctx) return;\n\t\t\tconst { segment } = ctx;\n\t\t\tconst isBlank = !this.#segmentValues[segment.type].replace(/_/g, '');\n\n\t\t\t// Pending tens digit: complete the two-digit entry\n\t\t\tif (this.#segmentSelected && this.#pendingTensDigit !== null && !isBlank) {\n\t\t\t\tconst newVal = this.#pendingTensDigit + char;\n\t\t\t\tconst newParts = { ...this.#segmentValues, [segment.type]: newVal };\n\t\t\t\tconst err = this.#validateSegment(newParts, segment);\n\t\t\t\tif (err) {\n\t\t\t\t\tthis.inlineError = err;\n\t\t\t\t\tthis.#pendingTensDigit = null;\n\t\t\t\t\tthis.#segmentSelected = false;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.inlineError = '';\n\t\t\t\tthis.#segmentValues[segment.type] = newVal;\n\t\t\t\tthis.#pendingTensDigit = null;\n\t\t\t\tthis.#segmentSelected = false;\n\t\t\t\tthis.#refresh();\n\t\t\t\tif (ctx.index < this.#segments.length - 1) {\n\t\t\t\t\tthis.#cursor.segmentIndex = ctx.index + 1;\n\t\t\t\t\tthis.#cursor.positionInSegment = 0;\n\t\t\t\t\tthis.#segmentSelected = true;\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Clear-on-type: typing into a selected filled segment clears it first\n\t\t\tif (this.#segmentSelected && !isBlank) {\n\t\t\t\tthis.#segmentValues[segment.type] = '_'.repeat(segment.len);\n\t\t\t\tthis.#cursor.positionInSegment = 0;\n\t\t\t}\n\t\t\tthis.#segmentSelected = false;\n\t\t\tthis.#pendingTensDigit = null;\n\n\t\t\tconst display = this.#segmentValues[segment.type];\n\t\t\tconst firstBlank = display.indexOf('_');\n\t\t\tconst pos =\n\t\t\t\tfirstBlank >= 0 ? firstBlank : Math.min(this.#cursor.positionInSegment, segment.len - 1);\n\t\t\tif (pos < 0 || pos >= segment.len) return;\n\n\t\t\tlet newVal = display.slice(0, pos) + char + display.slice(pos + 1);\n\n\t\t\t// Smart digit placement\n\t\t\tlet shouldStaySelected = false;\n\t\t\tif (pos === 0 && display === '__' && (segment.type === 'month' || segment.type === 'day')) {\n\t\t\t\tconst digit = Number.parseInt(char, 10);\n\t\t\t\tnewVal = `0${char}`;\n\t\t\t\tshouldStaySelected = digit <= (segment.type === 'month' ? 1 : 2);\n\t\t\t}\n\t\t\tif (segment.type === 'year') {\n\t\t\t\tconst digits = display.replace(/_/g, '');\n\t\t\t\tnewVal = (digits + char).padStart(segment.len, '_');\n\t\t\t}\n\n\t\t\tif (!newVal.includes('_')) {\n\t\t\t\tconst newParts = { ...this.#segmentValues, [segment.type]: newVal };\n\t\t\t\tconst err = this.#validateSegment(newParts, segment);\n\t\t\t\tif (err) {\n\t\t\t\t\tthis.inlineError = err;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.inlineError = '';\n\n\t\t\tthis.#segmentValues[segment.type] = newVal;\n\n\t\t\t// Clamp only when the current segment is fully entered\n\t\t\tconst parsed = !newVal.includes('_') ? validParts(this.#segmentValues) : undefined;\n\t\t\tif (parsed) {\n\t\t\t\tconst { year, month } = parsed;\n\t\t\t\tconst maxDay = daysInMonth(year, month);\n\t\t\t\tthis.#segmentValues = {\n\t\t\t\t\tyear: String(Math.max(0, Math.min(9999, year))).padStart(4, '0'),\n\t\t\t\t\tmonth: String(Math.max(1, Math.min(12, month))).padStart(2, '0'),\n\t\t\t\t\tday: String(Math.max(1, Math.min(maxDay, parsed.day))).padStart(2, '0'),\n\t\t\t\t};\n\t\t\t}\n\t\t\tthis.#refresh();\n\n\t\t\t// Advance cursor\n\t\t\tconst nextBlank = newVal.indexOf('_');\n\t\t\tif (shouldStaySelected) {\n\t\t\t\tthis.#segmentSelected = true;\n\t\t\t\tthis.#pendingTensDigit = char;\n\t\t\t} else if (nextBlank >= 0) {\n\t\t\t\tthis.#cursor.positionInSegment = nextBlank;\n\t\t\t} else if (firstBlank >= 0 && ctx.index < this.#segments.length - 1) {\n\t\t\t\tthis.#cursor.segmentIndex = ctx.index + 1;\n\t\t\t\tthis.#cursor.positionInSegment = 0;\n\t\t\t\tthis.#segmentSelected = true;\n\t\t\t} else {\n\t\t\t\tthis.#cursor.positionInSegment = Math.min(pos + 1, segment.len - 1);\n\t\t\t}\n\t\t}\n\t}\n\n\t#validateSegment(parts: DateParts, seg: SegmentConfig): string | undefined {\n\t\tconst { month, day } = parse(parts);\n\t\tif (seg.type === 'month' && (month < 0 || month > 12)) {\n\t\t\treturn settings.date.messages.invalidMonth;\n\t\t}\n\t\tif (seg.type === 'day' && (day < 0 || day > 31)) {\n\t\t\treturn settings.date.messages.invalidDay(31, 'any month');\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t#onFinalize(opts: DateOptions) {\n\t\tconst { year, month, day } = parse(this.#segmentValues);\n\t\tif (year && month && day) {\n\t\t\tconst maxDay = daysInMonth(year, month);\n\t\t\tthis.#segmentValues = {\n\t\t\t\t...this.#segmentValues,\n\t\t\t\tday: String(Math.min(day, maxDay)).padStart(2, '0'),\n\t\t\t};\n\t\t}\n\t\tthis.value = toDate(this.#segmentValues) ?? opts.defaultValue ?? undefined;\n\t}\n}\n","import Prompt, { type PromptOptions } from './prompt.js';\n\nexport interface GroupMultiSelectOptions<T extends { value: any }>\n\textends PromptOptions<T['value'][], GroupMultiSelectPrompt<T>> {\n\toptions: Record<string, T[]>;\n\tinitialValues?: T['value'][];\n\trequired?: boolean;\n\tcursorAt?: T['value'];\n\tselectableGroups?: boolean;\n}\nexport default class GroupMultiSelectPrompt<T extends { value: any }> extends Prompt<T['value'][]> {\n\toptions: (T & { group: string | boolean })[];\n\tcursor = 0;\n\t#selectableGroups: boolean;\n\n\tgetGroupItems(group: string): T[] {\n\t\treturn this.options.filter((o) => o.group === group);\n\t}\n\n\tisGroupSelected(group: string) {\n\t\tconst items = this.getGroupItems(group);\n\t\tconst value = this.value;\n\t\tif (value === undefined) {\n\t\t\treturn false;\n\t\t}\n\t\treturn items.every((i) => value.includes(i.value));\n\t}\n\n\tprivate toggleValue() {\n\t\tconst item = this.options[this.cursor];\n\t\tif (this.value === undefined) {\n\t\t\tthis.value = [];\n\t\t}\n\t\tif (item.group === true) {\n\t\t\tconst group = item.value;\n\t\t\tconst groupedItems = this.getGroupItems(group);\n\t\t\tif (this.isGroupSelected(group)) {\n\t\t\t\tthis.value = this.value.filter(\n\t\t\t\t\t(v: string) => groupedItems.findIndex((i) => i.value === v) === -1\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthis.value = [...this.value, ...groupedItems.map((i) => i.value)];\n\t\t\t}\n\t\t\tthis.value = Array.from(new Set(this.value));\n\t\t} else {\n\t\t\tconst selected = this.value.includes(item.value);\n\t\t\tthis.value = selected\n\t\t\t\t? this.value.filter((v: T['value']) => v !== item.value)\n\t\t\t\t: [...this.value, item.value];\n\t\t}\n\t}\n\n\tconstructor(opts: GroupMultiSelectOptions<T>) {\n\t\tsuper(opts, false);\n\t\tconst { options } = opts;\n\t\tthis.#selectableGroups = opts.selectableGroups !== false;\n\t\tthis.options = Object.entries(options).flatMap(([key, option]) => [\n\t\t\t{ value: key, group: true, label: key },\n\t\t\t...option.map((opt) => ({ ...opt, group: key })),\n\t\t]) as any;\n\t\tthis.value = [...(opts.initialValues ?? [])];\n\t\tthis.cursor = Math.max(\n\t\t\tthis.options.findIndex(({ value }) => value === opts.cursorAt),\n\t\t\tthis.#selectableGroups ? 0 : 1\n\t\t);\n\n\t\tthis.on('cursor', (key) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'up': {\n\t\t\t\t\tthis.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;\n\t\t\t\t\tconst currentIsGroup = this.options[this.cursor]?.group === true;\n\t\t\t\t\tif (!this.#selectableGroups && currentIsGroup) {\n\t\t\t\t\t\tthis.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'down':\n\t\t\t\tcase 'right': {\n\t\t\t\t\tthis.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;\n\t\t\t\t\tconst currentIsGroup = this.options[this.cursor]?.group === true;\n\t\t\t\t\tif (!this.#selectableGroups && currentIsGroup) {\n\t\t\t\t\t\tthis.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase 'space':\n\t\t\t\t\tthis.toggleValue();\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t}\n}\n","import type { Key } from 'node:readline';\nimport { styleText } from 'node:util';\nimport { findTextCursor } from '../utils/cursor.js';\nimport { type Action, settings } from '../utils/index.js';\nimport Prompt, { type PromptOptions } from './prompt.js';\n\nexport interface MultiLineOptions extends PromptOptions<string, MultiLinePrompt> {\n\tplaceholder?: string;\n\tdefaultValue?: string;\n\tshowSubmit?: boolean;\n}\n\nexport default class MultiLinePrompt extends Prompt<string> {\n\t#lastKeyWasReturn = false;\n\t#showSubmit: boolean;\n\tpublic focused: 'editor' | 'submit' = 'editor';\n\n\tget userInputWithCursor() {\n\t\tif (this.state === 'submit') {\n\t\t\treturn this.userInput;\n\t\t}\n\t\tconst userInput = this.userInput;\n\t\tif (this.cursor >= userInput.length) {\n\t\t\treturn `${userInput}█`;\n\t\t}\n\t\tconst s1 = userInput.slice(0, this.cursor);\n\t\tconst s2 = userInput[this.cursor];\n\t\tconst s3 = userInput.slice(this.cursor + 1);\n\t\tif (s2 === '\\n') return `${s1}█\\n${s3}`;\n\t\treturn `${s1}${styleText('inverse', s2)}${s3}`;\n\t}\n\tget cursor() {\n\t\treturn this._cursor;\n\t}\n\t#insertAtCursor(char: string) {\n\t\tif (this.userInput.length === 0) {\n\t\t\tthis._setUserInput(char);\n\t\t\treturn;\n\t\t}\n\t\tthis._setUserInput(\n\t\t\tthis.userInput.slice(0, this.cursor) + char + this.userInput.slice(this.cursor)\n\t\t);\n\t}\n\t#handleCursor(key?: Action) {\n\t\tconst text = this.value ?? '';\n\t\tswitch (key) {\n\t\t\tcase 'up':\n\t\t\t\tthis._cursor = findTextCursor(this._cursor, 0, -1, text);\n\t\t\t\treturn;\n\t\t\tcase 'down':\n\t\t\t\tthis._cursor = findTextCursor(this._cursor, 0, 1, text);\n\t\t\t\treturn;\n\t\t\tcase 'left':\n\t\t\t\tthis._cursor = findTextCursor(this._cursor, -1, 0, text);\n\t\t\t\treturn;\n\t\t\tcase 'right':\n\t\t\t\tthis._cursor = findTextCursor(this._cursor, 1, 0, text);\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\tprotected override _shouldSubmit(_char: string | undefined, _key: Key): boolean {\n\t\tif (this.#showSubmit) {\n\t\t\tif (this.focused === 'submit') {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tthis.#insertAtCursor('\\n');\n\t\t\tthis._cursor++;\n\t\t\treturn false;\n\t\t}\n\t\tconst wasReturn = this.#lastKeyWasReturn;\n\t\tthis.#lastKeyWasReturn = true;\n\t\tif (wasReturn) {\n\t\t\tif (this.userInput[this.cursor - 1] === '\\n') {\n\t\t\t\tthis._setUserInput(\n\t\t\t\t\tthis.userInput.slice(0, this.cursor - 1) + this.userInput.slice(this.cursor)\n\t\t\t\t);\n\t\t\t\tthis._cursor--;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tthis.#insertAtCursor('\\n');\n\t\tthis._cursor++;\n\t\treturn false;\n\t}\n\n\tconstructor(opts: MultiLineOptions) {\n\t\tsuper(opts, false);\n\t\tthis.#showSubmit = opts.showSubmit ?? false;\n\n\t\tthis.on('key', (char, key) => {\n\t\t\tif (key?.name && settings.actions.has(key.name as Action)) {\n\t\t\t\tthis.#handleCursor(key.name as Action);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (char === '\\t' && this.#showSubmit) {\n\t\t\t\tthis.focused = this.focused === 'editor' ? 'submit' : 'editor';\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (key?.name === 'return') {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.#lastKeyWasReturn = false;\n\t\t\tif (key?.name === 'backspace' && this.cursor > 0) {\n\t\t\t\tthis._setUserInput(\n\t\t\t\t\tthis.userInput.slice(0, this.cursor - 1) + this.userInput.slice(this.cursor)\n\t\t\t\t);\n\t\t\t\tthis._cursor--;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (key?.name === 'delete' && this.cursor < this.userInput.length) {\n\t\t\t\tthis._setUserInput(\n\t\t\t\t\tthis.userInput.slice(0, this.cursor) + this.userInput.slice(this.cursor + 1)\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (char) {\n\t\t\t\tif (this.#showSubmit && this.focused === 'submit') {\n\t\t\t\t\tthis.focused = 'editor';\n\t\t\t\t}\n\t\t\t\tthis.#insertAtCursor(char ?? '');\n\t\t\t\tthis._cursor++;\n\t\t\t}\n\t\t});\n\n\t\tthis.on('userInput', (input) => {\n\t\t\tthis._setValue(input);\n\t\t});\n\t\tthis.on('finalize', () => {\n\t\t\tif (!this.value) {\n\t\t\t\tthis.value = opts.defaultValue;\n\t\t\t}\n\t\t\tif (this.value === undefined) {\n\t\t\t\tthis.value = '';\n\t\t\t}\n\t\t});\n\t}\n}\n","import { findCursor } from '../utils/cursor.js';\nimport Prompt, { type PromptOptions } from './prompt.js';\n\ninterface OptionLike {\n\tvalue: any;\n\tdisabled?: boolean;\n}\n\nexport interface MultiSelectOptions<T extends OptionLike>\n\textends PromptOptions<T['value'][], MultiSelectPrompt<T>> {\n\toptions: T[];\n\tinitialValues?: T['value'][];\n\trequired?: boolean;\n\tcursorAt?: T['value'];\n}\nexport default class MultiSelectPrompt<T extends OptionLike> extends Prompt<T['value'][]> {\n\toptions: T[];\n\tcursor = 0;\n\n\tprivate get _value(): T['value'] {\n\t\treturn this.options[this.cursor].value;\n\t}\n\n\tprivate get _enabledOptions(): T[] {\n\t\treturn this.options.filter((option) => option.disabled !== true);\n\t}\n\n\tprivate toggleAll() {\n\t\tconst enabledOptions = this._enabledOptions;\n\t\tconst allSelected = this.value !== undefined && this.value.length === enabledOptions.length;\n\t\tthis.value = allSelected ? [] : enabledOptions.map((v) => v.value);\n\t}\n\n\tprivate toggleInvert() {\n\t\tconst value = this.value;\n\t\tif (!value) {\n\t\t\treturn;\n\t\t}\n\t\tconst notSelected = this._enabledOptions.filter((v) => !value.includes(v.value));\n\t\tthis.value = notSelected.map((v) => v.value);\n\t}\n\n\tprivate toggleValue() {\n\t\tif (this.value === undefined) {\n\t\t\tthis.value = [];\n\t\t}\n\t\tconst selected = this.value.includes(this._value);\n\t\tthis.value = selected\n\t\t\t? this.value.filter((value) => value !== this._value)\n\t\t\t: [...this.value, this._value];\n\t}\n\n\tconstructor(opts: MultiSelectOptions<T>) {\n\t\tsuper(opts, false);\n\n\t\tthis.options = opts.options;\n\t\tthis.value = [...(opts.initialValues ?? [])];\n\t\tconst cursor = Math.max(\n\t\t\tthis.options.findIndex(({ value }) => value === opts.cursorAt),\n\t\t\t0\n\t\t);\n\t\tthis.cursor = this.options[cursor].disabled ? findCursor<T>(cursor, 1, this.options) : cursor;\n\t\tthis.on('key', (char) => {\n\t\t\tif (char === 'a') {\n\t\t\t\tthis.toggleAll();\n\t\t\t}\n\t\t\tif (char === 'i') {\n\t\t\t\tthis.toggleInvert();\n\t\t\t}\n\t\t});\n\n\t\tthis.on('cursor', (key) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'up':\n\t\t\t\t\tthis.cursor = findCursor<T>(this.cursor, -1, this.options);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'down':\n\t\t\t\tcase 'right':\n\t\t\t\t\tthis.cursor = findCursor<T>(this.cursor, 1, this.options);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'space':\n\t\t\t\t\tthis.toggleValue();\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t}\n}\n","import { styleText } from 'node:util';\nimport Prompt, { type PromptOptions } from './prompt.js';\n\nexport interface PasswordOptions extends PromptOptions<string, PasswordPrompt> {\n\tmask?: string;\n}\nexport default class PasswordPrompt extends Prompt<string> {\n\tprivate _mask = '•';\n\tget cursor() {\n\t\treturn this._cursor;\n\t}\n\tget masked() {\n\t\treturn this.userInput.replaceAll(/./g, this._mask);\n\t}\n\tget userInputWithCursor() {\n\t\tif (this.state === 'submit' || this.state === 'cancel') {\n\t\t\treturn this.masked;\n\t\t}\n\t\tconst userInput = this.userInput;\n\t\tif (this.cursor >= userInput.length) {\n\t\t\treturn `${this.masked}${styleText(['inverse', 'hidden'], '_')}`;\n\t\t}\n\t\tconst masked = this.masked;\n\t\tconst s1 = masked.slice(0, this.cursor);\n\t\tconst s2 = masked.slice(this.cursor);\n\t\treturn `${s1}${styleText('inverse', s2[0])}${s2.slice(1)}`;\n\t}\n\tclear() {\n\t\tthis._clearUserInput();\n\t}\n\tconstructor({ mask, ...opts }: PasswordOptions) {\n\t\tsuper(opts);\n\t\tthis._mask = mask ?? '•';\n\t\tthis.on('userInput', (input) => {\n\t\t\tthis._setValue(input);\n\t\t});\n\t}\n}\n","import { findCursor } from '../utils/cursor.js';\nimport Prompt, { type PromptOptions } from './prompt.js';\n\nexport interface SelectOptions<T extends { value: any; disabled?: boolean }>\n\textends PromptOptions<T['value'], SelectPrompt<T>> {\n\toptions: T[];\n\tinitialValue?: T['value'];\n}\nexport default class SelectPrompt<T extends { value: any; disabled?: boolean }> extends Prompt<\n\tT['value']\n> {\n\toptions: T[];\n\tcursor = 0;\n\n\tprivate get _selectedValue() {\n\t\treturn this.options[this.cursor];\n\t}\n\n\tprivate changeValue() {\n\t\tthis.value = this._selectedValue.value;\n\t}\n\n\tconstructor(opts: SelectOptions<T>) {\n\t\tsuper(opts, false);\n\n\t\tthis.options = opts.options;\n\n\t\tconst initialCursor = this.options.findIndex(({ value }) => value === opts.initialValue);\n\t\tconst cursor = initialCursor === -1 ? 0 : initialCursor;\n\t\tthis.cursor = this.options[cursor].disabled ? findCursor<T>(cursor, 1, this.options) : cursor;\n\t\tthis.changeValue();\n\n\t\tthis.on('cursor', (key) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase 'left':\n\t\t\t\tcase 'up':\n\t\t\t\t\tthis.cursor = findCursor<T>(this.cursor, -1, this.options);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'down':\n\t\t\t\tcase 'right':\n\t\t\t\t\tthis.cursor = findCursor<T>(this.cursor, 1, this.options);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tthis.changeValue();\n\t\t});\n\t}\n}\n","import Prompt, { type PromptOptions } from './prompt.js';\n\nexport interface SelectKeyOptions<T extends { value: string }>\n\textends PromptOptions<T['value'], SelectKeyPrompt<T>> {\n\toptions: T[];\n\tcaseSensitive?: boolean;\n}\nexport default class SelectKeyPrompt<T extends { value: string }> extends Prompt<T['value']> {\n\toptions: T[];\n\tcursor = 0;\n\n\tconstructor(opts: SelectKeyOptions<T>) {\n\t\tsuper(opts, false);\n\n\t\tthis.options = opts.options;\n\t\tconst caseSensitive = opts.caseSensitive === true;\n\t\tconst keys = this.options.map(({ value: [initial] }) => {\n\t\t\treturn caseSensitive ? initial : initial?.toLowerCase();\n\t\t});\n\t\tthis.cursor = Math.max(keys.indexOf(opts.initialValue), 0);\n\n\t\tthis.on('key', (key, keyInfo) => {\n\t\t\tif (!key) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst casedKey = caseSensitive && keyInfo.shift ? key.toUpperCase() : key;\n\t\t\tif (!keys.includes(casedKey)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst value = this.options.find(({ value: [initial] }) => {\n\t\t\t\treturn caseSensitive ? initial === casedKey : initial?.toLowerCase() === key;\n\t\t\t});\n\t\t\tif (value) {\n\t\t\t\tthis.value = value.value;\n\t\t\t\tthis.state = 'submit';\n\t\t\t\tthis.emit('submit');\n\t\t\t}\n\t\t});\n\t}\n}\n","import { styleText } from 'node:util';\nimport Prompt, { type PromptOptions } from './prompt.js';\n\nexport interface TextOptions extends PromptOptions<string, TextPrompt> {\n\tplaceholder?: string;\n\tdefaultValue?: string;\n}\n\nexport default class TextPrompt extends Prompt<string> {\n\tget userInputWithCursor() {\n\t\tif (this.state === 'submit') {\n\t\t\treturn this.userInput;\n\t\t}\n\t\tconst userInput = this.userInput;\n\t\tif (this.cursor >= userInput.length) {\n\t\t\treturn `${this.userInput}█`;\n\t\t}\n\t\tconst s1 = userInput.slice(0, this.cursor);\n\t\tconst [s2, ...s3] = userInput.slice(this.cursor);\n\t\treturn `${s1}${styleText('inverse', s2)}${s3.join('')}`;\n\t}\n\tget cursor() {\n\t\treturn this._cursor;\n\t}\n\tconstructor(opts: TextOptions) {\n\t\tsuper({\n\t\t\t...opts,\n\t\t\tinitialUserInput: opts.initialUserInput ?? opts.initialValue,\n\t\t});\n\n\t\tthis.on('userInput', (input) => {\n\t\t\tthis._setValue(input);\n\t\t});\n\t\tthis.on('finalize', () => {\n\t\t\tif (!this.value) {\n\t\t\t\tthis.value = opts.defaultValue;\n\t\t\t}\n\t\t\tif (this.value === undefined) {\n\t\t\t\tthis.value = '';\n\t\t\t}\n\t\t});\n\t}\n}\n","import process from 'node:process';\n\nexport default function isUnicodeSupported() {\n\tif (process.platform !== 'win32') {\n\t\treturn process.env.TERM !== 'linux'; // Linux console (kernel)\n\t}\n\n\treturn Boolean(process.env.CI)\n\t\t|| Boolean(process.env.WT_SESSION) // Windows Terminal\n\t\t|| Boolean(process.env.TERMINUS_SUBLIME) // Terminus (<0.2.27)\n\t\t|| process.env.ConEmuTask === '{cmd::Cmder}' // ConEmu and cmder\n\t\t|| process.env.TERM_PROGRAM === 'Terminus-Sublime'\n\t\t|| process.env.TERM_PROGRAM === 'vscode'\n\t\t|| process.env.TERM === 'xterm-256color'\n\t\t|| process.env.TERM === 'alacritty'\n\t\t|| process.env.TERMINAL_EMULATOR === 'JetBrains-JediTerm';\n}\n","import type { Readable, Writable } from 'node:stream';\nimport { styleText } from 'node:util';\nimport type { State } from '@clack/core';\nimport isUnicodeSupported from 'is-unicode-supported';\n\nexport const unicode = isUnicodeSupported();\nexport const isCI = (): boolean => process.env.CI === 'true';\nexport const isTTY = (output: Writable): boolean => {\n\treturn (output as Writable & { isTTY?: boolean }).isTTY === true;\n};\nexport const unicodeOr = (c: string, fallback: string) => (unicode ? c : fallback);\nexport const S_STEP_ACTIVE = unicodeOr('◆', '*');\nexport const S_STEP_CANCEL = unicodeOr('■', 'x');\nexport const S_STEP_ERROR = unicodeOr('▲', 'x');\nexport const S_STEP_SUBMIT = unicodeOr('◇', 'o');\n\nexport const S_BAR_START = unicodeOr('┌', 'T');\nexport const S_BAR = unicodeOr('│', '|');\nexport const S_BAR_END = unicodeOr('└', '—');\nexport const S_BAR_START_RIGHT = unicodeOr('┐', 'T');\nexport const S_BAR_END_RIGHT = unicodeOr('┘', '—');\n\nexport const S_RADIO_ACTIVE = unicodeOr('●', '>');\nexport const S_RADIO_INACTIVE = unicodeOr('○', ' ');\nexport const S_CHECKBOX_ACTIVE = unicodeOr('◻', '[•]');\nexport const S_CHECKBOX_SELECTED = unicodeOr('◼', '[+]');\nexport const S_CHECKBOX_INACTIVE = unicodeOr('◻', '[ ]');\nexport const S_PASSWORD_MASK = unicodeOr('▪', '•');\n\nexport const S_BAR_H = unicodeOr('─', '-');\nexport const S_CORNER_TOP_RIGHT = unicodeOr('╮', '+');\nexport const S_CONNECT_LEFT = unicodeOr('├', '+');\nexport const S_CORNER_BOTTOM_RIGHT = unicodeOr('╯', '+');\nexport const S_CORNER_BOTTOM_LEFT = unicodeOr('╰', '+');\nexport const S_CORNER_TOP_LEFT = unicodeOr('╭', '+');\n\nexport const S_INFO = unicodeOr('●', '•');\nexport const S_SUCCESS = unicodeOr('◆', '*');\nexport const S_WARN = unicodeOr('▲', '!');\nexport const S_ERROR = unicodeOr('■', 'x');\n\nexport const symbol = (state: State) => {\n\tswitch (state) {\n\t\tcase 'initial':\n\t\tcase 'active':\n\t\t\treturn styleText('cyan', S_STEP_ACTIVE);\n\t\tcase 'cancel':\n\t\t\treturn styleText('red', S_STEP_CANCEL);\n\t\tcase 'error':\n\t\t\treturn styleText('yellow', S_STEP_ERROR);\n\t\tcase 'submit':\n\t\t\treturn styleText('green', S_STEP_SUBMIT);\n\t}\n};\n\nexport const symbolBar = (state: State) => {\n\tswitch (state) {\n\t\tcase 'initial':\n\t\tcase 'active':\n\t\t\treturn styleText('cyan', S_BAR);\n\t\tcase 'cancel':\n\t\t\treturn styleText('red', S_BAR);\n\t\tcase 'error':\n\t\t\treturn styleText('yellow', S_BAR);\n\t\tcase 'submit':\n\t\t\treturn styleText('green', S_BAR);\n\t}\n};\n\nexport interface CommonOptions {\n\tinput?: Readable;\n\toutput?: Writable;\n\tsignal?: AbortSignal;\n\twithGuide?: boolean;\n}\n","import { styleText } from 'node:util';\nimport { getColumns, getRows } from '@clack/core';\nimport { wrapAnsi } from 'fast-wrap-ansi';\nimport type { CommonOptions } from './common.js';\n\nexport interface LimitOptionsParams<TOption> extends CommonOptions {\n\toptions: TOption[];\n\tcursor: number;\n\tstyle: (option: TOption, active: boolean) => string;\n\tmaxItems?: number;\n\tcolumnPadding?: number;\n\trowPadding?: number;\n}\n\nconst trimLines = (\n\tgroups: Array<string[]>,\n\tinitialLineCount: number,\n\tstartIndex: number,\n\tendIndex: number,\n\tmaxLines: number,\n\tfromEnd = false\n) => {\n\tlet lineCount = initialLineCount;\n\tlet removals = 0;\n\tif (fromEnd) {\n\t\tfor (let i = endIndex - 1; i >= startIndex; i--) {\n\t\t\tlineCount -= groups[i].length;\n\t\t\tremovals++;\n\t\t\tif (lineCount <= maxLines) break;\n\t\t}\n\t} else {\n\t\tfor (let i = startIndex; i < endIndex; i++) {\n\t\t\tlineCount -= groups[i].length;\n\t\t\tremovals++;\n\t\t\tif (lineCount <= maxLines) break;\n\t\t}\n\t}\n\treturn { lineCount, removals };\n};\n\nexport const limitOptions = <TOption>({\n\tcursor,\n\toptions,\n\tstyle,\n\toutput = process.stdout,\n\tmaxItems = Number.POSITIVE_INFINITY,\n\tcolumnPadding = 0,\n\trowPadding = 4,\n}: LimitOptionsParams<TOption>): string[] => {\n\tconst columns = getColumns(output);\n\tconst maxWidth = columns - columnPadding;\n\tconst rows = getRows(output);\n\tconst overflowFormat = styleText('dim', '...');\n\n\tconst outputMaxItems = Math.max(rows - rowPadding, 0);\n\t// We clamp to minimum 5 because anything less doesn't make sense UX wise\n\tconst computedMaxItems = Math.max(Math.min(maxItems, outputMaxItems), 5);\n\tlet slidingWindowLocation = 0;\n\n\tif (cursor >= computedMaxItems - 3) {\n\t\tslidingWindowLocation = Math.max(\n\t\t\tMath.min(cursor - computedMaxItems + 3, options.length - computedMaxItems),\n\t\t\t0\n\t\t);\n\t}\n\n\tlet shouldRenderTopEllipsis = computedMaxItems < options.length && slidingWindowLocation > 0;\n\tlet shouldRenderBottomEllipsis =\n\t\tcomputedMaxItems < options.length && slidingWindowLocation + computedMaxItems < options.length;\n\n\tconst slidingWindowLocationEnd = Math.min(\n\t\tslidingWindowLocation + computedMaxItems,\n\t\toptions.length\n\t);\n\tconst lineGroups: Array<string[]> = [];\n\tlet lineCount = 0;\n\tif (shouldRenderTopEllipsis) {\n\t\tlineCount++;\n\t}\n\tif (shouldRenderBottomEllipsis) {\n\t\tlineCount++;\n\t}\n\n\tconst slidingWindowLocationWithEllipsis =\n\t\tslidingWindowLocation + (shouldRenderTopEllipsis ? 1 : 0);\n\tconst slidingWindowLocationEndWithEllipsis =\n\t\tslidingWindowLocationEnd - (shouldRenderBottomEllipsis ? 1 : 0);\n\n\tfor (let i = slidingWindowLocationWithEllipsis; i < slidingWindowLocationEndWithEllipsis; i++) {\n\t\tconst wrappedLines = wrapAnsi(style(options[i], i === cursor), maxWidth, {\n\t\t\thard: true,\n\t\t\ttrim: false,\n\t\t}).split('\\n');\n\t\tlineGroups.push(wrappedLines);\n\t\tlineCount += wrappedLines.length;\n\t}\n\n\tif (lineCount > outputMaxItems) {\n\t\tlet precedingRemovals = 0;\n\t\tlet followingRemovals = 0;\n\t\tlet newLineCount = lineCount;\n\t\tconst cursorGroupIndex = cursor - slidingWindowLocationWithEllipsis;\n\t\tlet adjustedMax = outputMaxItems;\n\t\tconst trimPreceding = () =>\n\t\t\ttrimLines(lineGroups, newLineCount, 0, cursorGroupIndex, adjustedMax);\n\t\tconst trimFollowing = () =>\n\t\t\ttrimLines(\n\t\t\t\tlineGroups,\n\t\t\t\tnewLineCount,\n\t\t\t\tcursorGroupIndex + 1,\n\t\t\t\tlineGroups.length,\n\t\t\t\tadjustedMax,\n\t\t\t\ttrue\n\t\t\t);\n\n\t\tif (shouldRenderTopEllipsis) {\n\t\t\t({ lineCount: newLineCount, removals: precedingRemovals } = trimPreceding());\n\t\t\tif (newLineCount > adjustedMax) {\n\t\t\t\tif (!shouldRenderBottomEllipsis) adjustedMax -= 1;\n\t\t\t\t({ lineCount: newLineCount, removals: followingRemovals } = trimFollowing());\n\t\t\t}\n\t\t} else {\n\t\t\tif (!shouldRenderBottomEllipsis) adjustedMax -= 1;\n\t\t\t({ lineCount: newLineCount, removals: followingRemovals } = trimFollowing());\n\t\t\tif (newLineCount > adjustedMax) {\n\t\t\t\tadjustedMax -= 1;\n\t\t\t\t({ lineCount: newLineCount, removals: precedingRemovals } = trimPreceding());\n\t\t\t}\n\t\t}\n\n\t\tif (precedingRemovals > 0) {\n\t\t\tshouldRenderTopEllipsis = true;\n\t\t\tlineGroups.splice(0, precedingRemovals);\n\t\t}\n\t\tif (followingRemovals > 0) {\n\t\t\tshouldRenderBottomEllipsis = true;\n\t\t\tlineGroups.splice(lineGroups.length - followingRemovals, followingRemovals);\n\t\t}\n\t}\n\n\tconst result: string[] = [];\n\tif (shouldRenderTopEllipsis) {\n\t\tresult.push(overflowFormat);\n\t}\n\tfor (const lineGroup of lineGroups) {\n\t\tfor (const line of lineGroup) {\n\t\t\tresult.push(line);\n\t\t}\n\t}\n\tif (shouldRenderBottomEllipsis) {\n\t\tresult.push(overflowFormat);\n\t}\n\n\treturn result;\n};\n","import { styleText } from 'node:util';\nimport { AutocompletePrompt, settings } from '@clack/core';\nimport {\n\ttype CommonOptions,\n\tS_BAR,\n\tS_BAR_END,\n\tS_CHECKBOX_INACTIVE,\n\tS_CHECKBOX_SELECTED,\n\tS_RADIO_ACTIVE,\n\tS_RADIO_INACTIVE,\n\tsymbol,\n} from './common.js';\nimport { limitOptions } from './limit-options.js';\nimport type { Option } from './select.js';\n\nfunction getLabel<T>(option: Option<T>) {\n\treturn option.label ?? String(option.value ?? '');\n}\n\nfunction getFilteredOption<T>(searchText: string, option: Option<T>): boolean {\n\tif (!searchText) {\n\t\treturn true;\n\t}\n\tconst label = (option.label ?? String(option.value ?? '')).toLowerCase();\n\tconst hint = (option.hint ?? '').toLowerCase();\n\tconst value = String(option.value).toLowerCase();\n\tconst term = searchText.toLowerCase();\n\n\treturn label.includes(term) || hint.includes(term) || value.includes(term);\n}\n\nfunction getSelectedOptions<T>(values: T[], options: Option<T>[]): Option<T>[] {\n\tconst results: Option<T>[] = [];\n\n\tfor (const option of options) {\n\t\tif (values.includes(option.value)) {\n\t\t\tresults.push(option);\n\t\t}\n\t}\n\n\treturn results;\n}\n\ninterface AutocompleteSharedOptions<Value> extends CommonOptions {\n\t/**\n\t * The message to display to the user.\n\t */\n\tmessage: string;\n\t/**\n\t * Available options for the autocomplete prompt.\n\t */\n\toptions: Option<Value>[] | ((this: AutocompletePrompt<Option<Value>>) => Option<Value>[]);\n\t/**\n\t * Maximum number of items to display at once.\n\t */\n\tmaxItems?: number;\n\t/**\n\t * Placeholder text to display when no input is provided.\n\t */\n\tplaceholder?: string;\n\t/**\n\t * Validates the value\n\t */\n\tvalidate?: (value: Value | Value[] | undefined) => string | Error | undefined;\n\t/**\n\t * Custom filter function to match options against search input.\n\t * If not provided, a default filter that matches label, hint, and value is used.\n\t */\n\tfilter?: (search: string, option: Option<Value>) => boolean;\n}\n\nexport interface AutocompleteOptions<Value> extends AutocompleteSharedOptions<Value> {\n\t/**\n\t * The initial selected value.\n\t */\n\tinitialValue?: Value;\n\t/**\n\t * The initial user input\n\t */\n\tinitialUserInput?: string;\n}\n\nexport const autocomplete = <Value>(opts: AutocompleteOptions<Value>) => {\n\tconst prompt = new AutocompletePrompt({\n\t\toptions: opts.options,\n\t\tinitialValue: opts.initialValue ? [opts.initialValue] : undefined,\n\t\tinitialUserInput: opts.initialUserInput,\n\t\tplaceholder: opts.placeholder,\n\t\tfilter:\n\t\t\topts.filter ??\n\t\t\t((search: string, opt: Option<Value>) => {\n\t\t\t\treturn getFilteredOption(search, opt);\n\t\t\t}),\n\t\tsignal: opts.signal,\n\t\tinput: opts.input,\n\t\toutput: opts.output,\n\t\tvalidate: opts.validate,\n\t\trender() {\n\t\t\tconst hasGuide = opts.withGuide ?? settings.withGuide;\n\t\t\t// Title and message display\n\t\t\tconst headings = hasGuide\n\t\t\t\t? [`${styleText('gray', S_BAR)}`, `${symbol(this.state)} ${opts.message}`]\n\t\t\t\t: [`${symbol(this.state)} ${opts.message}`];\n\t\t\tconst userInput = this.userInput;\n\t\t\tconst options = this.options;\n\t\t\tconst placeholder = opts.placeholder;\n\t\t\tconst showPlaceholder = userInput === '' && placeholder !== undefined;\n\t\t\tconst opt = (option: Option<Value>, state: 'inactive' | 'active' | 'disabled') => {\n\t\t\t\tconst label = getLabel(option);\n\t\t\t\tconst hint =\n\t\t\t\t\toption.hint && option.value === this.focusedValue\n\t\t\t\t\t\t? styleText('dim', ` (${option.hint})`)\n\t\t\t\t\t\t: '';\n\t\t\t\tswitch (state) {\n\t\t\t\t\tcase 'active':\n\t\t\t\t\t\treturn `${styleText('green', S_RADIO_ACTIVE)} ${label}${hint}`;\n\t\t\t\t\tcase 'inactive':\n\t\t\t\t\t\treturn `${styleText('dim', S_RADIO_INACTIVE)} ${styleText('dim', label)}`;\n\t\t\t\t\tcase 'disabled':\n\t\t\t\t\t\treturn `${styleText('gray', S_RADIO_INACTIVE)} ${styleText(['strikethrough', 'gray'], label)}`;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t// Handle different states\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'submit': {\n\t\t\t\t\t// Show selected value\n\t\t\t\t\tconst selected = getSelectedOptions(this.selectedValues, options);\n\t\t\t\t\tconst label =\n\t\t\t\t\t\tselected.length > 0 ? ` ${styleText('dim', selected.map(getLabel).join(', '))}` : '';\n\t\t\t\t\tconst submitPrefix = hasGuide ? styleText('gray', S_BAR) : '';\n\t\t\t\t\treturn `${headings.join('\\n')}\\n${submitPrefix}${label}`;\n\t\t\t\t}\n\n\t\t\t\tcase 'cancel': {\n\t\t\t\t\tconst userInputText = userInput\n\t\t\t\t\t\t? ` ${styleText(['strikethrough', 'dim'], userInput)}`\n\t\t\t\t\t\t: '';\n\t\t\t\t\tconst cancelPrefix = hasGuide ? styleText('gray', S_BAR) : '';\n\t\t\t\t\treturn `${headings.join('\\n')}\\n${cancelPrefix}${userInputText}`;\n\t\t\t\t}\n\n\t\t\t\tdefault: {\n\t\t\t\t\tconst barStyle = this.state === 'error' ? 'yellow' : 'cyan';\n\t\t\t\t\tconst guidePrefix = hasGuide ? `${styleText(barStyle, S_BAR)} ` : '';\n\t\t\t\t\tconst guidePrefixEnd = hasGuide ? styleText(barStyle, S_BAR_END) : '';\n\t\t\t\t\t// Display cursor position - show plain text in navigation mode\n\t\t\t\t\tlet searchText = '';\n\t\t\t\t\tif (this.isNavigating || showPlaceholder) {\n\t\t\t\t\t\tconst searchTextValue = showPlaceholder ? placeholder : userInput;\n\t\t\t\t\t\tsearchText = searchTextValue !== '' ? ` ${styleText('dim', searchTextValue)}` : '';\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsearchText = ` ${this.userInputWithCursor}`;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Show match count if filtered\n\t\t\t\t\tconst matches =\n\t\t\t\t\t\tthis.filteredOptions.length !== options.length\n\t\t\t\t\t\t\t? styleText(\n\t\t\t\t\t\t\t\t\t'dim',\n\t\t\t\t\t\t\t\t\t` (${this.filteredOptions.length} match${this.filteredOptions.length === 1 ? '' : 'es'})`\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: '';\n\n\t\t\t\t\t// No matches message\n\t\t\t\t\tconst noResults =\n\t\t\t\t\t\tthis.filteredOptions.length === 0 && userInput\n\t\t\t\t\t\t\t? [`${guidePrefix}${styleText('yellow', 'No matches found')}`]\n\t\t\t\t\t\t\t: [];\n\n\t\t\t\t\tconst validationError =\n\t\t\t\t\t\tthis.state === 'error' ? [`${guidePrefix}${styleText('yellow', this.error)}`] : [];\n\n\t\t\t\t\tif (hasGuide) {\n\t\t\t\t\t\theadings.push(`${guidePrefix.trimEnd()}`);\n\t\t\t\t\t}\n\t\t\t\t\theadings.push(\n\t\t\t\t\t\t`${guidePrefix}${styleText('dim', 'Search:')}${searchText}${matches}`,\n\t\t\t\t\t\t...noResults,\n\t\t\t\t\t\t...validationError\n\t\t\t\t\t);\n\n\t\t\t\t\t// Show instructions\n\t\t\t\t\tconst instructions = [\n\t\t\t\t\t\t`${styleText('dim', '↑/↓')} to select`,\n\t\t\t\t\t\t`${styleText('dim', 'Enter:')} confirm`,\n\t\t\t\t\t\t`${styleText('dim', 'Type:')} to search`,\n\t\t\t\t\t];\n\n\t\t\t\t\tconst footers = [`${guidePrefix}${instructions.join(' • ')}`, guidePrefixEnd];\n\n\t\t\t\t\t// Render options with selection\n\t\t\t\t\tconst displayOptions =\n\t\t\t\t\t\tthis.filteredOptions.length === 0\n\t\t\t\t\t\t\t? []\n\t\t\t\t\t\t\t: limitOptions({\n\t\t\t\t\t\t\t\t\tcursor: this.cursor,\n\t\t\t\t\t\t\t\t\toptions: this.filteredOptions,\n\t\t\t\t\t\t\t\t\tcolumnPadding: hasGuide ? 3 : 0, // for `| ` when guide is shown\n\t\t\t\t\t\t\t\t\trowPadding: headings.length + footers.length,\n\t\t\t\t\t\t\t\t\tstyle: (option, active) => {\n\t\t\t\t\t\t\t\t\t\treturn opt(\n\t\t\t\t\t\t\t\t\t\t\toption,\n\t\t\t\t\t\t\t\t\t\t\toption.disabled ? 'disabled' : active ? 'active' : 'inactive'\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tmaxItems: opts.maxItems,\n\t\t\t\t\t\t\t\t\toutput: opts.output,\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t// Return the formatted prompt\n\t\t\t\t\treturn [\n\t\t\t\t\t\t...headings,\n\t\t\t\t\t\t...displayOptions.map((option) => `${guidePrefix}${option}`),\n\t\t\t\t\t\t...footers,\n\t\t\t\t\t].join('\\n');\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t});\n\n\t// Return the result or cancel symbol\n\treturn prompt.prompt() as Promise<Value | symbol>;\n};\n\n// Type definition for the autocompleteMultiselect component\nexport interface AutocompleteMultiSelectOptions<Value> extends AutocompleteSharedOptions<Value> {\n\t/**\n\t * The initial selected values\n\t */\n\tinitialValues?: Value[];\n\t/**\n\t * If true, at least one option must be selected\n\t */\n\trequired?: boolean;\n}\n\n/**\n * Integrated autocomplete multiselect - combines type-ahead filtering with multiselect in one UI\n */\nexport const autocompleteMultiselect = <Value>(opts: AutocompleteMultiSelectOptions<Value>) => {\n\tconst formatOption = (\n\t\toption: Option<Value>,\n\t\tactive: boolean,\n\t\tselectedValues: Value[],\n\t\tfocusedValue: Value | undefined\n\t) => {\n\t\tconst isSelected = selectedValues.includes(option.value);\n\t\tconst label = option.label ?? String(option.value ?? '');\n\t\tconst hint =\n\t\t\toption.hint && focusedValue !== undefined && option.value === focusedValue\n\t\t\t\t? styleText('dim', ` (${option.hint})`)\n\t\t\t\t: '';\n\t\tconst checkbox = isSelected\n\t\t\t? styleText('green', S_CHECKBOX_SELECTED)\n\t\t\t: styleText('dim', S_CHECKBOX_INACTIVE);\n\n\t\tif (option.disabled) {\n\t\t\treturn `${styleText('gray', S_CHECKBOX_INACTIVE)} ${styleText(['strikethrough', 'gray'], label)}`;\n\t\t}\n\t\tif (active) {\n\t\t\treturn `${checkbox} ${label}${hint}`;\n\t\t}\n\t\treturn `${checkbox} ${styleText('dim', label)}`;\n\t};\n\n\t// Create text prompt which we'll use as foundation\n\tconst prompt = new AutocompletePrompt<Option<Value>>({\n\t\toptions: opts.options,\n\t\tmultiple: true,\n\t\tplaceholder: opts.placeholder,\n\t\tfilter:\n\t\t\topts.filter ??\n\t\t\t((search, opt) => {\n\t\t\t\treturn getFilteredOption(search, opt);\n\t\t\t}),\n\t\tvalidate: () => {\n\t\t\tif (opts.required && prompt.selectedValues.length === 0) {\n\t\t\t\treturn 'Please select at least one item';\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t\tinitialValue: opts.initialValues,\n\t\tsignal: opts.signal,\n\t\tinput: opts.input,\n\t\toutput: opts.output,\n\t\trender() {\n\t\t\tconst hasGuide = opts.withGuide ?? settings.withGuide;\n\t\t\t// Title and symbol\n\t\t\tconst title = `${hasGuide ? `${styleText('gray', S_BAR)}\\n` : ''}${symbol(this.state)} ${\n\t\t\t\topts.message\n\t\t\t}\\n`;\n\n\t\t\t// Selection counter\n\t\t\tconst userInput = this.userInput;\n\t\t\tconst placeholder = opts.placeholder;\n\t\t\tconst showPlaceholder = userInput === '' && placeholder !== undefined;\n\n\t\t\t// Search input display\n\t\t\tconst searchText =\n\t\t\t\tthis.isNavigating || showPlaceholder\n\t\t\t\t\t? styleText('dim', showPlaceholder ? placeholder : userInput) // Just show plain text when in navigation mode\n\t\t\t\t\t: this.userInputWithCursor;\n\n\t\t\tconst options = this.options;\n\n\t\t\tconst matches =\n\t\t\t\tthis.filteredOptions.length !== options.length\n\t\t\t\t\t? styleText(\n\t\t\t\t\t\t\t'dim',\n\t\t\t\t\t\t\t` (${this.filteredOptions.length} match${this.filteredOptions.length === 1 ? '' : 'es'})`\n\t\t\t\t\t\t)\n\t\t\t\t\t: '';\n\n\t\t\t// Render prompt state\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'submit': {\n\t\t\t\t\treturn `${title}${hasGuide ? `${styleText('gray', S_BAR)} ` : ''}${styleText(\n\t\t\t\t\t\t'dim',\n\t\t\t\t\t\t`${this.selectedValues.length} items selected`\n\t\t\t\t\t)}`;\n\t\t\t\t}\n\t\t\t\tcase 'cancel': {\n\t\t\t\t\treturn `${title}${hasGuide ? `${styleText('gray', S_BAR)} ` : ''}${styleText(\n\t\t\t\t\t\t['strikethrough', 'dim'],\n\t\t\t\t\t\tuserInput\n\t\t\t\t\t)}`;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\tconst barStyle = this.state === 'error' ? 'yellow' : 'cyan';\n\t\t\t\t\tconst guidePrefix = hasGuide ? `${styleText(barStyle, S_BAR)} ` : '';\n\t\t\t\t\tconst guidePrefixEnd = hasGuide ? styleText(barStyle, S_BAR_END) : '';\n\t\t\t\t\t// Instructions\n\t\t\t\t\tconst instructions = [\n\t\t\t\t\t\t`${styleText('dim', '↑/↓')} to navigate`,\n\t\t\t\t\t\t`${styleText('dim', this.isNavigating ? 'Space/Tab:' : 'Tab:')} select`,\n\t\t\t\t\t\t`${styleText('dim', 'Enter:')} confirm`,\n\t\t\t\t\t\t`${styleText('dim', 'Type:')} to search`,\n\t\t\t\t\t];\n\n\t\t\t\t\t// No results message\n\t\t\t\t\tconst noResults =\n\t\t\t\t\t\tthis.filteredOptions.length === 0 && userInput\n\t\t\t\t\t\t\t? [`${guidePrefix}${styleText('yellow', 'No matches found')}`]\n\t\t\t\t\t\t\t: [];\n\n\t\t\t\t\tconst errorMessage =\n\t\t\t\t\t\tthis.state === 'error' ? [`${guidePrefix}${styleText('yellow', this.error)}`] : [];\n\n\t\t\t\t\t// Calculate header and footer line counts for rowPadding\n\t\t\t\t\tconst headerLines = [\n\t\t\t\t\t\t...`${title}${hasGuide ? styleText(barStyle, S_BAR) : ''}`.split('\\n'),\n\t\t\t\t\t\t`${guidePrefix}${styleText('dim', 'Search:')} ${searchText}${matches}`,\n\t\t\t\t\t\t...noResults,\n\t\t\t\t\t\t...errorMessage,\n\t\t\t\t\t];\n\t\t\t\t\tconst footerLines = [`${guidePrefix}${instructions.join(' • ')}`, guidePrefixEnd];\n\n\t\t\t\t\t// Get limited options for display\n\t\t\t\t\tconst displayOptions = limitOptions({\n\t\t\t\t\t\tcursor: this.cursor,\n\t\t\t\t\t\toptions: this.filteredOptions,\n\t\t\t\t\t\tstyle: (option, active) =>\n\t\t\t\t\t\t\tformatOption(option, active, this.selectedValues, this.focusedValue),\n\t\t\t\t\t\tmaxItems: opts.maxItems,\n\t\t\t\t\t\toutput: opts.output,\n\t\t\t\t\t\trowPadding: headerLines.length + footerLines.length,\n\t\t\t\t\t});\n\n\t\t\t\t\t// Build the prompt display\n\t\t\t\t\treturn [\n\t\t\t\t\t\t...headerLines,\n\t\t\t\t\t\t...displayOptions.map((option) => `${guidePrefix}${option}`),\n\t\t\t\t\t\t...footerLines,\n\t\t\t\t\t].join('\\n');\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t});\n\n\t// Return the result or cancel symbol\n\treturn prompt.prompt() as Promise<Value[] | symbol>;\n};\n","import type { Writable } from 'node:stream';\nimport { getColumns, settings } from '@clack/core';\nimport stringWidth from 'fast-string-width';\nimport { wrapAnsi } from 'fast-wrap-ansi';\nimport {\n\ttype CommonOptions,\n\tS_BAR,\n\tS_BAR_END,\n\tS_BAR_END_RIGHT,\n\tS_BAR_H,\n\tS_BAR_START,\n\tS_BAR_START_RIGHT,\n\tS_CORNER_BOTTOM_LEFT,\n\tS_CORNER_BOTTOM_RIGHT,\n\tS_CORNER_TOP_LEFT,\n\tS_CORNER_TOP_RIGHT,\n} from './common.js';\n\nexport type BoxAlignment = 'left' | 'center' | 'right';\n\ntype BoxSymbols = [topLeft: string, topRight: string, bottomLeft: string, bottomRight: string];\n\nconst roundedSymbols: BoxSymbols = [\n\tS_CORNER_TOP_LEFT,\n\tS_CORNER_TOP_RIGHT,\n\tS_CORNER_BOTTOM_LEFT,\n\tS_CORNER_BOTTOM_RIGHT,\n];\nconst squareSymbols: BoxSymbols = [S_BAR_START, S_BAR_START_RIGHT, S_BAR_END, S_BAR_END_RIGHT];\n\nexport interface BoxOptions extends CommonOptions {\n\tcontentAlign?: BoxAlignment;\n\ttitleAlign?: BoxAlignment;\n\twidth?: number | 'auto';\n\ttitlePadding?: number;\n\tcontentPadding?: number;\n\trounded?: boolean;\n\tformatBorder?: (text: string) => string;\n}\n\nfunction getPaddingForLine(\n\tlineLength: number,\n\tinnerWidth: number,\n\tpadding: number,\n\tcontentAlign: BoxAlignment | undefined\n): [number, number] {\n\tlet leftPadding = padding;\n\tlet rightPadding = padding;\n\tif (contentAlign === 'center') {\n\t\tleftPadding = Math.floor((innerWidth - lineLength) / 2);\n\t} else if (contentAlign === 'right') {\n\t\tleftPadding = innerWidth - lineLength - padding;\n\t}\n\n\trightPadding = innerWidth - leftPadding - lineLength;\n\n\treturn [leftPadding, rightPadding];\n}\n\nconst defaultFormatBorder = (text: string) => text;\n\nexport const box = (message = '', title = '', opts?: BoxOptions) => {\n\tconst output: Writable = opts?.output ?? process.stdout;\n\tconst columns = getColumns(output);\n\tconst borderWidth = 1;\n\tconst borderTotalWidth = borderWidth * 2;\n\tconst titlePadding = opts?.titlePadding ?? 1;\n\tconst contentPadding = opts?.contentPadding ?? 2;\n\tconst width = opts?.width === undefined || opts.width === 'auto' ? 1 : Math.min(1, opts.width);\n\tconst hasGuide = opts?.withGuide ?? settings.withGuide;\n\tconst linePrefix = !hasGuide ? '' : `${S_BAR} `;\n\tconst formatBorder = opts?.formatBorder ?? defaultFormatBorder;\n\tconst symbols = (opts?.rounded ? roundedSymbols : squareSymbols).map(formatBorder);\n\tconst hSymbol = formatBorder(S_BAR_H);\n\tconst vSymbol = formatBorder(S_BAR);\n\tconst linePrefixWidth = stringWidth(linePrefix);\n\tconst titleWidth = stringWidth(title);\n\tconst maxBoxWidth = columns - linePrefixWidth;\n\tlet boxWidth = Math.floor(columns * width) - linePrefixWidth;\n\tif (opts?.width === 'auto') {\n\t\tconst lines = message.split('\\n');\n\t\tlet longestLine = titleWidth + titlePadding * 2;\n\t\tfor (const line of lines) {\n\t\t\tconst lineWithPadding = stringWidth(line) + contentPadding * 2;\n\t\t\tif (lineWithPadding > longestLine) {\n\t\t\t\tlongestLine = lineWithPadding;\n\t\t\t}\n\t\t}\n\t\tconst longestLineWidth = longestLine + borderTotalWidth;\n\t\tif (longestLineWidth < boxWidth) {\n\t\t\tboxWidth = longestLineWidth;\n\t\t}\n\t}\n\tif (boxWidth % 2 !== 0) {\n\t\tif (boxWidth < maxBoxWidth) {\n\t\t\tboxWidth++;\n\t\t} else {\n\t\t\tboxWidth--;\n\t\t}\n\t}\n\tconst innerWidth = boxWidth - borderTotalWidth;\n\tconst maxTitleLength = innerWidth - titlePadding * 2;\n\tconst truncatedTitle =\n\t\ttitleWidth > maxTitleLength ? `${title.slice(0, maxTitleLength - 3)}...` : title;\n\tconst [titlePaddingLeft, titlePaddingRight] = getPaddingForLine(\n\t\tstringWidth(truncatedTitle),\n\t\tinnerWidth,\n\t\ttitlePadding,\n\t\topts?.titleAlign\n\t);\n\tconst wrappedMessage = wrapAnsi(message, innerWidth - contentPadding * 2, {\n\t\thard: true,\n\t\ttrim: false,\n\t});\n\toutput.write(\n\t\t`${linePrefix}${symbols[0]}${hSymbol.repeat(titlePaddingLeft)}${truncatedTitle}${hSymbol.repeat(titlePaddingRight)}${symbols[1]}\\n`\n\t);\n\tconst wrappedLines = wrappedMessage.split('\\n');\n\tfor (const line of wrappedLines) {\n\t\tconst [leftLinePadding, rightLinePadding] = getPaddingForLine(\n\t\t\tstringWidth(line),\n\t\t\tinnerWidth,\n\t\t\tcontentPadding,\n\t\t\topts?.contentAlign\n\t\t);\n\t\toutput.write(\n\t\t\t`${linePrefix}${vSymbol}${' '.repeat(leftLinePadding)}${line}${' '.repeat(rightLinePadding)}${vSymbol}\\n`\n\t\t);\n\t}\n\toutput.write(`${linePrefix}${symbols[2]}${hSymbol.repeat(innerWidth)}${symbols[3]}\\n`);\n};\n","import { styleText } from 'node:util';\nimport { ConfirmPrompt, settings, wrapTextWithPrefix } from '@clack/core';\nimport {\n\ttype CommonOptions,\n\tS_BAR,\n\tS_BAR_END,\n\tS_RADIO_ACTIVE,\n\tS_RADIO_INACTIVE,\n\tsymbol,\n} from './common.js';\n\nexport interface ConfirmOptions extends CommonOptions {\n\tmessage: string;\n\tactive?: string;\n\tinactive?: string;\n\tinitialValue?: boolean;\n\tvertical?: boolean;\n}\nexport const confirm = (opts: ConfirmOptions) => {\n\tconst active = opts.active ?? 'Yes';\n\tconst inactive = opts.inactive ?? 'No';\n\treturn new ConfirmPrompt({\n\t\tactive,\n\t\tinactive,\n\t\tsignal: opts.signal,\n\t\tinput: opts.input,\n\t\toutput: opts.output,\n\t\tinitialValue: opts.initialValue ?? true,\n\t\trender() {\n\t\t\tconst hasGuide = opts.withGuide ?? settings.withGuide;\n\t\t\tconst titlePrefix = `${symbol(this.state)} `;\n\t\t\tconst titlePrefixBar = hasGuide ? `${styleText('gray', S_BAR)} ` : '';\n\t\t\tconst messageLines = wrapTextWithPrefix(\n\t\t\t\topts.output,\n\t\t\t\topts.message,\n\t\t\t\ttitlePrefixBar,\n\t\t\t\ttitlePrefix\n\t\t\t);\n\t\t\tconst title = `${hasGuide ? `${styleText('gray', S_BAR)}\\n` : ''}${messageLines}\\n`;\n\t\t\tconst value = this.value ? active : inactive;\n\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'submit': {\n\t\t\t\t\tconst submitPrefix = hasGuide ? `${styleText('gray', S_BAR)} ` : '';\n\t\t\t\t\treturn `${title}${submitPrefix}${styleText('dim', value)}`;\n\t\t\t\t}\n\t\t\t\tcase 'cancel': {\n\t\t\t\t\tconst cancelPrefix = hasGuide ? `${styleText('gray', S_BAR)} ` : '';\n\t\t\t\t\treturn `${title}${cancelPrefix}${styleText(['strikethrough', 'dim'], value)}${\n\t\t\t\t\t\thasGuide ? `\\n${styleText('gray', S_BAR)}` : ''\n\t\t\t\t\t}`;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\tconst defaultPrefix = hasGuide ? `${styleText('cyan', S_BAR)} ` : '';\n\t\t\t\t\tconst defaultPrefixEnd = hasGuide ? styleText('cyan', S_BAR_END) : '';\n\t\t\t\t\treturn `${title}${defaultPrefix}${\n\t\t\t\t\t\tthis.value\n\t\t\t\t\t\t\t? `${styleText('green', S_RADIO_ACTIVE)} ${active}`\n\t\t\t\t\t\t\t: `${styleText('dim', S_RADIO_INACTIVE)} ${styleText('dim', active)}`\n\t\t\t\t\t}${opts.vertical ? (hasGuide ? `\\n${styleText('cyan', S_BAR)} ` : '\\n') : ` ${styleText('dim', '/')} `}${\n\t\t\t\t\t\t!this.value\n\t\t\t\t\t\t\t? `${styleText('green', S_RADIO_ACTIVE)} ${inactive}`\n\t\t\t\t\t\t\t: `${styleText('dim', S_RADIO_INACTIVE)} ${styleText('dim', inactive)}`\n\t\t\t\t\t}\\n${defaultPrefixEnd}\\n`;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<boolean | symbol>;\n};\n","import { styleText } from 'node:util';\nimport type { DateFormat, State } from '@clack/core';\nimport { DatePrompt, settings } from '@clack/core';\nimport { type CommonOptions, S_BAR, S_BAR_END, symbol } from './common.js';\n\nexport type { DateFormat };\n\nexport interface DateOptions extends CommonOptions {\n\tmessage: string;\n\tformat?: DateFormat;\n\tlocale?: string;\n\tdefaultValue?: Date;\n\tinitialValue?: Date;\n\tminDate?: Date;\n\tmaxDate?: Date;\n\tvalidate?: (value: Date | undefined) => string | Error | undefined;\n}\n\nexport const date = (opts: DateOptions) => {\n\tconst validate = opts.validate;\n\treturn new DatePrompt({\n\t\t...opts,\n\t\tvalidate(value: Date | undefined) {\n\t\t\tif (value === undefined) {\n\t\t\t\tif (opts.defaultValue !== undefined) return undefined;\n\t\t\t\tif (validate) return validate(value);\n\t\t\t\treturn settings.date.messages.required;\n\t\t\t}\n\t\t\tconst iso = (d: Date) => d.toISOString().slice(0, 10);\n\t\t\tif (opts.minDate && iso(value) < iso(opts.minDate)) {\n\t\t\t\treturn settings.date.messages.afterMin(opts.minDate);\n\t\t\t}\n\t\t\tif (opts.maxDate && iso(value) > iso(opts.maxDate)) {\n\t\t\t\treturn settings.date.messages.beforeMax(opts.maxDate);\n\t\t\t}\n\t\t\tif (validate) return validate(value);\n\t\t\treturn undefined;\n\t\t},\n\t\trender() {\n\t\t\tconst hasGuide = (opts?.withGuide ?? settings.withGuide) !== false;\n\t\t\tconst titlePrefix = `${hasGuide ? `${styleText('gray', S_BAR)}\\n` : ''}${symbol(this.state)} `;\n\t\t\tconst title = `${titlePrefix}${opts.message}\\n`;\n\n\t\t\tconst state = this.state !== 'initial' ? this.state : 'active';\n\n\t\t\tconst userInput = renderDate(this, state);\n\t\t\tconst value = this.value instanceof Date ? this.formattedValue : '';\n\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'error': {\n\t\t\t\t\tconst errorText = this.error ? ` ${styleText('yellow', this.error)}` : '';\n\t\t\t\t\tconst bar = hasGuide ? `${styleText('yellow', S_BAR)} ` : '';\n\t\t\t\t\tconst barEnd = hasGuide ? styleText('yellow', S_BAR_END) : '';\n\t\t\t\t\treturn `${title.trim()}\\n${bar}${userInput}\\n${barEnd}${errorText}\\n`;\n\t\t\t\t}\n\t\t\t\tcase 'submit': {\n\t\t\t\t\tconst valueText = value ? ` ${styleText('dim', value)}` : '';\n\t\t\t\t\tconst bar = hasGuide ? styleText('gray', S_BAR) : '';\n\t\t\t\t\treturn `${title}${bar}${valueText}`;\n\t\t\t\t}\n\t\t\t\tcase 'cancel': {\n\t\t\t\t\tconst valueText = value ? ` ${styleText(['strikethrough', 'dim'], value)}` : '';\n\t\t\t\t\tconst bar = hasGuide ? styleText('gray', S_BAR) : '';\n\t\t\t\t\treturn `${title}${bar}${valueText}${value.trim() ? `\\n${bar}` : ''}`;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\tconst bar = hasGuide ? `${styleText('cyan', S_BAR)} ` : '';\n\t\t\t\t\tconst barEnd = hasGuide ? styleText('cyan', S_BAR_END) : '';\n\t\t\t\t\tconst inlineBar = hasGuide ? `${styleText('cyan', S_BAR)} ` : '';\n\t\t\t\t\tconst inlineError = this.inlineError\n\t\t\t\t\t\t? `\\n${inlineBar}${styleText('yellow', this.inlineError)}`\n\t\t\t\t\t\t: '';\n\t\t\t\t\treturn `${title}${bar}${userInput}${inlineError}\\n${barEnd}\\n`;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<Date | symbol>;\n};\n\nfunction renderDate(prompt: Omit<InstanceType<typeof DatePrompt>, 'prompt'>, state: State): string {\n\tconst parts = prompt.segmentValues;\n\tconst cursor = prompt.segmentCursor;\n\n\tif (state === 'submit' || state === 'cancel') {\n\t\treturn prompt.formattedValue;\n\t}\n\n\tconst sep = styleText('gray', prompt.separator);\n\treturn prompt.segments\n\t\t.map((seg, i) => {\n\t\t\tconst isActive = i === cursor.segmentIndex && !['submit', 'cancel'].includes(state);\n\t\t\tconst label = DEFAULT_LABELS[seg.type];\n\t\t\treturn renderSegment(parts[seg.type], { isActive, label });\n\t\t})\n\t\t.join(sep);\n}\n\ninterface SegmentOptions {\n\tisActive: boolean;\n\tlabel: string;\n}\nfunction renderSegment(value: string, opts: SegmentOptions): string {\n\tconst isBlank = !value || value.replace(/_/g, '') === '';\n\tif (opts.isActive) return styleText('inverse', isBlank ? opts.label : value.replace(/_/g, ' '));\n\tif (isBlank) return styleText('dim', opts.label);\n\treturn value.replace(/_/g, styleText('dim', ' '));\n}\n\nconst DEFAULT_LABELS: Record<'year' | 'month' | 'day', string> = {\n\tyear: 'yyyy',\n\tmonth: 'mm',\n\tday: 'dd',\n};\n","import { isCancel } from '@clack/core';\n\ntype Prettify<T> = {\n\t[P in keyof T]: T[P];\n} & {};\n\nexport type PromptGroupAwaitedReturn<T> = {\n\t[P in keyof T]: Exclude<Awaited<T[P]>, symbol>;\n};\n\nexport interface PromptGroupOptions<T> {\n\t/**\n\t * Control how the group can be canceled\n\t * if one of the prompts is canceled.\n\t */\n\tonCancel?: (opts: { results: Prettify<Partial<PromptGroupAwaitedReturn<T>>> }) => void;\n}\n\nexport type PromptGroup<T> = {\n\t[P in keyof T]: (opts: {\n\t\tresults: Prettify<Partial<PromptGroupAwaitedReturn<Omit<T, P>>>>;\n\t}) => undefined | Promise<T[P] | undefined>;\n};\n\n/**\n * Define a group of prompts to be displayed\n * and return a results of objects within the group\n */\nexport const group = async <T>(\n\tprompts: PromptGroup<T>,\n\topts?: PromptGroupOptions<T>\n): Promise<Prettify<PromptGroupAwaitedReturn<T>>> => {\n\tconst results = {} as any;\n\tconst promptNames = Object.keys(prompts);\n\n\tfor (const name of promptNames) {\n\t\tconst prompt = prompts[name as keyof T];\n\t\tconst result = await prompt({ results })?.catch((e) => {\n\t\t\tthrow e;\n\t\t});\n\n\t\t// Pass the results to the onCancel function\n\t\t// so the user can decide what to do with the results\n\t\t// TODO: Switch to callback within core to avoid isCancel Fn\n\t\tif (typeof opts?.onCancel === 'function' && isCancel(result)) {\n\t\t\tresults[name] = 'canceled';\n\t\t\topts.onCancel({ results });\n\t\t\tcontinue;\n\t\t}\n\n\t\tresults[name] = result;\n\t}\n\n\treturn results;\n};\n","import { styleText } from 'node:util';\nimport { GroupMultiSelectPrompt, settings, wrapTextWithPrefix } from '@clack/core';\nimport {\n\ttype CommonOptions,\n\tS_BAR,\n\tS_BAR_END,\n\tS_CHECKBOX_ACTIVE,\n\tS_CHECKBOX_INACTIVE,\n\tS_CHECKBOX_SELECTED,\n\tsymbol,\n} from './common.js';\nimport { limitOptions } from './limit-options.js';\nimport type { Option } from './select.js';\n\nexport interface GroupMultiSelectOptions<Value> extends CommonOptions {\n\tmessage: string;\n\toptions: Record<string, Option<Value>[]>;\n\tinitialValues?: Value[];\n\tmaxItems?: number;\n\trequired?: boolean;\n\tcursorAt?: Value;\n\tselectableGroups?: boolean;\n\tgroupSpacing?: number;\n}\nexport const groupMultiselect = <Value>(opts: GroupMultiSelectOptions<Value>) => {\n\tconst { selectableGroups = true, groupSpacing = 0 } = opts;\n\tconst opt = (\n\t\toption: Option<Value> & { group: string | boolean },\n\t\tstate:\n\t\t\t| 'inactive'\n\t\t\t| 'active'\n\t\t\t| 'selected'\n\t\t\t| 'active-selected'\n\t\t\t| 'group-active'\n\t\t\t| 'group-active-selected'\n\t\t\t| 'submitted'\n\t\t\t| 'cancelled',\n\t\toptions: (Option<Value> & { group: string | boolean })[] = []\n\t) => {\n\t\tconst label = option.label ?? String(option.value);\n\t\tconst isItem = typeof option.group === 'string';\n\t\tconst next = isItem && (options[options.indexOf(option) + 1] ?? { group: true });\n\t\tconst isLast = isItem && next && next.group === true;\n\t\tlet prefix = '';\n\t\tlet prefixEnd = '';\n\t\tif (isItem) {\n\t\t\tif (selectableGroups) {\n\t\t\t\tprefix = isLast ? `${S_BAR_END} ` : `${S_BAR} `;\n\t\t\t\tprefixEnd = isLast ? ` ` : `${S_BAR} `;\n\t\t\t} else {\n\t\t\t\tprefix = ' ';\n\t\t\t}\n\t\t}\n\t\tlet spacingPrefix = '';\n\t\tif (groupSpacing > 0 && !isItem) {\n\t\t\tspacingPrefix = '\\n'.repeat(groupSpacing);\n\t\t}\n\n\t\tif (state === 'active') {\n\t\t\treturn wrapTextWithPrefix(\n\t\t\t\topts.output,\n\t\t\t\t`${label}${option.hint ? ` ${styleText('dim', `(${option.hint})`)}` : ''}`,\n\t\t\t\t`${spacingPrefix}${styleText('dim', prefix)} `,\n\t\t\t\t`${spacingPrefix}${styleText('dim', prefix)}${styleText('cyan', S_CHECKBOX_ACTIVE)} `,\n\t\t\t\t`${spacingPrefix}${styleText('dim', prefixEnd)} `\n\t\t\t);\n\t\t}\n\t\tif (state === 'group-active') {\n\t\t\treturn wrapTextWithPrefix(\n\t\t\t\topts.output,\n\t\t\t\tlabel,\n\t\t\t\t`${spacingPrefix}${prefix} `,\n\t\t\t\t`${spacingPrefix}${prefix}${styleText('cyan', S_CHECKBOX_ACTIVE)} `,\n\t\t\t\t`${spacingPrefix}${prefixEnd} `,\n\t\t\t\t(str) => styleText('dim', str)\n\t\t\t);\n\t\t}\n\t\tif (state === 'group-active-selected') {\n\t\t\treturn wrapTextWithPrefix(\n\t\t\t\topts.output,\n\t\t\t\tlabel,\n\t\t\t\t`${spacingPrefix}${prefix} `,\n\t\t\t\t`${spacingPrefix}${prefix}${styleText('green', S_CHECKBOX_SELECTED)} `,\n\t\t\t\t`${spacingPrefix}${prefixEnd} `,\n\t\t\t\t(str) => styleText('dim', str)\n\t\t\t);\n\t\t}\n\t\tif (state === 'selected') {\n\t\t\tconst selectedCheckbox =\n\t\t\t\tisItem || selectableGroups ? styleText('green', S_CHECKBOX_SELECTED) : '';\n\t\t\treturn wrapTextWithPrefix(\n\t\t\t\topts.output,\n\t\t\t\t`${label}${option.hint ? ` (${option.hint})` : ''}`,\n\t\t\t\t`${spacingPrefix}${styleText('dim', prefix)} `,\n\t\t\t\t`${spacingPrefix}${styleText('dim', prefix)}${selectedCheckbox} `,\n\t\t\t\t`${spacingPrefix}${styleText('dim', prefixEnd)} `,\n\t\t\t\t(str) => styleText('dim', str)\n\t\t\t);\n\t\t}\n\t\tif (state === 'cancelled') {\n\t\t\treturn `${styleText(['strikethrough', 'dim'], label)}`;\n\t\t}\n\t\tif (state === 'active-selected') {\n\t\t\treturn wrapTextWithPrefix(\n\t\t\t\topts.output,\n\t\t\t\t`${label}${option.hint ? ` ${styleText('dim', `(${option.hint})`)}` : ''}`,\n\t\t\t\t`${spacingPrefix}${styleText('dim', prefix)} `,\n\t\t\t\t`${spacingPrefix}${styleText('dim', prefix)}${styleText('green', S_CHECKBOX_SELECTED)} `,\n\t\t\t\t`${spacingPrefix}${styleText('dim', prefixEnd)} `\n\t\t\t);\n\t\t}\n\t\tif (state === 'submitted') {\n\t\t\treturn `${styleText('dim', label)}`;\n\t\t}\n\t\tconst unselectedCheckbox =\n\t\t\tisItem || selectableGroups ? styleText('dim', S_CHECKBOX_INACTIVE) : '';\n\t\treturn wrapTextWithPrefix(\n\t\t\topts.output,\n\t\t\tlabel,\n\t\t\t`${spacingPrefix}${styleText('dim', prefix)} `,\n\t\t\t`${spacingPrefix}${styleText('dim', prefix)}${unselectedCheckbox} `,\n\t\t\t`${spacingPrefix}${styleText('dim', prefixEnd)} `,\n\t\t\t(str) => styleText('dim', str)\n\t\t);\n\t};\n\tconst required = opts.required ?? true;\n\n\treturn new GroupMultiSelectPrompt({\n\t\toptions: opts.options,\n\t\tsignal: opts.signal,\n\t\tinput: opts.input,\n\t\toutput: opts.output,\n\t\tinitialValues: opts.initialValues,\n\t\trequired,\n\t\tcursorAt: opts.cursorAt,\n\t\tselectableGroups,\n\t\tvalidate(selected: Value[] | undefined) {\n\t\t\tif (required && (selected === undefined || selected.length === 0))\n\t\t\t\treturn `Please select at least one option.\\n${styleText(\n\t\t\t\t\t'reset',\n\t\t\t\t\tstyleText(\n\t\t\t\t\t\t'dim',\n\t\t\t\t\t\t`Press ${styleText(['gray', 'bgWhite', 'inverse'], ' space ')} to select, ${styleText(\n\t\t\t\t\t\t\t'gray',\n\t\t\t\t\t\t\tstyleText(['bgWhite', 'inverse'], ' enter ')\n\t\t\t\t\t\t)} to submit`\n\t\t\t\t\t)\n\t\t\t\t)}`;\n\t\t},\n\t\trender() {\n\t\t\tconst hasGuide = opts.withGuide ?? settings.withGuide;\n\t\t\tconst title = `${hasGuide ? `${styleText('gray', S_BAR)}\\n` : ''}${symbol(this.state)} ${opts.message}\\n`;\n\t\t\tconst value = this.value ?? [];\n\n\t\t\tconst styleOption = (\n\t\t\t\toption: Option<Value> & { group: string | boolean },\n\t\t\t\tactive: boolean\n\t\t\t) => {\n\t\t\t\tconst options = this.options;\n\t\t\t\tconst selected =\n\t\t\t\t\tvalue.includes(option.value) ||\n\t\t\t\t\t(option.group === true && this.isGroupSelected(`${option.value}`));\n\t\t\t\tconst groupActive =\n\t\t\t\t\t!active &&\n\t\t\t\t\ttypeof option.group === 'string' &&\n\t\t\t\t\tthis.options[this.cursor].value === option.group;\n\t\t\t\tif (groupActive) {\n\t\t\t\t\treturn opt(option, selected ? 'group-active-selected' : 'group-active', options);\n\t\t\t\t}\n\t\t\t\tif (active && selected) {\n\t\t\t\t\treturn opt(option, 'active-selected', options);\n\t\t\t\t}\n\t\t\t\tif (selected) {\n\t\t\t\t\treturn opt(option, 'selected', options);\n\t\t\t\t}\n\t\t\t\treturn opt(option, active ? 'active' : 'inactive', options);\n\t\t\t};\n\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'submit': {\n\t\t\t\t\tconst selectedOptions = this.options\n\t\t\t\t\t\t.filter(({ value: optionValue }) => value.includes(optionValue))\n\t\t\t\t\t\t.map((option) => opt(option, 'submitted'));\n\t\t\t\t\tconst optionsText =\n\t\t\t\t\t\tselectedOptions.length === 0 ? '' : ` ${selectedOptions.join(styleText('dim', ', '))}`;\n\t\t\t\t\treturn `${title}${hasGuide ? styleText('gray', S_BAR) : ''}${optionsText}`;\n\t\t\t\t}\n\t\t\t\tcase 'cancel': {\n\t\t\t\t\tconst label = this.options\n\t\t\t\t\t\t.filter(({ value: optionValue }) => value.includes(optionValue))\n\t\t\t\t\t\t.map((option) => opt(option, 'cancelled'))\n\t\t\t\t\t\t.join(styleText('dim', ', '));\n\t\t\t\t\treturn `${title}${hasGuide ? `${styleText('gray', S_BAR)} ` : ''}${\n\t\t\t\t\t\tlabel.trim() ? `${label}${hasGuide ? `\\n${styleText('gray', S_BAR)}` : ''}` : ''\n\t\t\t\t\t}`;\n\t\t\t\t}\n\t\t\t\tcase 'error': {\n\t\t\t\t\tconst guidePrefix = hasGuide ? `${styleText('yellow', S_BAR)} ` : '';\n\t\t\t\t\tconst footer = this.error\n\t\t\t\t\t\t.split('\\n')\n\t\t\t\t\t\t.map((ln, i) =>\n\t\t\t\t\t\t\ti === 0\n\t\t\t\t\t\t\t\t? `${hasGuide ? `${styleText('yellow', S_BAR_END)} ` : ''}${styleText('yellow', ln)}`\n\t\t\t\t\t\t\t\t: ` ${ln}`\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join('\\n');\n\t\t\t\t\t// Calculate rowPadding: title lines + footer lines (error message + trailing newline)\n\t\t\t\t\tconst titleLineCount = title.split('\\n').length;\n\t\t\t\t\tconst footerLineCount = footer.split('\\n').length + 1; // footer + trailing newline\n\t\t\t\t\tconst optionsText = limitOptions({\n\t\t\t\t\t\toutput: opts.output,\n\t\t\t\t\t\toptions: this.options,\n\t\t\t\t\t\tcursor: this.cursor,\n\t\t\t\t\t\tmaxItems: opts.maxItems,\n\t\t\t\t\t\tcolumnPadding: guidePrefix.length,\n\t\t\t\t\t\trowPadding: titleLineCount + footerLineCount,\n\t\t\t\t\t\tstyle: styleOption,\n\t\t\t\t\t}).join(`\\n${guidePrefix}`);\n\t\t\t\t\treturn `${title}${guidePrefix}${optionsText}\\n${footer}\\n`;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\tconst guidePrefix = hasGuide ? `${styleText('cyan', S_BAR)} ` : '';\n\t\t\t\t\t// Calculate rowPadding: title lines + footer lines (S_BAR_END + trailing newline)\n\t\t\t\t\tconst titleLineCount = title.split('\\n').length;\n\t\t\t\t\tconst footerLineCount = (hasGuide ? 1 : 0) + 1; // guide line + trailing newline\n\t\t\t\t\tconst optionsText = limitOptions({\n\t\t\t\t\t\toutput: opts.output,\n\t\t\t\t\t\toptions: this.options,\n\t\t\t\t\t\tcursor: this.cursor,\n\t\t\t\t\t\tmaxItems: opts.maxItems,\n\t\t\t\t\t\tcolumnPadding: guidePrefix.length,\n\t\t\t\t\t\trowPadding: titleLineCount + footerLineCount,\n\t\t\t\t\t\tstyle: styleOption,\n\t\t\t\t\t}).join(`\\n${guidePrefix}`);\n\t\t\t\t\treturn `${title}${guidePrefix}${optionsText}\\n${\n\t\t\t\t\t\thasGuide ? styleText('cyan', S_BAR_END) : ''\n\t\t\t\t\t}\\n`;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<Value[] | symbol>;\n};\n","import { styleText } from 'node:util';\nimport { settings } from '@clack/core';\nimport {\n\ttype CommonOptions,\n\tS_BAR,\n\tS_ERROR,\n\tS_INFO,\n\tS_STEP_SUBMIT,\n\tS_SUCCESS,\n\tS_WARN,\n} from './common.js';\n\nexport interface LogMessageOptions extends CommonOptions {\n\tsymbol?: string;\n\tspacing?: number;\n\tsecondarySymbol?: string;\n}\n\nexport const log = {\n\tmessage: (\n\t\tmessage: string | string[] = [],\n\t\t{\n\t\t\tsymbol = styleText('gray', S_BAR),\n\t\t\tsecondarySymbol = styleText('gray', S_BAR),\n\t\t\toutput = process.stdout,\n\t\t\tspacing = 1,\n\t\t\twithGuide,\n\t\t}: LogMessageOptions = {}\n\t) => {\n\t\tconst parts: string[] = [];\n\t\tconst hasGuide = withGuide ?? settings.withGuide;\n\t\tconst spacingString = !hasGuide ? '' : secondarySymbol;\n\t\tconst prefix = !hasGuide ? '' : `${symbol} `;\n\t\tconst secondaryPrefix = !hasGuide ? '' : `${secondarySymbol} `;\n\n\t\tfor (let i = 0; i < spacing; i++) {\n\t\t\tparts.push(spacingString);\n\t\t}\n\n\t\tconst messageParts = Array.isArray(message) ? message : message.split('\\n');\n\t\tif (messageParts.length > 0) {\n\t\t\tconst [firstLine, ...lines] = messageParts;\n\t\t\tif (firstLine.length > 0) {\n\t\t\t\tparts.push(`${prefix}${firstLine}`);\n\t\t\t} else {\n\t\t\t\tparts.push(hasGuide ? symbol : '');\n\t\t\t}\n\t\t\tfor (const ln of lines) {\n\t\t\t\tif (ln.length > 0) {\n\t\t\t\t\tparts.push(`${secondaryPrefix}${ln}`);\n\t\t\t\t} else {\n\t\t\t\t\tparts.push(hasGuide ? secondarySymbol : '');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\toutput.write(`${parts.join('\\n')}\\n`);\n\t},\n\tinfo: (message: string, opts?: LogMessageOptions) => {\n\t\tlog.message(message, { ...opts, symbol: styleText('blue', S_INFO) });\n\t},\n\tsuccess: (message: string, opts?: LogMessageOptions) => {\n\t\tlog.message(message, { ...opts, symbol: styleText('green', S_SUCCESS) });\n\t},\n\tstep: (message: string, opts?: LogMessageOptions) => {\n\t\tlog.message(message, { ...opts, symbol: styleText('green', S_STEP_SUBMIT) });\n\t},\n\twarn: (message: string, opts?: LogMessageOptions) => {\n\t\tlog.message(message, { ...opts, symbol: styleText('yellow', S_WARN) });\n\t},\n\t/** alias for `log.warn()`. */\n\twarning: (message: string, opts?: LogMessageOptions) => {\n\t\tlog.warn(message, opts);\n\t},\n\terror: (message: string, opts?: LogMessageOptions) => {\n\t\tlog.message(message, { ...opts, symbol: styleText('red', S_ERROR) });\n\t},\n};\n","import type { Writable } from 'node:stream';\nimport { styleText } from 'node:util';\nimport { settings } from '@clack/core';\nimport { type CommonOptions, S_BAR, S_BAR_END, S_BAR_START } from './common.js';\n\nexport const cancel = (message = '', opts?: CommonOptions) => {\n\tconst output: Writable = opts?.output ?? process.stdout;\n\tconst hasGuide = opts?.withGuide ?? settings.withGuide;\n\tconst prefix = hasGuide ? `${styleText('gray', S_BAR_END)} ` : '';\n\toutput.write(`${prefix}${styleText('red', message)}\\n\\n`);\n};\n\nexport const intro = (title = '', opts?: CommonOptions) => {\n\tconst output: Writable = opts?.output ?? process.stdout;\n\tconst hasGuide = opts?.withGuide ?? settings.withGuide;\n\tconst prefix = hasGuide ? `${styleText('gray', S_BAR_START)} ` : '';\n\toutput.write(`${prefix}${title}\\n`);\n};\n\nexport const outro = (message = '', opts?: CommonOptions) => {\n\tconst output: Writable = opts?.output ?? process.stdout;\n\tconst hasGuide = opts?.withGuide ?? settings.withGuide;\n\tconst prefix = hasGuide ? `${styleText('gray', S_BAR)}\\n${styleText('gray', S_BAR_END)} ` : '';\n\toutput.write(`${prefix}${message}\\n\\n`);\n};\n","import { styleText } from 'node:util';\nimport { MultiLinePrompt, settings, wrapTextWithPrefix } from '@clack/core';\nimport { S_BAR, S_BAR_END, symbol } from './common.js';\nimport type { TextOptions } from './text.js';\n\n/**\n * Options for the {@link multiline} prompt\n */\nexport interface MultiLineOptions extends TextOptions {\n\t/**\n\t * When enabled it shows a `[ submit ]` button that can be focused with tab.\n\t * By default, pressing `Enter` twice submits the input\n\t *\n\t * @default false\n\t */\n\tshowSubmit?: boolean;\n}\n\n/**\n * The multi-line prompt accepts multiple lines of text input.\n * By default, pressing `Enter` twice submits the input.\n *\n * @see https://bomb.sh/docs/clack/packages/prompts/#multi-line-text\n *\n * @example\n * ```ts\n * import { multiline } from '@clack/prompts';\n *\n * const bio = await multiline({\n * message: 'Enter your bio',\n * placeholder: 'Tell us about yourself...',\n * showSubmit: true,\n * });\n * ```\n */\nexport const multiline = (opts: MultiLineOptions) => {\n\treturn new MultiLinePrompt({\n\t\tvalidate: opts.validate,\n\t\tplaceholder: opts.placeholder,\n\t\tdefaultValue: opts.defaultValue,\n\t\tinitialValue: opts.initialValue,\n\t\tshowSubmit: opts.showSubmit,\n\t\toutput: opts.output,\n\t\tsignal: opts.signal,\n\t\tinput: opts.input,\n\t\trender() {\n\t\t\tconst hasGuide = opts?.withGuide ?? settings.withGuide;\n\t\t\tconst titlePrefix = `${hasGuide ? `${styleText('gray', S_BAR)}\\n` : ''}${symbol(this.state)} `;\n\t\t\tconst title = `${titlePrefix}${opts.message}\\n`;\n\t\t\tconst placeholder = opts.placeholder\n\t\t\t\t? styleText('inverse', opts.placeholder[0]) + styleText('dim', opts.placeholder.slice(1))\n\t\t\t\t: styleText(['inverse', 'hidden'], '_');\n\t\t\tconst userInput = !this.userInput ? placeholder : this.userInputWithCursor;\n\t\t\tconst value = this.value ?? '';\n\t\t\tconst submitButton = opts.showSubmit\n\t\t\t\t? `\\n ${styleText(this.focused === 'submit' ? 'cyan' : 'dim', '[ submit ]')}`\n\t\t\t\t: '';\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'error': {\n\t\t\t\t\tconst errorPrefix = `${styleText('yellow', S_BAR)} `;\n\t\t\t\t\tconst lines = hasGuide\n\t\t\t\t\t\t? wrapTextWithPrefix(opts.output, userInput, errorPrefix, undefined)\n\t\t\t\t\t\t: userInput;\n\t\t\t\t\tconst errorPrefixEnd = styleText('yellow', S_BAR_END);\n\t\t\t\t\treturn `${title}${lines}\\n${errorPrefixEnd} ${styleText('yellow', this.error)}${submitButton}\\n`;\n\t\t\t\t}\n\t\t\t\tcase 'submit': {\n\t\t\t\t\tconst submitPrefix = `${styleText('gray', S_BAR)} `;\n\t\t\t\t\tconst lines = hasGuide\n\t\t\t\t\t\t? wrapTextWithPrefix(opts.output, value, submitPrefix, undefined, undefined, (str) =>\n\t\t\t\t\t\t\t\tstyleText('dim', str)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: value\n\t\t\t\t\t\t\t? styleText('dim', value)\n\t\t\t\t\t\t\t: '';\n\t\t\t\t\treturn `${title}${lines}`;\n\t\t\t\t}\n\t\t\t\tcase 'cancel': {\n\t\t\t\t\tconst cancelPrefix = `${styleText('gray', S_BAR)} `;\n\t\t\t\t\tconst lines = hasGuide\n\t\t\t\t\t\t? wrapTextWithPrefix(opts.output, value, cancelPrefix, undefined, undefined, (str) =>\n\t\t\t\t\t\t\t\tstyleText(['strikethrough', 'dim'], str)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: value\n\t\t\t\t\t\t\t? styleText(['strikethrough', 'dim'], value)\n\t\t\t\t\t\t\t: '';\n\t\t\t\t\treturn `${title}${lines}`;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\tconst defaultPrefix = hasGuide ? `${styleText('cyan', S_BAR)} ` : '';\n\t\t\t\t\tconst defaultPrefixEnd = hasGuide ? styleText('cyan', S_BAR_END) : '';\n\t\t\t\t\tconst lines = hasGuide\n\t\t\t\t\t\t? wrapTextWithPrefix(opts.output, userInput, defaultPrefix)\n\t\t\t\t\t\t: userInput;\n\t\t\t\t\treturn `${title}${lines}\\n${defaultPrefixEnd}${submitButton}\\n`;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<string | symbol>;\n};\n","import { styleText } from 'node:util';\nimport { MultiSelectPrompt, settings, wrapTextWithPrefix } from '@clack/core';\nimport {\n\ttype CommonOptions,\n\tS_BAR,\n\tS_BAR_END,\n\tS_CHECKBOX_ACTIVE,\n\tS_CHECKBOX_INACTIVE,\n\tS_CHECKBOX_SELECTED,\n\tsymbol,\n\tsymbolBar,\n} from './common.js';\nimport { limitOptions } from './limit-options.js';\nimport type { Option } from './select.js';\n\nexport interface MultiSelectOptions<Value> extends CommonOptions {\n\tmessage: string;\n\toptions: Option<Value>[];\n\tinitialValues?: Value[];\n\tmaxItems?: number;\n\trequired?: boolean;\n\tcursorAt?: Value;\n}\nconst computeLabel = (label: string, format: (text: string) => string) => {\n\treturn label\n\t\t.split('\\n')\n\t\t.map((line) => format(line))\n\t\t.join('\\n');\n};\n\nexport const multiselect = <Value>(opts: MultiSelectOptions<Value>) => {\n\tconst opt = (\n\t\toption: Option<Value>,\n\t\tstate:\n\t\t\t| 'inactive'\n\t\t\t| 'active'\n\t\t\t| 'selected'\n\t\t\t| 'active-selected'\n\t\t\t| 'submitted'\n\t\t\t| 'cancelled'\n\t\t\t| 'disabled'\n\t) => {\n\t\tconst label = option.label ?? String(option.value);\n\t\tif (state === 'disabled') {\n\t\t\treturn `${styleText('gray', S_CHECKBOX_INACTIVE)} ${computeLabel(label, (str) => styleText(['strikethrough', 'gray'], str))}${\n\t\t\t\toption.hint ? ` ${styleText('dim', `(${option.hint ?? 'disabled'})`)}` : ''\n\t\t\t}`;\n\t\t}\n\t\tif (state === 'active') {\n\t\t\treturn `${styleText('cyan', S_CHECKBOX_ACTIVE)} ${label}${\n\t\t\t\toption.hint ? ` ${styleText('dim', `(${option.hint})`)}` : ''\n\t\t\t}`;\n\t\t}\n\t\tif (state === 'selected') {\n\t\t\treturn `${styleText('green', S_CHECKBOX_SELECTED)} ${computeLabel(label, (text) => styleText('dim', text))}${\n\t\t\t\toption.hint ? ` ${styleText('dim', `(${option.hint})`)}` : ''\n\t\t\t}`;\n\t\t}\n\t\tif (state === 'cancelled') {\n\t\t\treturn `${computeLabel(label, (text) => styleText(['strikethrough', 'dim'], text))}`;\n\t\t}\n\t\tif (state === 'active-selected') {\n\t\t\treturn `${styleText('green', S_CHECKBOX_SELECTED)} ${label}${\n\t\t\t\toption.hint ? ` ${styleText('dim', `(${option.hint})`)}` : ''\n\t\t\t}`;\n\t\t}\n\t\tif (state === 'submitted') {\n\t\t\treturn `${computeLabel(label, (text) => styleText('dim', text))}`;\n\t\t}\n\t\treturn `${styleText('dim', S_CHECKBOX_INACTIVE)} ${computeLabel(label, (text) => styleText('dim', text))}`;\n\t};\n\tconst required = opts.required ?? true;\n\n\treturn new MultiSelectPrompt({\n\t\toptions: opts.options,\n\t\tsignal: opts.signal,\n\t\tinput: opts.input,\n\t\toutput: opts.output,\n\t\tinitialValues: opts.initialValues,\n\t\trequired,\n\t\tcursorAt: opts.cursorAt,\n\t\tvalidate(selected: Value[] | undefined) {\n\t\t\tif (required && (selected === undefined || selected.length === 0))\n\t\t\t\treturn `Please select at least one option.\\n${styleText(\n\t\t\t\t\t'reset',\n\t\t\t\t\tstyleText(\n\t\t\t\t\t\t'dim',\n\t\t\t\t\t\t`Press ${styleText(['gray', 'bgWhite', 'inverse'], ' space ')} to select, ${styleText(\n\t\t\t\t\t\t\t'gray',\n\t\t\t\t\t\t\tstyleText('bgWhite', styleText('inverse', ' enter '))\n\t\t\t\t\t\t)} to submit`\n\t\t\t\t\t)\n\t\t\t\t)}`;\n\t\t},\n\t\trender() {\n\t\t\tconst hasGuide = opts.withGuide ?? settings.withGuide;\n\t\t\tconst wrappedMessage = wrapTextWithPrefix(\n\t\t\t\topts.output,\n\t\t\t\topts.message,\n\t\t\t\thasGuide ? `${symbolBar(this.state)} ` : '',\n\t\t\t\t`${symbol(this.state)} `\n\t\t\t);\n\t\t\tconst title = `${hasGuide ? `${styleText('gray', S_BAR)}\\n` : ''}${wrappedMessage}\\n`;\n\t\t\tconst value = this.value ?? [];\n\n\t\t\tconst styleOption = (option: Option<Value>, active: boolean) => {\n\t\t\t\tif (option.disabled) {\n\t\t\t\t\treturn opt(option, 'disabled');\n\t\t\t\t}\n\t\t\t\tconst selected = value.includes(option.value);\n\t\t\t\tif (active && selected) {\n\t\t\t\t\treturn opt(option, 'active-selected');\n\t\t\t\t}\n\t\t\t\tif (selected) {\n\t\t\t\t\treturn opt(option, 'selected');\n\t\t\t\t}\n\t\t\t\treturn opt(option, active ? 'active' : 'inactive');\n\t\t\t};\n\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'submit': {\n\t\t\t\t\tconst submitText =\n\t\t\t\t\t\tthis.options\n\t\t\t\t\t\t\t.filter(({ value: optionValue }) => value.includes(optionValue))\n\t\t\t\t\t\t\t.map((option) => opt(option, 'submitted'))\n\t\t\t\t\t\t\t.join(styleText('dim', ', ')) || styleText('dim', 'none');\n\t\t\t\t\tconst wrappedSubmitText = wrapTextWithPrefix(\n\t\t\t\t\t\topts.output,\n\t\t\t\t\t\tsubmitText,\n\t\t\t\t\t\thasGuide ? `${styleText('gray', S_BAR)} ` : ''\n\t\t\t\t\t);\n\t\t\t\t\treturn `${title}${wrappedSubmitText}`;\n\t\t\t\t}\n\t\t\t\tcase 'cancel': {\n\t\t\t\t\tconst label = this.options\n\t\t\t\t\t\t.filter(({ value: optionValue }) => value.includes(optionValue))\n\t\t\t\t\t\t.map((option) => opt(option, 'cancelled'))\n\t\t\t\t\t\t.join(styleText('dim', ', '));\n\t\t\t\t\tif (label.trim() === '') {\n\t\t\t\t\t\treturn `${title}${styleText('gray', S_BAR)}`;\n\t\t\t\t\t}\n\t\t\t\t\tconst wrappedLabel = wrapTextWithPrefix(\n\t\t\t\t\t\topts.output,\n\t\t\t\t\t\tlabel,\n\t\t\t\t\t\thasGuide ? `${styleText('gray', S_BAR)} ` : ''\n\t\t\t\t\t);\n\t\t\t\t\treturn `${title}${wrappedLabel}${hasGuide ? `\\n${styleText('gray', S_BAR)}` : ''}`;\n\t\t\t\t}\n\t\t\t\tcase 'error': {\n\t\t\t\t\tconst prefix = hasGuide ? `${styleText('yellow', S_BAR)} ` : '';\n\t\t\t\t\tconst footer = this.error\n\t\t\t\t\t\t.split('\\n')\n\t\t\t\t\t\t.map((ln, i) =>\n\t\t\t\t\t\t\ti === 0\n\t\t\t\t\t\t\t\t? `${hasGuide ? `${styleText('yellow', S_BAR_END)} ` : ''}${styleText('yellow', ln)}`\n\t\t\t\t\t\t\t\t: ` ${ln}`\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join('\\n');\n\t\t\t\t\t// Calculate rowPadding: title lines + footer lines (error message + trailing newline)\n\t\t\t\t\tconst titleLineCount = title.split('\\n').length;\n\t\t\t\t\tconst footerLineCount = footer.split('\\n').length + 1; // footer + trailing newline\n\t\t\t\t\treturn `${title}${prefix}${limitOptions({\n\t\t\t\t\t\toutput: opts.output,\n\t\t\t\t\t\toptions: this.options,\n\t\t\t\t\t\tcursor: this.cursor,\n\t\t\t\t\t\tmaxItems: opts.maxItems,\n\t\t\t\t\t\tcolumnPadding: prefix.length,\n\t\t\t\t\t\trowPadding: titleLineCount + footerLineCount,\n\t\t\t\t\t\tstyle: styleOption,\n\t\t\t\t\t}).join(`\\n${prefix}`)}\\n${footer}\\n`;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\tconst prefix = hasGuide ? `${styleText('cyan', S_BAR)} ` : '';\n\t\t\t\t\t// Calculate rowPadding: title lines + footer lines (S_BAR_END + trailing newline)\n\t\t\t\t\tconst titleLineCount = title.split('\\n').length;\n\t\t\t\t\tconst footerLineCount = hasGuide ? 2 : 1; // S_BAR_END + trailing newline\n\t\t\t\t\treturn `${title}${prefix}${limitOptions({\n\t\t\t\t\t\toutput: opts.output,\n\t\t\t\t\t\toptions: this.options,\n\t\t\t\t\t\tcursor: this.cursor,\n\t\t\t\t\t\tmaxItems: opts.maxItems,\n\t\t\t\t\t\tcolumnPadding: prefix.length,\n\t\t\t\t\t\trowPadding: titleLineCount + footerLineCount,\n\t\t\t\t\t\tstyle: styleOption,\n\t\t\t\t\t}).join(`\\n${prefix}`)}\\n${hasGuide ? styleText('cyan', S_BAR_END) : ''}\\n`;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<Value[] | symbol>;\n};\n","import process from 'node:process';\nimport type { Writable } from 'node:stream';\nimport { styleText } from 'node:util';\nimport { getColumns, settings } from '@clack/core';\nimport stringWidth from 'fast-string-width';\nimport { type Options as WrapAnsiOptions, wrapAnsi } from 'fast-wrap-ansi';\nimport {\n\ttype CommonOptions,\n\tS_BAR,\n\tS_BAR_H,\n\tS_CONNECT_LEFT,\n\tS_CORNER_BOTTOM_LEFT,\n\tS_CORNER_BOTTOM_RIGHT,\n\tS_CORNER_TOP_RIGHT,\n\tS_STEP_SUBMIT,\n} from './common.js';\n\ntype FormatFn = (line: string) => string;\nexport interface NoteOptions extends CommonOptions {\n\tformat?: FormatFn;\n}\n\nconst defaultNoteFormatter = (line: string): string => styleText('dim', line);\n\nconst wrapWithFormat = (message: string, width: number, format: FormatFn): string => {\n\tconst opts: WrapAnsiOptions = {\n\t\thard: true,\n\t\ttrim: false,\n\t};\n\tconst wrapMsg = wrapAnsi(message, width, opts).split('\\n');\n\tconst maxWidthNormal = wrapMsg.reduce((sum, ln) => Math.max(stringWidth(ln), sum), 0);\n\tconst maxWidthFormat = wrapMsg.map(format).reduce((sum, ln) => Math.max(stringWidth(ln), sum), 0);\n\tconst wrapWidth = width - (maxWidthFormat - maxWidthNormal);\n\treturn wrapAnsi(message, wrapWidth, opts);\n};\n\nexport const note = (message = '', title = '', opts?: NoteOptions) => {\n\tconst output: Writable = opts?.output ?? process.stdout;\n\tconst hasGuide = opts?.withGuide ?? settings.withGuide;\n\tconst format = opts?.format ?? defaultNoteFormatter;\n\tconst wrapMsg = wrapWithFormat(message, getColumns(output) - 6, format);\n\tconst lines = ['', ...wrapMsg.split('\\n').map(format), ''];\n\tconst titleLen = stringWidth(title);\n\tconst len =\n\t\tMath.max(\n\t\t\tlines.reduce((sum, ln) => {\n\t\t\t\tconst width = stringWidth(ln);\n\t\t\t\treturn width > sum ? width : sum;\n\t\t\t}, 0),\n\t\t\ttitleLen\n\t\t) + 2;\n\tconst msg = lines\n\t\t.map(\n\t\t\t(ln) =>\n\t\t\t\t`${styleText('gray', S_BAR)} ${ln}${' '.repeat(len - stringWidth(ln))}${styleText('gray', S_BAR)}`\n\t\t)\n\t\t.join('\\n');\n\tconst leadingBorder = hasGuide ? `${styleText('gray', S_BAR)}\\n` : '';\n\tconst bottomLeft = hasGuide ? S_CONNECT_LEFT : S_CORNER_BOTTOM_LEFT;\n\toutput.write(\n\t\t`${leadingBorder}${styleText('green', S_STEP_SUBMIT)} ${styleText('reset', title)} ${styleText(\n\t\t\t'gray',\n\t\t\tS_BAR_H.repeat(Math.max(len - titleLen - 1, 1)) + S_CORNER_TOP_RIGHT\n\t\t)}\\n${msg}\\n${styleText('gray', bottomLeft + S_BAR_H.repeat(len + 2) + S_CORNER_BOTTOM_RIGHT)}\\n`\n\t);\n};\n","import { styleText } from 'node:util';\nimport { PasswordPrompt, settings } from '@clack/core';\nimport { type CommonOptions, S_BAR, S_BAR_END, S_PASSWORD_MASK, symbol } from './common.js';\n\n/**\n * Options for the {@link password} prompt\n */\nexport interface PasswordOptions extends CommonOptions {\n\t/**\n\t * The prompt message or question shown to the user above the input.\n\t */\n\tmessage: string;\n\n\t/**\n\t * Character to use for masking input.\n\t * @default ▪/•\n\t */\n\tmask?: string;\n\n\t/**\n\t * A function that validates user input. Return a `string` or `Error` to show as a\n\t * validation error, or `undefined` to accept the result.\n\t */\n\tvalidate?: (value: string | undefined) => string | Error | undefined;\n\n\t/**\n\t * When enabled it causes the input to be cleared if/when validation fails.\n\t * @default false\n\t */\n\tclearOnError?: boolean;\n}\n\n/**\n * The password prompt behaves like the {@link text} prompt, but the input is masked.\n *\n * @see https://bomb.sh/docs/clack/packages/prompts/#password-input\n *\n * @example\n * ```ts\n * import { password } from '@clack/prompts';\n *\n * const result = await password({\n * message: 'Enter your password',\n * });\n * ```\n */\nexport const password = (opts: PasswordOptions) => {\n\treturn new PasswordPrompt({\n\t\tvalidate: opts.validate,\n\t\tmask: opts.mask ?? S_PASSWORD_MASK,\n\t\tsignal: opts.signal,\n\t\tinput: opts.input,\n\t\toutput: opts.output,\n\t\trender() {\n\t\t\tconst hasGuide = opts.withGuide ?? settings.withGuide;\n\t\t\tconst title = `${hasGuide ? `${styleText('gray', S_BAR)}\\n` : ''}${symbol(this.state)} ${opts.message}\\n`;\n\t\t\tconst userInput = this.userInputWithCursor;\n\t\t\tconst masked = this.masked;\n\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'error': {\n\t\t\t\t\tconst errorPrefix = hasGuide ? `${styleText('yellow', S_BAR)} ` : '';\n\t\t\t\t\tconst errorPrefixEnd = hasGuide ? `${styleText('yellow', S_BAR_END)} ` : '';\n\t\t\t\t\tconst maskedText = masked ?? '';\n\t\t\t\t\tif (opts.clearOnError) {\n\t\t\t\t\t\tthis.clear();\n\t\t\t\t\t}\n\t\t\t\t\treturn `${title.trim()}\\n${errorPrefix}${maskedText}\\n${errorPrefixEnd}${styleText('yellow', this.error)}\\n`;\n\t\t\t\t}\n\t\t\t\tcase 'submit': {\n\t\t\t\t\tconst submitPrefix = hasGuide ? `${styleText('gray', S_BAR)} ` : '';\n\t\t\t\t\tconst maskedText = masked ? styleText('dim', masked) : '';\n\t\t\t\t\treturn `${title}${submitPrefix}${maskedText}`;\n\t\t\t\t}\n\t\t\t\tcase 'cancel': {\n\t\t\t\t\tconst cancelPrefix = hasGuide ? `${styleText('gray', S_BAR)} ` : '';\n\t\t\t\t\tconst maskedText = masked ? styleText(['strikethrough', 'dim'], masked) : '';\n\t\t\t\t\treturn `${title}${cancelPrefix}${maskedText}${\n\t\t\t\t\t\tmasked && hasGuide ? `\\n${styleText('gray', S_BAR)}` : ''\n\t\t\t\t\t}`;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\tconst defaultPrefix = hasGuide ? `${styleText('cyan', S_BAR)} ` : '';\n\t\t\t\t\tconst defaultPrefixEnd = hasGuide ? styleText('cyan', S_BAR_END) : '';\n\t\t\t\t\treturn `${title}${defaultPrefix}${userInput}\\n${defaultPrefixEnd}\\n`;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<string | symbol>;\n};\n","import { existsSync, lstatSync, readdirSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { autocomplete } from './autocomplete.js';\nimport type { CommonOptions } from './common.js';\n\nexport interface PathOptions extends CommonOptions {\n\troot?: string;\n\tdirectory?: boolean;\n\tinitialValue?: string;\n\tmessage: string;\n\tvalidate?: (value: string | undefined) => string | Error | undefined;\n}\n\nexport const path = (opts: PathOptions) => {\n\tconst validate = opts.validate;\n\n\treturn autocomplete({\n\t\t...opts,\n\t\tinitialUserInput: opts.initialValue ?? opts.root ?? process.cwd(),\n\t\tmaxItems: 5,\n\t\tvalidate(value) {\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\t// Shouldn't ever happen since we don't enable `multiple: true`\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tif (!value) {\n\t\t\t\treturn 'Please select a path';\n\t\t\t}\n\t\t\tif (validate) {\n\t\t\t\treturn validate(value);\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t\toptions() {\n\t\t\tconst userInput = this.userInput;\n\t\t\tif (userInput === '') {\n\t\t\t\treturn [];\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tlet searchPath: string;\n\n\t\t\t\tif (!existsSync(userInput)) {\n\t\t\t\t\tsearchPath = dirname(userInput);\n\t\t\t\t} else {\n\t\t\t\t\tconst stat = lstatSync(userInput);\n\t\t\t\t\tif (stat.isDirectory() && (!opts.directory || userInput.endsWith('/'))) {\n\t\t\t\t\t\tsearchPath = userInput;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsearchPath = dirname(userInput);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Strip trailing slash so startsWith matches the directory itself among its siblings\n\t\t\t\tconst prefix =\n\t\t\t\t\tuserInput.length > 1 && userInput.endsWith('/') ? userInput.slice(0, -1) : userInput;\n\n\t\t\t\tconst items = readdirSync(searchPath)\n\t\t\t\t\t.map((item) => {\n\t\t\t\t\t\tconst path = join(searchPath, item);\n\t\t\t\t\t\tconst stats = lstatSync(path);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tname: item,\n\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\tisDirectory: stats.isDirectory(),\n\t\t\t\t\t\t};\n\t\t\t\t\t})\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t({ path, isDirectory }) => path.startsWith(prefix) && (isDirectory || !opts.directory)\n\t\t\t\t\t);\n\n\t\t\t\treturn items.map((item) => ({\n\t\t\t\t\tvalue: item.path,\n\t\t\t\t}));\n\t\t\t} catch (_e) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t},\n\t});\n};\n","import { styleText } from 'node:util';\nimport { block, getColumns, settings } from '@clack/core';\nimport { wrapAnsi } from 'fast-wrap-ansi';\nimport { cursor, erase } from 'sisteransi';\nimport {\n\ttype CommonOptions,\n\tisCI as isCIFn,\n\tS_BAR,\n\tS_STEP_CANCEL,\n\tS_STEP_ERROR,\n\tS_STEP_SUBMIT,\n\tunicode,\n} from './common.js';\n\nexport interface SpinnerOptions extends CommonOptions {\n\tindicator?: 'dots' | 'timer';\n\tonCancel?: () => void;\n\tcancelMessage?: string;\n\terrorMessage?: string;\n\tframes?: string[];\n\tdelay?: number;\n\tstyleFrame?: (frame: string) => string;\n}\n\nexport interface SpinnerResult {\n\tstart(msg?: string): void;\n\tstop(msg?: string): void;\n\tcancel(msg?: string): void;\n\terror(msg?: string): void;\n\tmessage(msg?: string): void;\n\tclear(): void;\n\treadonly isCancelled: boolean;\n}\n\nconst defaultStyleFn: SpinnerOptions['styleFrame'] = (frame) => styleText('magenta', frame);\n\nexport const spinner = ({\n\tindicator = 'dots',\n\tonCancel,\n\toutput = process.stdout,\n\tcancelMessage,\n\terrorMessage,\n\tframes = unicode ? ['◒', '◐', '◓', '◑'] : ['•', 'o', 'O', '0'],\n\tdelay = unicode ? 80 : 120,\n\tsignal,\n\t...opts\n}: SpinnerOptions = {}): SpinnerResult => {\n\tconst isCI = isCIFn();\n\n\tlet unblock: () => void;\n\tlet loop: NodeJS.Timeout;\n\tlet isSpinnerActive = false;\n\tlet isCancelled = false;\n\tlet _message = '';\n\tlet _prevMessage: string | undefined;\n\tlet _origin: number = performance.now();\n\tconst columns = getColumns(output);\n\tconst styleFn = opts?.styleFrame ?? defaultStyleFn;\n\n\tconst handleExit = (code: number) => {\n\t\tconst msg =\n\t\t\tcode > 1\n\t\t\t\t? (errorMessage ?? settings.messages.error)\n\t\t\t\t: (cancelMessage ?? settings.messages.cancel);\n\t\tisCancelled = code === 1;\n\t\tif (isSpinnerActive) {\n\t\t\t_stop(msg, code);\n\t\t\tif (isCancelled && typeof onCancel === 'function') {\n\t\t\t\tonCancel();\n\t\t\t}\n\t\t}\n\t};\n\n\tconst errorEventHandler = () => handleExit(2);\n\tconst signalEventHandler = () => handleExit(1);\n\n\tconst registerHooks = () => {\n\t\t// Reference: https://nodejs.org/api/process.html#event-uncaughtexception\n\t\tprocess.on('uncaughtExceptionMonitor', errorEventHandler);\n\t\t// Reference: https://nodejs.org/api/process.html#event-unhandledrejection\n\t\tprocess.on('unhandledRejection', errorEventHandler);\n\t\t// Reference Signal Events: https://nodejs.org/api/process.html#signal-events\n\t\tprocess.on('SIGINT', signalEventHandler);\n\t\tprocess.on('SIGTERM', signalEventHandler);\n\t\tprocess.on('exit', handleExit);\n\n\t\tif (signal) {\n\t\t\tsignal.addEventListener('abort', signalEventHandler);\n\t\t}\n\t};\n\n\tconst clearHooks = () => {\n\t\tprocess.removeListener('uncaughtExceptionMonitor', errorEventHandler);\n\t\tprocess.removeListener('unhandledRejection', errorEventHandler);\n\t\tprocess.removeListener('SIGINT', signalEventHandler);\n\t\tprocess.removeListener('SIGTERM', signalEventHandler);\n\t\tprocess.removeListener('exit', handleExit);\n\n\t\tif (signal) {\n\t\t\tsignal.removeEventListener('abort', signalEventHandler);\n\t\t}\n\t};\n\n\tconst clearPrevMessage = () => {\n\t\tif (_prevMessage === undefined) return;\n\t\tif (isCI) output.write('\\n');\n\t\tconst wrapped = wrapAnsi(_prevMessage, columns, {\n\t\t\thard: true,\n\t\t\ttrim: false,\n\t\t});\n\t\tconst prevLines = wrapped.split('\\n');\n\t\tif (prevLines.length > 1) {\n\t\t\toutput.write(cursor.up(prevLines.length - 1));\n\t\t}\n\t\toutput.write(cursor.to(0));\n\t\toutput.write(erase.down());\n\t};\n\n\tconst removeTrailingDots = (msg: string): string => {\n\t\treturn msg.replace(/\\.+$/, '');\n\t};\n\n\tconst formatTimer = (origin: number): string => {\n\t\tconst duration = (performance.now() - origin) / 1000;\n\t\tconst min = Math.floor(duration / 60);\n\t\tconst secs = Math.floor(duration % 60);\n\t\treturn min > 0 ? `[${min}m ${secs}s]` : `[${secs}s]`;\n\t};\n\n\tconst hasGuide = opts.withGuide ?? settings.withGuide;\n\n\tconst start = (msg = ''): void => {\n\t\tisSpinnerActive = true;\n\t\tunblock = block({ output });\n\t\t_message = removeTrailingDots(msg);\n\t\t_origin = performance.now();\n\t\tif (hasGuide) {\n\t\t\toutput.write(`${styleText('gray', S_BAR)}\\n`);\n\t\t}\n\t\tlet frameIndex = 0;\n\t\tlet indicatorTimer = 0;\n\t\tregisterHooks();\n\t\tloop = setInterval(() => {\n\t\t\tif (isCI && _message === _prevMessage) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tclearPrevMessage();\n\t\t\t_prevMessage = _message;\n\t\t\tconst frame = styleFn(frames[frameIndex]);\n\t\t\tlet outputMessage: string;\n\n\t\t\tif (isCI) {\n\t\t\t\toutputMessage = `${frame} ${_message}...`;\n\t\t\t} else if (indicator === 'timer') {\n\t\t\t\toutputMessage = `${frame} ${_message} ${formatTimer(_origin)}`;\n\t\t\t} else {\n\t\t\t\tconst loadingDots = '.'.repeat(Math.floor(indicatorTimer)).slice(0, 3);\n\t\t\t\toutputMessage = `${frame} ${_message}${loadingDots}`;\n\t\t\t}\n\n\t\t\tconst wrapped = wrapAnsi(outputMessage, columns, {\n\t\t\t\thard: true,\n\t\t\t\ttrim: false,\n\t\t\t});\n\t\t\toutput.write(wrapped);\n\n\t\t\tframeIndex = frameIndex + 1 < frames.length ? frameIndex + 1 : 0;\n\t\t\t// indicator increase by 1 every 8 frames\n\t\t\tindicatorTimer = indicatorTimer < 4 ? indicatorTimer + 0.125 : 0;\n\t\t}, delay);\n\t};\n\n\tconst _stop = (msg = '', code = 0, silent: boolean = false): void => {\n\t\tif (!isSpinnerActive) return;\n\t\tisSpinnerActive = false;\n\t\tclearInterval(loop);\n\t\tclearPrevMessage();\n\t\tconst step =\n\t\t\tcode === 0\n\t\t\t\t? styleText('green', S_STEP_SUBMIT)\n\t\t\t\t: code === 1\n\t\t\t\t\t? styleText('red', S_STEP_CANCEL)\n\t\t\t\t\t: styleText('red', S_STEP_ERROR);\n\t\t_message = msg ?? _message;\n\t\tif (!silent) {\n\t\t\tif (indicator === 'timer') {\n\t\t\t\toutput.write(`${step} ${_message} ${formatTimer(_origin)}\\n`);\n\t\t\t} else {\n\t\t\t\toutput.write(`${step} ${_message}\\n`);\n\t\t\t}\n\t\t}\n\t\tclearHooks();\n\t\tunblock();\n\t};\n\n\tconst stop = (msg = ''): void => _stop(msg, 0);\n\tconst cancel = (msg = ''): void => _stop(msg, 1);\n\tconst error = (msg = ''): void => _stop(msg, 2);\n\t// TODO (43081j): this will leave the initial S_BAR since we purposely\n\t// don't erase that in `clearPrevMessage`. In future, we may want to treat\n\t// `clear` as a special case and remove the bar too.\n\tconst clear = (): void => _stop('', 0, true);\n\n\tconst message = (msg = ''): void => {\n\t\t_message = removeTrailingDots(msg ?? _message);\n\t};\n\n\treturn {\n\t\tstart,\n\t\tstop,\n\t\tmessage,\n\t\tcancel,\n\t\terror,\n\t\tclear,\n\t\tget isCancelled() {\n\t\t\treturn isCancelled;\n\t\t},\n\t};\n};\n","import { styleText } from 'node:util';\nimport type { State } from '@clack/core';\nimport { unicodeOr } from './common.js';\nimport { type SpinnerOptions, type SpinnerResult, spinner } from './spinner.js';\n\nconst S_PROGRESS_CHAR: Record<NonNullable<ProgressOptions['style']>, string> = {\n\tlight: unicodeOr('─', '-'),\n\theavy: unicodeOr('━', '='),\n\tblock: unicodeOr('█', '#'),\n};\n\nexport interface ProgressOptions extends SpinnerOptions {\n\tstyle?: 'light' | 'heavy' | 'block';\n\tmax?: number;\n\tsize?: number;\n}\n\nexport interface ProgressResult extends SpinnerResult {\n\tadvance(step?: number, msg?: string): void;\n}\n\nexport function progress({\n\tstyle = 'heavy',\n\tmax: userMax = 100,\n\tsize: userSize = 40,\n\t...spinnerOptions\n}: ProgressOptions = {}): ProgressResult {\n\tconst spin = spinner(spinnerOptions);\n\tlet value = 0;\n\tlet previousMessage = '';\n\n\tconst max = Math.max(1, userMax);\n\tconst size = Math.max(1, userSize);\n\n\tconst activeStyle = (state: State) => {\n\t\tswitch (state) {\n\t\t\tcase 'initial':\n\t\t\tcase 'active':\n\t\t\t\treturn (text: string) => styleText('magenta', text);\n\t\t\tcase 'error':\n\t\t\tcase 'cancel':\n\t\t\t\treturn (text: string) => styleText('red', text);\n\t\t\tcase 'submit':\n\t\t\t\treturn (text: string) => styleText('green', text);\n\t\t\tdefault:\n\t\t\t\treturn (text: string) => styleText('magenta', text);\n\t\t}\n\t};\n\tconst drawProgress = (state: State, msg: string) => {\n\t\tconst active = Math.floor((value / max) * size);\n\t\treturn `${activeStyle(state)(S_PROGRESS_CHAR[style].repeat(active))}${styleText('dim', S_PROGRESS_CHAR[style].repeat(size - active))} ${msg}`;\n\t};\n\n\tconst start = (msg = '') => {\n\t\tpreviousMessage = msg;\n\t\tspin.start(drawProgress('initial', msg));\n\t};\n\tconst advance = (step = 1, msg?: string): void => {\n\t\tvalue = Math.min(max, step + value);\n\t\tspin.message(drawProgress('active', msg ?? previousMessage));\n\t\tpreviousMessage = msg ?? previousMessage;\n\t};\n\treturn {\n\t\tstart,\n\t\tstop: spin.stop,\n\t\tcancel: spin.cancel,\n\t\terror: spin.error,\n\t\tclear: spin.clear,\n\t\tadvance,\n\t\tisCancelled: spin.isCancelled,\n\t\tmessage: (msg: string) => advance(0, msg),\n\t};\n}\n","import { styleText } from 'node:util';\nimport { SelectPrompt, settings, wrapTextWithPrefix } from '@clack/core';\nimport {\n\ttype CommonOptions,\n\tS_BAR,\n\tS_BAR_END,\n\tS_RADIO_ACTIVE,\n\tS_RADIO_INACTIVE,\n\tsymbol,\n\tsymbolBar,\n} from './common.js';\nimport { limitOptions } from './limit-options.js';\n\ntype Primitive = Readonly<string | boolean | number>;\n\nexport type Option<Value> = Value extends Primitive\n\t? {\n\t\t\t/**\n\t\t\t * Internal data for this option.\n\t\t\t */\n\t\t\tvalue: Value;\n\t\t\t/**\n\t\t\t * The optional, user-facing text for this option.\n\t\t\t *\n\t\t\t * By default, the `value` is converted to a string.\n\t\t\t */\n\t\t\tlabel?: string;\n\t\t\t/**\n\t\t\t * An optional hint to display to the user when\n\t\t\t * this option might be selected.\n\t\t\t *\n\t\t\t * By default, no `hint` is displayed.\n\t\t\t */\n\t\t\thint?: string;\n\t\t\t/**\n\t\t\t * Whether this option is disabled.\n\t\t\t * Disabled options are visible but cannot be selected.\n\t\t\t *\n\t\t\t * By default, options are not disabled.\n\t\t\t */\n\t\t\tdisabled?: boolean;\n\t\t}\n\t: {\n\t\t\t/**\n\t\t\t * Internal data for this option.\n\t\t\t */\n\t\t\tvalue: Value;\n\t\t\t/**\n\t\t\t * Required. The user-facing text for this option.\n\t\t\t */\n\t\t\tlabel: string;\n\t\t\t/**\n\t\t\t * An optional hint to display to the user when\n\t\t\t * this option might be selected.\n\t\t\t *\n\t\t\t * By default, no `hint` is displayed.\n\t\t\t */\n\t\t\thint?: string;\n\t\t\t/**\n\t\t\t * Whether this option is disabled.\n\t\t\t * Disabled options are visible but cannot be selected.\n\t\t\t *\n\t\t\t * By default, options are not disabled.\n\t\t\t */\n\t\t\tdisabled?: boolean;\n\t\t};\n\nexport interface SelectOptions<Value> extends CommonOptions {\n\tmessage: string;\n\toptions: Option<Value>[];\n\tinitialValue?: Value;\n\tmaxItems?: number;\n}\n\nconst computeLabel = (label: string, format: (text: string) => string) => {\n\tif (!label.includes('\\n')) {\n\t\treturn format(label);\n\t}\n\treturn label\n\t\t.split('\\n')\n\t\t.map((line) => format(line))\n\t\t.join('\\n');\n};\n\nexport const select = <Value>(opts: SelectOptions<Value>) => {\n\tconst opt = (\n\t\toption: Option<Value>,\n\t\tstate: 'inactive' | 'active' | 'selected' | 'cancelled' | 'disabled'\n\t) => {\n\t\tconst label = option.label ?? String(option.value);\n\t\tswitch (state) {\n\t\t\tcase 'disabled':\n\t\t\t\treturn `${styleText('gray', S_RADIO_INACTIVE)} ${computeLabel(label, (text) => styleText('gray', text))}${\n\t\t\t\t\toption.hint ? ` ${styleText('dim', `(${option.hint ?? 'disabled'})`)}` : ''\n\t\t\t\t}`;\n\t\t\tcase 'selected':\n\t\t\t\treturn `${computeLabel(label, (text) => styleText('dim', text))}`;\n\t\t\tcase 'active':\n\t\t\t\treturn `${styleText('green', S_RADIO_ACTIVE)} ${label}${\n\t\t\t\t\toption.hint ? ` ${styleText('dim', `(${option.hint})`)}` : ''\n\t\t\t\t}`;\n\t\t\tcase 'cancelled':\n\t\t\t\treturn `${computeLabel(label, (str) => styleText(['strikethrough', 'dim'], str))}`;\n\t\t\tdefault:\n\t\t\t\treturn `${styleText('dim', S_RADIO_INACTIVE)} ${computeLabel(label, (text) => styleText('dim', text))}`;\n\t\t}\n\t};\n\n\treturn new SelectPrompt({\n\t\toptions: opts.options,\n\t\tsignal: opts.signal,\n\t\tinput: opts.input,\n\t\toutput: opts.output,\n\t\tinitialValue: opts.initialValue,\n\t\trender() {\n\t\t\tconst hasGuide = opts.withGuide ?? settings.withGuide;\n\t\t\tconst titlePrefix = `${symbol(this.state)} `;\n\t\t\tconst titlePrefixBar = `${symbolBar(this.state)} `;\n\t\t\tconst messageLines = wrapTextWithPrefix(\n\t\t\t\topts.output,\n\t\t\t\topts.message,\n\t\t\t\ttitlePrefixBar,\n\t\t\t\ttitlePrefix\n\t\t\t);\n\t\t\tconst title = `${hasGuide ? `${styleText('gray', S_BAR)}\\n` : ''}${messageLines}\\n`;\n\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'submit': {\n\t\t\t\t\tconst submitPrefix = hasGuide ? `${styleText('gray', S_BAR)} ` : '';\n\t\t\t\t\tconst wrappedLines = wrapTextWithPrefix(\n\t\t\t\t\t\topts.output,\n\t\t\t\t\t\topt(this.options[this.cursor], 'selected'),\n\t\t\t\t\t\tsubmitPrefix\n\t\t\t\t\t);\n\t\t\t\t\treturn `${title}${wrappedLines}`;\n\t\t\t\t}\n\t\t\t\tcase 'cancel': {\n\t\t\t\t\tconst cancelPrefix = hasGuide ? `${styleText('gray', S_BAR)} ` : '';\n\t\t\t\t\tconst wrappedLines = wrapTextWithPrefix(\n\t\t\t\t\t\topts.output,\n\t\t\t\t\t\topt(this.options[this.cursor], 'cancelled'),\n\t\t\t\t\t\tcancelPrefix\n\t\t\t\t\t);\n\t\t\t\t\treturn `${title}${wrappedLines}${hasGuide ? `\\n${styleText('gray', S_BAR)}` : ''}`;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\tconst prefix = hasGuide ? `${styleText('cyan', S_BAR)} ` : '';\n\t\t\t\t\tconst prefixEnd = hasGuide ? styleText('cyan', S_BAR_END) : '';\n\t\t\t\t\t// Calculate rowPadding: title lines + footer lines (S_BAR_END + trailing newline)\n\t\t\t\t\tconst titleLineCount = title.split('\\n').length;\n\t\t\t\t\tconst footerLineCount = hasGuide ? 2 : 1; // S_BAR_END + trailing newline (or just trailing newline)\n\t\t\t\t\treturn `${title}${prefix}${limitOptions({\n\t\t\t\t\t\toutput: opts.output,\n\t\t\t\t\t\tcursor: this.cursor,\n\t\t\t\t\t\toptions: this.options,\n\t\t\t\t\t\tmaxItems: opts.maxItems,\n\t\t\t\t\t\tcolumnPadding: prefix.length,\n\t\t\t\t\t\trowPadding: titleLineCount + footerLineCount,\n\t\t\t\t\t\tstyle: (item, active) =>\n\t\t\t\t\t\t\topt(item, item.disabled ? 'disabled' : active ? 'active' : 'inactive'),\n\t\t\t\t\t}).join(`\\n${prefix}`)}\\n${prefixEnd}\\n`;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<Value | symbol>;\n};\n","import { styleText } from 'node:util';\nimport { SelectKeyPrompt, settings, wrapTextWithPrefix } from '@clack/core';\nimport { type CommonOptions, S_BAR, S_BAR_END, symbol } from './common.js';\nimport type { Option } from './select.js';\n\nexport interface SelectKeyOptions<Value extends string> extends CommonOptions {\n\tmessage: string;\n\toptions: Option<Value>[];\n\tinitialValue?: Value;\n\tcaseSensitive?: boolean;\n}\n\nexport const selectKey = <Value extends string>(opts: SelectKeyOptions<Value>) => {\n\tconst opt = (\n\t\toption: Option<Value>,\n\t\tstate: 'inactive' | 'active' | 'selected' | 'cancelled' = 'inactive'\n\t) => {\n\t\tconst label = option.label ?? String(option.value);\n\t\tif (state === 'selected') {\n\t\t\treturn `${styleText('dim', label)}`;\n\t\t}\n\t\tif (state === 'cancelled') {\n\t\t\treturn `${styleText(['strikethrough', 'dim'], label)}`;\n\t\t}\n\t\tif (state === 'active') {\n\t\t\treturn `${styleText(['bgCyan', 'gray'], ` ${option.value} `)} ${label}${\n\t\t\t\toption.hint ? ` ${styleText('dim', `(${option.hint})`)}` : ''\n\t\t\t}`;\n\t\t}\n\t\treturn `${styleText(['gray', 'bgWhite', 'inverse'], ` ${option.value} `)} ${label}${\n\t\t\toption.hint ? ` ${styleText('dim', `(${option.hint})`)}` : ''\n\t\t}`;\n\t};\n\n\treturn new SelectKeyPrompt({\n\t\toptions: opts.options,\n\t\tsignal: opts.signal,\n\t\tinput: opts.input,\n\t\toutput: opts.output,\n\t\tinitialValue: opts.initialValue,\n\t\tcaseSensitive: opts.caseSensitive,\n\t\trender() {\n\t\t\tconst hasGuide = opts.withGuide ?? settings.withGuide;\n\t\t\tconst title = `${hasGuide ? `${styleText('gray', S_BAR)}\\n` : ''}${symbol(this.state)} ${opts.message}\\n`;\n\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'submit': {\n\t\t\t\t\tconst submitPrefix = hasGuide ? `${styleText('gray', S_BAR)} ` : '';\n\t\t\t\t\tconst selectedOption =\n\t\t\t\t\t\tthis.options.find((opt) => opt.value === this.value) ?? opts.options[0];\n\t\t\t\t\tconst wrapped = wrapTextWithPrefix(\n\t\t\t\t\t\topts.output,\n\t\t\t\t\t\topt(selectedOption, 'selected'),\n\t\t\t\t\t\tsubmitPrefix\n\t\t\t\t\t);\n\t\t\t\t\treturn `${title}${wrapped}`;\n\t\t\t\t}\n\t\t\t\tcase 'cancel': {\n\t\t\t\t\tconst cancelPrefix = hasGuide ? `${styleText('gray', S_BAR)} ` : '';\n\t\t\t\t\tconst wrapped = wrapTextWithPrefix(\n\t\t\t\t\t\topts.output,\n\t\t\t\t\t\topt(this.options[0], 'cancelled'),\n\t\t\t\t\t\tcancelPrefix\n\t\t\t\t\t);\n\t\t\t\t\treturn `${title}${wrapped}${hasGuide ? `\\n${styleText('gray', S_BAR)}` : ''}`;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\tconst defaultPrefix = hasGuide ? `${styleText('cyan', S_BAR)} ` : '';\n\t\t\t\t\tconst defaultPrefixEnd = hasGuide ? styleText('cyan', S_BAR_END) : '';\n\t\t\t\t\tconst wrapped = this.options\n\t\t\t\t\t\t.map((option, i) =>\n\t\t\t\t\t\t\twrapTextWithPrefix(\n\t\t\t\t\t\t\t\topts.output,\n\t\t\t\t\t\t\t\topt(option, i === this.cursor ? 'active' : 'inactive'),\n\t\t\t\t\t\t\t\tdefaultPrefix\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join('\\n');\n\t\t\t\t\treturn `${title}${wrapped}\\n${defaultPrefixEnd}\\n`;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<Value | symbol>;\n};\n","import { stripVTControlCharacters as strip, styleText } from 'node:util';\nimport { S_BAR, S_ERROR, S_INFO, S_STEP_SUBMIT, S_SUCCESS, S_WARN } from './common.js';\nimport type { LogMessageOptions } from './log.js';\n\nconst prefix = `${styleText('gray', S_BAR)} `;\n\n// TODO (43081j): this currently doesn't support custom `output` writables\n// because we rely on `columns` existing (i.e. `process.stdout.columns).\n//\n// If we want to support `output` being passed in, we will need to use\n// a condition like `if (output insance Writable)` to check if it has columns\nexport const stream = {\n\tmessage: async (\n\t\titerable: Iterable<string> | AsyncIterable<string>,\n\t\t{ symbol = styleText('gray', S_BAR) }: LogMessageOptions = {}\n\t) => {\n\t\tprocess.stdout.write(`${styleText('gray', S_BAR)}\\n${symbol} `);\n\t\tlet lineWidth = 3;\n\t\tfor await (let chunk of iterable) {\n\t\t\tchunk = chunk.replace(/\\n/g, `\\n${prefix}`);\n\t\t\tif (chunk.includes('\\n')) {\n\t\t\t\tlineWidth = 3 + strip(chunk.slice(chunk.lastIndexOf('\\n'))).length;\n\t\t\t}\n\t\t\tconst chunkLen = strip(chunk).length;\n\t\t\tif (lineWidth + chunkLen < process.stdout.columns) {\n\t\t\t\tlineWidth += chunkLen;\n\t\t\t\tprocess.stdout.write(chunk);\n\t\t\t} else {\n\t\t\t\tprocess.stdout.write(`\\n${prefix}${chunk.trimStart()}`);\n\t\t\t\tlineWidth = 3 + strip(chunk.trimStart()).length;\n\t\t\t}\n\t\t}\n\t\tprocess.stdout.write('\\n');\n\t},\n\tinfo: (iterable: Iterable<string> | AsyncIterable<string>) => {\n\t\treturn stream.message(iterable, { symbol: styleText('blue', S_INFO) });\n\t},\n\tsuccess: (iterable: Iterable<string> | AsyncIterable<string>) => {\n\t\treturn stream.message(iterable, { symbol: styleText('green', S_SUCCESS) });\n\t},\n\tstep: (iterable: Iterable<string> | AsyncIterable<string>) => {\n\t\treturn stream.message(iterable, { symbol: styleText('green', S_STEP_SUBMIT) });\n\t},\n\twarn: (iterable: Iterable<string> | AsyncIterable<string>) => {\n\t\treturn stream.message(iterable, { symbol: styleText('yellow', S_WARN) });\n\t},\n\t/** alias for `log.warn()`. */\n\twarning: (iterable: Iterable<string> | AsyncIterable<string>) => {\n\t\treturn stream.warn(iterable);\n\t},\n\terror: (iterable: Iterable<string> | AsyncIterable<string>) => {\n\t\treturn stream.message(iterable, { symbol: styleText('red', S_ERROR) });\n\t},\n};\n","import type { CommonOptions } from './common.js';\nimport { spinner } from './spinner.js';\n\nexport type Task = {\n\t/**\n\t * Task title\n\t */\n\ttitle: string;\n\t/**\n\t * Task function\n\t */\n\ttask: (message: (string: string) => void) => string | Promise<string> | void | Promise<void>;\n\n\t/**\n\t * If enabled === false the task will be skipped\n\t */\n\tenabled?: boolean;\n};\n\n/**\n * Define a group of tasks to be executed\n */\nexport const tasks = async (tasks: Task[], opts?: CommonOptions) => {\n\tfor (const task of tasks) {\n\t\tif (task.enabled === false) continue;\n\n\t\tconst s = spinner(opts);\n\t\ts.start(task.title);\n\t\tconst result = await task.task(s.message);\n\t\ts.stop(result || task.title);\n\t}\n};\n","import type { Writable } from 'node:stream';\nimport { styleText } from 'node:util';\nimport { getColumns } from '@clack/core';\nimport { erase } from 'sisteransi';\nimport {\n\ttype CommonOptions,\n\tisCI as isCIFn,\n\tisTTY as isTTYFn,\n\tS_BAR,\n\tS_STEP_SUBMIT,\n} from './common.js';\nimport { log } from './log.js';\n\nexport interface TaskLogOptions extends CommonOptions {\n\ttitle: string;\n\tlimit?: number;\n\tspacing?: number;\n\tretainLog?: boolean;\n}\n\nexport interface TaskLogMessageOptions {\n\traw?: boolean;\n}\n\nexport interface TaskLogCompletionOptions {\n\tshowLog?: boolean;\n}\n\ninterface BufferEntry {\n\theader?: string;\n\tvalue: string;\n\tfull: string;\n\tresult?: {\n\t\tstatus: 'success' | 'error';\n\t\tmessage: string;\n\t};\n}\n\nconst stripDestructiveANSI = (input: string): string => {\n\t// biome-ignore lint/suspicious/noControlCharactersInRegex: intentional\n\treturn input.replace(/\\x1b\\[(?:\\d+;)*\\d*[ABCDEFGHfJKSTsu]|\\x1b\\[(s|u)/g, '');\n};\n\n/**\n * Renders a log which clears on success and remains on failure\n */\nexport const taskLog = (opts: TaskLogOptions) => {\n\tconst output: Writable = opts.output ?? process.stdout;\n\tconst columns = getColumns(output);\n\tconst secondarySymbol = styleText('gray', S_BAR);\n\tconst spacing = opts.spacing ?? 1;\n\tconst barSize = 3;\n\tconst retainLog = opts.retainLog === true;\n\tconst isTTY = !isCIFn() && isTTYFn(output);\n\n\toutput.write(`${secondarySymbol}\\n`);\n\toutput.write(`${styleText('green', S_STEP_SUBMIT)} ${opts.title}\\n`);\n\tfor (let i = 0; i < spacing; i++) {\n\t\toutput.write(`${secondarySymbol}\\n`);\n\t}\n\n\tconst buffers: BufferEntry[] = [\n\t\t{\n\t\t\tvalue: '',\n\t\t\tfull: '',\n\t\t},\n\t];\n\tlet lastMessageWasRaw = false;\n\n\tconst clear = (clearTitle: boolean): void => {\n\t\tif (buffers.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tlet lines = 0;\n\n\t\tif (clearTitle) {\n\t\t\tlines += spacing + 2;\n\t\t}\n\n\t\tfor (const buffer of buffers) {\n\t\t\tconst { value, result } = buffer;\n\t\t\tlet text = result?.message ?? value;\n\n\t\t\tif (text.length === 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (result === undefined && buffer.header !== undefined && buffer.header !== '') {\n\t\t\t\ttext += `\\n${buffer.header}`;\n\t\t\t}\n\n\t\t\tconst bufferHeight = text.split('\\n').reduce((count, line) => {\n\t\t\t\tif (line === '') {\n\t\t\t\t\treturn count + 1;\n\t\t\t\t}\n\t\t\t\treturn count + Math.ceil((line.length + barSize) / columns);\n\t\t\t}, 0);\n\n\t\t\tlines += bufferHeight;\n\t\t}\n\n\t\tif (lines > 0) {\n\t\t\tlines += 1;\n\t\t\toutput.write(erase.lines(lines));\n\t\t}\n\t};\n\tconst printBuffer = (buffer: BufferEntry, messageSpacing?: number, full?: boolean): void => {\n\t\tconst messages = full ? `${buffer.full}\\n${buffer.value}` : buffer.value;\n\t\tif (buffer.header !== undefined && buffer.header !== '') {\n\t\t\tlog.message(\n\t\t\t\tbuffer.header.split('\\n').map((line) => styleText('bold', line)),\n\t\t\t\t{\n\t\t\t\t\toutput,\n\t\t\t\t\tsecondarySymbol,\n\t\t\t\t\tsymbol: secondarySymbol,\n\t\t\t\t\tspacing: 0,\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t\tlog.message(\n\t\t\tmessages.split('\\n').map((line) => styleText('dim', line)),\n\t\t\t{\n\t\t\t\toutput,\n\t\t\t\tsecondarySymbol,\n\t\t\t\tsymbol: secondarySymbol,\n\t\t\t\tspacing: messageSpacing ?? spacing,\n\t\t\t}\n\t\t);\n\t};\n\tconst renderBuffer = (): void => {\n\t\tfor (const buffer of buffers) {\n\t\t\tconst { header, value, full } = buffer;\n\t\t\tif ((header === undefined || header.length === 0) && value.length === 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tprintBuffer(buffer, undefined, retainLog === true && full.length > 0);\n\t\t}\n\t};\n\tconst message = (buffer: BufferEntry, msg: string, mopts?: TaskLogMessageOptions) => {\n\t\tclear(false);\n\t\tif ((mopts?.raw !== true || !lastMessageWasRaw) && buffer.value !== '') {\n\t\t\tbuffer.value += '\\n';\n\t\t}\n\t\tbuffer.value += stripDestructiveANSI(msg);\n\t\tlastMessageWasRaw = mopts?.raw === true;\n\t\tif (opts.limit !== undefined) {\n\t\t\tconst lines = buffer.value.split('\\n');\n\t\t\tconst linesToRemove = lines.length - opts.limit;\n\t\t\tif (linesToRemove > 0) {\n\t\t\t\tconst removedLines = lines.splice(0, linesToRemove);\n\t\t\t\tif (retainLog) {\n\t\t\t\t\tbuffer.full += (buffer.full === '' ? '' : '\\n') + removedLines.join('\\n');\n\t\t\t\t}\n\t\t\t}\n\t\t\tbuffer.value = lines.join('\\n');\n\t\t}\n\t\tif (isTTY) {\n\t\t\tprintBuffers();\n\t\t}\n\t};\n\tconst printBuffers = (): void => {\n\t\tfor (const buffer of buffers) {\n\t\t\tif (buffer.result) {\n\t\t\t\tif (buffer.result.status === 'error') {\n\t\t\t\t\tlog.error(buffer.result.message, { output, secondarySymbol, spacing: 0 });\n\t\t\t\t} else {\n\t\t\t\t\tlog.success(buffer.result.message, { output, secondarySymbol, spacing: 0 });\n\t\t\t\t}\n\t\t\t} else if (buffer.value !== '') {\n\t\t\t\tprintBuffer(buffer, 0);\n\t\t\t}\n\t\t}\n\t};\n\tconst completeBuffer = (buffer: BufferEntry, result: BufferEntry['result']): void => {\n\t\tclear(false);\n\n\t\tbuffer.result = result;\n\n\t\tif (isTTY) {\n\t\t\tprintBuffers();\n\t\t}\n\t};\n\n\treturn {\n\t\tmessage(msg: string, mopts?: TaskLogMessageOptions) {\n\t\t\tmessage(buffers[0], msg, mopts);\n\t\t},\n\t\tgroup(name: string) {\n\t\t\tconst buffer: BufferEntry = {\n\t\t\t\theader: name,\n\t\t\t\tvalue: '',\n\t\t\t\tfull: '',\n\t\t\t};\n\t\t\tbuffers.push(buffer);\n\t\t\treturn {\n\t\t\t\tmessage(msg: string, mopts?: TaskLogMessageOptions) {\n\t\t\t\t\tmessage(buffer, msg, mopts);\n\t\t\t\t},\n\t\t\t\terror(message: string) {\n\t\t\t\t\tcompleteBuffer(buffer, {\n\t\t\t\t\t\tstatus: 'error',\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tsuccess(message: string) {\n\t\t\t\t\tcompleteBuffer(buffer, {\n\t\t\t\t\t\tstatus: 'success',\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t\terror(message: string, opts?: TaskLogCompletionOptions): void {\n\t\t\tclear(true);\n\t\t\tlog.error(message, { output, secondarySymbol, spacing: 1 });\n\t\t\tif (opts?.showLog !== false) {\n\t\t\t\trenderBuffer();\n\t\t\t}\n\t\t\t// clear buffer since error is an end state\n\t\t\tbuffers.splice(1, buffers.length - 1);\n\t\t\tbuffers[0].value = '';\n\t\t\tbuffers[0].full = '';\n\t\t},\n\t\tsuccess(message: string, opts?: TaskLogCompletionOptions): void {\n\t\t\tclear(true);\n\t\t\tlog.success(message, { output, secondarySymbol, spacing: 1 });\n\t\t\tif (opts?.showLog === true) {\n\t\t\t\trenderBuffer();\n\t\t\t}\n\t\t\t// clear buffer since success is an end state\n\t\t\tbuffers.splice(1, buffers.length - 1);\n\t\t\tbuffers[0].value = '';\n\t\t\tbuffers[0].full = '';\n\t\t},\n\t};\n};\n","import { styleText } from 'node:util';\nimport { settings, TextPrompt } from '@clack/core';\nimport { type CommonOptions, S_BAR, S_BAR_END, symbol } from './common.js';\n\n/**\n * Options for the {@link text} prompt\n */\nexport interface TextOptions extends CommonOptions {\n\t/**\n\t * The prompt message or question shown to the user above the input.\n\t */\n\tmessage: string;\n\n\t/**\n\t * A visual hint shown when the field has no content.\n\t */\n\tplaceholder?: string;\n\n\t/**\n\t * A fallback value returned when the user provides nothing (empty input).\n\t */\n\tdefaultValue?: string;\n\n\t/**\n\t * The starting value shown when the prompt first renders.\n\t * Users can edit this value before submitting.\n\t */\n\tinitialValue?: string;\n\n\t/**\n\t * A function that validates user input. Return a `string` or `Error` to show as a\n\t * validation error, or `undefined` to accept the result.\n\t */\n\tvalidate?: (value: string | undefined) => string | Error | undefined;\n}\n\n/**\n * The text prompt accepts a single line of text.\n *\n * @see https://bomb.sh/docs/clack/packages/prompts/#text-input\n *\n * @example\n * ```ts\n * import { text } from '@clack/prompts';\n *\n * const name = await text({\n * message: 'What is your name?',\n * placeholder: 'John Doe',\n * validate: (value) => {\n * if (!value || value.length < 2) return 'Name must be at least 2 characters';\n * return undefined;\n * },\n * });\n * ```\n */\nexport const text = (opts: TextOptions) => {\n\treturn new TextPrompt({\n\t\tvalidate: opts.validate,\n\t\tplaceholder: opts.placeholder,\n\t\tdefaultValue: opts.defaultValue,\n\t\tinitialValue: opts.initialValue,\n\t\toutput: opts.output,\n\t\tsignal: opts.signal,\n\t\tinput: opts.input,\n\t\trender() {\n\t\t\tconst hasGuide = opts?.withGuide ?? settings.withGuide;\n\t\t\tconst titlePrefix = `${hasGuide ? `${styleText('gray', S_BAR)}\\n` : ''}${symbol(this.state)} `;\n\t\t\tconst title = `${titlePrefix}${opts.message}\\n`;\n\t\t\tconst placeholder = opts.placeholder\n\t\t\t\t? styleText('inverse', opts.placeholder[0]) + styleText('dim', opts.placeholder.slice(1))\n\t\t\t\t: styleText(['inverse', 'hidden'], '_');\n\t\t\tconst userInput = !this.userInput ? placeholder : this.userInputWithCursor;\n\t\t\tconst value = this.value ?? '';\n\n\t\t\tswitch (this.state) {\n\t\t\t\tcase 'error': {\n\t\t\t\t\tconst errorText = this.error ? ` ${styleText('yellow', this.error)}` : '';\n\t\t\t\t\tconst errorPrefix = hasGuide ? `${styleText('yellow', S_BAR)} ` : '';\n\t\t\t\t\tconst errorPrefixEnd = hasGuide ? styleText('yellow', S_BAR_END) : '';\n\t\t\t\t\treturn `${title.trim()}\\n${errorPrefix}${userInput}\\n${errorPrefixEnd}${errorText}\\n`;\n\t\t\t\t}\n\t\t\t\tcase 'submit': {\n\t\t\t\t\tconst valueText = value ? ` ${styleText('dim', value)}` : '';\n\t\t\t\t\tconst submitPrefix = hasGuide ? styleText('gray', S_BAR) : '';\n\t\t\t\t\treturn `${title}${submitPrefix}${valueText}`;\n\t\t\t\t}\n\t\t\t\tcase 'cancel': {\n\t\t\t\t\tconst valueText = value ? ` ${styleText(['strikethrough', 'dim'], value)}` : '';\n\t\t\t\t\tconst cancelPrefix = hasGuide ? styleText('gray', S_BAR) : '';\n\t\t\t\t\treturn `${title}${cancelPrefix}${valueText}${value.trim() ? `\\n${cancelPrefix}` : ''}`;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\tconst defaultPrefix = hasGuide ? `${styleText('cyan', S_BAR)} ` : '';\n\t\t\t\t\tconst defaultPrefixEnd = hasGuide ? styleText('cyan', S_BAR_END) : '';\n\t\t\t\t\treturn `${title}${defaultPrefix}${userInput}\\n${defaultPrefixEnd}\\n`;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}).prompt() as Promise<string | symbol>;\n};\n","/**\n * Spawn the user's editor positioned at a specific file:line.\n *\n * Honors `$VISUAL` then `$EDITOR`; defaults to `vi` when neither is set.\n * Recognizes VS Code's `--goto` flag separately because `code +<line>`\n * doesn't work; everything else uses the classic `+<line> <file>` form\n * that vim, nvim, nano, and emacs all understand.\n */\nimport { spawn } from \"node:child_process\";\nimport { resolve } from \"node:path\";\n\nexport type EditorDeps = {\n /** Project root the file path is relative to. */\n rootDir: string;\n /** Override the editor command (mainly for tests). */\n editor?: string;\n /** Override stdio (mainly for tests). */\n stdio?: \"inherit\" | \"ignore\";\n};\n\nconst isCodeFamily = (cmd: string): boolean =>\n /(^|\\/)code(-insiders)?(\\.exe)?$/i.test(cmd) ||\n /(^|\\/)cursor(\\.exe)?$/i.test(cmd);\n\n/** Resolve which editor to invoke. Exposed for testing. */\nexport function pickEditor(env: NodeJS.ProcessEnv, override?: string): string {\n if (override) return override;\n return env.VISUAL || env.EDITOR || \"vi\";\n}\n\n/**\n * Build the argv passed to the editor. Public for testing.\n *\n * vim/nvim/nano/emacs → `+<line> <file>`\n * code/cursor → `--goto <file>:<line>`\n */\nexport function editorArgs(\n editor: string,\n file: string,\n line?: number\n): string[] {\n if (line && isCodeFamily(editor)) return [\"--goto\", `${file}:${line}`];\n if (line) return [`+${line}`, file];\n return [file];\n}\n\n/** Open `file` (project-relative) at `line` in the user's editor. */\nexport async function openInEditor(\n file: string,\n line: number | undefined,\n deps: EditorDeps\n): Promise<{ ok: boolean; reason?: string }> {\n const editor = pickEditor(process.env, deps.editor);\n const absPath = resolve(deps.rootDir, file);\n const args = editorArgs(editor, absPath, line);\n return await new Promise((resolveP) => {\n const child = spawn(editor, args, {\n /* c8 ignore next — \"inherit\" path runs only inside a real TTY. */\n stdio: deps.stdio ?? \"inherit\",\n });\n child.on(\"error\", (err) => {\n resolveP({ ok: false, reason: err.message });\n });\n child.on(\"exit\", (code) => {\n resolveP({\n ok: code === 0,\n reason: code === 0 ? undefined : `exit ${code}`,\n });\n });\n });\n}\n","/**\n * Patch a tty input stream so vim users can drive @clack/prompts.\n *\n * j → cursor down (\\x1b[B)\n * k → cursor up (\\x1b[A)\n * q → ESC (clack treats ESC as cancel, which doubles as \"back\")\n * / → fires the registered \"slash\" callback AND emits ESC so\n * the currently-active prompt cancels; the loop checks the\n * callback's pending flag to decide whether to jump to\n * search instead of going one level up.\n *\n * Arrow keys and every other byte pass through unchanged. `pause()`\n * disables translation entirely — used during text-input prompts so\n * `j`, `k`, `/`, etc. are typed literally.\n */\n\nconst UP = Buffer.from(\"\\x1b[A\");\nconst DOWN = Buffer.from(\"\\x1b[B\");\nconst ESC = Buffer.from(\"\\x1b\");\n\nconst matches = (chunk: Buffer, key: string): boolean =>\n chunk.length === key.length && chunk.toString(\"utf8\") === key;\n\ntype Direction = \"down\" | \"up\" | \"cancel\" | \"slash\" | null;\n\n/** Classify a chunk into one of our handled directions, or null. */\nexport function classify(chunk: Buffer): Direction {\n if (matches(chunk, \"j\")) return \"down\";\n if (matches(chunk, \"k\")) return \"up\";\n if (matches(chunk, \"q\")) return \"cancel\";\n if (matches(chunk, \"/\")) return \"slash\";\n return null;\n}\n\ntype StreamLike = {\n emit: (event: string, ...args: unknown[]) => boolean;\n};\n\nexport type VimKeysHandle = {\n /** Remove the patch entirely. Idempotent. */\n restore: () => void;\n /** Temporarily stop translating bytes (e.g. during a text-input prompt). */\n pause: () => void;\n /** Resume translating bytes after a `pause()`. */\n resume: () => void;\n /** Register a callback fired when `/` is pressed. Returns an unsubscribe fn. */\n onSlash: (cb: () => void) => () => void;\n};\n\nexport function enableVimKeys(stdin: StreamLike): VimKeysHandle {\n const origEmit = stdin.emit.bind(stdin);\n let active = true;\n const slashListeners: Array<() => void> = [];\n\n const patched: StreamLike[\"emit\"] = (event, ...args) => {\n if (active && event === \"data\" && args[0] instanceof Buffer) {\n const direction = classify(args[0] as Buffer);\n if (direction === \"down\") return origEmit(\"data\", DOWN);\n if (direction === \"up\") return origEmit(\"data\", UP);\n if (direction === \"cancel\") return origEmit(\"data\", ESC);\n if (direction === \"slash\") {\n for (const cb of slashListeners) cb();\n return origEmit(\"data\", ESC);\n }\n }\n return origEmit(event, ...args);\n };\n stdin.emit = patched;\n\n let restored = false;\n return {\n restore: () => {\n if (restored) return;\n restored = true;\n if (stdin.emit === patched) stdin.emit = origEmit;\n },\n pause: () => {\n active = false;\n },\n resume: () => {\n active = true;\n },\n onSlash: (cb) => {\n slashListeners.push(cb);\n return () => {\n const i = slashListeners.indexOf(cb);\n if (i >= 0) slashListeners.splice(i, 1);\n };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,QAAIA,KAAI,WAAW,CAAC;AAApB,QAAuB,OAAOA,GAAE,QAAQ,CAAC;AAAzC,QAA4C,MAAMA,GAAE,OAAO,CAAC;AAC5D,QAAI,mBACH,EAAE,CAAC,CAAC,IAAI,YAAY,KAAK,SAAS,YAAY,OAC7C,CAAC,CAAC,IAAI,eAAe,KAAK,SAAS,SAAS,KAAKA,GAAE,aAAa,YAAaA,GAAE,UAAU,CAAC,GAAG,SAAS,IAAI,SAAS,UAAW,CAAC,CAAC,IAAI;AAEtI,QAAI,YAAY,CAAC,MAAM,OAAO,UAAU,SACvC,WAAS;AACR,UAAI,SAAS,KAAK,OAAO,QAAQ,OAAO,QAAQ,OAAO,KAAK,MAAM;AAClE,aAAO,CAAC,QAAQ,OAAO,aAAa,QAAQ,OAAO,SAAS,KAAK,IAAI,QAAQ,OAAO,SAAS;AAAA,IAC9F;AAED,QAAI,eAAe,CAAC,QAAQ,OAAO,SAAS,UAAU;AACrD,UAAI,SAAS,IAAI,SAAS;AAC1B,SAAG;AACF,kBAAU,OAAO,UAAU,QAAQ,KAAK,IAAI;AAC5C,iBAAS,QAAQ,MAAM;AACvB,gBAAQ,OAAO,QAAQ,OAAO,MAAM;AAAA,MACrC,SAAS,CAAC;AACV,aAAO,SAAS,OAAO,UAAU,MAAM;AAAA,IACxC;AAEA,QAAI,eAAe,CAAC,UAAU,qBAAqB;AAClD,UAAIC,KAAI,UAAU,YAAY,MAAM;AACpC,aAAO;AAAA,QACN,kBAAkB;AAAA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,MAAM,SAAS,SAAS;AAAA,EAE5B,QAAQ;AACN,WAAO;AAAA,EACT;AACF,GAAG;AAEH,IAAI,QAAQ;AACV,OAAK;AAAA,IACH,OAAO,QAAQ;AAAA,IACf,QAAQ,QAAQ;AAAA,IAChB,aAAa,QAAQ;AAAA,IACrB,OAAO,CAAC,CAAC,QAAQ,OAAO;AAAA,IACxB,MAAM,QAAQ,KAAK,MAAM,CAAC;AAAA,IAC1B,eAAe;AAAA,IACf,YAAY,QAAQ,IAAI,YAAY,QAAQ,IAAI;AAAA,EAClD,CAAC,EAAE;AAAA,IACD,CAAC,SAAS,QAAQ,KAAK,IAAI;AAAA,IAC3B,CAAC,QAAQ;AACP,cAAQ,OAAO;AAAA,QACb,qBAAgB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA;AAAA,MAClE;AACA,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF;","names":["p","f","ESC","CSI","x","resolve","q","m","e","st","f","r","p","e","result","_t","k","m","p","p","f","m","k","m","f","p","e","m","st","e","b","q","pc","k","matches","m","q","w","st","p","e","x","h","r","z","st","p","z","m","loc","findActionsEmitting","st","findReactionsFor","findProjectionsFor","p","m","e","x","reactions","projections","resolve","x","NO_TRUNCATION","dist_default","dist_default","findCursor","cursor","delta","options","opt","newCursor","maxCursor","clampedCursor","actions","DEFAULT_MONTH_NAMES","settings","days","month","min","max","isActionKey","key","action","settings","value","diffLines","a","b","aLines","bLines","numLines","diff","i","isWindows","CANCEL_SYMBOL","isCancel","setRawMode","input","getColumns","output","getRows","wrapTextWithPrefix","text","prefix","startPrefix","endPrefix","lineFormatter","columns","stdout","wrapAnsi","line","index","arr","lineString","g$1","options","trackValue","input","stdin","render","signal","opts","event","params","cb","data","cbs","cleanup","subscriber","resolve","CANCEL_SYMBOL","readline","setRawMode","cursor","char","_key","_char","value","write","key","settings","problem","isActionKey","lines","frame","diff","diffLines","rows","diffOffsetAfter","diffOffsetBefore","diffLine","erase","adjustedDiffLine","newLines","SelectPrompt","Prompt","opts","initialCursor","value","cursor","findCursor","key","TextPrompt","Prompt","userInput","s1","s2","s3","styleText","opts","input","isUnicodeSupported","process","unicode","unicodeOr","c","fallback","unicode","S_STEP_ACTIVE","S_STEP_CANCEL","S_STEP_ERROR","S_STEP_SUBMIT","S_BAR_START","S_BAR","S_BAR_END","S_BAR_START_RIGHT","S_BAR_END_RIGHT","S_RADIO_ACTIVE","S_RADIO_INACTIVE","S_CHECKBOX_ACTIVE","S_CHECKBOX_SELECTED","S_CHECKBOX_INACTIVE","S_PASSWORD_MASK","S_BAR_H","S_CORNER_TOP_RIGHT","S_CONNECT_LEFT","S_CORNER_BOTTOM_RIGHT","S_CORNER_BOTTOM_LEFT","S_CORNER_TOP_LEFT","S_INFO","S_SUCCESS","S_WARN","S_ERROR","symbol","state","styleText","symbolBar","trimLines","groups","initialLineCount","startIndex","endIndex","maxLines","fromEnd","lineCount","removals","i","limitOptions","cursor","options","style","output","maxItems","columnPadding","rowPadding","maxWidth","getColumns","rows","getRows","overflowFormat","outputMaxItems","computedMaxItems","slidingWindowLocation","shouldRenderTopEllipsis","shouldRenderBottomEllipsis","slidingWindowLocationEnd","lineGroups","slidingWindowLocationWithEllipsis","slidingWindowLocationEndWithEllipsis","wrappedLines","wrapAnsi","precedingRemovals","followingRemovals","newLineCount","cursorGroupIndex","adjustedMax","trimPreceding","trimFollowing","result","lineGroup","line","log","message","symbol","styleText","S_BAR","secondarySymbol","output","spacing","withGuide","parts","hasGuide","settings","spacingString","prefix","secondaryPrefix","i","messageParts","firstLine","lines","ln","opts","S_INFO","S_SUCCESS","S_STEP_SUBMIT","S_WARN","S_ERROR","intro","title","opts","output","prefix","settings","styleText","S_BAR_START","outro","message","S_BAR","S_BAR_END","S_PROGRESS_CHAR","unicodeOr","computeLabel","label","format","line","select","opts","opt","option","state","styleText","S_RADIO_INACTIVE","text","S_RADIO_ACTIVE","str","SelectPrompt","hasGuide","settings","titlePrefix","symbol","titlePrefixBar","symbolBar","messageLines","wrapTextWithPrefix","title","S_BAR","submitPrefix","wrappedLines","cancelPrefix","prefix","prefixEnd","S_BAR_END","titleLineCount","footerLineCount","limitOptions","item","active","prefix","styleText","S_BAR","text","opts","TextPrompt","hasGuide","settings","title","styleText","S_BAR","symbol","placeholder","userInput","value","errorText","errorPrefix","errorPrefixEnd","S_BAR_END","valueText","submitPrefix","cancelPrefix","defaultPrefix","defaultPrefixEnd","resolve","ESC","e","loc","R","resolve","q","matches","k","resolve","matches","m"]}