@athrio/loom 0.0.12 → 0.0.14

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 (31) hide show
  1. package/dist/{LanguageLoader-BzlRnQhO.js → LanguageLoader-BAPSmTv0.js} +19 -11
  2. package/dist/{LanguageLoader-BzlRnQhO.js.map → LanguageLoader-BAPSmTv0.js.map} +1 -1
  3. package/dist/LanguageLoader-BF5irHbe.js +3 -0
  4. package/dist/{LanguageService-BTCvgdWm.js → LanguageService-C3_9lh8E.js} +2 -2
  5. package/dist/{LanguageService-BTCvgdWm.js.map → LanguageService-C3_9lh8E.js.map} +1 -1
  6. package/dist/{LoomFormatter-Bu8L8cdR.js → LoomFormatter-CcAXsbSL.js} +13 -5
  7. package/dist/{LoomFormatter-Bu8L8cdR.js.map → LoomFormatter-CcAXsbSL.js.map} +1 -1
  8. package/dist/{LoomServer-DXIree_1.js → LoomServer-DpleSkxj.js} +28 -12
  9. package/dist/{LoomServer-DXIree_1.js.map → LoomServer-DpleSkxj.js.map} +1 -1
  10. package/dist/{LoomStore-pA-ohGNX.js → LoomStore-Bcx6V9HH.js} +106 -22
  11. package/dist/LoomStore-Bcx6V9HH.js.map +1 -0
  12. package/dist/{Runtime-XT-nb-2w.js → Runtime-B-1DeuX_.js} +1 -1
  13. package/dist/{Runtime-Byw6clui.js → Runtime-CE2kCsKX.js} +3 -3
  14. package/dist/{Runtime-Byw6clui.js.map → Runtime-CE2kCsKX.js.map} +1 -1
  15. package/dist/_virtual_tree-sitter-loom-CFLf84Ng.js +15 -0
  16. package/dist/{dist-D3YSXNOO.js → dist-NXZtp5_0.js} +2 -2
  17. package/dist/{dist-D3YSXNOO.js.map → dist-NXZtp5_0.js.map} +1 -1
  18. package/dist/main.js +375 -52
  19. package/dist/main.js.map +1 -1
  20. package/package.json +3 -1
  21. package/dist/LanguageLoader-DJZBFaqF.js +0 -3
  22. package/dist/LoomStore-pA-ohGNX.js.map +0 -1
  23. package/dist/tree-sitter-loom/editors/helix/queries/loom/highlights.scm +0 -120
  24. package/dist/tree-sitter-loom/editors/helix/queries/loom/injections.scm +0 -413
  25. package/dist/tree-sitter-loom/queries/highlights.scm +0 -120
  26. package/dist/tree-sitter-loom/queries/injections.scm +0 -85
  27. package/dist/tree-sitter-loom/src/parser.c +0 -4689
  28. package/dist/tree-sitter-loom/src/scanner.c +0 -293
  29. package/dist/tree-sitter-loom/src/tree_sitter/alloc.h +0 -54
  30. package/dist/tree-sitter-loom/src/tree_sitter/array.h +0 -330
  31. package/dist/tree-sitter-loom/src/tree_sitter/parser.h +0 -286
package/dist/main.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"main.js","names":["TypeId","Predicate.hasProperty","Schema.TaggedError","Schema.String","Runtime.errorReported","Runtime.errorExitCode","Proto","Schema.TrueLiterals","Schema.FalseLiterals","toCodecStringTree","Schema.toCodecStringTree","Schema.decodeUnknownEffect","Effect.mapError","Boolean","Schema.BooleanLiterals","Int","Schema.Int","String","Effect.succeed","format","Effect.fail","Path","Effect.fnUntraced","FileSystem.FileSystem","Path_.Path","reset","TypeId","Ansi.cyanBright","Ansi.blackBright","Ansi.green","Ansi.red","Ansi.white","Ansi.detectColors","Effect.map","Ansi.annotate","Ansi.combine","Ansi.italicized","Date","Effect.succeed","Option.none","Number","Effect.fail","Int","map","Redacted.make","run","Terminal.Terminal","Effect.cached","Terminal.QuitError","Effect.scoped","String","Effect.suspend","Effect.flatMap","Effect.isEffect","Action","Effect.orDie","Queue.take","Effect.raceFirst","Effect.ensuring","Ansi.cursorShow","Ansi.eraseLine","Ansi.cursorTo","Ansi.eraseLines","Arr.map","Arr.reduce","Ansi.cursorDown","Effect.fnUntraced","Ansi.cursorLeft","Ansi.cursorHide","Option.getOrElse","Option.isSome","Arr.match","Arr.isReadonlyArrayNonEmpty","Ansi.cursorSavePosition","Ansi.cursorRestorePosition","Ansi.underlined","Option.match","Effect.match","Option.some","Arr.empty","Arr.findFirstIndex","Arr.findFirst","Arr.findLast","Ansi.bold","Effect.sync","EffectNumber.round","Ansi.strikethrough","Ansi.cursorMove","TypeId","Proto","Predicate.hasProperty","Option.none","String","Primitive.String","Boolean","Primitive.Boolean","Int","Primitive.Int","ChoiceWithValue","Primitive.Choice","Path","Primitive.Path","Directory","withAlias","withDescription","Option.some","Effect.map","Effect.flatMap","optional","Effect.catchTags","Effect.succeed","withDefault","Effect.isEffect","Option.getOrElse","Option.match","Option.fromUndefinedOr","withMetavar","CliError.MissingArgument","Effect.mapError","CliError.InvalidValue","CliError.MissingOption","Predicate.isNotUndefined","Option.getOrUndefined","String","Param.String","Param.argumentKind","Param.Directory","optional","Param.optional","Ansi.detectColors","Option.getOrElse","Param.isParam","TypeId","Proto","Context.Service","Context.empty","Predicate.isNotUndefined","Effect.fail","CliError.ShowHelp","Param.extractSingleParams","Param.getParamMetadata","Primitive.getTypeName","Option.exists","Arr.map","Primitive.getChoiceKeys","Option.match","Option.some","Effect.fnUntraced","CliError.UnexpectedArgument","CliError.DuplicateOption","Primitive.getChoiceKeys","Primitive.getPathType","Param.extractSingleParams","Option.getOrUndefined","Param.getParamMetadata","generateFunction","generate","generate","sanitize","generate","generate","Bash.generate","Zsh.generate","Fish.generate","PowerShell.generate","Param.Boolean","Param.flagKind","Param.Int","Param.ChoiceWithValue","Param.withAlias","Param.withDescription","Param.withMetavar","Param.optional","Param.withDefault","Param.extractSingleParams","Param.getParamMetadata","Effect.gen","Context.Service","CliOutput.Formatter","HelpInternal.getHelpForCommandPath","Console.log","Effect.void","Flag.optional","Option.isNone","CommandDescriptor.fromCommand","Completions_.generate","Context.Reference","GlobalFlag.BuiltIns","Option.match","Effect.gen","Param.extractSingleParams","Param.isFlagParam","Option.none","Option.some","Primitive.isBoolean","CliError.InvalidValue","Primitive.getChoiceKeys","Primitive.getTypeName","Primitive.isTrueLiteral","Primitive.isFalseLiteral","CliError.UnrecognizedOption","CliError.UnknownSubcommand","run","Prompt.Theme","Console.log","Prompt.run","Prompt.Select","Param.getUnderlyingSingleOrThrow","Param.getParamMetadata","Prompt.Confirm","Prompt.Int","Option.getOrElse","Option.isSome","Effect.map","Primitive.getChoiceKeys","Prompt.Date","Prompt.Number","Prompt.Password","Redacted.value","value","Prompt.String","Option.getOrUndefined","Ansi.magenta","Ansi.annotate","Ansi.bold","Ansi.cyanBright","Ansi.blackBright","Ansi.white","Ansi.green","Ansi.red","Predicate.hasProperty","TypeId","make","Predicate.isNotUndefined","Effect.fnUntraced","Option.isNone","internal","CliError.ShowHelp","Effect.provideService","Param.extractSingleParams","CliError.UnrecognizedOption","Effect.gen","CliConfig.CliConfig","CliOutput.Formatter","error","Console.log","Console.error","Runtime.errorReported","Effect.flatMap","Lexer.lex","Parser.createFlagRegistry","Param.isFlagParam","Parser.consumeGlobalFlags","Parser.parseArgs","Parser.getCommandPath","GlobalFlag.Wizard","Prompt.Theme","Wizard.renderIntroduction","Wizard.run","Wizard.renderCompletion","Prompt.run","Prompt.Toggle","Effect.catchTag","Wizard.renderQuit","Effect.result","GlobalFlag.LogLevel","Option.none","Option.match","Context.empty","Context.make","References.MinimumLogLevel","Effect.provideContext","Effect.catchFilter","CliError.isCliError","Result.succeed","Result.fail","Effect.andThen","Effect.fail","Terminal.isQuitError","Effect.interrupt","Inspectable.BaseProto","make","Effect.map","Stream.decodeText","Stream.unwrap","Stream.splitLines","Effect.scoped","Effect.flatMap","Stream.runCollect","Stream.mkString","Context.Service","Context.getUnsafe","make","PlatformError.systemError","Sink.fromChannel","Channel.mapDone","Channel.fromTransform","Effect.succeed","Effect.flatMap","Effect.callback","Effect.void","Effect.sync","Effect.forever","Pull.catchDone","Cause.done","Effect.raceFirst","Effect.fail","Stream.fromChannel","Channel.fromTransform","MutableRef.make","Latch.makeUnsafe","Exit.fail","Cause.Done","Effect.suspend","Effect.fail","Effect.flatMap","Arr.of","Effect.succeed","Effect.as","Scope.addFinalizer","Effect.sync","Cause.UnknownError","Deferred.isDoneUnsafe","make","FileSystem.FileSystem","Path.Path","Effect.fnUntraced","Predicate.isUndefined","Stream.isStream","Sink.isSink","ChildProcess.parseFdName","Predicate.isNotUndefined","Sink.drain","Stream.empty","NodeSink.fromWritable","Effect.forkScoped","Stream.run","NodeStream.fromReadable","Stream.transduce","Effect.suspend","Predicate.isNotNull","Effect.as","Effect.succeed","Stream.merge","Effect.callback","Deferred.makeUnsafe","Effect.fail","Exit.succeed","Effect.sync","Effect.void","Effect.try","Effect.catch","Duration.toMillis","Deferred.await","Effect.acquireRelease","Deferred.isDone","Effect.ignore","Effect.map","Effect.flatMap","Stream.unwrap","ChildProcess.make","fdName","ChildProcess.fdName","Effect.forEach","Effect.gen","makeSpawner","layer","Effect.try","PlatformError.systemError","make","layer","EffectCrypto.Crypto","layer","NodeCrypto.layer","Error.badArgument","Option.flatMap","Option.fromNullishOr","BI.toNumber","Option.map","Effect.try","Effect.suspend","remove","Effect.acquireRelease","Effect.orDie","Effect.fail","Effect.succeed","Effect.flatMap","Effect.map","FileSystem.FileTypeId","Option.none","Option.some","Error.systemError","Effect.void","Effect.fnUntraced","Crypto","Effect.tryPromise","Effect.callback","ByteSize.bytes","Stream.callback","Effect.sync","Effect.matchEffect","Queue.offer","Cause.fail","Effect.tap","Effect.all","Effect.serviceOption","FileSystem.WatchBackend","Option.orElse","Option.getOrElse","Stream.unwrap","FileSystem.make","layer","FileSystem.FileSystem","layer","NodeFileSystem.layer","Effect.try","Path","NodePath","layer","layer","NodePath.layer","layer","Stdio.Stdio","layer","NodeStdio.layer","Queue.make","Effect.addFinalizer","Effect.sync","RcRef.make","Effect.acquireRelease","Queue.offerUnsafe","Effect.gen","Option.fromUndefinedOr","RcRef.get","Effect.suspend","Queue.poll","Effect.flatMap","Option.match","Effect.scoped","Effect.andThen","Queue.take","Effect.succeed","Effect.mapError","Terminal.QuitError","Effect.uninterruptible","Effect.callback","Predicate.isNullish","Effect.void","Effect.fail","Terminal.make","layer","Terminal.Terminal","layer","NodeTerminal.layer","NodeChildProcessSpawner.layer","NodeFileSystem.layer","NodeCrypto.layer","NodePath.layer","NodeStdio.layer","NodeTerminal.layer","runMain","NodeRuntime.runMain"],"sources":["../../../node_modules/effect/dist/cli/CliError.js","../../../node_modules/effect/dist/cli/Primitive.js","../../../node_modules/effect/dist/cli/internal/ansi.js","../../../node_modules/effect/dist/cli/Prompt.js","../../../node_modules/effect/dist/cli/Param.js","../../../node_modules/effect/dist/cli/Argument.js","../../../node_modules/effect/dist/cli/CliOutput.js","../../../node_modules/effect/dist/cli/internal/config.js","../../../node_modules/effect/dist/cli/internal/command.js","../../../node_modules/effect/dist/cli/internal/completions/descriptor.js","../../../node_modules/effect/dist/cli/internal/completions/bash.js","../../../node_modules/effect/dist/cli/internal/completions/fish.js","../../../node_modules/effect/dist/cli/internal/completions/powershell.js","../../../node_modules/effect/dist/cli/internal/completions/zsh.js","../../../node_modules/effect/dist/cli/Completions.js","../../../node_modules/effect/dist/cli/Flag.js","../../../node_modules/effect/dist/cli/internal/help.js","../../../node_modules/effect/dist/cli/GlobalFlag.js","../../../node_modules/effect/dist/cli/CliConfig.js","../../../node_modules/effect/dist/cli/internal/lexer.js","../../../node_modules/effect/dist/cli/internal/auto-suggest.js","../../../node_modules/effect/dist/cli/internal/parser.js","../../../node_modules/effect/dist/cli/internal/wizard.js","../../../node_modules/effect/dist/cli/Command.js","../../../node_modules/effect/dist/process/ChildProcessSpawner.js","../../../node_modules/effect/dist/process/ChildProcess.js","../../../node_modules/@effect/platform-node-shared/dist/internal/nodeChildProcessSpawner.js","../../../node_modules/@effect/platform-node-shared/dist/internal/utils.js","../../../node_modules/@effect/platform-node-shared/dist/NodeSink.js","../../../node_modules/@effect/platform-node-shared/dist/NodeStream.js","../../../node_modules/@effect/platform-node-shared/dist/NodeChildProcessSpawner.js","../../../node_modules/@effect/platform-node-shared/dist/NodeCrypto.js","../../../node_modules/@effect/platform-node/dist/NodeCrypto.js","../../../node_modules/@effect/platform-node-shared/dist/NodeFileSystem.js","../../../node_modules/@effect/platform-node/dist/NodeFileSystem.js","../../../node_modules/@effect/platform-node-shared/dist/NodePath.js","../../../node_modules/@effect/platform-node/dist/NodePath.js","../../../node_modules/@effect/platform-node-shared/dist/NodeStdio.js","../../../node_modules/@effect/platform-node/dist/NodeStdio.js","../../../node_modules/@effect/platform-node-shared/dist/NodeTerminal.js","../../../node_modules/@effect/platform-node/dist/NodeTerminal.js","../../../node_modules/@effect/platform-node/dist/NodeServices.js","../../../node_modules/@effect/platform-node-shared/dist/NodeRuntime.js","../../../node_modules/@effect/platform-node/dist/NodeRuntime.js","../../loom-lang/src/LoomLock.ts","../../loom-lang/src/LoomTangler.ts","../../loom-lang/src/weave/LoomWeaver.ts","../../loom-lang/src/weave/LoomContents.ts","../src/main.ts"],"sourcesContent":["/**\n * Defines structured errors for the unstable CLI parser and runner.\n *\n * CLI errors describe problems such as unknown or duplicate flags, missing\n * flags or arguments, unexpected positional arguments, invalid values, unknown\n * subcommands, user handler failures, and requests to show command help. This\n * module includes the `CliError` union, the `isCliError` guard, schema-backed\n * error classes with display messages, and the `NonShowHelpErrors` union used\n * when parse or validation errors should be shown with help output.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Predicate from \"../Predicate.js\";\nimport * as Runtime from \"../Runtime.js\";\nimport * as Schema from \"../Schema.js\";\n/**\n * @stability unstable\n * @category type IDs\n * @since 4.0.0\n */\nconst TypeId = \"~effect/cli/CliError\";\n/**\n * Type guard to check if a value is a CLI error.\n *\n * **Example** (Checking CLI errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/cli\"\n *\n * const error = new CliError.MissingOption({ option: \"api-key\" })\n * const program = CliError.isCliError(error)\n * ? Effect.succeed(error.message)\n * : Effect.fail(\"Unknown error\")\n *\n * await Effect.runPromise(program) // => \"Missing required flag: --api-key\"\n * ```\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isCliError = u => Predicate.hasProperty(u, TypeId);\n/**\n * Error thrown when an unrecognized option is encountered.\n *\n * **Example** (Creating unrecognized option errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/cli\"\n *\n * // Creating an unrecognized option error\n * const unrecognizedError = new CliError.UnrecognizedOption({\n * option: \"--unknown-flag\",\n * command: [\"deploy\", \"production\"],\n * suggestions: [\"--verbose\", \"--force\"]\n * })\n *\n * unrecognizedError._tag // => \"UnrecognizedOption\"\n * unrecognizedError.option // => \"--unknown-flag\"\n * unrecognizedError.command // => [\"deploy\", \"production\"]\n *\n * // In CLI parsing context\n * const parseCommand = Effect.gen(function*() {\n * // If parsing encounters unknown flag\n * return yield* unrecognizedError\n * })\n *\n * const parseError = await Effect.runPromise(Effect.flip(parseCommand))\n * parseError._tag // => \"UnrecognizedOption\"\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class UnrecognizedOption extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/UnrecognizedOption`)(\"UnrecognizedOption\", {\n option: Schema.String,\n command: /*#__PURE__*/Schema.optional(/*#__PURE__*/Schema.Array(Schema.String)),\n suggestions: /*#__PURE__*/Schema.Array(Schema.String)\n}) {\n /**\n * Marks this value as a CLI parsing error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Formats the unrecognized option with command context and suggestions.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n const suggestionText = this.suggestions.length > 0 ? `\\n\\n Did you mean this?\\n ${this.suggestions.join(\"\\n \")}` : \"\";\n const baseMessage = this.command ? `Unrecognized flag: ${this.option} in command ${this.command.join(\" \")}` : `Unrecognized flag: ${this.option}`;\n return baseMessage + suggestionText;\n }\n}\n/**\n * Error thrown when duplicate option names are detected between parent and child commands.\n *\n * **Example** (Creating duplicate option errors)\n *\n * ```ts import.meta.vitest\n * import { CliError } from \"effect/cli\"\n *\n * const duplicateError = new CliError.DuplicateOption({\n * option: \"--verbose\",\n * parentCommand: \"myapp\",\n * childCommand: \"deploy\"\n * })\n *\n * duplicateError._tag // => \"DuplicateOption\"\n * duplicateError.option // => \"--verbose\"\n * duplicateError.parentCommand // => \"myapp\"\n * duplicateError.childCommand // => \"deploy\"\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class DuplicateOption extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/DuplicateOption`)(\"DuplicateOption\", {\n option: Schema.String,\n parentCommand: Schema.String,\n childCommand: Schema.String\n}) {\n /**\n * Marks this value as a CLI configuration error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Explains which parent and child commands define the duplicate option.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n return `Duplicate flag name \"${this.option}\" in parent command \"${this.parentCommand}\" and subcommand \"${this.childCommand}\". ` + `Parent will always claim this flag (Mode A semantics). Consider renaming one of them to avoid confusion.`;\n }\n}\n/**\n * Error thrown when a required option is missing.\n *\n * **Example** (Creating missing option errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/cli\"\n *\n * const missingOptionError = new CliError.MissingOption({\n * option: \"api-key\"\n * })\n *\n * const details = [missingOptionError._tag, missingOptionError.option] // => [\"MissingOption\", \"api-key\"]\n *\n * // In validation context\n * const validateRequiredOptions = (options: Record<string, string | undefined>) =>\n * Effect.gen(function*() {\n * const apiKey = options[\"api-key\"]\n * if (!apiKey) {\n * return yield* missingOptionError\n * }\n * return apiKey\n * })\n *\n * const validationError = await Effect.runPromise(Effect.flip(validateRequiredOptions({})))\n * validationError._tag // => \"MissingOption\"\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class MissingOption extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/MissingOption`)(\"MissingOption\", {\n option: Schema.String\n}) {\n /**\n * Marks this value as a missing CLI option error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Formats the missing required flag for display.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n return `Missing required flag: --${this.option}`;\n }\n}\n/**\n * Error thrown when a required positional argument is missing.\n *\n * **Example** (Creating missing argument errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/cli\"\n *\n * const missingArgError = new CliError.MissingArgument({\n * argument: \"target\"\n * })\n *\n * const details = [missingArgError._tag, missingArgError.argument] // => [\"MissingArgument\", \"target\"]\n *\n * // In argument parsing\n * const parseArguments = (args: Array<string>) =>\n * Effect.gen(function*() {\n * if (args.length === 0) {\n * return yield* missingArgError\n * }\n * return args[0]\n * })\n *\n * const parseError = await Effect.runPromise(Effect.flip(parseArguments([])))\n * parseError._tag // => \"MissingArgument\"\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class MissingArgument extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/MissingArgument`)(\"MissingArgument\", {\n argument: Schema.String\n}) {\n /**\n * Marks this value as a missing CLI argument error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Formats the missing required positional argument for display.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n return `Missing required argument: ${this.argument}`;\n }\n}\n/**\n * Error thrown when positional arguments remain after a command has parsed all\n * of its parameters.\n *\n * **Example** (Reporting unexpected arguments)\n *\n * ```ts import.meta.vitest\n * import { CliError } from \"effect/cli\"\n *\n * const error = new CliError.UnexpectedArgument({\n * arguments: [\"extra.txt\"]\n * })\n *\n * const details = [error._tag, error.arguments] // => [\"UnexpectedArgument\", [\"extra.txt\"]]\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class UnexpectedArgument extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/UnexpectedArgument`)(\"UnexpectedArgument\", {\n arguments: /*#__PURE__*/Schema.Array(Schema.String)\n}) {\n /**\n * Marks this value as an unexpected CLI argument error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Formats the unexpected positional arguments for display.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n const label = this.arguments.length === 1 ? \"argument\" : \"arguments\";\n return `Unexpected positional ${label}: ${this.arguments.map(value => JSON.stringify(value)).join(\", \")}`;\n }\n}\n/**\n * Error thrown when an option or argument value is invalid.\n *\n * **Example** (Creating invalid value errors)\n *\n * ```ts import.meta.vitest\n * import { CliError } from \"effect/cli\"\n *\n * const invalidValueError = new CliError.InvalidValue({\n * option: \"port\",\n * value: \"abc123\",\n * expected: \"integer between 1 and 65535\",\n * kind: \"flag\"\n * })\n *\n * invalidValueError._tag // => \"InvalidValue\"\n * invalidValueError.kind // => \"flag\"\n * invalidValueError.option // => \"port\"\n * invalidValueError.value // => \"abc123\"\n *\n * // For positional arguments\n * const invalidArgError = new CliError.InvalidValue({\n * option: \"count\",\n * value: \"abc\",\n * expected: \"integer\",\n * kind: \"argument\"\n * })\n *\n * const details = [invalidArgError.kind, invalidArgError.option, invalidArgError.value] // => [\"argument\", \"count\", \"abc\"]\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class InvalidValue extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/InvalidValue`)(\"InvalidValue\", {\n option: Schema.String,\n value: Schema.String,\n expected: Schema.String,\n kind: /*#__PURE__*/Schema.Union([/*#__PURE__*/Schema.Literal(\"flag\"), /*#__PURE__*/Schema.Literal(\"argument\")])\n}) {\n /**\n * Marks this value as an invalid CLI value error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Formats the invalid flag or argument value with the expected input.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n const expectation = this.expected.startsWith(\"Expected \") || this.expected.startsWith(\"Expected:\") ? this.expected : `Expected: ${this.expected}`;\n if (this.kind === \"argument\") {\n return `Invalid value for argument <${this.option}>: \"${this.value}\". ${expectation}`;\n }\n if (this.value.length === 0) {\n return `Missing value for flag --${this.option}. ${expectation}`;\n }\n return `Invalid value for flag --${this.option}: \"${this.value}\". ${expectation}`;\n }\n}\n/**\n * Error thrown when an unknown subcommand is encountered.\n *\n * **Example** (Creating unknown subcommand errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/cli\"\n *\n * const unknownSubcommandError = new CliError.UnknownSubcommand({\n * subcommand: \"deplyo\", // typo\n * parent: [\"myapp\"],\n * suggestions: [\"deploy\", \"destroy\"]\n * })\n *\n * unknownSubcommandError._tag // => \"UnknownSubcommand\"\n * unknownSubcommandError.subcommand // => \"deplyo\"\n * unknownSubcommandError.parent // => [\"myapp\"]\n *\n * // In subcommand parsing\n * const parseSubcommand = (subcommand: string) =>\n * Effect.gen(function*() {\n * const validCommands = [\"deploy\", \"destroy\", \"status\"]\n * if (!validCommands.includes(subcommand)) {\n * return yield* unknownSubcommandError\n * }\n * return subcommand\n * })\n *\n * const parseError = await Effect.runPromise(Effect.flip(parseSubcommand(\"deplyo\")))\n * parseError._tag // => \"UnknownSubcommand\"\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class UnknownSubcommand extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/UnknownSubcommand`)(\"UnknownSubcommand\", {\n subcommand: Schema.String,\n parent: /*#__PURE__*/Schema.optional(/*#__PURE__*/Schema.Array(Schema.String)),\n suggestions: /*#__PURE__*/Schema.Array(Schema.String)\n}) {\n /**\n * Marks this value as an unknown CLI subcommand error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Formats the unknown subcommand with parent command context and suggestions.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n const suggestionText = this.suggestions.length > 0 ? `\\n\\n Did you mean this?\\n ${this.suggestions.join(\"\\n \")}` : \"\";\n return this.parent ? `Unknown subcommand \"${this.subcommand}\" for \"${this.parent.join(\" \")}\"${suggestionText}` : `Unknown subcommand \"${this.subcommand}\"${suggestionText}`;\n }\n}\n/**\n * Error wrapper for user handler failures in the CLI error channel.\n *\n * **Details**\n *\n * `userMessage` can provide safe, user-facing text independently of the\n * underlying cause. When omitted or empty, `message` uses a non-empty string\n * cause or `Error.message`, then falls back to `\"An error occurred\"`.\n *\n * **Example** (Wrapping user errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/cli\"\n *\n * // Wrapping user errors\n * const userError = new CliError.UserError({\n * cause: new Error(\"Database connection failed for postgres://localhost\"),\n * userMessage: \"Could not connect to the database\"\n * })\n *\n * // In command handler\n * const deployCommand = Effect.gen(function*() {\n * const result = yield* Effect.try({\n * try: () => ({ deployed: true }),\n * catch: (error) => new CliError.UserError({ cause: error })\n * })\n * return result\n * })\n *\n * // In error handling\n * const handleError = (error: CliError.CliError): Effect.Effect<number> => {\n * if (error._tag === \"UserError\") {\n * return Effect.succeed(1) // Exit code 1\n * }\n * return Effect.succeed(0)\n * }\n *\n * await Effect.runPromise(deployCommand) // => { deployed: true }\n * await Effect.runPromise(handleError(userError)) // => 1\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class UserError extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/UserError`)(\"UserError\", {\n cause: /*#__PURE__*/Schema.Defect(),\n userMessage: /*#__PURE__*/Schema.optionalKey(Schema.String)\n}) {\n /**\n * Marks this value as a user handler error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Controls whether the runtime logger should report this error. The CLI\n * runner sets this to `false` after rendering the error itself.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [Runtime.errorReported] = true;\n /**\n * Returns the explicit user-facing message or a safe fallback from `cause`.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n if (this.userMessage) return this.userMessage;\n if (typeof this.cause === \"string\" && this.cause) return this.cause;\n if (this.cause instanceof Error && this.cause.message) return this.cause.message;\n return \"An error occurred\";\n }\n}\n/**\n * Schema for concrete CLI errors that can be reported together with help output.\n *\n * **Details**\n *\n * This excludes `ShowHelp` itself, allowing parse and validation errors to be\n * stored in `ShowHelp.errors` without nesting another help-control value.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const NonShowHelpErrors = /*#__PURE__*/Schema.Union([UnrecognizedOption, DuplicateOption, MissingOption, MissingArgument, UnexpectedArgument, InvalidValue, UnknownSubcommand, UserError]);\n/**\n * Error data requesting CLI help rendering for a command path.\n *\n * **Details**\n *\n * It is used for explicit help requests and for parse or validation failures\n * that should be shown with help text. When `errors` is non-empty, the runtime\n * exit code is `1`; otherwise it is `0`.\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class ShowHelp extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/ShowHelp`)(\"ShowHelp\", {\n commandPath: /*#__PURE__*/Schema.Array(Schema.String),\n errors: /*#__PURE__*/Schema.Array(NonShowHelpErrors)\n}) {\n [TypeId] = TypeId;\n [Runtime.errorExitCode] = this.errors.length ? 1 : 0;\n [Runtime.errorReported] = false;\n get message() {\n return \"Help requested\";\n }\n}\n//# sourceMappingURL=CliError.js.map","/**\n * Parses raw command-line strings into typed values.\n *\n * A `Primitive<A>` receives one string and returns an `Effect` that either\n * produces an `A` or fails with a parser message. `Argument` and `Flag` build\n * on these primitives to add names, aliases, defaults, prompts, configuration\n * fallbacks, repetition, and help metadata. Primitive parsers cover common\n * scalar values, paths, files, structured config files, schema-decoded input,\n * redacted values, and key-value pairs.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Effect from \"../Effect.js\";\nimport * as Ini from \"../encoding/Ini.js\";\nimport * as Toml from \"../encoding/Toml.js\";\nimport * as Yaml from \"../encoding/Yaml.js\";\nimport * as FileSystem from \"../FileSystem.js\";\nimport { format } from \"../Formatter.js\";\nimport { identity } from \"../Function.js\";\nimport * as Path_ from \"../Path.js\";\nimport * as Redacted_ from \"../Redacted.js\";\nimport * as Schema from \"../Schema.js\";\nconst TypeId = \"~effect/cli/Primitive\";\nconst Proto = {\n [TypeId]: {\n _A: identity\n }\n};\n/**\n * @internal\n */\nexport const isTrueLiteral = /*#__PURE__*/Schema.is(Schema.TrueLiterals);\n/**\n * @internal\n */\nexport const isFalseLiteral = /*#__PURE__*/Schema.is(Schema.FalseLiterals);\n/**\n * @internal\n */\nexport const isBoolean = p => p._tag === \"Boolean\";\nconst makePrimitive = (tag, parse) => Object.assign(Object.create(Proto), {\n _tag: tag,\n parse\n});\nconst makeSchemaPrimitive = (tag, schema) => {\n const toCodecStringTree = Schema.toCodecStringTree(schema);\n const decode = Schema.decodeUnknownEffect(toCodecStringTree);\n return makePrimitive(tag, value => Effect.mapError(decode(value), error => error.message));\n};\n/**\n * Creates a primitive that parses boolean values from string input.\n *\n * **Details**\n *\n * Recognizes various forms of true/false values:\n * - True values: \"true\", \"1\", \"y\", \"yes\", \"on\"\n * - False values: \"false\", \"0\", \"n\", \"no\", \"off\"\n *\n * **Example** (Parsing boolean values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parseBoolean = Effect.all([\n * Primitive.Boolean.parse(\"true\"),\n * Primitive.Boolean.parse(\"yes\"),\n * Primitive.Boolean.parse(\"false\"),\n * Primitive.Boolean.parse(\"0\")\n * ])\n *\n * await Effect.runPromise(parseBoolean.pipe(Effect.provide(CliTestLayer))) // => [true, true, false, false]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Boolean = /*#__PURE__*/makeSchemaPrimitive(\"Boolean\", Schema.BooleanLiterals);\n/**\n * Creates a primitive that parses finite numbers from string input.\n *\n * **Example** (Parsing finite numbers)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parseFloat = Effect.all([\n * Primitive.Finite.parse(\"3.14\"),\n * Primitive.Finite.parse(\"-42.5\"),\n * Primitive.Finite.parse(\"0\")\n * ])\n *\n * await Effect.runPromise(parseFloat.pipe(Effect.provide(CliTestLayer))) // => [3.14, -42.5, 0]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Finite = /*#__PURE__*/makeSchemaPrimitive(\"Finite\", Schema.Finite);\n/**\n * Creates a primitive that parses integer numbers from string input.\n *\n * **Example** (Parsing integer values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parseInteger = Effect.all([\n * Primitive.Int.parse(\"42\"),\n * Primitive.Int.parse(\"-123\"),\n * Primitive.Int.parse(\"0\")\n * ])\n *\n * await Effect.runPromise(parseInteger.pipe(Effect.provide(CliTestLayer))) // => [42, -123, 0]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Int = /*#__PURE__*/makeSchemaPrimitive(\"Int\", Schema.Int);\n/**\n * Creates a primitive that parses Date objects from string input.\n *\n * **Example** (Parsing date values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parseDate = Effect.gen(function*() {\n * const result = yield* Primitive.Date.parse(\"2023-12-25\")\n * return result.toISOString()\n * })\n *\n * await Effect.runPromise(parseDate.pipe(Effect.provide(CliTestLayer))) // => \"2023-12-25T00:00:00.000Z\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Date = /*#__PURE__*/makeSchemaPrimitive(\"Date\", Schema.Date);\n/**\n * Creates a primitive that accepts any string value without validation.\n *\n * **Example** (Parsing string values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parseString = Effect.all([\n * Primitive.String.parse(\"hello world\"),\n * Primitive.String.parse(\"\"),\n * Primitive.String.parse(\"123\")\n * ])\n *\n * await Effect.runPromise(parseString.pipe(Effect.provide(CliTestLayer))) // => [\"hello world\", \"\", \"123\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const String = /*#__PURE__*/makePrimitive(\"String\", value => Effect.succeed(value));\n/**\n * Creates a primitive that accepts only specific choice values mapped to custom types.\n *\n * **Example** (Parsing choices)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\"\n *\n * const logLevelPrimitive = Primitive.Choice<LogLevel>([\n * [\"debug\", \"debug\"],\n * [\"info\", \"info\"],\n * [\"warn\", \"warn\"],\n * [\"error\", \"error\"]\n * ])\n *\n * const parseLogLevel = Effect.all([\n * logLevelPrimitive.parse(\"info\"),\n * logLevelPrimitive.parse(\"debug\")\n * ])\n *\n * await Effect.runPromise(parseLogLevel.pipe(Effect.provide(CliTestLayer))) // => [\"info\", \"debug\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Choice = choices => {\n const choiceMap = new Map(choices);\n const validChoices = choices.map(([key]) => format(key)).join(\" | \");\n const primitive = makePrimitive(\"Choice\", value => {\n if (choiceMap.has(value)) {\n return Effect.succeed(choiceMap.get(value));\n }\n return Effect.fail(validChoices);\n });\n return Object.assign(primitive, {\n choiceKeys: choices.map(([key]) => key)\n });\n};\n/**\n * Creates a primitive that validates and resolves file system paths.\n *\n * **Example** (Parsing file system paths)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const services = Layer.mergeAll(\n * Path.layer,\n * FileSystem.layerNoop({\n * exists: () => Effect.succeed(true),\n * stat: () => Effect.succeed({ type: \"File\" } as FileSystem.File.Info)\n * }),\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const program = Effect.gen(function*() {\n * const filePrimitive = Primitive.Path(\"file\", true)\n * const filePath = yield* filePrimitive.parse(\"./package.json\")\n * return filePath.endsWith(\"/package.json\")\n * }).pipe(Effect.provide(services))\n *\n * await Effect.runPromise(program) // => true\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Path = (pathType, mustExist) => {\n const primitive = makePrimitive(\"Path\", Effect.fnUntraced(function* (value) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path_.Path;\n // Resolve the path to absolute\n const absolutePath = path.isAbsolute(value) ? value : path.resolve(value);\n // Check if path exists\n const exists = yield* Effect.mapError(fs.exists(absolutePath), error => `Failed to check path existence: ${error.message}`);\n // Validate existence requirements\n if (mustExist === true && !exists) {\n return yield* Effect.fail(`Path does not exist: ${absolutePath}`);\n }\n // Validate path type if it exists\n if (exists && pathType !== \"either\") {\n const stat = yield* Effect.mapError(fs.stat(absolutePath), error => `Failed to stat path: ${error.message}`);\n if (pathType === \"file\" && stat.type !== \"File\") {\n return yield* Effect.fail(`Path is not a file: ${absolutePath}`);\n }\n if (pathType === \"directory\" && stat.type !== \"Directory\") {\n return yield* Effect.fail(`Path is not a directory: ${absolutePath}`);\n }\n }\n return absolutePath;\n }));\n return Object.assign(primitive, {\n pathType\n });\n};\n/**\n * Creates a primitive that wraps string input in `Redacted`.\n *\n * **Details**\n *\n * The wrapped value is hidden when formatted or inspected, while the original\n * string remains available through the `Redacted` API when explicitly needed.\n *\n * **Example** (Parsing redacted values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Redacted, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parseRedacted = Effect.gen(function*() {\n * const result = yield* Primitive.Redacted.parse(\"secret-password\")\n * return [Redacted.value(result), String(result)] as const\n * })\n *\n * await Effect.runPromise(parseRedacted.pipe(Effect.provide(CliTestLayer))) // => [\"secret-password\", \"<redacted>\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Redacted = /*#__PURE__*/makePrimitive(\"Redacted\", value => Effect.succeed(Redacted_.make(value)));\n/**\n * Creates a primitive that reads and returns the contents of a file as a string.\n *\n * **Example** (Reading file text)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const services = Layer.mergeAll(\n * Path.layer,\n * FileSystem.layerNoop({\n * exists: () => Effect.succeed(true),\n * stat: () => Effect.succeed({ type: \"File\" } as FileSystem.File.Info),\n * readFileString: () => Effect.succeed('{\"private\":true}')\n * }),\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const readConfigFile = Effect.gen(function*() {\n * const content = yield* Primitive.FileText.parse(\"./package.json\")\n * return JSON.parse(content) as { private: boolean }\n * }).pipe(Effect.provide(services))\n *\n * await Effect.runPromise(readConfigFile) // => { private: true }\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileText = /*#__PURE__*/makePrimitive(\"FileText\", /*#__PURE__*/Effect.fnUntraced(function* (filePath) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path_.Path;\n // Resolve to absolute path\n const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(filePath);\n // Check if file exists\n const exists = yield* Effect.mapError(fs.exists(absolutePath), error => `Failed to check file existence: ${error.message}`);\n if (!exists) {\n return yield* Effect.fail(`File does not exist: ${absolutePath}`);\n }\n // Check if it's actually a file\n const stat = yield* Effect.mapError(fs.stat(absolutePath), error => `Failed to stat file: ${error.message}`);\n if (stat.type !== \"File\") {\n return yield* Effect.fail(`Path is not a file: ${absolutePath}`);\n }\n // Read file content\n const content = yield* Effect.mapError(fs.readFileString(absolutePath), error => `Failed to read file: ${error.message}`);\n return content;\n}));\nconst fileParsers = {\n ini: content => Ini.parse(content),\n json: content => JSON.parse(content),\n toml: content => Toml.parse(content),\n yml: content => Yaml.parse(content),\n yaml: content => Yaml.parse(content)\n};\n/**\n * Creates a primitive that reads a file and parses its content as structured\n * data.\n *\n * **Details**\n *\n * The parser is selected from `options.format` when provided, otherwise from\n * the file extension. Supported formats include INI, JSON, TOML, YAML, and YML.\n *\n * **Example** (Parsing file content)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const services = Layer.mergeAll(\n * Path.layer,\n * FileSystem.layerNoop({\n * exists: () => Effect.succeed(true),\n * stat: () => Effect.succeed({ type: \"File\" } as FileSystem.File.Info),\n * readFileString: () => Effect.succeed('{\"private\":true}')\n * }),\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const jsonFilePrimitive = Primitive.FileParse({ format: \"json\" })\n *\n * const loadConfig = Effect.gen(function*() {\n * const config = yield* jsonFilePrimitive.parse(\"./package.json\")\n * return config as { private: boolean }\n * }).pipe(Effect.provide(services))\n *\n * await Effect.runPromise(loadConfig) // => { private: true }\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileParse = options => {\n return makePrimitive(\"FileParse\", Effect.fnUntraced(function* (filePath) {\n const fileFormat = options?.format ?? filePath.split(\".\").pop();\n const parser = fileParsers[fileFormat];\n if (parser === undefined) {\n return yield* Effect.fail(`Unsupported file format: ${fileFormat}`);\n }\n const content = yield* FileText.parse(filePath);\n return yield* Effect.try({\n try: () => parser(content),\n catch: error => `Failed to parse '.${fileFormat}' file content: ${error}`\n });\n }));\n};\n/**\n * Reads and parses file content using the specified schema.\n *\n * **Example** (Parsing file content with a schema)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Schema, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const services = Layer.mergeAll(\n * Path.layer,\n * FileSystem.layerNoop({\n * exists: () => Effect.succeed(true),\n * stat: () => Effect.succeed({ type: \"File\" } as FileSystem.File.Info),\n * readFileString: () => Effect.succeed('{\"private\":true}')\n * }),\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const ConfigSchema = Schema.Struct({\n * private: Schema.Boolean\n * })\n *\n * const jsonConfigPrimitive = Primitive.FileSchema(ConfigSchema, {\n * format: \"json\"\n * })\n *\n * const loadConfig = Effect.gen(function*() {\n * return yield* jsonConfigPrimitive.parse(\"./package.json\")\n * }).pipe(Effect.provide(services))\n *\n * await Effect.runPromise(loadConfig) // => { private: true }\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileSchema = (schema, options) => {\n const decode = Schema.decodeUnknownEffect(schema);\n return makePrimitive(\"FileSchema\", Effect.fnUntraced(function* (filePath) {\n const content = yield* FileParse(options).parse(filePath);\n return yield* Effect.mapError(decode(content), error => options?.errorFormatter?.(error.issue) ?? error.toString());\n }));\n};\n/**\n * Parses a single `key=value` pair into a record object.\n *\n * **Details**\n *\n * Splits at the first `=`. Keys and values must be non-empty; values may contain `=`.\n *\n * **Example** (Parsing key-value pairs)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parseKeyValue = Effect.all([\n * Primitive.KeyValuePair.parse(\"name=john\"),\n * Primitive.KeyValuePair.parse(\"port=3000\"),\n * Primitive.KeyValuePair.parse(\"debug=true\")\n * ])\n *\n * const result = await Effect.runPromise(parseKeyValue.pipe(Effect.provide(CliTestLayer)))\n * result // => [{ name: \"john\" }, { port: \"3000\" }, { debug: \"true\" }]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const KeyValuePair = /*#__PURE__*/makePrimitive(\"KeyValuePair\", /*#__PURE__*/Effect.fnUntraced(function* (value) {\n const separator = value.indexOf(\"=\");\n if (separator === -1) {\n return yield* Effect.fail(`Invalid key=value format. Expected format: key=value, got: ${value}`);\n }\n const key = value.slice(0, separator);\n const val = value.slice(separator + 1);\n if (!key || !val) {\n return yield* Effect.fail(`Invalid key=value format. Both key and value must be non-empty. Got: ${value}`);\n }\n return {\n [key]: val\n };\n}));\n/**\n * A primitive that always fails to parse.\n *\n * **Example** (Rejecting option values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const program = Effect.gen(function*() {\n * return yield* Primitive.Never.parse(\"any-value\")\n * })\n *\n * await Effect.runPromise(Effect.flip(program).pipe(Effect.provide(CliTestLayer))) // => \"This option does not accept values\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Never = /*#__PURE__*/makePrimitive(\"Never\", () => Effect.fail(\"This option does not accept values\"));\n/**\n * Gets a human-readable type name for a primitive.\n *\n * **When to use**\n *\n * Use when you need the display type name for a `Primitive`, such as when\n * generating CLI help documentation.\n *\n * **Example** (Getting primitive type names)\n *\n * ```ts import.meta.vitest\n * import { Primitive } from \"effect/cli\"\n *\n * Primitive.getTypeName(Primitive.String) // => \"string\"\n * Primitive.getTypeName(Primitive.Int) // => \"integer\"\n * Primitive.getTypeName(Primitive.Boolean) // => \"boolean\"\n * Primitive.getTypeName(Primitive.Date) // => \"date\"\n * Primitive.getTypeName(Primitive.KeyValuePair) // => \"key=value\"\n *\n * const logLevelChoice = Primitive.Choice([\n * [\"debug\", \"debug\"],\n * [\"info\", \"info\"]\n * ])\n * Primitive.getTypeName(logLevelChoice) // => \"choice\"\n * ```\n *\n * @stability unstable\n * @category getters\n * @since 4.0.0\n */\nexport const getTypeName = primitive => {\n switch (primitive._tag) {\n case \"Boolean\":\n return \"boolean\";\n case \"String\":\n return \"string\";\n case \"Int\":\n return \"integer\";\n case \"Finite\":\n return \"number\";\n case \"Date\":\n return \"date\";\n case \"Path\":\n return \"path\";\n case \"Choice\":\n return \"choice\";\n case \"Redacted\":\n return \"string\";\n case \"FileText\":\n return \"file\";\n case \"FileParse\":\n return \"file\";\n case \"FileSchema\":\n return \"file\";\n case \"KeyValuePair\":\n return \"key=value\";\n case \"Never\":\n return \"none\";\n default:\n return \"value\";\n }\n};\n/**\n * @internal\n */\nexport const getChoiceKeys = primitive => primitive._tag === \"Choice\" ? primitive.choiceKeys : undefined;\n/**\n * @internal\n */\nexport const getPathType = primitive => primitive._tag === \"Path\" ? primitive.pathType : undefined;\n//# sourceMappingURL=Primitive.js.map","/**\n * Internal ANSI escape sequence helpers used by the unstable CLI rendering\n * implementation. This module centralizes the control codes for text styling,\n * cursor movement, line erasing, and terminal notifications so renderers can\n * compose terminal output without scattering raw escape sequences throughout\n * the CLI internals.\n *\n * The helpers deliberately work with plain strings because terminal rendering\n * is sensitive to ordering: style codes must be reset after annotated text,\n * cursor operations must account for one-based terminal coordinates, and line\n * clearing usually needs to preserve the cursor position expected by the next\n * frame.\n */\nconst ESC = \"\\x1B[\";\nconst BEL = \"\\x07\";\nconst SEP = \";\";\n/**\n * @internal\n */\nexport const reset = `${ESC}0m`;\n/**\n * @internal\n */\nexport const bold = `${ESC}1m`;\n/**\n * @internal\n */\nexport const italicized = `${ESC}3m`;\n/**\n * @internal\n */\nexport const underlined = `${ESC}4m`;\n/**\n * @internal\n */\nexport const strikethrough = `${ESC}9m`;\n/**\n * @internal\n */\nexport const cursorShow = `${ESC}?25h`;\n/**\n * @internal\n */\nexport const cursorHide = `${ESC}?25l`;\n/**\n * @internal\n */\nexport const cursorLeft = `${ESC}G`;\n/**\n * @internal\n */\nexport const cursorSavePosition = `${ESC}s`;\n/**\n * @internal\n */\nexport const cursorRestorePosition = `${ESC}u`;\n/**\n * @internal\n */\nexport const eraseLine = `${ESC}2K`;\n/**\n * @internal\n */\nexport const beep = BEL;\n/**\n * @internal\n */\nexport const red = `${ESC}31m`;\n/**\n * @internal\n */\nexport const green = `${ESC}32m`;\n/**\n * @internal\n */\nexport const magenta = `${ESC}35m`;\n/**\n * @internal\n */\nexport const white = `${ESC}37m`;\n/**\n * @internal\n */\nexport const blackBright = `${ESC}90m`;\n/**\n * @internal\n */\nexport const cyanBright = `${ESC}96m`;\n/**\n * Wraps `text` in the given styles followed by a reset. When `colors` is\n * `false` the text is returned unchanged, so callers gate color and style\n * escapes in one place while cursor and erase controls stay untouched.\n *\n * @internal\n */\nexport const annotate = (colors, text, ...styles) => {\n if (!colors) return text;\n return `${styles.flat().join(\"\")}${text}${reset}`;\n};\n/**\n * Detects whether CLI output should use color and style escapes: stdout must\n * be a TTY and `NO_COLOR` must be unset or empty.\n *\n * @internal\n */\nexport const detectColors = () => {\n const globalProcess = globalThis.process;\n return typeof globalProcess === \"object\" && globalProcess !== null && typeof globalProcess.stdout === \"object\" && globalProcess.stdout !== null && globalProcess.stdout.isTTY === true && !globalProcess.env?.NO_COLOR;\n};\nexport const combine = (...styles) => styles;\n/**\n * @internal\n */\nexport const cursorTo = (column, row) => {\n if (row === undefined) {\n return `${ESC}${Math.max(column + 1, 0)}G`;\n }\n return `${ESC}${row + 1}${SEP}${Math.max(column + 1, 0)}H`;\n};\n/**\n * @internal\n */\nexport const cursorDown = (lines = 1) => {\n return `${ESC}${lines}B`;\n};\n/**\n * @internal\n */\nexport const cursorMove = (column, row = 0) => {\n let command = \"\";\n if (row < 0) {\n command += `${ESC}${-row}A`;\n }\n if (row > 0) {\n command += `${ESC}${row}B`;\n }\n if (column > 0) {\n command += `${ESC}${column}C`;\n }\n if (column < 0) {\n command += `${ESC}${-column}D`;\n }\n return command;\n};\n/**\n * @internal\n */\nexport const eraseLines = rows => {\n let command = \"\";\n for (let i = 0; i < rows; i++) {\n command += `${ESC}2K` + (i < rows - 1 ? `${ESC}1A` : \"\");\n }\n if (rows > 0) {\n command += `${ESC}G`;\n }\n return command;\n};\n//# sourceMappingURL=ansi.js.map","/**\n * Builds interactive terminal prompts for CLI applications.\n *\n * A `Prompt<A>` describes a small terminal UI that renders frames, reads\n * keyboard input, validates responses, and eventually produces an `A`. Prompts\n * can ask for simple values, selections, lists, files, hidden text, or custom\n * interactions. This module includes prompt constructors, tools for combining\n * and transforming prompt output, and support for running prompts through the\n * `Terminal` service.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Arr from \"../Array.js\";\nimport * as Context from \"../Context.js\";\nimport * as Data from \"../Data.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Effectable from \"../Effectable.js\";\nimport * as FileSystem from \"../FileSystem.js\";\nimport { dual, pipe } from \"../Function.js\";\nimport * as EffectNumber from \"../Number.js\";\nimport * as Option from \"../Option.js\";\nimport * as Path from \"../Path.js\";\nimport * as Predicate from \"../Predicate.js\";\nimport * as Queue from \"../Queue.js\";\nimport * as Redacted from \"../Redacted.js\";\nimport * as Terminal from \"../Terminal.js\";\nimport * as Ansi from \"./internal/ansi.js\";\nconst TypeId = \"~effect/cli/Prompt\";\n/**\n * Returns `true` if the provided value is a `Prompt`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isPrompt = u => Predicate.hasProperty(u, TypeId);\nconst defaultTheme = {\n prefix: \"?\",\n arrowUp: \"↑\",\n arrowDown: \"↓\",\n checkboxOn: \"☒\",\n checkboxOff: \"☐\",\n tick: \"✔\",\n ellipsis: \"…\",\n pointerSmall: \"›\",\n pointer: \"❯\",\n descriptionSeparator: \"- \",\n passwordMask: \"*\",\n toggleSeparator: \"/\",\n primaryColor: Ansi.cyanBright,\n mutedColor: Ansi.blackBright,\n successColor: Ansi.green,\n errorColor: Ansi.red,\n submittedColor: Ansi.white\n};\nconst windowsTheme = {\n ...defaultTheme,\n checkboxOn: \"[*]\",\n checkboxOff: \"[ ]\",\n tick: \"√\",\n ellipsis: \"...\",\n pointerSmall: \"»\",\n pointer: \">\"\n};\n/**\n * Creates a prompt theme using the current platform defaults.\n *\n * **Details**\n *\n * Unless `colors` is provided, it is detected when the theme is created:\n * colors are enabled when stdout is a TTY and `NO_COLOR` is unset or empty.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeTheme = options => ({\n ...(process.platform === \"win32\" ? windowsTheme : defaultTheme),\n ...options,\n colors: options?.colors ?? Ansi.detectColors()\n});\n/**\n * Context reference for the theme used by built-in prompts.\n *\n * **Details**\n *\n * Provide this reference once to theme every prompt in an application. A\n * prompt's `theme` option takes precedence over the context value. The\n * command wizard also reads `colors` from this reference, so provide a theme\n * with `colors: false` to disable wizard styling.\n *\n * The default value is created with `makeTheme` the first time it is read,\n * so color detection runs once per process. Changes to `NO_COLOR` after the\n * first prompt do not affect the default theme.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const Theme = /*#__PURE__*/Context.Reference(\"effect/cli/Prompt/Theme\", {\n defaultValue: makeTheme\n});\nconst getTheme = options => Effect.map(Theme, theme => ({\n ...theme,\n ...options.theme\n}));\n/**\n * Runs all the provided prompts in sequence respecting the structure provided\n * in input.\n *\n * **Details**\n *\n * Supports either a tuple / iterable of prompts or a record / struct of prompts\n * as an argument.\n *\n * **Example** (Collecting prompt results)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Terminal } from \"effect\"\n * import { Prompt } from \"effect/cli\"\n *\n * const terminal = Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.succeed({} as never),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })\n * const services = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Layer.succeed(Terminal.Terminal, terminal)\n * )\n *\n * const username = Prompt.succeed(\"alice\")\n * const password = Prompt.succeed(\"secret\")\n *\n * const allWithTuple = Prompt.all([username, password])\n *\n * const allWithRecord = Prompt.all({ username, password })\n *\n * await Effect.runPromise(Effect.provide(allWithTuple, services)) // => [\"alice\", \"secret\"]\n * await Effect.runPromise(Effect.provide(allWithRecord, services)) // => { username: \"alice\", password: \"secret\" }\n * ```\n *\n * @stability unstable\n * @category combining\n * @since 4.0.0\n */\nexport const all = function () {\n if (arguments.length === 1) {\n if (isPrompt(arguments[0])) {\n return map(arguments[0], x => [x]);\n } else if (Predicate.isIterable(arguments[0])) {\n return allTupled(Arr.fromIterable(arguments[0]));\n } else {\n const entries = Object.entries(arguments[0]);\n if (entries.length === 0) {\n return succeed({});\n }\n let result = map(entries[0][1], value => ({\n [entries[0][0]]: value\n }));\n if (entries.length === 1) {\n return result;\n }\n const rest = entries.slice(1);\n for (const [key, prompt] of rest) {\n result = result.pipe(flatMap(record => prompt.pipe(map(value => ({\n ...record,\n [key]: value\n })))));\n }\n return result;\n }\n }\n return allTupled(arguments[0]);\n};\nconst annotateErrorLine = (theme, line) => Ansi.annotate(theme.colors, line, Ansi.combine(Ansi.italicized, theme.errorColor));\nconst annotateSymbol = (theme, symbol, ...styles) => symbol.length === 0 ? \"\" : Ansi.annotate(theme.colors, symbol, ...styles);\nconst separateSymbol = (symbol, text) => symbol.length === 0 ? text : symbol + \" \" + text;\nconst renderPagingPrefix = (theme, showArrowUp, showArrowDown) => {\n const width = Math.max(theme.arrowUp.length, theme.arrowDown.length);\n if (showArrowUp) {\n return theme.arrowUp.padEnd(width);\n }\n if (showArrowDown) {\n return theme.arrowDown.padEnd(width);\n }\n return \" \".repeat(width);\n};\n/**\n * Creates a confirmation prompt that asks the user to choose a boolean yes/no\n * value.\n *\n * **When to use**\n *\n * Use to ask for a yes/no answer that can be submitted directly.\n *\n * **Details**\n *\n * `initial` defaults to `false`. Enter submits the current default, yes-style\n * input submits `true`, no-style input submits `false`, and other input beeps.\n *\n * @see {@link Toggle} for an interactive switch-before-submit boolean prompt\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Confirm = options => {\n const opts = {\n initial: false,\n ...options,\n label: {\n confirm: \"yes\",\n deny: \"no\",\n ...options.label\n },\n placeholder: {\n defaultConfirm: \"(Y/n)\",\n defaultDeny: \"(y/N)\",\n ...options.placeholder\n }\n };\n const initialState = {\n value: opts.initial\n };\n return Custom(initialState, {\n render: handleConfirmRender(opts),\n process: input => handleConfirmProcess(input, opts.initial),\n clear: handleConfirmClear(opts)\n });\n};\n/**\n * Creates a custom `Prompt` from the specified initial state and handlers.\n *\n * **Details**\n *\n * The initial state can either be a pure value or an `Effect`. This is\n * particularly useful when the initial state of the `Prompt` must be computed\n * by performing an effectful computation, such as reading data from the file\n * system. A `Prompt` runs as a render loop: `render` returns ANSI output for\n * the current frame, the `Terminal` obtains user input, `process` returns the\n * next prompt action, and `clear` returns ANSI output used to clear the previous\n * frame.\n *\n * Optionally, an external `events` dequeue can be provided as the third\n * argument. When present, the render loop will race user input against events\n * from the dequeue, allowing background events to trigger re-renders without\n * waiting for a keypress. When an event is received from the dequeue, the\n * `receive` handler is called instead of `process`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Custom = (initialState, ...args) => {\n const [events, handlers] = args.length === 1 ? [undefined, args[0]] : [args[0], args[1]];\n const op = Object.create(proto);\n op._tag = \"Loop\";\n op.initialState = initialState;\n op.render = handlers.render;\n op.process = handlers.process;\n op.clear = handlers.clear;\n op.events = events;\n return op;\n};\n/**\n * Creates a date prompt that lets the user edit a formatted date value and\n * validates the final `Date` before submission.\n *\n * **Details**\n *\n * `initial` defaults to the current `Date`, `dateMask` defaults to\n * `YYYY-MM-DD HH:mm:ss`, mask parsing creates editable date parts plus literal\n * tokens, `locales` customizes month and weekday labels, and `validate` runs on\n * submission.\n *\n * **Gotchas**\n *\n * A supplied `initial` `Date` is edited in place during prompt interaction.\n * Date edits use JavaScript `Date` setters, so out-of-range typed values can\n * normalize before validation. If the prompt is meant to be editable,\n * `dateMask` should contain at least one editable date token.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Date = options => {\n const opts = {\n initial: new globalThis.Date(),\n dateMask: \"YYYY-MM-DD HH:mm:ss\",\n validate: Effect.succeed,\n ...options,\n locales: {\n ...defaultLocales,\n ...options.locales\n }\n };\n const dateParts = makeDateParts(opts.dateMask, opts.initial, opts.locales);\n const initialCursorPosition = dateParts.findIndex(part => !part.isToken());\n const initialState = {\n dateParts,\n typed: \"\",\n cursor: initialCursorPosition,\n value: opts.initial,\n error: Option.none()\n };\n return Custom(initialState, {\n render: handleDateRender(opts),\n process: handleDateProcess(opts),\n clear: handleDateClear(opts)\n });\n};\n/**\n * Creates a file-system selection prompt and returns the selected path.\n *\n * **Details**\n *\n * The prompt can be configured to select files, directories, or either path\n * type.\n *\n * You can also type to filter the listed entries. Every printable character is\n * appended to the filter query, so navigation is bound to the arrow keys,\n * `tab`, and the `Ctrl+P` / `Ctrl+N` chords used by `readline` and `fzf`\n * (`Ctrl+K` also moves up). `Ctrl+U` clears the query.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const File = (options = {}) => {\n const opts = {\n ...options,\n type: options.type ?? \"file\",\n message: options.message ?? `Choose a file`,\n startingPath: Option.fromUndefinedOr(options.startingPath),\n default: Option.fromUndefinedOr(options.default),\n maxPerPage: options.maxPerPage ?? 10,\n filter: options.filter ?? (() => Effect.succeed(true))\n };\n const initialState = Effect.gen(function* () {\n const currentPath = yield* resolveCurrentPath(Option.none(), opts);\n const path = yield* Path.Path;\n const defaultPath = Option.map(opts.default, defaultValue => path.resolve(currentPath, defaultValue));\n const initialPath = Option.match(defaultPath, {\n onNone: () => currentPath,\n onSome: defaultPath => path.dirname(defaultPath)\n });\n const files = yield* getFileList(initialPath, opts);\n const cursor = Option.match(defaultPath, {\n onNone: () => 0,\n onSome: defaultPath => {\n const index = files.indexOf(path.basename(defaultPath));\n return index === -1 ? 0 : index;\n }\n });\n const confirm = FileConfirm.Hide();\n return {\n cursor,\n files,\n allFiles: files,\n query: \"\",\n path: Option.map(defaultPath, path.dirname),\n confirm\n };\n });\n return Custom(initialState, {\n render: handleFileRender(opts),\n process: handleFileProcess(opts),\n clear: handleFileClear(opts)\n });\n};\n/**\n * Composes prompts by using the output of this prompt to create the next prompt.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const flatMap = /*#__PURE__*/dual(2, (self, f) => {\n const op = Object.create(proto);\n op._tag = \"OnSuccess\";\n op.prompt = self;\n op.onSuccess = f;\n return op;\n});\n/**\n * Creates a floating-point number prompt.\n *\n * **Details**\n *\n * The prompt supports minimum and maximum bounds, keyboard step sizes, display\n * precision, and additional validation before submission.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Number = options => {\n const opts = {\n default: 0,\n min: globalThis.Number.NEGATIVE_INFINITY,\n max: globalThis.Number.POSITIVE_INFINITY,\n incrementBy: 1,\n decrementBy: 1,\n precision: 2,\n validate: n => {\n if (n < opts.min) {\n return Effect.fail(`${n} must be greater than or equal to ${opts.min}`);\n }\n if (n > opts.max) {\n return Effect.fail(`${n} must be less than or equal to ${opts.max}`);\n }\n return Effect.succeed(n);\n },\n ...options\n };\n const initialValue = options.default === undefined ? \"\" : `${opts.default}`;\n const initialState = {\n cursor: initialValue.length,\n value: initialValue,\n error: Option.none()\n };\n return Custom(initialState, {\n render: handleRenderFloat(opts),\n process: handleProcessFloat(opts),\n clear: handleNumberClear(opts)\n });\n};\n/**\n * Creates a text prompt that does not echo typed input and returns the\n * submitted value wrapped in `Redacted`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Hidden = options => basePrompt(options, \"hidden\").pipe(map(Redacted.make));\n/**\n * Creates an integer prompt.\n *\n * **Details**\n *\n * The prompt supports minimum and maximum bounds, keyboard step sizes, and\n * additional validation before submission.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Int = options => {\n const opts = {\n default: 0,\n min: globalThis.Number.NEGATIVE_INFINITY,\n max: globalThis.Number.POSITIVE_INFINITY,\n incrementBy: 1,\n decrementBy: 1,\n validate: n => {\n if (n < opts.min) {\n return Effect.fail(`${n} must be greater than or equal to ${opts.min}`);\n }\n if (n > opts.max) {\n return Effect.fail(`${n} must be less than or equal to ${opts.max}`);\n }\n return Effect.succeed(n);\n },\n ...options\n };\n const initialValue = options.default === undefined ? \"\" : `${opts.default}`;\n const initialState = {\n cursor: initialValue.length,\n value: initialValue,\n error: Option.none()\n };\n return Custom(initialState, {\n render: handleRenderInteger(opts),\n process: handleProcessInteger(opts),\n clear: handleNumberClear(opts)\n });\n};\n/**\n * Creates a text prompt that returns an array of strings by splitting the\n * submitted input on the configured delimiter.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const List = options => String(options).pipe(map(output => output.split(options.delimiter || \",\")));\n/**\n * Transforms the output value produced by a prompt.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => flatMap(self, a => succeed(f(a))));\n/**\n * Creates a password prompt that masks typed input and returns the submitted\n * value wrapped in `Redacted`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Password = options => basePrompt(options, \"password\").pipe(map(Redacted.make));\n/**\n * Runs a prompt by reading terminal input and rendering prompt frames until the\n * prompt submits a value.\n *\n * **Gotchas**\n *\n * The returned effect may fail with `Terminal.QuitError` if terminal input ends\n * or the prompt is quit.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const run = /*#__PURE__*/Effect.fnUntraced(function* (self) {\n const terminal = yield* Terminal.Terminal;\n const input = yield* Effect.cached(terminal.readInput);\n return yield* runWithInput(self, terminal, input);\n}, /*#__PURE__*/Effect.mapError(() => new Terminal.QuitError({})), Effect.scoped);\nconst getSelectInitialIndex = choices => {\n let initialIndex = 0;\n let seenSelected = -1;\n for (let i = 0; i < choices.length; i++) {\n const choice = choices[i];\n if (choice.selected === true) {\n if (seenSelected !== -1) {\n throw new Error(\"InvalidArgumentException: only a single choice can be selected by default for Prompt.Select\");\n }\n seenSelected = i;\n }\n }\n if (seenSelected !== -1) {\n initialIndex = seenSelected;\n }\n return initialIndex;\n};\n/**\n * Creates a prompt that lets the user select a single value from a list of\n * choices.\n *\n * **Gotchas**\n *\n * At most one choice may be marked as selected by default.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Select = options => {\n const opts = {\n maxPerPage: 10,\n ...options\n };\n const initialIndex = getSelectInitialIndex(opts.choices);\n return Custom(initialIndex, {\n render: handleSelectRender(opts),\n process: handleSelectProcess(opts),\n clear: handleSelectClear(opts)\n });\n};\n/**\n * Creates a prompt that lets users filter select choices by typing.\n *\n * **Details**\n *\n * Every printable character is appended to the filter query, so navigation is\n * bound to the arrow keys, `tab`, and the `Ctrl+P` / `Ctrl+N` chords used by\n * `readline` and `fzf` (`Ctrl+K` also moves up). `Ctrl+U` clears the query.\n *\n * **Example** (Filtering choices with autocomplete)\n *\n * ```ts import.meta.vitest\n * import { Prompt } from \"effect/cli\"\n *\n * const language = Prompt.AutoComplete({\n * message: \"Choose a language\",\n * choices: [\n * { title: \"TypeScript\", value: \"ts\" },\n * { title: \"Rust\", value: \"rs\" },\n * { title: \"Kotlin\", value: \"kt\" }\n * ]\n * })\n *\n * Prompt.isPrompt(language) // => true\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const AutoComplete = options => {\n const opts = {\n maxPerPage: 10,\n filterLabel: \"filter\",\n filterPlaceholder: \"type to filter\",\n emptyMessage: \"No matches\",\n ...options\n };\n const initialIndex = getSelectInitialIndex(opts.choices);\n const filtered = filterAutoCompleteChoices(opts.choices, \"\");\n const index = filtered.length === 0 ? 0 : filtered.includes(initialIndex) ? initialIndex : filtered[0];\n const initialState = {\n query: \"\",\n index,\n filtered\n };\n return Custom(initialState, {\n render: handleAutoCompleteRender(opts),\n process: handleAutoCompleteProcess(opts),\n clear: handleAutoCompleteClear(opts)\n });\n};\n/**\n * Creates a prompt that lets the user select multiple choices and returns their\n * values as an array.\n *\n * **Details**\n *\n * The prompt supports default selected choices, bulk-selection commands, and\n * minimum or maximum selection counts.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const MultiSelect = options => {\n const opts = {\n maxPerPage: 10,\n ...options\n };\n // Seed initial selection from choices marked as selected: true\n const initialSelected = new Set();\n for (let i = 0; i < opts.choices.length; i++) {\n const choice = opts.choices[i];\n if (choice.selected === true && !choice.disabled) {\n initialSelected.add(i);\n }\n }\n const initialState = {\n index: 0,\n selectedIndices: initialSelected,\n error: Option.none()\n };\n return Custom(initialState, {\n render: handleMultiSelectRender(opts),\n process: handleMultiSelectProcess(opts),\n clear: handleMultiSelectClear(opts)\n });\n};\n/**\n * Creates a `Prompt` which immediately succeeds with the specified value.\n *\n * **Details**\n *\n * This prompt does not attempt to obtain user input or render anything to the\n * screen.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const succeed = value => {\n const op = Object.create(proto);\n op._tag = \"Succeed\";\n op.value = value;\n return op;\n};\n/**\n * Creates a text-entry prompt that echoes input and returns the submitted\n * string after validation.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const String = options => basePrompt(options, \"text\");\n/**\n * Creates a toggle prompt that lets the user switch between active and inactive\n * states and returns the selected boolean value.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Toggle = options => {\n const opts = {\n initial: false,\n active: \"on\",\n inactive: \"off\",\n ...options\n };\n return Custom(opts.initial, {\n render: handleToggleRender(opts),\n process: handleToggleProcess,\n clear: () => handleToggleClear(opts)\n });\n};\nconst proto = {\n ... /*#__PURE__*/Effectable.Prototype({\n label: \"Prompt\",\n evaluate() {\n return run(this);\n }\n }),\n [TypeId]: {\n _Output: _ => _\n }\n};\nconst allTupled = arg => {\n if (arg.length === 0) {\n return succeed([]);\n }\n if (arg.length === 1) {\n return map(arg[0], x => [x]);\n }\n let result = map(arg[0], x => [x]);\n for (let i = 1; i < arg.length; i++) {\n const curr = arg[i];\n result = flatMap(result, tuple => map(curr, a => [...tuple, a]));\n }\n return result;\n};\nconst runWithInput = (prompt, terminal, input) => Effect.suspend(() => {\n const op = prompt;\n switch (op._tag) {\n case \"Loop\":\n {\n return Effect.flatMap(input, queue => runLoop(op, terminal, queue));\n }\n case \"OnSuccess\":\n {\n return Effect.flatMap(runWithInput(op.prompt, terminal, input), a => runWithInput(op.onSuccess(a), terminal, input));\n }\n case \"Succeed\":\n {\n return Effect.succeed(op.value);\n }\n }\n});\nconst runLoop = /*#__PURE__*/Effect.fnUntraced(function* (loop, terminal, input) {\n let state = Effect.isEffect(loop.initialState) ? yield* loop.initialState : loop.initialState;\n let action = Action.NextFrame({\n state\n });\n let clear = \"\";\n while (true) {\n const msg = yield* loop.render(state, action);\n yield* Effect.orDie(terminal.display(clear + msg));\n clear = \"\";\n if (loop.events) {\n const takeInput = Queue.take(input).pipe(Effect.map(input => ({\n _tag: \"Input\",\n input\n })));\n const result = yield* Effect.raceFirst(takeInput, Queue.take(loop.events).pipe(Effect.map(value => ({\n _tag: \"Event\",\n value\n }))));\n action = yield* loop.process(result, state);\n } else {\n const result = yield* Queue.take(input);\n action = yield* loop.process(result, state);\n }\n switch (action._tag) {\n case \"Beep\":\n continue;\n case \"NextFrame\":\n {\n clear = yield* loop.clear(state, action);\n state = action.state;\n continue;\n }\n case \"Submit\":\n {\n clear = yield* loop.clear(state, action);\n const msg = yield* loop.render(state, action);\n yield* Effect.orDie(terminal.display(clear + msg));\n return action.value;\n }\n }\n }\n}, (effect, _, terminal) => Effect.ensuring(effect, Effect.orDie(terminal.display(Ansi.cursorShow))));\nconst Action = /*#__PURE__*/Data.taggedEnum();\n/**\n * Clears all lines taken up by the specified `text`.\n */\nconst eraseText = (text, columns) => {\n if (columns === 0) {\n return Ansi.eraseLine + Ansi.cursorTo(0);\n }\n let rows = 0;\n const lines = text.split(NEWLINE_REGEXP);\n for (const line of lines) {\n rows += 1 + Math.floor(Math.max(line.length - 1, 0) / columns);\n }\n return Ansi.eraseLines(rows);\n};\nconst lines = (prompt, columns) => {\n const lines = prompt.split(NEWLINE_REGEXP);\n return columns === 0 ? lines.length : pipe(Arr.map(lines, line => Math.ceil(line.length / columns)), Arr.reduce(0, (left, right) => left + right));\n};\nconst clearOutputWithError = (outputText, columns, errorText) => {\n if (errorText !== undefined && errorText.length > 0) {\n return Ansi.cursorDown(lines(errorText, columns)) + eraseText(`\\n${errorText}`, columns) + eraseText(outputText, columns);\n }\n return eraseText(outputText, columns);\n};\nconst renderBeep = Ansi.beep;\nconst NEWLINE_REGEXP = /\\r?\\n/;\nconst handleConfirmClear = options => {\n return Effect.fnUntraced(function* (state, _) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const confirmMessage = state.value ? options.placeholder.defaultConfirm : options.placeholder.defaultDeny;\n const promptText = renderPrompt(confirmMessage, options.message, figures.prefix, figures.pointerSmall, figures, {\n plain: true\n });\n const clearOutput = eraseText(promptText, columns);\n const resetCurrentLine = Ansi.eraseLine + Ansi.cursorLeft;\n return clearOutput + resetCurrentLine;\n });\n};\nconst renderConfirmNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n // Marking these explicitly as present with `!` because they always will be\n // and there is really no value in adding a `DeepRequired` type helper just\n // for these internal cases\n const confirmMessage = state.value ? options.placeholder.defaultConfirm : options.placeholder.defaultDeny;\n const confirm = Ansi.annotate(figures.colors, confirmMessage, figures.mutedColor);\n const promptMsg = renderPrompt(confirm, options.message, leadingSymbol, trailingSymbol, figures);\n return Ansi.cursorHide + promptMsg;\n});\nconst renderConfirmSubmission = /*#__PURE__*/Effect.fnUntraced(function* (value, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const confirmMessage = value ? options.label.confirm : options.label.deny;\n const promptMsg = renderPrompt(confirmMessage, options.message, leadingSymbol, trailingSymbol, figures);\n return promptMsg + \"\\n\";\n});\nconst handleConfirmRender = options => {\n return (_, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderConfirmNextFrame(state, options),\n Submit: ({\n value\n }) => renderConfirmSubmission(value, options)\n });\n };\n};\nconst TRUE_VALUE_REGEXP = /^y|t$/;\nconst FALSE_VALUE_REGEXP = /^n|f$/;\nconst handleConfirmProcess = (input, defaultValue) => {\n const value = Option.getOrElse(input.input, () => \"\");\n if (input.key.name === \"enter\" || input.key.name === \"return\") {\n return Effect.succeed(Action.Submit({\n value: defaultValue\n }));\n }\n if (TRUE_VALUE_REGEXP.test(value.toLowerCase())) {\n return Effect.succeed(Action.Submit({\n value: true\n }));\n }\n if (FALSE_VALUE_REGEXP.test(value.toLowerCase())) {\n return Effect.succeed(Action.Submit({\n value: false\n }));\n }\n return Effect.succeed(Action.Beep());\n};\nconst handleDateClear = options => {\n return Effect.fnUntraced(function* (state, _) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const resetCurrentLine = Ansi.eraseLine + Ansi.cursorLeft;\n const parts = Arr.reduce(state.dateParts, \"\", (doc, part) => doc + part.toString());\n const promptText = renderPrompt(parts, options.message, figures.prefix, figures.pointerSmall, figures, {\n plain: true\n });\n const errorText = Option.isSome(state.error) ? Arr.match(state.error.value.split(NEWLINE_REGEXP), {\n onEmpty: () => \"\",\n onNonEmpty: errorLines => separateSymbol(figures.pointerSmall, errorLines.join(\"\\n\"))\n }) : \"\";\n const clearOutput = clearOutputWithError(promptText, columns, errorText);\n return clearOutput + resetCurrentLine;\n });\n};\nconst renderDateError = (state, pointer, theme) => {\n if (Option.isSome(state.error)) {\n const errorLines = state.error.value.split(NEWLINE_REGEXP);\n if (Arr.isReadonlyArrayNonEmpty(errorLines)) {\n const prefix = annotateSymbol(theme, pointer, theme.errorColor);\n const lines = Arr.map(errorLines, str => annotateErrorLine(theme, str));\n return Ansi.cursorSavePosition + \"\\n\" + separateSymbol(prefix, lines.join(\"\\n\")) + Ansi.cursorRestorePosition;\n }\n }\n return \"\";\n};\nconst renderParts = (state, theme, submitted = false) => {\n return Arr.reduce(state.dateParts, \"\", (doc, part, currentIndex) => {\n const partDoc = part.toString();\n if (currentIndex === state.cursor && !submitted) {\n const annotation = Ansi.combine(Ansi.underlined, theme.primaryColor);\n return doc + Ansi.annotate(theme.colors, partDoc, annotation);\n }\n return doc + partDoc;\n });\n};\nconst renderDateNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const parts = renderParts(state, figures);\n const promptMsg = renderPrompt(parts, options.message, leadingSymbol, trailingSymbol, figures);\n const errorMsg = renderDateError(state, figures.pointerSmall, figures);\n return Ansi.cursorHide + promptMsg + errorMsg;\n});\nconst renderDateSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const parts = renderParts(state, figures, true);\n const promptMsg = renderPrompt(parts, options.message, leadingSymbol, trailingSymbol, figures);\n return promptMsg + \"\\n\";\n});\nconst processUp = state => {\n state.dateParts[state.cursor].increment();\n return Action.NextFrame({\n state: {\n ...state,\n typed: \"\"\n }\n });\n};\nconst processDown = state => {\n state.dateParts[state.cursor].decrement();\n return Action.NextFrame({\n state: {\n ...state,\n typed: \"\"\n }\n });\n};\nconst processDateCursorLeft = state => {\n const previous = state.dateParts[state.cursor].previousPart();\n if (Option.isSome(previous)) {\n return Action.NextFrame({\n state: {\n ...state,\n typed: \"\",\n cursor: state.dateParts.indexOf(previous.value)\n }\n });\n }\n return Action.Beep();\n};\nconst processDateCursorRight = state => {\n const next = state.dateParts[state.cursor].nextPart();\n if (Option.isSome(next)) {\n return Action.NextFrame({\n state: {\n ...state,\n typed: \"\",\n cursor: state.dateParts.indexOf(next.value)\n }\n });\n }\n return Action.Beep();\n};\nconst processDateNext = state => {\n const next = state.dateParts[state.cursor].nextPart();\n const cursor = Option.match(next, {\n onNone: () => state.dateParts.findIndex(part => !part.isToken()),\n onSome: next => state.dateParts.indexOf(next)\n });\n return Action.NextFrame({\n state: {\n ...state,\n typed: \"\",\n cursor\n }\n });\n};\nconst defaultDateProcessor = (value, state) => {\n if (/\\d/.test(value)) {\n const typed = state.typed + value;\n state.dateParts[state.cursor].setValue(typed);\n return Action.NextFrame({\n state: {\n ...state,\n typed\n }\n });\n }\n return Action.Beep();\n};\nconst defaultLocales = {\n months: [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"],\n monthsShort: [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"],\n weekdays: [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"],\n weekdaysShort: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"]\n};\nconst handleDateRender = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderDateNextFrame(state, options),\n Submit: () => renderDateSubmission(state, options)\n });\n };\n};\nconst handleDateProcess = options => {\n return (input, state) => {\n switch (input.key.name) {\n case \"left\":\n {\n return Effect.succeed(processDateCursorLeft(state));\n }\n case \"right\":\n {\n return Effect.succeed(processDateCursorRight(state));\n }\n case \"k\":\n case \"up\":\n {\n return Effect.succeed(processUp(state));\n }\n case \"j\":\n case \"down\":\n {\n return Effect.succeed(processDown(state));\n }\n case \"tab\":\n {\n return Effect.succeed(processDateNext(state));\n }\n case \"enter\":\n case \"return\":\n {\n return Effect.match(options.validate(state.value), {\n onFailure: error => Action.NextFrame({\n state: {\n ...state,\n error: Option.some(error)\n }\n }),\n onSuccess: value => Action.Submit({\n value\n })\n });\n }\n default:\n {\n return Effect.succeed(defaultDateProcessor(Option.getOrElse(input.input, () => \"\"), state));\n }\n }\n };\n};\nconst DATE_PART_REGEXP = /\\\\(.)|\"((?:\\\\[\"\\\\]|[^\"])+)\"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g;\nconst regExpGroups = {\n 1: ({\n token,\n ...opts\n }) => new Token({\n token: token.replace(/\\\\(.)/g, \"$1\"),\n ...opts\n }),\n 2: opts => new Day(opts),\n 3: opts => new Month(opts),\n 4: opts => new Year(opts),\n 5: opts => new Meridiem(opts),\n 6: opts => new Hours(opts),\n 7: opts => new Minutes(opts),\n 8: opts => new Seconds(opts),\n 9: opts => new Milliseconds(opts)\n};\nconst makeDateParts = (dateMask, date, locales) => {\n const parts = [];\n let result = null;\n // oxlint-disable-next-line no-cond-assign\n while (result = DATE_PART_REGEXP.exec(dateMask)) {\n const match = result.shift();\n const index = result.findIndex(group => group !== undefined);\n if (index in regExpGroups) {\n const token = result[index] || match;\n parts.push(regExpGroups[index]({\n token,\n date,\n parts,\n locales\n }));\n } else {\n parts.push(new Token({\n token: result[index] || match,\n date,\n parts,\n locales\n }));\n }\n }\n const orderedParts = parts.reduce((array, element) => {\n const lastElement = array[array.length - 1];\n if (element.isToken() && lastElement !== undefined && lastElement.isToken()) {\n lastElement.setValue(element.token);\n } else {\n array.push(element);\n }\n return array;\n }, Arr.empty());\n parts.splice(0, parts.length, ...orderedParts);\n return parts;\n};\nclass DatePart {\n token;\n date;\n parts;\n locales;\n constructor(params) {\n this.token = params.token;\n this.locales = params.locales;\n this.date = params.date || new globalThis.Date();\n this.parts = params.parts || [this];\n }\n /**\n * Returns `true` if this `DatePart` is a `Token`, `false` otherwise.\n */\n isToken() {\n return false;\n }\n /**\n * Retrieves the next date part in the list of parts.\n */\n nextPart() {\n const currentPartIndex = Option.getOrElse(Arr.findFirstIndex(this.parts, part => part === this), () => 0);\n return Arr.findFirst(this.parts.slice(currentPartIndex + 1), part => !part.isToken());\n }\n /**\n * Retrieves the previous date part in the list of parts.\n */\n previousPart() {\n const currentPartIndex = Arr.findFirstIndex(this.parts, part => part === this);\n if (Option.isSome(currentPartIndex)) {\n return Arr.findLast(this.parts.slice(0, currentPartIndex.value), part => !part.isToken());\n }\n return Option.none();\n }\n toString() {\n return globalThis.String(this.date);\n }\n}\nclass Token extends DatePart {\n increment() {}\n decrement() {}\n setValue(value) {\n this.token = this.token + value;\n }\n isToken() {\n return true;\n }\n toString() {\n return this.token;\n }\n}\nclass Milliseconds extends DatePart {\n increment() {\n this.date.setMilliseconds(this.date.getMilliseconds() + 1);\n }\n decrement() {\n this.date.setMilliseconds(this.date.getMilliseconds() - 1);\n }\n setValue(value) {\n this.date.setMilliseconds(globalThis.Number.parseInt(value.slice(-this.token.length)));\n }\n toString() {\n const millis = `${this.date.getMilliseconds()}`;\n return millis.padStart(4, \"0\").substring(0, this.token.length);\n }\n}\nclass Seconds extends DatePart {\n increment() {\n this.date.setSeconds(this.date.getSeconds() + 1);\n }\n decrement() {\n this.date.setSeconds(this.date.getSeconds() - 1);\n }\n setValue(value) {\n this.date.setSeconds(globalThis.Number.parseInt(value.slice(-2)));\n }\n toString() {\n const seconds = `${this.date.getSeconds()}`;\n return this.token.length > 1 ? seconds.padStart(2, \"0\") : seconds;\n }\n}\nclass Minutes extends DatePart {\n increment() {\n this.date.setMinutes(this.date.getMinutes() + 1);\n }\n decrement() {\n this.date.setMinutes(this.date.getMinutes() - 1);\n }\n setValue(value) {\n this.date.setMinutes(globalThis.Number.parseInt(value.slice(-2)));\n }\n toString() {\n const minutes = `${this.date.getMinutes()}`;\n return this.token.length > 1 ? minutes.padStart(2, \"0\") : minutes;\n }\n}\nclass Hours extends DatePart {\n increment() {\n this.date.setHours(this.date.getHours() + 1);\n }\n decrement() {\n this.date.setHours(this.date.getHours() - 1);\n }\n setValue(value) {\n this.date.setHours(globalThis.Number.parseInt(value.slice(-2)));\n }\n toString() {\n const hours = /h/.test(this.token) ? this.date.getHours() % 12 || 12 : this.date.getHours();\n return this.token.length > 1 ? `${hours}`.padStart(2, \"0\") : `${hours}`;\n }\n}\nclass Day extends DatePart {\n increment() {\n this.date.setDate(this.date.getDate() + 1);\n }\n decrement() {\n this.date.setDate(this.date.getDate() - 1);\n }\n setValue(value) {\n this.date.setDate(globalThis.Number.parseInt(value.slice(-2)));\n }\n toString() {\n const date = this.date.getDate();\n const day = this.date.getDay();\n switch (this.token) {\n case \"DD\":\n return `${date}`.padStart(2, \"0\");\n case \"Do\":\n return `${date}${this.ordinalIndicator(date)}`;\n case \"d\":\n return `${day + 1}`;\n case \"ddd\":\n return this.locales.weekdaysShort[day];\n case \"dddd\":\n return this.locales.weekdays[day];\n default:\n return `${date}`;\n }\n }\n ordinalIndicator(day) {\n if (day >= 11 && day <= 13) {\n return \"th\";\n }\n switch (day % 10) {\n case 1:\n return \"st\";\n case 2:\n return \"nd\";\n case 3:\n return \"rd\";\n default:\n return \"th\";\n }\n }\n}\nclass Month extends DatePart {\n increment() {\n this.date.setMonth(this.date.getMonth() + 1);\n }\n decrement() {\n this.date.setMonth(this.date.getMonth() - 1);\n }\n setValue(value) {\n const month = globalThis.Number.parseInt(value.slice(-2)) - 1;\n this.date.setMonth(month < 0 ? 0 : month);\n }\n toString() {\n const month = this.date.getMonth();\n switch (this.token.length) {\n case 2:\n return `${month + 1}`.padStart(2, \"0\");\n case 3:\n return this.locales.monthsShort[month];\n case 4:\n return this.locales.months[month];\n default:\n return `${month + 1}`;\n }\n }\n}\nclass Year extends DatePart {\n increment() {\n this.date.setFullYear(this.date.getFullYear() + 1);\n }\n decrement() {\n this.date.setFullYear(this.date.getFullYear() - 1);\n }\n setValue(value) {\n this.date.setFullYear(globalThis.Number.parseInt(value.slice(-4)));\n }\n toString() {\n const year = `${this.date.getFullYear()}`.padStart(4, \"0\");\n return this.token.length === 2 ? year.slice(-2) : year;\n }\n}\nclass Meridiem extends DatePart {\n increment() {\n this.date.setHours((this.date.getHours() + 12) % 24);\n }\n decrement() {\n this.increment();\n }\n setValue(_value) {}\n toString() {\n const meridiem = this.date.getHours() >= 12 ? \"pm\" : \"am\";\n return /A/.test(this.token) ? meridiem.toUpperCase() : meridiem;\n }\n}\nconst CONFIRM_MESSAGE = \"The selected directory contains files. Would you like to traverse the selected directory?\";\nconst FILE_FILTER_LABEL = \"filter\";\nconst FILE_FILTER_PLACEHOLDER = \"type to filter\";\nconst FILE_EMPTY_MESSAGE = \"No matches\";\nconst FileConfirm = /*#__PURE__*/Data.taggedEnum();\nconst showConfirmation = /*#__PURE__*/FileConfirm.$is(\"Show\");\nconst resolveCurrentPath = (path, options) => {\n if (Option.isSome(path)) {\n return Effect.succeed(path.value);\n }\n if (Option.isSome(options.startingPath)) {\n const startingPath = options.startingPath.value;\n return Effect.flatMap(FileSystem.FileSystem, fs =>\n // Ensure the user provided starting path exists\n Effect.orDie(fs.exists(startingPath)).pipe(Effect.flatMap(exists => exists ? Effect.void : Effect.die(`The provided starting path '${startingPath}' does not exist`)), Effect.as(startingPath)));\n }\n return Effect.sync(() => process.cwd());\n};\nconst getFileList = /*#__PURE__*/Effect.fnUntraced(function* (directory, options) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const files = yield* Effect.orDie(fs.readDirectory(directory)).pipe(\n // Always prepend the `\"..\"` option to the file list but allow it\n // to be filtered out if the user so desires\n Effect.map(files => [\"..\", ...files]));\n return yield* Effect.filter(files, file => {\n const result = options.filter(file);\n const userDefinedFilter = Effect.isEffect(result) ? result : Effect.succeed(result);\n const directoryFilter = options.type === \"directory\" ? Effect.map(Effect.orDie(fs.stat(path.join(directory, file))), info => info.type === \"Directory\") : Effect.succeed(true);\n return Effect.zipWith(userDefinedFilter, directoryFilter, (a, b) => a && b);\n }, {\n concurrency: files.length\n });\n});\nconst filterFiles = (files, query) => {\n if (query.length === 0) {\n return files;\n }\n const normalizedQuery = query.toLowerCase();\n const filtered = [];\n for (let index = 0; index < files.length; index++) {\n if (files[index].toLowerCase().includes(normalizedQuery)) {\n filtered.push(files[index]);\n }\n }\n return filtered;\n};\nconst updateFileState = (state, query, allFiles = state.allFiles) => {\n const files = filterFiles(allFiles, query);\n if (files.length === 0) {\n return {\n ...state,\n query,\n allFiles,\n files,\n cursor: 0\n };\n }\n const selected = state.files[state.cursor];\n const cursor = selected === undefined ? 0 : files.indexOf(selected);\n return {\n ...state,\n query,\n allFiles,\n files,\n cursor: cursor === -1 ? 0 : cursor\n };\n};\nconst handleFileClear = options => {\n return Effect.fnUntraced(function* (state, _) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const path = yield* Path.Path;\n const figures = yield* getTheme(options);\n const currentPath = yield* resolveCurrentPath(state.path, options);\n const selectedPath = state.files[state.cursor];\n const resolvedPath = selectedPath === undefined ? currentPath : path.resolve(currentPath, selectedPath);\n const resolvedPathText = separateSymbol(figures.pointerSmall, resolvedPath);\n const isConfirming = showConfirmation(state.confirm);\n const promptText = isConfirming ? renderPrompt(\"(Y/n)\", CONFIRM_MESSAGE, figures.prefix, figures.pointerSmall, figures, {\n plain: true\n }) : renderPrompt(renderFileFilter(state, figures, {\n plain: true\n }), options.message, figures.tick, figures.ellipsis, figures, {\n plain: true\n });\n const filesText = isConfirming ? \"\" : renderFiles(state, state.files, figures, options, {\n plain: true\n });\n const outputText = isConfirming ? `${promptText}\\n${resolvedPathText}` : `${promptText}\\n${resolvedPathText}\\n${filesText}`;\n const clearOutput = eraseText(outputText, columns);\n const resetCurrentLine = Ansi.eraseLine + Ansi.cursorLeft;\n return clearOutput + resetCurrentLine;\n });\n};\nconst renderPrompt = (confirm, message, leadingSymbol, trailingSymbol, theme, options) => {\n const prefix = leadingSymbol.length === 0 ? \"\" : leadingSymbol + \" \";\n const renderLine = line => {\n let output = prefix + line;\n if (trailingSymbol.length > 0) {\n output += \" \" + trailingSymbol;\n }\n if (confirm.length > 0) {\n output += \" \" + confirm;\n } else if (trailingSymbol.length > 0) {\n output += \" \";\n }\n return output;\n };\n return Arr.match(message.split(NEWLINE_REGEXP), {\n onEmpty: () => renderLine(\"\"),\n onNonEmpty: promptLines => {\n const lines = options?.plain === true ? promptLines : Arr.map(promptLines, line => Ansi.annotate(theme.colors, line, Ansi.bold));\n return renderLine(lines.join(\"\\n\"));\n }\n });\n};\nconst renderPrefix = (state, toDisplay, currentIndex, length, figures, renderOptions) => {\n const prefix = renderPagingPrefix(figures, currentIndex === toDisplay.startIndex && toDisplay.startIndex > 0, currentIndex === toDisplay.endIndex - 1 && toDisplay.endIndex < length);\n if (state.cursor === currentIndex) {\n return renderOptions?.plain === true ? figures.pointer + prefix : annotateSymbol(figures, figures.pointer, figures.primaryColor) + prefix;\n }\n return prefix + \" \".repeat(figures.pointer.length);\n};\nconst renderFileName = (file, isSelected, theme, renderOptions) => {\n if (renderOptions?.plain === true) {\n return file;\n }\n return isSelected ? Ansi.annotate(theme.colors, file, Ansi.combine(Ansi.underlined, theme.primaryColor)) : file;\n};\nconst renderFileFilter = (state, theme, renderOptions) => {\n const filterValue = state.query.length === 0 ? renderOptions?.plain === true ? FILE_FILTER_PLACEHOLDER : Ansi.annotate(theme.colors, FILE_FILTER_PLACEHOLDER, theme.mutedColor) : renderOptions?.plain === true ? state.query : Ansi.annotate(theme.colors, state.query, Ansi.combine(Ansi.underlined, theme.primaryColor));\n return `[${FILE_FILTER_LABEL}: ${filterValue}]`;\n};\nconst renderFiles = (state, files, figures, options, renderOptions) => {\n const length = files.length;\n if (length === 0) {\n return renderOptions?.plain === true ? FILE_EMPTY_MESSAGE : Ansi.annotate(figures.colors, FILE_EMPTY_MESSAGE, figures.mutedColor);\n }\n const toDisplay = entriesToDisplay(state.cursor, length, options.maxPerPage);\n const documents = [];\n for (let index = toDisplay.startIndex; index < toDisplay.endIndex; index++) {\n const isSelected = state.cursor === index;\n const prefix = renderPrefix(state, toDisplay, index, length, figures, renderOptions);\n const fileName = renderFileName(files[index], isSelected, figures, renderOptions);\n documents.push(prefix + fileName);\n }\n return documents.join(\"\\n\");\n};\nconst renderFileNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const path = yield* Path.Path;\n const figures = yield* getTheme(options);\n const currentPath = yield* resolveCurrentPath(state.path, options);\n const selectedPath = state.files[state.cursor];\n const resolvedPath = selectedPath === undefined ? currentPath : path.resolve(currentPath, selectedPath);\n const resolvedPathMsg = Ansi.annotate(figures.colors, separateSymbol(figures.pointerSmall, resolvedPath), figures.mutedColor);\n if (showConfirmation(state.confirm)) {\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const confirm = Ansi.annotate(figures.colors, \"(Y/n)\", figures.mutedColor);\n const promptMsg = renderPrompt(confirm, CONFIRM_MESSAGE, leadingSymbol, trailingSymbol, figures);\n return Ansi.cursorHide + promptMsg + \"\\n\" + resolvedPathMsg;\n }\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const promptMsg = renderPrompt(renderFileFilter(state, figures), options.message, leadingSymbol, trailingSymbol, figures);\n const files = renderFiles(state, state.files, figures, options);\n return Ansi.cursorHide + promptMsg + \"\\n\" + resolvedPathMsg + \"\\n\" + files;\n});\nconst renderFileSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, value, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const promptMsg = renderPrompt(renderFileFilter(state, figures), options.message, leadingSymbol, trailingSymbol, figures);\n return promptMsg + \" \" + Ansi.annotate(figures.colors, value, figures.submittedColor) + \"\\n\";\n});\nconst handleFileRender = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderFileNextFrame(state, options),\n Submit: ({\n value\n }) => renderFileSubmission(state, value, options)\n });\n };\n};\nconst processFileCursorUp = state => {\n if (state.files.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const cursor = state.cursor - 1;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor: cursor < 0 ? state.files.length - 1 : cursor\n }\n }));\n};\nconst processFileCursorDown = state => {\n if (state.files.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor: (state.cursor + 1) % state.files.length\n }\n }));\n};\nconst processFileBackspace = state => {\n if (state.query.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const query = state.query.slice(0, state.query.length - 1);\n return Effect.succeed(Action.NextFrame({\n state: updateFileState(state, query)\n }));\n};\nconst processFileClear = state => Effect.succeed(Action.NextFrame({\n state: updateFileState(state, \"\")\n}));\nconst processFileInput = (input, state) => {\n if (input.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const query = state.query + input;\n return Effect.succeed(Action.NextFrame({\n state: updateFileState(state, query)\n }));\n};\nconst processSelection = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n if (state.files.length === 0) {\n return Action.Beep();\n }\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const currentPath = yield* resolveCurrentPath(state.path, options);\n const selectedPath = state.files[state.cursor];\n const resolvedPath = path.resolve(currentPath, selectedPath);\n const info = yield* Effect.orDie(fs.stat(resolvedPath));\n if (info.type === \"Directory\") {\n const files = yield* getFileList(resolvedPath, options);\n const filesWithoutParent = files.filter(file => file !== \"..\");\n // If the user selected a directory AND the prompt type can result with\n // a directory, we must confirm:\n // - If the selected directory has any files\n // - Confirm whether or not the user wants to traverse those files\n if (options.type === \"directory\" || options.type === \"either\") {\n return filesWithoutParent.length === 0\n // Directory is empty so it's safe to select it\n ? Action.Submit({\n value: resolvedPath\n })\n // Directory has contents - show confirmation to user\n : Action.NextFrame({\n state: {\n ...state,\n confirm: FileConfirm.Show()\n }\n });\n }\n return Action.NextFrame({\n state: {\n cursor: 0,\n files,\n allFiles: files,\n query: \"\",\n path: Option.some(resolvedPath),\n confirm: FileConfirm.Hide()\n }\n });\n }\n return Action.Submit({\n value: resolvedPath\n });\n});\nconst handleFileProcess = options => {\n return Effect.fnUntraced(function* (input, state) {\n // Navigation is bound to ctrl chords rather than bare `j`/`k`, so that every\n // printable character reaches the filter input.\n if (input.key.ctrl) {\n switch (input.key.name) {\n case \"u\":\n {\n if (showConfirmation(state.confirm)) {\n return Action.Beep();\n }\n return yield* processFileClear(state);\n }\n case \"p\":\n case \"k\":\n {\n return yield* processFileCursorUp(state);\n }\n case \"n\":\n {\n return yield* processFileCursorDown(state);\n }\n default:\n {\n return Action.Beep();\n }\n }\n }\n switch (input.key.name) {\n case \"up\":\n {\n return yield* processFileCursorUp(state);\n }\n case \"down\":\n case \"tab\":\n {\n return yield* processFileCursorDown(state);\n }\n case \"backspace\":\n {\n if (showConfirmation(state.confirm)) {\n return Action.Beep();\n }\n return yield* processFileBackspace(state);\n }\n case \"enter\":\n case \"return\":\n {\n return yield* processSelection(state, options);\n }\n case \"y\":\n case \"t\":\n {\n if (showConfirmation(state.confirm)) {\n const path = yield* Path.Path;\n const currentPath = yield* resolveCurrentPath(state.path, options);\n const selectedPath = state.files[state.cursor];\n const resolvedPath = path.resolve(currentPath, selectedPath);\n const files = yield* getFileList(resolvedPath, options);\n return Action.NextFrame({\n state: {\n cursor: 0,\n files,\n allFiles: files,\n query: \"\",\n path: Option.some(resolvedPath),\n confirm: FileConfirm.Hide()\n }\n });\n }\n return yield* processFileInput(Option.getOrElse(input.input, () => \"\"), state);\n }\n case \"n\":\n case \"f\":\n {\n if (showConfirmation(state.confirm)) {\n const path = yield* Path.Path;\n const currentPath = yield* resolveCurrentPath(state.path, options);\n const selectedPath = state.files[state.cursor];\n const resolvedPath = path.resolve(currentPath, selectedPath);\n return Action.Submit({\n value: resolvedPath\n });\n }\n return yield* processFileInput(Option.getOrElse(input.input, () => \"\"), state);\n }\n default:\n {\n if (showConfirmation(state.confirm)) {\n return Action.Beep();\n }\n return yield* processFileInput(Option.getOrElse(input.input, () => \"\"), state);\n }\n }\n });\n};\nconst renderMultiSelectError = (state, pointer, theme, renderOptions) => {\n if (Option.isSome(state.error)) {\n return Arr.match(state.error.value.split(NEWLINE_REGEXP), {\n onEmpty: () => \"\",\n onNonEmpty: errorLines => {\n if (renderOptions?.plain === true) {\n return separateSymbol(pointer, errorLines.join(\"\\n\"));\n }\n const prefix = annotateSymbol(theme, pointer, theme.errorColor);\n const lines = Arr.map(errorLines, str => annotateErrorLine(theme, str));\n return Ansi.cursorSavePosition + \"\\n\" + separateSymbol(prefix, lines.join(\"\\n\")) + Ansi.cursorRestorePosition;\n }\n });\n }\n return \"\";\n};\nconst renderChoiceDescription = (choice, isActive, theme, renderOptions) => {\n if (!choice.disabled && choice.description && isActive) {\n const text = theme.descriptionSeparator + choice.description;\n return renderOptions?.plain === true ? text : Ansi.annotate(theme.colors, text, theme.mutedColor);\n }\n return \"\";\n};\nconst metaOptionsCount = 2;\nconst renderMultiSelectTitle = (title, isHighlighted, theme, renderOptions) => {\n if (renderOptions?.plain === true || !isHighlighted) {\n return title;\n }\n return Ansi.annotate(theme.colors, title, Ansi.combine(Ansi.underlined, theme.primaryColor));\n};\nconst renderMultiSelectChoices = (state, options, figures, renderOptions) => {\n const choices = options.choices;\n const checkboxWidth = Math.max(figures.checkboxOn.length, figures.checkboxOff.length);\n const selectableCount = choices.filter(choice => !choice.disabled).length;\n const selectedCount = Array.from(state.selectedIndices).filter(index => !choices[index].disabled).length;\n const allSelected = selectedCount === selectableCount;\n const selectAllText = allSelected ? options?.selectNone ?? \"Select None\" : options?.selectAll ?? \"Select All\";\n const inverseSelectionText = options?.inverseSelection ?? \"Inverse Selection\";\n const metaOptions = [{\n title: selectAllText\n }, {\n title: inverseSelectionText\n }];\n const allChoices = [...metaOptions, ...choices];\n const toDisplay = entriesToDisplay(state.index, allChoices.length, options.maxPerPage);\n const documents = [];\n for (let index = toDisplay.startIndex; index < toDisplay.endIndex; index++) {\n const choice = allChoices[index];\n const isHighlighted = state.index === index;\n const prefix = renderPagingPrefix(figures, index === toDisplay.startIndex && toDisplay.startIndex > 0, index === toDisplay.endIndex - 1 && toDisplay.endIndex < allChoices.length);\n if (index < metaOptions.length) {\n // Meta options\n const title = renderMultiSelectTitle(choice.title, isHighlighted, figures, renderOptions);\n documents.push(prefix + (prefix.length === 0 ? \"\" : \" \") + title);\n } else {\n // Regular choices\n const choiceIndex = index - metaOptions.length;\n const isSelected = state.selectedIndices.has(choiceIndex);\n const checkbox = isSelected ? figures.checkboxOn : figures.checkboxOff;\n const annotatedCheckbox = isHighlighted && renderOptions?.plain !== true ? Ansi.annotate(figures.colors, checkbox, figures.primaryColor) : checkbox;\n const selectChoice = choice;\n const title = renderChoiceTitle(selectChoice, isHighlighted, figures, renderOptions);\n const description = renderChoiceDescription(selectChoice, isHighlighted, figures, renderOptions);\n const checkboxPrefix = checkboxWidth === 0 ? \"\" : annotatedCheckbox + \" \".repeat(checkboxWidth - checkbox.length + 1);\n documents.push(prefix + (prefix.length === 0 ? \"\" : \" \") + checkboxPrefix + title + \" \" + description);\n }\n }\n return documents.join(\"\\n\");\n};\nconst renderMultiSelectNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const choices = renderMultiSelectChoices(state, options, figures);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const promptMsg = renderSelectOutput(leadingSymbol, trailingSymbol, options, figures);\n const error = renderMultiSelectError(state, figures.pointer, figures);\n return Ansi.cursorHide + withSelectHeader(promptMsg, choices) + error;\n});\nconst renderMultiSelectSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const selectedChoices = Array.from(state.selectedIndices).sort(EffectNumber.Order).map(index => options.choices[index].title);\n const selectedText = selectedChoices.join(\", \");\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const promptMsg = renderSelectOutput(leadingSymbol, trailingSymbol, options, figures) ?? leadingSymbol;\n return promptMsg + \" \" + Ansi.annotate(figures.colors, selectedText, figures.submittedColor) + \"\\n\";\n});\nconst processMultiSelectCursorUp = (state, totalChoices) => {\n const newIndex = state.index === 0 ? totalChoices - 1 : state.index - 1;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n index: newIndex\n }\n }));\n};\nconst processMultiSelectCursorDown = (state, totalChoices) => {\n const newIndex = (state.index + 1) % totalChoices;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n index: newIndex\n }\n }));\n};\nconst processSpace = (state, options) => {\n const selectedIndices = new Set(state.selectedIndices);\n if (state.index === 0) {\n const selectableCount = options.choices.filter(choice => !choice.disabled).length;\n const selectedCount = Array.from(state.selectedIndices).filter(index => !options.choices[index].disabled).length;\n if (selectedCount === selectableCount) {\n selectedIndices.clear();\n } else {\n for (let i = 0; i < options.choices.length; i++) {\n if (!options.choices[i].disabled) {\n selectedIndices.add(i);\n }\n }\n }\n } else if (state.index === 1) {\n for (let i = 0; i < options.choices.length; i++) {\n if (options.choices[i].disabled || state.selectedIndices.has(i)) {\n selectedIndices.delete(i);\n } else {\n selectedIndices.add(i);\n }\n }\n } else {\n const choiceIndex = state.index - metaOptionsCount;\n if (options.choices[choiceIndex].disabled) {\n return Effect.succeed(Action.Beep());\n } else if (selectedIndices.has(choiceIndex)) {\n selectedIndices.delete(choiceIndex);\n } else {\n selectedIndices.add(choiceIndex);\n }\n }\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n selectedIndices\n }\n }));\n};\nconst handleMultiSelectClear = options => Effect.fnUntraced(function* (state, _) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const clearPrompt = Ansi.eraseLine + Ansi.cursorLeft;\n const promptText = renderSelectOutput(figures.prefix, figures.pointerSmall, options, figures, {\n plain: true\n });\n const choicesText = renderMultiSelectChoices(state, options, figures, {\n plain: true\n });\n const errorText = renderMultiSelectError(state, figures.pointer, figures, {\n plain: true\n });\n const clearOutput = clearOutputWithError(withSelectHeader(promptText, choicesText), columns, errorText);\n return clearOutput + clearPrompt;\n});\nconst handleMultiSelectProcess = options => {\n return (input, state) => {\n const totalChoices = options.choices.length + metaOptionsCount;\n switch (input.key.name) {\n case \"k\":\n case \"up\":\n {\n return processMultiSelectCursorUp({\n ...state,\n error: Option.none()\n }, totalChoices);\n }\n case \"j\":\n case \"down\":\n case \"tab\":\n {\n return processMultiSelectCursorDown({\n ...state,\n error: Option.none()\n }, totalChoices);\n }\n case \"space\":\n {\n return processSpace(state, options);\n }\n case \"enter\":\n case \"return\":\n {\n const selectedIndices = Array.from(state.selectedIndices).filter(index => !options.choices[index].disabled);\n const selectedCount = selectedIndices.length;\n if (options.min !== undefined && selectedCount < options.min) {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n error: Option.some(`At least ${options.min} are required`)\n }\n }));\n }\n if (options.max !== undefined && selectedCount > options.max) {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n error: Option.some(`At most ${options.max} choices are allowed`)\n }\n }));\n }\n const selectedValues = selectedIndices.sort(EffectNumber.Order).map(index => options.choices[index].value);\n return Effect.succeed(Action.Submit({\n value: selectedValues\n }));\n }\n default:\n {\n return Effect.succeed(Action.Beep());\n }\n }\n };\n};\nconst handleMultiSelectRender = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderMultiSelectNextFrame(state, options),\n Submit: () => renderMultiSelectSubmission(state, options)\n });\n };\n};\nconst handleNumberClear = options => {\n return Effect.fnUntraced(function* (state, _) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const resetCurrentLine = Ansi.eraseLine + Ansi.cursorLeft;\n const errorText = renderNumberError(state, figures.pointerSmall, figures, {\n plain: true\n });\n const promptText = renderNumberOutput(state, figures.prefix, figures.pointerSmall, options, figures, {\n plain: true\n });\n const clearOutput = clearOutputWithError(promptText, columns, errorText);\n return clearOutput + resetCurrentLine;\n });\n};\nconst renderNumberInput = (state, submitted, theme, renderOptions) => {\n const value = state.value === \"\" ? \"\" : `${state.value}`;\n if (submitted || renderOptions?.plain === true) {\n return value;\n }\n const annotation = Option.isSome(state.error) ? theme.errorColor : Ansi.combine(Ansi.underlined, theme.primaryColor);\n return Ansi.annotate(theme.colors, value, annotation);\n};\nconst renderNumberError = (state, pointer, theme, renderOptions) => {\n if (Option.isSome(state.error)) {\n return Arr.match(state.error.value.split(NEWLINE_REGEXP), {\n onEmpty: () => \"\",\n onNonEmpty: errorLines => {\n if (renderOptions?.plain === true) {\n return separateSymbol(pointer, errorLines.join(\"\\n\"));\n }\n const prefix = annotateSymbol(theme, pointer, theme.errorColor);\n const lines = Arr.map(errorLines, str => annotateErrorLine(theme, str));\n return Ansi.cursorSavePosition + \"\\n\" + separateSymbol(prefix, lines.join(\"\\n\")) + Ansi.cursorRestorePosition;\n }\n });\n }\n return \"\";\n};\nconst renderNumberOutput = (state, leadingSymbol, trailingSymbol, options, theme, renderOptions, submitted = false) => {\n const value = renderNumberInput(state, submitted, theme, renderOptions);\n return renderPrompt(value, options.message, leadingSymbol, trailingSymbol, theme, renderOptions);\n};\nconst renderNumberNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const errorMsg = renderNumberError(state, figures.pointerSmall, figures);\n const promptMsg = renderNumberOutput(state, leadingSymbol, trailingSymbol, options, figures);\n return promptMsg + errorMsg;\n});\nconst renderNumberSubmission = /*#__PURE__*/Effect.fnUntraced(function* (nextState, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const promptMsg = renderNumberOutput(nextState, leadingSymbol, trailingSymbol, options, figures, undefined, true);\n return promptMsg + \"\\n\";\n});\nconst processNumberBackspace = state => {\n if (state.value.length <= 0) {\n return Effect.succeed(Action.Beep());\n }\n const value = state.value.slice(0, state.value.length - 1);\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value,\n error: Option.none()\n }\n }));\n};\nconst processNumberClear = state => Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor: 0,\n value: \"\",\n error: Option.none()\n }\n}));\nconst defaultIntProcessor = (input, state) => {\n if (state.value.length === 0 && input === \"-\") {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: \"-\",\n error: Option.none()\n }\n }));\n }\n const parsed = globalThis.Number.parseInt(state.value + input);\n if (globalThis.Number.isNaN(parsed)) {\n return Effect.succeed(Action.Beep());\n } else {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: `${parsed}`,\n error: Option.none()\n }\n }));\n }\n};\nconst defaultFloatProcessor = (input, state) => {\n if (input === \".\" && state.value.includes(\".\")) {\n return Effect.succeed(Action.Beep());\n }\n if (state.value.length === 0 && input === \"-\") {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: \"-\",\n error: Option.none()\n }\n }));\n }\n const parsed = globalThis.Number.parseFloat(state.value + input);\n if (globalThis.Number.isNaN(parsed)) {\n return Effect.succeed(Action.Beep());\n } else {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: input === \".\" ? `${parsed}.` : state.value.includes(\".\") && /^\\d$/.test(input) ? state.value + input : `${parsed}`,\n error: Option.none()\n }\n }));\n }\n};\nconst handleRenderInteger = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderNumberNextFrame(state, options),\n Submit: () => renderNumberSubmission(state, options)\n });\n };\n};\nconst handleProcessInteger = options => {\n return (input, state) => {\n if (input.key.ctrl && input.key.name === \"u\") {\n return processNumberClear(state);\n }\n switch (input.key.name) {\n case \"backspace\":\n {\n return processNumberBackspace(state);\n }\n case \"k\":\n case \"up\":\n {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: state.value === \"\" || state.value === \"-\" ? `${options.incrementBy}` : `${globalThis.Number.parseInt(state.value) + options.incrementBy}`,\n error: Option.none()\n }\n }));\n }\n case \"j\":\n case \"down\":\n {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: state.value === \"\" || state.value === \"-\" ? `-${options.decrementBy}` : `${globalThis.Number.parseInt(state.value) - options.decrementBy}`,\n error: Option.none()\n }\n }));\n }\n case \"enter\":\n case \"return\":\n {\n const parsed = globalThis.Number.parseInt(state.value);\n if (globalThis.Number.isNaN(parsed)) {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n error: Option.some(\"Must provide an integer value\")\n }\n }));\n } else {\n return Effect.match(options.validate(parsed), {\n onFailure: error => Action.NextFrame({\n state: {\n ...state,\n error: Option.some(error)\n }\n }),\n onSuccess: value => Action.Submit({\n value\n })\n });\n }\n }\n default:\n {\n return defaultIntProcessor(Option.getOrElse(input.input, () => \"\"), state);\n }\n }\n };\n};\nconst handleRenderFloat = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderNumberNextFrame(state, options),\n Submit: () => renderNumberSubmission(state, options)\n });\n };\n};\nconst handleProcessFloat = options => {\n return (input, state) => {\n if (input.key.ctrl && input.key.name === \"u\") {\n return processNumberClear(state);\n }\n switch (input.key.name) {\n case \"backspace\":\n {\n return processNumberBackspace(state);\n }\n case \"k\":\n case \"up\":\n {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: state.value === \"\" || state.value === \"-\" ? `${options.incrementBy}` : `${globalThis.Number.parseFloat(state.value) + options.incrementBy}`,\n error: Option.none()\n }\n }));\n }\n case \"j\":\n case \"down\":\n {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: state.value === \"\" || state.value === \"-\" ? `-${options.decrementBy}` : `${globalThis.Number.parseFloat(state.value) - options.decrementBy}`,\n error: Option.none()\n }\n }));\n }\n case \"enter\":\n case \"return\":\n {\n const parsed = globalThis.Number.parseFloat(state.value);\n if (globalThis.Number.isNaN(parsed)) {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n error: Option.some(\"Must provide a floating point value\")\n }\n }));\n } else {\n return Effect.flatMap(Effect.sync(() => EffectNumber.round(parsed, options.precision)), rounded => Effect.match(options.validate(rounded), {\n onFailure: error => Action.NextFrame({\n state: {\n ...state,\n error: Option.some(error)\n }\n }),\n onSuccess: value => Action.Submit({\n value\n })\n }));\n }\n }\n default:\n {\n return defaultFloatProcessor(Option.getOrElse(input.input, () => \"\"), state);\n }\n }\n };\n};\nconst filterAutoCompleteChoices = (choices, query) => {\n const normalizedQuery = query.toLowerCase();\n const indices = [];\n for (let i = 0; i < choices.length; i++) {\n if (choices[i].title.toLowerCase().includes(normalizedQuery)) {\n indices.push(i);\n }\n }\n return indices;\n};\nconst updateAutoCompleteState = (state, options, query) => {\n const filtered = filterAutoCompleteChoices(options.choices, query);\n if (filtered.length === 0) {\n return {\n ...state,\n query,\n filtered,\n index: 0\n };\n }\n if (filtered.includes(state.index)) {\n return {\n ...state,\n query,\n filtered\n };\n }\n return {\n ...state,\n query,\n filtered,\n index: filtered[0]\n };\n};\nconst autoCompleteCursor = state => Option.getOrElse(Arr.findFirstIndex(state.filtered, index => index === state.index), () => 0);\nconst renderSelectOutput = (leadingSymbol, trailingSymbol, options, theme, renderOptions) => options.message === undefined ? undefined : renderPrompt(\"\", options.message, leadingSymbol, trailingSymbol, theme, renderOptions);\nconst withSelectHeader = (header, body) => header === undefined ? body : header + \"\\n\" + body;\nconst renderAutoCompleteFilter = (state, options, theme, renderOptions) => {\n const filterValue = state.query.length === 0 ? renderOptions?.plain === true ? options.filterPlaceholder : Ansi.annotate(theme.colors, options.filterPlaceholder, theme.mutedColor) : renderOptions?.plain === true ? state.query : Ansi.annotate(theme.colors, state.query, Ansi.combine(Ansi.underlined, theme.primaryColor));\n return `[${options.filterLabel}: ${filterValue}]`;\n};\nconst renderAutoCompleteOutput = (state, leadingSymbol, trailingSymbol, options, theme, renderOptions) => {\n const filter = renderAutoCompleteFilter(state, options, theme, renderOptions);\n return renderPrompt(filter, options.message, leadingSymbol, trailingSymbol, theme, renderOptions);\n};\nconst renderChoicePrefix = (state, choices, toDisplay, currentIndex, figures, renderOptions) => {\n const prefix = renderPagingPrefix(figures, currentIndex === toDisplay.startIndex && toDisplay.startIndex > 0, currentIndex === toDisplay.endIndex - 1 && toDisplay.endIndex < choices.length);\n if (renderOptions?.plain === true) {\n return state === currentIndex ? figures.pointer + prefix : prefix + \" \".repeat(figures.pointer.length);\n }\n if (choices[currentIndex].disabled) {\n const annotation = Ansi.combine(Ansi.bold, figures.mutedColor);\n return state === currentIndex ? annotateSymbol(figures, figures.pointer, annotation) + prefix : prefix + \" \".repeat(figures.pointer.length);\n }\n return state === currentIndex ? annotateSymbol(figures, figures.pointer, figures.primaryColor) + prefix : prefix + \" \".repeat(figures.pointer.length);\n};\nconst renderAutoCompleteChoicePrefix = (state, options, toDisplay, currentIndex, figures, renderOptions) => {\n const prefix = renderPagingPrefix(figures, currentIndex === toDisplay.startIndex && toDisplay.startIndex > 0, currentIndex === toDisplay.endIndex - 1 && toDisplay.endIndex < state.filtered.length);\n const choiceIndex = state.filtered[currentIndex];\n if (renderOptions?.plain === true) {\n return state.index === choiceIndex ? figures.pointer + prefix : prefix + \" \".repeat(figures.pointer.length);\n }\n const choice = options.choices[choiceIndex];\n if (choice.disabled) {\n const annotation = Ansi.combine(Ansi.bold, figures.mutedColor);\n return state.index === choiceIndex ? annotateSymbol(figures, figures.pointer, annotation) + prefix : prefix + \" \".repeat(figures.pointer.length);\n }\n return state.index === choiceIndex ? annotateSymbol(figures, figures.pointer, figures.primaryColor) + prefix : prefix + \" \".repeat(figures.pointer.length);\n};\nconst renderChoiceTitle = (choice, isSelected, theme, renderOptions) => {\n if (renderOptions?.plain === true) {\n return choice.title;\n }\n const title = choice.title;\n if (isSelected) {\n return choice.disabled ? Ansi.annotate(theme.colors, title, Ansi.combine(Ansi.underlined, theme.mutedColor)) : Ansi.annotate(theme.colors, title, Ansi.combine(Ansi.underlined, theme.primaryColor));\n }\n return choice.disabled ? Ansi.annotate(theme.colors, title, Ansi.combine(Ansi.strikethrough, theme.mutedColor)) : title;\n};\nconst renderSelectChoices = (state, options, figures, renderOptions) => {\n const choices = options.choices;\n const toDisplay = entriesToDisplay(state, choices.length, options.maxPerPage);\n const documents = [];\n for (let index = toDisplay.startIndex; index < toDisplay.endIndex; index++) {\n const choice = choices[index];\n const isSelected = state === index;\n const prefix = renderChoicePrefix(state, choices, toDisplay, index, figures, renderOptions);\n const title = renderChoiceTitle(choice, isSelected, figures, renderOptions);\n const description = renderChoiceDescription(choice, isSelected, figures, renderOptions);\n documents.push(prefix + title + \" \" + description);\n }\n return documents.join(\"\\n\");\n};\nconst renderAutoCompleteChoices = (state, options, figures, renderOptions) => {\n if (state.filtered.length === 0) {\n return renderOptions?.plain === true ? options.emptyMessage : Ansi.annotate(figures.colors, options.emptyMessage, figures.mutedColor);\n }\n const cursor = autoCompleteCursor(state);\n const toDisplay = entriesToDisplay(cursor, state.filtered.length, options.maxPerPage);\n const documents = [];\n for (let index = toDisplay.startIndex; index < toDisplay.endIndex; index++) {\n const choiceIndex = state.filtered[index];\n const choice = options.choices[choiceIndex];\n const isSelected = state.index === choiceIndex;\n const prefix = renderAutoCompleteChoicePrefix(state, options, toDisplay, index, figures, renderOptions);\n const title = renderChoiceTitle(choice, isSelected, figures, renderOptions);\n const description = renderChoiceDescription(choice, isSelected, figures, renderOptions);\n documents.push(prefix + title + \" \" + description);\n }\n return documents.join(\"\\n\");\n};\nconst renderSelectNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const choices = renderSelectChoices(state, options, figures);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const promptMsg = renderSelectOutput(leadingSymbol, trailingSymbol, options, figures);\n return Ansi.cursorHide + withSelectHeader(promptMsg, choices);\n});\nconst renderAutoCompleteNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const choices = renderAutoCompleteChoices(state, options, figures);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const promptMsg = renderAutoCompleteOutput(state, leadingSymbol, trailingSymbol, options, figures);\n return Ansi.cursorHide + promptMsg + \"\\n\" + choices;\n});\nconst renderSelectSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const selected = options.choices[state].title;\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const promptMsg = renderSelectOutput(leadingSymbol, trailingSymbol, options, figures) ?? leadingSymbol;\n return promptMsg + \" \" + Ansi.annotate(figures.colors, selected, figures.submittedColor) + \"\\n\";\n});\nconst renderAutoCompleteSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const selected = options.choices[state.index].title;\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const promptMsg = renderAutoCompleteOutput(state, leadingSymbol, trailingSymbol, options, figures);\n return promptMsg + \" \" + Ansi.annotate(figures.colors, selected, figures.submittedColor) + \"\\n\";\n});\nconst processSelectCursorUp = (state, choices) => {\n if (state === 0) {\n return Effect.succeed(Action.NextFrame({\n state: choices.length - 1\n }));\n }\n return Effect.succeed(Action.NextFrame({\n state: state - 1\n }));\n};\nconst processSelectCursorDown = (state, choices) => {\n if (state === choices.length - 1) {\n return Effect.succeed(Action.NextFrame({\n state: 0\n }));\n }\n return Effect.succeed(Action.NextFrame({\n state: state + 1\n }));\n};\nconst processSelectNext = (state, choices) => {\n return Effect.succeed(Action.NextFrame({\n state: (state + 1) % choices.length\n }));\n};\nconst processAutoCompleteCursorUp = state => {\n if (state.filtered.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const cursor = autoCompleteCursor(state);\n const nextCursor = cursor === 0 ? state.filtered.length - 1 : cursor - 1;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n index: state.filtered[nextCursor]\n }\n }));\n};\nconst processAutoCompleteCursorDown = state => {\n if (state.filtered.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const cursor = autoCompleteCursor(state);\n const nextCursor = (cursor + 1) % state.filtered.length;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n index: state.filtered[nextCursor]\n }\n }));\n};\nconst processAutoCompleteNext = state => processAutoCompleteCursorDown(state);\nconst processAutoCompleteBackspace = (state, options) => {\n if (state.query.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const query = state.query.slice(0, state.query.length - 1);\n return Effect.succeed(Action.NextFrame({\n state: updateAutoCompleteState(state, options, query)\n }));\n};\nconst processAutoCompleteClear = (state, options) => Effect.succeed(Action.NextFrame({\n state: updateAutoCompleteState(state, options, \"\")\n}));\nconst processAutoCompleteInput = (input, state, options) => {\n if (input.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const query = state.query + input;\n return Effect.succeed(Action.NextFrame({\n state: updateAutoCompleteState(state, options, query)\n }));\n};\nconst handleSelectRender = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderSelectNextFrame(state, options),\n Submit: () => renderSelectSubmission(state, options)\n });\n };\n};\nconst handleAutoCompleteRender = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderAutoCompleteNextFrame(state, options),\n Submit: () => renderAutoCompleteSubmission(state, options)\n });\n };\n};\nconst handleSelectClear = options => Effect.fnUntraced(function* (state, _) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const clearPrompt = Ansi.eraseLine + Ansi.cursorLeft;\n const promptText = renderSelectOutput(figures.prefix, figures.pointerSmall, options, figures, {\n plain: true\n });\n const choicesText = renderSelectChoices(state, options, figures, {\n plain: true\n });\n const clearOutput = eraseText(withSelectHeader(promptText, choicesText), columns);\n return clearOutput + clearPrompt;\n});\nconst handleAutoCompleteClear = options => Effect.fnUntraced(function* (state, _) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const clearPrompt = Ansi.eraseLine + Ansi.cursorLeft;\n const promptText = renderAutoCompleteOutput(state, figures.prefix, figures.pointerSmall, options, figures, {\n plain: true\n });\n const choicesText = renderAutoCompleteChoices(state, options, figures, {\n plain: true\n });\n const clearOutput = eraseText(`${promptText}\\n${choicesText}`, columns);\n return clearOutput + clearPrompt;\n});\nconst handleSelectProcess = options => {\n return (input, state) => {\n switch (input.key.name) {\n case \"k\":\n case \"up\":\n {\n return processSelectCursorUp(state, options.choices);\n }\n case \"j\":\n case \"down\":\n {\n return processSelectCursorDown(state, options.choices);\n }\n case \"tab\":\n {\n return processSelectNext(state, options.choices);\n }\n case \"enter\":\n case \"return\":\n {\n const selected = options.choices[state];\n if (selected.disabled) {\n return Effect.succeed(Action.Beep());\n }\n return Effect.succeed(Action.Submit({\n value: selected.value\n }));\n }\n default:\n {\n return Effect.succeed(Action.Beep());\n }\n }\n };\n};\nconst handleAutoCompleteProcess = options => {\n return (input, state) => {\n // Navigation is bound to ctrl chords rather than bare `j`/`k`, so that every\n // printable character reaches the filter input.\n if (input.key.ctrl) {\n switch (input.key.name) {\n case \"u\":\n {\n return processAutoCompleteClear(state, options);\n }\n case \"p\":\n case \"k\":\n {\n return processAutoCompleteCursorUp(state);\n }\n case \"n\":\n {\n return processAutoCompleteCursorDown(state);\n }\n default:\n {\n return Effect.succeed(Action.Beep());\n }\n }\n }\n switch (input.key.name) {\n case \"up\":\n {\n return processAutoCompleteCursorUp(state);\n }\n case \"down\":\n {\n return processAutoCompleteCursorDown(state);\n }\n case \"tab\":\n {\n return processAutoCompleteNext(state);\n }\n case \"backspace\":\n {\n return processAutoCompleteBackspace(state, options);\n }\n case \"enter\":\n case \"return\":\n {\n if (state.filtered.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const selected = options.choices[state.index];\n if (selected.disabled) {\n return Effect.succeed(Action.Beep());\n }\n return Effect.succeed(Action.Submit({\n value: selected.value\n }));\n }\n default:\n {\n return processAutoCompleteInput(Option.getOrElse(input.input, () => \"\"), state, options);\n }\n }\n };\n};\nconst renderClearScreen = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const resetCurrentLine = Ansi.eraseLine + Ansi.cursorLeft;\n const errorText = renderTextError(state, figures.pointerSmall, figures, {\n plain: true\n });\n const clearOutput = clearOutputWithError(renderTextOutput(state, figures.prefix, figures.pointerSmall, options, figures, {\n plain: true\n }), columns, errorText);\n return clearOutput + resetCurrentLine;\n});\nconst renderTextInput = (nextState, options, theme, submitted, renderOptions) => {\n const text = nextState.value;\n if (renderOptions?.plain === true) {\n switch (options.type) {\n case \"hidden\":\n {\n return \"\";\n }\n case \"password\":\n {\n return theme.passwordMask.repeat(text.length);\n }\n case \"text\":\n {\n return text;\n }\n }\n }\n if (text.length === 0) {\n // Avoid wrapping an empty value in ANSI codes, which would make renderPrompt\n // add spacing for content that occupies no terminal columns.\n return \"\";\n }\n const annotation = Option.isSome(nextState.error) ? theme.errorColor : submitted ? theme.submittedColor : Ansi.combine(Ansi.underlined, theme.primaryColor);\n switch (options.type) {\n case \"hidden\":\n {\n return \"\";\n }\n case \"password\":\n {\n return annotateSymbol(theme, theme.passwordMask.repeat(text.length), annotation);\n }\n case \"text\":\n {\n return Ansi.annotate(theme.colors, text, annotation);\n }\n }\n};\nconst renderTextError = (nextState, pointer, theme, renderOptions) => {\n if (Option.isSome(nextState.error)) {\n return Arr.match(nextState.error.value.split(NEWLINE_REGEXP), {\n onEmpty: () => \"\",\n onNonEmpty: errorLines => {\n if (renderOptions?.plain === true) {\n return separateSymbol(pointer, errorLines.join(\"\\n\"));\n }\n const prefix = annotateSymbol(theme, pointer, theme.errorColor);\n const lines = Arr.map(errorLines, str => annotateErrorLine(theme, str));\n return Ansi.cursorSavePosition + \"\\n\" + separateSymbol(prefix, lines.join(\"\\n\")) + Ansi.cursorRestorePosition;\n }\n });\n }\n return \"\";\n};\nconst renderTextOutput = (nextState, leadingSymbol, trailingSymbol, options, theme, renderOptions, submitted = false) => {\n const value = renderTextInput(nextState, options, theme, submitted, renderOptions);\n return renderPrompt(value, options.message, leadingSymbol, trailingSymbol, theme, renderOptions);\n};\nconst renderTextNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const promptMsg = renderTextOutput(state, leadingSymbol, trailingSymbol, options, figures);\n const errorMsg = renderTextError(state, figures.pointerSmall, figures);\n const cursorWidth = options.type === \"password\" ? figures.passwordMask.length : 1;\n const offset = (state.cursor - state.value.length) * cursorWidth;\n return promptMsg + errorMsg + Ansi.cursorMove(offset);\n});\nconst renderTextSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const promptMsg = renderTextOutput(state, leadingSymbol, trailingSymbol, options, figures, undefined, true);\n return promptMsg + \"\\n\";\n});\nconst processTextBackspace = state => {\n if (state.cursor <= 0) {\n return Effect.succeed(Action.Beep());\n }\n const beforeCursor = state.value.slice(0, state.cursor - 1);\n const afterCursor = state.value.slice(state.cursor);\n const cursor = state.cursor - 1;\n const value = `${beforeCursor}${afterCursor}`;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor,\n value,\n error: Option.none()\n }\n }));\n};\nconst processTextClear = state => Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor: 0,\n value: \"\",\n error: Option.none()\n }\n}));\nconst processTextCursorLeft = state => {\n if (state.cursor <= 0) {\n return Effect.succeed(Action.Beep());\n }\n const cursor = state.cursor - 1;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor,\n error: Option.none()\n }\n }));\n};\nconst processTextCursorRight = state => {\n if (state.cursor >= state.value.length) {\n return Effect.succeed(Action.Beep());\n }\n const cursor = Math.min(state.cursor + 1, state.value.length);\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor,\n error: Option.none()\n }\n }));\n};\nconst processTextCursorStart = state => Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor: 0,\n error: Option.none()\n }\n}));\nconst processTextCursorEnd = state => Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor: state.value.length,\n error: Option.none()\n }\n}));\nconst processTab = (state, options) => {\n if (state.value === options.default) {\n return Effect.succeed(Action.Beep());\n }\n const value = state.value.length === 0 ? options.default : state.value;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value,\n cursor: value.length,\n error: Option.none()\n }\n }));\n};\nconst defaultTextProcessor = (input, state) => {\n const beforeCursor = state.value.slice(0, state.cursor);\n const afterCursor = state.value.slice(state.cursor);\n const value = `${beforeCursor}${input}${afterCursor}`;\n const cursor = state.cursor + input.length;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor,\n value,\n error: Option.none()\n }\n }));\n};\nconst handleTextRender = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderTextNextFrame(state, options),\n Submit: () => renderTextSubmission(state, options)\n });\n };\n};\nconst handleTextProcess = options => {\n return (input, state) => {\n if (input.key.ctrl) {\n switch (input.key.name) {\n case \"u\":\n {\n return processTextClear(state);\n }\n case \"a\":\n {\n return processTextCursorStart(state);\n }\n case \"e\":\n {\n return processTextCursorEnd(state);\n }\n default:\n {\n return Effect.succeed(Action.Beep());\n }\n }\n }\n switch (input.key.name) {\n case \"backspace\":\n {\n return processTextBackspace(state);\n }\n case \"left\":\n {\n return processTextCursorLeft(state);\n }\n case \"right\":\n {\n return processTextCursorRight(state);\n }\n case \"home\":\n {\n return processTextCursorStart(state);\n }\n case \"end\":\n {\n return processTextCursorEnd(state);\n }\n case \"enter\":\n case \"return\":\n {\n const value = state.value;\n return Effect.match(options.validate(value), {\n onFailure: error => Action.NextFrame({\n state: {\n ...state,\n value,\n error: Option.some(error)\n }\n }),\n onSuccess: value => Action.Submit({\n value\n })\n });\n }\n case \"tab\":\n {\n return processTab(state, options);\n }\n default:\n {\n return defaultTextProcessor(Option.getOrElse(input.input, () => \"\"), state);\n }\n }\n };\n};\nconst handleTextClear = options => {\n return (state, _) => {\n return renderClearScreen(state, options);\n };\n};\nconst basePrompt = (options, type) => {\n const opts = {\n default: \"\",\n type,\n validate: Effect.succeed,\n ...options\n };\n const initialState = {\n cursor: opts.default.length,\n value: opts.default,\n error: Option.none()\n };\n return Custom(initialState, {\n render: handleTextRender(opts),\n process: handleTextProcess(opts),\n clear: handleTextClear(opts)\n });\n};\nconst handleToggleClear = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const clearPrompt = Ansi.eraseLine + Ansi.cursorLeft;\n const toggleText = options.active + \" \" + separateSymbol(figures.toggleSeparator, options.inactive);\n const promptText = renderPrompt(toggleText, options.message, figures.prefix, figures.pointerSmall, figures, {\n plain: true\n });\n const clearOutput = eraseText(promptText, columns);\n return clearOutput + clearPrompt;\n});\nconst renderToggle = (value, options, theme, submitted = false) => {\n const separator = annotateSymbol(theme, theme.toggleSeparator, theme.mutedColor);\n const selectedAnnotation = Ansi.combine(Ansi.underlined, submitted ? theme.submittedColor : theme.primaryColor);\n const inactive = value ? options.inactive : Ansi.annotate(theme.colors, options.inactive, selectedAnnotation);\n const active = value ? Ansi.annotate(theme.colors, options.active, selectedAnnotation) : options.active;\n return active + \" \" + separateSymbol(separator, inactive);\n};\nconst renderToggleNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const toggle = renderToggle(state, options, figures);\n const promptMsg = renderPrompt(toggle, options.message, leadingSymbol, trailingSymbol, figures);\n return Ansi.cursorHide + promptMsg;\n});\nconst renderToggleSubmission = /*#__PURE__*/Effect.fnUntraced(function* (value, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const toggle = renderToggle(value, options, figures, true);\n const promptMsg = renderPrompt(toggle, options.message, leadingSymbol, trailingSymbol, figures);\n return promptMsg + \"\\n\";\n});\nconst activate = /*#__PURE__*/Effect.succeed(/*#__PURE__*/Action.NextFrame({\n state: true\n}));\nconst deactivate = /*#__PURE__*/Effect.succeed(/*#__PURE__*/Action.NextFrame({\n state: false\n}));\nconst handleToggleRender = options => {\n return (state, action) => {\n switch (action._tag) {\n case \"Beep\":\n {\n return Effect.succeed(renderBeep);\n }\n case \"NextFrame\":\n {\n return renderToggleNextFrame(state, options);\n }\n case \"Submit\":\n {\n return renderToggleSubmission(state, options);\n }\n }\n };\n};\nconst handleToggleProcess = (input, state) => {\n switch (input.key.name) {\n case \"0\":\n case \"j\":\n case \"delete\":\n case \"right\":\n case \"down\":\n {\n return deactivate;\n }\n case \"1\":\n case \"k\":\n case \"left\":\n case \"up\":\n {\n return activate;\n }\n case \" \":\n case \"tab\":\n {\n return state ? deactivate : activate;\n }\n case \"enter\":\n case \"return\":\n {\n return Effect.succeed(Action.Submit({\n value: state\n }));\n }\n default:\n {\n return Effect.succeed(Action.Beep());\n }\n }\n};\nconst entriesToDisplay = (cursor, total, maxVisible) => {\n const max = maxVisible === undefined ? total : maxVisible;\n let startIndex = Math.min(total - max, cursor - Math.floor(max / 2));\n if (startIndex < 0) {\n startIndex = 0;\n }\n const endIndex = Math.min(startIndex + max, total);\n return {\n startIndex,\n endIndex\n };\n};\n//# sourceMappingURL=Prompt.js.map","/**\n * Defines the shared parameter model for CLI arguments and flags.\n *\n * A `Param<Kind, A>` describes how to consume parsed command-line input and\n * return a typed value. The `Kind` decides whether the parameter reads\n * positional arguments or named flags. `Argument` and `Flag` build on this\n * module to share parsing structure, primitive constructors, help metadata,\n * aliases, defaults, prompts, configuration fallbacks, validation, schema\n * decoding, fallback parameters, and traversal helpers.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Config from \"../Config.js\";\nimport * as Effect from \"../Effect.js\";\nimport { dual, identity } from \"../Function.js\";\nimport * as Option from \"../Option.js\";\nimport { pipeArguments } from \"../Pipeable.js\";\nimport * as Predicate from \"../Predicate.js\";\nimport * as Result from \"../Result.js\";\nimport * as Schema from \"../Schema.js\";\nimport * as CliError from \"./CliError.js\";\nimport * as Primitive from \"./Primitive.js\";\nimport * as Prompt from \"./Prompt.js\";\nconst TypeId = \"~effect/cli/Param\";\n/**\n * Defines the kind discriminator for positional argument parameters.\n *\n * **When to use**\n *\n * Use to build low-level `Param` constructors or type positions for positional\n * argument parameters.\n *\n * @see {@link flagKind} for the named flag parameter discriminator\n * @see {@link ParamKind} for the full parameter kind union\n *\n * @stability unstable\n * @category constants\n * @since 4.0.0\n */\nexport const argumentKind = \"argument\";\n/**\n * Defines the kind discriminator for flag parameters.\n *\n * **When to use**\n *\n * Use to build low-level `Param` constructors or type positions for named flag\n * parameters.\n *\n * @see {@link argumentKind} for the positional argument parameter discriminator\n *\n * @stability unstable\n * @category constants\n * @since 4.0.0\n */\nexport const flagKind = \"flag\";\nconst Proto = {\n [TypeId]: {\n _A: identity\n },\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\n/**\n * Type guard to check if a value is a Param.\n *\n * **Example** (Checking for params)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const maybeParam = Param.String(Param.flagKind, \"name\")\n *\n * Param.isParam(maybeParam) // => true\n * ```\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isParam = u => Predicate.hasProperty(u, TypeId);\n/**\n * Type guard to check if a param is a Single param (not composed).\n *\n * **Example** (Checking for single params)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const nameParam = Param.String(Param.flagKind, \"name\")\n * const optionalParam = Param.optional(nameParam)\n *\n * Param.isSingle(nameParam) // => true\n * Param.isSingle(optionalParam) // => false\n * ```\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isSingle = param => Predicate.isTagged(param, \"Single\");\n/**\n * Type guard to check if a Single param is a flag (not an argument).\n *\n * @internal\n */\nexport const isFlagParam = single => single.kind === \"flag\";\n/**\n * Constructs a leaf `Single` parameter from its kind, name, primitive parser,\n * and optional help metadata.\n *\n * **Details**\n *\n * The returned parser reads either one positional argument or the named flag,\n * depending on `kind`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeSingle = params => {\n const parse = args => params.kind === argumentKind ? parsePositional(params.name, params.primitiveType, args) : parseFlag(params.name, params.primitiveType, args);\n return Object.setPrototypeOf({\n _tag: \"Single\",\n ...params,\n description: params.description ?? Option.none(),\n aliases: params.aliases ?? [],\n hidden: params.hidden ?? false,\n parse\n }, Proto);\n};\n/**\n * Creates a string parameter.\n *\n * **Example** (Creating string parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Create a string flag\n * const nameFlag = Param.String(Param.flagKind, \"name\")\n *\n * // Create a string argument\n * const fileArg = Param.String(Param.argumentKind, \"file\")\n *\n * // Usage in CLI: --name \"John Doe\" or as positional argument\n * const kinds = [nameFlag.kind, fileArg.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const String = (kind, name) => makeSingle({\n name,\n primitiveType: Primitive.String,\n kind\n});\n/**\n * Creates a boolean parameter.\n *\n * **Example** (Creating boolean parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Create a boolean flag\n * const verboseFlag = Param.Boolean(Param.flagKind, \"verbose\")\n *\n * // Create a boolean argument\n * const enableArg = Param.Boolean(Param.argumentKind, \"enable\")\n *\n * // Usage in CLI: --verbose (true) or --no-verbose (false).\n * // The flag is required unless made optional or given a fallback.\n * // Boolean positional arguments accept true/false.\n * const kinds = [verboseFlag.kind, enableArg.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Boolean = (kind, name) => makeSingle({\n name,\n primitiveType: Primitive.Boolean,\n kind\n});\n/**\n * Creates an integer parameter.\n *\n * **Example** (Creating integer parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Create an integer flag\n * const portFlag = Param.Int(Param.flagKind, \"port\")\n *\n * // Create an integer argument\n * const countArg = Param.Int(Param.argumentKind, \"count\")\n *\n * // Usage in CLI: --port 8080 or as positional argument: 42\n * const kinds = [portFlag.kind, countArg.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Int = (kind, name) => makeSingle({\n name,\n primitiveType: Primitive.Int,\n kind\n});\n/**\n * Creates a finite number parameter.\n *\n * **Example** (Creating finite number parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const rateFlag = Param.Finite(Param.flagKind, \"rate\")\n *\n * const thresholdArg = Param.Finite(Param.argumentKind, \"threshold\")\n *\n * const kinds = [rateFlag.kind, thresholdArg.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Finite = (kind, name) => makeSingle({\n name,\n primitiveType: Primitive.Finite,\n kind\n});\n/**\n * Creates a date parameter that parses ISO date strings.\n *\n * **Example** (Creating date parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Create a date flag\n * const startFlag = Param.Date(Param.flagKind, \"start-date\")\n *\n * // Create a date argument\n * const dueDateArg = Param.Date(Param.argumentKind, \"due-date\")\n *\n * // Usage in CLI: --start-date \"2023-12-25\" or as positional: \"2023-01-01\"\n * // Parses to JavaScript Date object\n * const kinds = [startFlag.kind, dueDateArg.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Date = (kind, name) => makeSingle({\n name,\n primitiveType: Primitive.Date,\n kind\n});\n/**\n * Constructs command-line params that represent a choice between several\n * inputs. The input will be mapped to it's associated value during parsing.\n *\n * **Example** (Creating valued choices)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * type Animal = Dog | Cat\n *\n * interface Dog {\n * readonly _tag: \"Dog\"\n * }\n *\n * interface Cat {\n * readonly _tag: \"Cat\"\n * }\n *\n * const animal = Param.ChoiceWithValue(Param.flagKind, \"animal\", [\n * [\"dog\", { _tag: \"Dog\" }],\n * [\"cat\", { _tag: \"Cat\" }]\n * ])\n * animal.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const ChoiceWithValue = (kind, name, choices) => makeSingle({\n name,\n primitiveType: Primitive.Choice(choices),\n kind\n});\n/**\n * Constructs command-line params that represent a choice between several\n * string inputs.\n *\n * **Example** (Creating string choices)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const logLevel = Param.Literals(Param.flagKind, \"log-level\", [\n * \"debug\",\n * \"info\",\n * \"warn\",\n * \"error\"\n * ])\n * logLevel.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Literals = (kind, name, choices) => {\n const mappedChoices = choices.map(value => [value, value]);\n return ChoiceWithValue(kind, name, mappedChoices);\n};\n/**\n * Creates a path parameter that accepts file or directory paths.\n *\n * **Example** (Creating path parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Basic path parameter\n * const outputPath = Param.Path(Param.flagKind, \"output\")\n *\n * // Path that must exist\n * const inputPath = Param.Path(Param.flagKind, \"input\", { mustExist: true })\n *\n * // File-only path\n * const configFile = Param.Path(Param.flagKind, \"config\", {\n * pathType: \"file\",\n * mustExist: true,\n * typeName: \"config-file\"\n * })\n * const kinds = [outputPath.kind, inputPath.kind, configFile.kind] // => [\"flag\", \"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Path = (kind, name, options) => makeSingle({\n name,\n kind,\n primitiveType: Primitive.Path(options?.pathType ?? \"either\", options?.mustExist),\n typeName: options?.typeName\n});\n/**\n * Creates a directory path parameter.\n *\n * **Details**\n *\n * This is a convenience function that creates a path parameter with the\n * `pathType` set to `\"directory\"` and a default type name of `\"directory\"`.\n *\n * **Example** (Creating directory parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Basic directory parameter\n * const outputDir = Param.Directory(Param.flagKind, \"output-dir\")\n *\n * // Directory that must exist\n * const sourceDir = Param.Directory(Param.flagKind, \"source\", { mustExist: true })\n *\n * // Usage: --output-dir /path/to/dir --source /existing/dir\n * const kinds = [outputDir.kind, sourceDir.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Directory = (kind, name, options) => Path(kind, name, {\n pathType: \"directory\",\n typeName: \"directory\",\n mustExist: options?.mustExist\n});\n/**\n * Creates a file path parameter.\n *\n * **Details**\n *\n * This is a convenience function that creates a path parameter with a\n * `pathType` set to `\"file\"` and a default type name of `\"file\"`.\n *\n * **Example** (Creating file parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Basic file parameter\n * const outputFile = Param.File(Param.flagKind, \"output\")\n *\n * // File that must exist\n * const inputFile = Param.File(Param.flagKind, \"input\", { mustExist: true })\n *\n * // Usage: --output result.txt --input existing-file.txt\n * const kinds = [outputFile.kind, inputFile.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const File = (kind, name, options) => Path(kind, name, {\n pathType: \"file\",\n typeName: \"file\",\n mustExist: options?.mustExist\n});\n/**\n * Creates a redacted parameter for sensitive data like passwords.\n * The value is masked in help output and logging.\n *\n * **Example** (Creating redacted parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Create a password parameter\n * const password = Param.Redacted(Param.flagKind, \"password\")\n *\n * // Create an API key argument\n * const apiKey = Param.Redacted(Param.argumentKind, \"api-key\")\n *\n * // Usage: --password (value will be hidden in help/logs)\n * const kinds = [password.kind, apiKey.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Redacted = (kind, name) => makeSingle({\n name,\n primitiveType: Primitive.Redacted,\n kind\n});\n/**\n * Creates a parameter that reads and returns file content as a string.\n *\n * **Example** (Reading file text)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Read a config file as string\n * const configContent = Param.FileText(Param.flagKind, \"config\")\n *\n * // Read a template file as argument\n * const templateContent = Param.FileText(Param.argumentKind, \"template\")\n *\n * // Usage: --config config.txt (reads file content into string)\n * const kinds = [configContent.kind, templateContent.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileText = (kind, name) => makeSingle({\n name,\n primitiveType: Primitive.FileText,\n kind\n});\n/**\n * Creates a param that reads and parses the content of the specified file.\n *\n * **Details**\n *\n * The parser that is utilized will depend on the specified `format`, or the\n * extension of the file passed on the command-line if no `format` is specified.\n *\n * **Example** (Parsing file contents)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Will use the extension of the file passed on the command line to determine\n * // the parser to use\n * const config = Param.FileParse(Param.flagKind, \"config\")\n *\n * // Will use the JSON parser\n * const jsonConfig = Param.FileParse(Param.flagKind, \"json-config\", {\n * format: \"json\"\n * })\n * const kinds = [config.kind, jsonConfig.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileParse = (kind, name, options) => makeSingle({\n name,\n primitiveType: Primitive.FileParse(options),\n kind\n});\n/**\n * Creates a parameter that reads and validates file content using a schema.\n *\n * **Example** (Validating file contents)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Param } from \"effect/cli\"\n * // Parse JSON config file\n * const configSchema = Schema.Struct({\n * port: Schema.Number,\n * host: Schema.String\n * })\n *\n * const config = Param.FileSchema(Param.flagKind, \"config\", configSchema, {\n * format: \"json\"\n * })\n *\n * // Parse YAML file\n * const yamlConfig = Param.FileSchema(Param.flagKind, \"config\", configSchema, {\n * format: \"yaml\"\n * })\n *\n * // Usage: --config config.json (reads and validates file content)\n * const kinds = [config.kind, yamlConfig.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileSchema = (kind, name, schema, options) => makeSingle({\n name,\n primitiveType: Primitive.FileSchema(schema, options),\n kind\n});\n/**\n * Creates a param that parses key=value pairs.\n *\n * **When to use**\n *\n * Use when you need command-line options or arguments that collect `key=value`\n * configuration entries.\n *\n * **Details**\n *\n * Requires at least one key=value pair. The parsed pairs are merged into a\n * single record object.\n *\n * **Example** (Parsing key-value pairs)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const env = Param.KeyValuePair(Param.flagKind, \"env\")\n * // --env FOO=bar --env BAZ=qux will parse to { FOO: \"bar\", BAZ: \"qux\" }\n *\n * const props = Param.KeyValuePair(Param.flagKind, \"property\")\n * // --property name=value --property debug=true\n * const kinds = [env.kind, props.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const KeyValuePair = (kind, name) => map(variadic(makeSingle({\n name,\n primitiveType: Primitive.KeyValuePair,\n kind\n}), {\n min: 1\n}), objects => Object.fromEntries(objects.flatMap(Object.entries)));\n/**\n * A parameter that always fails to parse.\n *\n * **Example** (Creating sentinel parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const disabledDebugParam = Param.Never(Param.flagKind)\n *\n * const makeDebugParam = (enableDebug: boolean) =>\n * enableDebug ? Param.String(Param.flagKind, \"debug\") : disabledDebugParam\n *\n * makeDebugParam(true) === disabledDebugParam // => false\n * makeDebugParam(false) === disabledDebugParam // => true\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Never = kind => makeSingle({\n name: \"__never__\",\n primitiveType: Primitive.Never,\n kind\n});\nconst FLAG_DASH_REGEXP = /^-+/;\n/**\n * Adds an alias to an option.\n *\n * **When to use**\n *\n * Use when you need a CLI parameter to accept an alternate name, such as \"-f\"\n * for \"--force\".\n *\n * **Details**\n *\n * This works on any param structure by recursively finding the underlying\n * `Single` node and applying the alias there.\n *\n * **Example** (Adding parameter aliases)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const force = Param.Boolean(Param.flagKind, \"force\").pipe(\n * Param.withAlias(\"-f\"),\n * Param.withAlias(\"-F\")\n * )\n *\n * // Also works on composed params:\n * const count = Param.Int(Param.flagKind, \"count\").pipe(\n * Param.optional,\n * Param.withAlias(\"-c\") // finds the underlying Single and adds alias\n * )\n * const kinds = [force.kind, count.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withAlias = /*#__PURE__*/dual(2, (self, alias) => {\n return transformSingle(self, single => makeSingle({\n ...single,\n aliases: [...single.aliases, alias.replace(FLAG_DASH_REGEXP, \"\")]\n }));\n});\n/**\n * Adds a description to an option for help text.\n *\n * **Details**\n *\n * Descriptions provide users with information about what the option does\n * when they view help documentation.\n *\n * **Example** (Adding help descriptions)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const verbose = Param.Boolean(Param.flagKind, \"verbose\").pipe(\n * Param.withAlias(\"-v\"),\n * Param.withDescription(\"Enable verbose output\")\n * )\n * verbose.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withDescription = /*#__PURE__*/dual(2, (self, description) => {\n return transformSingle(self, single => makeSingle({\n ...single,\n description: Option.some(description)\n }));\n});\n/**\n * Hides a parameter from generated help output and completions while keeping\n * it parseable on the command line.\n *\n * **When to use**\n *\n * Use when experimental, internal, or deprecated flags should be accepted but\n * not advertised.\n *\n * **Example** (Hiding a flag from help)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const experimental = Param.Boolean(Param.flagKind, \"experimental-foo\").pipe(\n * Param.withHidden\n * )\n * experimental.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category metadata\n * @since 4.0.0\n */\nexport const withHidden = self => transformSingle(self, single => makeSingle({\n ...single,\n hidden: true\n}));\n/**\n * Transforms the parsed value of an option using a mapping function.\n *\n * **Example** (Mapping parsed values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const port = Param.Int(Param.flagKind, \"port\").pipe(\n * Param.map((n) => ({ port: n, url: `http://localhost:${n}` }))\n * )\n * port.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => {\n const parse = args => Effect.map(self.parse(args), ([operands, value]) => [operands, f(value)]);\n return Object.assign(Object.create(Proto), {\n _tag: \"Map\",\n kind: self.kind,\n param: self,\n f,\n parse\n });\n});\nconst transform = (self, f, alternatives = []) => {\n const alternativeParsers = alternatives.map(alternative => () => alternative().parse);\n return Object.assign(Object.create(Proto), {\n _tag: \"Transform\",\n kind: self.kind,\n param: self,\n alternatives,\n f,\n parse: f(self.parse, alternativeParsers)\n });\n};\n/**\n * Transforms the parsed value of an option using an effectful mapping function.\n *\n * **Example** (Mapping parsed values effectfully)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { CliError, Param } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const validatedEmail = Param.String(Param.flagKind, \"email\").pipe(\n * Param.mapEffect((email) =>\n * email.includes(\"@\")\n * ? Effect.succeed(email)\n * : Effect.fail(\n * new CliError.InvalidValue({\n * option: \"email\",\n * value: email,\n * expected: \"valid email format\",\n * kind: \"flag\"\n * })\n * )\n * )\n * )\n *\n * const [, value] = await Effect.runPromise(\n * validatedEmail.parse({\n * arguments: [],\n * flags: { email: [\"alice@example.com\"] }\n * }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => \"alice@example.com\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const mapEffect = /*#__PURE__*/dual(2, (self, f) => transform(self, parse => args => Effect.flatMap(parse(args), ([leftover, a]) => f(a).pipe(Effect.map(b => [leftover, b])))));\n/**\n * Transforms the parsed value of an option using a function that may throw,\n * converting any thrown errors into failure messages.\n *\n * **Example** (Mapping thrown errors)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Param } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parsedJson = Param.String(Param.flagKind, \"config\").pipe(\n * Param.mapTryCatch(\n * (str) => JSON.parse(str),\n * (error) =>\n * `Invalid JSON: ${error instanceof Error ? error.message : String(error)}`\n * )\n * )\n *\n * const [, value] = await Effect.runPromise(\n * parsedJson.parse({\n * arguments: [],\n * flags: { config: ['{\"enabled\":true}'] }\n * }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => { enabled: true }\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const mapTryCatch = /*#__PURE__*/dual(3, (self, f, onError) => {\n const single = getUnderlyingSingleOrThrow(self);\n return transform(self, parse => args => Effect.flatMap(parse(args), ([leftover, a]) => Effect.try({\n try: () => f(a),\n catch: error => onError(error)\n }).pipe(Effect.mapError(error => new CliError.InvalidValue({\n option: single.name,\n value: globalThis.String(a),\n expected: error,\n kind: single.kind\n })), Effect.map(b => [leftover, b]))));\n});\n/**\n * Makes a flag or positional argument optional.\n *\n * **Details**\n *\n * When the parameter is absent, parsing succeeds with `Option.none()` instead\n * of failing with a missing option or missing argument error. When present, the\n * parsed value is wrapped in `Option.some()`.\n *\n * **Example** (Making parameters optional)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Create an optional port option\n * // - When not provided: returns Option.none()\n * // - When provided: returns Option.some(parsedValue)\n * const port = Param.optional(Param.Int(Param.flagKind, \"port\"))\n * port.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const optional = param => {\n const parse = args => param.parse(args).pipe(Effect.map(([leftover, value]) => [leftover, Option.some(value)]),\n // Catch both MissingOption (for flags) and MissingArgument (for positional arguments)\n Effect.catchTags({\n MissingOption: () => Effect.succeed([args.arguments, Option.none()]),\n MissingArgument: () => Effect.succeed([args.arguments, Option.none()])\n }));\n return Object.assign(Object.create(Proto), {\n _tag: \"Optional\",\n kind: param.kind,\n param,\n parse\n });\n};\n/**\n * Makes a flag or positional argument optional by supplying a fallback value.\n *\n * **Details**\n *\n * The fallback may be a pure value or an effect. It is used only when the\n * parameter is absent; provided values are parsed normally.\n *\n * **Example** (Providing default values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Using the pipe operator to make an option optional\n * const port = Param.Int(Param.flagKind, \"port\").pipe(\n * Param.withDefault(8080)\n * )\n *\n * // Can also be used with other combinators\n * const verbose = Param.Boolean(Param.flagKind, \"verbose\").pipe(\n * Param.withAlias(\"-v\"),\n * Param.withDescription(\"Enable verbose output\"),\n * Param.withDefault(false)\n * )\n * const kinds = [port.kind, verbose.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withDefault = /*#__PURE__*/dual(2, (self, defaultValue) => {\n if (!Effect.isEffect(defaultValue)) {\n return map(optional(self), Option.getOrElse(() => defaultValue));\n }\n return mapEffect(optional(self), Option.match({\n onNone: () => defaultValue,\n onSome: Effect.succeed\n }));\n});\n/**\n * Adds a fallback config that is loaded when a required parameter is missing.\n *\n * **When to use**\n *\n * Use when you need config to provide a fallback source for required flags or\n * arguments that are absent from CLI input.\n *\n * **Details**\n *\n * Provided CLI values win. Config is loaded only after a missing option or\n * missing argument error.\n *\n * **Gotchas**\n *\n * Missing config preserves the original missing-parameter error. Config parse\n * failure becomes `CliError.InvalidValue`.\n *\n * @see {@link withDefault} for a pure default value\n * @see {@link withFallbackPrompt} for prompting interactively when input is missing\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackConfig = /*#__PURE__*/dual(2, (self, config) => {\n const toInvalidValue = (error, configError) => new CliError.InvalidValue({\n option: error._tag === \"MissingOption\" ? error.option : error.argument,\n value: \"config\",\n expected: configError.message,\n kind: error._tag === \"MissingOption\" ? \"flag\" : \"argument\"\n });\n const runConfig = (error, args) => Config.option(config).pipe(Effect.mapError(configError => toInvalidValue(error, configError)), Effect.flatMap(Option.match({\n onNone: () => Effect.fail(error),\n onSome: value => Effect.succeed([args.arguments, value])\n })));\n return transform(self, parse => args => parse(args).pipe(Effect.catchTag([\"MissingOption\", \"MissingArgument\"], error => runConfig(error, args))));\n});\n/**\n * Adds a fallback prompt that is shown when a required parameter is missing.\n *\n * **When to use**\n *\n * Use when a CLI should ask interactively for a missing required flag or\n * argument.\n *\n * **Details**\n *\n * `FallbackPrompt` accepts either a `Prompt` or an effect that builds one.\n * Effectful prompt creation is lazy and runs only when the fallback is needed.\n *\n * **Gotchas**\n *\n * This only handles missing options and missing arguments. Invalid values do not\n * prompt, and prompt cancellation re-fails with the original missing error.\n *\n * @see {@link FallbackPrompt} for accepted fallback prompt forms\n * @see {@link withFallbackConfig} for loading a fallback from config\n * @see {@link withDefault} for a pure default value\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackPrompt = /*#__PURE__*/dual(2, (self, prompt) => {\n const runPrompt = (error, args) => Effect.flatMap(Prompt.isPrompt(prompt) ? Effect.succeed(prompt) : prompt, Prompt.run).pipe(Effect.map(value => [args.arguments, value]), Effect.catchTag(\"QuitError\", () => Effect.fail(error)));\n return transform(self, parse => args => parse(args).pipe(Effect.catchTag([\"MissingOption\", \"MissingArgument\"], error => runPrompt(error, args))));\n});\n/**\n * Creates a variadic parameter that can be specified multiple times.\n *\n * **Details**\n *\n * This is the base combinator for creating parameters that accept multiple values.\n * The `min` and `max` parameters are optional. When they are not provided, the\n * parameter can be specified any number of times, from 0 to infinity.\n *\n * **Example** (Accepting multiple values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Basic variadic parameter (0 to infinity)\n * const tags = Param.variadic(Param.String(Param.flagKind, \"tag\"))\n *\n * // Variadic with minimum count\n * const inputs = Param.variadic(\n * Param.String(Param.flagKind, \"input\"),\n * { min: 1 } // at least 1 required\n * )\n *\n * // Variadic with both min and max\n * const limited = Param.variadic(Param.String(Param.flagKind, \"item\"), {\n * min: 2, // at least 2 times\n * max: 2 // at most 2 times\n * })\n * const kinds = [tags.kind, inputs.kind, limited.kind] // => [\"flag\", \"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const variadic = (self, options) => {\n const single = getUnderlyingSingleOrThrow(self);\n const parse = args => {\n if (single.kind === \"argument\") {\n return parsePositionalVariadic(self, single, args, options);\n } else {\n return parseOptionVariadic(self, single, args, options);\n }\n };\n return Object.assign(Object.create(Proto), {\n _tag: \"Variadic\",\n kind: self.kind,\n param: self,\n min: Option.fromUndefinedOr(options?.min),\n max: Option.fromUndefinedOr(options?.max),\n parse\n });\n};\n/**\n * Wraps an option to allow it to be specified multiple times within a range.\n *\n * **Details**\n *\n * This combinator transforms an option to accept between `min` and `max`\n * occurrences on the command line, returning an array of all provided values.\n *\n * **Example** (Bounding repeated values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Allow 1-3 file inputs\n * const files = Param.String(Param.flagKind, \"file\").pipe(\n * Param.between(1, 3),\n * Param.withAlias(\"-f\")\n * )\n *\n * // Parse: --file a.txt --file b.txt\n * // Result: [\"a.txt\", \"b.txt\"]\n *\n * // Allow 0 or more tags\n * const tags = Param.String(Param.flagKind, \"tag\").pipe(\n * Param.between(0, Number.MAX_SAFE_INTEGER)\n * )\n *\n * // Parse: --tag dev --tag staging --tag v1.0\n * // Result: [\"dev\", \"staging\", \"v1.0\"]\n * const kinds = [files.kind, tags.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const between = /*#__PURE__*/dual(3, (self, min, max) => {\n if (min < 0) {\n throw new Error(\"between: min must be non-negative\");\n }\n if (max < min) {\n throw new Error(\"between: max must be greater than or equal to min\");\n }\n return variadic(self, {\n min,\n max\n });\n});\n/**\n * Wraps an option to allow it to be specified at most `max` times.\n *\n * **Details**\n *\n * This combinator transforms an option to accept between 0 and `max`\n * occurrences on the command line, returning an array of all provided values.\n *\n * **Example** (Limiting repeated values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Allow at most 3 warning suppressions\n * const suppressions = Param.String(Param.flagKind, \"suppress\").pipe(\n * Param.atMost(3)\n * )\n *\n * // Parse: --suppress warning1 --suppress warning2\n * // Result: [\"warning1\", \"warning2\"]\n * suppressions.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const atMost = /*#__PURE__*/dual(2, (self, max) => {\n if (max < 0) {\n throw new Error(\"atMost: max must be non-negative\");\n }\n return variadic(self, {\n max\n });\n});\n/**\n * Wraps an option to require it to be specified at least `min` times.\n *\n * **Details**\n *\n * This combinator transforms an option to accept at least `min`\n * occurrences on the command line, returning an array of all provided values.\n *\n * **Example** (Requiring repeated values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Require at least 2 input files\n * const inputs = Param.String(Param.flagKind, \"input\").pipe(\n * Param.atLeast(2),\n * Param.withAlias(\"-i\")\n * )\n *\n * // Parse: --input file1.txt --input file2.txt --input file3.txt\n * // Result: [\"file1.txt\", \"file2.txt\", \"file3.txt\"]\n * inputs.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const atLeast = /*#__PURE__*/dual(2, (self, min) => {\n if (min < 0) {\n throw new Error(\"atLeast: min must be non-negative\");\n }\n return variadic(self, {\n min\n });\n});\n/**\n * Filters and transforms parsed values, failing with a custom error message\n * if the filter function returns `Option.none()`.\n *\n * **When to use**\n *\n * Use when you need validation and transformation in a single parameter\n * combinator.\n *\n * **Example** (Filtering and transforming values)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n * import { Param } from \"effect/cli\"\n * const positiveInt = Param.Int(Param.flagKind, \"count\").pipe(\n * Param.filterMap(\n * (n) => n > 0 ? Option.some(n) : Option.none(),\n * (n) => `Expected positive integer, got ${n}`\n * )\n * )\n * positiveInt.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(3, (self, filter, onNone) => mapEffect(self, Effect.fnUntraced(function* (a) {\n const result = filter(a);\n if (Option.isSome(result)) {\n return result.value;\n }\n const single = getUnderlyingSingleOrThrow(self);\n return yield* new CliError.InvalidValue({\n option: single.name,\n value: globalThis.String(a),\n expected: onNone(a),\n kind: single.kind\n });\n})));\n/**\n * Filters parsed values, failing with a custom error message if the predicate returns false.\n *\n * **Example** (Filtering parsed values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const evenNumber = Param.Int(Param.flagKind, \"num\").pipe(\n * Param.filter(\n * (n) => n % 2 === 0,\n * (n) => `Expected even number, got ${n}`\n * )\n * )\n * evenNumber.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const filter = /*#__PURE__*/dual(3, (self, predicate, onFalse) => filterMap(self, Option.liftPredicate(predicate), onFalse));\n/**\n * Sets a custom metavar (placeholder name) for the param in help documentation.\n *\n * **Details**\n *\n * The metavar is displayed in usage text to indicate what value the user should provide.\n * For example, `--output FILE` shows `FILE` as the metavar.\n *\n * **Example** (Setting metavars)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const port = Param.Int(Param.flagKind, \"port\").pipe(\n * Param.withMetavar(\"PORT\"),\n * Param.filter(\n * (p) => p >= 1 && p <= 65535,\n * () => \"Port must be between 1 and 65535\"\n * )\n * )\n * port.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category metadata\n * @since 4.0.0\n */\nexport const withMetavar = /*#__PURE__*/dual(2, (self, metavar) => transformSingle(self, single => makeSingle({\n ...single,\n typeName: metavar\n})));\n/**\n * Lets a flag be given without a value, in which case `value` is used.\n *\n * **Details**\n *\n * Follows GNU-style optional values. An explicit value must be attached with\n * `=` (`--watch=until-done`), and a bare `--watch` is parsed as\n * `--watch=<value>`. The flag never consumes the next token. It is still\n * required unless it is made optional or given a default.\n *\n * **Example** (Flag with an optional value)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const watch = Param.String(Param.flagKind, \"watch\").pipe(\n * Param.withOptionalValue(\"first-failure\"),\n * Param.optional\n * )\n * watch.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.1.0\n */\nexport const withOptionalValue = /*#__PURE__*/dual(2, (self, value) => transformSingle(self, single => makeSingle({\n ...single,\n optionalValue: value\n})));\n/**\n * Validates parsed values against a Schema, providing detailed error messages.\n *\n * **Example** (Validating with schemas)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Param } from \"effect/cli\"\n * const isEmail = Schema.isPattern(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/)\n *\n * const Email = Schema.String.pipe(\n * Schema.check(isEmail)\n * )\n *\n * const email = Param.String(Param.flagKind, \"email\").pipe(\n * Param.withSchema(Email)\n * )\n * email.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withSchema = /*#__PURE__*/dual(2, (self, schema) => {\n const decodeParam = Schema.decodeUnknownEffect(schema);\n return mapEffect(self, value => Effect.mapError(decodeParam(value), error => {\n const single = getUnderlyingSingleOrThrow(self);\n return new CliError.InvalidValue({\n option: single.name,\n value: globalThis.String(value),\n expected: `Schema validation failed: ${error.message}`,\n kind: single.kind\n });\n }));\n});\n/**\n * Provides a fallback param to use if this param fails to parse.\n *\n * **Example** (Falling back to another parameter)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const config = Param.File(Param.flagKind, \"config\").pipe(\n * Param.orElse(() => Param.String(Param.flagKind, \"config-url\"))\n * )\n * config.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const orElse = /*#__PURE__*/dual(2, (self, orElse) => transform(self, (parse, alternatives) => args => Effect.catch(parse(args), () => alternatives[0]()(args)), [orElse]));\n/**\n * Provides a fallback param and returns a `Result` indicating which param\n * succeeded.\n *\n * **Details**\n *\n * The original param's value is returned as `Result.succeed`, while the\n * fallback param's value is returned as `Result.fail`.\n *\n * **Example** (Returning fallback results)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const configSource = Param.File(Param.flagKind, \"config\").pipe(\n * Param.orElseResult(() => Param.String(Param.flagKind, \"config-url\"))\n * )\n * // Returns Result<string, string>\n * configSource.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const orElseResult = /*#__PURE__*/dual(2, (self, orElse) => {\n return transform(self, (parse, alternatives) => args => Effect.catch(Effect.map(parse(args), ([leftover, value]) => [leftover, Result.succeed(value)]), () => Effect.map(alternatives[0]()(args), ([leftover, value]) => [leftover, Result.fail(value)])), [orElse]);\n});\n// =============================================================================\n// Parsing Utilities\n// =============================================================================\nconst parsePositional = /*#__PURE__*/Effect.fnUntraced(function* (name, primitiveType, args) {\n if (args.arguments.length === 0) {\n return yield* new CliError.MissingArgument({\n argument: name\n });\n }\n const arg = args.arguments[0];\n const value = yield* Effect.mapError(primitiveType.parse(arg), error => new CliError.InvalidValue({\n option: name,\n value: arg,\n expected: error,\n kind: \"argument\"\n }));\n return [args.arguments.slice(1), value];\n});\nconst parseFlag = /*#__PURE__*/Effect.fnUntraced(function* (name, primitiveType, args) {\n const providedValues = args.flags[name];\n if (providedValues === undefined || providedValues.length === 0) {\n return yield* new CliError.MissingOption({\n option: name\n });\n }\n // Parse the first value (later we can handle multiple)\n const arg = providedValues[0];\n const value = yield* Effect.mapError(primitiveType.parse(arg), error => new CliError.InvalidValue({\n option: name,\n value: arg,\n expected: error,\n kind: \"flag\"\n }));\n return [args.arguments, value];\n});\nconst parsePositionalVariadic = /*#__PURE__*/Effect.fnUntraced(function* (self, single, args, options) {\n const results = [];\n const minValue = options?.min ?? 0;\n const maxValue = options?.max ?? Number.POSITIVE_INFINITY;\n let count = 0;\n let currentArgs = args.arguments;\n while (currentArgs.length > 0 && count < maxValue) {\n const [remainingArgs, value] = yield* self.parse({\n flags: args.flags,\n arguments: currentArgs\n });\n results.push(value);\n currentArgs = remainingArgs;\n count++;\n }\n if (count < minValue) {\n return yield* count === 0 ? new CliError.MissingArgument({\n argument: single.name\n }) : new CliError.InvalidValue({\n option: single.name,\n value: `${count} values`,\n expected: `at least ${minValue} value${minValue === 1 ? \"\" : \"s\"}`,\n kind: single.kind\n });\n }\n return [currentArgs, results];\n});\nconst parseOptionVariadic = /*#__PURE__*/Effect.fnUntraced(function* (self, single, args, options) {\n const results = [];\n const names = [single.name, ...single.aliases];\n const values = names.flatMap(name => args.flags[name] ?? []);\n const count = values.length;\n // Validate count constraints\n if (Predicate.isNotUndefined(options?.min) && count < options.min) {\n return yield* count === 0 ? new CliError.MissingOption({\n option: single.name\n }) : new CliError.InvalidValue({\n option: single.name,\n value: `${count} occurrences`,\n expected: `at least ${options.min} value${options.min === 1 ? \"\" : \"s\"}`,\n kind: single.kind\n });\n }\n if (Predicate.isNotUndefined(options?.max) && count > options.max) {\n return yield* new CliError.InvalidValue({\n option: single.name,\n value: `${count} occurrences`,\n expected: `at most ${options.max} value${options.max === 1 ? \"\" : \"s\"}`,\n kind: single.kind\n });\n }\n // Parse each value individually\n for (const value of values) {\n const [, parsedValue] = yield* self.parse({\n flags: {\n [single.name]: [value]\n },\n arguments: []\n });\n results.push(parsedValue);\n }\n return [args.arguments, results];\n});\n/**\n * Type-safe param matcher that handles the unsafe casting internally.\n * This provides a clean API for pattern matching on param types while\n * maintaining type safety at the call site.\n */\nconst matchParam = (param, patterns) => {\n const p = param;\n switch (p._tag) {\n case \"Single\":\n return patterns.Single(p);\n case \"Map\":\n return patterns.Map(p);\n case \"Transform\":\n return patterns.Transform(p);\n case \"Optional\":\n return patterns.Optional(p);\n case \"Variadic\":\n return patterns.Variadic(p);\n }\n};\n/**\n * Recursively transforms a param by applying a function to any `Single` nodes.\n * This is used internally by combinators like `withAlias` to traverse the param tree.\n */\nconst transformSingle = (param, f) => {\n return matchParam(param, {\n Single: single => f(single),\n Map: mapped => map(transformSingle(mapped.param, f), mapped.f),\n Transform: mapped => transform(transformSingle(mapped.param, f), mapped.f, mapped.alternatives.map(alternative => () => transformSingle(alternative(), f))),\n Optional: p => optional(transformSingle(p.param, f)),\n Variadic: p => variadic(transformSingle(p.param, f), {\n min: Option.getOrUndefined(p.min),\n max: Option.getOrUndefined(p.max)\n })\n });\n};\n/**\n * Extracts all Single params from a potentially nested param structure.\n * This handles all param combinators including Map, Transform, Optional, and Variadic.\n *\n * @internal\n */\nexport const extractSingleParams = param => {\n return matchParam(param, {\n Single: single => [single],\n Map: mapped => extractSingleParams(mapped.param),\n Transform: mapped => [...extractSingleParams(mapped.param), ...mapped.alternatives.flatMap(alternative => extractSingleParams(alternative()))],\n Optional: optional => extractSingleParams(optional.param),\n Variadic: variadic => extractSingleParams(variadic.param)\n });\n};\n/**\n * Gets the underlying Single param from a potentially nested param structure.\n * Throws an error if there are no singles or multiple singles found.\n *\n * @internal\n */\nexport const getUnderlyingSingleOrThrow = param => {\n const singles = extractSingleParams(param);\n if (singles.length === 0) {\n throw new Error(\"No Single param found in param structure\");\n }\n if (singles.length > 1) {\n throw new Error(`Multiple Single params found: ${singles.map(s => s.name).join(\", \")}`);\n }\n return singles[0];\n};\n/**\n * Gets param metadata by traversing the structure.\n *\n * @internal\n */\nexport const getParamMetadata = param => {\n return matchParam(param, {\n Single: () => ({\n isOptional: false,\n isVariadic: false,\n variadicMin: Option.none(),\n variadicMax: Option.none()\n }),\n Map: mapped => getParamMetadata(mapped.param),\n Transform: mapped => getParamMetadata(mapped.param),\n Optional: optional => ({\n ...getParamMetadata(optional.param),\n isOptional: true\n }),\n Variadic: variadic => ({\n ...getParamMetadata(variadic.param),\n isVariadic: true,\n variadicMin: variadic.min,\n variadicMax: variadic.max\n })\n });\n};\n//# sourceMappingURL=Param.js.map","import { dual } from \"../Function.js\";\nimport * as Param from \"./Param.js\";\n// -------------------------------------------------------------------------------------\n// constructors\n// -------------------------------------------------------------------------------------\n/**\n * Creates a positional string argument.\n *\n * **Example** (Creating a string argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const filename = Argument.String(\"filename\")\n * filename.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const String = name => Param.String(Param.argumentKind, name);\n/**\n * Creates a positional integer argument.\n *\n * **Example** (Creating an integer argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const count = Argument.Int(\"count\")\n * count.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Int = name => Param.Int(Param.argumentKind, name);\n/**\n * Creates a positional file path argument.\n *\n * **Example** (Creating file path arguments)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const inputFile = Argument.File(\"input\", { mustExist: true }) // Must exist\n * const outputFile = Argument.File(\"output\", { mustExist: false }) // Must not exist\n * const kinds = [inputFile.kind, outputFile.kind] // => [\"argument\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const File = (name, options) => Param.File(Param.argumentKind, name, options);\n/**\n * Creates a positional directory path argument.\n *\n * **Example** (Creating a directory path argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const workspace = Argument.Directory(\"workspace\", { mustExist: true }) // Must exist\n * workspace.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Directory = (name, options) => Param.Directory(Param.argumentKind, name, options);\n/**\n * Creates a positional argument that parses finite numbers.\n *\n * **Example** (Parsing a finite number)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const ratio = Argument.Finite(\"ratio\")\n * ratio.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Finite = name => Param.Finite(Param.argumentKind, name);\n/**\n * Creates a positional date argument.\n *\n * **Example** (Creating a date argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const startDate = Argument.Date(\"start-date\")\n * startDate.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Date = name => Param.Date(Param.argumentKind, name);\n/**\n * Creates a positional choice argument.\n *\n * **Example** (Creating a choice argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const environment = Argument.Literals(\"environment\", [\"dev\", \"staging\", \"prod\"])\n * environment.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Literals = (name, choices) => Param.Literals(Param.argumentKind, name, choices);\n/**\n * Creates a positional path argument.\n *\n * **Example** (Creating a path argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const configPath = Argument.Path(\"config\")\n * configPath.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Path = (name, options) => Param.Path(Param.argumentKind, name, options);\n/**\n * Creates a positional redacted argument that obscures its value.\n *\n * **Example** (Creating a redacted argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const secret = Argument.Redacted(\"secret\")\n * secret.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Redacted = name => Param.Redacted(Param.argumentKind, name);\n/**\n * Creates a positional argument that reads file content as a string.\n *\n * **Example** (Reading file text)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const config = Argument.FileText(\"config-file\")\n * config.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileText = name => Param.FileText(Param.argumentKind, name);\n/**\n * Creates a positional argument that reads a file and parses its content.\n *\n * **Details**\n *\n * The parser is chosen from the explicit `format` option or, when omitted, the\n * file extension. The parsed value is `unknown`; use `fileSchema` when the\n * parsed content should also be decoded with a Schema.\n *\n * **Example** (Parsing file content)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const config = Argument.FileParse(\"config\", { format: \"json\" })\n * config.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileParse = (name, options) => Param.FileParse(Param.argumentKind, name, options);\n/**\n * Creates a positional argument that reads and validates file content using a schema.\n *\n * **Example** (Validating file content with a schema)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Argument } from \"effect/cli\"\n *\n * const ConfigSchema = Schema.Struct({\n * port: Schema.Number,\n * host: Schema.String\n * })\n *\n * const config = Argument.FileSchema(\"config\", ConfigSchema)\n * config.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileSchema = (name, schema, options) => Param.FileSchema(Param.argumentKind, name, schema, options);\n/**\n * An argument that always fails to parse.\n *\n * **Example** (Creating a sentinel argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const noArg = Argument.Never\n * noArg.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Never = /*#__PURE__*/Param.Never(Param.argumentKind);\n// -------------------------------------------------------------------------------------\n// combinators\n// -------------------------------------------------------------------------------------\n/**\n * Makes a positional argument optional.\n *\n * **Example** (Making an argument optional)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const optionalVersion = Argument.String(\"version\").pipe(Argument.optional)\n * optionalVersion.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const optional = arg => Param.optional(arg);\n/**\n * Adds a description to a positional argument.\n *\n * **Example** (Adding an argument description)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const filename = Argument.String(\"filename\").pipe(\n * Argument.withDescription(\"The input file to process\")\n * )\n * filename.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withDescription = /*#__PURE__*/dual(2, (self, description) => Param.withDescription(self, description));\n/**\n * Provides a default value for a positional argument.\n *\n * **Example** (Providing a default value)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const port = Argument.Int(\"port\").pipe(Argument.withDefault(8080))\n * port.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withDefault = Param.withDefault;\n/**\n * Adds a fallback config that is loaded when a required argument is missing.\n *\n * **Example** (Loading a fallback config)\n *\n * ```ts import.meta.vitest\n * import { Config } from \"effect\"\n * import { Argument } from \"effect/cli\"\n *\n * const repository = Argument.String(\"repository\").pipe(\n * Argument.withFallbackConfig(Config.String(\"REPOSITORY\"))\n * )\n * repository.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackConfig = /*#__PURE__*/dual(2, (self, config) => Param.withFallbackConfig(self, config));\n/**\n * Adds a fallback prompt that is shown when a required argument is missing.\n *\n * **Example** (Showing a fallback prompt)\n *\n * ```ts import.meta.vitest\n * import { Argument, Prompt } from \"effect/cli\"\n *\n * const filename = Argument.String(\"filename\").pipe(\n * Argument.withFallbackPrompt(Prompt.String({ message: \"Filename\" }))\n * )\n * filename.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackPrompt = /*#__PURE__*/dual(2, (self, prompt) => Param.withFallbackPrompt(self, prompt));\n/**\n * Creates a variadic positional argument that accepts multiple values.\n *\n * **Example** (Accepting multiple values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * // Accept any number of files\n * const anyFiles = Argument.String(\"files\").pipe(Argument.variadic)\n *\n * // Accept at least 1 file\n * const atLeastOneFile = Argument.String(\"files\").pipe(\n * Argument.variadic({ min: 1 })\n * )\n *\n * // Accept between 1 and 5 files\n * const limitedFiles = Argument.String(\"files\").pipe(\n * Argument.variadic({ min: 1, max: 5 })\n * )\n *\n * const kinds = [anyFiles.kind, atLeastOneFile.kind, limitedFiles.kind] // => [\"argument\", \"argument\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const variadic = /*#__PURE__*/dual(args => Param.isParam(args[0]), (self, options) => Param.variadic(self, options));\n/**\n * Transforms the parsed value of a positional argument.\n *\n * **Example** (Mapping parsed values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const port = Argument.Int(\"port\").pipe(\n * Argument.map((p) => ({ port: p, url: `http://localhost:${p}` }))\n * )\n * port.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => Param.map(self, f));\n/**\n * Transforms the parsed value of a positional argument using an effectful function.\n *\n * **Example** (Validating values effectfully)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Argument, CliError } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const files = Argument.String(\"files\").pipe(\n * Argument.mapEffect((file) =>\n * file.endsWith(\".txt\")\n * ? Effect.succeed(file)\n * : Effect.fail(\n * new CliError.UserError({\n * cause: new Error(`Unsupported file extension: ${file}`),\n * userMessage: \"Only .txt files allowed\"\n * })\n * )\n * )\n * )\n *\n * const [, value] = await Effect.runPromise(\n * files.parse({ arguments: [\"notes.txt\"], flags: {} }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => \"notes.txt\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const mapEffect = /*#__PURE__*/dual(2, (self, f) => Param.mapEffect(self, f));\n/**\n * Transforms the parsed value of a positional argument using a function that may throw.\n *\n * **Example** (Mapping values that may throw)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Argument } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const json = Argument.String(\"data\").pipe(\n * Argument.mapTryCatch(\n * (str) => JSON.parse(str),\n * (error) =>\n * `Invalid JSON: ${error instanceof Error ? error.message : String(error)}`\n * )\n * )\n *\n * const [, value] = await Effect.runPromise(\n * json.parse({ arguments: ['{\"enabled\":true}'], flags: {} }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => { enabled: true }\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const mapTryCatch = /*#__PURE__*/dual(3, (self, f, onError) => Param.mapTryCatch(self, f, onError));\n/**\n * Creates a variadic argument that requires at least n values.\n *\n * **Example** (Requiring a minimum number of values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const files = Argument.String(\"files\").pipe(Argument.atLeast(1))\n * files.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const atLeast = /*#__PURE__*/dual(2, (self, min) => Param.atLeast(self, min));\n/**\n * Creates a variadic argument that accepts at most n values.\n *\n * **Example** (Limiting the maximum number of values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const files = Argument.String(\"files\").pipe(Argument.atMost(5))\n * files.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const atMost = /*#__PURE__*/dual(2, (self, max) => Param.atMost(self, max));\n/**\n * Creates a variadic argument that accepts between min and max values.\n *\n * **Example** (Requiring a range of values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const files = Argument.String(\"files\").pipe(Argument.between(1, 5))\n * files.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const between = /*#__PURE__*/dual(3, (self, min, max) => Param.between(self, min, max));\n/**\n * Validates parsed values against a Schema.\n *\n * **Example** (Validating parsed values with a schema)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Argument } from \"effect/cli\"\n *\n * const input = Argument.String(\"input\").pipe(\n * Argument.withSchema(Schema.NonEmptyString)\n * )\n * input.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withSchema = /*#__PURE__*/dual(2, (self, schema) => Param.withSchema(self, schema));\n/**\n * Creates a positional choice argument with custom value mapping.\n *\n * **Example** (Mapping choices to values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const logLevel = Argument.ChoiceWithValue(\"level\", [\n * [\"debug\", 0],\n * [\"info\", 1],\n * [\"warn\", 2],\n * [\"error\", 3]\n * ])\n * logLevel.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const ChoiceWithValue = (name, choices) => Param.ChoiceWithValue(Param.argumentKind, name, choices);\n// -------------------------------------------------------------------------------------\n// metadata\n// -------------------------------------------------------------------------------------\n/**\n * Sets a custom metavar (placeholder name) for the argument in help documentation.\n *\n * **Details**\n *\n * The metavar is displayed in usage text to indicate what value the user should provide.\n * For example, `<FILE>` shows `FILE` as the metavar.\n *\n * **Example** (Setting a metavar)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const port = Argument.Int(\"port\").pipe(\n * Argument.withMetavar(\"PORT\")\n * )\n * port.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category metadata\n * @since 4.0.0\n */\nexport const withMetavar = /*#__PURE__*/dual(2, (self, metavar) => Param.withMetavar(self, metavar));\n/**\n * Filters parsed values, failing with a custom error message if the predicate returns false.\n *\n * **Example** (Filtering parsed values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const positiveInt = Argument.Int(\"count\").pipe(\n * Argument.filter(\n * (n) => n > 0,\n * (n) => `Expected positive integer, got ${n}`\n * )\n * )\n * positiveInt.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const filter = /*#__PURE__*/dual(3, (self, predicate, onFalse) => Param.filter(self, predicate, onFalse));\n/**\n * Filters and transforms parsed values, failing with a custom error message\n * if the filter function returns None.\n *\n * **Example** (Filtering and mapping parsed values)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n * import { Argument } from \"effect/cli\"\n *\n * const positiveInt = Argument.Int(\"count\").pipe(\n * Argument.filterMap(\n * (n) => n > 0 ? Option.some(n) : Option.none(),\n * (n) => `Expected positive integer, got ${n}`\n * )\n * )\n * positiveInt.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(3, (self, f, onNone) => Param.filterMap(self, f, onNone));\n/**\n * Provides a fallback argument to use if this argument fails to parse.\n *\n * **Example** (Providing a fallback argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const value = Argument.Int(\"value\").pipe(\n * Argument.orElse(() => Argument.String(\"value\"))\n * )\n * value.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const orElse = /*#__PURE__*/dual(2, (self, that) => Param.orElse(self, that));\n/**\n * Provides a fallback argument, wrapping results in Result to distinguish which succeeded.\n *\n * **Example** (Returning which fallback succeeded)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const source = Argument.File(\"source\").pipe(\n * Argument.orElseResult(() => Argument.String(\"url\"))\n * )\n * // Returns Result<string, string>\n * source.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const orElseResult = /*#__PURE__*/dual(2, (self, that) => Param.orElseResult(self, that));\n//# sourceMappingURL=Argument.js.map","/**\n * Formats CLI help and errors as text.\n *\n * This module turns help documents, CLI errors, grouped errors, and version\n * information into strings. It does not write those strings to the terminal\n * itself. It includes the `Formatter` interface, the formatter service, a layer\n * for custom formatters, and the default formatter with configurable color\n * support.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"../Context.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as Option from \"../Option.js\";\nimport * as Ansi from \"./internal/ansi.js\";\n/**\n * Service reference for the CLI output formatter. Provides a default implementation\n * that can be overridden for custom formatting or testing.\n *\n * **Example** (Accessing the output formatter)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliOutput } from \"effect/cli\"\n *\n * // Access the formatter service\n * const program = Effect.gen(function*() {\n * const formatter = yield* CliOutput.Formatter\n *\n * // Format version information\n * return formatter.formatVersion(\"my-cli\", \"2.1.0\")\n * })\n *\n * // Run with default formatter\n * await Effect.runPromise(program.pipe(\n * Effect.provide(CliOutput.layer(CliOutput.defaultFormatter({ colors: false })))\n * )) // => \"my-cli v2.1.0\"\n * ```\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const Formatter = /*#__PURE__*/Context.Reference(\"effect/cli/CliOutput\", {\n defaultValue: () => defaultFormatter()\n});\n/**\n * Creates a Layer that provides a custom Formatter implementation.\n *\n * **Example** (Providing a custom formatter)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliOutput } from \"effect/cli\"\n *\n * // Create a custom formatter without colors\n * const noColorFormatter = CliOutput.defaultFormatter({ colors: false })\n * const NoColorLayer = CliOutput.layer(noColorFormatter)\n *\n * // Create a program that uses the custom formatter\n * const program = Effect.gen(function*() {\n * const formatter = yield* CliOutput.Formatter\n * return formatter.formatVersion(\"my-cli\", \"1.0.0\")\n * }).pipe(\n * Effect.provide(NoColorLayer)\n * )\n *\n * await Effect.runPromise(program) // => \"my-cli v1.0.0\"\n * ```\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = formatter => Layer.succeed(Formatter)(formatter);\nconst escapeControlCharacters = text =>\n// oxlint-disable-next-line no-control-regex\ntext.replace(/[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F]/g, character => `\\\\x${character.charCodeAt(0).toString(16).padStart(2, \"0\")}`);\n/**\n * Creates a default formatter with configurable options.\n *\n * **Example** (Creating default formatters)\n *\n * ```ts import.meta.vitest\n * import { CliError, CliOutput } from \"effect/cli\"\n *\n * // Create a formatter without colors for tests or CI environments\n * const noColorFormatter = CliOutput.defaultFormatter({ colors: false })\n *\n * // Create a formatter with colors forced on\n * const colorFormatter = CliOutput.defaultFormatter({ colors: true })\n *\n * // Auto-detect colors based on terminal support (default behavior)\n * const autoFormatter = CliOutput.defaultFormatter()\n *\n * const error = new CliError.InvalidValue({\n * option: \"foo\",\n * value: \"bar\",\n * expected: \"baz\",\n * kind: \"flag\"\n * })\n *\n * noColorFormatter.formatError(error).includes(\"Invalid value\") // => true\n * colorFormatter.formatVersion(\"my-tool\", \"1.2.3\").includes(\"my-tool\") // => true\n * autoFormatter.formatVersion(\"my-tool\", \"1.2.3\").includes(\"1.2.3\") // => true\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const defaultFormatter = options => {\n const useColor = options?.colors ?? Ansi.detectColors();\n // Color palette using ANSI escape codes\n const colors = useColor ? {\n bold: text => `\\x1b[1m${text}\\x1b[0m`,\n dim: text => `\\x1b[2m${text}\\x1b[0m`,\n cyan: text => `\\x1b[36m${text}\\x1b[0m`,\n green: text => `\\x1b[32m${text}\\x1b[0m`,\n blue: text => `\\x1b[34m${text}\\x1b[0m`,\n yellow: text => `\\x1b[33m${text}\\x1b[0m`,\n magenta: text => `\\x1b[35m${text}\\x1b[0m`\n } : {\n bold: text => text,\n dim: text => text,\n cyan: text => text,\n green: text => text,\n blue: text => text,\n yellow: text => text,\n magenta: text => text\n };\n const reset = useColor ? \"\\x1b[0m\" : \"\";\n const red = useColor ? \"\\x1b[31m\" : \"\";\n const bold = useColor ? \"\\x1b[1m\" : \"\";\n return {\n formatHelpDoc: doc => formatHelpDocImpl(doc, colors),\n formatCliError: error => escapeControlCharacters(error.message),\n formatError: error => {\n return `\\n${bold}${red}ERROR${reset}\\n ${escapeControlCharacters(error.message)}${reset}`;\n },\n formatErrors: errors => {\n if (errors.length === 0) return \"\";\n if (errors.length === 1) {\n return `\\n${bold}${red}ERROR${reset}\\n ${escapeControlCharacters(errors[0].message)}${reset}`;\n }\n // Group errors by _tag\n const grouped = new Map();\n for (const error of errors) {\n const tag = error._tag ?? \"Error\";\n const group = grouped.get(tag) ?? [];\n group.push(error);\n grouped.set(tag, group);\n }\n const sections = [];\n sections.push(`\\n${bold}${red}ERRORS${reset}`);\n for (const [, group] of grouped) {\n for (const error of group) {\n sections.push(` ${escapeControlCharacters(error.message)}${reset}`);\n }\n }\n return sections.join(\"\\n\");\n },\n formatVersion: (name, version) => `${colors.bold(name)} ${colors.dim(\"v\")}${colors.bold(version)}`\n };\n};\n/**\n * Strips ANSI escape codes from a string to calculate visual width.\n * @internal\n */\nconst stripAnsi = text => {\n // oxlint-disable-next-line no-control-regex\n return text.replace(/\\u001B\\[[0-9;]*m/g, \"\");\n};\n/**\n * Segments text into grapheme clusters.\n * @internal\n */\nconst graphemeSegmenter = /*#__PURE__*/new Intl.Segmenter(undefined, {\n granularity: \"grapheme\"\n});\nconst zeroWidthCodePoints = /[\\p{Mark}\\p{Control}\\p{Default_Ignorable_Code_Point}]/gu;\nconst emojiPresentation = /\\p{Emoji_Presentation}/u;\nconst isFullWidthCodePoint = codePoint => {\n if (codePoint < 0x1100) return false;\n return codePoint <= 0x115f || codePoint === 0x2329 || codePoint === 0x232a || codePoint >= 0x2e80 && codePoint <= 0x303e || codePoint >= 0x3040 && codePoint <= 0xa4cf || codePoint >= 0xac00 && codePoint <= 0xd7a3 || codePoint >= 0xf900 && codePoint <= 0xfaff || codePoint >= 0xfe10 && codePoint <= 0xfe19 || codePoint >= 0xfe30 && codePoint <= 0xfe6f || codePoint >= 0xff00 && codePoint <= 0xff60 || codePoint >= 0xffe0 && codePoint <= 0xffe6 || codePoint >= 0x1b000 && codePoint <= 0x1b2ff || codePoint >= 0x1f200 && codePoint <= 0x1f251 || codePoint >= 0x20000 && codePoint <= 0x3fffd;\n};\nconst graphemeWidth = grapheme => {\n const visible = grapheme.replace(zeroWidthCodePoints, \"\");\n if (visible.length === 0) return 0;\n if (emojiPresentation.test(grapheme) || grapheme.includes(\"\\uFE0F\")) return 2;\n return isFullWidthCodePoint(visible.codePointAt(0)) ? 2 : 1;\n};\n/**\n * Measures the number of terminal cells a string occupies.\n *\n * **Details**\n *\n * Uses the same measurement as built-in help and table rendering. ANSI styling\n * is stripped before measuring graphemes: zero-width graphemes count as `0`,\n * emoji presentation sequences and fullwidth characters as `2`, and other\n * graphemes as `1`.\n *\n * **Example** (Measuring terminal-cell widths)\n *\n * ```ts import.meta.vitest\n * import { CliOutput } from \"effect/cli\"\n *\n * CliOutput.displayWidth(\"file\") // => 4\n * CliOutput.displayWidth(\"ファイル\") // => 8\n * CliOutput.displayWidth(\"é\") // => 1\n * CliOutput.displayWidth(\"1️⃣\") // => 2\n * CliOutput.displayWidth(\"\\u001B[1mbold\\u001B[0m\") // => 4\n * ```\n *\n * @stability unstable\n * @category measuring\n * @since 4.0.3\n */\nexport const displayWidth = text => {\n let length = 0;\n for (const {\n segment\n } of graphemeSegmenter.segment(stripAnsi(text))) {\n length += graphemeWidth(segment);\n }\n return length;\n};\n/**\n * Helper function to pad strings to a specified width.\n * @internal\n */\nconst pad = (s, width) => {\n const actualLength = displayWidth(s);\n const padding = Math.max(0, width - actualLength);\n return s + \" \".repeat(padding);\n};\n/**\n * Renders a table with aligned columns.\n * @internal\n */\nconst renderTable = (rows, widthCap) => {\n const maxColumn = Math.max(...rows.map(r => displayWidth(r.left))) + 4;\n const col = widthCap === undefined ? maxColumn : Math.min(maxColumn, widthCap);\n return rows.map(({\n left,\n right\n }) => ` ${pad(left, Math.max(col, displayWidth(left) + 1))}${right}`).join(\"\\n\");\n};\nconst formatSubcommandName = (name, alias) => alias ? `${name}, ${alias}` : name;\n/**\n * Internal implementation of help formatting that accepts configurable color functions.\n * @internal\n */\nconst formatHelpDocImpl = (doc, colors) => {\n const sections = [];\n // Description section\n if (doc.description) {\n sections.push(colors.bold(\"DESCRIPTION\"));\n sections.push(` ${doc.description}`);\n sections.push(\"\");\n }\n // Usage section\n sections.push(colors.bold(\"USAGE\"));\n sections.push(` ${colors.cyan(doc.usage)}`);\n sections.push(\"\");\n // Arguments section\n if (doc.args && doc.args.length > 0) {\n sections.push(colors.bold(\"ARGUMENTS\"));\n const argRows = doc.args.map(arg => {\n let name = arg.name;\n if (arg.variadic) {\n name += \"...\";\n }\n const coloredName = colors.green(name);\n const coloredType = colors.dim(arg.type);\n const nameType = `${coloredName} ${coloredType}`;\n const optionalSuffix = arg.required ? \"\" : colors.dim(\" (optional)\");\n const description = Option.getOrElse(arg.description, () => \"\") + optionalSuffix;\n return {\n left: nameType,\n right: description\n };\n });\n sections.push(renderTable(argRows, 25));\n sections.push(\"\");\n }\n // Flags section\n if (doc.flags.length > 0) {\n sections.push(colors.bold(\"FLAGS\"));\n const flagRows = doc.flags.map(flag => {\n const names = [];\n // Add main name with -- prefix first\n names.push(colors.green(`--${flag.name}`));\n // Add aliases after (like -f) to match expected ordering\n for (const alias of flag.aliases) {\n names.push(colors.green(alias));\n }\n const namesPart = names.join(\", \");\n const typePart = flag.type !== \"boolean\" ? ` ${colors.dim(flag.type)}` : \"\";\n return {\n left: namesPart + typePart,\n right: Option.getOrElse(flag.description, () => \"\")\n };\n });\n sections.push(renderTable(flagRows));\n sections.push(\"\");\n }\n // Global Flags section\n if (doc.globalFlags && doc.globalFlags.length > 0) {\n sections.push(colors.bold(\"GLOBAL FLAGS\"));\n const globalFlagRows = doc.globalFlags.map(flag => {\n const names = [];\n // Add main name with -- prefix first\n names.push(colors.green(`--${flag.name}`));\n // Add aliases after (like -f) to match expected ordering\n for (const alias of flag.aliases) {\n names.push(colors.green(alias));\n }\n const namesPart = names.join(\", \");\n const typePart = flag.type !== \"boolean\" ? ` ${colors.dim(flag.type)}` : \"\";\n return {\n left: namesPart + typePart,\n right: Option.getOrElse(flag.description, () => \"\")\n };\n });\n sections.push(renderTable(globalFlagRows));\n sections.push(\"\");\n }\n // Subcommands section\n if (doc.subcommands && doc.subcommands.length > 0) {\n const ungrouped = doc.subcommands.find(group => group.group === undefined);\n if (ungrouped) {\n sections.push(colors.bold(\"SUBCOMMANDS\"));\n sections.push(renderTable(ungrouped.commands.map(sub => ({\n left: colors.cyan(formatSubcommandName(sub.name, sub.alias)),\n right: sub.shortDescription ?? sub.description\n })), 20));\n if (doc.subcommands.length > 1) {\n sections.push(\"\");\n }\n }\n for (const group of doc.subcommands) {\n if (group.group === undefined) continue;\n sections.push(colors.bold(`${group.group}:`));\n sections.push(renderTable(group.commands.map(sub => ({\n left: colors.cyan(formatSubcommandName(sub.name, sub.alias)),\n right: sub.shortDescription ?? sub.description\n })), 20));\n sections.push(\"\");\n }\n }\n // Examples section\n if (doc.examples && doc.examples.length > 0) {\n sections.push(colors.bold(\"EXAMPLES\"));\n let first = true;\n let previousHadDescription = false;\n for (const example of doc.examples) {\n if (example.description) {\n if (!first) sections.push(\"\");\n sections.push(` ${colors.dim(`# ${example.description}`)}`);\n } else if (previousHadDescription) {\n sections.push(\"\");\n }\n sections.push(` ${colors.cyan(example.command)}`);\n first = false;\n previousHadDescription = !!example.description;\n }\n sections.push(\"\");\n }\n // Remove trailing empty line if present\n if (sections[sections.length - 1] === \"\") {\n sections.pop();\n }\n return sections.join(\"\\n\");\n};\n//# sourceMappingURL=CliOutput.js.map","/**\n * Config Internal\n * ================\n *\n * The processed internal representation of a Command.Config declaration.\n * Separates the user's declared config shape from the flat parsing representation.\n *\n * Key concepts:\n * - ConfigInternal: The full processed form (flags, arguments, tree)\n * - ConfigInternal.Tree: Maps declaration keys to nodes\n * - ConfigInternal.Node: Param reference, Array, or Nested subtree\n *\n * Example transformation from Command.Config to Command.Config.Internal:\n *\n * ```ts\n * // User declares:\n * const config = {\n * verbose: Flag.Boolean(\"verbose\").pipe(Flag.withDefault(false)),\n * server: {\n * host: Flag.String(\"host\"),\n * port: Flag.Int(\"port\")\n * },\n * files: Argument.String(\"files\").pipe(Argument.variadic)\n * }\n *\n * // Becomes Config.Internal:\n * {\n * arguments: [filesParam], // Flat array of arguments\n * flags: [verboseParam, hostParam, portParam], // Flat array of flags\n * orderedParams: [verboseParam, hostParam, portParam, filesParam],\n * tree: { // Preserves nested structure\n * verbose: { _tag: \"Param\", index: 0 },\n * server: {\n * _tag: \"Nested\",\n * tree: {\n * host: { _tag: \"Param\", index: 1 },\n * port: { _tag: \"Param\", index: 2 }\n * }\n * },\n * files: { _tag: \"Param\", index: 3 }\n * }\n * }\n * ```\n *\n * This separation allows:\n * 1. Flat iteration over all params for parsing/validation\n * 2. Reconstruction of original nested shape for handler input\n */\nimport * as InternalRecord from \"../../internal/record.js\";\nimport * as Param from \"../Param.js\";\n/* ========================================================================== */\n/* Type ID */\n/* ========================================================================== */\nconst ConfigInternalTypeId = \"~effect/cli/Command/Config/Internal\";\n/**\n * Parses a Command.Config into a ConfigInternal.\n *\n * Walks the config structure and:\n * 1. Extracts all Params into flat arrays (flags, arguments, orderedParams)\n * 2. Builds a tree that remembers the original nested structure\n * 3. Assigns each Param an index to link parsed values back\n *\n * @internal\n */\nexport const parseConfig = config => {\n const orderedParams = [];\n const flags = [];\n const args = [];\n function parse(config) {\n const tree = Object.create(null);\n for (const key of Object.keys(config)) {\n tree[key] = parseValue(config[key]);\n }\n return tree;\n }\n function parseValue(value) {\n if (Array.isArray(value)) {\n return {\n _tag: \"Array\",\n children: value.map(v => parseValue(v))\n };\n } else if (Param.isParam(value)) {\n const index = orderedParams.length;\n orderedParams.push(value);\n if (value.kind === \"argument\") {\n args.push(value);\n } else {\n flags.push(value);\n }\n return {\n _tag: \"Param\",\n index\n };\n } else {\n return {\n _tag: \"Nested\",\n tree: parse(value)\n };\n }\n }\n return {\n [ConfigInternalTypeId]: ConfigInternalTypeId,\n flags,\n arguments: args,\n orderedParams,\n tree: parse(config)\n };\n};\n/**\n * @internal\n */\nexport const emptyConfig = /*#__PURE__*/parseConfig({});\nconst shiftNodeIndexes = (node, offset) => {\n switch (node._tag) {\n case \"Param\":\n return {\n _tag: \"Param\",\n index: node.index + offset\n };\n case \"Array\":\n return {\n _tag: \"Array\",\n children: node.children.map(child => shiftNodeIndexes(child, offset))\n };\n case \"Nested\":\n return {\n _tag: \"Nested\",\n tree: shiftTreeIndexes(node.tree, offset)\n };\n }\n};\nconst shiftTreeIndexes = (tree, offset) => {\n const output = Object.create(null);\n for (const key of Object.keys(tree)) {\n output[key] = shiftNodeIndexes(tree[key], offset);\n }\n return output;\n};\n/**\n * @internal\n */\nexport const mergeConfig = (left, right) => {\n const offset = left.orderedParams.length;\n return {\n [ConfigInternalTypeId]: ConfigInternalTypeId,\n flags: [...left.flags, ...right.flags],\n arguments: [...left.arguments, ...right.arguments],\n orderedParams: [...left.orderedParams, ...right.orderedParams],\n tree: Object.assign(Object.create(null), left.tree, shiftTreeIndexes(right.tree, offset))\n };\n};\n/* ========================================================================== */\n/* Reconstruction */\n/* ========================================================================== */\n/**\n * Reconstructs the original nested config shape from parsed values.\n *\n * Uses the tree as a blueprint to place each parsed value back into\n * its original position in the nested structure.\n *\n * @internal\n */\nexport const reconstructTree = (tree, results) => {\n const output = {};\n for (const key of Object.keys(tree)) {\n InternalRecord.assignProperty(output, key, nodeValue(tree[key]));\n }\n return output;\n function nodeValue(node) {\n switch (node._tag) {\n case \"Param\":\n return results[node.index];\n case \"Array\":\n return node.children.map(child => nodeValue(child));\n case \"Nested\":\n return reconstructTree(node.tree, results);\n }\n }\n};\n//# sourceMappingURL=config.js.map","/**\n * Command Implementation\n * ======================\n *\n * Internal implementation details for CLI commands.\n * Public API is in ../Command.ts\n */\nimport * as Arr from \"../../Array.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Effectable from \"../../Effectable.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as CliError from \"../CliError.js\";\nimport * as Param from \"../Param.js\";\nimport * as Primitive from \"../Primitive.js\";\nimport { emptyConfig, reconstructTree } from \"./config.js\";\n/* ========================================================================== */\n/* Type ID */\n/* ========================================================================== */\nexport const TypeId = \"~effect/cli/Command\";\n/* ========================================================================== */\n/* Casting */\n/* ========================================================================== */\n/**\n * Casts a Command to its internal implementation.\n * For use by internal modules that need access to config, parse, handle, etc.\n */\nexport const toImpl = self => self;\n/* ========================================================================== */\n/* Proto */\n/* ========================================================================== */\nexport const Proto = {\n ... /*#__PURE__*/Effectable.Prototype({\n label: \"Command\",\n evaluate() {\n return toImpl(this).service;\n }\n })\n};\n/* ========================================================================== */\n/* Constructor */\n/* ========================================================================== */\n/**\n * Internal command constructor. Only accepts already-parsed ConfigInternal.\n */\nexport const makeCommand = options => {\n const config = options.config;\n const contextConfig = options.contextConfig ?? emptyConfig;\n const service = options.service ?? Context.Service(`${TypeId}/${options.name}`);\n const annotations = options.annotations ?? Context.empty();\n const globalFlags = options.globalFlags ?? [];\n const subcommands = options.subcommands ?? [];\n const handle = (input, commandPath) => Predicate.isNotUndefined(options.handle) ? options.handle(input, commandPath) : Effect.fail(new CliError.ShowHelp({\n commandPath,\n errors: []\n }));\n const parse = options.parse ?? makeParser(config);\n const parseContext = options.parseContext ?? makeParser(contextConfig, {\n allowLeftovers: true\n });\n const buildHelpDoc = commandPath => {\n const args = [];\n const flags = [];\n for (const arg of config.arguments) {\n const singles = Param.extractSingleParams(arg);\n const metadata = Param.getParamMetadata(arg);\n for (const single of singles) {\n args.push({\n name: single.name,\n type: single.typeName ?? Primitive.getTypeName(single.primitiveType),\n description: single.description,\n required: !metadata.isOptional && (!metadata.isVariadic || Option.exists(metadata.variadicMin, min => min > 0)),\n variadic: metadata.isVariadic\n });\n }\n }\n let usage = commandPath.length > 0 ? commandPath.join(\" \") : options.name;\n // Only render `<subcommand>` in usage when at least one visible subcommand\n // exists; an all-unlisted subcommand tree should look like a leaf command.\n if (subcommands.some(group => group.commands.some(c => !c.unlisted))) {\n usage += \" <subcommand>\";\n }\n usage += \" [flags]\";\n for (const arg of args) {\n const argName = arg.variadic ? `<${arg.name}...>` : `<${arg.name}>`;\n usage += ` ${arg.required ? argName : `[${argName}]`}`;\n }\n for (const option of config.flags) {\n const singles = Param.extractSingleParams(option);\n const metadata = Param.getParamMetadata(option);\n for (const single of singles) {\n // Hidden flags still parse on the command line but are omitted from\n // generated --help output.\n if (single.hidden) continue;\n flags.push(toFlagDoc(single, metadata));\n }\n }\n const subcommandDocs = [];\n for (const group of subcommands) {\n // Unlisted subcommands still parse on the command line but are omitted\n // from --help. Drop the whole group when nothing visible remains so we\n // don't render an empty heading.\n const visible = group.commands.filter(c => !c.unlisted);\n if (visible.length === 0) continue;\n subcommandDocs.push({\n group: group.group,\n commands: Arr.map(visible, subcommand => ({\n name: subcommand.name,\n alias: subcommand.alias,\n shortDescription: subcommand.shortDescription,\n description: subcommand.description ?? \"\"\n }))\n });\n }\n const examples = options.examples ?? [];\n return {\n description: options.description ?? \"\",\n usage,\n flags,\n annotations,\n ...(args.length > 0 && {\n args\n }),\n ...(subcommandDocs.length > 0 && {\n subcommands: subcommandDocs\n }),\n ...(examples.length > 0 && {\n examples\n })\n };\n };\n return Object.assign(Object.create(Proto), {\n [TypeId]: TypeId,\n name: options.name,\n examples: options.examples ?? [],\n annotations,\n globalFlags,\n subcommands,\n unlisted: options.unlisted ?? false,\n config,\n contextConfig,\n service,\n parse,\n parseContext,\n handle,\n buildHelpDoc,\n ...(Predicate.isNotUndefined(options.description) ? {\n description: options.description\n } : {}),\n ...(Predicate.isNotUndefined(options.shortDescription) ? {\n shortDescription: options.shortDescription\n } : {}),\n ...(Predicate.isNotUndefined(options.alias) ? {\n alias: options.alias\n } : {})\n });\n};\n/* ========================================================================== */\n/* Helpers */\n/* ========================================================================== */\n/**\n * Converts a single flag param into a FlagDoc for help display.\n *\n * @internal\n */\nexport const toFlagDoc = (single, metadata) => {\n const formattedAliases = single.aliases.map(alias => alias.length === 1 ? `-${alias}` : `--${alias}`);\n const type = single.typeName ?? Primitive.getTypeName(single.primitiveType);\n return {\n name: single.name,\n aliases: formattedAliases,\n type: single.optionalValue === undefined ? type : `[=${type}]`,\n description: appendChoiceKeys(single.description, Primitive.getChoiceKeys(single.primitiveType)),\n required: single.primitiveType._tag !== \"Boolean\" && !metadata.isOptional\n };\n};\nconst appendChoiceKeys = (description, choiceKeys) => {\n if (choiceKeys === undefined || choiceKeys.length === 0) {\n return description;\n }\n const choiceSuffix = `(choices: ${choiceKeys.join(\", \")})`;\n return Option.match(description, {\n onNone: () => Option.some(choiceSuffix),\n onSome: value => Option.some(`${value} ${choiceSuffix}`)\n });\n};\n/**\n * Creates a parser for a given config. Used as the default for both `parse`\n * and `parseContext`, and also by `withSharedFlags` to avoid constructing a\n * full throwaway command.\n */\nexport const makeParser = (cfg, options) => Effect.fnUntraced(function* (input) {\n const parsedArgs = {\n flags: input.flags,\n arguments: input.arguments\n };\n const [remainingArguments, values] = yield* parseParams(parsedArgs, cfg.orderedParams);\n if (options?.allowLeftovers !== true && remainingArguments.length > 0) {\n return yield* new CliError.UnexpectedArgument({\n arguments: remainingArguments\n });\n }\n return reconstructTree(cfg.tree, values);\n});\n/**\n * Parses param values from parsed command arguments into their typed\n * representations.\n */\nconst parseParams = /*#__PURE__*/Effect.fnUntraced(function* (parsedArgs, params) {\n const results = [];\n let currentArguments = parsedArgs.arguments;\n for (const option of params) {\n const [remainingArguments, parsed] = yield* option.parse({\n flags: parsedArgs.flags,\n arguments: currentArguments\n });\n results.push(parsed);\n currentArguments = remainingArguments;\n }\n return [currentArguments, results];\n});\n/**\n * Checks that inherited parent context flags do not reuse names declared by\n * child command flags.\n *\n * When `contextConfig` is supplied, it is used as the inherited flag set;\n * otherwise the parent's current context config is checked.\n */\nexport const checkForDuplicateFlags = (parent, subcommands, options) => {\n const parentImpl = toImpl(parent);\n const parentOptionNames = new Set();\n const extractNames = flags => {\n for (const option of flags) {\n const singles = Param.extractSingleParams(option);\n for (const single of singles) {\n parentOptionNames.add(single.name);\n }\n }\n };\n extractNames((options?.contextConfig ?? parentImpl.contextConfig).flags);\n for (const subcommand of subcommands) {\n const subImpl = toImpl(subcommand);\n for (const option of subImpl.config.flags) {\n const singles = Param.extractSingleParams(option);\n for (const single of singles) {\n if (parentOptionNames.has(single.name)) {\n throw new CliError.DuplicateOption({\n option: single.name,\n parentCommand: parent.name,\n childCommand: subcommand.name\n });\n }\n }\n }\n }\n};\n//# sourceMappingURL=command.js.map","/**\n * CommandDescriptor — pure-data representation of a command tree for\n * shell completion generation.\n *\n * @internal\n */\nimport * as Option from \"../../../Option.js\";\nimport * as Param from \"../../Param.js\";\nimport * as Primitive from \"../../Primitive.js\";\nimport { toImpl } from \"../command.js\";\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\nconst toFlagType = single => {\n const tag = single.primitiveType._tag;\n switch (tag) {\n case \"Boolean\":\n return {\n _tag: \"Boolean\"\n };\n case \"Int\":\n return {\n _tag: \"Int\"\n };\n case \"Finite\":\n return {\n _tag: \"Finite\"\n };\n case \"Date\":\n return {\n _tag: \"Date\"\n };\n case \"Choice\":\n {\n const keys = Primitive.getChoiceKeys(single.primitiveType);\n return {\n _tag: \"Choice\",\n values: keys ?? []\n };\n }\n case \"Path\":\n return {\n _tag: \"Path\",\n pathType: Primitive.getPathType(single.primitiveType) ?? \"either\"\n };\n case \"FileText\":\n case \"FileParse\":\n case \"FileSchema\":\n return {\n _tag: \"Path\",\n pathType: \"file\"\n };\n default:\n return {\n _tag: \"String\"\n };\n }\n};\nconst toArgumentType = single => {\n const tag = single.primitiveType._tag;\n switch (tag) {\n case \"Int\":\n return {\n _tag: \"Int\"\n };\n case \"Finite\":\n return {\n _tag: \"Finite\"\n };\n case \"Date\":\n return {\n _tag: \"Date\"\n };\n case \"Choice\":\n {\n const keys = Primitive.getChoiceKeys(single.primitiveType);\n return {\n _tag: \"Choice\",\n values: keys ?? []\n };\n }\n case \"Path\":\n return {\n _tag: \"Path\",\n pathType: Primitive.getPathType(single.primitiveType) ?? \"either\"\n };\n case \"FileText\":\n case \"FileParse\":\n case \"FileSchema\":\n return {\n _tag: \"Path\",\n pathType: \"file\"\n };\n default:\n return {\n _tag: \"String\"\n };\n }\n};\n// ---------------------------------------------------------------------------\n// Extraction\n// ---------------------------------------------------------------------------\n/**\n * @internal\n */\nexport const fromCommand = (cmd, inheritedFlags = []) => {\n const impl = toImpl(cmd);\n const config = impl.config;\n const flags = [];\n const seen = new Set();\n // Match help's precedence: local flags first, then ancestors root to leaf.\n for (const [index, flag] of [...config.flags, ...inheritedFlags].entries()) {\n const singles = Param.extractSingleParams(flag);\n for (const single of singles) {\n if (single.kind !== \"flag\") continue;\n // Omit hidden flags from completion scripts so tab-completion in the\n // shell does not advertise flags that are absent from --help.\n if (single.hidden) continue;\n if (index >= config.flags.length && seen.has(single.name)) continue;\n seen.add(single.name);\n flags.push({\n name: single.name,\n aliases: single.aliases,\n description: Option.getOrUndefined(single.description),\n type: toFlagType(single),\n optionalValue: single.optionalValue !== undefined\n });\n }\n }\n const args = [];\n for (const arg of config.arguments) {\n const singles = Param.extractSingleParams(arg);\n const metadata = Param.getParamMetadata(arg);\n for (const single of singles) {\n if (single.kind !== \"argument\") continue;\n args.push({\n name: single.name,\n description: Option.getOrUndefined(single.description),\n required: !metadata.isOptional,\n variadic: metadata.isVariadic,\n type: toArgumentType(single)\n });\n }\n }\n const subcommands = [];\n const sharedFlags = [...inheritedFlags, ...impl.contextConfig.flags];\n for (const group of cmd.subcommands) {\n for (const subcommand of group.commands) {\n // Omit unlisted subcommands from completion scripts so tab-completion in\n // the shell does not advertise commands that are absent from --help.\n if (subcommand.unlisted) continue;\n const descriptor = fromCommand(subcommand, sharedFlags);\n subcommands.push(descriptor);\n if (subcommand.alias && subcommand.alias !== subcommand.name) {\n subcommands.push({\n ...descriptor,\n name: subcommand.alias\n });\n }\n }\n }\n return {\n name: cmd.name,\n description: cmd.shortDescription ?? cmd.description,\n flags,\n arguments: args,\n subcommands\n };\n};\n/**\n * Whether the flag reads its value from the next word.\n *\n * @internal\n */\nexport const takesSeparateValue = flag => flag.type._tag !== \"Boolean\" && flag.optionalValue !== true;\n//# sourceMappingURL=descriptor.js.map","import { takesSeparateValue } from \"./descriptor.js\";\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\nconst escapeForBash = s => s.replace(/'/g, \"'\\\\''\");\nconst sanitizeFunctionName = s => s.replace(/[^a-zA-Z0-9_]/g, \"_\");\nconst flagNamesForWordlist = flag => {\n const names = [`--${flag.name}`];\n for (const alias of flag.aliases) {\n names.push(alias.length === 1 ? `-${alias}` : `--${alias}`);\n }\n if (flag.type._tag === \"Boolean\") {\n names.push(`--no-${flag.name}`);\n }\n return names;\n};\n/** Emit a Bash 3.2-compatible used-flag filter. */\nconst buildFlagGroupDeclarations = (flags, lines) => {\n if (flags.length === 0) return;\n const groups = flags.map(flagNamesForWordlist);\n lines.push(` local ${groups.map((_, index) => `_used_${index}=\"\"`).join(\" \")}`);\n lines.push(` for ((i = 1; i < cword; i++)); do`);\n lines.push(` case \"\\${words[i]%%=*}\" in`);\n groups.forEach((forms, index) => {\n lines.push(` ${forms.join(\"|\")}) _used_${index}=1 ;;`);\n });\n lines.push(` esac`);\n lines.push(` done`);\n lines.push(` local _filtered_flags=\"\"`);\n groups.forEach((forms, index) => {\n lines.push(` [[ -n \"$_used_${index}\" ]] || _filtered_flags+=\" ${forms.join(\" \")}\"`);\n });\n lines.push(``);\n};\n/**\n * Complete choices without `compgen -W`, which reparses quoted values. Escape\n * only the portion readline replaces for the active quote context.\n *\n * `!` cannot be escaped inside a user-opened double quote without changing the\n * resulting argument.\n */\nconst choicesHelper = (helperName, lines) => {\n lines.push(`${helperName}()`);\n lines.push(`{`);\n lines.push(` local _cur=\"$1\" _word=\"$2\"; shift 2`);\n lines.push(``);\n lines.push(` local _head=\"\\${_cur%\"$_word\"}\"`);\n lines.push(` local _open=\"\"`);\n lines.push(` case \"$_head\" in`);\n lines.push(` *\\\\') _open=\"'\" ;;`);\n lines.push(` *\\\\\") _open='\"' ;;`);\n lines.push(` esac`);\n lines.push(``);\n lines.push(` local _prefix=\"$_cur\" _committed=\"$_head\"`);\n // Quoting these substitutions breaks quote matching on Bash 3.2.\n lines.push(` _prefix=\\${_prefix//\\\\\\\\/}; _prefix=\\${_prefix//\\\\\"/}; _prefix=\\${_prefix//\\\\'/}`);\n lines.push(` _committed=\\${_committed//\\\\\\\\/}; _committed=\\${_committed//\\\\\"/}; _committed=\\${_committed//\\\\'/}`);\n lines.push(``);\n lines.push(` COMPREPLY=()`);\n lines.push(` local _choice _rest _match`);\n lines.push(` for _choice in \"$@\"; do`);\n lines.push(` [[ \"$_choice\" == \"$_prefix\"* ]] || continue`);\n lines.push(` _rest=\"\\${_choice#\"$_committed\"}\"`);\n lines.push(` case \"$_open\" in`);\n lines.push(` \"'\")`);\n lines.push(` if [[ \"$_head\" == \"'\" ]]; then`);\n // Use a shell splice for a quote opened at the start of the word.\n lines.push(` _match=\\${_rest//\\\\'/\\\\'\\\\\\\\\\\\'\\\\'}`);\n lines.push(` else`);\n // A mid-word single-quote context cannot contain another single quote.\n lines.push(` [[ \"$_rest\" == *\\\\'* ]] && continue`);\n lines.push(` _match=\"$_rest\"`);\n lines.push(` fi`);\n lines.push(` ;;`);\n lines.push(` '\"')`);\n lines.push(` _match=\"\\${_rest//\\\\\\\\/\\\\\\\\\\\\\\\\}\"`);\n lines.push(` _match=\"\\${_match//\\\\$/\\\\\\\\$}\"`);\n lines.push(\" _match=\\\"${_match//\\\\`/\\\\\\\\\\\\`}\\\"\");\n lines.push(` _match=\"\\${_match//\\\\\"/\\\\\\\\\\\\\"}\"`);\n lines.push(` ;;`);\n lines.push(` *)`);\n lines.push(` printf -v _match '%q' \"$_rest\"`);\n // Bash 3.2 leaves a leading tilde unescaped.\n lines.push(` [[ -z \"$_head\" && \"$_match\" == '~'* ]] && _match=\"\\\\\\\\$_match\"`);\n lines.push(` ;;`);\n lines.push(` esac`);\n // Readline omits a closing quote already present in the match.\n lines.push(` [[ -n \"$_open\" && \"$_match\" == *\"$_open\" ]] && _match+=\"$_open\"`);\n lines.push(` COMPREPLY+=(\"$_match\")`);\n lines.push(` done`);\n lines.push(`}`);\n lines.push(``);\n};\nconst choiceCompletion = (helperName, values) => `${helperName} \"$cur\" \"$_comp_word\" ${values.map(value => `'${escapeForBash(value)}'`).join(\" \")}`;\nconst flagValueCompletion = (type, helperName) => {\n switch (type._tag) {\n case \"Boolean\":\n return undefined;\n case \"Choice\":\n return choiceCompletion(helperName, type.values);\n case \"Path\":\n if (type.pathType === \"directory\") return `COMPREPLY=( $(compgen -d -- \"$cur\") )`;\n return `COMPREPLY=( $(compgen -f -- \"$cur\") )`;\n default:\n return undefined;\n }\n};\nconst argCompletion = (type, helperName) => {\n switch (type._tag) {\n case \"Choice\":\n return choiceCompletion(helperName, type.values);\n case \"Path\":\n if (type.pathType === \"directory\") return `COMPREPLY=( $(compgen -d -- \"$cur\") )`;\n return `COMPREPLY=( $(compgen -f -- \"$cur\") )`;\n default:\n return undefined;\n }\n};\n// ---------------------------------------------------------------------------\n// Generator\n// ---------------------------------------------------------------------------\nconst generateFunction = (descriptor, parentPath, lines, helperName) => {\n const currentPath = [...parentPath, descriptor.name];\n const funcName = `_${currentPath.map(sanitizeFunctionName).join(\"_\")}`;\n lines.push(`${funcName}()`);\n lines.push(`{`);\n lines.push(` local cur prev words cword i`);\n lines.push(parentPath.length === 0 ? ` local _command_index=0` : ` local _command_index=\"$1\"`);\n // Keep values containing COMP_WORDBREAKS characters in one word.\n lines.push(` _init_completion -n \"$COMP_WORDBREAKS\" || return`);\n if (parentPath.length === 0) {\n // Subcommand functions inherit this through Bash's dynamic scope.\n lines.push(` local _comp_word=\"$2\"`);\n }\n lines.push(``);\n // Build flag-value dispatch\n const flagsWithValues = descriptor.flags.filter(takesSeparateValue);\n if (flagsWithValues.length > 0) {\n lines.push(` # Flag value completions`);\n lines.push(` case \"$prev\" in`);\n for (const flag of flagsWithValues) {\n const longNames = [`--${flag.name}`];\n for (const alias of flag.aliases) {\n longNames.push(alias.length === 1 ? `-${alias}` : `--${alias}`);\n }\n const completion = flagValueCompletion(flag.type, helperName);\n if (completion) {\n lines.push(` ${longNames.join(\"|\")})`);\n lines.push(` ${completion}`);\n lines.push(` return`);\n lines.push(` ;;`);\n }\n }\n lines.push(` esac`);\n lines.push(``);\n }\n // Subcommand dispatch\n if (descriptor.subcommands.length > 0) {\n lines.push(` # Subcommand dispatch`);\n lines.push(` local cmd _skip_next=0`);\n lines.push(` for ((i = _command_index + 1; i < cword; i++)); do`);\n lines.push(` if (( _skip_next )); then`);\n lines.push(` _skip_next=0`);\n lines.push(` continue`);\n lines.push(` fi`);\n lines.push(` case \"\\${words[i]}\" in`);\n for (const flag of descriptor.flags) {\n if (!takesSeparateValue(flag)) continue;\n const forms = flagNamesForWordlist(flag);\n lines.push(` ${forms.join(\"|\")}) _skip_next=1 ;;`);\n lines.push(` ${forms.map(form => `${form}=*`).join(\"|\")}) ;;`);\n }\n for (const sub of descriptor.subcommands) {\n const subFuncName = `_${[...currentPath, sub.name].map(sanitizeFunctionName).join(\"_\")}`;\n lines.push(` ${sub.name})`);\n lines.push(` ${subFuncName} \"$i\"`);\n lines.push(` return`);\n lines.push(` ;;`);\n }\n lines.push(` esac`);\n lines.push(` done`);\n lines.push(``);\n }\n // Filter already-used flags (entire alias group removed when any form is used)\n buildFlagGroupDeclarations(descriptor.flags, lines);\n if (descriptor.flags.length > 0 || descriptor.subcommands.length > 0) {\n lines.push(` # Complete flags (filtered) and subcommands`);\n lines.push(` if [[ \"$cur\" == -* ]]; then`);\n if (descriptor.flags.length > 0) {\n lines.push(` COMPREPLY=( $(compgen -W \"$_filtered_flags\" -- \"$cur\") )`);\n }\n lines.push(` return`);\n lines.push(` fi`);\n lines.push(``);\n }\n // Positional argument completion\n const argsWithCompletions = descriptor.arguments.flatMap((argument, index) => {\n const completion = argCompletion(argument.type, helperName);\n return completion === undefined ? [] : [{\n argument,\n completion,\n index\n }];\n });\n if (argsWithCompletions.length > 0) {\n lines.push(` # Positional argument completions`);\n lines.push(` local _position=0 _skip_next=0 _end_of_options=0`);\n lines.push(` for ((i = _command_index + 1; i < cword; i++)); do`);\n lines.push(` if (( _skip_next )); then`);\n lines.push(` _skip_next=0`);\n lines.push(` continue`);\n lines.push(` fi`);\n lines.push(` if (( _end_of_options )); then`);\n lines.push(` ((_position += 1))`);\n lines.push(` continue`);\n lines.push(` fi`);\n lines.push(` case \"\\${words[i]}\" in`);\n lines.push(` --) _end_of_options=1 ;;`);\n for (const flag of descriptor.flags) {\n const forms = flagNamesForWordlist(flag);\n if (!takesSeparateValue(flag)) {\n lines.push(` ${forms.join(\"|\")}) ;;`);\n } else {\n lines.push(` ${forms.join(\"|\")}) _skip_next=1 ;;`);\n lines.push(` ${forms.map(form => `${form}=*`).join(\"|\")}) ;;`);\n }\n }\n lines.push(` -*) ;;`);\n lines.push(` *) ((_position += 1)) ;;`);\n lines.push(` esac`);\n lines.push(` done`);\n lines.push(` case \"$_position\" in`);\n for (const {\n argument,\n completion,\n index\n } of argsWithCompletions) {\n if (argument.variadic) continue;\n lines.push(` ${index})`);\n lines.push(` ${completion}`);\n lines.push(` return`);\n lines.push(` ;;`);\n }\n lines.push(` esac`);\n const variadic = argsWithCompletions.find(({\n argument\n }) => argument.variadic);\n if (variadic !== undefined) {\n lines.push(` if (( _position >= ${variadic.index} )); then`);\n lines.push(` ${variadic.completion}`);\n lines.push(` return`);\n lines.push(` fi`);\n }\n } else if (descriptor.subcommands.length > 0) {\n const subNames = descriptor.subcommands.map(s => s.name);\n lines.push(` COMPREPLY=( $(compgen -W '${subNames.join(\" \")}' -- \"$cur\") )`);\n }\n lines.push(`}`);\n lines.push(``);\n // Recurse into subcommands\n for (const sub of descriptor.subcommands) {\n generateFunction(sub, currentPath, lines, helperName);\n }\n};\n/**\n * @internal\n */\nexport const generate = (executableName, descriptor) => {\n const lines = [];\n const safeName = sanitizeFunctionName(executableName);\n // Sanitized command names cannot contain `-`.\n const helperName = `_${safeName}--choices`;\n lines.push(`###-begin-${escapeForBash(executableName)}-completions-###`);\n lines.push(`#`);\n lines.push(`# Static completion script for Bash`);\n lines.push(`#`);\n lines.push(`# Installation:`);\n lines.push(`# ${escapeForBash(executableName)} --completions bash >> ~/.bashrc`);\n lines.push(`#`);\n lines.push(``);\n // Fallback for environments without bash-completion. Preserve word-break\n // characters inside values.\n lines.push(`if ! type _init_completion &>/dev/null; then`);\n lines.push(` _init_completion()`);\n lines.push(` {`);\n lines.push(` COMPREPLY=()`);\n lines.push(` local _i _j=0 _piece _line=\"$COMP_LINE\"`);\n lines.push(` words=(\"\\${COMP_WORDS[0]}\")`);\n lines.push(` cword=0`);\n lines.push(` _line=\"\\${_line#*\"\\${COMP_WORDS[0]}\"}\"`);\n lines.push(` for ((_i = 1; _i < \\${#COMP_WORDS[@]}; _i++)); do`);\n lines.push(` _piece=\"\\${COMP_WORDS[_i]}\"`);\n lines.push(` if [[ \"$_line\" == [[:blank:]]* ]]; then`);\n lines.push(` ((_j++))`);\n lines.push(` words[_j]=\"$_piece\"`);\n lines.push(` else`);\n lines.push(` words[_j]=\"\\${words[_j]}$_piece\"`);\n lines.push(` fi`);\n lines.push(` ((_i == COMP_CWORD)) && cword=$_j`);\n lines.push(` _line=\"\\${_line#*\"$_piece\"}\"`);\n lines.push(` done`);\n lines.push(` cur=\"\\${words[cword]}\"`);\n lines.push(` prev=\"\"`);\n lines.push(` ((cword > 0)) && prev=\"\\${words[cword-1]}\"`);\n lines.push(` return 0`);\n lines.push(` }`);\n lines.push(`fi`);\n lines.push(``);\n choicesHelper(helperName, lines);\n generateFunction(descriptor, [], lines, helperName);\n lines.push(`complete -F _${safeName} ${escapeForBash(executableName)}`);\n lines.push(`###-end-${escapeForBash(executableName)}-completions-###`);\n return lines.join(\"\\n\");\n};\n//# sourceMappingURL=bash.js.map","import { takesSeparateValue } from \"./descriptor.js\";\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\nconst escapeFishString = s => s.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\");\n/** Escape choices for Fish's second expansion of `complete -a`. */\nconst escapeFishChoice = s => escapeFishString(s.replace(/[^A-Za-z0-9_.,/@%+-]/gu, \"\\\\$&\"));\n/**\n * Build a Fish condition that checks the current subcommand context.\n *\n * For root-level completions with subcommands: `__fish_use_subcommand`\n * For nested commands: verify the full parent path is active AND none of its\n * child subcommands have been entered yet.\n */\nconst subcommandCondition = (parentPath, childSubcommandNames) => {\n if (parentPath.length === 0) {\n if (childSubcommandNames.length > 0) {\n return `__fish_use_subcommand`;\n }\n return ``;\n }\n const parentCondition = parentPath.map(parent => `__fish_seen_subcommand_from ${parent}`).join(\"; and \");\n if (childSubcommandNames.length > 0) {\n // Show only when the parent path is active but no child subcommand has been entered\n return `${parentCondition}; and not __fish_seen_subcommand_from ${childSubcommandNames.join(\" \")}`;\n }\n return parentCondition;\n};\n/**\n * Build a __fish_contains_opt condition that checks whether any form of this\n * flag has already been typed. Returns the condition string without wrapping\n * quotes (the caller adds those).\n */\nconst flagContainsOptCondition = flag => {\n const optArgs = [];\n for (const alias of flag.aliases) {\n if (alias.length === 1) {\n optArgs.push(`-s ${alias}`);\n }\n }\n // Long names (fish __fish_contains_opt uses bare words for long opts)\n optArgs.push(flag.name);\n for (const alias of flag.aliases) {\n if (alias.length > 1) {\n optArgs.push(alias);\n }\n }\n if (flag.type._tag === \"Boolean\") {\n optArgs.push(`no-${flag.name}`);\n }\n return `not __fish_contains_opt ${optArgs.join(\" \")}`;\n};\n/** Hide used value flags without suppressing their value completions. */\nconst valueFlagDedupCondition = flag => {\n const forms = [`--${flag.name}`];\n for (const alias of flag.aliases) {\n forms.push(alias.length === 1 ? `-${alias}` : `--${alias}`);\n }\n return `begin; ${flagContainsOptCondition(flag)}; or contains -- (commandline -poc)[-1] ${forms.join(\" \")}; end`;\n};\nconst flagCompletionArgs = flag => {\n const args = [`-l ${flag.name}`];\n for (const alias of flag.aliases) {\n if (alias.length === 1) {\n args.push(`-s ${alias}`);\n } else {\n args.push(`-l ${alias}`);\n }\n }\n if (flag.description) {\n args.push(`-d '${escapeFishString(flag.description)}'`);\n }\n const valueArgs = takesSeparateValue(flag) ? flagValueArgs(flag.type) : undefined;\n if (valueArgs) {\n args.push(valueArgs);\n }\n return args;\n};\nconst flagValueArgs = type => {\n switch (type._tag) {\n case \"Boolean\":\n return undefined;\n case \"Choice\":\n return `-r -f -a '${type.values.map(escapeFishChoice).join(\" \")}'`;\n case \"Path\":\n if (type.pathType === \"directory\") return `-r -F`;\n return `-r -F`;\n default:\n // -r: requires a value, -f: don't fall back to file completion\n return `-r -f`;\n }\n};\nconst argValueArgs = type => {\n switch (type._tag) {\n case \"Choice\":\n return `-r -f -a '${type.values.map(escapeFishChoice).join(\" \")}'`;\n case \"Path\":\n return `-r -F`;\n default:\n return undefined;\n }\n};\n// ---------------------------------------------------------------------------\n// Generator\n// ---------------------------------------------------------------------------\nconst generateCompletions = (executableName, descriptor, parentPath, lines) => {\n const allSubNames = descriptor.subcommands.map(s => s.name);\n const condition = subcommandCondition(parentPath, allSubNames);\n const conditionArg = condition ? `-n '${condition}'` : ``;\n // Suppress default file completion unless the command has path-type\n // positional arguments. Without this, fish falls back to listing files\n // even when only flags are valid.\n const hasPathArgs = descriptor.arguments.some(a => a.type._tag === \"Path\");\n if (!hasPathArgs) {\n const parts = [`complete -c ${executableName}`];\n if (conditionArg) parts.push(conditionArg);\n parts.push(`-f`);\n lines.push(parts.join(\" \"));\n }\n // Subcommand completions\n for (const sub of descriptor.subcommands) {\n const parts = [`complete -c ${executableName}`];\n if (conditionArg) parts.push(conditionArg);\n parts.push(`-f -a '${escapeFishString(sub.name)}'`);\n if (sub.description) {\n parts.push(`-d '${escapeFishString(sub.description)}'`);\n }\n lines.push(parts.join(\" \"));\n }\n // Flag completions\n for (const flag of descriptor.flags) {\n const dedup = takesSeparateValue(flag) ? valueFlagDedupCondition(flag) : flagContainsOptCondition(flag);\n const flagCondition = condition ? `${condition}; and ${dedup}` : dedup;\n const flagCondArg = flagCondition ? `-n '${flagCondition}'` : ``;\n const parts = [`complete -c ${executableName}`];\n if (flagCondArg) parts.push(flagCondArg);\n parts.push(...flagCompletionArgs(flag));\n lines.push(parts.join(\" \"));\n // Boolean negation\n if (flag.type._tag === \"Boolean\") {\n const negParts = [`complete -c ${executableName}`];\n if (flagCondArg) negParts.push(flagCondArg);\n negParts.push(`-l no-${flag.name}`);\n if (flag.description) {\n negParts.push(`-d '${escapeFishString(`Disable ${flag.name}`)}'`);\n }\n lines.push(negParts.join(\" \"));\n }\n }\n // Flags as -a entries for bare <TAB> visibility.\n // Fish only shows -l/-s entries when the current word starts with -, so\n // without this, flags are invisible on bare <TAB>. Guarded to only show\n // when NOT already typing an option (avoids duplication with -l/-s above)\n // and hidden once a flag has been used (__fish_contains_opt).\n if (descriptor.flags.length > 0) {\n const notDash = `not string match -q -- \"-*\" (commandline -ct)`;\n const bareBase = condition ? `${condition}; and ${notDash}` : notDash;\n for (const flag of descriptor.flags) {\n const bareCondition = `${bareBase}; and ${flagContainsOptCondition(flag)}`;\n const isBoolean = flag.type._tag === \"Boolean\";\n const parts = [`complete -c ${executableName}`];\n parts.push(`-n '${bareCondition}'`);\n parts.push(`-f -a '--${flag.name}'`);\n if (flag.description) {\n parts.push(`-d '${escapeFishString(flag.description)}'`);\n }\n lines.push(parts.join(\" \"));\n if (isBoolean) {\n const negParts = [`complete -c ${executableName}`];\n negParts.push(`-n '${bareCondition}'`);\n negParts.push(`-f -a '--no-${flag.name}'`);\n if (flag.description) {\n negParts.push(`-d '${escapeFishString(`Disable ${flag.name}`)}'`);\n }\n lines.push(negParts.join(\" \"));\n }\n }\n }\n // Argument completions (type hints only)\n for (const arg of descriptor.arguments) {\n const valueArg = argValueArgs(arg.type);\n if (valueArg) {\n const parts = [`complete -c ${executableName}`];\n if (conditionArg) parts.push(conditionArg);\n parts.push(valueArg);\n if (arg.description) {\n parts.push(`-d '${escapeFishString(arg.description)}'`);\n }\n lines.push(parts.join(\" \"));\n }\n }\n // Recurse into subcommands\n for (const sub of descriptor.subcommands) {\n generateCompletions(executableName, sub, [...parentPath, sub.name], lines);\n }\n};\n/**\n * @internal\n */\nexport const generate = (executableName, descriptor) => {\n const lines = [];\n lines.push(`###-begin-${executableName}-completions-###`);\n lines.push(`#`);\n lines.push(`# Static completion script for Fish`);\n lines.push(`#`);\n lines.push(`# Installation:`);\n lines.push(`# ${executableName} --completions fish > ~/.config/fish/completions/${executableName}.fish`);\n lines.push(`#`);\n lines.push(``);\n generateCompletions(executableName, descriptor, [], lines);\n lines.push(``);\n lines.push(`###-end-${executableName}-completions-###`);\n return lines.join(\"\\n\");\n};\n//# sourceMappingURL=fish.js.map","/**\n * Encode non-ASCII and control characters as `[char]` code units. Windows\n * PowerShell 5.1 can misread BOM-less UTF-8 as ANSI, turning some bytes into\n * PowerShell quote delimiters.\n */\nconst quotePs = s => {\n const parts = [];\n let literal = \"\";\n for (let i = 0; i < s.length; i++) {\n const code = s.charCodeAt(i);\n if (code >= 0x20 && code < 0x80) {\n literal += s[i] === \"'\" ? \"''\" : s[i];\n continue;\n }\n if (literal !== \"\" || parts.length === 0) parts.push(`'${literal}'`);\n literal = \"\";\n parts.push(`[char]0x${code.toString(16).toUpperCase().padStart(4, \"0\")}`);\n }\n if (literal !== \"\" || parts.length === 0) parts.push(`'${literal}'`);\n return parts.length === 1 ? parts[0] : `(${parts.join(\" + \")})`;\n};\nconst psArray = items => `@(${items.map(quotePs).join(\", \")})`;\nconst psOptional = s => s ? quotePs(s) : \"$null\";\nconst sanitize = s => s.replace(/[^a-zA-Z0-9_]/g, \"_\");\nconst flagForms = flag => [`--${flag.name}`, ...flag.aliases.map(alias => alias.length === 1 ? `-${alias}` : `--${alias}`)];\nconst valueFields = type => `values = ${psArray(type._tag === \"Choice\" ? type.values : [])}; ` + `pathType = ${type._tag === \"Path\" ? quotePs(type.pathType) : \"$null\"}`;\nconst flagEntry = flag => `@{ name = ${quotePs(flag.name)}; forms = ${psArray(flagForms(flag))}; ` + `takesValue = $${flag.type._tag !== \"Boolean\"}; ` + (flag.optionalValue === true ? `optionalValue = $true; ` : \"\") + `${valueFields(flag.type)}; ` + `description = ${psOptional(flag.description)} }`;\nconst argumentEntry = argument => `@{ name = ${quotePs(argument.name)}; variadic = $${argument.variadic}; ${valueFields(argument.type)}; ` + `description = ${psOptional(argument.description)} }`;\nconst pushList = (lines, field, entries) => {\n if (entries.length === 0) {\n lines.push(` ${field} = @()`);\n return;\n }\n lines.push(` ${field} = @(`);\n for (const entry of entries) {\n lines.push(` ${entry}`);\n }\n lines.push(` )`);\n};\n/**\n * Emit one context per subcommand path. Subcommands are case-sensitive, so\n * contexts go in an ordinal hashtable instead of a hash literal, whose keys\n * ignore case.\n */\nconst generateContexts = (dataName, descriptor, path, lines, seen) => {\n const key = path.join(\" \");\n if (seen.has(key)) return;\n seen.add(key);\n lines.push(`${dataName}[${quotePs(key)}] = @{`);\n pushList(lines, \"subcommands\", descriptor.subcommands.map(sub => `@{ name = ${quotePs(sub.name)}; description = ${psOptional(sub.description)} }`));\n pushList(lines, \"flags\", descriptor.flags.map(flagEntry));\n pushList(lines, \"arguments\", descriptor.arguments.map(argumentEntry));\n lines.push(`}`);\n for (const sub of descriptor.subcommands) {\n generateContexts(dataName, sub, [...path, sub.name], lines, seen);\n }\n};\n/**\n * Replay the committed words with the CLI lexer and parser rules: `--`, short\n * flag clusters, inline values, boolean literals, negative numbers, and\n * subcommand selection by the first value only.\n */\nconst completer = dataName => String.raw` param($wordToComplete, $commandAst, $cursorPosition)\n\n $spec = ${dataName}\n $results = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new()\n $booleanLiterals = @('true', 'yes', 'on', '1', 'y', 'false', 'no', 'off', '0', 'n')\n\n $index = {\n param($context)\n $lookup = [hashtable]::new([System.StringComparer]::Ordinal)\n foreach ($flag in $context.flags) {\n foreach ($form in $flag.forms) { $lookup[$form] = $flag }\n }\n $lookup\n }\n\n $add = {\n param([string]$value, [string]$type, $tooltip, [string]$typed, [string]$textPrefix)\n if (-not $value.StartsWith($typed, [System.StringComparison]::OrdinalIgnoreCase)) { return }\n $text = $value\n if ($value -notmatch '^[\\w./:%+=\\\\-]+$') { $text = \"'\" + ($value -replace \"['\\u2018-\\u201b]\", '$0$0') + \"'\" }\n $text = $textPrefix + $text\n $label = $value\n if (-not $label) { $label = $text }\n if (-not $tooltip) { $tooltip = $label }\n $results.Add([System.Management.Automation.CompletionResult]::new($text, $label, $type, $tooltip))\n }\n\n $addValues = {\n param($entry, [string]$typed, [string]$textPrefix)\n foreach ($value in $entry.values) {\n if ($textPrefix -eq '' -and (& $optionLike $value)) { continue }\n & $add $value 'ParameterValue' $entry.description $typed $textPrefix\n }\n if ($entry.pathType) {\n foreach ($file in [System.Management.Automation.CompletionCompleters]::CompleteFilename($typed)) {\n if ($entry.pathType -eq 'directory' -and $file.ResultType -ne 'ProviderContainer') { continue }\n $results.Add([System.Management.Automation.CompletionResult]::new($textPrefix + $file.CompletionText, $file.ListItemText, $file.ResultType, $file.ToolTip))\n }\n }\n }\n\n $addFlags = {\n param([string]$typed)\n foreach ($flag in $context.flags) {\n if ($used.ContainsKey($flag.name)) { continue }\n foreach ($form in $flag.forms) {\n & $add $form 'ParameterName' $flag.description $typed ''\n }\n if (-not $flag.takesValue) {\n $tooltip = $null\n if ($flag.description) { $tooltip = 'Disable ' + $flag.name }\n & $add ('--no-' + $flag.name) 'ParameterName' $tooltip $typed ''\n }\n }\n }\n\n # As in the CLI lexer, nothing after '--' is an option, and negative numbers\n # and a lone '-' are values.\n $optionLike = {\n param([string]$word)\n -not $endOfOptions -and $word -match '^-.' -and $word -notmatch '^-(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$'\n }\n\n # A typed value that has no candidates completes to itself, so the engine\n # does not fall back to listing files.\n $keepTyped = {\n if ($results.Count -eq 0 -and $current) {\n $results.Add([System.Management.Automation.CompletionResult]::new($current, $current, 'ParameterValue', $current))\n }\n }\n\n $path = ''\n $context = $spec[$path]\n $lookup = & $index $context\n $used = [hashtable]::new([System.StringComparer]::Ordinal)\n $pending = $null\n $endOfOptions = $false\n $position = 0\n\n # The engine strips the quotes from a quoted word.\n $typed = [string]$wordToComplete\n if ($typed -match '^([''\"])(.*?)\\1?$') { $typed = $Matches[2] }\n $current = $null\n\n $elements = $commandAst.CommandElements\n for ($i = 1; $i -lt $elements.Count; $i++) {\n $element = $elements[$i]\n $word = $element.Extent.Text\n if ($element -is [System.Management.Automation.Language.StringConstantExpressionAst]) { $word = $element.Value }\n if ($element.Extent.EndOffset -ge $cursorPosition) {\n if ($element -is [System.Management.Automation.Language.ConstantExpressionAst] -and $element.Extent.StartOffset -le $cursorPosition) {\n $current = $element.Extent.Text\n if ($element.Extent.EndOffset -eq $cursorPosition) { $typed = $word }\n }\n break\n }\n\n # A flag takes the next word as its value unless it is an option or '--';\n # a boolean flag only takes a boolean literal.\n $isOption = & $optionLike $word\n if ($null -ne $pending) {\n $flag = $pending\n $pending = $null\n if ($flag.takesValue) {\n if (-not $isOption) { continue }\n } elseif ($booleanLiterals -ccontains $word) { continue }\n }\n if ($endOfOptions) { $position++; continue }\n if ($word -ceq '--') { $endOfOptions = $true; continue }\n\n if ($isOption) {\n $hasValue = $word.Contains('=')\n if ($hasValue) {\n $forms = @($word.Substring(0, $word.IndexOf('=')))\n } elseif ($word.StartsWith('--')) {\n $forms = @($word)\n } else {\n $forms = @(foreach ($char in $word.Substring(1).ToCharArray()) { '-' + $char })\n }\n foreach ($form in $forms) {\n $pending = $null\n $flag = $lookup[$form]\n if ($null -eq $flag) {\n if ($form.StartsWith('--no-')) {\n $name = $form.Substring(5)\n $flag = $lookup['--' + $name]\n if ($null -ne $flag -and -not $flag.takesValue -and $flag.name -ceq $name) { $used[$name] = $true }\n }\n continue\n }\n $used[$flag.name] = $true\n # A flag with an optional value only takes a value attached with '='.\n if (-not $hasValue -and -not $flag.optionalValue) { $pending = $flag }\n }\n continue\n }\n\n if ($position -eq 0 -and $context.subcommands.name -ccontains $word) {\n if ($path) { $path = $path + ' ' + $word } else { $path = $word }\n $context = $spec[$path]\n $lookup = & $index $context\n $used = [hashtable]::new([System.StringComparer]::Ordinal)\n continue\n }\n $position++\n }\n\n $typedIsOption = & $optionLike $typed\n if ($null -ne $pending -and $pending.takesValue -and -not $typedIsOption) {\n & $addValues $pending $typed ''\n & $keepTyped\n return $results\n }\n\n if ($typedIsOption) {\n if ($typed -match '^(-[^=]+)=(.*)$') {\n $form = $Matches[1]\n $flag = $lookup[$form]\n if ($null -ne $flag -and $flag.takesValue) {\n & $addValues $flag $Matches[2] ($form + '=')\n & $keepTyped\n }\n } else {\n & $addFlags $typed\n }\n return $results\n }\n\n if (-not $endOfOptions -and $position -eq 0) {\n foreach ($sub in $context.subcommands) {\n & $add $sub.name 'Command' $sub.description $typed ''\n }\n }\n\n $arguments = $context.arguments\n if ($position -lt $arguments.Count) {\n & $addValues $arguments[$position] $typed ''\n } elseif ($arguments.Count -gt 0 -and $arguments[-1].variadic) {\n & $addValues $arguments[-1] $typed ''\n }\n\n if (-not $endOfOptions) {\n & $addFlags $typed\n }\n return $results`;\n/** @internal */\nexport const generate = (executableName, descriptor) => {\n const dataName = `$global:_${sanitize(executableName)}_Completions`;\n const lines = [];\n lines.push(`###-begin-${executableName}-completions-###`);\n lines.push(`#`);\n lines.push(`# Static completion script for PowerShell`);\n lines.push(`#`);\n lines.push(`# Installation:`);\n // `>>` on Windows PowerShell 5.1 appends UTF-16LE to the profile, so the\n // script goes in its own file.\n lines.push(`# ${executableName} --completions powershell > ${executableName}-completion.ps1`);\n lines.push(`# then add this line to your $PROFILE (use the full path to the file):`);\n lines.push(`# . <PATH>\\\\${executableName}-completion.ps1`);\n lines.push(`#`);\n lines.push(``);\n lines.push(`${dataName} = [hashtable]::new([System.StringComparer]::Ordinal)`);\n generateContexts(dataName, descriptor, [], lines, new Set());\n lines.push(``);\n lines.push(`Register-ArgumentCompleter -Native -CommandName ${quotePs(executableName)} -ScriptBlock {`);\n lines.push(completer(dataName));\n lines.push(`}`);\n lines.push(``);\n lines.push(`###-end-${executableName}-completions-###`);\n return lines.join(\"\\n\");\n};\n//# sourceMappingURL=powershell.js.map","// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\nconst escapeZsh = s => s.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"'\\\\''\").replace(/:/g, \"\\\\:\");\nconst escapeZshExplanation = s => escapeZsh(s).replace(/]/g, \"\\\\]\");\n/** Escape choices for the second parse of a Zsh `_arguments` action. */\nconst escapeZshChoice = s => s.replace(/[^A-Za-z0-9_.,/@%+-]/gu, \"\\\\$&\").replace(/'/g, \"'\\\\''\");\nconst sanitize = s => s.replace(/[^a-zA-Z0-9_]/g, \"_\");\n/**\n * All forms of a flag (--name, -alias, --no-name) for the exclusion group.\n */\nconst allForms = flag => {\n const forms = [`--${flag.name}`];\n for (const alias of flag.aliases) {\n forms.push(alias.length === 1 ? `-${alias}` : `--${alias}`);\n }\n if (flag.type._tag === \"Boolean\") {\n forms.push(`--no-${flag.name}`);\n }\n return forms;\n};\nconst valueAction = type => {\n switch (type._tag) {\n case \"Boolean\":\n return \"\";\n case \"Choice\":\n return `:value:(${type.values.map(escapeZshChoice).join(\" \")})`;\n case \"Path\":\n return type.pathType === \"directory\" ? `:directory:_directories` : `:file:_files`;\n case \"Int\":\n return `:integer:`;\n case \"Finite\":\n return `:float:`;\n case \"Date\":\n return `:date:`;\n default:\n return `:value:`;\n }\n};\nconst argAction = type => {\n switch (type._tag) {\n case \"Choice\":\n return `(${type.values.map(escapeZshChoice).join(\" \")})`;\n case \"Path\":\n return type.pathType === \"directory\" ? `_directories` : `_files`;\n default:\n return ``;\n }\n};\n/**\n * Produce _arguments optspecs for a single flag. Each spec is a complete,\n * single-quoted string — no brace expansion, no line continuations.\n */\nconst flagSpecs = flag => {\n const specs = [];\n const desc = flag.description ? `[${escapeZshExplanation(flag.description)}]` : \"\";\n // An optional value must follow `=` in the same word (`--name=-`), and `::`\n // marks it optional.\n const optional = flag.optionalValue === true && flag.type._tag !== \"Boolean\";\n const valueSuffix = optional ? \"=-\" : \"\";\n const action = optional ? `:${valueAction(flag.type)}` : valueAction(flag.type);\n const excl = `(${allForms(flag).join(\" \")})`;\n // Primary long name\n specs.push(`'${excl}--${flag.name}${valueSuffix}${desc}${action}'`);\n // Aliases\n for (const alias of flag.aliases) {\n const prefix = alias.length === 1 ? \"-\" : \"--\";\n specs.push(`'${excl}${prefix}${alias}${valueSuffix}${desc}${action}'`);\n }\n // Boolean negation\n if (flag.type._tag === \"Boolean\") {\n const negDesc = flag.description ? `[${escapeZshExplanation(`Disable ${flag.name}`)}]` : \"\";\n specs.push(`'${excl}--no-${flag.name}${negDesc}'`);\n }\n return specs;\n};\nconst argSpec = arg => {\n const desc = arg.description ? escapeZsh(arg.description) : arg.name;\n const action = argAction(arg.type);\n const prefix = arg.variadic ? \"*\" : \"\";\n return `'${prefix}:${desc}:${action}'`;\n};\n// ---------------------------------------------------------------------------\n// Generator\n// ---------------------------------------------------------------------------\nconst generateFunction = (descriptor, parentPath, lines) => {\n const currentPath = [...parentPath, descriptor.name];\n const funcName = `_${currentPath.map(sanitize).join(\"_\")}`;\n lines.push(`${funcName}() {`);\n if (descriptor.subcommands.length > 0) {\n // _arguments -C requires these locals for the state machine\n lines.push(` local context state state_descr line`);\n lines.push(` typeset -A opt_args`);\n lines.push(``);\n // Subcommand list\n lines.push(` local -a commands`);\n lines.push(` commands=(`);\n for (const sub of descriptor.subcommands) {\n const desc = sub.description ? escapeZsh(sub.description) : \"\";\n lines.push(` '${sub.name}:${desc}'`);\n }\n lines.push(` )`);\n lines.push(``);\n // Build specs array to avoid brace expansion / line continuation issues\n lines.push(` local -a specs`);\n lines.push(` specs=(`);\n for (const flag of descriptor.flags) {\n for (const spec of flagSpecs(flag)) {\n lines.push(` ${spec}`);\n }\n }\n if (descriptor.arguments.length > 0) {\n lines.push(` -`);\n lines.push(` parent-arguments`);\n for (const arg of descriptor.arguments) {\n lines.push(` ${argSpec(arg)}`);\n }\n lines.push(` -`);\n lines.push(` subcommands`);\n }\n lines.push(` '1:command:->command'`);\n lines.push(` '*::arg:->args'`);\n lines.push(` )`);\n lines.push(``);\n lines.push(` _arguments -C \"\\${specs[@]}\"`);\n lines.push(``);\n // State dispatch\n lines.push(` case \"$state\" in`);\n lines.push(` command)`);\n lines.push(` _describe -t commands 'commands' commands`);\n lines.push(` ;;`);\n lines.push(` args)`);\n lines.push(` case \"$words[1]\" in`);\n for (const sub of descriptor.subcommands) {\n const subFunc = `_${[...currentPath, sub.name].map(sanitize).join(\"_\")}`;\n lines.push(` ${sub.name})`);\n lines.push(` ${subFunc}`);\n lines.push(` ;;`);\n }\n lines.push(` esac`);\n lines.push(` ;;`);\n lines.push(` esac`);\n } else {\n // Leaf command — no subcommands\n const allSpecs = [];\n for (const flag of descriptor.flags) {\n allSpecs.push(...flagSpecs(flag));\n }\n for (const arg of descriptor.arguments) {\n allSpecs.push(argSpec(arg));\n }\n if (allSpecs.length > 0) {\n lines.push(` local -a specs`);\n lines.push(` specs=(`);\n for (const spec of allSpecs) {\n lines.push(` ${spec}`);\n }\n lines.push(` )`);\n lines.push(` _arguments \"\\${specs[@]}\"`);\n }\n }\n lines.push(`}`);\n lines.push(``);\n for (const sub of descriptor.subcommands) {\n generateFunction(sub, currentPath, lines);\n }\n};\n/**\n * @internal\n */\nexport const generate = (executableName, descriptor) => {\n const lines = [];\n const safeName = sanitize(executableName);\n lines.push(`#compdef ${executableName}`);\n lines.push(`###-begin-${executableName}-completions-###`);\n lines.push(`#`);\n lines.push(`# Static completion script for Zsh`);\n lines.push(`#`);\n lines.push(`# Installation:`);\n lines.push(`# ${executableName} --completions zsh > ~/.zsh/completions/_${executableName}`);\n lines.push(`# then add ~/.zsh/completions to your fpath`);\n lines.push(`#`);\n lines.push(``);\n generateFunction(descriptor, [], lines);\n lines.push(`# Handle both direct invocation and autoload`);\n lines.push(`if [[ \"\\${zsh_eval_context[-1]}\" == \"loadautofunc\" ]]; then`);\n lines.push(` _${safeName} \"$@\"`);\n lines.push(`else`);\n lines.push(` compdef _${safeName} ${executableName}`);\n lines.push(`fi`);\n lines.push(`###-end-${executableName}-completions-###`);\n return lines.join(\"\\n\");\n};\n//# sourceMappingURL=zsh.js.map","/**\n * The `Completions` module turns a plain description of an Effect CLI command\n * tree into shell completion scripts for Bash, Zsh, Fish, and PowerShell. It\n * is the low-level script generation surface used by the unstable CLI package\n * and by the built-in completions global flag.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Bash from \"./internal/completions/bash.js\";\nimport * as Fish from \"./internal/completions/fish.js\";\nimport * as PowerShell from \"./internal/completions/powershell.js\";\nimport * as Zsh from \"./internal/completions/zsh.js\";\n/**\n * Generates a shell completion script for a command descriptor.\n *\n * **When to use**\n *\n * Use when you need an installable completion script from an existing\n * `CommandDescriptor`.\n *\n * **Details**\n *\n * Dispatches by `shell` to Bash, Zsh, Fish, or PowerShell generation and\n * returns a static script string for `executableName`.\n *\n * @see {@link Shell} for supported shell names\n * @see {@link CommandDescriptor} for the command shape used by completion generation\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const generate = (executableName, shell, descriptor) => {\n switch (shell) {\n case \"bash\":\n return Bash.generate(executableName, descriptor);\n case \"zsh\":\n return Zsh.generate(executableName, descriptor);\n case \"fish\":\n return Fish.generate(executableName, descriptor);\n case \"powershell\":\n return PowerShell.generate(executableName, descriptor);\n }\n};\n//# sourceMappingURL=Completions.js.map","import { dual } from \"../Function.js\";\nimport * as Param from \"./Param.js\";\n// -------------------------------------------------------------------------------------\n// constructors\n// -------------------------------------------------------------------------------------\n/**\n * Creates a string flag that accepts text input.\n *\n * **Example** (Creating string flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const nameFlag = Flag.String(\"name\")\n * // Usage: --name \"John Doe\"\n * nameFlag.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const String = name => Param.String(Param.flagKind, name);\n/**\n * Creates a boolean flag that can be enabled or disabled.\n *\n * **Example** (Creating boolean flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const verboseFlag = Flag.Boolean(\"verbose\")\n * // Usage: --verbose (true) or --no-verbose (false)\n * // Omission fails unless the flag is made optional or given a fallback.\n * verboseFlag.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Boolean = name => Param.Boolean(Param.flagKind, name);\n/**\n * Creates an integer flag that accepts whole number input.\n *\n * **Example** (Creating integer flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const portFlag = Flag.Int(\"port\")\n * // Usage: --port 8080\n * portFlag.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Int = name => Param.Int(Param.flagKind, name);\n/**\n * Creates a float flag that accepts decimal number input.\n *\n * **Example** (Creating float flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const rateFlag = Flag.Finite(\"rate\")\n * // Usage: --rate 3.14\n * rateFlag.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Finite = name => Param.Finite(Param.flagKind, name);\n/**\n * Creates a date flag that accepts date input in ISO format.\n *\n * **Example** (Creating date flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const startDateFlag = Flag.Date(\"start-date\")\n * // Usage: --start-date 2023-12-25\n * startDateFlag.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Date = name => Param.Date(Param.flagKind, name);\n/**\n * Constructs option parameters that represent a choice between several inputs.\n * Each tuple maps a string flag value to an associated typed value.\n *\n * **Example** (Creating flag choices with values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // simple enum like choice mapping directly to string union\n * const color = Flag.Literals(\"color\", [\"red\", \"green\", \"blue\"])\n *\n * // choice with custom value mapping\n * const logLevel = Flag.ChoiceWithValue(\"log-level\", [\n * [\"debug\", \"Debug\" as const],\n * [\"info\", \"Info\" as const],\n * [\"error\", \"Error\" as const]\n * ])\n * const kinds = [color.kind, logLevel.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const ChoiceWithValue = (name, choices) => Param.ChoiceWithValue(Param.flagKind, name, choices);\n/**\n * Accepts one of the provided strings. An empty array rejects all input.\n *\n * @see {@link ChoiceWithValue} for mapping accepted strings to different typed values\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Literals = (name, literals) => Param.Literals(Param.flagKind, name, literals);\n/**\n * Creates a path flag that accepts file system path input with validation options.\n *\n * **Example** (Creating path flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Basic path flag\n * const pathFlag = Flag.Path(\"config-path\")\n *\n * // File-only path that must exist\n * const fileFlag = Flag.Path(\"input-file\", {\n * pathType: \"file\",\n * mustExist: true\n * })\n *\n * // Directory path with custom type name\n * const dirFlag = Flag.Path(\"output-dir\", {\n * pathType: \"directory\",\n * typeName: \"OUTPUT_DIRECTORY\"\n * })\n * const kinds = [pathFlag.kind, fileFlag.kind, dirFlag.kind] // => [\"flag\", \"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Path = (name, options) => Param.Path(Param.flagKind, name, options);\n/**\n * Creates a file path flag that accepts file paths with optional existence validation.\n *\n * **Example** (Creating file flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Basic file flag\n * const inputFlag = Flag.File(\"input\")\n * // Usage: --input ./data.json\n *\n * // File that must exist\n * const configFlag = Flag.File(\"config\", { mustExist: true })\n * // Usage: --config ./config.yaml (file must exist)\n * const kinds = [inputFlag.kind, configFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const File = (name, options) => Param.File(Param.flagKind, name, options);\n/**\n * Creates a directory path flag that accepts directory paths with optional existence validation.\n *\n * **Example** (Creating directory flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Basic directory flag\n * const outputFlag = Flag.Directory(\"output\")\n * // Usage: --output ./build\n *\n * // Directory that must exist\n * const sourceFlag = Flag.Directory(\"source\", { mustExist: true })\n * // Usage: --source ./src (directory must exist)\n * const kinds = [outputFlag.kind, sourceFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Directory = (name, options) => Param.Directory(Param.flagKind, name, options);\n/**\n * Creates a string flag whose parsed value is wrapped in `Redacted.Redacted` so\n * stringification and logging redact the value.\n *\n * **Gotchas**\n *\n * Values supplied on the command line may still be visible to the operating\n * system or shell history.\n *\n * **Example** (Creating redacted flags)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Redacted, Stdio, Terminal } from \"effect\"\n * import { Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const passwordFlag = Flag.Redacted(\"password\")\n *\n * const program = Effect.gen(function*() {\n * const [, password] = yield* passwordFlag.parse({\n * arguments: [],\n * flags: { \"password\": [\"abc123\"] }\n * })\n * return Redacted.value(password).length\n * })\n *\n * await Effect.runPromise(program.pipe(Effect.provide(CliTestLayer))) // => 6\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Redacted = name => Param.Redacted(Param.flagKind, name);\n/**\n * Creates a flag that reads and returns file content as a string.\n *\n * **Example** (Reading file text)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const config = Flag.FileText(\"config-file\")\n * // --config-file ./app.json will read the file content\n * config.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileText = name => Param.FileText(Param.flagKind, name);\n/**\n * Creates a flag that reads and parses the content of the specified file.\n *\n * **Details**\n *\n * The parser that is utilized will depend on the specified `format`, or the\n * extension of the file passed on the command-line if no `format` is specified.\n *\n * **Example** (Parsing file contents)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Will use the extension of the file passed on the command line to determine\n * // the parser to use\n * const config = Flag.FileParse(\"config\")\n *\n * // Will use the JSON parser\n * const jsonConfig = Flag.FileParse(\"json-config\", { format: \"json\" })\n * const kinds = [config.kind, jsonConfig.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileParse = (name, options) => Param.FileParse(Param.flagKind, name, options);\n/**\n * Creates a flag that reads and validates file content using the specified\n * schema.\n *\n * **Example** (Validating file contents)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Flag } from \"effect/cli\"\n *\n * const ConfigSchema = Schema.Struct({\n * port: Schema.Number,\n * host: Schema.String\n * })\n *\n * const config = Flag.FileSchema(\"config\", ConfigSchema, { format: \"json\" })\n * config.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileSchema = (name, schema, options) => Param.FileSchema(Param.flagKind, name, schema, options);\n/**\n * Creates a flag that parses key=value pairs.\n *\n * **When to use**\n *\n * Use when you need a CLI flag that accepts one or more `key=value`\n * configuration entries.\n *\n * **Details**\n *\n * Requires at least one key=value pair. Multiple pairs are merged into a single\n * record.\n *\n * **Example** (Parsing key-value pairs)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const env = Flag.KeyValuePair(\"env\")\n * // --env FOO=bar --env BAZ=qux will parse to { FOO: \"bar\", BAZ: \"qux\" }\n * env.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const KeyValuePair = name => Param.KeyValuePair(Param.flagKind, name);\n/**\n * A flag that always fails to parse.\n *\n * **Example** (Creating sentinel flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const makeValueFlag = (includeValue: boolean) =>\n * includeValue ? Flag.String(\"value\") : Flag.Never\n *\n * makeValueFlag(true) === Flag.Never // => false\n * makeValueFlag(false) === Flag.Never // => true\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Never = /*#__PURE__*/Param.Never(Param.flagKind);\n// -------------------------------------------------------------------------------------\n// combinators\n// -------------------------------------------------------------------------------------\n/**\n * Adds an alias to a flag, allowing it to be referenced by multiple names.\n *\n * **Example** (Adding flag aliases)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Flag can be used as both --verbose and -v\n * const verboseFlag = Flag.Boolean(\"verbose\").pipe(\n * Flag.withAlias(\"v\")\n * )\n *\n * // Multiple aliases can be chained\n * const helpFlag = Flag.Boolean(\"help\").pipe(\n * Flag.withAlias(\"h\"),\n * Flag.withAlias(\"?\")\n * )\n * const kinds = [verboseFlag.kind, helpFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category aliasing\n * @since 4.0.0\n */\nexport const withAlias = /*#__PURE__*/dual(2, (self, alias) => Param.withAlias(self, alias));\n/**\n * Adds a description to a flag for help documentation.\n *\n * **Example** (Adding help descriptions)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const portFlag = Flag.Int(\"port\").pipe(\n * Flag.withDescription(\"The port number to listen on\")\n * )\n *\n * const configFlag = Flag.File(\"config\").pipe(\n * Flag.withDescription(\"Path to the configuration file\")\n * )\n * const kinds = [portFlag.kind, configFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category metadata\n * @since 4.0.0\n */\nexport const withDescription = /*#__PURE__*/dual(2, (self, description) => Param.withDescription(self, description));\n/**\n * Lets a flag be given without a value, in which case `value` is used.\n *\n * **Details**\n *\n * Follows GNU-style optional values, like `--color[=WHEN]`. An explicit value\n * must be attached with `=` (`--watch=until-done` or `-w=until-done`). A bare\n * `--watch` is parsed as `--watch=<value>`, so `value` is validated like any\n * other input. The flag never consumes the next token, so in `--watch build`,\n * `build` stays a positional argument or subcommand. The flag is still\n * required unless it is made optional or given a default.\n *\n * **Example** (Flag with an optional value)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const watch = Flag.Literals(\"watch\", [\"first-failure\", \"until-done\"]).pipe(\n * Flag.withOptionalValue(\"first-failure\"),\n * Flag.optional\n * )\n * // --watch => Option.some(\"first-failure\")\n * // --watch=until-done => Option.some(\"until-done\")\n * // (absent) => Option.none()\n * // In help: --watch [=choice]\n * watch.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.1.0\n */\nexport const withOptionalValue = /*#__PURE__*/dual(2, (self, value) => Param.withOptionalValue(self, value));\n// -------------------------------------------------------------------------------------\n// metadata\n// -------------------------------------------------------------------------------------\n/**\n * Sets a custom metavar (placeholder name) for the flag in help documentation.\n *\n * **Details**\n *\n * The metavar is displayed in usage text to indicate what value the user should\n * provide. For example, `--output FILE` shows `FILE` as the metavar.\n *\n * **Example** (Setting metavars)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const databaseFlag = Flag.String(\"database-url\").pipe(\n * Flag.withMetavar(\"URL\"),\n * Flag.withDescription(\"Database connection URL\")\n * )\n * // In help: --database-url URL\n *\n * const timeoutFlag = Flag.Int(\"timeout\").pipe(\n * Flag.withMetavar(\"SECONDS\")\n * )\n * // In help: --timeout SECONDS\n * const kinds = [databaseFlag.kind, timeoutFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category metadata\n * @since 4.0.0\n */\nexport const withMetavar = /*#__PURE__*/dual(2, (self, metavar) => Param.withMetavar(self, metavar));\n/**\n * Hides a flag from generated help output and shell completions while keeping\n * it fully parseable on the command line.\n *\n * **When to use**\n *\n * Use when experimental or internal flags should be accepted but not advertised, such as\n * `--experimental-foo`, debug toggles, or escape hatches that are not yet committed to the\n * public CLI surface.\n *\n * **Example** (Hiding a flag from help)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Flag still parses --experimental-foo, but it does not appear in --help.\n * const experimental = Flag.Boolean(\"experimental-foo\").pipe(\n * Flag.withHidden\n * )\n * experimental.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category metadata\n * @since 4.0.0\n */\nexport const withHidden = self => Param.withHidden(self);\n/**\n * Makes a flag optional, returning an Option type that can be None if not provided.\n *\n * **Example** (Making flags optional)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Option, Path, Stdio, Terminal } from \"effect\"\n * import { Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const optionalPort = Flag.optional(Flag.Int(\"port\"))\n *\n * const program = Effect.gen(function*() {\n * const [, port] = yield* optionalPort.parse({\n * arguments: [],\n * flags: { \"port\": [\"4000\"] }\n * })\n * return port\n * })\n *\n * await Effect.runPromise(program.pipe(Effect.provide(CliTestLayer))) // => Option.some(4000)\n * ```\n *\n * @stability unstable\n * @category optionality\n * @since 4.0.0\n */\nexport const optional = param => Param.optional(param);\n/**\n * Provides a default value for a flag when it's not specified.\n *\n * **Example** (Providing default values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const portFlag = Flag.Int(\"port\").pipe(\n * Flag.withDefault(8080)\n * )\n * // If --port is not provided, defaults to 8080\n *\n * const hostFlag = Flag.String(\"host\").pipe(\n * Flag.withDefault(\"localhost\")\n * )\n * // If --host is not provided, defaults to \"localhost\"\n * const kinds = [portFlag.kind, hostFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category optionality\n * @since 4.0.0\n */\nexport const withDefault = Param.withDefault;\n/**\n * Adds a fallback config that is loaded when a required flag is missing.\n *\n * **Example** (Falling back to config)\n *\n * ```ts import.meta.vitest\n * import { Config } from \"effect\"\n * import { Flag } from \"effect/cli\"\n *\n * const verbose = Flag.Boolean(\"verbose\").pipe(\n * Flag.withFallbackConfig(Config.Boolean(\"VERBOSE\"))\n * )\n * verbose.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackConfig = /*#__PURE__*/dual(2, (self, config) => Param.withFallbackConfig(self, config));\n/**\n * Adds a fallback prompt that is shown when a required flag is missing.\n *\n * **Example** (Falling back to prompts)\n *\n * ```ts import.meta.vitest\n * import { Flag, Prompt } from \"effect/cli\"\n *\n * const name = Flag.String(\"name\").pipe(\n * Flag.withFallbackPrompt(Prompt.String({ message: \"Name\" }))\n * )\n * name.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackPrompt = /*#__PURE__*/dual(2, (self, prompt) => Param.withFallbackPrompt(self, prompt));\n/**\n * Transforms the parsed value of a flag using a mapping function.\n *\n * **Example** (Mapping parsed values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Convert string to uppercase\n * const nameFlag = Flag.String(\"name\").pipe(\n * Flag.map((name) => name.toUpperCase())\n * )\n *\n * // Convert port to URL\n * const urlFlag = Flag.Int(\"port\").pipe(\n * Flag.map((port) => `http://localhost:${port}`)\n * )\n * const kinds = [nameFlag.kind, urlFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => Param.map(self, f));\n/**\n * Transforms the parsed value using an Effect that can perform IO operations.\n *\n * **Example** (Mapping parsed values effectfully)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const upperName = Flag.String(\"name\").pipe(\n * Flag.mapEffect((name) => Effect.succeed(name.toUpperCase()))\n * )\n *\n * const [, value] = await Effect.runPromise(\n * upperName.parse({\n * arguments: [],\n * flags: { name: [\"alice\"] }\n * }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => \"ALICE\"\n * ```\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const mapEffect = /*#__PURE__*/dual(2, (self, f) => Param.mapEffect(self, f));\n/**\n * Transforms the parsed value using a function that might throw, with error handling.\n *\n * **Example** (Mapping thrown errors)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * // Parse JSON string with error handling\n * const jsonFlag = Flag.String(\"config\").pipe(\n * Flag.mapTryCatch(\n * (json) => JSON.parse(json),\n * (error) => `Invalid JSON: ${error}`\n * )\n * )\n *\n * // Parse URL with error handling\n * const urlFlag = Flag.String(\"url\").pipe(\n * Flag.mapTryCatch(\n * (url) => new URL(url),\n * (error) => `Invalid URL: ${error}`\n * )\n * )\n *\n * const [, value] = await Effect.runPromise(\n * jsonFlag.parse({\n * arguments: [],\n * flags: { config: ['{\"enabled\":true}'] }\n * }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => { enabled: true }\n * ```\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const mapTryCatch = /*#__PURE__*/dual(3, (self, f, onError) => Param.mapTryCatch(self, f, onError));\n/**\n * Ensures a flag is specified at least a minimum number of times.\n *\n * **Example** (Requiring repeated values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const sourceFlag = Flag.atLeast(Flag.File(\"source\"), 2)\n * // Requires at least 2 source files\n * // Usage: --source file1.ts --source file2.ts\n *\n * const tagFlag = Flag.String(\"tag\").pipe(\n * Flag.atLeast(1)\n * )\n * // Requires at least 1 tag\n * const kinds = [sourceFlag.kind, tagFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category repetition\n * @since 4.0.0\n */\nexport const atLeast = /*#__PURE__*/dual(2, (self, min) => Param.atLeast(self, min));\n/**\n * Ensures a flag is specified at most a maximum number of times.\n *\n * **Example** (Limiting repeated values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const warningFlag = Flag.atMost(Flag.String(\"warning\"), 3)\n * // Allows up to 3 warning flags\n * // Usage: --warning w1 --warning w2 --warning w3\n *\n * const debugFlag = Flag.String(\"debug\").pipe(\n * Flag.atMost(1)\n * )\n * // Allows at most 1 debug flag\n * const kinds = [warningFlag.kind, debugFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category repetition\n * @since 4.0.0\n */\nexport const atMost = /*#__PURE__*/dual(2, (self, max) => Param.atMost(self, max));\n/**\n * Ensures a flag is specified between a minimum and maximum number of times.\n *\n * **Example** (Bounding repeated values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const hostFlag = Flag.between(Flag.String(\"host\"), 1, 3)\n * // Requires 1-3 host flags\n * // Usage: --host host1 --host host2\n *\n * const excludeFlag = Flag.String(\"exclude\").pipe(\n * Flag.between(0, 5)\n * )\n * // Allows 0-5 exclude patterns\n * const kinds = [hostFlag.kind, excludeFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category repetition\n * @since 4.0.0\n */\nexport const between = /*#__PURE__*/dual(3, (self, min, max) => Param.between(self, min, max));\n/**\n * Transforms and filters a flag value, failing with a custom error if the transformation returns None.\n *\n * **Example** (Filtering and transforming values)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n * import { Flag } from \"effect/cli\"\n *\n * // Parse positive integers only\n * const positiveInt = Flag.Int(\"count\").pipe(\n * Flag.filterMap(\n * (n) => n > 0 ? Option.some(n) : Option.none(),\n * (n) => `Expected positive integer, got ${n}`\n * )\n * )\n *\n * // Parse valid email addresses\n * const emailFlag = Flag.String(\"email\").pipe(\n * Flag.filterMap(\n * (email) => email.includes(\"@\") ? Option.some(email) : Option.none(),\n * (email) => `Invalid email address: ${email}`\n * )\n * )\n * const kinds = [positiveInt.kind, emailFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(3, (self, f, onNone) => Param.filterMap(self, f, onNone));\n/**\n * Filters a flag value based on a predicate, failing with a custom error if the predicate returns false.\n *\n * **Example** (Filtering parsed values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Ensure port is in valid range\n * const portFlag = Flag.Int(\"port\").pipe(\n * Flag.filter(\n * (port) => port >= 1 && port <= 65535,\n * (port) => `Port ${port} is out of range (1-65535)`\n * )\n * )\n *\n * // Ensure non-empty string\n * const nameFlag = Flag.String(\"name\").pipe(\n * Flag.filter(\n * (name) => name.trim().length > 0,\n * () => \"Name cannot be empty\"\n * )\n * )\n * const kinds = [portFlag.kind, nameFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filter = /*#__PURE__*/dual(3, (self, predicate, onFalse) => Param.filter(self, predicate, onFalse));\n/**\n * Provides an alternative flag if the first one fails to parse.\n *\n * **Example** (Falling back to another flag)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Try parsing as integer, fallback to string\n * const valueFlag = Flag.orElse(\n * Flag.Int(\"value\"),\n * () => Flag.String(\"value\")\n * )\n *\n * // Multiple input sources with fallback\n * const configFlag = Flag.orElse(\n * Flag.File(\"config\"),\n * () => Flag.String(\"config-url\")\n * )\n * const kinds = [valueFlag.kind, configFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category alternatives\n * @since 4.0.0\n */\nexport const orElse = /*#__PURE__*/dual(2, (self, that) => Param.orElse(self, that));\n/**\n * Tries to parse with the first flag, then the second, returning a Result that indicates which succeeded.\n *\n * **Example** (Returning fallback results)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Result, Stdio, Terminal } from \"effect\"\n * import { Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const sourceFlag = Flag.orElseResult(\n * Flag.String(\"source\"),\n * () => Flag.String(\"source-url\")\n * )\n *\n * const program = Effect.gen(function*() {\n * const [, source] = yield* sourceFlag.parse({\n * arguments: [],\n * flags: { \"source-url\": [\"https://example.com\"] }\n * })\n * return source\n * })\n *\n * await Effect.runPromise(program.pipe(Effect.provide(CliTestLayer))) // => Result.fail(\"https://example.com\")\n * ```\n *\n * @stability unstable\n * @category alternatives\n * @since 4.0.0\n */\nexport const orElseResult = /*#__PURE__*/dual(2, (self, that) => Param.orElseResult(self, that));\n/**\n * Validates and transforms a flag value using a Schema codec.\n *\n * **Example** (Validating with schemas)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Flag } from \"effect/cli\"\n *\n * const isEmail = Schema.isPattern(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/, {\n * message: \"Must be a valid email address\"\n * })\n *\n * // Parse and validate email with custom schema\n * const EmailSchema = Schema.String.pipe(\n * Schema.check(isEmail)\n * )\n *\n * const emailFlag = Flag.String(\"email\").pipe(\n * Flag.withSchema(EmailSchema)\n * )\n *\n * // Parse JSON configuration with schema validation\n * const ConfigSchema = Schema.Struct({\n * port: Schema.Number,\n * host: Schema.String,\n * ssl: Schema.optional(Schema.Boolean)\n * }).pipe(Schema.fromJsonString)\n *\n * const configFlag = Flag.String(\"config\").pipe(\n * Flag.withSchema(ConfigSchema)\n * )\n * const kinds = [emailFlag.kind, configFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const withSchema = /*#__PURE__*/dual(2, (self, schema) => Param.withSchema(self, schema));\n//# sourceMappingURL=Flag.js.map","/**\n * Help Documentation\n * ================\n *\n * Internal helpers for generating help documentation.\n * Extracted from command.ts to avoid circular dependencies.\n */\nimport * as Effect from \"../../Effect.js\";\nimport * as Param from \"../Param.js\";\nimport { toFlagDoc, toImpl } from \"./command.js\";\nconst dedupeGlobalFlags = flags => {\n const seen = new Set();\n const deduped = [];\n for (const flag of flags) {\n if (seen.has(flag)) {\n continue;\n }\n seen.add(flag);\n deduped.push(flag);\n }\n return deduped;\n};\n/**\n * Returns the resolved command lineage for the provided path.\n * Includes the root command as the first element.\n */\nexport const getCommandsForCommandPath = (command, commandPath) => {\n const commands = [command];\n let currentCommand = command;\n for (let i = 1; i < commandPath.length; i++) {\n const subcommandName = commandPath[i];\n let subcommand = undefined;\n for (const group of currentCommand.subcommands) {\n subcommand = group.commands.find(sub => sub.name === subcommandName);\n if (subcommand) {\n break;\n }\n }\n if (!subcommand) {\n break;\n }\n commands.push(subcommand);\n currentCommand = subcommand;\n }\n return commands;\n};\n/**\n * Returns active global flags for a command path.\n * Built-ins are prepended and declarations are collected root -> leaf.\n */\nexport const getGlobalFlagsForCommandPath = (command, commandPath, builtIns) => {\n const commands = getCommandsForCommandPath(command, commandPath);\n const declared = commands.flatMap(current => toImpl(current).globalFlags);\n return dedupeGlobalFlags([...builtIns, ...declared]);\n};\nconst collectDeclaredGlobalFlags = command => {\n const collected = [];\n const visit = current => {\n const impl = toImpl(current);\n for (const flag of impl.globalFlags) {\n collected.push(flag);\n }\n for (const group of current.subcommands) {\n for (const subcommand of group.commands) {\n visit(subcommand);\n }\n }\n };\n visit(command);\n return dedupeGlobalFlags(collected);\n};\nconst getSharedFlagsForCommandPath = (commands, currentFlags) => {\n if (commands.length <= 1) {\n return [];\n }\n const seen = new Set(currentFlags.map(flag => flag.name));\n const sharedFlags = [];\n for (const ancestor of commands.slice(0, -1)) {\n const ancestorImpl = toImpl(ancestor);\n for (const flag of ancestorImpl.contextConfig.flags) {\n const singles = Param.extractSingleParams(flag);\n const metadata = Param.getParamMetadata(flag);\n for (const single of singles) {\n if (seen.has(single.name)) {\n continue;\n }\n // Hidden ancestor flags are excluded from the shared-flags section\n // of subcommand help, the same way they're excluded from the owning\n // command's own help output.\n if (single.hidden) {\n continue;\n }\n seen.add(single.name);\n sharedFlags.push(toFlagDoc(single, metadata));\n }\n }\n }\n return sharedFlags;\n};\n/**\n * Returns all global flags declared in a command tree.\n * Built-ins are prepended and command declarations are deduplicated by identity.\n */\nexport const getGlobalFlagsForCommandTree = (command, builtIns) => dedupeGlobalFlags([...builtIns, ...collectDeclaredGlobalFlags(command)]);\n/**\n * Helper function to get help documentation for a specific command path.\n * Navigates through the command hierarchy to find the right command.\n * Reads active global flags for the path and includes them in the help doc.\n */\nexport const getHelpForCommandPath = (command, commandPath, builtIns) => Effect.gen(function* () {\n const commands = getCommandsForCommandPath(command, commandPath);\n const currentCommand = commands.length > 0 ? commands[commands.length - 1] : command;\n const baseDoc = toImpl(currentCommand).buildHelpDoc(commandPath);\n const sharedFlags = getSharedFlagsForCommandPath(commands, baseDoc.flags);\n const flags = getGlobalFlagsForCommandPath(command, commandPath, builtIns);\n const globalFlagDocs = [];\n for (const flag of flags) {\n const singles = Param.extractSingleParams(flag.flag);\n const metadata = Param.getParamMetadata(flag.flag);\n for (const single of singles) {\n // Same rule as command-local flags: hidden globals are still parsed\n // and still trigger their handlers, they just don't appear under\n // \"GLOBAL FLAGS\" in --help.\n if (single.hidden) continue;\n globalFlagDocs.push({\n ...toFlagDoc(single, metadata),\n required: false\n });\n }\n }\n return {\n ...baseDoc,\n flags: [...sharedFlags, ...baseDoc.flags],\n globalFlags: globalFlagDocs\n };\n});\n//# sourceMappingURL=help.js.map","/**\n * Global flags for Effect CLI command trees. Global flags are parsed outside a\n * single command's local flags and can apply to a command and its descendants.\n *\n * This module defines two kinds of global flags: action flags, which run an\n * effect and stop normal command execution, and setting flags, which provide a\n * parsed value to the command handler through the Effect context. It also\n * defines the built-in help, version, wizard, shell-completion, and log-level flags\n * used by `Command.run` and `Command.runWith`.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Console from \"../Console.js\";\nimport * as Context from \"../Context.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Option from \"../Option.js\";\nimport * as CliOutput from \"./CliOutput.js\";\nimport * as Completions_ from \"./Completions.js\";\nimport * as Flag from \"./Flag.js\";\nimport * as CommandDescriptor from \"./internal/completions/descriptor.js\";\nimport * as HelpInternal from \"./internal/help.js\";\n/* ========================================================================== */\n/* Constructors */\n/* ========================================================================== */\n/**\n * Creates an Action flag that performs a side effect and exits.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Action = options => ({\n _tag: \"Action\",\n flag: options.flag,\n run: options.run\n});\n/**\n * Creates a Setting flag that configures the command handler's environment.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Setting = id => options => {\n settingIdCounter += 1;\n const ref = Context.Service(`effect/cli/GlobalFlag/${id}/${settingIdCounter}`);\n return Object.assign(ref, {\n _tag: \"Setting\",\n id,\n flag: options.flag\n });\n};\nlet settingIdCounter = 0;\n/* ========================================================================== */\n/* Built-in Flag References */\n/* ========================================================================== */\n/**\n * Defines the `--help` / `-h` global flag, which shows help documentation for the\n * active command path.\n *\n * @see {@link BuiltIns} for the default list containing this flag\n * @see {@link Action} for defining custom action global flags\n *\n * @stability unstable\n * @category references\n * @since 4.0.0\n */\nexport const Help = /*#__PURE__*/Action({\n flag: /*#__PURE__*/Flag.Boolean(\"help\").pipe(/*#__PURE__*/Flag.withAlias(\"h\"), /*#__PURE__*/Flag.withDescription(\"Show help information\"), /*#__PURE__*/Flag.withDefault(false)),\n run: /*#__PURE__*/Effect.fnUntraced(function* (_, {\n builtIns,\n command,\n commandPath\n }) {\n const formatter = yield* CliOutput.Formatter;\n const helpDoc = yield* HelpInternal.getHelpForCommandPath(command, commandPath, builtIns);\n yield* Console.log(formatter.formatHelpDoc(helpDoc));\n })\n});\n/**\n * Defines the global action flag for showing command version information.\n *\n * **When to use**\n *\n * Use to add a built-in `--version / -v` flag to a command runner.\n *\n * @stability unstable\n * @category references\n * @since 4.0.0\n */\nexport const Version = /*#__PURE__*/Action({\n flag: /*#__PURE__*/Flag.Boolean(\"version\").pipe(/*#__PURE__*/Flag.withAlias(\"v\"), /*#__PURE__*/Flag.withDescription(\"Show version information\"), /*#__PURE__*/Flag.withDefault(false)),\n run: /*#__PURE__*/Effect.fnUntraced(function* (_, {\n command,\n version\n }) {\n const formatter = yield* CliOutput.Formatter;\n yield* Console.log(formatter.formatVersion(command.name, version));\n })\n});\n/**\n * Defines the global action flag for starting interactive wizard mode.\n *\n * **Details**\n *\n * `Command.run` and `Command.runWith` handle this action specially so the\n * generated arguments can be passed back through the command parser.\n *\n * @stability unstable\n * @category references\n * @since 4.0.0\n */\nexport const Wizard = /*#__PURE__*/Action({\n flag: /*#__PURE__*/Flag.Boolean(\"wizard\").pipe(/*#__PURE__*/Flag.withDescription(\"Start wizard mode for a command\"), /*#__PURE__*/Flag.withDefault(false)),\n run: () => Effect.void\n});\n/**\n * Defines the `--completions` global flag, which prints a shell completion script for\n * the given shell.\n *\n * **Details**\n *\n * Accepted values are `bash`, `zsh`, `fish`, `powershell`, `sh`, and `pwsh`;\n * `sh` is normalized to `bash` and `pwsh` to `powershell`.\n *\n * @stability unstable\n * @category references\n * @since 4.0.0\n */\nexport const Completions = /*#__PURE__*/Action({\n flag: /*#__PURE__*/Flag.ChoiceWithValue(\"completions\", [[\"bash\", \"bash\"], [\"zsh\", \"zsh\"], [\"fish\", \"fish\"], [\"powershell\", \"powershell\"], [\"sh\", \"bash\"], [\"pwsh\", \"powershell\"]]).pipe(Flag.optional, /*#__PURE__*/Flag.withMetavar(\"<bash|zsh|fish|powershell|sh|pwsh>\"), /*#__PURE__*/Flag.withDescription(\"Print shell completion script\")),\n run: /*#__PURE__*/Effect.fnUntraced(function* (shell, {\n command\n }) {\n if (Option.isNone(shell)) return;\n const descriptor = CommandDescriptor.fromCommand(command);\n yield* Console.log(Completions_.generate(command.name, shell.value, descriptor));\n })\n});\n/**\n * Defines the global setting flag for command log level.\n *\n * **When to use**\n *\n * Use to add a built-in `--log-level` option that configures the minimum log\n * level for the command.\n *\n * @stability unstable\n * @category references\n * @since 4.0.0\n */\nexport const LogLevel = /*#__PURE__*/Setting(\"log-level\")({\n flag: /*#__PURE__*/Flag.ChoiceWithValue(\"log-level\", [[\"all\", \"All\"], [\"trace\", \"Trace\"], [\"debug\", \"Debug\"], [\"info\", \"Info\"], [\"warn\", \"Warn\"], [\"warning\", \"Warn\"], [\"error\", \"Error\"], [\"fatal\", \"Fatal\"], [\"none\", \"None\"]]).pipe(Flag.optional, /*#__PURE__*/Flag.withDescription(\"Sets the minimum log level\"), /*#__PURE__*/Flag.withMetavar(\"<all|trace|debug|info|warn|warning|error|fatal|none>\"))\n});\n/* ========================================================================== */\n/* References */\n/* ========================================================================== */\n/**\n * Built-in global flags in default precedence order.\n *\n * **When to use**\n *\n * Use when extending or inspecting the default global-flag set that\n * `Command.runWith` prepends before user-defined global flags.\n *\n * **Details**\n *\n * The built-ins are `Help`, `Version`, `Wizard`, `Completions`, and `LogLevel`.\n * `Command.runWith` prepends these built-ins when collecting and parsing global\n * flags.\n *\n * **Gotchas**\n *\n * Action flags are processed in active flag order and the first present action\n * exits, so this array controls built-in action precedence.\n *\n * @see {@link Help} for the help action flag\n * @see {@link Version} for the version action flag\n * @see {@link Completions} for the shell-completions action flag\n * @see {@link LogLevel} for the built-in log-level setting flag\n *\n * @stability unstable\n * @category references\n * @since 4.0.0\n */\nexport const BuiltIns = [Help, Version, Wizard, Completions, LogLevel];\n//# sourceMappingURL=GlobalFlag.js.map","/**\n * Configuration for Effect CLI command execution.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"../Context.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as GlobalFlag from \"./GlobalFlag.js\";\n/**\n * Context reference for configuration shared by CLI parsing, help generation,\n * and command execution.\n *\n * **When to use**\n *\n * Use when you need to customize runner-wide CLI behavior, such as which\n * built-in global flags are available.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class CliConfig extends /*#__PURE__*/Context.Reference(\"effect/cli/CliConfig\", {\n defaultValue: () => defaults\n}) {}\n/**\n * Default CLI configuration containing every built-in global flag.\n *\n * @stability unstable\n * @category defaults\n * @since 4.0.0\n */\nexport const defaults = {\n builtIns: GlobalFlag.BuiltIns\n};\n/**\n * Creates CLI configuration by merging the provided options over `defaults`.\n *\n * **When to use**\n *\n * Use when you need a configuration value to provide directly through the\n * `CliConfig` context reference.\n *\n * @see {@link layer} for providing configuration as a layer\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = options => ({\n ...defaults,\n ...options\n});\n/**\n * Creates a layer that provides CLI configuration merged over `defaults`.\n *\n * **When to use**\n *\n * Use when wiring customized CLI behavior into an application layer.\n *\n * @see {@link make} for creating a configuration value directly\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = options => Layer.succeed(CliConfig, make(options));\n//# sourceMappingURL=CliConfig.js.map","/**\n * @internal\n */\nexport function lex(argv) {\n const endIndex = argv.indexOf(\"--\");\n if (endIndex === -1) {\n // No -- delimiter, lex everything normally\n return {\n tokens: lexTokens(argv),\n trailingOperands: []\n };\n }\n // Split at -- delimiter\n return {\n tokens: lexTokens(argv.slice(0, endIndex)),\n trailingOperands: argv.slice(endIndex + 1)\n };\n}\nconst negativeNumberRegex = /^-(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?$/;\nconst lexTokens = args => {\n const tokens = [];\n for (const arg of args) {\n if (!arg.startsWith(\"-\") || negativeNumberRegex.test(arg)) {\n tokens.push({\n _tag: \"Value\",\n value: arg\n });\n } else if (arg.startsWith(\"--\")) {\n const equalIndex = arg.indexOf(\"=\");\n if (equalIndex !== -1) {\n const name = arg.slice(2, equalIndex);\n const value = arg.slice(equalIndex + 1);\n tokens.push({\n _tag: \"LongOption\",\n name,\n raw: arg,\n value\n });\n } else {\n tokens.push({\n _tag: \"LongOption\",\n name: arg.slice(2),\n raw: arg\n });\n }\n } else if (arg.length > 1) {\n const flags = arg.slice(1);\n const equalIndex = flags.indexOf(\"=\");\n if (equalIndex !== -1) {\n const flag = flags.slice(0, equalIndex);\n const value = flags.slice(equalIndex + 1);\n tokens.push({\n _tag: \"ShortOption\",\n flag,\n raw: `-${flag}`,\n value\n });\n } else {\n for (const ch of flags) {\n tokens.push({\n _tag: \"ShortOption\",\n flag: ch,\n raw: `-${ch}`\n });\n }\n }\n } else {\n tokens.push({\n _tag: \"Value\",\n value: arg\n });\n }\n }\n return tokens;\n};\n//# sourceMappingURL=lexer.js.map","/**\n * Simple Levenshtein distance implementation (small N, no perf worries)\n */\nconst levenshtein = (a, b) => {\n const m = a.length;\n const n = b.length;\n const dp = Array.from({\n length: m + 1\n }, () => new Array(n + 1).fill(0));\n for (let i = 0; i <= m; i++) dp[i][0] = i;\n for (let j = 0; j <= n; j++) dp[0][j] = j;\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);\n }\n }\n return dp[m][n];\n};\n/**\n * Return suggestions with minimum distance found, up to distance 2.\n *\n * @internal\n */\nexport const suggest = (input, candidates) => {\n const distances = candidates.map(c => [levenshtein(input, c), c]).filter(([d]) => d <= 2) // Stricter threshold\n .sort(([a], [b]) => a - b);\n if (distances.length === 0) return [];\n // Only return suggestions with the minimum distance found\n const minDistance = distances[0][0];\n return distances.filter(([d]) => d === minDistance).map(([, c]) => c);\n};\n//# sourceMappingURL=auto-suggest.js.map","/**\n * Parsing Pipeline for CLI Commands\n * ==================================\n *\n * The parser transforms raw argv tokens into structured command input through\n * three main phases:\n *\n * 1. **Lexer** (external): Converts argv strings into typed tokens\n * - LongOption: --name or --name=value\n * - ShortOption: -n or -n=value (also handles -abc as three flags)\n * - Value: positional arguments\n *\n * 2. **Built-in Extraction**: Peels off built-in flags (help/version/completions)\n * before command-specific parsing begins.\n *\n * 3. **Command Parsing**: Recursively processes command levels:\n * - Collects flags defined at this level\n * - Detects subcommand from first value token\n * - Forwards remaining tokens to child command\n *\n * Key Behaviors\n * -------------\n * - Inherited parent flags may appear before OR after the subcommand name (npm-style)\n * - Only the first Value token can open a subcommand\n * - Errors accumulate rather than throwing exceptions\n */\nimport * as Effect from \"../../Effect.js\";\nimport * as Option from \"../../Option.js\";\nimport * as CliError from \"../CliError.js\";\nimport * as Param from \"../Param.js\";\nimport * as Primitive from \"../Primitive.js\";\nimport { suggest } from \"./auto-suggest.js\";\nimport { toImpl } from \"./command.js\";\n/* ========================================================================== */\n/* Public API */\n/* ========================================================================== */\n/**\n * @internal\n */\nexport const getCommandPath = parsedInput => Option.match(parsedInput.subcommand, {\n onNone: () => [],\n onSome: subcommand => [subcommand.name, ...getCommandPath(subcommand.parsedInput)]\n});\n/**\n * @internal\n */\nexport const parseArgs = (lexResult, command, commandPath = []) => Effect.gen(function* () {\n const {\n tokens,\n trailingOperands: afterEndOfOptions\n } = lexResult;\n const newCommandPath = [...commandPath, command.name];\n const commandImpl = toImpl(command);\n const singles = commandImpl.config.flags.flatMap(Param.extractSingleParams);\n const flagParams = singles.filter(Param.isFlagParam);\n const flagRegistry = createFlagRegistry(flagParams);\n const inheritedSingles = commandImpl.contextConfig.flags.flatMap(Param.extractSingleParams);\n const inheritedFlagParams = inheritedSingles.filter(Param.isFlagParam);\n const inheritedFlagRegistry = createFlagRegistry(inheritedFlagParams);\n const inheritedNames = new Set(inheritedFlagParams.map(param => param.name));\n const context = {\n command,\n commandPath: newCommandPath,\n flagRegistry,\n inheritedFlagRegistry,\n localFlagNames: flagParams.filter(param => !inheritedNames.has(param.name)).map(param => param.name)\n };\n const result = scanCommandLevel(tokens, context);\n if (result._tag === \"Leaf\") {\n return {\n flags: result.flags,\n arguments: [...result.arguments, ...afterEndOfOptions],\n subcommand: Option.none(),\n ...(result.errors.length > 0 && {\n errors: result.errors\n })\n };\n }\n const subLex = {\n tokens: result.childTokens,\n trailingOperands: afterEndOfOptions\n };\n const subParsed = yield* parseArgs(subLex, result.sub, newCommandPath);\n const allErrors = [...result.errors, ...(subParsed.errors ?? [])];\n return {\n flags: result.flags,\n arguments: [],\n subcommand: Option.some({\n name: result.sub.name,\n parsedInput: subParsed\n }),\n ...(allErrors.length > 0 && {\n errors: allErrors\n })\n };\n});\nconst makeCursor = tokens => {\n let i = 0;\n return {\n peek: () => tokens[i],\n take: () => tokens[i++],\n rest: () => tokens.slice(i)\n };\n};\n/* ========================================================================== */\n/* Flag Registry */\n/* ========================================================================== */\n/**\n * Creates a registry for O(1) flag lookup by name or alias.\n * @internal\n */\nexport const createFlagRegistry = params => {\n const index = new Map();\n for (const param of params) {\n if (index.has(param.name)) {\n throw new Error(`Duplicate flag name \"${param.name}\" in command definition`);\n }\n index.set(param.name, param);\n for (const alias of param.aliases) {\n if (index.has(alias)) {\n throw new Error(`Duplicate flag/alias \"${alias}\" in command definition (conflicts with \"${index.get(alias).name}\")`);\n }\n index.set(alias, param);\n }\n }\n return {\n params,\n index\n };\n};\nconst buildSubcommandIndex = subcommands => {\n const index = new Map();\n const setKey = (key, command) => {\n const existing = index.get(key);\n if (existing && existing !== command) {\n throw new Error(`Duplicate subcommand name/alias \"${key}\" in command definition (conflicts with \"${existing.name}\")`);\n }\n index.set(key, command);\n };\n for (const group of subcommands) {\n for (const subcommand of group.commands) {\n setKey(subcommand.name, subcommand);\n if (subcommand.alias && subcommand.alias !== subcommand.name) {\n setKey(subcommand.alias, subcommand);\n }\n }\n }\n return index;\n};\n/* ========================================================================== */\n/* Flag Accumulator */\n/* ========================================================================== */\n/** Creates an empty flag map with all known flag names initialized to [].\n * @internal\n */\nexport const createEmptyFlagMap = params => Object.fromEntries(params.map(p => [p.name, []]));\n/**\n * Creates a mutable accumulator for collecting flag values.\n * Pre-initializes empty arrays for all known flags.\n */\nconst createFlagAccumulator = params => {\n const map = createEmptyFlagMap(params);\n return {\n add: (name, raw) => {\n if (raw !== undefined) map[name].push(raw);\n },\n merge: from => {\n for (const key in from) {\n const values = from[key];\n if (values?.length) {\n for (let i = 0; i < values.length; i++) {\n map[key].push(values[i]);\n }\n }\n }\n },\n snapshot: () => map\n };\n};\nconst isFlagToken = t => t._tag === \"LongOption\" || t._tag === \"ShortOption\";\nconst getFlagName = t => t._tag === \"LongOption\" ? t.name : t.flag;\nconst resolveFlag = (token, registry) => {\n const tokenName = getFlagName(token);\n const direct = registry.index.get(tokenName);\n if (direct && direct.name === tokenName) {\n return {\n param: direct,\n negated: false\n };\n }\n if (token._tag === \"LongOption\" && token.name.startsWith(\"no-\")) {\n const canonicalName = token.name.slice(3);\n const param = registry.index.get(canonicalName);\n if (param && param.name === canonicalName && Primitive.isBoolean(param.primitiveType)) {\n return {\n param,\n negated: true\n };\n }\n }\n if (direct) {\n return {\n param: direct,\n negated: false\n };\n }\n return undefined;\n};\nconst invalidNegatedFlagValue = (token, spec, value) => new CliError.InvalidValue({\n option: spec.name,\n value,\n expected: `omit the value and use ${token.raw} by itself to set --${spec.name} to false`,\n kind: \"flag\"\n});\nconst missingFlagValue = spec => {\n const choices = Primitive.getChoiceKeys(spec.primitiveType);\n return new CliError.InvalidValue({\n option: spec.name,\n value: \"\",\n expected: choices === undefined ? spec.typeName ?? Primitive.getTypeName(spec.primitiveType) : choices.join(\" | \"),\n kind: \"flag\"\n });\n};\n/**\n * Checks whether a token is a boolean literal value.\n * Recognizes: true/false, yes/no, on/off, 1/0\n */\nconst asBooleanLiteral = token => token?._tag === \"Value\" && (Primitive.isTrueLiteral(token.value) || Primitive.isFalseLiteral(token.value)) ? token.value : undefined;\n/* ========================================================================== */\n/* Flag Value Consumption */\n/* ========================================================================== */\n/**\n * Reads a flag's value from the token stream.\n *\n * Value resolution order:\n * 1. Inline value: --flag=value or -f=value\n * 2. Optional value: the flag's configured value, without consuming a token\n * 3. Boolean special case: implicit \"true\" or explicit boolean literal\n * 4. Next token: consume following Value token if present\n */\nconst consumeFlagValue = (cursor, token, spec, negated = false) => {\n const consumed = consumeFlagValueWithTokens(cursor, token, spec, negated);\n switch (consumed._tag) {\n case \"Value\":\n return {\n _tag: \"Value\",\n value: consumed.value\n };\n case \"Error\":\n return {\n _tag: \"Error\",\n error: consumed.error\n };\n }\n};\nconst consumeFlagValueWithTokens = (cursor, token, spec, negated = false) => {\n // Inline value has highest priority\n if (negated) {\n if (token.value !== undefined) {\n return {\n _tag: \"Error\",\n error: invalidNegatedFlagValue(token, spec, token.value),\n tokens: []\n };\n }\n const literal = spec.optionalValue === undefined ? asBooleanLiteral(cursor.peek()) : undefined;\n if (literal !== undefined) {\n const literalToken = cursor.take();\n return {\n _tag: \"Error\",\n error: invalidNegatedFlagValue(token, spec, literal),\n tokens: literalToken === undefined ? [] : [literalToken]\n };\n }\n return {\n _tag: \"Value\",\n value: \"false\",\n tokens: []\n };\n }\n if (token.value !== undefined) {\n return {\n _tag: \"Value\",\n value: token.value,\n tokens: []\n };\n }\n if (spec.optionalValue !== undefined) {\n return {\n _tag: \"Value\",\n value: spec.optionalValue,\n tokens: []\n };\n }\n // Boolean flags: check for explicit literal or default to \"true\"\n if (Primitive.isBoolean(spec.primitiveType)) {\n const literal = asBooleanLiteral(cursor.peek());\n const literalToken = literal !== undefined ? cursor.take() : undefined;\n return {\n _tag: \"Value\",\n value: literal ?? \"true\",\n tokens: literalToken === undefined ? [] : [literalToken]\n };\n }\n // Non-boolean: try to consume next Value token\n const next = cursor.peek();\n if (next?._tag === \"Value\") {\n const valueToken = cursor.take();\n return {\n _tag: \"Value\",\n value: next.value,\n tokens: valueToken === undefined ? [] : [valueToken]\n };\n }\n return {\n _tag: \"Error\",\n error: missingFlagValue(spec),\n tokens: []\n };\n};\n/**\n * Consumes known flags from a token stream.\n * Unrecognized tokens are passed through to remainder.\n * Used for both global flag extraction and npm-style parent flag collection.\n * @internal\n */\nexport const consumeKnownFlags = (tokens, registry) => {\n const flagMap = createEmptyFlagMap(registry.params);\n const remainder = [];\n const errors = [];\n const cursor = makeCursor(tokens);\n for (let t = cursor.take(); t; t = cursor.take()) {\n if (!isFlagToken(t)) {\n remainder.push(t);\n continue;\n }\n const resolved = resolveFlag(t, registry);\n if (!resolved) {\n remainder.push(t);\n continue;\n }\n const consumed = consumeFlagValue(cursor, t, resolved.param, resolved.negated);\n if (consumed._tag === \"Error\") {\n errors.push(consumed.error);\n continue;\n }\n if (consumed.value !== undefined) {\n flagMap[resolved.param.name].push(consumed.value);\n }\n }\n return {\n flagMap,\n remainder,\n errors\n };\n};\nconst extractFlagParams = command => {\n const commandImpl = toImpl(command);\n const singles = commandImpl.config.flags.flatMap(Param.extractSingleParams);\n return singles.filter(Param.isFlagParam);\n};\nconst extractContextFlagParams = command => {\n const commandImpl = toImpl(command);\n const singles = commandImpl.contextConfig.flags.flatMap(Param.extractSingleParams);\n return singles.filter(Param.isFlagParam);\n};\nconst resolveFromRegistries = (token, registries) => {\n for (const registry of registries) {\n const resolved = resolveFlag(token, registry);\n if (resolved !== undefined) {\n return resolved;\n }\n }\n return undefined;\n};\nconst preserveFlag = (remainder, cursor, token, resolved) => {\n remainder.push(token);\n const consumed = consumeFlagValueWithTokens(cursor, token, resolved.param, resolved.negated);\n remainder.push(...consumed.tokens);\n};\nconst localFlagWouldPrecedeSubcommand = (token, remainingTokens, resolved, subIndex, registries) => {\n const cursor = makeCursor(remainingTokens);\n consumeFlagValueWithTokens(cursor, token, resolved.param, resolved.negated);\n for (let token = cursor.take(); token; token = cursor.take()) {\n if (isFlagToken(token)) {\n const known = resolveFromRegistries(token, registries);\n if (known !== undefined) {\n consumeFlagValueWithTokens(cursor, token, known.param, known.negated);\n }\n continue;\n }\n if (token._tag === \"Value\") {\n return subIndex.has(token.value);\n }\n }\n return false;\n};\n/**\n * Consumes global flags while walking the command tree.\n *\n * Command-local flags take precedence over global flags at the selected command\n * level. This lets commands reuse a global flag name, for example a subcommand\n * with its own `--version <value>` flag overriding the built-in global\n * `--version` action.\n * @internal\n */\nexport const consumeGlobalFlags = (tokens, command, registry) => {\n const flagMap = createEmptyFlagMap(registry.params);\n const errors = [];\n const consumeLevel = (tokens, command, ignoredRegistries) => {\n const localRegistry = createFlagRegistry(extractFlagParams(command));\n const inheritedRegistry = createFlagRegistry(extractContextFlagParams(command));\n const subIndex = buildSubcommandIndex(command.subcommands);\n const cursor = makeCursor(tokens);\n const remainder = [];\n let awaitingFirstValue = true;\n for (let token = cursor.take(); token; token = cursor.take()) {\n if (isFlagToken(token)) {\n const ignored = resolveFromRegistries(token, ignoredRegistries);\n if (ignored !== undefined) {\n preserveFlag(remainder, cursor, token, ignored);\n continue;\n }\n const inherited = resolveFlag(token, inheritedRegistry);\n if (inherited !== undefined) {\n preserveFlag(remainder, cursor, token, inherited);\n continue;\n }\n const local = resolveFlag(token, localRegistry);\n const global = resolveFlag(token, registry);\n if (local !== undefined) {\n if (global === undefined || !awaitingFirstValue || !localFlagWouldPrecedeSubcommand(token, cursor.rest(), local, subIndex, [localRegistry, inheritedRegistry, registry])) {\n preserveFlag(remainder, cursor, token, local);\n continue;\n }\n }\n if (global !== undefined) {\n const consumed = consumeFlagValueWithTokens(cursor, token, global.param, global.negated);\n if (consumed._tag === \"Error\") {\n errors.push(consumed.error);\n continue;\n }\n if (consumed.value !== undefined) {\n flagMap[global.param.name].push(consumed.value);\n }\n continue;\n }\n remainder.push(token);\n continue;\n }\n if (token._tag === \"Value\" && awaitingFirstValue) {\n const sub = subIndex.get(token.value);\n if (sub !== undefined) {\n remainder.push(token);\n remainder.push(...consumeLevel(cursor.rest(), sub, [...ignoredRegistries, inheritedRegistry]));\n return remainder;\n }\n awaitingFirstValue = false;\n }\n remainder.push(token);\n }\n return remainder;\n };\n return {\n flagMap,\n remainder: consumeLevel(tokens, command, []),\n errors\n };\n};\n/* ========================================================================== */\n/* Error Creation */\n/* ========================================================================== */\nconst createUnrecognizedFlagError = (token, params, commandPath) => {\n const printable = token._tag === \"LongOption\" ? `--${token.name}` : `-${token.flag}`;\n const validNames = [];\n for (const p of params) {\n // Exclude hidden flags so a near-miss typo cannot reveal a flag name\n // that was intentionally kept out of --help.\n if (p.hidden) continue;\n validNames.push(p.name);\n if (Primitive.isBoolean(p.primitiveType)) {\n validNames.push(`no-${p.name}`);\n }\n for (const alias of p.aliases) {\n validNames.push(alias);\n }\n }\n const suggestions = suggest(getFlagName(token), validNames).map(n => n.length === 1 ? `-${n}` : `--${n}`);\n return new CliError.UnrecognizedOption({\n option: printable,\n suggestions,\n command: commandPath\n });\n};\n/* ========================================================================== */\n/* Parse State */\n/* ========================================================================== */\nconst createParseState = registry => ({\n flags: createFlagAccumulator(registry.params),\n arguments: [],\n errors: [],\n mode: {\n _tag: \"AwaitingFirstValue\"\n }\n});\nconst toLeafResult = state => ({\n _tag: \"Leaf\",\n flags: state.flags.snapshot(),\n arguments: state.arguments,\n errors: state.errors\n});\n/* ========================================================================== */\n/* First Value Resolution */\n/* ========================================================================== */\n/**\n * Determines how to handle the first value token.\n *\n * If it matches a known subcommand:\n * - Collect inherited parent flags from remaining tokens (npm-style)\n * - Return SubcommandResult with child tokens\n *\n * Otherwise:\n * - Return Argument to treat it as a positional argument\n * - Report error if command expects subcommand but got unknown value\n */\nconst resolveFirstValue = (value, cursor, context, state) => {\n const {\n command,\n commandPath,\n inheritedFlagRegistry,\n localFlagNames\n } = context;\n const subIndex = buildSubcommandIndex(command.subcommands);\n const sub = subIndex.get(value);\n if (sub) {\n const selectedPath = [...commandPath, sub.name];\n // Local flags are not inherited by subcommands.\n const parentFlags = state.flags.snapshot();\n for (const localFlagName of localFlagNames) {\n const values = parentFlags[localFlagName];\n if (values !== undefined && values.length > 0) {\n state.errors.push(new CliError.UnrecognizedOption({\n option: `--${localFlagName}`,\n suggestions: [],\n command: selectedPath\n }));\n }\n }\n // npm-style: inherited parent flags can appear after subcommand name\n const tail = consumeKnownFlags(cursor.rest(), inheritedFlagRegistry);\n state.flags.merge(tail.flagMap);\n state.errors.push(...tail.errors);\n return {\n _tag: \"Subcommand\",\n result: {\n _tag: \"Sub\",\n flags: state.flags.snapshot(),\n sub,\n childTokens: tail.remainder,\n errors: state.errors\n }\n };\n }\n // Not a subcommand. Check if this looks like a typo.\n const expectsArgs = toImpl(command).config.arguments.length > 0;\n if (!expectsArgs && subIndex.size > 0) {\n // Exclude unlisted subcommands so a typo cannot reveal a subcommand name\n // that was intentionally kept out of --help. Unlisted commands still\n // resolve via subIndex when invoked by exact name.\n const visibleKeys = [];\n for (const [key, sub] of subIndex) {\n if (!sub.unlisted) visibleKeys.push(key);\n }\n const suggestions = suggest(value, visibleKeys);\n state.errors.push(new CliError.UnknownSubcommand({\n subcommand: value,\n parent: commandPath,\n suggestions\n }));\n }\n return {\n _tag: \"Argument\"\n };\n};\n/* ========================================================================== */\n/* Token Processing */\n/* ========================================================================== */\n/**\n * Processes a flag token: looks up in registry, consumes value, records it.\n * Reports unrecognized flags as errors.\n */\nconst processFlag = (token, cursor, context, state) => {\n const {\n commandPath,\n flagRegistry\n } = context;\n const resolved = resolveFlag(token, flagRegistry);\n if (!resolved) {\n state.errors.push(createUnrecognizedFlagError(token, flagRegistry.params, commandPath));\n return;\n }\n const consumed = consumeFlagValue(cursor, token, resolved.param, resolved.negated);\n if (consumed._tag === \"Error\") {\n state.errors.push(consumed.error);\n return;\n }\n state.flags.add(resolved.param.name, consumed.value);\n};\n/**\n * Processes a value token based on current parsing mode.\n *\n * In AwaitingFirstValue mode:\n * - Check if value is a subcommand\n * - If so, return SubcommandResult to exit scanning\n * - If not, switch to CollectingArguments mode\n *\n * In CollectingArguments mode:\n * - Simply add value to arguments list\n */\nconst processValue = (value, cursor, context, state) => {\n if (state.mode._tag === \"AwaitingFirstValue\") {\n const result = resolveFirstValue(value, cursor, context, state);\n if (result._tag === \"Subcommand\") {\n return result.result;\n }\n state.mode = {\n _tag: \"CollectingArguments\"\n };\n }\n state.arguments.push(value);\n return undefined;\n};\n/* ========================================================================== */\n/* Command Level Scanning */\n/* ========================================================================== */\n/**\n * Scans a single command level, processing all tokens.\n *\n * For each token:\n * - Flags: Look up, consume value, record in accumulator\n * - Values: Check for subcommand (first value only), then collect as arguments\n *\n * Returns LeafResult if no subcommand detected, SubcommandResult otherwise.\n */\nconst scanCommandLevel = (tokens, context) => {\n const cursor = makeCursor(tokens);\n const state = createParseState(context.flagRegistry);\n for (let token = cursor.take(); token; token = cursor.take()) {\n if (isFlagToken(token)) {\n processFlag(token, cursor, context, state);\n continue;\n }\n if (token._tag === \"Value\") {\n const subResult = processValue(token.value, cursor, context, state);\n if (subResult) return subResult;\n }\n }\n return toLeafResult(state);\n};\n//# sourceMappingURL=parser.js.map","import * as Console from \"../../Console.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Redacted from \"../../Redacted.js\";\nimport * as Param from \"../Param.js\";\nimport * as Primitive from \"../Primitive.js\";\nimport * as Prompt from \"../Prompt.js\";\nimport * as Ansi from \"./ansi.js\";\nimport { toImpl } from \"./command.js\";\nexport const run = /*#__PURE__*/Effect.fnUntraced(function* (command, options) {\n const commandPath = options?.commandPath ?? [command.name];\n const selected = getCommandAtPath(command, commandPath);\n const commandLine = (options?.prefix ?? commandPath).map(value => commandLineArg(value));\n const {\n colors\n } = yield* Prompt.Theme;\n yield* logCurrentCommand(commandLine, colors);\n yield* promptCommand(selected, commandLine, selected === command ? \"ROOT\" : selected.name, colors);\n return {\n args: commandLine.map(arg => arg.value),\n displayArgs: commandLine.map(arg => arg.displayValue)\n };\n});\nconst getCommandAtPath = (command, commandPath) => {\n let current = command;\n for (const name of commandPath.slice(1)) {\n const child = current.subcommands.flatMap(group => group.commands).find(candidate => candidate.name === name || candidate.alias === name);\n if (child === undefined) {\n break;\n }\n current = child;\n }\n return current;\n};\nconst promptCommand = /*#__PURE__*/Effect.fnUntraced(function* (command, commandLine, sectionName, colors) {\n const impl = toImpl(command);\n const visibleSubcommands = command.subcommands.flatMap(group => group.commands.filter(child => !child.unlisted));\n const config = visibleSubcommands.length === 0 ? impl.config : impl.contextConfig;\n if (config.flags.length > 0) {\n yield* Console.log(renderSection(sectionName, \"FLAGS\", colors));\n for (const param of config.flags) {\n commandLine.push(...(yield* promptParam(param)));\n }\n if (config.arguments.length > 0 || visibleSubcommands.length > 0) {\n yield* logCurrentCommand(commandLine, colors);\n }\n }\n if (config.arguments.length > 0) {\n yield* Console.log(renderSection(sectionName, \"ARGUMENTS\", colors));\n for (const param of config.arguments) {\n commandLine.push(...(yield* promptParam(param)));\n }\n if (visibleSubcommands.length > 0) {\n yield* logCurrentCommand(commandLine, colors);\n }\n }\n if (visibleSubcommands.length === 0) {\n return;\n }\n const child = yield* Prompt.run(Prompt.Select({\n message: \"Command\",\n choices: visibleSubcommands.map(command => ({\n title: command.name,\n value: command,\n ...(command.shortDescription !== undefined ? {\n description: command.shortDescription\n } : command.description !== undefined ? {\n description: command.description\n } : {})\n }))\n }));\n yield* Console.log();\n commandLine.push(commandLineArg(child.name));\n if (hasWizardSteps(child)) {\n yield* logCurrentCommand(commandLine, colors);\n }\n yield* promptCommand(child, commandLine, child.name, colors);\n});\nconst hasWizardSteps = command => {\n const hasVisibleSubcommands = command.subcommands.some(group => group.commands.some(child => !child.unlisted));\n return hasVisibleSubcommands || toImpl(command).config.orderedParams.length > 0;\n};\nconst promptParam = /*#__PURE__*/Effect.fnUntraced(function* (param) {\n const single = Param.getUnderlyingSingleOrThrow(param);\n const metadata = Param.getParamMetadata(param);\n if (metadata.isOptional) {\n const include = yield* Prompt.run(Prompt.Confirm({\n message: `Set ${renderParamLabel(single)}?`,\n initial: false\n }));\n if (!include) {\n yield* Console.log();\n return [];\n }\n }\n const count = !metadata.isVariadic ? 1 : yield* Prompt.run(Prompt.Int({\n message: `${renderParamLabel(single)} count`,\n default: Option.getOrElse(metadata.variadicMin, () => 0),\n min: Option.getOrElse(metadata.variadicMin, () => 0),\n ...(Option.isSome(metadata.variadicMax) ? {\n max: metadata.variadicMax.value\n } : {})\n }));\n const values = [];\n for (let i = 0; i < count; i++) {\n values.push(yield* promptSingle(single));\n }\n const parsed = single.kind === Param.flagKind ? {\n flags: {\n [single.name]: values.map(arg => arg.value)\n },\n arguments: []\n } : {\n flags: {},\n arguments: values.map(arg => arg.value)\n };\n yield* param.parse(parsed);\n yield* Console.log();\n if (single.kind === Param.argumentKind) {\n return values;\n }\n // Inline option-looking values so the lexer cannot interpret them as flags or the -- delimiter.\n // Flags with an optional value only accept an inline value.\n return values.flatMap(value => single.optionalValue !== undefined || value.value.startsWith(\"-\") && value.value.length > 1 ? [commandLineArg(`--${single.name}=${value.value}`, `--${single.name}=${value.displayValue}`)] : [commandLineArg(`--${single.name}`), value]);\n});\nconst promptSingle = single => {\n const message = renderParamMessage(single);\n switch (single.primitiveType._tag) {\n case \"Boolean\":\n return Effect.map(Prompt.run(Prompt.Confirm({\n message,\n label: {\n confirm: \"true\",\n deny: \"false\"\n },\n placeholder: {\n defaultConfirm: \"(T/f)\",\n defaultDeny: \"(t/F)\"\n }\n })), value => commandLineArg(String(value)));\n case \"Choice\":\n {\n const choices = Primitive.getChoiceKeys(single.primitiveType) ?? [];\n return Effect.map(Prompt.run(Prompt.Select({\n message,\n choices: choices.map(choice => ({\n title: choice,\n value: choice\n }))\n })), commandLineArg);\n }\n case \"Date\":\n return Effect.map(Prompt.run(Prompt.Date({\n message\n })), date => commandLineArg(date.toISOString()));\n case \"Finite\":\n return Effect.map(Prompt.run(Prompt.Number({\n message\n })), value => commandLineArg(String(value)));\n case \"Int\":\n return Effect.map(Prompt.run(Prompt.Int({\n message\n })), value => commandLineArg(String(value)));\n case \"Redacted\":\n return Effect.map(Prompt.run(Prompt.Password({\n message\n })), value => commandLineArg(Redacted.value(value), \"<redacted>\"));\n default:\n return Effect.map(Prompt.run(Prompt.String({\n message\n })), commandLineArg);\n }\n};\nconst commandLineArg = (value, displayValue = value) => ({\n value,\n displayValue\n});\nconst formatName = single => single.kind === Param.flagKind ? `--${single.name}` : single.name;\nconst renderParamMessage = single => renderParamLabel(single);\nconst renderParamLabel = single => {\n const description = Option.getOrUndefined(single.description)?.trim();\n const label = single.kind === Param.flagKind && description !== undefined && description.length <= 32 ? description : humanize(single.name);\n return single.kind === Param.flagKind ? `${label} (${formatName(single)})` : label;\n};\nconst humanize = name => {\n const words = name.split(/[-_]+/).filter(word => word.length > 0);\n if (words.length === 0) return name;\n return [words[0][0].toUpperCase() + words[0].slice(1), ...words.slice(1)].join(\" \");\n};\nconst logCurrentCommand = (commandLine, colors) => Console.log(renderCommandBlock(\"Current command\", commandLine.map(arg => arg.displayValue), colors, Ansi.magenta));\nconst renderSection = (commandName, section, colors) => `${Ansi.annotate(colors, commandName.toUpperCase(), Ansi.bold, Ansi.cyanBright)} ${Ansi.annotate(colors, \"·\", Ansi.blackBright)} ${Ansi.annotate(colors, section, Ansi.bold, Ansi.white)}`;\nexport const renderIntroduction = (name, version, summary, colors) => {\n const title = `${Ansi.annotate(colors, name, Ansi.bold, Ansi.cyanBright)} ${Ansi.annotate(colors, `v${version}`, Ansi.white)} ${Ansi.annotate(colors, \"· Command wizard\", Ansi.bold, Ansi.white)}`;\n return [title, ...(summary === undefined || summary.length === 0 ? [] : [summary]), Ansi.annotate(colors, \"Build a command interactively. Press Ctrl+C to cancel.\", Ansi.blackBright), \"\"].join(\"\\n\");\n};\nexport const renderCompletion = (commandLine, colors) => renderCommandBlock(\"Command ready\", commandLine, colors, Ansi.cyanBright, Ansi.green);\nexport const renderQuit = colors => `\\n${Ansi.annotate(colors, \"Wizard cancelled.\", Ansi.red)}`;\nconst renderCommandBlock = (label, commandLine, colors, commandColor, labelColor = Ansi.white) => {\n const lines = wrapCommand(commandLine);\n return [Ansi.annotate(colors, label, Ansi.bold, labelColor), ...lines.map(line => Ansi.annotate(colors, line, commandColor)), \"\"].join(\"\\n\");\n};\nconst wrapCommand = commandLine => {\n const width = 88;\n const firstIndent = \" $ \";\n const continuationIndent = \" \";\n const args = commandLine.map(formatShellArg);\n const lines = [];\n let current = firstIndent;\n for (const arg of args) {\n const separator = current === firstIndent || current === continuationIndent ? \"\" : \" \";\n if (current.length + separator.length + arg.length > width && current !== firstIndent) {\n lines.push(`${current} \\\\`);\n current = `${continuationIndent}${arg}`;\n } else {\n current += `${separator}${arg}`;\n }\n }\n if (current !== firstIndent) {\n lines.push(current);\n }\n return lines;\n};\nconst formatShellArg = arg => /^[A-Za-z0-9_./:@%+=,-]+$/.test(arg) ? arg : `'${arg.replaceAll(\"'\", `'\"'\"'`)}'`;\n//# sourceMappingURL=wizard.js.map","import * as Console from \"../Console.js\";\nimport * as Context from \"../Context.js\";\nimport * as Effect from \"../Effect.js\";\nimport { dual } from \"../Function.js\";\nimport * as Option from \"../Option.js\";\nimport * as Predicate from \"../Predicate.js\";\nimport * as References from \"../References.js\";\nimport * as Result from \"../Result.js\";\nimport * as Runtime from \"../Runtime.js\";\nimport * as Stdio from \"../Stdio.js\";\nimport * as Terminal from \"../Terminal.js\";\nimport * as CliConfig from \"./CliConfig.js\";\nimport * as CliError from \"./CliError.js\";\nimport * as CliOutput from \"./CliOutput.js\";\nimport * as GlobalFlag from \"./GlobalFlag.js\";\nimport { checkForDuplicateFlags, makeCommand, makeParser, toImpl, TypeId } from \"./internal/command.js\";\nimport { mergeConfig, parseConfig } from \"./internal/config.js\";\nimport { getGlobalFlagsForCommandPath, getGlobalFlagsForCommandTree, getHelpForCommandPath } from \"./internal/help.js\";\nimport * as Lexer from \"./internal/lexer.js\";\nimport * as Parser from \"./internal/parser.js\";\nimport * as Wizard from \"./internal/wizard.js\";\nimport * as Param from \"./Param.js\";\nimport * as Prompt from \"./Prompt.js\";\n/**\n * Returns `true` if the provided value is a `Command`.\n *\n * **Gotchas**\n *\n * This checks for the `Command` type-id property; it does not validate the full\n * command shape.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isCommand = u => Predicate.hasProperty(u, TypeId);\n/* ========================================================================== */\n/* Constructors */\n/* ========================================================================== */\n/**\n * Creates a `Command` from a name, an optional configuration, and an optional\n * handler.\n *\n * **Details**\n *\n * Use `withDescription` and related metadata combinators to add help text. The\n * overloads support simple commands, configured commands, and commands with\n * effectful handlers.\n *\n * **Example** (Creating commands)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Argument, Command, Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * // Simple command with no configuration\n * const version = Command.make(\"version\")\n *\n * // Command with simple flags\n * const greet = Command.make(\"greet\", {\n * name: Flag.String(\"name\"),\n * count: Flag.Int(\"count\").pipe(Flag.withDefault(1))\n * })\n *\n * // Command with nested configuration\n * const deploy = Command.make(\"deploy\", {\n * environment: Flag.String(\"env\").pipe(\n * Flag.withDescription(\"Target environment\")\n * ),\n * server: {\n * host: Flag.String(\"host\").pipe(Flag.withDefault(\"localhost\")),\n * port: Flag.Int(\"port\").pipe(Flag.withDefault(3000))\n * },\n * files: Argument.String(\"files\").pipe(Argument.variadic),\n * force: Flag.Boolean(\"force\").pipe(\n * Flag.withDescription(\"Force deployment\"),\n * Flag.withDefault(false)\n * )\n * })\n *\n * // Command with handler\n * const output: Array<string> = []\n * const deployWithHandler = Command.make(\"deploy\", {\n * environment: Flag.String(\"env\"),\n * force: Flag.Boolean(\"force\").pipe(Flag.withDefault(false))\n * }, (config) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => output.push(`Starting deployment to ${config.environment}`))\n *\n * if (!config.force && config.environment === \"production\") {\n * return yield* Effect.fail(\"Production deployments require --force flag\")\n * }\n *\n * yield* Effect.sync(() => output.push(\"Deployment completed successfully\"))\n * }))\n *\n * await Effect.runPromise(\n * Command.runWith(deployWithHandler, { version: \"1.0.0\" })([\n * \"--env\",\n * \"staging\",\n * \"--force\"\n * ]).pipe(Effect.provide(CliTestLayer))\n * )\n * output // => [\"Starting deployment to staging\", \"Deployment completed successfully\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = (name, config, handler) => {\n const parsedConfig = parseConfig(config ?? {});\n return makeCommand({\n name,\n config: parsedConfig,\n ...(Predicate.isNotUndefined(handler) ? {\n handle: handler\n } : {})\n });\n};\n/* ========================================================================== */\n/* Combinators */\n/* ========================================================================== */\n/**\n * Adds or replaces the handler for a command.\n *\n * **Example** (Adding command handlers)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * // Command without initial handler\n * const greet = Command.make(\"greet\", {\n * name: Flag.String(\"name\")\n * })\n *\n * // Add handler later\n * const output: Array<string> = []\n * const greetWithHandler = greet.pipe(\n * Command.withHandler((config: { readonly name: string }) =>\n * Effect.sync(() => output.push(`Hello, ${config.name}!`)).pipe(Effect.asVoid)\n * )\n * )\n *\n * await Effect.runPromise(\n * Command.runWith(greetWithHandler, { version: \"1.0.0\" })([\"--name\", \"Alice\"]).pipe(\n * Effect.provide(CliTestLayer)\n * )\n * )\n * output // => [\"Hello, Alice!\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withHandler = /*#__PURE__*/dual(2, (self, handler) => makeCommand({\n ...toImpl(self),\n handle: handler\n}));\nconst normalizeSubcommandEntries = entries => {\n const flat = [];\n const grouped = new Map();\n const addToGroup = (group, command) => {\n flat.push(command);\n const existing = grouped.get(group);\n if (existing) {\n existing.push(command);\n } else {\n grouped.set(group, [command]);\n }\n };\n for (const entry of entries) {\n if (isCommand(entry)) {\n addToGroup(undefined, entry);\n continue;\n }\n for (const command of entry.commands) {\n addToGroup(entry.group, command);\n }\n }\n const groups = [];\n const ungroupedCommands = grouped.get(undefined);\n if (ungroupedCommands && ungroupedCommands.length > 0) {\n groups.push({\n group: undefined,\n commands: ungroupedCommands\n });\n }\n for (const [group, commands] of grouped) {\n if (group === undefined) {\n continue;\n }\n groups.push({\n group,\n commands\n });\n }\n return {\n flat,\n groups\n };\n};\n/**\n * Adds subcommands to a command, creating a hierarchical command structure.\n *\n * **Details**\n *\n * Subcommands can access their parent's parsed configuration by yielding the parent\n * command within their handler. This enables shared parent flags that affect\n * all subcommands.\n *\n * **Example** (Adding subcommands)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * // Parent command with shared flags\n * const git = Command.make(\"git\").pipe(\n * Command.withSharedFlags({\n * verbose: Flag.Boolean(\"verbose\").pipe(Flag.withDefault(false))\n * })\n * )\n *\n * // Subcommand that accesses parent config\n * const output: Array<string> = []\n * const clone = Command.make(\"clone\", {\n * repository: Flag.String(\"repo\")\n * }, (config) =>\n * Effect.gen(function*() {\n * const parent = yield* git // Access parent's parsed config\n * if (parent.verbose) {\n * yield* Effect.sync(() => output.push(\"Verbose mode enabled\"))\n * }\n * yield* Effect.sync(() => output.push(`Cloning ${config.repository}`))\n * }))\n *\n * const app = git.pipe(Command.withSubcommands([clone]))\n *\n * await Effect.runPromise(\n * Command.runWith(app, { version: \"1.0.0\" })([\n * \"--verbose\",\n * \"clone\",\n * \"--repo\",\n * \"github.com/foo/bar\"\n * ]).pipe(Effect.provide(CliTestLayer))\n * )\n * output // => [\"Verbose mode enabled\", \"Cloning github.com/foo/bar\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withSubcommands = /*#__PURE__*/dual(2, (self, subcommands) => {\n const normalized = normalizeSubcommandEntries(subcommands);\n checkForDuplicateFlags(self, normalized.flat);\n const impl = toImpl(self);\n const byName = new Map(normalized.flat.map(s => [s.name, toImpl(s)]));\n const SubcommandStateSymbol = Symbol(\"effect/cli/SubcommandState\");\n const parse = Effect.fnUntraced(function* (raw) {\n if (Option.isNone(raw.subcommand)) {\n return yield* impl.parse(raw);\n }\n const sub = byName.get(raw.subcommand.value.name);\n if (!sub) {\n return yield* impl.parse(raw);\n }\n const context = yield* impl.parseContext(raw);\n const result = yield* sub.parse(raw.subcommand.value.parsedInput);\n return {\n ...context,\n [SubcommandStateSymbol]: {\n name: sub.name,\n result\n }\n };\n });\n const handle = Effect.fnUntraced(function* (input, path) {\n const internal = input;\n const selectedSubcommand = internal[SubcommandStateSymbol];\n if (selectedSubcommand) {\n const child = byName.get(selectedSubcommand.name);\n if (!child) {\n return yield* new CliError.ShowHelp({\n commandPath: path,\n errors: []\n });\n }\n return yield* child.handle(selectedSubcommand.result, [...path, child.name]).pipe(Effect.provideService(impl.service, input));\n }\n return yield* impl.handle(input, path);\n });\n return makeCommand({\n name: impl.name,\n config: impl.config,\n contextConfig: impl.contextConfig,\n description: impl.description,\n shortDescription: impl.shortDescription,\n alias: impl.alias,\n unlisted: impl.unlisted,\n annotations: impl.annotations,\n globalFlags: impl.globalFlags,\n examples: impl.examples,\n service: impl.service,\n subcommands: normalized.groups,\n parse,\n parseContext: impl.parseContext,\n handle\n });\n});\n/**\n * Adds flags that are inherited by subcommands.\n *\n * **Details**\n *\n * Shared flags are available to this command's handler and to descendant\n * handlers via `yield* parentCommand`. Shared flags are accepted both before\n * and after a selected subcommand name (npm-style).\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withSharedFlags = /*#__PURE__*/dual(2, (self, sharedFlags) => {\n const impl = toImpl(self);\n const sharedConfig = parseConfig(sharedFlags);\n const mergedConfig = mergeConfig(impl.config, sharedConfig);\n const mergedContextConfig = mergeConfig(impl.contextConfig, sharedConfig);\n if (impl.subcommands.length > 0) {\n const flatSubcommands = impl.subcommands.flatMap(group => group.commands);\n checkForDuplicateFlags(self, flatSubcommands, {\n contextConfig: mergedContextConfig\n });\n }\n const parseShared = makeParser(sharedConfig, {\n allowLeftovers: true\n });\n const parse = Effect.fnUntraced(function* (raw) {\n const base = yield* impl.parse(raw);\n const shared = yield* parseShared(raw);\n return {\n ...base,\n ...shared\n };\n });\n const parseContext = Effect.fnUntraced(function* (raw) {\n const base = yield* impl.parseContext(raw);\n const shared = yield* parseShared(raw);\n return {\n ...base,\n ...shared\n };\n });\n const handle = (input, commandPath) => impl.handle(input, commandPath);\n return makeCommand({\n name: impl.name,\n config: mergedConfig,\n contextConfig: mergedContextConfig,\n description: impl.description,\n shortDescription: impl.shortDescription,\n alias: impl.alias,\n unlisted: impl.unlisted,\n annotations: impl.annotations,\n globalFlags: impl.globalFlags,\n examples: impl.examples,\n service: impl.service,\n subcommands: impl.subcommands,\n parse,\n parseContext,\n handle\n });\n});\n/**\n * Adds global flags to a command scope.\n *\n * **Details**\n *\n * Declared global flags apply to the command and all of its descendants.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withGlobalFlags = /*#__PURE__*/dual(2, (self, globalFlags) => {\n const impl = toImpl(self);\n const next = Array.from(new Set([...impl.globalFlags, ...globalFlags]));\n return makeCommand({\n ...impl,\n globalFlags: next\n });\n});\n/**\n * Sets the description for a command.\n *\n * **Details**\n *\n * Descriptions provide users with information about what the command does\n * when they view help documentation.\n *\n * **Example** (Setting descriptions)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const output: Array<string> = []\n * const deploy = Command.make(\"deploy\", {\n * environment: Flag.String(\"env\")\n * }, (config) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => output.push(`Deploying to ${config.environment}`))\n * })).pipe(\n * Command.withDescription(\"Deploy the application to a specified environment\")\n * )\n *\n * await Effect.runPromise(\n * Command.runWith(deploy, { version: \"1.0.0\" })([\"--env\", \"staging\"]).pipe(Effect.provide(CliTestLayer))\n * )\n * output // => [\"Deploying to staging\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withDescription = /*#__PURE__*/dual(2, (self, description) => makeCommand({\n ...toImpl(self),\n description\n}));\n/**\n * Sets a short description for a command.\n *\n * **Details**\n *\n * Short descriptions are used when listing subcommands in help output and\n * shell completions. If no short description is provided, the full\n * `description` is used as a fallback.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withShortDescription = /*#__PURE__*/dual(2, (self, shortDescription) => makeCommand({\n ...toImpl(self),\n shortDescription\n}));\n/**\n * Sets an alias for a command.\n *\n * **Details**\n *\n * Aliases are accepted as alternate subcommand names during parsing and are\n * shown in help output as `name, alias`.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withAlias = /*#__PURE__*/dual(2, (self, alias) => makeCommand({\n ...toImpl(self),\n alias\n}));\n/**\n * Omits a subcommand from parent help output, shell completions, and\n * \"did you mean?\" suggestions while keeping it fully invocable by exact name.\n *\n * **When to use**\n *\n * Use when experimental or internal subcommands should be accepted but not advertised on\n * the public CLI surface.\n *\n * **Example** (Unlisting a subcommand)\n *\n * ```ts import.meta.vitest\n * import { Command } from \"effect/cli\"\n *\n * // `experimental` still runs when invoked as `mycli experimental`,\n * // but it does not appear under SUBCOMMANDS in `mycli --help`.\n * const experimental = Command.make(\"experimental\").pipe(\n * Command.unlisted\n * )\n *\n * const root = Command.make(\"mycli\").pipe(\n * Command.withSubcommands([experimental])\n * )\n *\n * root.subcommands[0].commands[0].unlisted // => true\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const unlisted = self => makeCommand({\n ...toImpl(self),\n unlisted: true\n});\n/**\n * Adds a custom annotation to a command.\n *\n * **When to use**\n *\n * Use to attach one command-scoped metadata value under a `Context.Key`,\n * especially for consumers such as custom help formatters.\n *\n * **Details**\n *\n * Annotations are stored on the command's annotation context and flow into\n * generated help document annotations.\n *\n * **Gotchas**\n *\n * Adding the same `Context.Key` again replaces the earlier value.\n *\n * @see {@link annotateMerge} for merging an existing annotation context\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const annotate = /*#__PURE__*/dual(3, (self, service, value) => {\n const impl = toImpl(self);\n return makeCommand({\n ...impl,\n annotations: Context.add(impl.annotations, service, value)\n });\n});\n/**\n * Merges a Context of annotations into a command.\n *\n * **When to use**\n *\n * Use when you need to attach an already-built `Context.Context` of command\n * annotations.\n *\n * **Details**\n *\n * Merged annotations are stored on the command and exposed through generated\n * help document annotations.\n *\n * **Gotchas**\n *\n * If both contexts contain the same `Context.Key`, the incoming annotations\n * context wins.\n *\n * @see {@link annotate} for adding a single annotation without constructing a `Context`\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const annotateMerge = /*#__PURE__*/dual(2, (self, annotations) => {\n const impl = toImpl(self);\n return makeCommand({\n ...impl,\n annotations: Context.merge(impl.annotations, annotations)\n });\n});\n/**\n * Sets usage examples for a command.\n *\n * **Details**\n *\n * Examples are exposed in structured `HelpDoc` data and rendered by the\n * default formatter in an `EXAMPLES` section.\n *\n * **Example** (Adding usage examples)\n *\n * ```ts import.meta.vitest\n * import { Command } from \"effect/cli\"\n *\n * const login = Command.make(\"login\").pipe(\n * Command.withExamples([\n * { command: \"myapp login\", description: \"Log in with browser OAuth\" },\n * { command: \"myapp login --token sbp_abc123\", description: \"Log in with a token\" }\n * ])\n * )\n *\n * login.examples.map((example) => example.command) // => [\"myapp login\", \"myapp login --token sbp_abc123\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withExamples = /*#__PURE__*/dual(2, (self, examples) => makeCommand({\n ...toImpl(self),\n examples\n}));\n/* ========================================================================== */\n/* Providing Services */\n/* ========================================================================== */\n// Internal helper: transforms a command's handler while preserving other properties\nconst mapHandler = (self, f) => {\n const impl = toImpl(self);\n return makeCommand({\n ...impl,\n handle: (input, path) => f(impl.handle(input, path), input)\n });\n};\n/**\n * Provides the handler of a command with the services produced by a layer\n * that optionally depends on the command-line input to be created.\n *\n * **Example** (Providing command services)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, PlatformError, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const output: Array<string> = []\n * const deploy = Command.make(\"deploy\", {\n * env: Flag.String(\"env\")\n * }, (config) =>\n * Effect.gen(function*() {\n * const fs = yield* FileSystem.FileSystem\n * yield* Effect.sync(() => output.push(`Using file system for ${config.env}`))\n * })).pipe(\n * // Provide FileSystem based on the --env flag\n * Command.provide((config) =>\n * config.env === \"local\"\n * ? FileSystem.layerNoop({})\n * : FileSystem.layerNoop({\n * access: () =>\n * Effect.fail(\n * PlatformError.badArgument({\n * module: \"FileSystem\",\n * method: \"access\"\n * })\n * )\n * })\n * )\n * )\n *\n * await Effect.runPromise(\n * Command.runWith(deploy, { version: \"1.0.0\" })([\"--env\", \"local\"]).pipe(Effect.provide(CliTestLayer))\n * )\n * output // => [\"Using file system for local\"]\n * ```\n *\n * @stability unstable\n * @category providing services\n * @since 4.0.0\n */\nexport const provide = /*#__PURE__*/dual(args => isCommand(args[0]), (self, layer, options) => mapHandler(self, (handler, input) => Effect.provide(handler, typeof layer === \"function\" ? layer(input) : layer, options)));\n/**\n * Provides the handler of a command with the implementation of a service that\n * optionally depends on the command-line input to be constructed.\n *\n * **When to use**\n *\n * Use when a command handler needs a pure service implementation, optionally\n * derived from the parsed command input.\n *\n * @stability unstable\n * @category providing services\n * @since 4.0.0\n */\nexport const provideSync = /*#__PURE__*/dual(3, (self, service, implementation) => mapHandler(self, (handler, input) => Effect.provideService(handler, service, typeof implementation === \"function\" ? implementation(input) : implementation)));\n/**\n * Provides the handler of a command with the service produced by an effect\n * that optionally depends on the command-line input to be created.\n *\n * **When to use**\n *\n * Use to acquire a service effectfully for each command run, optionally using\n * parsed command input.\n *\n * @see {@link provideSync} for synchronous service acquisition\n * @see {@link provide} for providing an already-available service\n * @see {@link provideEffectDiscard} for running an effect before the handler without providing a service\n *\n * @stability unstable\n * @category providing services\n * @since 4.0.0\n */\nexport const provideEffect = /*#__PURE__*/dual(3, (self, service, effect) => mapHandler(self, (handler, input) => Effect.provideServiceEffect(handler, service, typeof effect === \"function\" ? effect(input) : effect)));\n/**\n * Allows for execution of an effect, which optionally depends on command-line\n * input to be created, prior to executing the handler of a command.\n *\n * @stability unstable\n * @category providing services\n * @since 4.0.0\n */\nexport const provideEffectDiscard = /*#__PURE__*/dual(2, (self, effect) => mapHandler(self, (handler, input) => Effect.andThen(typeof effect === \"function\" ? effect(input) : effect, handler)));\n/* ========================================================================== */\n/* Execution */\n/* ========================================================================== */\n/**\n * Interactively constructs command-line arguments for a command.\n *\n * **Details**\n *\n * The returned arguments include the command name and can be inspected,\n * modified, or passed to another command runner by the caller.\n *\n * **Example** (Constructing command arguments)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const command = Command.make(\"app\")\n * const silentConsole: Console.Console = Object.assign(Object.create(console), {\n * log: () => {}\n * })\n *\n * const program = Command.wizard(command).pipe(\n * Effect.provideService(Console.Console, silentConsole),\n * Effect.provide(CliTestLayer)\n * )\n *\n * await Effect.runPromise(program) // => [\"app\"]\n * ```\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const wizard = (command, options) => Effect.map(Wizard.run(command, options), result => result.args);\nconst getOutOfScopeGlobalFlagErrors = (allFlags, activeFlags, flagMap, commandPath) => {\n const activeSet = new Set(activeFlags);\n const errors = [];\n const seen = new Set();\n for (const flag of allFlags) {\n if (activeSet.has(flag)) {\n continue;\n }\n const singles = Param.extractSingleParams(flag.flag);\n for (const single of singles) {\n const entries = flagMap[single.name];\n if (!entries || entries.length === 0) {\n continue;\n }\n const option = `--${single.name}`;\n if (seen.has(option)) {\n continue;\n }\n seen.add(option);\n errors.push(new CliError.UnrecognizedOption({\n option,\n suggestions: [],\n command: commandPath\n }));\n }\n }\n return errors;\n};\nconst showHelp = (command, error, renderErrors) => Effect.gen(function* () {\n const {\n builtIns\n } = yield* CliConfig.CliConfig;\n const formatter = yield* CliOutput.Formatter;\n const helpDoc = yield* getHelpForCommandPath(command, error.commandPath, builtIns);\n yield* Console.log(formatter.formatHelpDoc(helpDoc));\n if (renderErrors && error.errors.length > 0) {\n yield* Console.error(formatter.formatErrors(error.errors));\n }\n});\nconst showUserError = error => Effect.gen(function* () {\n const formatter = yield* CliOutput.Formatter;\n yield* Console.error(formatter.formatError(error));\n error[Runtime.errorReported] = false;\n});\n/**\n * Runs a command using the arguments supplied by the `Stdio` service.\n *\n * **When to use**\n *\n * Use when command-line arguments should come from `Stdio` at the application\n * entry point.\n *\n * Help documents are always rendered. By default, parse error details and\n * `CliError.UserError` failures are also rendered with the installed\n * `CliOutput.Formatter` before the error is rethrown. Set `renderErrors` to\n * `false` when the host application owns error rendering.\n *\n * **Example** (Running commands with standard input)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({\n * args: Effect.succeed([\"--name\", \"Alice\"])\n * }),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const output: Array<string> = []\n * const greetCommand = Command.make(\"greet\", {\n * name: Flag.String(\"name\")\n * }, (config) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => output.push(`Hello, ${config.name}!`))\n * }))\n *\n * // Automatically gets args from the Stdio service\n * const program = Command.run(greetCommand, {\n * version: \"1.0.0\"\n * })\n *\n * await Effect.runPromise(program.pipe(Effect.provide(CliTestLayer)))\n * output // => [\"Hello, Alice!\"]\n * ```\n *\n * @see {@link runWith} for running a command with an explicit argument array\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const run = /*#__PURE__*/dual(2, (command, config) => Stdio.Stdio.use(({\n args\n}) => Effect.flatMap(args, args => runWith(command, config)(args))));\n/**\n * Runs a command with explicitly provided arguments instead of using arguments from `Stdio`.\n *\n * **When to use**\n *\n * Use when you need to test CLI applications or programmatically execute\n * commands with specific arguments.\n *\n * Help documents are always rendered. By default, parse error details and\n * `CliError.UserError` failures are also rendered with the installed\n * `CliOutput.Formatter` before the error is rethrown. Set `renderErrors` to\n * `false` when the host application owns error rendering.\n *\n * **Example** (Running commands with explicit arguments)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const output: Array<string> = []\n * const greet = Command.make(\"greet\", {\n * name: Flag.String(\"name\"),\n * count: Flag.Int(\"count\").pipe(Flag.withDefault(1))\n * }, (config) =>\n * Effect.gen(function*() {\n * for (let i = 0; i < config.count; i++) {\n * yield* Effect.sync(() => output.push(`Hello, ${config.name}!`))\n * }\n * }))\n *\n * // Test with specific arguments\n * const testProgram = Effect.gen(function*() {\n * const runCommand = Command.runWith(greet, { version: \"1.0.0\" })\n *\n * yield* runCommand([\"--name\", \"Alice\", \"--count\", \"2\"])\n * })\n *\n * await Effect.runPromise(testProgram.pipe(Effect.provide(CliTestLayer)))\n * output // => [\"Hello, Alice!\", \"Hello, Alice!\"]\n * ```\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const runWith = (command, config) => {\n const commandImpl = toImpl(command);\n return Effect.fnUntraced(function* (args) {\n const {\n builtIns\n } = yield* CliConfig.CliConfig;\n const {\n tokens,\n trailingOperands\n } = Lexer.lex(args);\n // 1. Collect known global flags from the command tree\n const allFlags = getGlobalFlagsForCommandTree(command, builtIns);\n // 2. Extract global flag tokens\n const allFlagParams = allFlags.flatMap(f => Param.extractSingleParams(f.flag));\n const globalRegistry = Parser.createFlagRegistry(allFlagParams.filter(Param.isFlagParam));\n const {\n flagMap,\n remainder,\n errors: globalFlagErrors\n } = Parser.consumeGlobalFlags(tokens, command, globalRegistry);\n const emptyArgs = {\n flags: flagMap,\n arguments: []\n };\n // 3. Parse command arguments from remaining tokens\n const parsedArgs = yield* Parser.parseArgs({\n tokens: remainder,\n trailingOperands\n }, command);\n const commandPath = [command.name, ...Parser.getCommandPath(parsedArgs)];\n const handlerCtx = {\n builtIns,\n command,\n commandPath,\n version: config.version\n };\n const activeFlags = getGlobalFlagsForCommandPath(command, commandPath, builtIns);\n // 4. Reject globals that were passed outside the active command scope\n const outOfScopeErrors = getOutOfScopeGlobalFlagErrors(allFlags, activeFlags, flagMap, commandPath);\n if (outOfScopeErrors.length > 0 || globalFlagErrors.length > 0) {\n const parseErrors = parsedArgs.errors ?? [];\n return yield* new CliError.ShowHelp({\n commandPath,\n errors: [...globalFlagErrors, ...outOfScopeErrors, ...parseErrors]\n });\n }\n // 5. Process action flags — first present action wins, then exit\n for (const flag of activeFlags) {\n if (flag._tag !== \"Action\") continue;\n const singles = Param.extractSingleParams(flag.flag);\n const hasEntry = singles.some(s => {\n const entries = flagMap[s.name];\n return entries !== undefined && entries.length > 0;\n });\n if (!hasEntry) continue;\n const [, value] = yield* flag.flag.parse(emptyArgs);\n if (flag === GlobalFlag.Wizard) {\n const {\n colors\n } = yield* Prompt.Theme;\n return yield* Effect.gen(function* () {\n yield* Console.log(Wizard.renderIntroduction(command.name, config.version, command.description, colors));\n const prefix = [command.name, ...args.filter(arg => arg !== \"--wizard\" && !arg.startsWith(\"--wizard=\"))];\n const wizardResult = yield* Wizard.run(command, {\n commandPath,\n prefix\n });\n yield* Console.log(Wizard.renderCompletion(wizardResult.displayArgs, colors));\n const shouldRun = yield* Prompt.run(Prompt.Toggle({\n message: \"Run this command?\",\n initial: true,\n active: \"yes\",\n inactive: \"no\"\n }));\n if (shouldRun) {\n yield* Console.log();\n yield* runWith(command, {\n ...config,\n renderErrors: false\n })(wizardResult.args.slice(1));\n }\n }).pipe(Effect.catchTag(\"QuitError\", () => Console.log(Wizard.renderQuit(colors))));\n }\n yield* flag.run(value, handlerCtx);\n return;\n }\n // 6. Handle parsing errors\n if (parsedArgs.errors && parsedArgs.errors.length > 0) {\n return yield* new CliError.ShowHelp({\n commandPath,\n errors: parsedArgs.errors\n });\n }\n const parseResult = yield* Effect.result(commandImpl.parse(parsedArgs));\n if (parseResult._tag === \"Failure\") {\n return yield* new CliError.ShowHelp({\n commandPath,\n errors: [parseResult.failure]\n });\n }\n // 7. Provide setting values\n let program = commandImpl.handle(parseResult.success, [command.name]);\n const logLevel = activeFlags.includes(GlobalFlag.LogLevel) ? (yield* GlobalFlag.LogLevel.flag.parse(emptyArgs))[1] : Option.none();\n program = Effect.provideService(program, GlobalFlag.LogLevel, logLevel);\n for (const flag of activeFlags) {\n if (flag._tag !== \"Setting\" || flag === GlobalFlag.LogLevel) continue;\n const [, value] = yield* flag.flag.parse(emptyArgs);\n program = Effect.provideService(program, flag, value);\n }\n // 8. Apply built-in setting behavior\n const services = Option.match(logLevel, {\n onNone: () => Context.empty(),\n onSome: level => Context.make(References.MinimumLogLevel, level)\n });\n // 9. Run command handler with composed context\n yield* Effect.provideContext(program, services);\n }, Effect.catchFilter(error => CliError.isCliError(error) && error._tag === \"ShowHelp\" ? Result.succeed(error) : Result.fail(error), error => Effect.andThen(showHelp(command, error, config.renderErrors !== false), Effect.fail(error))), Effect.catchFilter(error => config.renderErrors !== false && CliError.isCliError(error) && error._tag === \"UserError\" ? Result.succeed(error) : Result.fail(error), error => Effect.andThen(showUserError(error), Effect.fail(error))), Effect.catchFilter(e => Terminal.isQuitError(e) ? Result.succeed(e) : Result.fail(e), _ => Effect.interrupt));\n};\n//# sourceMappingURL=Command.js.map","/**\n * Service boundary for starting and controlling child processes.\n *\n * `ChildProcessSpawner` is the service used by `ChildProcess` commands to start\n * operating-system processes. A spawner turns a command description into a\n * handle that can write to stdin, read stdout and stderr, wait for exit, kill\n * the process, and manage whether the process keeps its parent alive. Platform\n * backends implement this service, while most application code uses the higher\n * level `ChildProcess` module.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Brand from \"../Brand.js\";\nimport * as Context from \"../Context.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Inspectable from \"../Inspectable.js\";\nimport * as Stream from \"../Stream.js\";\n/**\n * Constructs branded child process `ExitCode` values.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const ExitCode = /*#__PURE__*/Brand.nominal();\n/**\n * Constructs branded child process `ProcessId` values.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const ProcessId = /*#__PURE__*/Brand.nominal();\nconst HandleTypeId = \"~effect/process/ChildProcessSpawner/ChildProcessHandle\";\nconst HandleProto = {\n [HandleTypeId]: HandleTypeId,\n ...Inspectable.BaseProto,\n toJSON() {\n return {\n _id: \"ChildProcessHandle\",\n pid: this.pid\n };\n }\n};\n/**\n * Constructs a new `ChildProcessHandle`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeHandle = params => Object.setPrototypeOf({\n ...params\n}, HandleProto);\n/**\n * Creates a `ChildProcessSpawner` service from a `spawn` function, deriving\n * helpers for exit codes and output collection from that implementation.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = spawn => {\n const streamString = (command, options) => spawn(command).pipe(Effect.map(handle => Stream.decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), Stream.unwrap);\n const streamLines = (command, options) => Stream.splitLines(streamString(command, options));\n return ChildProcessSpawner.of({\n spawn,\n exitCode: command => Effect.scoped(Effect.flatMap(spawn(command), handle => handle.exitCode)),\n streamString,\n streamLines,\n lines: (command, options) => Stream.runCollect(streamLines(command, options)),\n string: (command, options) => Stream.mkString(streamString(command, options))\n });\n};\n/**\n * Service tag for child process spawning.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class ChildProcessSpawner extends /*#__PURE__*/Context.Service()(\"effect/process/ChildProcessSpawner\") {}\n//# sourceMappingURL=ChildProcessSpawner.js.map","/**\n * Describes child processes before they are started.\n *\n * A `Command` stores the executable, arguments, environment, standard streams,\n * working directory, and other process options. Commands can also be piped\n * together. A command is an `Effect`; running it asks the\n * `ChildProcessSpawner` service to start the process and returns a\n * `ChildProcessHandle`.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"../Context.js\";\nimport * as Effectable from \"../Effectable.js\";\nimport { dual } from \"../Function.js\";\nimport * as Predicate from \"../Predicate.js\";\nimport { ChildProcessSpawner } from \"./ChildProcessSpawner.js\";\nconst TypeId = \"~effect/process/ChildProcess\";\n// =============================================================================\n// Constructors\n// =============================================================================\nconst Proto = {\n ... /*#__PURE__*/Effectable.Prototype({\n label: \"Command\",\n evaluate(fiber) {\n return Context.getUnsafe(fiber.context, ChildProcessSpawner).spawn(this);\n }\n }),\n [TypeId]: TypeId\n};\n/**\n * Checks whether a value is a `Command`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isCommand = u => Predicate.hasProperty(u, TypeId);\n/**\n * Checks whether a command is a `StandardCommand`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isStandardCommand = command => command._tag === \"StandardCommand\";\n/**\n * Checks whether a command is a `PipedCommand`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isPipedCommand = command => command._tag === \"PipedCommand\";\nconst makeStandardCommand = (command, args, options) => Object.assign(Object.create(Proto), {\n _tag: \"StandardCommand\",\n command,\n args,\n options\n});\nconst makePipedCommand = (left, right, options = {}) => Object.assign(Object.create(Proto), {\n _tag: \"PipedCommand\",\n left,\n right,\n options\n});\n/**\n * Create a command from a template literal, options + template, or array form.\n *\n * **Details**\n *\n * This function supports three calling conventions:\n * 1. Template literal: `make\\`npm run build\\``\n * 2. Options + template literal: `make({ cwd: \"/app\" })\\`npm run build\\``\n * 3. Array form: `make(\"npm\", [\"run\", \"build\"], options?)`\n *\n * Template literals are not parsed until execution time, allowing parsing\n * errors to flow through Effect's error channel.\n *\n * **Example** (Creating commands)\n *\n * ```ts import.meta.vitest\n * import { ChildProcess } from \"effect/process\"\n *\n * // Template literal form\n * const cmd1 = ChildProcess.make`echo \"hello\"`\n *\n * // With options\n * const cmd2 = ChildProcess.make({ cwd: \"/tmp\" })`ls -la`\n *\n * // Array form\n * const cmd3 = ChildProcess.make(\"git\", [\"status\"])\n *\n * const result = [cmd1.command, cmd2.options.cwd, cmd3.args[0]] // => [\"echo\", \"/tmp\", \"status\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = function make(...args) {\n // Template literal form: make`command`\n if (isTemplateString(args[0])) {\n const [templates, ...expressions] = args;\n const tokens = parseTemplates(templates, expressions);\n return makeStandardCommand(tokens[0] ?? \"\", tokens.slice(1), {});\n }\n // Options form: make({ cwd: \"/tmp\" })`command`\n if (typeof args[0] === \"object\" && !Array.isArray(args[0]) && !isTemplateString(args[0])) {\n const options = args[0];\n return function (templates, ...expressions) {\n const tokens = parseTemplates(templates, expressions);\n return makeStandardCommand(tokens[0] ?? \"\", tokens.slice(1), options);\n };\n }\n // Standard form without arguments: make(\"command\", options?)\n if (typeof args[0] === \"string\" && !Array.isArray(args[1])) {\n const [command, options = {}] = args;\n return makeStandardCommand(command, [], options);\n }\n // Standard form with arguments: make(\"command\", [\"arg1\", \"arg2\"], options?)\n const [command, cmdArgs = [], options = {}] = args;\n return makeStandardCommand(command, cmdArgs, options);\n};\n/**\n * Pipes the output of one command to the input of another.\n *\n * **Details**\n *\n * By default, pipes `stdout` from the source to `stdin` of the destination.\n * Use the `options` parameter to customize which streams are connected.\n *\n * **Example** (Piping command output)\n *\n * ```ts import.meta.vitest\n * import { ChildProcess } from \"effect/process\"\n *\n * // Pipe stdout (default)\n * const pipeline1 = ChildProcess.make`cat file.txt`.pipe(\n * ChildProcess.pipeTo(ChildProcess.make`grep pattern`)\n * )\n *\n * // Pipe stderr instead of stdout\n * const pipeline2 = ChildProcess.make`my-program`.pipe(\n * ChildProcess.pipeTo(ChildProcess.make`grep error`, { from: \"stderr\" })\n * )\n *\n * // Pipe combined stdout and stderr\n * const pipeline3 = ChildProcess.make`my-program`.pipe(\n * ChildProcess.pipeTo(ChildProcess.make`tee output.log`, { from: \"all\" })\n * )\n *\n * const result = [pipeline1._tag, pipeline2.options.from, pipeline3.options.from]\n * result // => [\"PipedCommand\", \"stderr\", \"all\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const pipeTo = /*#__PURE__*/dual(args => isCommand(args[0]) && isCommand(args[1]), (self, that, options) => makePipedCommand(self, that, options ?? {}));\n/**\n * Prepends another command to a command.\n *\n * **Details**\n *\n * For pipelines, only the leftmost command is prefixed.\n *\n * **Example** (Prefixing commands)\n *\n * ```ts import.meta.vitest\n * import { ChildProcess } from \"effect/process\"\n *\n * const command = ChildProcess.make`echo \"foo\"`\n *\n * const prefixed = command.pipe(\n * ChildProcess.prefix`time`\n * )\n *\n * // now prefixed will execute `time echo \"foo\"`\n * const result = prefixed._tag === \"StandardCommand\" ? `${prefixed.command} ${prefixed.args[0]}` : prefixed._tag\n * result // => \"time echo\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const prefix = function prefix(...args) {\n if (isCommand(args[0]) && args.length > 1) {\n const [self, ...rest] = args;\n const prefixSpec = parsePrefixArgs(rest);\n return applyPrefix(self, prefixSpec);\n }\n const prefixSpec = parsePrefixArgs(args);\n return self => applyPrefix(self, prefixSpec);\n};\nconst parsePrefixArgs = args => {\n if (isTemplateString(args[0])) {\n const [templates, ...expressions] = args;\n const tokens = parseTemplates(templates, expressions);\n return {\n command: tokens[0] ?? \"\",\n args: tokens.slice(1)\n };\n }\n const [command, cmdArgs = []] = args;\n return {\n command,\n args: cmdArgs\n };\n};\nconst applyPrefix = (self, prefixSpec) => {\n switch (self._tag) {\n case \"StandardCommand\":\n {\n return makeStandardCommand(prefixSpec.command, [...prefixSpec.args, self.command, ...self.args], self.options);\n }\n case \"PipedCommand\":\n {\n return makePipedCommand(applyPrefix(self.left, prefixSpec), self.right, self.options);\n }\n }\n};\n/**\n * Sets the current working directory for a command.\n *\n * **Details**\n *\n * For pipelines, applies to each command in the pipeline.\n *\n * **Example** (Setting command working directories)\n *\n * ```ts import.meta.vitest\n * import { ChildProcess } from \"effect/process\"\n *\n * const cmd = ChildProcess.make`ls -la`.pipe(\n * ChildProcess.setCwd(\"/tmp\")\n * )\n * const result = cmd._tag === \"StandardCommand\" && cmd.options.cwd // => \"/tmp\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setCwd = /*#__PURE__*/dual(2, (self, cwd) => {\n switch (self._tag) {\n case \"StandardCommand\":\n {\n return makeStandardCommand(self.command, self.args, {\n ...self.options,\n cwd\n });\n }\n case \"PipedCommand\":\n {\n return makePipedCommand(setCwd(self.left, cwd), setCwd(self.right, cwd), self.options);\n }\n }\n});\n/**\n * Adds environment variables to a command, merging them with any existing\n * command environment and overriding duplicate keys.\n *\n * **Details**\n *\n * For pipelines, applies to each command in the pipeline.\n *\n * **Example** (Setting command environment variables)\n *\n * ```ts import.meta.vitest\n * import { ChildProcess } from \"effect/process\"\n *\n * const cmd = ChildProcess.make`node script.js`.pipe(\n * ChildProcess.setEnv({ NODE_ENV: \"test\" })\n * )\n * const result = cmd._tag === \"StandardCommand\" && cmd.options.env?.NODE_ENV // => \"test\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setEnv = /*#__PURE__*/dual(2, (self, env) => {\n switch (self._tag) {\n case \"StandardCommand\":\n {\n const nextEnv = self.options.env === undefined ? env : {\n ...self.options.env,\n ...env\n };\n return makeStandardCommand(self.command, self.args, {\n ...self.options,\n env: nextEnv\n });\n }\n case \"PipedCommand\":\n {\n return makePipedCommand(setEnv(self.left, env), setEnv(self.right, env), self.options);\n }\n }\n});\nconst isTemplateString = u => Array.isArray(u) && \"raw\" in u && Array.isArray(u.raw);\n// =============================================================================\n// Utilities\n// =============================================================================\n/**\n * Parses an fd name like \"fd3\" to its numeric index.\n * Returns undefined if the name is invalid.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const parseFdName = name => {\n const match = /^fd(\\d+)$/.exec(name);\n if (match === null) return undefined;\n const fd = parseInt(match[1], 10);\n return fd >= 3 ? fd : undefined;\n};\n/**\n * Create an fd name from its numeric index.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const fdName = fd => `fd${fd}`;\n// =============================================================================\n// Template Parsing\n// =============================================================================\nconst parseTemplates = (templates, expressions) => {\n let tokens = [];\n for (const [index, template] of templates.entries()) {\n tokens = parseTemplate(templates, expressions, tokens, template, index);\n }\n return tokens;\n};\nconst parseTemplate = (templates, expressions, prevTokens, template, index) => {\n const rawTemplate = templates.raw[index];\n if (rawTemplate === undefined) {\n throw new Error(`Invalid backslash sequence: ${templates.raw[index]}`);\n }\n const {\n hasLeadingWhitespace,\n hasTrailingWhitespace,\n tokens\n } = splitByWhitespaces(template, rawTemplate);\n const nextTokens = concatTokens(prevTokens, tokens, hasLeadingWhitespace);\n if (index === expressions.length) {\n return nextTokens;\n }\n const expression = expressions[index];\n const expressionTokens = Array.isArray(expression) ? expression.map(expression => parseExpression(expression)) : [parseExpression(expression)];\n return concatTokens(nextTokens, expressionTokens, hasTrailingWhitespace);\n};\n/**\n * Convert valid expressions defined in a template string command (i.e. using\n * `${expression}` into strings.\n */\nconst parseExpression = expression => {\n const type = typeof expression;\n if (type === \"string\") {\n return expression; // Return strings directly\n }\n return String(expression); // Convert numbers to strings\n};\nconst DELIMITERS = /*#__PURE__*/new Set([\" \", \"\\t\", \"\\r\", \"\\n\"]);\n/**\n * Number of characters in backslash escape sequences: \\0 \\xXX or \\uXXXX\n * \\cX is allowed in RegExps but not in strings\n * Octal sequences are not allowed in strict mode\n */\nconst ESCAPE_LENGTH = {\n x: 3,\n u: 5\n};\n/**\n * Splits a template string by whitespace while also properly handling escape\n * sequences.\n *\n * As an example, let's review the following valid commands:\n *\n * ```ts\n * ChildProcess.exec`echo foo\\n bar`\n * // We should run `[\"echo\", \"foo\\n\", \"bar\"]`\n *\n * ChildProcess.exec`echo foo\n * bar`\n * // We should run `[\"echo\", \"foo\", \"bar]`\n * ```\n *\n * The problem is that when we evaluate the template string for both of the above\n * commands, we will end up with the same string \"echo foo\\n bar\".\n *\n * What we really want is to include the escaped character in the arguments for\n * the first command, since it was written explicitly by the user.\n *\n * This is why also having access to the raw template string is useful - in a\n * template string, there are two representations of the same string:\n * 1. `template` - The processed string (escape sequences are evaluated).\n * 2. `template.raw` - The raw string (escape sequences are literal).\n */\nconst splitByWhitespaces = (template, rawTemplate) => {\n if (rawTemplate.length === 0) {\n return {\n tokens: [],\n hasLeadingWhitespace: false,\n hasTrailingWhitespace: false\n };\n }\n const hasLeadingWhitespace = DELIMITERS.has(rawTemplate[0]);\n const tokens = [];\n // Given that escape sequences will have different lengths in the template\n // versus the raw template, we must maintain two indices:\n // - One for the index into the template string\n // - One for the index into the raw template string\n // We also maintain the current cursor position for where we are in the template\n let templateCursor = 0;\n for (let templateIndex = 0, rawIndex = 0; templateIndex < template.length; templateIndex += 1, rawIndex += 1) {\n // Use the raw template character to check for actual whitespace\n const rawCharacter = rawTemplate[rawIndex];\n if (DELIMITERS.has(rawCharacter)) {\n // Whitespace found, extract token from template if necessary\n if (templateCursor !== templateIndex) {\n tokens.push(template.slice(templateCursor, templateIndex));\n }\n // Advance the template start index to the current position\n templateCursor = templateIndex + 1;\n } else if (rawCharacter === \"\\\\\") {\n // Escape sequence detected, check the next raw character\n const nextRawCharacter = rawTemplate[rawIndex + 1];\n if (nextRawCharacter === \"\\n\") {\n // Handle `\\` character followed by a newline (i.e. a line continuation) by:\n // - Reversing the template index (backslash-newline is erased in template)\n // - Advancing the raw template index past the line continuation\n templateIndex -= 1;\n rawIndex += 1;\n } else if (nextRawCharacter === \"u\" && rawTemplate[rawIndex + 2] === \"{\") {\n // Handle variable-length unicode escape sequences (i.e. `\\u{1F600}`) by:\n // - Advancing the template index an extra code unit for astral code points\n // - Advancing the raw template index past the unicode escape sequence\n const end = rawTemplate.indexOf(\"}\", rawIndex + 3);\n if (parseInt(rawTemplate.slice(rawIndex + 3, end), 16) > 0xffff) {\n templateIndex += 1;\n }\n rawIndex = end;\n } else {\n // Advance raw template index past fixed-length escape sequences:\n // - \\n → 2 chars (backslash + n)\n // - \\t → 2 chars (backslash + t)\n // - \\xHH → 4 chars (backslash + x + H + H)\n // - \\uHHHH → 6 chars (backslash + u + H + H + H + H)\n rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;\n }\n }\n }\n // Trailing whitespace only exists if the template cursor is equivalent to the\n // length of the template\n const hasTrailingWhitespace = templateCursor === template.length;\n // If we did not end with trailing whitespace, ensure the final token is added\n if (!hasTrailingWhitespace) {\n tokens.push(template.slice(templateCursor));\n }\n return {\n tokens,\n hasLeadingWhitespace,\n hasTrailingWhitespace\n };\n};\n/**\n * Concatenates two separate sets of string tokens together.\n *\n * If either set is empty or `isSeparated=false`, the last element of `prevTokens`\n * and the first element of `nextTokens` will be joined into a single token.\n */\nconst concatTokens = (prevTokens, nextTokens, isSeparated) => isSeparated || prevTokens.length === 0 || nextTokens.length === 0\n// Keep the previous and next tokens separate from one another\n? [...prevTokens, ...nextTokens]\n// Join the last token from the previous set and the first token from the next set\n: [...prevTokens.slice(0, -1), `${prevTokens.at(-1)}${nextTokens.at(0)}`, ...nextTokens.slice(1)];\n//# sourceMappingURL=ChildProcess.js.map","export const buildSpawnOptions = (options, base, platform) => {\n const detached = options.detached ?? platform !== \"win32\";\n return {\n ...base,\n detached,\n shell: options.shell,\n windowsHide: options.windowsHide ?? !detached\n };\n};\n//# sourceMappingURL=nodeChildProcessSpawner.js.map","import * as PlatformError from \"effect/PlatformError\";\n/** @internal */\nexport const handleErrnoException = (module, method) => (err, [path]) => {\n let reason = \"Unknown\";\n switch (err.code) {\n case \"ENOENT\":\n reason = \"NotFound\";\n break;\n case \"EACCES\":\n reason = \"PermissionDenied\";\n break;\n case \"EEXIST\":\n reason = \"AlreadyExists\";\n break;\n case \"EISDIR\":\n reason = \"BadResource\";\n break;\n case \"ENOTDIR\":\n reason = \"BadResource\";\n break;\n case \"EBUSY\":\n reason = \"Busy\";\n break;\n case \"ELOOP\":\n reason = \"BadResource\";\n break;\n }\n return PlatformError.systemError({\n _tag: reason,\n module,\n method,\n pathOrDescriptor: path,\n syscall: err.syscall,\n cause: err\n });\n};\n//# sourceMappingURL=utils.js.map","import * as Cause from \"effect/Cause\";\nimport * as Channel from \"effect/Channel\";\nimport * as Effect from \"effect/Effect\";\nimport { identity } from \"effect/Function\";\nimport * as Pull from \"effect/Pull\";\nimport * as Sink from \"effect/Sink\";\n/**\n * Creates a `Sink` that writes chunks to a Node writable stream, respecting\n * backpressure, mapping writable errors with `onError`, and ending the stream\n * on completion unless `endOnDone` is `false`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromWritable = options => Sink.fromChannel(Channel.mapDone(fromWritableChannel(options), _ => [_]));\n/**\n * Creates a `Channel` that pulls chunks from upstream and writes them to a\n * Node writable stream, respecting backpressure and optionally ending the\n * writable when upstream is done.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromWritableChannel = options => Channel.fromTransform(pull => {\n const writable = options.evaluate();\n return Effect.succeed(pullIntoWritable({\n ...options,\n writable,\n pull\n }));\n});\n/**\n * Writes Effect chunks into a Node writable stream.\n *\n * **When to use**\n *\n * Use to implement custom Node stream adapters that already have an upstream\n * pull and need direct control over a writable stream.\n *\n * **Details**\n *\n * The loop waits for `drain` when needed, fails on writable errors, and ends\n * the writable on upstream completion unless `endOnDone` is `false`.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const pullIntoWritable = options => options.pull.pipe(Effect.flatMap(chunk => {\n let i = 0;\n return Effect.callback(resume => {\n let cancelled = false;\n const loop = () => {\n for (; i < chunk.length;) {\n if (cancelled) {\n return;\n }\n const success = options.writable.write(chunk[i++], options.encoding);\n if (!success) {\n if (!cancelled) {\n options.writable.once(\"drain\", loop);\n }\n return;\n }\n }\n if (!cancelled) {\n resume(Effect.void);\n }\n };\n loop();\n return Effect.sync(() => {\n cancelled = true;\n options.writable.off(\"drain\", loop);\n });\n });\n}), Effect.forever({\n disableYield: true\n}), options.endOnDone !== false ? Pull.catchDone(_ => {\n if (\"closed\" in options.writable && options.writable.closed) {\n return Cause.done(_);\n }\n return Effect.callback(resume => {\n const onFinish = () => resume(Cause.done(_));\n options.writable.once(\"finish\", onFinish);\n options.writable.end();\n return Effect.sync(() => {\n options.writable.off(\"finish\", onFinish);\n });\n });\n}) : identity, Effect.raceFirst(Effect.callback(resume => {\n const onError = error => resume(Effect.fail(options.onError(error)));\n options.writable.once(\"error\", onError);\n return Effect.sync(() => {\n options.writable.off(\"error\", onError);\n });\n})));\n//# sourceMappingURL=NodeSink.js.map","/**\n * Adapters between Node streams and Effect streams, channels, and readables.\n *\n * This module is the stream boundary for Node APIs. It wraps `Readable` and\n * `Duplex` values as Effect `Stream`s and `Channel`s, pipes Effect streams\n * through Node duplex streams, exposes an Effect `Stream` back to Node as a\n * `Readable`, and collects readable payloads into strings, array buffers, or\n * `Uint8Array`s with optional byte limits.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Arr from \"effect/Array\";\nimport * as ByteSize from \"effect/ByteSize\";\nimport * as Cause from \"effect/Cause\";\nimport * as Channel from \"effect/Channel\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport { dual } from \"effect/Function\";\nimport * as Latch from \"effect/Latch\";\nimport * as MutableRef from \"effect/MutableRef\";\nimport * as Pull from \"effect/Pull\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport { Readable } from \"node:stream\";\nimport { pullIntoWritable } from \"./NodeSink.js\";\n/**\n * Converts a Node readable stream into an Effect `Stream`, reading chunks with\n * an optional chunk size, mapping stream errors with `onError`, and destroying\n * the readable on completion unless `closeOnDone` is `false`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromReadable = options => Stream.fromChannel(fromReadableChannel(options));\n/**\n * Creates a `Channel` that pulls chunks from a Node readable stream, mapping\n * errors with `onError` and destroying the readable on completion unless\n * `closeOnDone` is `false`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromReadableChannel = options => Channel.fromTransform((_, scope) => readableToPullUnsafe({\n scope,\n readable: options.evaluate(),\n onError: options.onError ?? defaultOnError,\n chunkSize: options.chunkSize,\n closeOnDone: options.closeOnDone\n}));\n/**\n * Creates a `Channel` over a Node `Duplex`, writing upstream chunks with\n * backpressure while emitting chunks read from the duplex and optionally ending\n * the writable side when upstream completes.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromDuplex = options => Channel.fromTransform((upstream, scope) => {\n const duplex = options.evaluate();\n const exit = MutableRef.make(undefined);\n const latch = Latch.makeUnsafe(false);\n return pullIntoWritable({\n pull: upstream,\n writable: duplex,\n onError: options.onError ?? defaultOnError,\n endOnDone: options.endOnDone,\n encoding: options.encoding\n }).pipe(Effect.catchCause(cause => {\n if (Pull.isDoneCause(cause)) return Effect.void;\n exit.current = Exit.failCause(cause);\n latch.openUnsafe();\n return Effect.void;\n }), Effect.forkIn(scope), Effect.flatMap(() => readableToPullUnsafe({\n scope,\n exit,\n latch,\n readable: duplex,\n onError: options.onError ?? defaultOnError,\n chunkSize: options.chunkSize\n })));\n});\n/**\n * Pipes an Effect `Stream` through a Node `Duplex`, writing the stream's\n * chunks to the duplex and emitting chunks read back from it.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const pipeThroughDuplex = /*#__PURE__*/dual(2, (self, options) => Stream.pipeThroughChannelOrFail(self, fromDuplex(options)));\n/**\n * Pipes a stream of strings or bytes through a Node `Duplex` using default\n * options and `Cause.UnknownError` for stream failures.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const pipeThroughSimple = /*#__PURE__*/dual(2, (self, duplex) => pipeThroughDuplex(self, {\n evaluate: duplex\n}));\n/**\n * Converts an Effect `Stream` into a Node `Readable`, using the caller's\n * Effect context to run the stream and destroying the readable if the stream\n * fails.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toReadable = stream => Effect.map(Effect.context(), context => new StreamAdapter(context, stream));\n/**\n * Converts a service-free Effect `Stream` into a Node `Readable` using an\n * empty Effect context.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toReadableNever = stream => new StreamAdapter(Context.empty(), stream);\n/**\n * Consumes a Node readable stream into a string using the selected encoding,\n * failing through `onError` on stream errors or when `maxBytes` is exceeded\n * and destroying the stream on interruption or failure.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toString = (readable, options) => {\n const maxBytesNumber = toMaxBytes(options?.maxBytes);\n const onError = options?.onError ?? defaultOnError;\n const encoding = options?.encoding ?? \"utf8\";\n return Effect.callback(resume => {\n const stream = readable();\n stream.setEncoding(encoding);\n stream.once(\"error\", err => {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n resume(Effect.fail(onError(err)));\n });\n let string = \"\";\n let bytes = 0;\n stream.once(\"end\", () => {\n resume(Effect.succeed(string));\n });\n stream.on(\"data\", chunk => {\n string += chunk;\n bytes += Buffer.byteLength(chunk);\n if (maxBytesNumber !== undefined && bytes > maxBytesNumber) {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n resume(Effect.fail(onError(new Error(\"maxBytes exceeded\"))));\n }\n });\n return Effect.sync(() => {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n });\n });\n};\n/**\n * Consumes a Node readable stream into an `ArrayBuffer`, failing through\n * `onError` on stream errors or when `maxBytes` is exceeded and destroying the\n * stream on interruption or failure.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toArrayBuffer = (readable, options) => {\n const maxBytesNumber = toMaxBytes(options?.maxBytes);\n const onError = options?.onError ?? defaultOnError;\n return Effect.callback(resume => {\n const stream = readable();\n const buffers = [];\n let bytes = 0;\n stream.once(\"error\", err => {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n resume(Effect.fail(onError(err)));\n });\n stream.once(\"end\", () => {\n const buffer = buffers.length === 1 ? buffers[0] : Buffer.concat(buffers);\n if (buffer.byteOffset === 0 && buffer.buffer.byteLength === buffer.byteLength) {\n return resume(Effect.succeed(buffer.buffer));\n }\n resume(Effect.succeed(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)));\n });\n stream.on(\"data\", chunk => {\n buffers.push(chunk);\n bytes += chunk.length;\n if (maxBytesNumber !== undefined && bytes > maxBytesNumber) {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n resume(Effect.fail(onError(new Error(\"maxBytes exceeded\"))));\n }\n });\n return Effect.sync(() => {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n });\n });\n};\n/**\n * Consumes a Node readable stream into a `Uint8Array`, using the same error\n * mapping and `maxBytes` handling as `toArrayBuffer`.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toUint8Array = (readable, options) => Effect.map(toArrayBuffer(readable, options), buffer => new Uint8Array(buffer));\n// ----------------------------------------------------------------------------\n// internal\n// ----------------------------------------------------------------------------\nconst readableToPullUnsafe = options => {\n const readable = options.readable;\n const closeOnDone = options.closeOnDone ?? true;\n const exit = options.exit ?? MutableRef.make(undefined);\n const latch = options.latch ?? Latch.makeUnsafe(false);\n function onReadable() {\n latch.openUnsafe();\n }\n function onError(error) {\n exit.current = Exit.fail(options.onError(error));\n latch.openUnsafe();\n }\n function onEnd() {\n exit.current = Exit.fail(Cause.Done());\n latch.openUnsafe();\n }\n readable.on(\"readable\", onReadable);\n readable.once(\"error\", onError);\n readable.once(\"end\", onEnd);\n const pull = Effect.suspend(function loop() {\n let item = options.readable.read(options.chunkSize);\n if (item === null) {\n if (exit.current) {\n return exit.current;\n }\n if (readable.readableEnded) {\n return Effect.fail(Cause.Done());\n }\n latch.closeUnsafe();\n return Effect.flatMap(latch.await, loop);\n }\n const chunk = Arr.of(item);\n while (true) {\n item = options.readable.read(options.chunkSize);\n if (item === null) break;\n chunk.push(item);\n }\n return Effect.succeed(chunk);\n });\n return Effect.as(Scope.addFinalizer(options.scope, Effect.sync(() => {\n readable.off(\"readable\", onReadable);\n readable.off(\"error\", onError);\n readable.off(\"end\", onEnd);\n if (closeOnDone && \"closed\" in options.readable && !options.readable.closed) {\n options.readable.destroy();\n }\n })), pull);\n};\nclass StreamAdapter extends Readable {\n readLatch;\n fiber = undefined;\n constructor(context, stream) {\n super({});\n this.readLatch = Latch.makeUnsafe(false);\n this.fiber = Stream.runForEachArray(stream, chunk => this.readLatch.whenOpen(Effect.sync(() => {\n this.readLatch.closeUnsafe();\n for (let i = 0; i < chunk.length; i++) {\n const item = chunk[i];\n if (typeof item === \"string\") {\n this.push(item, \"utf8\");\n } else {\n this.push(item);\n }\n }\n }))).pipe(this.readLatch.whenOpen, Effect.provideContext(context), Effect.runFork);\n this.fiber.addObserver(exit => {\n this.fiber = undefined;\n if (Exit.isSuccess(exit)) {\n this.push(null);\n } else {\n this.destroy(Cause.squash(exit.cause));\n }\n });\n }\n _read(_size) {\n this.readLatch.openUnsafe();\n }\n _destroy(error, callback) {\n if (!this.fiber) {\n return callback(error);\n }\n Effect.runFork(Fiber.interrupt(this.fiber)).addObserver(exit => {\n callback(exit._tag === \"Failure\" ? Cause.squash(exit.cause) : error);\n });\n }\n}\nconst defaultOnError = error => new Cause.UnknownError(error);\nconst toMaxBytes = maxBytes => maxBytes === undefined || maxBytes === Infinity ? undefined : Number(ByteSize.fromInputUnsafe(maxBytes));\n//# sourceMappingURL=NodeStream.js.map","import * as Deferred from \"effect/Deferred\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as ChildProcess from \"effect/process/ChildProcess\";\nimport { ChildProcessSpawner, ExitCode, make as makeSpawner, makeHandle, ProcessId } from \"effect/process/ChildProcessSpawner\";\nimport * as Sink from \"effect/Sink\";\nimport * as Stream from \"effect/Stream\";\nimport * as NodeChildProcess from \"node:child_process\";\nimport { PassThrough } from \"node:stream\";\nimport { buildSpawnOptions } from \"./internal/nodeChildProcessSpawner.js\";\nimport { handleErrnoException } from \"./internal/utils.js\";\nimport * as NodeSink from \"./NodeSink.js\";\nimport * as NodeStream from \"./NodeStream.js\";\nconst toError = error => error instanceof globalThis.Error ? error : new globalThis.Error(String(error));\nconst toPlatformError = (method, error, command) => {\n const {\n commands\n } = flattenCommand(command);\n const commandStr = commands.reduce((acc, curr) => {\n const cmd = `${curr.command} ${curr.args.join(\" \")}`;\n return acc.length === 0 ? cmd : `${acc} | ${cmd}`;\n }, \"\");\n return handleErrnoException(\"ChildProcess\", method)(error, [commandStr]);\n};\nconst processGroupGraceMillis = 1_000;\nconst processGroupPollIntervalMillis = 10;\n// Buffered writes can fail after the sink has been interrupted and removed its\n// error listener. Keep a fallback until close, without replacing the sink\n// listener that propagates errors while it is active.\nconst handleInputErrors = writable => {\n const onError = () => {};\n writable.on(\"error\", onError);\n writable.once(\"close\", () => writable.off(\"error\", onError));\n};\n/** The leader has not exited, or a member of its process group still exists. */\nconst isProcessAlive = (childProcess, exitSignal) => {\n if (!Deferred.isDoneUnsafe(exitSignal)) {\n return true;\n }\n if (globalThis.process.platform === \"win32\") {\n return false;\n }\n try {\n globalThis.process.kill(-childProcess.pid, 0);\n return true;\n } catch {\n return false;\n }\n};\nconst taskkill = (childProcess, onExit = () => {}) => {\n // After the leader exits, its PID may be reused by an unrelated process.\n if (childProcess.exitCode !== null || childProcess.signalCode !== null) {\n onExit(null);\n return;\n }\n NodeChildProcess.execFile(\"taskkill\", [\"/pid\", String(childProcess.pid), \"/T\", \"/F\"], {\n windowsHide: true\n }, onExit);\n};\nconst make = /*#__PURE__*/Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const resolveWorkingDirectory = Effect.fnUntraced(function* (options) {\n if (Predicate.isUndefined(options.cwd)) return undefined;\n // Validate that the specified directory is accessible\n yield* fs.access(options.cwd);\n return path.resolve(options.cwd);\n });\n const resolveEnvironment = options => {\n return options.extendEnv ? {\n ...globalThis.process.env,\n ...options.env\n } : options.env;\n };\n const inputToStdioOption = input => Stream.isStream(input) ? \"pipe\" : input;\n const outputToStdioOption = input => Sink.isSink(input) ? \"pipe\" : input;\n const resolveStdinOption = options => {\n const defaultConfig = {\n stream: \"pipe\",\n encoding: \"utf-8\",\n endOnDone: true\n };\n if (Predicate.isUndefined(options.stdin)) {\n return defaultConfig;\n }\n if (typeof options.stdin === \"string\") {\n return {\n ...defaultConfig,\n stream: options.stdin\n };\n }\n if (Stream.isStream(options.stdin)) {\n return {\n ...defaultConfig,\n stream: options.stdin\n };\n }\n return {\n stream: options.stdin.stream,\n encoding: options.stdin.encoding ?? defaultConfig.encoding,\n endOnDone: options.stdin.endOnDone ?? defaultConfig.endOnDone\n };\n };\n const resolveOutputOption = (options, streamName) => {\n const option = options[streamName];\n if (Predicate.isUndefined(option)) {\n return {\n stream: \"pipe\"\n };\n }\n if (typeof option === \"string\") {\n return {\n stream: option\n };\n }\n if (Sink.isSink(option)) {\n return {\n stream: option\n };\n }\n return {\n stream: option.stream\n };\n };\n const resolveAdditionalFds = options => {\n if (Predicate.isUndefined(options.additionalFds)) {\n return [];\n }\n const result = [];\n for (const [name, config] of Object.entries(options.additionalFds)) {\n const fd = ChildProcess.parseFdName(name);\n if (Predicate.isNotUndefined(fd)) {\n result.push({\n fd,\n config\n });\n }\n }\n // Sort by fd number to ensure correct ordering\n return result.sort((a, b) => a.fd - b.fd);\n };\n const buildStdioArray = (stdinConfig, stdoutConfig, stderrConfig, additionalFds) => {\n const stdio = [inputToStdioOption(stdinConfig.stream), outputToStdioOption(stdoutConfig.stream), outputToStdioOption(stderrConfig.stream)];\n if (additionalFds.length === 0) {\n return stdio;\n }\n // Find the maximum fd number to size the array correctly\n const maxFd = additionalFds.reduce((max, {\n fd\n }) => Math.max(max, fd), 2);\n // Fill gaps with \"ignore\"\n for (let i = 3; i <= maxFd; i++) {\n stdio[i] = \"ignore\";\n }\n // Set up additional fds as \"pipe\"\n for (const {\n fd\n } of additionalFds) {\n stdio[fd] = \"pipe\";\n }\n return stdio;\n };\n const setupAdditionalFds = Effect.fnUntraced(function* (command, childProcess, additionalFds) {\n if (additionalFds.length === 0) {\n return {\n getInputFd: () => Sink.drain,\n getOutputFd: () => Stream.empty\n };\n }\n const inputSinks = new Map();\n const outputStreams = new Map();\n for (const {\n config,\n fd\n } of additionalFds) {\n const nodeStream = childProcess.stdio[fd];\n switch (config.type) {\n case \"input\":\n {\n // Create a sink to write to for input file descriptors\n let sink = Sink.drain;\n if (nodeStream && \"write\" in nodeStream) {\n handleInputErrors(nodeStream);\n sink = NodeSink.fromWritable({\n evaluate: () => nodeStream,\n onError: error => toPlatformError(`fromWritable(fd${fd})`, toError(error), command)\n });\n }\n // If user provided a stream, pipe it into the sink\n if (config.stream) {\n yield* Effect.forkScoped(Stream.run(config.stream, sink));\n }\n inputSinks.set(fd, sink);\n break;\n }\n case \"output\":\n {\n // Create a stream to read from for output file descriptors\n let stream = Stream.empty;\n if (nodeStream && \"read\" in nodeStream) {\n const passThrough = new PassThrough();\n nodeStream.on(\"error\", error => passThrough.destroy(error));\n nodeStream.pipe(passThrough);\n stream = NodeStream.fromReadable({\n evaluate: () => passThrough,\n onError: error => toPlatformError(`fromReadable(fd${fd})`, toError(error), command)\n });\n }\n // If user provided a sink, transduce the stream through it\n if (config.sink) {\n stream = Stream.transduce(stream, config.sink);\n }\n outputStreams.set(fd, stream);\n break;\n }\n }\n }\n return {\n getInputFd: fd => inputSinks.get(fd) ?? Sink.drain,\n getOutputFd: fd => outputStreams.get(fd) ?? Stream.empty\n };\n });\n const setupChildStdin = (command, childProcess, config) => Effect.suspend(() => {\n // If the child process has a standard input stream, connect it to the\n // sink that will attached to the process handle\n let sink = Sink.drain;\n if (Predicate.isNotNull(childProcess.stdin)) {\n handleInputErrors(childProcess.stdin);\n sink = NodeSink.fromWritable({\n evaluate: () => childProcess.stdin,\n onError: error => toPlatformError(\"fromWritable(stdin)\", toError(error), command),\n endOnDone: config.endOnDone,\n encoding: config.encoding\n });\n }\n // If the user provided a `Stream`, run it into the stdin sink\n if (Stream.isStream(config.stream)) {\n return Effect.as(Effect.forkScoped(Stream.run(config.stream, sink)), sink);\n }\n return Effect.succeed(sink);\n });\n const setupChildOutputStreams = (command, childProcess, stdoutConfig, stderrConfig) => {\n let stdout = childProcess.stdout ? (() => {\n const passThrough = new PassThrough();\n childProcess.stdout.on(\"error\", error => passThrough.destroy(error));\n childProcess.stdout.pipe(passThrough);\n return NodeStream.fromReadable({\n evaluate: () => passThrough,\n onError: error => toPlatformError(\"fromReadable(stdout)\", toError(error), command)\n });\n })() : Stream.empty;\n let stderr = childProcess.stderr ? (() => {\n const passThrough = new PassThrough();\n childProcess.stderr.on(\"error\", error => passThrough.destroy(error));\n childProcess.stderr.pipe(passThrough);\n return NodeStream.fromReadable({\n evaluate: () => passThrough,\n onError: error => toPlatformError(\"fromReadable(stderr)\", toError(error), command)\n });\n })() : Stream.empty;\n if (Sink.isSink(stdoutConfig.stream)) {\n stdout = Stream.transduce(stdout, stdoutConfig.stream);\n }\n if (Sink.isSink(stderrConfig.stream)) {\n stderr = Stream.transduce(stderr, stderrConfig.stream);\n }\n const all = Stream.merge(stdout, stderr);\n return {\n stdout,\n stderr,\n all\n };\n };\n const spawn = (command, spawnOptions) => Effect.callback(resume => {\n const deferred = Deferred.makeUnsafe();\n const handle = NodeChildProcess.spawn(command.command, command.args, spawnOptions);\n handle.on(\"error\", error => {\n resume(Effect.fail(toPlatformError(\"spawn\", error, command)));\n });\n handle.on(\"exit\", (...args) => {\n Deferred.doneUnsafe(deferred, Exit.succeed(args));\n });\n handle.on(\"spawn\", () => {\n resume(Effect.succeed([handle, deferred]));\n });\n return Effect.sync(() => {\n handle.kill(\"SIGTERM\");\n });\n });\n const killProcessGroup = (command, childProcess, signal) => {\n if (globalThis.process.platform === \"win32\") {\n return Effect.callback(resume => {\n taskkill(childProcess, error => {\n if (error) {\n resume(Effect.fail(toPlatformError(\"kill\", toError(error), command)));\n } else {\n resume(Effect.void);\n }\n });\n });\n }\n return Effect.try({\n try: () => {\n globalThis.process.kill(-childProcess.pid, signal);\n },\n catch: error => toPlatformError(\"kill\", toError(error), command)\n });\n };\n const killProcessGroupOnExit = (childProcess, signal) => {\n if (globalThis.process.platform === \"win32\") {\n // ignore errors during best-effort cleanup\n taskkill(childProcess);\n return;\n }\n try {\n globalThis.process.kill(-childProcess.pid, signal);\n } catch {\n // ignore errors during best-effort cleanup\n }\n };\n const killProcess = (command, childProcess, signal) => Effect.suspend(() => {\n const killed = childProcess.kill(signal);\n if (!killed) {\n const error = new globalThis.Error(\"Failed to kill child process\");\n return Effect.fail(toPlatformError(\"kill\", error, command));\n }\n return Effect.void;\n });\n /** Waits for the leader and its process group, bounded by native time. */\n const awaitProcessExit = (childProcess, exitSignal, timeoutMillis) => Effect.callback(resume => {\n const deadline = Date.now() + timeoutMillis;\n let timer;\n const stop = () => {\n clearTimeout(timer);\n childProcess.removeListener(\"exit\", poll);\n };\n const poll = () => {\n clearTimeout(timer);\n if (Date.now() >= deadline || !isProcessAlive(childProcess, exitSignal)) {\n stop();\n resume(Effect.void);\n return;\n }\n timer = setTimeout(poll, processGroupPollIntervalMillis);\n };\n // spawn's exit listener completes exitSignal before this listener runs\n childProcess.on(\"exit\", poll);\n poll();\n return Effect.sync(stop);\n });\n const terminateProcessGroup = Effect.fnUntraced(function* (command, childProcess, exitSignal, options) {\n const signalGroup = signal => killProcessGroup(command, childProcess, signal).pipe(Effect.catch(() => killProcess(command, childProcess, signal)));\n yield* signalGroup(options?.killSignal ?? \"SIGTERM\");\n if (Predicate.isUndefined(options?.forceKillAfter)) {\n yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis);\n } else {\n yield* awaitProcessExit(childProcess, exitSignal, Duration.toMillis(options.forceKillAfter));\n if (isProcessAlive(childProcess, exitSignal)) {\n yield* signalGroup(\"SIGKILL\");\n yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis);\n }\n }\n yield* Deferred.await(exitSignal);\n });\n /**\n * Get the appropriate source stream from a process handle based on the\n * `from` pipe option.\n */\n const getSourceStream = (handle, from) => {\n const fromOption = from ?? \"stdout\";\n switch (fromOption) {\n case \"stdout\":\n return handle.stdout;\n case \"stderr\":\n return handle.stderr;\n case \"all\":\n return handle.all;\n default:\n {\n // Handle fd3, fd4, etc.\n const fd = ChildProcess.parseFdName(fromOption);\n if (Predicate.isNotUndefined(fd)) {\n return handle.getOutputFd(fd);\n }\n // Fallback to stdout for invalid fd names\n return handle.stdout;\n }\n }\n };\n const spawnCommand = Effect.fnUntraced(function* (cmd) {\n switch (cmd._tag) {\n case \"StandardCommand\":\n {\n const stdinConfig = resolveStdinOption(cmd.options);\n const stdoutConfig = resolveOutputOption(cmd.options, \"stdout\");\n const stderrConfig = resolveOutputOption(cmd.options, \"stderr\");\n const resolvedAdditionalFds = resolveAdditionalFds(cmd.options);\n let isReferenced = true;\n const cwd = yield* resolveWorkingDirectory(cmd.options);\n const env = resolveEnvironment(cmd.options);\n const stdio = buildStdioArray(stdinConfig, stdoutConfig, stderrConfig, resolvedAdditionalFds);\n const [childProcess, exitSignal] = yield* Effect.acquireRelease(spawn(cmd, buildSpawnOptions(cmd.options, {\n cwd,\n env,\n stdio\n }, process.platform)), Effect.fnUntraced(function* ([childProcess, exitSignal]) {\n const exited = yield* Deferred.isDone(exitSignal);\n if (exited) {\n const [code] = yield* Deferred.await(exitSignal);\n if (code !== 0 && Predicate.isNotNull(code)) {\n yield* Effect.ignore(terminateProcessGroup(cmd, childProcess, exitSignal, cmd.options));\n } else if (isReferenced && process.platform !== \"win32\" && cmd.options.detached !== false) {\n yield* Effect.ignore(terminateProcessGroup(cmd, childProcess, exitSignal, cmd.options));\n }\n return;\n }\n if (!isReferenced) {\n return;\n }\n yield* Effect.ignore(terminateProcessGroup(cmd, childProcess, exitSignal, cmd.options));\n }));\n const pid = ProcessId(childProcess.pid);\n childProcess.on(\"exit\", code => {\n if (code !== 0 && Predicate.isNotNull(code)) {\n killProcessGroupOnExit(childProcess, cmd.options.killSignal ?? \"SIGTERM\");\n }\n });\n const reref = Effect.sync(() => {\n if (!isReferenced) {\n childProcess.ref();\n isReferenced = true;\n }\n });\n const unref = Effect.sync(() => {\n if (isReferenced) {\n childProcess.unref();\n isReferenced = false;\n }\n return reref;\n });\n const stdin = yield* setupChildStdin(cmd, childProcess, stdinConfig);\n const {\n all,\n stderr,\n stdout\n } = setupChildOutputStreams(cmd, childProcess, stdoutConfig, stderrConfig);\n const {\n getInputFd,\n getOutputFd\n } = yield* setupAdditionalFds(cmd, childProcess, resolvedAdditionalFds);\n const isRunning = Effect.map(Deferred.isDone(exitSignal), done => !done);\n const exitCode = Effect.flatMap(Deferred.await(exitSignal), ([code, signal]) => {\n if (Predicate.isNotNull(code)) {\n return Effect.succeed(ExitCode(code));\n }\n // If code is `null`, then `signal` must be defined. See the NodeJS\n // documentation for the `\"exit\"` event on a `child_process`.\n // https://nodejs.org/api/child_process.html#child_process_event_exit\n const error = new globalThis.Error(`Process interrupted due to receipt of signal: '${signal}'`);\n return Effect.fail(toPlatformError(\"exitCode\", error, cmd));\n });\n const kill = options => terminateProcessGroup(cmd, childProcess, exitSignal, options);\n return makeHandle({\n pid,\n exitCode,\n isRunning,\n kill,\n stdin,\n stdout,\n stderr,\n all,\n getInputFd,\n getOutputFd,\n unref\n });\n }\n case \"PipedCommand\":\n {\n const {\n commands,\n pipeOptions\n } = flattenCommand(cmd);\n const [root, ...pipeline] = commands;\n const handles = [yield* spawnCommand(root)];\n for (let i = 0; i < pipeline.length; i++) {\n const command = pipeline[i];\n const options = pipeOptions[i] ?? {};\n const stdinConfig = resolveStdinOption(command.options);\n // Get the appropriate stream from the source based on `from` option\n const sourceStream = Stream.unwrap(Effect.succeed(getSourceStream(handles[handles.length - 1], options.from)));\n // Determine where to pipe: stdin or custom fd\n const toOption = options.to ?? \"stdin\";\n if (toOption === \"stdin\") {\n // Pipe to stdin (default behavior)\n handles.push(yield* spawnCommand(ChildProcess.make(command.command, command.args, {\n ...command.options,\n stdin: {\n ...stdinConfig,\n stream: sourceStream\n }\n })));\n } else {\n // Pipe to custom fd (fd3, fd4, etc.)\n const fd = ChildProcess.parseFdName(toOption);\n if (Predicate.isNotUndefined(fd)) {\n const fdName = ChildProcess.fdName(fd);\n const existingFds = command.options.additionalFds ?? {};\n handles.push(yield* spawnCommand(ChildProcess.make(command.command, command.args, {\n ...command.options,\n additionalFds: {\n ...existingFds,\n [fdName]: {\n type: \"input\",\n stream: sourceStream\n }\n }\n })));\n } else {\n // Invalid fd name, fall back to stdin\n handles.push(yield* spawnCommand(ChildProcess.make(command.command, command.args, {\n ...command.options,\n stdin: {\n ...stdinConfig,\n stream: sourceStream\n }\n })));\n }\n }\n }\n const handle = handles[handles.length - 1];\n const kill = options => Effect.forEach([...handles].reverse(), handle => Effect.ignore(handle.kill(options)), {\n discard: true\n });\n const unref = Effect.gen(function* () {\n const rerefs = [];\n for (const handle of handles) {\n rerefs.push(yield* handle.unref);\n }\n return Effect.forEach([...rerefs].reverse(), reref => reref, {\n discard: true\n });\n });\n return makeHandle({\n pid: handle.pid,\n exitCode: handle.exitCode,\n isRunning: handle.isRunning,\n kill,\n stdin: handles[0].stdin,\n stdout: handle.stdout,\n stderr: handle.stderr,\n all: handle.all,\n getInputFd: handle.getInputFd,\n getOutputFd: handle.getOutputFd,\n unref\n });\n }\n }\n });\n return makeSpawner(spawnCommand);\n});\n/**\n * Layer that provides the `NodeChildProcessSpawner` implementation.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.effect(ChildProcessSpawner, make);\n/**\n * Flattens a `Command` into an array of `StandardCommand`s along with pipe\n * options for each connection.\n *\n * @stability unstable\n * @category transforming\n * @since 4.0.0\n */\nexport const flattenCommand = command => {\n const commands = [];\n const pipeOptions = [];\n const flatten = cmd => {\n switch (cmd._tag) {\n case \"StandardCommand\":\n {\n commands.push(cmd);\n break;\n }\n case \"PipedCommand\":\n {\n // Recursively flatten left side first\n flatten(cmd.left);\n // Store the pipe options for this connection\n pipeOptions.push(cmd.options);\n // Then flatten right side\n flatten(cmd.right);\n break;\n }\n }\n };\n flatten(command);\n // The commands array is guaranteed to be non-empty since we always have at\n // least one command in the input. We validate this at runtime and return a\n // properly typed tuple.\n if (commands.length === 0) {\n // This should never happen given a valid Command input\n throw new Error(\"flattenCommand produced empty commands array\");\n }\n const [first, ...rest] = commands;\n const nonEmptyCommands = [first, ...rest];\n return {\n commands: nonEmptyCommands,\n pipeOptions\n };\n};\n//# sourceMappingURL=NodeChildProcessSpawner.js.map","/**\n * Node-compatible implementation of Effect's `Crypto` service.\n *\n * This module builds the service from `node:crypto`, using `randomBytes` for\n * random data and `createHash` for supported digest algorithms. It exports\n * `make` as the concrete service value and `layer` for providing it through\n * Effect context.\n *\n * @stability unstable\n * @since 1.0.0\n */\nimport * as EffectCrypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as NodeCrypto from \"node:crypto\";\nconst toHashAlgorithm = algorithm => {\n switch (algorithm) {\n case \"SHA-1\":\n return \"sha1\";\n case \"SHA-256\":\n return \"sha256\";\n case \"SHA-384\":\n return \"sha384\";\n case \"SHA-512\":\n return \"sha512\";\n }\n};\nconst digest = (algorithm, data) => Effect.try({\n try: () => Uint8Array.from(NodeCrypto.createHash(toHashAlgorithm(algorithm)).update(data).digest()),\n catch: cause => PlatformError.systemError({\n module: \"Crypto\",\n method: \"digest\",\n _tag: \"Unknown\",\n description: \"Could not compute digest\",\n cause\n })\n});\n/**\n * The default Node.js Crypto service implementation.\n *\n * @stability unstable\n * @category constructors\n * @since 1.0.0\n */\nexport const make = /*#__PURE__*/EffectCrypto.make({\n randomBytes: NodeCrypto.randomBytes,\n digest\n});\n/**\n * Layer that provides the Node.js Crypto service implementation.\n *\n * @stability unstable\n * @category layers\n * @since 1.0.0\n */\nexport const layer = /*#__PURE__*/Layer.succeed(EffectCrypto.Crypto, make);\n//# sourceMappingURL=NodeCrypto.js.map","/**\n * The `NodeCrypto` module provides the Node.js `Crypto` service layer for\n * Effect programs. Provide {@link layer} at the edge of a Node application,\n * CLI, script, or test to satisfy `effect/Crypto` with Node's `node:crypto`\n * implementation for secure random bytes, UUID generation, random values, and\n * SHA digest operations.\n *\n * This module is the public Node adapter around the shared Node-compatible\n * implementation. Digest failures are reported as platform errors, and SHA-1\n * remains available only for interoperability with existing protocols.\n *\n * @stability unstable\n * @since 1.0.0\n */\nimport * as NodeCrypto from \"@effect/platform-node-shared/NodeCrypto\";\n/**\n * Layer that provides the Node.js Crypto service implementation.\n *\n * @stability unstable\n * @category layers\n * @since 1.0.0\n */\nexport const layer = NodeCrypto.layer;\n//# sourceMappingURL=NodeCrypto.js.map","/**\n * Shared Node-compatible implementation of Effect's `FileSystem` service.\n *\n * This module adapts Node's `node:fs`, `node:os`, and `node:path` APIs into a\n * `FileSystem` layer for Effect programs running on Node-compatible runtimes.\n * Platform packages use it to provide file and directory I/O, permissions,\n * links, metadata, temporary files and directories, and file watching through\n * the shared `FileSystem` service.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as BI from \"effect/BigInt\";\nimport * as ByteSize from \"effect/ByteSize\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport { effectify } from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport { pipe } from \"effect/Function\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Error from \"effect/PlatformError\";\nimport * as Queue from \"effect/Queue\";\nimport * as Stream from \"effect/Stream\";\nimport * as Crypto from \"node:crypto\";\nimport * as NFS from \"node:fs\";\nimport * as OS from \"node:os\";\nimport * as Path from \"node:path\";\nimport { handleErrnoException } from \"./internal/utils.js\";\nconst handleBadArgument = method => err => Error.badArgument({\n module: \"FileSystem\",\n method,\n description: err.message ?? String(err)\n});\nconst bigintToNumber = (value, field) => {\n const number = Number(value);\n if (!Number.isSafeInteger(number)) {\n throw new RangeError(`${field} exceeds the safe integer range: ${value}`);\n }\n return number;\n};\nconst bigintToNumberOption = value => Option.flatMap(Option.fromNullishOr(value), BI.toNumber);\n// Node fills bigint stats from a BigInt64Array, so unsigned 64-bit values such\n// as dev_t and ino_t at or above 2^63 are reported as negative.\nconst toUint64 = value => BigInt.asUintN(64, value);\nconst toUint64Option = value => Option.map(Option.fromNullishOr(value), toUint64);\n// fs.write ignores bigint positions.\nconst positionToNumber = (position, method) => Effect.try({\n try: () => bigintToNumber(position, \"position\"),\n catch: handleBadArgument(method)\n});\n// == access\nconst access = /*#__PURE__*/(() => {\n const nodeAccess = /*#__PURE__*/effectify(NFS.access, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"access\"), /*#__PURE__*/handleBadArgument(\"access\"));\n return (path, options) => {\n let mode = NFS.constants.F_OK;\n if (options?.readable) {\n mode |= NFS.constants.R_OK;\n }\n if (options?.writable) {\n mode |= NFS.constants.W_OK;\n }\n return nodeAccess(path, mode);\n };\n})();\n// == copy\nconst copy = /*#__PURE__*/(() => {\n const nodeCp = /*#__PURE__*/effectify(NFS.cp, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"copy\"), /*#__PURE__*/handleBadArgument(\"copy\"));\n return (fromPath, toPath, options) => nodeCp(fromPath, toPath, {\n force: options?.overwrite ?? false,\n preserveTimestamps: options?.preserveTimestamps ?? false,\n recursive: true\n });\n})();\n// == copyFile\nconst copyFile = /*#__PURE__*/(() => {\n const nodeCopyFile = /*#__PURE__*/effectify(NFS.copyFile, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"copyFile\"), /*#__PURE__*/handleBadArgument(\"copyFile\"));\n return (fromPath, toPath) => nodeCopyFile(fromPath, toPath);\n})();\n// == chmod\nconst chmod = /*#__PURE__*/(() => {\n const nodeChmod = /*#__PURE__*/effectify(NFS.chmod, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"chmod\"), /*#__PURE__*/handleBadArgument(\"chmod\"));\n return (path, mode) => nodeChmod(path, mode);\n})();\n// == chown\nconst chown = /*#__PURE__*/(() => {\n const nodeChown = /*#__PURE__*/effectify(NFS.chown, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"chown\"), /*#__PURE__*/handleBadArgument(\"chown\"));\n return (path, uid, gid) => nodeChown(path, uid, gid);\n})();\n// == glob\nconst glob = /*#__PURE__*/(() => {\n const nodeGlob = /*#__PURE__*/effectify(NFS.glob, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"glob\"), /*#__PURE__*/handleBadArgument(\"glob\"));\n return (pattern, options) => nodeGlob(pattern, {\n cwd: options?.root,\n exclude: options?.exclude\n });\n})();\n// == link\nconst link = /*#__PURE__*/(() => {\n const nodeLink = /*#__PURE__*/effectify(NFS.link, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"link\"), /*#__PURE__*/handleBadArgument(\"link\"));\n return (existingPath, newPath) => nodeLink(existingPath, newPath);\n})();\n// == makeDirectory\nconst makeDirectory = /*#__PURE__*/(() => {\n const nodeMkdir = /*#__PURE__*/effectify(NFS.mkdir, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"makeDirectory\"), /*#__PURE__*/handleBadArgument(\"makeDirectory\"));\n return (path, options) => nodeMkdir(path, {\n recursive: options?.recursive ?? false,\n mode: options?.mode\n });\n})();\n// == makeTempDirectory\nconst makeTempDirectoryFactory = method => {\n const nodeMkdtemp = effectify(NFS.mkdtemp, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n return options => Effect.suspend(() => {\n const prefix = options?.prefix ?? \"\";\n const directory = typeof options?.directory === \"string\" ? Path.join(options.directory, \".\") : OS.tmpdir();\n return nodeMkdtemp(prefix ? Path.join(directory, prefix) : directory + \"/\");\n });\n};\nconst makeTempDirectory = /*#__PURE__*/makeTempDirectoryFactory(\"makeTempDirectory\");\n// == remove\nconst removeFactory = method => {\n const nodeRm = effectify(NFS.rm, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n return (path, options) => nodeRm(path, {\n recursive: options?.recursive ?? false,\n force: options?.force ?? false\n });\n};\nconst remove = /*#__PURE__*/removeFactory(\"remove\");\n// == makeTempDirectoryScoped\nconst makeTempDirectoryScoped = /*#__PURE__*/(() => {\n const makeDirectory = /*#__PURE__*/makeTempDirectoryFactory(\"makeTempDirectoryScoped\");\n const removeDirectory = /*#__PURE__*/removeFactory(\"makeTempDirectoryScoped\");\n return options => Effect.acquireRelease(makeDirectory(options), directory => Effect.orDie(removeDirectory(directory, {\n recursive: true\n })));\n})();\n// == open\nconst openFlagBits = flag => {\n const {\n O_APPEND,\n O_CREAT,\n O_EXCL,\n O_RDONLY,\n O_RDWR,\n O_TRUNC,\n O_WRONLY\n } = NFS.constants;\n switch (flag) {\n case \"r\":\n return O_RDONLY;\n case \"r+\":\n return O_RDWR;\n case \"w\":\n return O_TRUNC | O_CREAT | O_WRONLY;\n case \"wx\":\n return O_TRUNC | O_CREAT | O_WRONLY | O_EXCL;\n case \"w+\":\n return O_TRUNC | O_CREAT | O_RDWR;\n case \"wx+\":\n return O_TRUNC | O_CREAT | O_RDWR | O_EXCL;\n case \"a\":\n return O_APPEND | O_CREAT | O_WRONLY;\n case \"ax\":\n return O_APPEND | O_CREAT | O_WRONLY | O_EXCL;\n case \"a+\":\n return O_APPEND | O_CREAT | O_RDWR;\n case \"ax+\":\n return O_APPEND | O_CREAT | O_RDWR | O_EXCL;\n }\n};\n// Reject unsupported platforms: libuv silently ignores unknown flags on Windows.\nconst noFollowFlags = (method, flag) => Effect.suspend(() => {\n const {\n O_NOFOLLOW\n } = NFS.constants;\n if (process.platform === \"win32\" || typeof O_NOFOLLOW !== \"number\" || O_NOFOLLOW === 0) {\n return Effect.fail(Error.badArgument({\n module: \"FileSystem\",\n method,\n description: \"noFollow is not supported on this platform\"\n }));\n }\n return Effect.succeed(openFlagBits(flag) | O_NOFOLLOW);\n});\nconst openFactory = method => {\n const nodeOpen = effectify(NFS.open, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n const nodeClose = effectify(NFS.close, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n return (path, options) => pipe(Effect.acquireRelease(options?.noFollow === true ? Effect.flatMap(noFollowFlags(method, options.flag ?? \"r\"), flags => nodeOpen(path, flags, options.mode)) : nodeOpen(path, options?.flag ?? \"r\", options?.mode), fd => Effect.orDie(nodeClose(fd))), Effect.map(fd => makeFile(fd, options?.flag?.startsWith(\"a\") ?? false)));\n};\nconst open = /*#__PURE__*/openFactory(\"open\");\nconst negativePosition = method => Error.badArgument({\n module: \"FileSystem\",\n method,\n description: \"Cannot read before the start of the file\"\n});\nconst makeFile = /*#__PURE__*/(() => {\n const nodeReadFactory = method => effectify(NFS.read, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n const nodeRead = /*#__PURE__*/nodeReadFactory(\"read\");\n const nodeReadAlloc = /*#__PURE__*/nodeReadFactory(\"readAlloc\");\n const nodeStat = /*#__PURE__*/effectify(NFS.fstat, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"stat\"), /*#__PURE__*/handleBadArgument(\"stat\"));\n const nodeTruncate = /*#__PURE__*/effectify(NFS.ftruncate, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"truncate\"), /*#__PURE__*/handleBadArgument(\"truncate\"));\n const nodeSync = /*#__PURE__*/effectify(NFS.fsync, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"sync\"), /*#__PURE__*/handleBadArgument(\"sync\"));\n const nodeWriteFactory = method => effectify(NFS.write, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n const nodeWrite = /*#__PURE__*/nodeWriteFactory(\"write\");\n const nodeWriteAll = /*#__PURE__*/nodeWriteFactory(\"writeAll\");\n class FileImpl {\n [FileSystem.FileTypeId];\n fd;\n append;\n position = /*#__PURE__*/BigInt(0);\n constructor(fd, append) {\n this[FileSystem.FileTypeId] = FileSystem.FileTypeId;\n this.fd = fd;\n this.append = append;\n }\n get stat() {\n return Effect.flatMap(nodeStat(this.fd, {\n bigint: true\n }), makeFileInfo);\n }\n get sync() {\n return nodeSync(this.fd);\n }\n seek(offset, from) {\n return Effect.suspend(() => {\n const position = from === \"start\" ? offset : this.position + offset;\n if (position < BigInt(0)) {\n return Effect.fail(Error.badArgument({\n module: \"FileSystem\",\n method: \"seek\",\n description: \"Cannot seek before the start of the file\"\n }));\n }\n this.position = position;\n return Effect.succeed(position);\n });\n }\n read(buffer, options) {\n return Effect.suspend(() => {\n const explicit = options?.position;\n if (explicit !== undefined) {\n return explicit < BigInt(0) ? Effect.fail(negativePosition(\"read\")) : nodeRead(this.fd, {\n buffer,\n position: explicit\n });\n }\n const position = this.position;\n return Effect.map(nodeRead(this.fd, {\n buffer,\n position\n }), bytesRead => {\n this.position = position + BigInt(bytesRead);\n return bytesRead;\n });\n });\n }\n readAlloc(size, options) {\n return Effect.suspend(() => {\n try {\n if (!Number.isInteger(size) || size < 0) {\n throw new RangeError(\"size must be a non-negative integer\");\n }\n const explicit = options?.position;\n if (explicit !== undefined && explicit < BigInt(0)) {\n return Effect.fail(negativePosition(\"readAlloc\"));\n }\n const buffer = Buffer.allocUnsafeSlow(size);\n const position = explicit ?? this.position;\n return Effect.map(nodeReadAlloc(this.fd, {\n buffer,\n position\n }), bytesRead => {\n if (bytesRead === 0) {\n return Option.none();\n }\n if (explicit === undefined) {\n this.position = position + BigInt(bytesRead);\n }\n if (bytesRead === size) {\n return Option.some(buffer);\n }\n const dst = Buffer.allocUnsafeSlow(bytesRead);\n buffer.copy(dst, 0, 0, bytesRead);\n return Option.some(dst);\n });\n } catch (cause) {\n return Effect.fail(handleBadArgument(\"readAlloc\")(cause));\n }\n });\n }\n truncate(length) {\n return Effect.map(nodeTruncate(this.fd, length || undefined), () => {\n if (!this.append) {\n const len = BigInt(length ?? 0);\n if (this.position > len) {\n this.position = len;\n }\n }\n });\n }\n write(buffer) {\n return Effect.suspend(() => {\n const position = this.position;\n return Effect.flatMap(this.append ? Effect.succeed(undefined) : positionToNumber(position, \"write\"), nodePosition => Effect.map(nodeWrite(this.fd, buffer, undefined, undefined, nodePosition), bytesWritten => {\n if (!this.append) {\n this.position = position + BigInt(bytesWritten);\n }\n return bytesWritten;\n }));\n });\n }\n writeAllChunk(buffer) {\n return Effect.suspend(() => {\n const position = this.position;\n return Effect.flatMap(this.append ? Effect.succeed(undefined) : positionToNumber(position, \"writeAll\"), nodePosition => Effect.flatMap(nodeWriteAll(this.fd, buffer, undefined, undefined, nodePosition), bytesWritten => {\n if (bytesWritten === 0) {\n return Effect.fail(Error.systemError({\n module: \"FileSystem\",\n method: \"writeAll\",\n _tag: \"WriteZero\",\n pathOrDescriptor: this.fd,\n description: \"write returned 0 bytes written\"\n }));\n }\n if (!this.append) {\n this.position = position + BigInt(bytesWritten);\n }\n return bytesWritten < buffer.length ? this.writeAllChunk(buffer.subarray(bytesWritten)) : Effect.void;\n }));\n });\n }\n writeAll(buffer) {\n return buffer.length === 0 ? Effect.void : this.writeAllChunk(buffer);\n }\n }\n return (fd, append) => new FileImpl(fd, append);\n})();\n// == makeTempFile\nconst makeTempFileFactory = method => {\n const makeDirectory = makeTempDirectoryFactory(method);\n return Effect.fnUntraced(function* (options) {\n const directory = yield* makeDirectory(options);\n const random = Crypto.randomBytes(6).toString(\"hex\");\n const name = Path.join(directory, options?.suffix ? `${random}${options.suffix}` : random);\n yield* writeFile(name, new Uint8Array(0));\n return name;\n });\n};\nconst makeTempFile = /*#__PURE__*/makeTempFileFactory(\"makeTempFile\");\n// == makeTempFileScoped\nconst makeTempFileScoped = /*#__PURE__*/(() => {\n const makeFile = /*#__PURE__*/makeTempFileFactory(\"makeTempFileScoped\");\n const removeDirectory = /*#__PURE__*/removeFactory(\"makeTempFileScoped\");\n return options => Effect.acquireRelease(makeFile(options), file => Effect.orDie(removeDirectory(Path.dirname(file), {\n recursive: true\n })));\n})();\n// == readDirectory\nconst readDirectory = (path, options) => Effect.tryPromise({\n try: () => NFS.promises.readdir(path, options),\n catch: err => handleErrnoException(\"FileSystem\", \"readDirectory\")(err, [path])\n});\n// == readFile\nconst readFile = path => Effect.callback((resume, signal) => {\n try {\n NFS.readFile(path, {\n signal\n }, (err, data) => {\n if (err) {\n resume(Effect.fail(handleErrnoException(\"FileSystem\", \"readFile\")(err, [path])));\n } else {\n resume(Effect.succeed(data));\n }\n });\n } catch (err) {\n resume(Effect.fail(handleBadArgument(\"readFile\")(err)));\n }\n});\n// == readLink\nconst readLink = /*#__PURE__*/(() => {\n const nodeReadLink = /*#__PURE__*/effectify(NFS.readlink, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"readLink\"), /*#__PURE__*/handleBadArgument(\"readLink\"));\n return path => nodeReadLink(path);\n})();\n// == realPath\nconst realPath = /*#__PURE__*/(() => {\n const nodeRealPath = /*#__PURE__*/effectify(NFS.realpath, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"realPath\"), /*#__PURE__*/handleBadArgument(\"realPath\"));\n return path => nodeRealPath(path);\n})();\n// == rename\nconst rename = /*#__PURE__*/(() => {\n const nodeRename = /*#__PURE__*/effectify(NFS.rename, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"rename\"), /*#__PURE__*/handleBadArgument(\"rename\"));\n return (oldPath, newPath) => nodeRename(oldPath, newPath);\n})();\n// == stat\nconst makeFileInfo = stat => Effect.try({\n try: () => ({\n type: stat.isFile() ? \"File\" : stat.isDirectory() ? \"Directory\" : stat.isSymbolicLink() ? \"SymbolicLink\" : stat.isBlockDevice() ? \"BlockDevice\" : stat.isCharacterDevice() ? \"CharacterDevice\" : stat.isFIFO() ? \"FIFO\" : stat.isSocket() ? \"Socket\" : \"Unknown\",\n mtime: Option.fromNullishOr(stat.mtime),\n atime: Option.fromNullishOr(stat.atime),\n birthtime: Option.fromNullishOr(stat.birthtime),\n dev: toUint64(stat.dev),\n rdev: toUint64Option(stat.rdev),\n ino: toUint64Option(stat.ino),\n mode: bigintToNumber(stat.mode, \"mode\"),\n nlink: toUint64Option(stat.nlink),\n uid: bigintToNumberOption(stat.uid),\n gid: bigintToNumberOption(stat.gid),\n size: ByteSize.bytes(stat.size),\n blksize: stat.blksize !== undefined ? Option.some(ByteSize.bytes(stat.blksize)) : Option.none(),\n blocks: Option.fromNullishOr(stat.blocks)\n }),\n catch: handleBadArgument(\"stat\")\n});\nconst stat = /*#__PURE__*/(() => {\n const nodeStat = /*#__PURE__*/effectify(NFS.stat, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"stat\"), /*#__PURE__*/handleBadArgument(\"stat\"));\n return path => Effect.flatMap(nodeStat(path, {\n bigint: true\n }), makeFileInfo);\n})();\n// == symlink\nconst symlink = /*#__PURE__*/(() => {\n const nodeSymlink = /*#__PURE__*/effectify(NFS.symlink, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"symlink\"), /*#__PURE__*/handleBadArgument(\"symlink\"));\n return (target, path) => nodeSymlink(target, path);\n})();\n// == truncate\nconst truncate = /*#__PURE__*/(() => {\n const nodeTruncate = /*#__PURE__*/effectify(NFS.truncate, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"truncate\"), /*#__PURE__*/handleBadArgument(\"truncate\"));\n return (path, length) => nodeTruncate(path, length);\n})();\n// == utimes\nconst utimes = /*#__PURE__*/(() => {\n const nodeUtimes = /*#__PURE__*/effectify(NFS.utimes, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"utime\"), /*#__PURE__*/handleBadArgument(\"utime\"));\n return (path, atime, mtime) => nodeUtimes(path, atime, mtime);\n})();\n// == watch\nconst watchNode = (path, info, options) => Stream.callback(queue => Effect.acquireRelease(Effect.sync(() => {\n const directory = info.type === \"Directory\" ? path : Path.dirname(path);\n const watcher = NFS.watch(path, {\n recursive: options?.recursive ?? false\n }, (event, path) => {\n if (!path) return;\n switch (event) {\n case \"rename\":\n {\n Effect.runFork(Effect.matchEffect(stat(Path.resolve(directory, path)), {\n onSuccess: _ => Queue.offer(queue, {\n _tag: \"Create\",\n path\n }),\n onFailure: _ => Queue.offer(queue, {\n _tag: \"Remove\",\n path\n })\n }));\n return;\n }\n case \"change\":\n {\n Queue.offerUnsafe(queue, {\n _tag: \"Update\",\n path\n });\n return;\n }\n }\n });\n watcher.on(\"error\", error => {\n Queue.failCauseUnsafe(queue, Cause.fail(Error.systemError({\n module: \"FileSystem\",\n _tag: \"Unknown\",\n method: \"watch\",\n pathOrDescriptor: path,\n cause: error\n })));\n });\n watcher.on(\"close\", () => {\n Queue.endUnsafe(queue);\n });\n return watcher;\n}), watcher => Effect.sync(() => watcher.close())).pipe(Effect.tap(() => Effect.sync(() => options?.onReady?.()))));\nconst watch = (backend, path, options) => Effect.all([stat(path), Effect.serviceOption(FileSystem.WatchBackend)]).pipe(Effect.map(([stat, callerBackend]) => Option.orElse(callerBackend, () => backend).pipe(Option.flatMap(_ => _.register(path, stat, options)), Option.getOrElse(() => watchNode(path, stat, options)))), Stream.unwrap);\n// == writeFile\nconst writeFile = (path, data, options) => Effect.callback((resume, signal) => {\n try {\n NFS.writeFile(path, data, {\n signal,\n flag: options?.flag,\n mode: options?.mode\n }, err => {\n if (err) {\n resume(Effect.fail(handleErrnoException(\"FileSystem\", \"writeFile\")(err, [path])));\n } else {\n resume(Effect.void);\n }\n });\n } catch (err) {\n resume(Effect.fail(handleBadArgument(\"writeFile\")(err)));\n }\n});\nconst makeFileSystem = /*#__PURE__*/Effect.map(/*#__PURE__*/Effect.serviceOption(FileSystem.WatchBackend), backend => FileSystem.make({\n access,\n chmod,\n chown,\n copy,\n copyFile,\n glob,\n link,\n makeDirectory,\n makeTempDirectory,\n makeTempDirectoryScoped,\n makeTempFile,\n makeTempFileScoped,\n open,\n readDirectory,\n readFile,\n readLink,\n realPath,\n remove,\n rename,\n stat,\n symlink,\n truncate,\n utimes,\n watch(path, options) {\n return watch(backend, path, options);\n },\n writeFile\n}));\n/**\n * Provides the `FileSystem` service backed by Node filesystem APIs, including\n * file operations, directory operations, links, metadata, and file watching.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.effect(FileSystem.FileSystem)(makeFileSystem);\n//# sourceMappingURL=NodeFileSystem.js.map","/**\n * Node.js `FileSystem` layer for programs that perform real filesystem I/O.\n *\n * The exported layer satisfies the platform-independent `FileSystem` service\n * with Node-backed operations for files, directories, metadata, permissions,\n * links, temporary paths, and path watching. Effects still call the service from\n * `effect/FileSystem`; this module only chooses the Node implementation.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as NodeFileSystem from \"@effect/platform-node-shared/NodeFileSystem\";\n/**\n * Provides the `FileSystem` service backed by Node filesystem APIs.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodeFileSystem.layer;\n//# sourceMappingURL=NodeFileSystem.js.map","/**\n * Node-backed provider for Effect's `Path` service.\n *\n * This module turns Node's `node:path` and `node:url` APIs into `Path` layers.\n * `layer` uses the host platform path implementation, while `layerPosix` and\n * `layerWin32` provide fixed POSIX and Windows variants. All three layers also\n * include helpers for converting between file paths and file URLs.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { make, Path } from \"effect/Path\";\nimport { BadArgument } from \"effect/PlatformError\";\nimport * as NodePath from \"node:path\";\nimport * as NodeUrl from \"node:url\";\nconst fileUrlOps = windows => ({\n fromFileUrl: url => Effect.try({\n try: () => NodeUrl.fileURLToPath(url, {\n windows\n }),\n catch: cause => new BadArgument({\n module: \"Path\",\n method: \"fromFileUrl\",\n cause\n })\n }),\n toFileUrl: path => Effect.try({\n try: () => NodeUrl.pathToFileURL(path, {\n windows\n }),\n catch: cause => new BadArgument({\n module: \"Path\",\n method: \"toFileUrl\",\n cause\n })\n })\n});\n/**\n * Provides the `Path` service using Node's POSIX path implementation plus\n * file URL conversion helpers.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerPosix = /*#__PURE__*/Layer.succeed(Path)(/*#__PURE__*/make({\n ...NodePath.posix,\n ... /*#__PURE__*/fileUrlOps(false)\n}));\n/**\n * Provides the `Path` service using Node's Windows path implementation plus\n * file URL conversion helpers.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerWin32 = /*#__PURE__*/Layer.succeed(Path)(/*#__PURE__*/make({\n ...NodePath.win32,\n ... /*#__PURE__*/fileUrlOps(true)\n}));\n/**\n * Provides the default `Path` service using the host platform's Node path\n * implementation plus file URL conversion helpers.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.succeed(Path)(/*#__PURE__*/make({\n ...NodePath,\n ... /*#__PURE__*/fileUrlOps(undefined)\n}));\n//# sourceMappingURL=NodePath.js.map","/**\n * Node.js layers for Effect's `Path` service.\n *\n * This module provides the default, POSIX, and Windows variants of the\n * platform-independent `Path` service by reusing the shared Node path\n * implementation. The provided path services include Node file URL conversion\n * behavior.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as NodePath from \"@effect/platform-node-shared/NodePath\";\n/**\n * Provides the default Node `Path` service using the platform's `node:path`\n * implementation.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodePath.layer;\n/**\n * Provides the `Path` service using Node's POSIX path implementation,\n * regardless of the host platform.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerPosix = NodePath.layerPosix;\n/**\n * Provides the `Path` service using Node's Windows path implementation,\n * regardless of the host platform.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerWin32 = NodePath.layerWin32;\n//# sourceMappingURL=NodePath.js.map","/**\n * Shared Node.js implementation of the Effect `Stdio` service.\n *\n * `NodeStdio` provides {@link Stdio.Stdio} from the current Node process. The\n * exported {@link layer} reads command-line arguments from `process.argv`,\n * consumes input from `process.stdin`, and writes normal and error output to\n * `process.stdout` and `process.stderr`. Standard input remains open, and\n * standard output and error output are not ended unless requested.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { systemError } from \"effect/PlatformError\";\nimport * as Stdio from \"effect/Stdio\";\nimport { fromWritable } from \"./NodeSink.js\";\nimport { fromReadable } from \"./NodeStream.js\";\n/**\n * Provides `Stdio` from `process.argv`, `process.stdin`, `process.stdout`,\n * and `process.stderr`; stdin remains open and stdout/stderr are not ended by\n * default.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.succeed(Stdio.Stdio, /*#__PURE__*/Stdio.make({\n args: /*#__PURE__*/Effect.sync(() => process.argv.slice(2)),\n stdinIsTerminal: /*#__PURE__*/Effect.sync(() => process.stdin.isTTY === true),\n stdoutIsTerminal: /*#__PURE__*/Effect.sync(() => process.stdout.isTTY === true),\n stderrIsTerminal: /*#__PURE__*/Effect.sync(() => process.stderr.isTTY === true),\n stdout: options => fromWritable({\n evaluate: () => process.stdout,\n onError: cause => systemError({\n module: \"Stdio\",\n method: \"stdout\",\n _tag: \"Unknown\",\n cause\n }),\n endOnDone: options?.endOnDone ?? false\n }),\n stderr: options => fromWritable({\n evaluate: () => process.stderr,\n onError: cause => systemError({\n module: \"Stdio\",\n method: \"stderr\",\n _tag: \"Unknown\",\n cause\n }),\n endOnDone: options?.endOnDone ?? false\n }),\n stdin: /*#__PURE__*/fromReadable({\n evaluate: () => process.stdin,\n onError: cause => systemError({\n module: \"Stdio\",\n method: \"stdin\",\n _tag: \"Unknown\",\n cause\n }),\n closeOnDone: false\n })\n}));\n//# sourceMappingURL=NodeStdio.js.map","/**\n * Node.js `Stdio` layer for the current process.\n *\n * The exported layer reuses the shared Node stdio implementation. It satisfies\n * the platform-independent `Stdio` service by reading command-line arguments\n * from `process.argv`, consuming input from `process.stdin`, and writing output\n * streams to `process.stdout` and `process.stderr`.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as NodeStdio from \"@effect/platform-node-shared/NodeStdio\";\n/**\n * Provides the `Stdio` service backed by the current process arguments,\n * stdin, stdout, and stderr streams.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodeStdio.layer;\n//# sourceMappingURL=NodeStdio.js.map","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport { badArgument } from \"effect/PlatformError\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Queue from \"effect/Queue\";\nimport * as RcRef from \"effect/RcRef\";\nimport * as Terminal from \"effect/Terminal\";\nimport * as readline from \"node:readline\";\n/**\n * Creates a scoped process-backed `Terminal` using Node `readline` and TTY raw mode.\n * By default, Esc, Ctrl+C, and Ctrl+D end key input. Supply `shouldQuit` to\n * override these quit keys.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (shouldQuit = defaultShouldQuit) {\n const stdin = process.stdin;\n const stdout = process.stdout;\n const lines = yield* Queue.make();\n // stdin \"end\" fires once per process, so remember end-of-input for readers\n // created after the event (Bun never sets `readableEnded`).\n let inputEnded = stdin.readableEnded;\n let readlineActive = false;\n const onStdinEnd = () => {\n inputEnded = true;\n if (!readlineActive) {\n Queue.endUnsafe(lines);\n }\n };\n stdin.once(\"end\", onStdinEnd);\n yield* Effect.addFinalizer(() => Effect.sync(() => stdin.off(\"end\", onStdinEnd)));\n const rlRef = yield* RcRef.make({\n acquire: Effect.acquireRelease(Effect.sync(() => {\n const rl = readline.createInterface({\n input: stdin,\n escapeCodeTimeout: 50\n });\n const onLine = line => Queue.offerUnsafe(lines, line);\n const onClose = () => {\n readlineActive = false;\n Queue.endUnsafe(lines);\n };\n readlineActive = true;\n readline.emitKeypressEvents(stdin, rl);\n rl.on(\"line\", onLine);\n rl.once(\"close\", onClose);\n if (stdin.isTTY) {\n stdin.setRawMode(true);\n }\n return {\n rl,\n onClose,\n onLine\n };\n }), ({\n rl,\n onClose,\n onLine\n }) => Effect.sync(() => {\n readlineActive = false;\n rl.off(\"line\", onLine);\n rl.off(\"close\", onClose);\n if (stdin.isTTY) {\n stdin.setRawMode(false);\n }\n rl.close();\n if (inputEnded) {\n Queue.endUnsafe(lines);\n }\n })),\n idleTimeToLive: \"10 millis\"\n });\n const columns = Effect.sync(() => stdout.columns ?? 0);\n const rows = Effect.sync(() => stdout.rows ?? 0);\n const readInput = Effect.gen(function* () {\n const queue = yield* Queue.make();\n const handleKeypress = (s, k) => {\n const userInput = {\n input: Option.fromUndefinedOr(s),\n key: {\n name: k.name ?? \"\",\n ctrl: !!k.ctrl,\n meta: !!k.meta,\n shift: !!k.shift\n }\n };\n Queue.offerUnsafe(queue, userInput);\n if (shouldQuit(userInput)) {\n Queue.endUnsafe(queue);\n }\n };\n // Deno's `process.stdin` shim does not keep the event loop alive, so a\n // program blocked on input can exit before `end` is ever delivered. A\n // timer holds the loop open for as long as this reader is active.\n const keepAlive = setInterval(() => {}, 2147483647);\n // Without this, consumers (e.g. `Prompt.run`) hang forever on closed stdin.\n const handleEnd = () => {\n clearInterval(keepAlive);\n Queue.endUnsafe(queue);\n };\n yield* Effect.addFinalizer(() => Effect.sync(() => {\n clearInterval(keepAlive);\n stdin.off(\"keypress\", handleKeypress);\n stdin.off(\"end\", handleEnd);\n }));\n stdin.on(\"keypress\", handleKeypress);\n if (inputEnded) {\n handleEnd();\n } else {\n yield* RcRef.get(rlRef);\n stdin.once(\"end\", handleEnd);\n }\n return queue;\n });\n const readLine = Effect.suspend(() => Queue.poll(lines).pipe(Effect.flatMap(Option.match({\n onNone: () => Effect.scoped(Effect.andThen(RcRef.get(rlRef), Queue.take(lines))),\n onSome: Effect.succeed\n })), Effect.mapError(() => new Terminal.QuitError({}))));\n const display = prompt => Effect.uninterruptible(Effect.callback(resume => {\n stdout.write(prompt, err => Predicate.isNullish(err) ? resume(Effect.void) : resume(Effect.fail(badArgument({\n module: \"Terminal\",\n method: \"display\",\n description: \"Failed to write prompt to stdout\",\n cause: err\n }))));\n }));\n return Terminal.make({\n columns,\n rows,\n readInput,\n readLine,\n display\n });\n});\n/**\n * Provides the default process-backed `Terminal` service, ending key input on\n * bare Esc, Ctrl+C, or Ctrl+D.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.effect(Terminal.Terminal, /*#__PURE__*/make(defaultShouldQuit));\nfunction defaultShouldQuit(input) {\n const key = input.key;\n return key.name === \"escape\" || key.ctrl && (key.name === \"c\" || key.name === \"d\");\n}\n//# sourceMappingURL=NodeTerminal.js.map","/**\n * Node.js implementation of the Effect `Terminal` service.\n *\n * This module reuses the shared Node terminal implementation. `make` creates a\n * scoped process-backed `Terminal` service, and `layer` provides the default\n * service with the standard quit behavior for key input.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as NodeTerminal from \"@effect/platform-node-shared/NodeTerminal\";\n/**\n * Creates a scoped `Terminal` service backed by process stdin/stdout.\n * By default, Esc, Ctrl+C, and Ctrl+D end key input. Supply `shouldQuit` to\n * override these quit keys.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = NodeTerminal.make;\n/**\n * Provides the default process-backed `Terminal` service, ending key input on\n * bare Esc, Ctrl+C, or Ctrl+D.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodeTerminal.layer;\n//# sourceMappingURL=NodeTerminal.js.map","import * as Layer from \"effect/Layer\";\nimport * as NodeChildProcessSpawner from \"./NodeChildProcessSpawner.js\";\nimport * as NodeCrypto from \"./NodeCrypto.js\";\nimport * as NodeFileSystem from \"./NodeFileSystem.js\";\nimport * as NodePath from \"./NodePath.js\";\nimport * as NodeStdio from \"./NodeStdio.js\";\nimport * as NodeTerminal from \"./NodeTerminal.js\";\n/**\n * Provides the default Node implementations for child process spawning,\n * filesystem, path, stdio, and terminal services.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.provideMerge(NodeChildProcessSpawner.layer, /*#__PURE__*/Layer.mergeAll(NodeFileSystem.layer, NodeCrypto.layer, NodePath.layer, NodeStdio.layer, NodeTerminal.layer));\n//# sourceMappingURL=NodeServices.js.map","import * as Runtime from \"effect/Runtime\";\n/**\n * Runs an Effect as the Node process main program, interrupting the fiber on\n * `SIGINT` or `SIGTERM` and invoking the configured teardown to determine the\n * process exit code.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const runMain = /*#__PURE__*/Runtime.makeRunMain(({\n fiber,\n teardown\n}) => {\n let receivedSignal = false;\n fiber.addObserver(exit => {\n process.removeListener(\"SIGINT\", onSigint);\n process.removeListener(\"SIGTERM\", onSigint);\n teardown(exit, code => {\n if (receivedSignal || code !== 0) {\n process.exit(code);\n }\n });\n });\n function onSigint() {\n receivedSignal = true;\n fiber.interruptUnsafe(fiber.id);\n }\n process.on(\"SIGINT\", onSigint);\n process.on(\"SIGTERM\", onSigint);\n});\n//# sourceMappingURL=NodeRuntime.js.map","/**\n * Node.js process runner for Effect programs.\n *\n * This module exports `runMain`, which runs one Effect as the main process\n * fiber in Node.js. It reuses the shared Node runtime runner, including its\n * error reporting, `SIGINT` / `SIGTERM` interruption, and optional teardown\n * behavior.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as NodeRuntime from \"@effect/platform-node-shared/NodeRuntime\";\n/**\n * Helps you run a main effect with built-in error handling, logging, and signal management.\n *\n * **When to use**\n *\n * Use to run a Node.js application's main Effect with structured error\n * handling, log management, interrupt support, or advanced teardown\n * capabilities.\n *\n * **Details**\n *\n * This function launches an Effect as the main entry point, setting exit codes\n * based on success or failure, handling interrupts (e.g., Ctrl+C), and optionally\n * logging errors. By default, it logs errors and uses a \"pretty\" format, but both\n * behaviors can be turned off. You can also provide custom teardown logic to\n * finalize resources or produce different exit codes.\n *\n * The optional configuration object can include:\n * - `disableErrorReporting`: Turn off automatic error logging.\n * - `teardown`: Provide custom finalization logic.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const runMain = NodeRuntime.runMain;\n//# sourceMappingURL=NodeRuntime.js.map","import { Array, Order, Schema, pipe } from 'effect'\n\nexport const LoomLockSchema = Schema.Struct({\n version: Schema.Literal(1),\n tangled: Schema.Array(Schema.String),\n})\n\nexport type LoomLock = typeof LoomLockSchema.Type\n\nexport const emptyLock: LoomLock = { version: 1, tangled: [] }\n\nexport const orphansOf = (lock: LoomLock, produced: ReadonlySet<string>): ReadonlyArray<string> =>\n Array.filter(lock.tangled, (path) => !produced.has(path))\n\nconst sortedUnique = (paths: ReadonlyArray<string>): ReadonlyArray<string> =>\n pipe(paths, Array.dedupe, Array.sort(Order.String))\n\nexport const recorded = (lock: LoomLock, produced: ReadonlyArray<string>): LoomLock => ({\n version: 1,\n tangled: sortedUnique([...lock.tangled, ...produced]),\n})\n\nexport const pruned = (produced: ReadonlyArray<string>): LoomLock => ({\n version: 1,\n tangled: sortedUnique(produced),\n})\n","import { Array, Context, Effect, FileSystem, Layer, Option, Result, Schema, Stream } from 'effect'\nimport { dirname, relative, resolve as resolvePath } from 'node:path'\nimport { type Path } from '@athrio/loom-ast/LoomCorpusAst'\nimport { workspaceRoot } from '@athrio/loom-lang-services/LoomStore'\nimport { LoomCompiler, type TangledFile, type TangleError } from './LoomCompiler'\nimport { PackageConfig } from './PackageConfig'\nimport { holds, loomsIn, projectIn, storeDirs, type LoomProject } from './LoomProject'\nimport { emptyLock, orphansOf, pruned, recorded, LoomLockSchema, type LoomLock } from './LoomLock'\n\nconst isStorePath = (name: string): boolean =>\n name.split('/').some((segment) => storeDirs.has(segment))\n\nexport class LoomTangler extends Context.Service<LoomTangler>()('LoomTangler', {\n make: Effect.gen(function* () {\n const compiler = yield* LoomCompiler\n const fs = yield* FileSystem.FileSystem\n const config = yield* PackageConfig\n\n const matchesDisk = (file: TangledFile): Effect.Effect<boolean> =>\n fs.readFileString(file.path).pipe(Effect.option, Effect.map(Option.contains(file.content)))\n\n const writeFile = (file: TangledFile): Effect.Effect<TangledFile> =>\n matchesDisk(file).pipe(\n Effect.flatMap((same) =>\n same\n ? Effect.void\n : fs\n .makeDirectory(dirname(file.path), { recursive: true })\n .pipe(Effect.andThen(fs.writeFileString(file.path, file.content))),\n ),\n Effect.orDie,\n Effect.as(file),\n )\n\n const tangleFile = (entry: Path): Effect.Effect<ReadonlyArray<TangledFile>, TangleError> =>\n compiler.tangle(entry).pipe(Effect.flatMap((files) => Effect.forEach(files, writeFile)))\n\n const projectOf = (path: Path): Effect.Effect<Option.Option<LoomProject>> =>\n config.resolve(path).pipe(Effect.map(projectIn))\n\n const loomsOf = (path: Path): Effect.Effect<ReadonlyArray<Path>> =>\n fs.stat(path).pipe(\n Effect.orDie,\n Effect.flatMap((info) =>\n info.type === 'Directory'\n ? projectOf(path).pipe(Effect.map((project) => loomsIn(path, project)))\n : Effect.succeed<ReadonlyArray<Path>>([path]),\n ),\n )\n\n const recordsFor = (path: Path): Effect.Effect<boolean> =>\n fs.stat(path).pipe(\n Effect.orDie,\n Effect.flatMap((info) =>\n info.type === 'Directory'\n ? Effect.succeed(true)\n : projectOf(path).pipe(\n Effect.map(\n Option.match({\n onNone: () => true,\n onSome: (project) => holds(project, path),\n }),\n ),\n ),\n ),\n )\n\n const workspaceOf = (path: Path): Effect.Effect<Path> =>\n fs.stat(path).pipe(\n Effect.orDie,\n Effect.map((info) => workspaceRoot(info.type === 'Directory' ? path : dirname(path))),\n )\n\n const lockFile = (root: Path): Path => resolvePath(root, '.loom', 'loom.lock')\n\n const readLock = (root: Path): Effect.Effect<LoomLock> =>\n fs.readFileString(lockFile(root)).pipe(\n Effect.flatMap((text) => Effect.try(() => JSON.parse(text) as unknown)),\n Effect.flatMap(Schema.decodeUnknownEffect(LoomLockSchema)),\n Effect.orElseSucceed(() => emptyLock),\n )\n\n const writeLock = (root: Path, lock: LoomLock): Effect.Effect<void> =>\n fs\n .makeDirectory(dirname(lockFile(root)), { recursive: true })\n .pipe(\n Effect.andThen(fs.writeFileString(lockFile(root), JSON.stringify(lock, null, 2) + '\\n')),\n Effect.orDie,\n )\n\n const tangle = (path: Path): Effect.Effect<ReadonlyArray<TangledFile>, TangleError> =>\n Effect.gen(function* () {\n const looms = yield* loomsOf(path)\n const written = (yield* Effect.forEach(looms, tangleFile)).flat()\n if (yield* recordsFor(path)) {\n const root = yield* workspaceOf(path)\n const lock = yield* readLock(root)\n yield* writeLock(\n root,\n recorded(\n lock,\n Array.map(written, (file) => relative(root, file.path)),\n ),\n )\n }\n return written\n })\n\n const orphanState = (\n from: Path,\n ): Effect.Effect<\n {\n readonly root: Path\n readonly produced: ReadonlyArray<string>\n readonly orphans: ReadonlyArray<string>\n },\n TangleError\n > =>\n Effect.gen(function* () {\n const root = workspaceRoot(from)\n const looms = loomsIn(root, yield* projectOf(root))\n const files = (yield* Effect.forEach(looms, (loom) => compiler.tangle(loom))).flat()\n const produced = Array.map(files, (file) => relative(root, file.path))\n const lock = yield* readLock(root)\n return { root, produced, orphans: orphansOf(lock, new Set(produced)) }\n })\n\n const orphans = (from: Path): Effect.Effect<ReadonlyArray<Path>, TangleError> =>\n orphanState(from).pipe(\n Effect.map(({ root, orphans }) => Array.map(orphans, (rel) => resolvePath(root, rel))),\n )\n\n const prune = (from: Path): Effect.Effect<ReadonlyArray<Path>, TangleError> =>\n Effect.gen(function* () {\n const { root, produced, orphans } = yield* orphanState(from)\n yield* Effect.forEach(orphans, (rel) =>\n fs.remove(resolvePath(root, rel), { force: true }).pipe(Effect.orDie),\n )\n yield* writeLock(root, pruned(produced))\n return Array.map(orphans, (rel) => resolvePath(root, rel))\n })\n\n const batchWindow = '50 millis'\n const batchLimit = 1000\n\n const isLoomEvent = (event: FileSystem.WatchEvent): boolean =>\n event.path.endsWith('.loom') && !isStorePath(event.path)\n\n const watchRoot = (path: Path): Effect.Effect<Path> =>\n fs.stat(path).pipe(\n Effect.orDie,\n Effect.flatMap((info) =>\n info.type === 'Directory'\n ? Effect.succeed(path)\n : config\n .resolve(path)\n .pipe(\n Effect.map(({ corpusDir }) =>\n Option.getOrElse(Option.fromNullishOr(corpusDir), () => dirname(path)),\n ),\n ),\n ),\n )\n\n const watch = (path: Path): Stream.Stream<Result.Result<ReadonlyArray<TangledFile>, TangleError>> =>\n Stream.unwrap(\n watchRoot(path).pipe(\n Effect.map((root) =>\n Stream.concat(\n Stream.fromEffect(Effect.result(tangle(path))),\n fs.watch(root).pipe(\n Stream.filter(isLoomEvent),\n Stream.groupedWithin(batchLimit, batchWindow),\n Stream.mapEffect((events) =>\n Effect.forEach(\n Array.dedupe(Array.map(events, (event) => resolvePath(root, event.path))),\n (changed) => compiler.invalidate(changed),\n { discard: true },\n ).pipe(Effect.andThen(Effect.result(tangle(path)))),\n ),\n Stream.orDie,\n ),\n ),\n ),\n ),\n )\n\n return { tangle, orphans, prune, watch }\n }),\n}) {\n static readonly layer = Layer.effect(this, this.make).pipe(Layer.provide(LoomCompiler.layer))\n}\n","import { Context, Effect, FileSystem, Layer } from 'effect'\nimport { dirname } from 'node:path'\nimport { type Path } from '@athrio/loom-ast/LoomCorpusAst'\nimport { LoomCompiler } from '../LoomCompiler'\n\nexport class LoomWeaver extends Context.Service<LoomWeaver>()('LoomWeaver', {\n make: Effect.gen(function* () {\n const compiler = yield* LoomCompiler\n const fs = yield* FileSystem.FileSystem\n\n const weave = (entry: Path, out: Path): Effect.Effect<Path> =>\n compiler.weave(entry).pipe(\n Effect.map((corpus) => JSON.stringify(corpus, null, 2)),\n Effect.flatMap((json) =>\n fs\n .makeDirectory(dirname(out), { recursive: true })\n .pipe(Effect.andThen(fs.writeFileString(out, json)), Effect.orDie, Effect.as(out)),\n ),\n )\n\n return { weave }\n }),\n}) {\n static readonly layer = Layer.effect(this, this.make).pipe(Layer.provide(LoomCompiler.layer))\n}\n","import { Context, Effect, FileSystem, Layer } from 'effect'\nimport { type Path } from '@athrio/loom-ast/LoomCorpusAst'\nimport { LoomCompiler } from '../LoomCompiler'\n\nexport class LoomContents extends Context.Service<LoomContents>()('LoomContents', {\n make: Effect.gen(function* () {\n const compiler = yield* LoomCompiler\n const fs = yield* FileSystem.FileSystem\n\n const write = (entry: Path): Effect.Effect<Path> =>\n compiler\n .contents(entry)\n .pipe(\n Effect.flatMap((text) =>\n fs.writeFileString(entry, text).pipe(Effect.orDie, Effect.as(entry)),\n ),\n )\n\n return { write }\n }),\n}) {\n static readonly layer = Layer.effect(this, this.make).pipe(Layer.provide(LoomCompiler.layer))\n}\n","import { Cause, Console, Data, Effect, Option, Result, Stream, pipe } from 'effect'\nimport { Argument, Command, Flag, Prompt } from 'effect/cli'\nimport { ChildProcess } from 'effect/process'\nimport { NodeRuntime, NodeServices } from '@effect/platform-node'\nimport { cpSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { homedir } from 'node:os'\nimport { dirname, resolve as resolvePath } from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { DocumentSource, type TangledFile, type TangleError } from '@athrio/loom-lang/LoomCompiler'\nimport { LoomTangler } from '@athrio/loom-lang/LoomTangler'\nimport { LoomWeaver } from '@athrio/loom-lang/weave/LoomWeaver'\nimport { LoomContents } from '@athrio/loom-lang/weave/LoomContents'\nimport { LoomFormatter } from '@athrio/loom-lang/LoomFormatter'\nimport { PackageConfig } from '@athrio/loom-lang/PackageConfig'\nimport { defaultWidth, LoomConfig } from '@athrio/loom-config/LoomConfig'\nimport {\n addService,\n installedVersion,\n removeService,\n ServiceInstall,\n servicePackage,\n serviceVersion,\n storeDir,\n workspaceRoot,\n} from '@athrio/loom-lang-services/LoomStore'\nimport type { LanguageService } from '@athrio/loom-lang-services/LanguageService'\n\nconst reset = '\\x1b[0m'\nconst teal = (s: string): string => `\\x1b[38;5;44m${s}${reset}`\nconst dim = (s: string): string => `\\x1b[2m${s}${reset}`\n\nconst wordmark = [\n ' ██╗ ██████╗ ██████╗ ███╗ ███╗',\n ' ██║ ██╔═══██╗██╔═══██╗████╗ ████║',\n ' ██║ ██║ ██║██║ ██║██╔████╔██║',\n ' ██║ ██║ ██║██║ ██║██║╚██╔╝██║',\n ' ███████╗╚██████╔╝╚██████╔╝██║ ╚═╝ ██║',\n ' ╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝',\n].join('\\n')\n\nconst banner = Console.log(`\\n${teal(wordmark)}\\n ${dim('a literate framework')}\\n`)\n\nconst reportWritten = (written: ReadonlyArray<TangledFile>): Effect.Effect<void> =>\n written.length === 0\n ? Console.log('loom: no {path} sinks to tangle')\n : Effect.forEach(written, (f) => Console.log(`loom: tangled ${f.section} → ${f.path}`), {\n discard: true,\n })\n\nconst tangleOnce = (file: string) =>\n Effect.gen(function* () {\n const tangler = yield* LoomTangler\n const written = yield* tangler.tangle(resolvePath(process.cwd(), file))\n yield* reportWritten(written)\n }).pipe(\n Effect.catchTag('TangleError', (e) =>\n Console.error(e.message).pipe(Effect.andThen(Effect.sync(() => void (process.exitCode = 1)))),\n ),\n )\n\nconst tangleWatch = (file: string) =>\n Effect.gen(function* () {\n const tangler = yield* LoomTangler\n yield* Console.log(`loom: watching ${file} — re-tangling on change`)\n yield* Stream.runForEach(\n tangler.watch(resolvePath(process.cwd(), file)),\n Result.match({\n onSuccess: reportWritten,\n onFailure: (error: TangleError) => Console.error(error.message),\n }),\n )\n })\n\nconst tangle = (file: string, watch: boolean) => (watch ? tangleWatch(file) : tangleOnce(file))\n\nconst orphans = (prune: boolean) =>\n Effect.gen(function* () {\n const tangler = yield* LoomTangler\n if (prune) {\n const removed = yield* tangler.prune(process.cwd())\n yield* removed.length === 0\n ? Console.log('loom: no orphans to prune')\n : Effect.forEach(removed, (path) => Console.log(`loom: pruned ${path}`))\n } else {\n const found = yield* tangler.orphans(process.cwd())\n yield* Effect.forEach(found, (path) => Console.log(path))\n }\n }).pipe(\n Effect.catchTag('TangleError', (e) =>\n Console.error(e.message).pipe(Effect.andThen(Effect.sync(() => void (process.exitCode = 1)))),\n ),\n )\n\nconst weave = (file: string, out: string) =>\n Effect.gen(function* () {\n const weaver = yield* LoomWeaver\n const written = yield* weaver.weave(\n resolvePath(process.cwd(), file),\n resolvePath(process.cwd(), out),\n )\n yield* Console.log(`loom: wove ${file} → ${written}`)\n })\n\nconst toc = (file: string) =>\n Effect.gen(function* () {\n const contents = yield* LoomContents\n const written = yield* contents.write(resolvePath(process.cwd(), file))\n yield* Console.log(`loom: wrote the table of contents into ${written}`)\n })\n\nconst format = (path: string, check: boolean) =>\n Effect.gen(function* () {\n const formatter = yield* LoomFormatter\n const target = resolvePath(process.cwd(), path)\n const languages = yield* formatLanguages(target)\n const looms = yield* formatter.looms(target)\n const changed = yield* Effect.filter(looms, (loom) =>\n Effect.gen(function* () {\n const text = yield* Effect.sync(() => readFileSync(loom, 'utf8'))\n const formatted = yield* formatter.format(loom, text, languages)\n if (formatted === text) return false\n if (!check) yield* Effect.sync(() => writeFileSync(loom, formatted))\n return true\n }),\n )\n yield* changed.length === 0\n ? Console.log('loom: every loom is formatted')\n : Effect.forEach(\n changed,\n (loom) => Console.log(`loom: ${check ? 'would format' : 'formatted'} ${loom}`),\n { discard: true },\n )\n if (check && changed.length > 0) yield* Effect.sync(() => void (process.exitCode = 1))\n })\n\nconst typeScriptFrom = (from: string): Option.Option<string> =>\n Option.liftThrowable(() => createRequire(from).resolve('typescript/lib/typescript.js'))()\n\nconst projectTypeScript = (\n root: string,\n): Effect.Effect<Option.Option<typeof import('typescript')>> =>\n Option.match(\n Option.orElse(typeScriptFrom(resolvePath(root, 'package.json')), () =>\n typeScriptFrom(import.meta.url),\n ),\n {\n onNone: () => Effect.succeed(Option.none()),\n onSome: (file) =>\n Effect.tryPromise(() => import(pathToFileURL(file).href)).pipe(\n Effect.map((module) => Option.some(module.default ?? module)),\n Effect.orElseSucceed(() => Option.none()),\n ),\n },\n )\n\nconst formatLanguages = (target: string) =>\n Effect.gen(function* () {\n const config = yield* LoomConfig\n const root = workspaceRoot(dirname(target))\n const manifest = yield* config.manifest(root)\n const ids = Object.keys(manifest?.languages ?? {})\n if (ids.length === 0) return [] as ReadonlyArray<LanguageService>\n const typescript = yield* projectTypeScript(root)\n return yield* Option.match(typescript, {\n onNone: () =>\n Console.error(\n 'loom: found no TypeScript to load the language services with, so code sections stay as written',\n ).pipe(Effect.as([] as ReadonlyArray<LanguageService>)),\n onSome: (ts) =>\n Effect.gen(function* () {\n yield* Effect.sync(() => {\n ;(globalThis as { require?: unknown }).require ??= createRequire(import.meta.url)\n })\n const { installHostRuntime } = yield* Effect.promise(\n () => import('@athrio/loom-lang-services/Runtime'),\n )\n const { loadActive } = yield* Effect.promise(\n () => import('@athrio/loom-lang-services/LanguageLoader'),\n )\n yield* Effect.sync(() => installHostRuntime(ts))\n return yield* loadActive(ids, root)\n }),\n })\n })\n\nconst mergeMcpConfig = (root: string): void => {\n const path = resolvePath(root, '.mcp.json')\n const existing = existsSync(path)\n ? (JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>)\n : {}\n const servers = (existing.mcpServers as Record<string, unknown> | undefined) ?? {}\n const merged = {\n ...existing,\n mcpServers: {\n ...servers,\n loom: { type: 'http', url: 'http://localhost:5710/mcp' },\n },\n }\n writeFileSync(path, JSON.stringify(merged, null, 2) + '\\n')\n}\n\ninterface ManagedBlock {\n readonly begin: string\n readonly end: string\n readonly lines: ReadonlyArray<string>\n readonly owned: RegExp\n}\n\nconst withManagedBlock = (text: string, managed: ManagedBlock): Option.Option<string> => {\n const block = [managed.begin, ...managed.lines, managed.end].join('\\n')\n const start = text.indexOf(managed.begin)\n const end = text.indexOf(managed.end, start)\n if (start >= 0 && end > start)\n return Option.some(text.slice(0, start) + block + text.slice(end + managed.end.length))\n if (managed.owned.test(text)) return Option.none()\n const kept = text.replace(/\\s*$/, '')\n return Option.some(kept === '' ? `${block}\\n` : `${kept}\\n\\n${block}\\n`)\n}\n\nconst editorconfigBlock = (width: number): ManagedBlock => ({\n begin: '# Loom: written by `loom init`, which replaces this block on every run',\n end: '# Loom: end',\n lines: ['[*.loom]', `max_line_length = ${width}`],\n owned: /^\\s*\\[\\*\\.loom\\]\\s*$/m,\n})\n\nconst init = (dir: Option.Option<string>) =>\n Effect.gen(function* () {\n const root = resolvePath(\n process.cwd(),\n Option.getOrElse(dir, () => '.'),\n )\n const config = yield* LoomConfig\n yield* banner\n\n const configFile = resolvePath(root, '.loom', 'config.yaml')\n const configured = yield* Effect.sync(() => existsSync(configFile))\n\n if (configured) {\n yield* Console.log(`\\n ${dim(`✓ using the configuration at ${configFile}`)}\\n`)\n } else {\n const language = yield* Prompt.run(\n Prompt.String({\n message: 'Primary language for specifier-less sections',\n default: 'typescript',\n }),\n )\n const activation = yield* Prompt.run(\n Prompt.String({\n message: 'Activate editor services for (space-separated language ids)',\n default: language,\n }),\n )\n const ids = activation.split(/\\s+/).filter((id) => id.length > 0)\n yield* config.materialize(root, {\n corpus: 'corpus',\n languages: Object.fromEntries(ids.map((id) => [id, {}])),\n primary: language,\n ignore: [],\n })\n yield* Effect.sync(() =>\n writeFileSync(resolvePath(root, '.loom', '.gitignore'), 'services/\\n'),\n )\n yield* Console.log(\n `\\n ${teal('✓')} wrote ${configFile}\\n` +\n ` ${dim(`primary language: ${language}`)}\\n` +\n ` ${dim(`activated: ${ids.join(', ') || 'none'}`)}\\n`,\n )\n }\n\n const manifest = yield* config.manifest(root)\n const corpusDir = resolvePath(root, manifest?.corpus ?? 'corpus')\n yield* Effect.sync(() => mkdirSync(corpusDir, { recursive: true }))\n yield* Console.log(` ${teal('✓')} corpus at ${corpusDir}\\n`)\n\n yield* Effect.sync(() => mergeMcpConfig(root))\n yield* Console.log(` ${teal('✓')} wrote ${resolvePath(root, '.mcp.json')}\\n`)\n\n const editorconfig = resolvePath(root, '.editorconfig')\n const current = yield* Effect.sync(() =>\n existsSync(editorconfig) ? readFileSync(editorconfig, 'utf8') : '',\n )\n const block = editorconfigBlock(manifest?.width ?? defaultWidth)\n yield* Option.match(withManagedBlock(current, block), {\n onNone: () => Console.log(` ${dim(`✓ kept the [*.loom] section in ${editorconfig}`)}\\n`),\n onSome: (text) =>\n Effect.sync(() => writeFileSync(editorconfig, text)).pipe(\n Effect.andThen(Console.log(` ${teal('✓')} wrote ${editorconfig}\\n`)),\n ),\n })\n }).pipe(Effect.catchTag('QuitError', () => Console.log(dim('\\n Cancelled.\\n'))))\n\nconst updateLanguages = (\n config: LoomConfig['Service'],\n dir: string,\n change: (ids: ReadonlyArray<string>) => ReadonlyArray<string>,\n): Effect.Effect<void> =>\n Effect.gen(function* () {\n const workspace = workspaceRoot(dir)\n const current = yield* config.manifest(workspace)\n const ids = change(Object.keys(current?.languages ?? {}))\n const languages = Object.fromEntries(ids.map((id) => [id, current?.languages?.[id] ?? {}]))\n yield* config.materialize(workspace, { ...(current ?? {}), languages })\n })\n\nconst add = (language: string) =>\n Effect.gen(function* () {\n const config = yield* LoomConfig\n const dir = process.cwd()\n const change = yield* addService(language, dir)\n yield* updateLanguages(config, dir, (ids) => [...new Set([...ids, language])])\n const service = `${servicePackage(language)} ${serviceVersion}`\n const done = ServiceInstall.$match(change, {\n Current: () => `${service} is already in the store`,\n Installed: () => `installed ${service}`,\n Updated: ({ from }) =>\n `updated ${servicePackage(language)} from ${from} to ${serviceVersion}`,\n })\n yield* Console.log(\n `\\n ${teal('✓')} activated ${language}\\n` +\n ` ${dim(done)}\\n` +\n ` ${dim(`store: ${storeDir(dir)}`)}\\n`,\n )\n }).pipe(\n Effect.catchTag('StoreError', (error) =>\n Console.error(\n `loom: could not install ${servicePackage(error.id)} — ${String(error.cause)}`,\n ).pipe(Effect.andThen(Effect.sync(() => void (process.exitCode = 1)))),\n ),\n )\n\nconst remove = (language: string) =>\n Effect.gen(function* () {\n const config = yield* LoomConfig\n const dir = process.cwd()\n yield* removeService(language, dir)\n yield* updateLanguages(config, dir, (ids) => ids.filter((id) => id !== language))\n yield* Console.log(`\\n ${teal('✓')} removed ${language}\\n`)\n })\n\nconst status = Effect.gen(function* () {\n const config = yield* LoomConfig\n const dir = process.cwd()\n const manifest = yield* config.manifest(workspaceRoot(dir))\n const primary = manifest?.primary\n const languages = Object.keys(manifest?.languages ?? {})\n const mark = (id: string): string =>\n Option.match(installedVersion(id, dir), {\n onNone: () => ` ${dim('○')} ${id}${dim(` — run \\`loom add ${id}\\``)}`,\n onSome: (version) =>\n version === serviceVersion\n ? ` ${teal('●')} ${id}`\n : ` ${dim('◐')} ${id}${dim(` — ${version} is installed; run \\`loom add ${id}\\` for ${serviceVersion}`)}`,\n })\n yield* Console.log(\n `\\n ${dim('store')} ${storeDir(dir)}\\n` +\n ` ${dim('primary')} ${primary ?? dim('(none)')}\\n` +\n ` ${dim('activated')} ${languages.length === 0 ? dim('(none)') : languages.join(', ')}\\n`,\n )\n if (languages.length > 0) yield* Console.log(`${languages.map(mark).join('\\n')}\\n`)\n})\n\nconst set = (name: string, value: string) =>\n Effect.gen(function* () {\n const config = yield* LoomConfig\n const tangler = yield* LoomTangler\n const workspace = workspaceRoot(process.cwd())\n const usage = 'usage: loom set <name> <value>'\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n yield* Console.error(`loom: \\`${name}\\` is not a variable name — ${usage}`)\n yield* Effect.sync(() => void (process.exitCode = 1))\n return\n }\n if (value.startsWith('=')) {\n yield* Console.error(\n `loom: a value cannot begin with \\`=\\`; give the name and value with a space, no \\`=\\` — ${usage}`,\n )\n yield* Effect.sync(() => void (process.exitCode = 1))\n return\n }\n const current = yield* config.manifest(workspace)\n yield* config.materialize(workspace, {\n ...(current ?? {}),\n variables: { ...(current?.variables ?? {}), [name]: value },\n })\n const corpus = resolvePath(workspace, current?.corpus ?? 'corpus')\n const written = yield* tangler.tangle(corpus)\n yield* Console.log(`loom: set ${name} = ${value} (re-tangled ${written.length} files)`)\n }).pipe(\n Effect.catchTag('TangleError', (e) =>\n Console.error(e.message).pipe(Effect.andThen(Effect.sync(() => void (process.exitCode = 1)))),\n ),\n )\n\nclass DesignMissing extends Data.TaggedError('DesignMissing')<{\n readonly directory: string\n}> {}\n\nconst manifestOf = (base: string) =>\n Effect.try(() => createRequire(base).resolve('@athrio/loom-design/package.json'))\n\nconst designBinary = Effect.gen(function* () {\n const directory = process.cwd()\n const manifest = yield* manifestOf(resolvePath(directory, 'index.js')).pipe(\n Effect.catch(() => manifestOf(import.meta.url)),\n Effect.mapError(() => new DesignMissing({ directory })),\n )\n return resolvePath(dirname(manifest), 'dist', 'loom-design.js')\n})\n\nconst design = (project: string, application: string, port: number) =>\n Effect.gen(function* () {\n const binary = yield* designBinary\n const code = yield* Effect.scoped(\n Effect.flatMap(\n ChildProcess.make(binary, [project, application, '--port', String(port)], {\n stdin: 'inherit',\n stdout: 'inherit',\n stderr: 'inherit',\n }),\n (running) => running.exitCode,\n ),\n )\n yield* Effect.sync(() => void (process.exitCode = code))\n }).pipe(\n Effect.catchTag('DesignMissing', () =>\n Console.error(\n 'loom: Loom Design is not installed.\\n' +\n ' Add it with `bun add -d @athrio/loom-design`, then run this again.',\n ).pipe(Effect.andThen(Effect.sync(() => void (process.exitCode = 1)))),\n ),\n Effect.catchCause((cause) =>\n Console.error(`loom: Loom Design could not start\\n${Cause.pretty(cause)}`).pipe(\n Effect.andThen(Effect.sync(() => void (process.exitCode = 1))),\n ),\n ),\n )\n\nclass GrammarMissing extends Data.TaggedError('GrammarMissing')<{}> {}\n\nconst grammarIn = (dir: string): Option.Option<string> =>\n existsSync(resolvePath(dir, 'src', 'parser.c')) ? Option.some(dir) : Option.none()\n\nconst shippedGrammar: Effect.Effect<string, GrammarMissing> = pipe(\n grammarIn(resolvePath(dirname(fileURLToPath(import.meta.url)), 'tree-sitter-loom')),\n Option.orElse(() =>\n Option.flatMap(\n Option.liftThrowable(() =>\n createRequire(import.meta.url).resolve('tree-sitter-loom/package.json'),\n )(),\n (manifest) => grammarIn(dirname(manifest)),\n ),\n ),\n Option.match({\n onNone: () => Effect.fail(new GrammarMissing()),\n onSome: (dir) => Effect.succeed(dir),\n }),\n)\n\nclass GrammarCompileFailed extends Data.TaggedError('GrammarCompileFailed')<{\n readonly compiler: string\n}> {}\n\nconst compileGrammar = (grammar: string, library: string) =>\n Effect.gen(function* () {\n const compiler = process.env.CC ?? 'cc'\n const partial = `${library}.${process.pid}`\n const source = resolvePath(grammar, 'src')\n const code = yield* Effect.scoped(\n Effect.flatMap(\n ChildProcess.make(\n compiler,\n [\n '-shared',\n '-fPIC',\n '-O2',\n '-I',\n source,\n resolvePath(source, 'parser.c'),\n resolvePath(source, 'scanner.c'),\n '-o',\n partial,\n ],\n { stdin: 'inherit', stdout: 'inherit', stderr: 'inherit' },\n ),\n (running) => running.exitCode,\n ),\n ).pipe(Effect.catchCause(() => Effect.succeed(-1)))\n if (code !== 0) return yield* Effect.fail(new GrammarCompileFailed({ compiler }))\n yield* Effect.sync(() => renameSync(partial, library))\n })\n\nconst refuse = (message: string) =>\n Console.error(message).pipe(Effect.andThen(Effect.sync(() => void (process.exitCode = 1))))\n\nconst cannotCompile = (error: GrammarCompileFailed) =>\n refuse(\n `loom: could not compile the grammar with \\`${error.compiler}\\`.\\n` +\n ' Install a C compiler, or name one in the CC variable, then run this again.',\n )\n\nconst helixConfigDir = (): string =>\n process.platform === 'win32'\n ? resolvePath(process.env.APPDATA ?? homedir(), 'helix')\n : resolvePath(process.env.XDG_CONFIG_HOME ?? resolvePath(homedir(), '.config'), 'helix')\n\nconst grammarLibrary = process.platform === 'win32' ? 'loom.dll' : 'loom.so'\n\nconst helixBlock: ManagedBlock = {\n begin: '# Loom: written by `loom helix`, which replaces this block on every run',\n end: '# Loom: end',\n lines: [\n '[[language]]',\n 'name = \"loom\"',\n 'scope = \"source.loom\"',\n 'file-types = [\"loom\"]',\n 'roots = [\".loom\"]',\n 'injection-regex = \"^loom$\"',\n 'language-servers = [\"loom\"]',\n 'soft-wrap = { enable = true, wrap-at-text-width = true }',\n `text-width = ${defaultWidth}`,\n '',\n '[language-server.loom]',\n 'command = \"loom\"',\n 'args = [\"lsp\", \"--stdio\"]',\n ],\n owned: /^\\s*name\\s*=\\s*\"loom\"/m,\n}\n\nclass HelixConfigClash extends Data.TaggedError('HelixConfigClash')<{\n readonly file: string\n}> {}\n\nconst withLoomLanguages = (file: string, text: string): Effect.Effect<string, HelixConfigClash> =>\n Option.match(withManagedBlock(text, helixBlock), {\n onNone: () => Effect.fail(new HelixConfigClash({ file })),\n onSome: Effect.succeed,\n })\n\nconst helix = Effect.gen(function* () {\n const config = helixConfigDir()\n const languagesFile = resolvePath(config, 'languages.toml')\n const grammar = yield* shippedGrammar\n const current = yield* Effect.sync(() =>\n existsSync(languagesFile) ? readFileSync(languagesFile, 'utf8') : '',\n )\n const languages = yield* withLoomLanguages(languagesFile, current)\n\n const library = resolvePath(config, 'runtime', 'grammars', grammarLibrary)\n yield* Effect.sync(() => mkdirSync(dirname(library), { recursive: true }))\n yield* compileGrammar(grammar, library)\n yield* Console.log(`\\n ${teal('✓')} built the grammar into ${library}`)\n\n const queries = resolvePath(config, 'runtime', 'queries', 'loom')\n yield* Effect.sync(() =>\n cpSync(resolvePath(grammar, 'editors', 'helix', 'queries', 'loom'), queries, {\n recursive: true,\n }),\n )\n yield* Console.log(` ${teal('✓')} copied the queries into ${queries}`)\n\n yield* Effect.sync(() => writeFileSync(languagesFile, languages))\n yield* Console.log(\n ` ${teal('✓')} added Loom to ${languagesFile}\\n` +\n ` ${dim('check it with `hx --health loom`')}\\n`,\n )\n}).pipe(\n Effect.catchTags({\n GrammarMissing: () => refuse('loom: this installation of Loom carries no grammar for Helix.'),\n GrammarCompileFailed: cannotCompile,\n HelixConfigClash: (error) =>\n refuse(\n `loom: ${error.file} already sets up Loom.\\n` +\n ' Remove its Loom entries, then run this again to replace them with the managed block.',\n ),\n }),\n)\n\nconst nvimSiteDir = (): string => {\n const name = process.env.NVIM_APPNAME ?? 'nvim'\n return process.platform === 'win32'\n ? resolvePath(process.env.LOCALAPPDATA ?? homedir(), `${name}-data`, 'site')\n : resolvePath(\n process.env.XDG_DATA_HOME ?? resolvePath(homedir(), '.local', 'share'),\n name,\n 'site',\n )\n}\n\nconst nvimHeader = '-- Loom: written by `loom nvim`, which replaces this file on every run'\n\nconst nvimPlugin = [\n nvimHeader,\n \"vim.filetype.add({ extension = { loom = 'loom' } })\",\n '',\n \"vim.lsp.config('loom', {\",\n \" cmd = { 'loom', 'lsp', '--stdio' },\",\n \" filetypes = { 'loom' },\",\n \" root_markers = { '.loom', '.git' },\",\n '})',\n \"vim.lsp.enable('loom')\",\n '',\n \"vim.api.nvim_create_autocmd('FileType', {\",\n \" pattern = 'loom',\",\n ' callback = function()',\n ' vim.treesitter.start()',\n \" vim.opt_local.formatoptions:remove({ 't', 'c' })\",\n ' end,',\n '})',\n '',\n].join('\\n')\n\nclass NvimConfigClash extends Data.TaggedError('NvimConfigClash')<{\n readonly file: string\n}> {}\n\nconst nvim = Effect.gen(function* () {\n const site = nvimSiteDir()\n const pluginFile = resolvePath(site, 'plugin', 'loom.lua')\n const grammar = yield* shippedGrammar\n const current = yield* Effect.sync(() =>\n existsSync(pluginFile) ? Option.some(readFileSync(pluginFile, 'utf8')) : Option.none<string>(),\n )\n if (Option.exists(current, (text) => !text.startsWith(nvimHeader)))\n return yield* Effect.fail(new NvimConfigClash({ file: pluginFile }))\n\n const parser = resolvePath(site, 'parser', 'loom.so')\n yield* Effect.sync(() => mkdirSync(dirname(parser), { recursive: true }))\n yield* compileGrammar(grammar, parser)\n yield* Console.log(`\\n ${teal('✓')} built the grammar into ${parser}`)\n\n const queries = resolvePath(site, 'queries', 'loom')\n yield* Effect.sync(() => cpSync(resolvePath(grammar, 'queries'), queries, { recursive: true }))\n yield* Console.log(` ${teal('✓')} copied the queries into ${queries}`)\n\n yield* Effect.sync(() => {\n mkdirSync(dirname(pluginFile), { recursive: true })\n writeFileSync(pluginFile, nvimPlugin)\n })\n yield* Console.log(\n ` ${teal('✓')} added Loom to ${pluginFile}\\n` +\n ` ${dim('check it with `:checkhealth vim.treesitter` in Neovim')}\\n`,\n )\n}).pipe(\n Effect.catchTags({\n GrammarMissing: () => refuse('loom: this installation of Loom carries no grammar for Neovim.'),\n GrammarCompileFailed: cannotCompile,\n NvimConfigClash: (error) =>\n refuse(\n `loom: ${error.file} was not written by \\`loom nvim\\`.\\n` +\n ' Move it aside, then run this again.',\n ),\n }),\n)\n\nconst tangleCommand = Command.make(\n 'tangle',\n { path: Argument.String('path'), watch: Flag.Boolean('watch').pipe(Flag.withDefault(false)) },\n ({ path, watch }) => tangle(path, watch),\n)\n\nconst orphansCommand = Command.make(\n 'orphans',\n { prune: Flag.Boolean('prune').pipe(Flag.withDefault(false)) },\n ({ prune }) => orphans(prune),\n)\n\nconst weaveCommand = Command.make(\n 'weave',\n { path: Argument.String('path'), out: Argument.String('out') },\n ({ path, out }) => weave(path, out),\n)\n\nconst formatCommand = Command.make(\n 'format',\n { path: Argument.String('path'), check: Flag.Boolean('check').pipe(Flag.withDefault(false)) },\n ({ path, check }) => format(path, check),\n)\n\nconst tocCommand = Command.make('toc', { path: Argument.String('path') }, ({ path }) => toc(path))\n\nconst initCommand = Command.make(\n 'init',\n { dir: Argument.optional(Argument.Directory('dir')) },\n ({ dir }) => init(dir),\n)\n\nconst addCommand = Command.make('add', { language: Argument.String('language') }, ({ language }) =>\n add(language),\n)\n\nconst removeCommand = Command.make(\n 'remove',\n { language: Argument.String('language') },\n ({ language }) => remove(language),\n)\n\nconst statusCommand = Command.make('status', {}, () => status)\n\nconst setCommand = Command.make(\n 'set',\n { name: Argument.String('name'), value: Argument.String('value') },\n ({ name, value }) => set(name, value),\n)\n\nconst designCommand = Command.make(\n 'design',\n {\n project: Argument.String('name'),\n application: Argument.String('address'),\n port: Flag.Int('port').pipe(Flag.withDefault(5710)),\n },\n ({ project, application, port }) => design(project, application, port),\n)\n\nconst helixCommand = Command.make('helix', {}, () => helix)\n\nconst nvimCommand = Command.make('nvim', {}, () => nvim)\n\nconst loom = Command.make('loom').pipe(\n Command.withSubcommands([\n tangleCommand,\n orphansCommand,\n weaveCommand,\n tocCommand,\n formatCommand,\n initCommand,\n addCommand,\n removeCommand,\n statusCommand,\n setCommand,\n designCommand,\n helixCommand,\n nvimCommand,\n ]),\n)\n\nconst program = Command.run(loom, {\n version: '0.0.12',\n}).pipe(\n Effect.provide(LoomTangler.layer),\n Effect.provide(LoomWeaver.layer),\n Effect.provide(LoomContents.layer),\n Effect.provide(LoomFormatter.layer),\n Effect.provide(DocumentSource.layer),\n Effect.provide(PackageConfig.layer),\n Effect.provide(LoomConfig.layer),\n Effect.provide(NodeServices.layer),\n)\n\nif (process.argv[2] === 'lsp') {\n ;(globalThis as { require?: unknown }).require = createRequire(import.meta.url)\n const { startLanguageServer } = await import('@athrio/loom-lang/LoomServer')\n startLanguageServer()\n} else {\n NodeRuntime.runMain(program)\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,IAAMA,WAAS;;;;;;;;;;;;;;;;;;;;;;AAsBf,IAAa,cAAa,MAAKC,YAAsB,GAAGD,QAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmC9D,IAAa,qBAAb,cAAqDE,YAAmB,GAAGF,SAAO,oBAAoB,CAAC,CAAC,sBAAsB;CAC5H,QAAQG;CACR,SAAsB,yBAA6B,0BAAaA,QAAa,CAAC;CAC9E,aAA0B,0BAAaA,QAAa;AACtD,CAAC,CAAC,CAAC;;;;;;;CAOD,CAACH,YAAUA;;;;;;;CAOX,IAAI,UAAU;EACZ,MAAM,iBAAiB,KAAK,YAAY,SAAS,IAAI,iCAAiC,KAAK,YAAY,KAAK,QAAQ,MAAM;EAE1H,QADoB,KAAK,UAAU,sBAAsB,KAAK,OAAO,cAAc,KAAK,QAAQ,KAAK,GAAG,MAAM,sBAAsB,KAAK,YACpH;CACvB;AACF;;;;;;;;;;;;;;;;;;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AAsC,UAAU,cAAc,OAAO,KAAK,GAAG;CAC9E,MAAM,EAAE,wBAAwB,MAAM,OAAO;CAC7C,oBAAoB;AACtB,OACE,QAAoB,OAAO"}
1
+ {"version":3,"file":"main.js","names":["TypeId","Predicate.hasProperty","Schema.TaggedError","Schema.String","Runtime.errorReported","Runtime.errorExitCode","Proto","Schema.TrueLiterals","Schema.FalseLiterals","toCodecStringTree","Schema.toCodecStringTree","Schema.decodeUnknownEffect","Effect.mapError","Boolean","Schema.BooleanLiterals","Int","Schema.Int","String","Effect.succeed","format","Effect.fail","Path","Effect.fnUntraced","FileSystem.FileSystem","Path_.Path","reset","TypeId","Ansi.cyanBright","Ansi.blackBright","Ansi.green","Ansi.red","Ansi.white","Ansi.detectColors","Effect.map","Ansi.annotate","Ansi.combine","Ansi.italicized","Date","Effect.succeed","Option.none","Number","Effect.fail","Int","map","Redacted.make","run","Terminal.Terminal","Effect.cached","Terminal.QuitError","Effect.scoped","String","Effect.suspend","Effect.flatMap","Effect.isEffect","Action","Effect.orDie","Queue.take","Effect.raceFirst","Effect.ensuring","Ansi.cursorShow","Ansi.eraseLine","Ansi.cursorTo","Ansi.eraseLines","Arr.map","Arr.reduce","Ansi.cursorDown","Effect.fnUntraced","Ansi.cursorLeft","Ansi.cursorHide","Option.getOrElse","Option.isSome","Arr.match","Arr.isReadonlyArrayNonEmpty","Ansi.cursorSavePosition","Ansi.cursorRestorePosition","Ansi.underlined","Option.match","Effect.match","Option.some","Arr.empty","Arr.findFirstIndex","Arr.findFirst","Arr.findLast","Ansi.bold","Effect.sync","EffectNumber.round","Ansi.strikethrough","Ansi.cursorMove","TypeId","Proto","Predicate.hasProperty","Option.none","String","Primitive.String","Boolean","Primitive.Boolean","Int","Primitive.Int","ChoiceWithValue","Primitive.Choice","Path","Primitive.Path","Directory","withAlias","withDescription","Option.some","Effect.map","Effect.flatMap","optional","Effect.catchTags","Effect.succeed","withDefault","Effect.isEffect","Option.getOrElse","Option.match","variadic","Option.fromUndefinedOr","withMetavar","CliError.MissingArgument","Effect.mapError","CliError.InvalidValue","CliError.MissingOption","Predicate.isNotUndefined","Option.getOrUndefined","String","Param.String","Param.argumentKind","Param.Directory","optional","Param.optional","Param.isParam","Param.variadic","Ansi.detectColors","Option.getOrElse","Param.isParam","TypeId","Proto","Context.Service","Context.empty","Predicate.isNotUndefined","Effect.fail","CliError.ShowHelp","Param.extractSingleParams","Param.getParamMetadata","Primitive.getTypeName","Option.exists","Arr.map","Primitive.getChoiceKeys","Option.match","Option.some","Effect.fnUntraced","CliError.UnexpectedArgument","CliError.DuplicateOption","Primitive.getChoiceKeys","Primitive.getPathType","Param.extractSingleParams","Option.getOrUndefined","Param.getParamMetadata","generateFunction","generate","generate","sanitize","generate","generate","Bash.generate","Zsh.generate","Fish.generate","PowerShell.generate","Param.Boolean","Param.flagKind","Param.Int","Param.ChoiceWithValue","Param.withAlias","Param.withDescription","Param.withMetavar","Param.optional","Param.withDefault","Param.extractSingleParams","Param.getParamMetadata","Effect.gen","Context.Service","CliOutput.Formatter","HelpInternal.getHelpForCommandPath","Console.log","Effect.void","Flag.optional","Option.isNone","CommandDescriptor.fromCommand","Completions_.generate","Context.Reference","GlobalFlag.BuiltIns","Option.match","Effect.gen","Param.extractSingleParams","Param.isFlagParam","Option.none","Option.some","Primitive.isBoolean","CliError.InvalidValue","Primitive.getChoiceKeys","Primitive.getTypeName","Primitive.isTrueLiteral","Primitive.isFalseLiteral","CliError.UnrecognizedOption","CliError.UnknownSubcommand","run","Prompt.Theme","Console.log","Prompt.run","Prompt.Select","Param.getUnderlyingSingleOrThrow","Param.getParamMetadata","Prompt.Confirm","Prompt.Int","Option.getOrElse","Option.isSome","Effect.map","Primitive.getChoiceKeys","Prompt.Date","Prompt.Number","Prompt.Password","Redacted.value","value","Prompt.String","Option.getOrUndefined","Ansi.magenta","Ansi.annotate","Ansi.bold","Ansi.cyanBright","Ansi.blackBright","Ansi.white","Ansi.green","Ansi.red","Predicate.hasProperty","TypeId","make","Predicate.isNotUndefined","Effect.fnUntraced","Option.isNone","internal","CliError.ShowHelp","Effect.provideService","Param.extractSingleParams","CliError.UnrecognizedOption","Effect.gen","CliConfig.CliConfig","CliOutput.Formatter","error","Console.log","Console.error","Runtime.errorReported","Effect.flatMap","Lexer.lex","Parser.createFlagRegistry","Param.isFlagParam","Parser.consumeGlobalFlags","Parser.parseArgs","Parser.getCommandPath","GlobalFlag.Wizard","Prompt.Theme","Wizard.renderIntroduction","Wizard.run","Wizard.renderCompletion","Prompt.run","Prompt.Toggle","Effect.catchTag","Wizard.renderQuit","Effect.result","GlobalFlag.LogLevel","Option.none","Option.match","Context.empty","Context.make","References.MinimumLogLevel","Effect.provideContext","Effect.catchFilter","CliError.isCliError","Result.succeed","Result.fail","Effect.andThen","Effect.fail","Terminal.isQuitError","Effect.interrupt","Inspectable.BaseProto","make","Effect.map","Stream.decodeText","Stream.unwrap","Stream.splitLines","Effect.scoped","Effect.flatMap","Stream.runCollect","Stream.mkString","Context.Service","Context.getUnsafe","make","PlatformError.systemError","Sink.fromChannel","Channel.mapDone","Channel.fromTransform","Effect.succeed","Effect.flatMap","Effect.callback","Effect.void","Effect.sync","Effect.forever","Pull.catchDone","Cause.done","Effect.raceFirst","Effect.fail","Stream.fromChannel","Channel.fromTransform","MutableRef.make","Latch.makeUnsafe","Exit.fail","Cause.Done","Effect.suspend","Effect.fail","Effect.flatMap","Arr.of","Effect.succeed","Effect.as","Scope.addFinalizer","Effect.sync","Cause.UnknownError","Deferred.isDoneUnsafe","make","FileSystem.FileSystem","Path.Path","Effect.fnUntraced","Predicate.isUndefined","Stream.isStream","Sink.isSink","ChildProcess.parseFdName","Predicate.isNotUndefined","Sink.drain","Stream.empty","NodeSink.fromWritable","Effect.forkScoped","Stream.run","NodeStream.fromReadable","Stream.transduce","Effect.suspend","Predicate.isNotNull","Effect.as","Effect.succeed","Stream.merge","Effect.callback","Deferred.makeUnsafe","Effect.fail","Exit.succeed","Effect.sync","Effect.void","Effect.try","Effect.catch","Duration.toMillis","Deferred.await","Effect.acquireRelease","Deferred.isDone","Effect.ignore","Effect.map","Effect.flatMap","Stream.unwrap","ChildProcess.make","fdName","ChildProcess.fdName","Effect.forEach","Effect.gen","makeSpawner","layer","Effect.try","PlatformError.systemError","make","layer","EffectCrypto.Crypto","layer","NodeCrypto.layer","Error.badArgument","Option.flatMap","Option.fromNullishOr","BI.toNumber","Option.map","Effect.try","Effect.suspend","remove","Effect.acquireRelease","Effect.orDie","Effect.fail","Effect.succeed","Effect.flatMap","Effect.map","FileSystem.FileTypeId","Option.none","Option.some","Error.systemError","Effect.void","Effect.fnUntraced","Crypto","Effect.tryPromise","Effect.callback","ByteSize.bytes","Stream.callback","Effect.sync","Effect.matchEffect","Queue.offer","Cause.fail","Effect.tap","Effect.all","Effect.serviceOption","FileSystem.WatchBackend","Option.orElse","Option.getOrElse","Stream.unwrap","FileSystem.make","layer","FileSystem.FileSystem","layer","NodeFileSystem.layer","Effect.try","Path","NodePath","layer","layer","NodePath.layer","layer","Stdio.Stdio","layer","NodeStdio.layer","Queue.make","Effect.addFinalizer","Effect.sync","RcRef.make","Effect.acquireRelease","Queue.offerUnsafe","Effect.gen","Option.fromUndefinedOr","RcRef.get","Effect.suspend","Queue.poll","Effect.flatMap","Option.match","Effect.scoped","Effect.andThen","Queue.take","Effect.succeed","Effect.mapError","Terminal.QuitError","Effect.uninterruptible","Effect.callback","Predicate.isNullish","Effect.void","Effect.fail","Terminal.make","layer","Terminal.Terminal","layer","NodeTerminal.layer","NodeChildProcessSpawner.layer","NodeFileSystem.layer","NodeCrypto.layer","NodePath.layer","NodeStdio.layer","NodeTerminal.layer","runMain","NodeRuntime.runMain"],"sources":["../../../node_modules/effect/dist/cli/CliError.js","../../../node_modules/effect/dist/cli/Primitive.js","../../../node_modules/effect/dist/cli/internal/ansi.js","../../../node_modules/effect/dist/cli/Prompt.js","../../../node_modules/effect/dist/cli/Param.js","../../../node_modules/effect/dist/cli/Argument.js","../../../node_modules/effect/dist/cli/CliOutput.js","../../../node_modules/effect/dist/cli/internal/config.js","../../../node_modules/effect/dist/cli/internal/command.js","../../../node_modules/effect/dist/cli/internal/completions/descriptor.js","../../../node_modules/effect/dist/cli/internal/completions/bash.js","../../../node_modules/effect/dist/cli/internal/completions/fish.js","../../../node_modules/effect/dist/cli/internal/completions/powershell.js","../../../node_modules/effect/dist/cli/internal/completions/zsh.js","../../../node_modules/effect/dist/cli/Completions.js","../../../node_modules/effect/dist/cli/Flag.js","../../../node_modules/effect/dist/cli/internal/help.js","../../../node_modules/effect/dist/cli/GlobalFlag.js","../../../node_modules/effect/dist/cli/CliConfig.js","../../../node_modules/effect/dist/cli/internal/lexer.js","../../../node_modules/effect/dist/cli/internal/auto-suggest.js","../../../node_modules/effect/dist/cli/internal/parser.js","../../../node_modules/effect/dist/cli/internal/wizard.js","../../../node_modules/effect/dist/cli/Command.js","../../../node_modules/effect/dist/process/ChildProcessSpawner.js","../../../node_modules/effect/dist/process/ChildProcess.js","../../../node_modules/@effect/platform-node-shared/dist/internal/nodeChildProcessSpawner.js","../../../node_modules/@effect/platform-node-shared/dist/internal/utils.js","../../../node_modules/@effect/platform-node-shared/dist/NodeSink.js","../../../node_modules/@effect/platform-node-shared/dist/NodeStream.js","../../../node_modules/@effect/platform-node-shared/dist/NodeChildProcessSpawner.js","../../../node_modules/@effect/platform-node-shared/dist/NodeCrypto.js","../../../node_modules/@effect/platform-node/dist/NodeCrypto.js","../../../node_modules/@effect/platform-node-shared/dist/NodeFileSystem.js","../../../node_modules/@effect/platform-node/dist/NodeFileSystem.js","../../../node_modules/@effect/platform-node-shared/dist/NodePath.js","../../../node_modules/@effect/platform-node/dist/NodePath.js","../../../node_modules/@effect/platform-node-shared/dist/NodeStdio.js","../../../node_modules/@effect/platform-node/dist/NodeStdio.js","../../../node_modules/@effect/platform-node-shared/dist/NodeTerminal.js","../../../node_modules/@effect/platform-node/dist/NodeTerminal.js","../../../node_modules/@effect/platform-node/dist/NodeServices.js","../../../node_modules/@effect/platform-node-shared/dist/NodeRuntime.js","../../../node_modules/@effect/platform-node/dist/NodeRuntime.js","../../loom-lang/src/LoomLock.ts","../../loom-lang/src/LoomTangler.ts","../../loom-lang/src/weave/LoomWeaver.ts","../../loom-lang/src/weave/LoomContents.ts","../src/main.ts"],"sourcesContent":["/**\n * Defines structured errors for the unstable CLI parser and runner.\n *\n * CLI errors describe problems such as unknown or duplicate flags, missing\n * flags or arguments, unexpected positional arguments, invalid values, unknown\n * subcommands, user handler failures, and requests to show command help. This\n * module includes the `CliError` union, the `isCliError` guard, schema-backed\n * error classes with display messages, and the `NonShowHelpErrors` union used\n * when parse or validation errors should be shown with help output.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Predicate from \"../Predicate.js\";\nimport * as Runtime from \"../Runtime.js\";\nimport * as Schema from \"../Schema.js\";\n/**\n * @stability unstable\n * @category type IDs\n * @since 4.0.0\n */\nconst TypeId = \"~effect/cli/CliError\";\n/**\n * Type guard to check if a value is a CLI error.\n *\n * **Example** (Checking CLI errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/cli\"\n *\n * const error = new CliError.MissingOption({ option: \"api-key\" })\n * const program = CliError.isCliError(error)\n * ? Effect.succeed(error.message)\n * : Effect.fail(\"Unknown error\")\n *\n * await Effect.runPromise(program) // => \"Missing required flag: --api-key\"\n * ```\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isCliError = u => Predicate.hasProperty(u, TypeId);\n/**\n * Error thrown when an unrecognized option is encountered.\n *\n * **Example** (Creating unrecognized option errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/cli\"\n *\n * // Creating an unrecognized option error\n * const unrecognizedError = new CliError.UnrecognizedOption({\n * option: \"--unknown-flag\",\n * command: [\"deploy\", \"production\"],\n * suggestions: [\"--verbose\", \"--force\"]\n * })\n *\n * unrecognizedError._tag // => \"UnrecognizedOption\"\n * unrecognizedError.option // => \"--unknown-flag\"\n * unrecognizedError.command // => [\"deploy\", \"production\"]\n *\n * // In CLI parsing context\n * const parseCommand = Effect.gen(function*() {\n * // If parsing encounters unknown flag\n * return yield* unrecognizedError\n * })\n *\n * const parseError = await Effect.runPromise(Effect.flip(parseCommand))\n * parseError._tag // => \"UnrecognizedOption\"\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class UnrecognizedOption extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/UnrecognizedOption`)(\"UnrecognizedOption\", {\n option: Schema.String,\n command: /*#__PURE__*/Schema.optional(/*#__PURE__*/Schema.Array(Schema.String)),\n suggestions: /*#__PURE__*/Schema.Array(Schema.String)\n}) {\n /**\n * Marks this value as a CLI parsing error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Formats the unrecognized option with command context and suggestions.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n const suggestionText = this.suggestions.length > 0 ? `\\n\\n Did you mean this?\\n ${this.suggestions.join(\"\\n \")}` : \"\";\n const baseMessage = this.command ? `Unrecognized flag: ${this.option} in command ${this.command.join(\" \")}` : `Unrecognized flag: ${this.option}`;\n return baseMessage + suggestionText;\n }\n}\n/**\n * Error thrown when duplicate option names are detected between parent and child commands.\n *\n * **Example** (Creating duplicate option errors)\n *\n * ```ts import.meta.vitest\n * import { CliError } from \"effect/cli\"\n *\n * const duplicateError = new CliError.DuplicateOption({\n * option: \"--verbose\",\n * parentCommand: \"myapp\",\n * childCommand: \"deploy\"\n * })\n *\n * duplicateError._tag // => \"DuplicateOption\"\n * duplicateError.option // => \"--verbose\"\n * duplicateError.parentCommand // => \"myapp\"\n * duplicateError.childCommand // => \"deploy\"\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class DuplicateOption extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/DuplicateOption`)(\"DuplicateOption\", {\n option: Schema.String,\n parentCommand: Schema.String,\n childCommand: Schema.String\n}) {\n /**\n * Marks this value as a CLI configuration error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Explains which parent and child commands define the duplicate option.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n return `Duplicate flag name \"${this.option}\" in parent command \"${this.parentCommand}\" and subcommand \"${this.childCommand}\". ` + `Parent will always claim this flag (Mode A semantics). Consider renaming one of them to avoid confusion.`;\n }\n}\n/**\n * Error thrown when a required option is missing.\n *\n * **Example** (Creating missing option errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/cli\"\n *\n * const missingOptionError = new CliError.MissingOption({\n * option: \"api-key\"\n * })\n *\n * const details = [missingOptionError._tag, missingOptionError.option] // => [\"MissingOption\", \"api-key\"]\n *\n * // In validation context\n * const validateRequiredOptions = (options: Record<string, string | undefined>) =>\n * Effect.gen(function*() {\n * const apiKey = options[\"api-key\"]\n * if (!apiKey) {\n * return yield* missingOptionError\n * }\n * return apiKey\n * })\n *\n * const validationError = await Effect.runPromise(Effect.flip(validateRequiredOptions({})))\n * validationError._tag // => \"MissingOption\"\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class MissingOption extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/MissingOption`)(\"MissingOption\", {\n option: Schema.String\n}) {\n /**\n * Marks this value as a missing CLI option error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Formats the missing required flag for display.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n return `Missing required flag: --${this.option}`;\n }\n}\n/**\n * Error thrown when a required positional argument is missing.\n *\n * **Example** (Creating missing argument errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/cli\"\n *\n * const missingArgError = new CliError.MissingArgument({\n * argument: \"target\"\n * })\n *\n * const details = [missingArgError._tag, missingArgError.argument] // => [\"MissingArgument\", \"target\"]\n *\n * // In argument parsing\n * const parseArguments = (args: Array<string>) =>\n * Effect.gen(function*() {\n * if (args.length === 0) {\n * return yield* missingArgError\n * }\n * return args[0]\n * })\n *\n * const parseError = await Effect.runPromise(Effect.flip(parseArguments([])))\n * parseError._tag // => \"MissingArgument\"\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class MissingArgument extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/MissingArgument`)(\"MissingArgument\", {\n argument: Schema.String\n}) {\n /**\n * Marks this value as a missing CLI argument error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Formats the missing required positional argument for display.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n return `Missing required argument: ${this.argument}`;\n }\n}\n/**\n * Error thrown when positional arguments remain after a command has parsed all\n * of its parameters.\n *\n * **Example** (Reporting unexpected arguments)\n *\n * ```ts import.meta.vitest\n * import { CliError } from \"effect/cli\"\n *\n * const error = new CliError.UnexpectedArgument({\n * arguments: [\"extra.txt\"]\n * })\n *\n * const details = [error._tag, error.arguments] // => [\"UnexpectedArgument\", [\"extra.txt\"]]\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class UnexpectedArgument extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/UnexpectedArgument`)(\"UnexpectedArgument\", {\n arguments: /*#__PURE__*/Schema.Array(Schema.String)\n}) {\n /**\n * Marks this value as an unexpected CLI argument error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Formats the unexpected positional arguments for display.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n const label = this.arguments.length === 1 ? \"argument\" : \"arguments\";\n return `Unexpected positional ${label}: ${this.arguments.map(value => JSON.stringify(value)).join(\", \")}`;\n }\n}\n/**\n * Error thrown when an option or argument value is invalid.\n *\n * **Example** (Creating invalid value errors)\n *\n * ```ts import.meta.vitest\n * import { CliError } from \"effect/cli\"\n *\n * const invalidValueError = new CliError.InvalidValue({\n * option: \"port\",\n * value: \"abc123\",\n * expected: \"integer between 1 and 65535\",\n * kind: \"flag\"\n * })\n *\n * invalidValueError._tag // => \"InvalidValue\"\n * invalidValueError.kind // => \"flag\"\n * invalidValueError.option // => \"port\"\n * invalidValueError.value // => \"abc123\"\n *\n * // For positional arguments\n * const invalidArgError = new CliError.InvalidValue({\n * option: \"count\",\n * value: \"abc\",\n * expected: \"integer\",\n * kind: \"argument\"\n * })\n *\n * const details = [invalidArgError.kind, invalidArgError.option, invalidArgError.value] // => [\"argument\", \"count\", \"abc\"]\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class InvalidValue extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/InvalidValue`)(\"InvalidValue\", {\n option: Schema.String,\n value: Schema.String,\n expected: Schema.String,\n kind: /*#__PURE__*/Schema.Union([/*#__PURE__*/Schema.Literal(\"flag\"), /*#__PURE__*/Schema.Literal(\"argument\")])\n}) {\n /**\n * Marks this value as an invalid CLI value error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Formats the invalid flag or argument value with the expected input.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n const expectation = this.expected.startsWith(\"Expected \") || this.expected.startsWith(\"Expected:\") ? this.expected : `Expected: ${this.expected}`;\n if (this.kind === \"argument\") {\n return `Invalid value for argument <${this.option}>: \"${this.value}\". ${expectation}`;\n }\n if (this.value.length === 0) {\n return `Missing value for flag --${this.option}. ${expectation}`;\n }\n return `Invalid value for flag --${this.option}: \"${this.value}\". ${expectation}`;\n }\n}\n/**\n * Error thrown when an unknown subcommand is encountered.\n *\n * **Example** (Creating unknown subcommand errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/cli\"\n *\n * const unknownSubcommandError = new CliError.UnknownSubcommand({\n * subcommand: \"deplyo\", // typo\n * parent: [\"myapp\"],\n * suggestions: [\"deploy\", \"destroy\"]\n * })\n *\n * unknownSubcommandError._tag // => \"UnknownSubcommand\"\n * unknownSubcommandError.subcommand // => \"deplyo\"\n * unknownSubcommandError.parent // => [\"myapp\"]\n *\n * // In subcommand parsing\n * const parseSubcommand = (subcommand: string) =>\n * Effect.gen(function*() {\n * const validCommands = [\"deploy\", \"destroy\", \"status\"]\n * if (!validCommands.includes(subcommand)) {\n * return yield* unknownSubcommandError\n * }\n * return subcommand\n * })\n *\n * const parseError = await Effect.runPromise(Effect.flip(parseSubcommand(\"deplyo\")))\n * parseError._tag // => \"UnknownSubcommand\"\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class UnknownSubcommand extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/UnknownSubcommand`)(\"UnknownSubcommand\", {\n subcommand: Schema.String,\n parent: /*#__PURE__*/Schema.optional(/*#__PURE__*/Schema.Array(Schema.String)),\n suggestions: /*#__PURE__*/Schema.Array(Schema.String)\n}) {\n /**\n * Marks this value as an unknown CLI subcommand error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Formats the unknown subcommand with parent command context and suggestions.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n const suggestionText = this.suggestions.length > 0 ? `\\n\\n Did you mean this?\\n ${this.suggestions.join(\"\\n \")}` : \"\";\n return this.parent ? `Unknown subcommand \"${this.subcommand}\" for \"${this.parent.join(\" \")}\"${suggestionText}` : `Unknown subcommand \"${this.subcommand}\"${suggestionText}`;\n }\n}\n/**\n * Error wrapper for user handler failures in the CLI error channel.\n *\n * **Details**\n *\n * `userMessage` can provide safe, user-facing text independently of the\n * underlying cause. When omitted or empty, `message` uses a non-empty string\n * cause or `Error.message`, then falls back to `\"An error occurred\"`.\n *\n * **Example** (Wrapping user errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/cli\"\n *\n * // Wrapping user errors\n * const userError = new CliError.UserError({\n * cause: new Error(\"Database connection failed for postgres://localhost\"),\n * userMessage: \"Could not connect to the database\"\n * })\n *\n * // In command handler\n * const deployCommand = Effect.gen(function*() {\n * const result = yield* Effect.try({\n * try: () => ({ deployed: true }),\n * catch: (error) => new CliError.UserError({ cause: error })\n * })\n * return result\n * })\n *\n * // In error handling\n * const handleError = (error: CliError.CliError): Effect.Effect<number> => {\n * if (error._tag === \"UserError\") {\n * return Effect.succeed(1) // Exit code 1\n * }\n * return Effect.succeed(0)\n * }\n *\n * await Effect.runPromise(deployCommand) // => { deployed: true }\n * await Effect.runPromise(handleError(userError)) // => 1\n * ```\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class UserError extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/UserError`)(\"UserError\", {\n cause: /*#__PURE__*/Schema.Defect(),\n userMessage: /*#__PURE__*/Schema.optionalKey(Schema.String)\n}) {\n /**\n * Marks this value as a user handler error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [TypeId] = TypeId;\n /**\n * Controls whether the runtime logger should report this error. The CLI\n * runner sets this to `false` after rendering the error itself.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [Runtime.errorReported] = true;\n /**\n * Returns the explicit user-facing message or a safe fallback from `cause`.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n if (this.userMessage) return this.userMessage;\n if (typeof this.cause === \"string\" && this.cause) return this.cause;\n if (this.cause instanceof Error && this.cause.message) return this.cause.message;\n return \"An error occurred\";\n }\n}\n/**\n * Schema for concrete CLI errors that can be reported together with help output.\n *\n * **Details**\n *\n * This excludes `ShowHelp` itself, allowing parse and validation errors to be\n * stored in `ShowHelp.errors` without nesting another help-control value.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const NonShowHelpErrors = /*#__PURE__*/Schema.Union([UnrecognizedOption, DuplicateOption, MissingOption, MissingArgument, UnexpectedArgument, InvalidValue, UnknownSubcommand, UserError]);\n/**\n * Error data requesting CLI help rendering for a command path.\n *\n * **Details**\n *\n * It is used for explicit help requests and for parse or validation failures\n * that should be shown with help text. When `errors` is non-empty, the runtime\n * exit code is `1`; otherwise it is `0`.\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class ShowHelp extends /*#__PURE__*/Schema.TaggedError(`${TypeId}/ShowHelp`)(\"ShowHelp\", {\n commandPath: /*#__PURE__*/Schema.Array(Schema.String),\n errors: /*#__PURE__*/Schema.Array(NonShowHelpErrors)\n}) {\n [TypeId] = TypeId;\n [Runtime.errorExitCode] = this.errors.length ? 1 : 0;\n [Runtime.errorReported] = false;\n get message() {\n return \"Help requested\";\n }\n}\n//# sourceMappingURL=CliError.js.map","/**\n * Parses raw command-line strings into typed values.\n *\n * A `Primitive<A>` receives one string and returns an `Effect` that either\n * produces an `A` or fails with a parser message. `Argument` and `Flag` build\n * on these primitives to add names, aliases, defaults, prompts, configuration\n * fallbacks, repetition, and help metadata. Primitive parsers cover common\n * scalar values, paths, files, structured config files, schema-decoded input,\n * redacted values, and key-value pairs.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Effect from \"../Effect.js\";\nimport * as Ini from \"../encoding/Ini.js\";\nimport * as Toml from \"../encoding/Toml.js\";\nimport * as Yaml from \"../encoding/Yaml.js\";\nimport * as FileSystem from \"../FileSystem.js\";\nimport { format } from \"../Formatter.js\";\nimport { identity } from \"../Function.js\";\nimport * as Path_ from \"../Path.js\";\nimport * as Redacted_ from \"../Redacted.js\";\nimport * as Schema from \"../Schema.js\";\nconst TypeId = \"~effect/cli/Primitive\";\nconst Proto = {\n [TypeId]: {\n _A: identity\n }\n};\n/**\n * @internal\n */\nexport const isTrueLiteral = /*#__PURE__*/Schema.is(Schema.TrueLiterals);\n/**\n * @internal\n */\nexport const isFalseLiteral = /*#__PURE__*/Schema.is(Schema.FalseLiterals);\n/**\n * @internal\n */\nexport const isBoolean = p => p._tag === \"Boolean\";\nconst makePrimitive = (tag, parse) => Object.assign(Object.create(Proto), {\n _tag: tag,\n parse\n});\nconst makeSchemaPrimitive = (tag, schema) => {\n const toCodecStringTree = Schema.toCodecStringTree(schema);\n const decode = Schema.decodeUnknownEffect(toCodecStringTree);\n return makePrimitive(tag, value => Effect.mapError(decode(value), error => error.message));\n};\n/**\n * Creates a primitive that parses boolean values from string input.\n *\n * **Details**\n *\n * Recognizes various forms of true/false values:\n * - True values: \"true\", \"1\", \"y\", \"yes\", \"on\"\n * - False values: \"false\", \"0\", \"n\", \"no\", \"off\"\n *\n * **Example** (Parsing boolean values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parseBoolean = Effect.all([\n * Primitive.Boolean.parse(\"true\"),\n * Primitive.Boolean.parse(\"yes\"),\n * Primitive.Boolean.parse(\"false\"),\n * Primitive.Boolean.parse(\"0\")\n * ])\n *\n * await Effect.runPromise(parseBoolean.pipe(Effect.provide(CliTestLayer))) // => [true, true, false, false]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Boolean = /*#__PURE__*/makeSchemaPrimitive(\"Boolean\", Schema.BooleanLiterals);\n/**\n * Creates a primitive that parses finite numbers from string input.\n *\n * **Example** (Parsing finite numbers)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parseFloat = Effect.all([\n * Primitive.Finite.parse(\"3.14\"),\n * Primitive.Finite.parse(\"-42.5\"),\n * Primitive.Finite.parse(\"0\")\n * ])\n *\n * await Effect.runPromise(parseFloat.pipe(Effect.provide(CliTestLayer))) // => [3.14, -42.5, 0]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Finite = /*#__PURE__*/makeSchemaPrimitive(\"Finite\", Schema.Finite);\n/**\n * Creates a primitive that parses integer numbers from string input.\n *\n * **Example** (Parsing integer values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parseInteger = Effect.all([\n * Primitive.Int.parse(\"42\"),\n * Primitive.Int.parse(\"-123\"),\n * Primitive.Int.parse(\"0\")\n * ])\n *\n * await Effect.runPromise(parseInteger.pipe(Effect.provide(CliTestLayer))) // => [42, -123, 0]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Int = /*#__PURE__*/makeSchemaPrimitive(\"Int\", Schema.Int);\n/**\n * Creates a primitive that parses Date objects from string input.\n *\n * **Example** (Parsing date values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parseDate = Effect.gen(function*() {\n * const result = yield* Primitive.Date.parse(\"2023-12-25\")\n * return result.toISOString()\n * })\n *\n * await Effect.runPromise(parseDate.pipe(Effect.provide(CliTestLayer))) // => \"2023-12-25T00:00:00.000Z\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Date = /*#__PURE__*/makeSchemaPrimitive(\"Date\", Schema.Date);\n/**\n * Creates a primitive that accepts any string value without validation.\n *\n * **Example** (Parsing string values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parseString = Effect.all([\n * Primitive.String.parse(\"hello world\"),\n * Primitive.String.parse(\"\"),\n * Primitive.String.parse(\"123\")\n * ])\n *\n * await Effect.runPromise(parseString.pipe(Effect.provide(CliTestLayer))) // => [\"hello world\", \"\", \"123\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const String = /*#__PURE__*/makePrimitive(\"String\", value => Effect.succeed(value));\n/**\n * Creates a primitive that accepts only specific choice values mapped to custom types.\n *\n * **Example** (Parsing choices)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\"\n *\n * const logLevelPrimitive = Primitive.Choice<LogLevel>([\n * [\"debug\", \"debug\"],\n * [\"info\", \"info\"],\n * [\"warn\", \"warn\"],\n * [\"error\", \"error\"]\n * ])\n *\n * const parseLogLevel = Effect.all([\n * logLevelPrimitive.parse(\"info\"),\n * logLevelPrimitive.parse(\"debug\")\n * ])\n *\n * await Effect.runPromise(parseLogLevel.pipe(Effect.provide(CliTestLayer))) // => [\"info\", \"debug\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Choice = choices => {\n const choiceMap = new Map(choices);\n const validChoices = choices.map(([key]) => format(key)).join(\" | \");\n const primitive = makePrimitive(\"Choice\", value => {\n if (choiceMap.has(value)) {\n return Effect.succeed(choiceMap.get(value));\n }\n return Effect.fail(validChoices);\n });\n return Object.assign(primitive, {\n choiceKeys: choices.map(([key]) => key)\n });\n};\n/**\n * Creates a primitive that validates and resolves file system paths.\n *\n * **Example** (Parsing file system paths)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const services = Layer.mergeAll(\n * Path.layer,\n * FileSystem.layerNoop({\n * exists: () => Effect.succeed(true),\n * stat: () => Effect.succeed({ type: \"File\" } as FileSystem.File.Info)\n * }),\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const program = Effect.gen(function*() {\n * const filePrimitive = Primitive.Path(\"file\", true)\n * const filePath = yield* filePrimitive.parse(\"./package.json\")\n * return filePath.endsWith(\"/package.json\")\n * }).pipe(Effect.provide(services))\n *\n * await Effect.runPromise(program) // => true\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Path = (pathType, mustExist) => {\n const primitive = makePrimitive(\"Path\", Effect.fnUntraced(function* (value) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path_.Path;\n // Resolve the path to absolute\n const absolutePath = path.isAbsolute(value) ? value : path.resolve(value);\n // Check if path exists\n const exists = yield* Effect.mapError(fs.exists(absolutePath), error => `Failed to check path existence: ${error.message}`);\n // Validate existence requirements\n if (mustExist === true && !exists) {\n return yield* Effect.fail(`Path does not exist: ${absolutePath}`);\n }\n // Validate path type if it exists\n if (exists && pathType !== \"either\") {\n const stat = yield* Effect.mapError(fs.stat(absolutePath), error => `Failed to stat path: ${error.message}`);\n if (pathType === \"file\" && stat.type !== \"File\") {\n return yield* Effect.fail(`Path is not a file: ${absolutePath}`);\n }\n if (pathType === \"directory\" && stat.type !== \"Directory\") {\n return yield* Effect.fail(`Path is not a directory: ${absolutePath}`);\n }\n }\n return absolutePath;\n }));\n return Object.assign(primitive, {\n pathType\n });\n};\n/**\n * Creates a primitive that wraps string input in `Redacted`.\n *\n * **Details**\n *\n * The wrapped value is hidden when formatted or inspected, while the original\n * string remains available through the `Redacted` API when explicitly needed.\n *\n * **Example** (Parsing redacted values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Redacted, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parseRedacted = Effect.gen(function*() {\n * const result = yield* Primitive.Redacted.parse(\"secret-password\")\n * return [Redacted.value(result), String(result)] as const\n * })\n *\n * await Effect.runPromise(parseRedacted.pipe(Effect.provide(CliTestLayer))) // => [\"secret-password\", \"<redacted>\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Redacted = /*#__PURE__*/makePrimitive(\"Redacted\", value => Effect.succeed(Redacted_.make(value)));\n/**\n * Creates a primitive that reads and returns the contents of a file as a string.\n *\n * **Example** (Reading file text)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const services = Layer.mergeAll(\n * Path.layer,\n * FileSystem.layerNoop({\n * exists: () => Effect.succeed(true),\n * stat: () => Effect.succeed({ type: \"File\" } as FileSystem.File.Info),\n * readFileString: () => Effect.succeed('{\"private\":true}')\n * }),\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const readConfigFile = Effect.gen(function*() {\n * const content = yield* Primitive.FileText.parse(\"./package.json\")\n * return JSON.parse(content) as { private: boolean }\n * }).pipe(Effect.provide(services))\n *\n * await Effect.runPromise(readConfigFile) // => { private: true }\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileText = /*#__PURE__*/makePrimitive(\"FileText\", /*#__PURE__*/Effect.fnUntraced(function* (filePath) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path_.Path;\n // Resolve to absolute path\n const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(filePath);\n // Check if file exists\n const exists = yield* Effect.mapError(fs.exists(absolutePath), error => `Failed to check file existence: ${error.message}`);\n if (!exists) {\n return yield* Effect.fail(`File does not exist: ${absolutePath}`);\n }\n // Check if it's actually a file\n const stat = yield* Effect.mapError(fs.stat(absolutePath), error => `Failed to stat file: ${error.message}`);\n if (stat.type !== \"File\") {\n return yield* Effect.fail(`Path is not a file: ${absolutePath}`);\n }\n // Read file content\n const content = yield* Effect.mapError(fs.readFileString(absolutePath), error => `Failed to read file: ${error.message}`);\n return content;\n}));\nconst fileParsers = {\n ini: content => Ini.parse(content),\n json: content => JSON.parse(content),\n toml: content => Toml.parse(content),\n yml: content => Yaml.parse(content),\n yaml: content => Yaml.parse(content)\n};\n/**\n * Creates a primitive that reads a file and parses its content as structured\n * data.\n *\n * **Details**\n *\n * The parser is selected from `options.format` when provided, otherwise from\n * the file extension. Supported formats include INI, JSON, TOML, YAML, and YML.\n *\n * **Example** (Parsing file content)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const services = Layer.mergeAll(\n * Path.layer,\n * FileSystem.layerNoop({\n * exists: () => Effect.succeed(true),\n * stat: () => Effect.succeed({ type: \"File\" } as FileSystem.File.Info),\n * readFileString: () => Effect.succeed('{\"private\":true}')\n * }),\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const jsonFilePrimitive = Primitive.FileParse({ format: \"json\" })\n *\n * const loadConfig = Effect.gen(function*() {\n * const config = yield* jsonFilePrimitive.parse(\"./package.json\")\n * return config as { private: boolean }\n * }).pipe(Effect.provide(services))\n *\n * await Effect.runPromise(loadConfig) // => { private: true }\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileParse = options => {\n return makePrimitive(\"FileParse\", Effect.fnUntraced(function* (filePath) {\n const fileFormat = options?.format ?? filePath.split(\".\").pop();\n const parser = fileParsers[fileFormat];\n if (parser === undefined) {\n return yield* Effect.fail(`Unsupported file format: ${fileFormat}`);\n }\n const content = yield* FileText.parse(filePath);\n return yield* Effect.try({\n try: () => parser(content),\n catch: error => `Failed to parse '.${fileFormat}' file content: ${error}`\n });\n }));\n};\n/**\n * Reads and parses file content using the specified schema.\n *\n * **Example** (Parsing file content with a schema)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Schema, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const services = Layer.mergeAll(\n * Path.layer,\n * FileSystem.layerNoop({\n * exists: () => Effect.succeed(true),\n * stat: () => Effect.succeed({ type: \"File\" } as FileSystem.File.Info),\n * readFileString: () => Effect.succeed('{\"private\":true}')\n * }),\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const ConfigSchema = Schema.Struct({\n * private: Schema.Boolean\n * })\n *\n * const jsonConfigPrimitive = Primitive.FileSchema(ConfigSchema, {\n * format: \"json\"\n * })\n *\n * const loadConfig = Effect.gen(function*() {\n * return yield* jsonConfigPrimitive.parse(\"./package.json\")\n * }).pipe(Effect.provide(services))\n *\n * await Effect.runPromise(loadConfig) // => { private: true }\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileSchema = (schema, options) => {\n const decode = Schema.decodeUnknownEffect(schema);\n return makePrimitive(\"FileSchema\", Effect.fnUntraced(function* (filePath) {\n const content = yield* FileParse(options).parse(filePath);\n return yield* Effect.mapError(decode(content), error => options?.errorFormatter?.(error.issue) ?? error.toString());\n }));\n};\n/**\n * Parses a single `key=value` pair into a record object.\n *\n * **Details**\n *\n * Splits at the first `=`. Keys and values must be non-empty; values may contain `=`.\n *\n * **Example** (Parsing key-value pairs)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parseKeyValue = Effect.all([\n * Primitive.KeyValuePair.parse(\"name=john\"),\n * Primitive.KeyValuePair.parse(\"port=3000\"),\n * Primitive.KeyValuePair.parse(\"debug=true\")\n * ])\n *\n * const result = await Effect.runPromise(parseKeyValue.pipe(Effect.provide(CliTestLayer)))\n * result // => [{ name: \"john\" }, { port: \"3000\" }, { debug: \"true\" }]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const KeyValuePair = /*#__PURE__*/makePrimitive(\"KeyValuePair\", /*#__PURE__*/Effect.fnUntraced(function* (value) {\n const separator = value.indexOf(\"=\");\n if (separator === -1) {\n return yield* Effect.fail(`Invalid key=value format. Expected format: key=value, got: ${value}`);\n }\n const key = value.slice(0, separator);\n const val = value.slice(separator + 1);\n if (!key || !val) {\n return yield* Effect.fail(`Invalid key=value format. Both key and value must be non-empty. Got: ${value}`);\n }\n return {\n [key]: val\n };\n}));\n/**\n * A primitive that always fails to parse.\n *\n * **Example** (Rejecting option values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const program = Effect.gen(function*() {\n * return yield* Primitive.Never.parse(\"any-value\")\n * })\n *\n * await Effect.runPromise(Effect.flip(program).pipe(Effect.provide(CliTestLayer))) // => \"This option does not accept values\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Never = /*#__PURE__*/makePrimitive(\"Never\", () => Effect.fail(\"This option does not accept values\"));\n/**\n * Gets a human-readable type name for a primitive.\n *\n * **When to use**\n *\n * Use when you need the display type name for a `Primitive`, such as when\n * generating CLI help documentation.\n *\n * **Example** (Getting primitive type names)\n *\n * ```ts import.meta.vitest\n * import { Primitive } from \"effect/cli\"\n *\n * Primitive.getTypeName(Primitive.String) // => \"string\"\n * Primitive.getTypeName(Primitive.Int) // => \"integer\"\n * Primitive.getTypeName(Primitive.Boolean) // => \"boolean\"\n * Primitive.getTypeName(Primitive.Date) // => \"date\"\n * Primitive.getTypeName(Primitive.KeyValuePair) // => \"key=value\"\n *\n * const logLevelChoice = Primitive.Choice([\n * [\"debug\", \"debug\"],\n * [\"info\", \"info\"]\n * ])\n * Primitive.getTypeName(logLevelChoice) // => \"choice\"\n * ```\n *\n * @stability unstable\n * @category getters\n * @since 4.0.0\n */\nexport const getTypeName = primitive => {\n switch (primitive._tag) {\n case \"Boolean\":\n return \"boolean\";\n case \"String\":\n return \"string\";\n case \"Int\":\n return \"integer\";\n case \"Finite\":\n return \"number\";\n case \"Date\":\n return \"date\";\n case \"Path\":\n return \"path\";\n case \"Choice\":\n return \"choice\";\n case \"Redacted\":\n return \"string\";\n case \"FileText\":\n return \"file\";\n case \"FileParse\":\n return \"file\";\n case \"FileSchema\":\n return \"file\";\n case \"KeyValuePair\":\n return \"key=value\";\n case \"Never\":\n return \"none\";\n default:\n return \"value\";\n }\n};\n/**\n * @internal\n */\nexport const getChoiceKeys = primitive => primitive._tag === \"Choice\" ? primitive.choiceKeys : undefined;\n/**\n * @internal\n */\nexport const getPathType = primitive => primitive._tag === \"Path\" ? primitive.pathType : undefined;\n//# sourceMappingURL=Primitive.js.map","/**\n * Internal ANSI escape sequence helpers used by the unstable CLI rendering\n * implementation. This module centralizes the control codes for text styling,\n * cursor movement, line erasing, and terminal notifications so renderers can\n * compose terminal output without scattering raw escape sequences throughout\n * the CLI internals.\n *\n * The helpers deliberately work with plain strings because terminal rendering\n * is sensitive to ordering: style codes must be reset after annotated text,\n * cursor operations must account for one-based terminal coordinates, and line\n * clearing usually needs to preserve the cursor position expected by the next\n * frame.\n */\nconst ESC = \"\\x1B[\";\nconst BEL = \"\\x07\";\nconst SEP = \";\";\n/**\n * @internal\n */\nexport const reset = `${ESC}0m`;\n/**\n * @internal\n */\nexport const bold = `${ESC}1m`;\n/**\n * @internal\n */\nexport const italicized = `${ESC}3m`;\n/**\n * @internal\n */\nexport const underlined = `${ESC}4m`;\n/**\n * @internal\n */\nexport const strikethrough = `${ESC}9m`;\n/**\n * @internal\n */\nexport const cursorShow = `${ESC}?25h`;\n/**\n * @internal\n */\nexport const cursorHide = `${ESC}?25l`;\n/**\n * @internal\n */\nexport const cursorLeft = `${ESC}G`;\n/**\n * @internal\n */\nexport const cursorSavePosition = `${ESC}s`;\n/**\n * @internal\n */\nexport const cursorRestorePosition = `${ESC}u`;\n/**\n * @internal\n */\nexport const eraseLine = `${ESC}2K`;\n/**\n * @internal\n */\nexport const beep = BEL;\n/**\n * @internal\n */\nexport const red = `${ESC}31m`;\n/**\n * @internal\n */\nexport const green = `${ESC}32m`;\n/**\n * @internal\n */\nexport const magenta = `${ESC}35m`;\n/**\n * @internal\n */\nexport const white = `${ESC}37m`;\n/**\n * @internal\n */\nexport const blackBright = `${ESC}90m`;\n/**\n * @internal\n */\nexport const cyanBright = `${ESC}96m`;\n/**\n * Wraps `text` in the given styles followed by a reset. When `colors` is\n * `false` the text is returned unchanged, so callers gate color and style\n * escapes in one place while cursor and erase controls stay untouched.\n *\n * @internal\n */\nexport const annotate = (colors, text, ...styles) => {\n if (!colors) return text;\n return `${styles.flat().join(\"\")}${text}${reset}`;\n};\n/**\n * Detects whether CLI output should use color and style escapes: stdout must\n * be a TTY and `NO_COLOR` must be unset or empty.\n *\n * @internal\n */\nexport const detectColors = () => {\n const globalProcess = globalThis.process;\n return typeof globalProcess === \"object\" && globalProcess !== null && typeof globalProcess.stdout === \"object\" && globalProcess.stdout !== null && globalProcess.stdout.isTTY === true && !globalProcess.env?.NO_COLOR;\n};\nexport const combine = (...styles) => styles;\n/**\n * @internal\n */\nexport const cursorTo = (column, row) => {\n if (row === undefined) {\n return `${ESC}${Math.max(column + 1, 0)}G`;\n }\n return `${ESC}${row + 1}${SEP}${Math.max(column + 1, 0)}H`;\n};\n/**\n * @internal\n */\nexport const cursorDown = (lines = 1) => {\n return `${ESC}${lines}B`;\n};\n/**\n * @internal\n */\nexport const cursorMove = (column, row = 0) => {\n let command = \"\";\n if (row < 0) {\n command += `${ESC}${-row}A`;\n }\n if (row > 0) {\n command += `${ESC}${row}B`;\n }\n if (column > 0) {\n command += `${ESC}${column}C`;\n }\n if (column < 0) {\n command += `${ESC}${-column}D`;\n }\n return command;\n};\n/**\n * @internal\n */\nexport const eraseLines = rows => {\n let command = \"\";\n for (let i = 0; i < rows; i++) {\n command += `${ESC}2K` + (i < rows - 1 ? `${ESC}1A` : \"\");\n }\n if (rows > 0) {\n command += `${ESC}G`;\n }\n return command;\n};\n//# sourceMappingURL=ansi.js.map","/**\n * Builds interactive terminal prompts for CLI applications.\n *\n * A `Prompt<A>` describes a small terminal UI that renders frames, reads\n * keyboard input, validates responses, and eventually produces an `A`. Prompts\n * can ask for simple values, selections, lists, files, hidden text, or custom\n * interactions. This module includes prompt constructors, tools for combining\n * and transforming prompt output, and support for running prompts through the\n * `Terminal` service.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Arr from \"../Array.js\";\nimport * as Context from \"../Context.js\";\nimport * as Data from \"../Data.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Effectable from \"../Effectable.js\";\nimport * as FileSystem from \"../FileSystem.js\";\nimport { dual, pipe } from \"../Function.js\";\nimport * as EffectNumber from \"../Number.js\";\nimport * as Option from \"../Option.js\";\nimport * as Path from \"../Path.js\";\nimport * as Predicate from \"../Predicate.js\";\nimport * as Queue from \"../Queue.js\";\nimport * as Redacted from \"../Redacted.js\";\nimport * as Terminal from \"../Terminal.js\";\nimport * as Ansi from \"./internal/ansi.js\";\nconst TypeId = \"~effect/cli/Prompt\";\n/**\n * Returns `true` if the provided value is a `Prompt`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isPrompt = u => Predicate.hasProperty(u, TypeId);\nconst defaultTheme = {\n prefix: \"?\",\n arrowUp: \"↑\",\n arrowDown: \"↓\",\n checkboxOn: \"☒\",\n checkboxOff: \"☐\",\n tick: \"✔\",\n ellipsis: \"…\",\n pointerSmall: \"›\",\n pointer: \"❯\",\n descriptionSeparator: \"- \",\n passwordMask: \"*\",\n toggleSeparator: \"/\",\n primaryColor: Ansi.cyanBright,\n mutedColor: Ansi.blackBright,\n successColor: Ansi.green,\n errorColor: Ansi.red,\n submittedColor: Ansi.white\n};\nconst windowsTheme = {\n ...defaultTheme,\n checkboxOn: \"[*]\",\n checkboxOff: \"[ ]\",\n tick: \"√\",\n ellipsis: \"...\",\n pointerSmall: \"»\",\n pointer: \">\"\n};\n/**\n * Creates a prompt theme using the current platform defaults.\n *\n * **Details**\n *\n * Unless `colors` is provided, it is detected when the theme is created:\n * colors are enabled when stdout is a TTY and `NO_COLOR` is unset or empty.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeTheme = options => ({\n ...(process.platform === \"win32\" ? windowsTheme : defaultTheme),\n ...options,\n colors: options?.colors ?? Ansi.detectColors()\n});\n/**\n * Context reference for the theme used by built-in prompts.\n *\n * **Details**\n *\n * Provide this reference once to theme every prompt in an application. A\n * prompt's `theme` option takes precedence over the context value. The\n * command wizard also reads `colors` from this reference, so provide a theme\n * with `colors: false` to disable wizard styling.\n *\n * The default value is created with `makeTheme` the first time it is read,\n * so color detection runs once per process. Changes to `NO_COLOR` after the\n * first prompt do not affect the default theme.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const Theme = /*#__PURE__*/Context.Reference(\"effect/cli/Prompt/Theme\", {\n defaultValue: makeTheme\n});\nconst getTheme = options => Effect.map(Theme, theme => ({\n ...theme,\n ...options.theme\n}));\n/**\n * Runs all the provided prompts in sequence respecting the structure provided\n * in input.\n *\n * **Details**\n *\n * Supports either a tuple / iterable of prompts or a record / struct of prompts\n * as an argument.\n *\n * **Example** (Collecting prompt results)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Terminal } from \"effect\"\n * import { Prompt } from \"effect/cli\"\n *\n * const terminal = Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.succeed({} as never),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })\n * const services = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Layer.succeed(Terminal.Terminal, terminal)\n * )\n *\n * const username = Prompt.succeed(\"alice\")\n * const password = Prompt.succeed(\"secret\")\n *\n * const allWithTuple = Prompt.all([username, password])\n *\n * const allWithRecord = Prompt.all({ username, password })\n *\n * await Effect.runPromise(Effect.provide(allWithTuple, services)) // => [\"alice\", \"secret\"]\n * await Effect.runPromise(Effect.provide(allWithRecord, services)) // => { username: \"alice\", password: \"secret\" }\n * ```\n *\n * @stability unstable\n * @category combining\n * @since 4.0.0\n */\nexport const all = function () {\n if (arguments.length === 1) {\n if (isPrompt(arguments[0])) {\n return map(arguments[0], x => [x]);\n } else if (Predicate.isIterable(arguments[0])) {\n return allTupled(Arr.fromIterable(arguments[0]));\n } else {\n const entries = Object.entries(arguments[0]);\n if (entries.length === 0) {\n return succeed({});\n }\n let result = map(entries[0][1], value => ({\n [entries[0][0]]: value\n }));\n if (entries.length === 1) {\n return result;\n }\n const rest = entries.slice(1);\n for (const [key, prompt] of rest) {\n result = result.pipe(flatMap(record => prompt.pipe(map(value => ({\n ...record,\n [key]: value\n })))));\n }\n return result;\n }\n }\n return allTupled(arguments[0]);\n};\nconst annotateErrorLine = (theme, line) => Ansi.annotate(theme.colors, line, Ansi.combine(Ansi.italicized, theme.errorColor));\nconst annotateSymbol = (theme, symbol, ...styles) => symbol.length === 0 ? \"\" : Ansi.annotate(theme.colors, symbol, ...styles);\nconst separateSymbol = (symbol, text) => symbol.length === 0 ? text : symbol + \" \" + text;\nconst renderPagingPrefix = (theme, showArrowUp, showArrowDown) => {\n const width = Math.max(theme.arrowUp.length, theme.arrowDown.length);\n if (showArrowUp) {\n return theme.arrowUp.padEnd(width);\n }\n if (showArrowDown) {\n return theme.arrowDown.padEnd(width);\n }\n return \" \".repeat(width);\n};\n/**\n * Creates a confirmation prompt that asks the user to choose a boolean yes/no\n * value.\n *\n * **When to use**\n *\n * Use to ask for a yes/no answer that can be submitted directly.\n *\n * **Details**\n *\n * `initial` defaults to `false`. Enter submits the current default, yes-style\n * input submits `true`, no-style input submits `false`, and other input beeps.\n *\n * @see {@link Toggle} for an interactive switch-before-submit boolean prompt\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Confirm = options => {\n const opts = {\n initial: false,\n ...options,\n label: {\n confirm: \"yes\",\n deny: \"no\",\n ...options.label\n },\n placeholder: {\n defaultConfirm: \"(Y/n)\",\n defaultDeny: \"(y/N)\",\n ...options.placeholder\n }\n };\n const initialState = {\n value: opts.initial\n };\n return Custom(initialState, {\n render: handleConfirmRender(opts),\n process: input => handleConfirmProcess(input, opts.initial),\n clear: handleConfirmClear(opts)\n });\n};\n/**\n * Creates a custom `Prompt` from the specified initial state and handlers.\n *\n * **Details**\n *\n * The initial state can either be a pure value or an `Effect`. This is\n * particularly useful when the initial state of the `Prompt` must be computed\n * by performing an effectful computation, such as reading data from the file\n * system. A `Prompt` runs as a render loop: `render` returns ANSI output for\n * the current frame, the `Terminal` obtains user input, `process` returns the\n * next prompt action, and `clear` returns ANSI output used to clear the previous\n * frame.\n *\n * Optionally, an external `events` dequeue can be provided as the third\n * argument. When present, the render loop will race user input against events\n * from the dequeue, allowing background events to trigger re-renders without\n * waiting for a keypress. When an event is received from the dequeue, the\n * `receive` handler is called instead of `process`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Custom = (initialState, ...args) => {\n const [events, handlers] = args.length === 1 ? [undefined, args[0]] : [args[0], args[1]];\n const op = Object.create(proto);\n op._tag = \"Loop\";\n op.initialState = initialState;\n op.render = handlers.render;\n op.process = handlers.process;\n op.clear = handlers.clear;\n op.events = events;\n return op;\n};\n/**\n * Creates a date prompt that lets the user edit a formatted date value and\n * validates the final `Date` before submission.\n *\n * **Details**\n *\n * `initial` defaults to the current `Date`, `dateMask` defaults to\n * `YYYY-MM-DD HH:mm:ss`, mask parsing creates editable date parts plus literal\n * tokens, `locales` customizes month and weekday labels, and `validate` runs on\n * submission.\n *\n * **Gotchas**\n *\n * A supplied `initial` `Date` is edited in place during prompt interaction.\n * Date edits use JavaScript `Date` setters, so out-of-range typed values can\n * normalize before validation. If the prompt is meant to be editable,\n * `dateMask` should contain at least one editable date token.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Date = options => {\n const opts = {\n initial: new globalThis.Date(),\n dateMask: \"YYYY-MM-DD HH:mm:ss\",\n validate: Effect.succeed,\n ...options,\n locales: {\n ...defaultLocales,\n ...options.locales\n }\n };\n const dateParts = makeDateParts(opts.dateMask, opts.initial, opts.locales);\n const initialCursorPosition = dateParts.findIndex(part => !part.isToken());\n const initialState = {\n dateParts,\n typed: \"\",\n cursor: initialCursorPosition,\n value: opts.initial,\n error: Option.none()\n };\n return Custom(initialState, {\n render: handleDateRender(opts),\n process: handleDateProcess(opts),\n clear: handleDateClear(opts)\n });\n};\n/**\n * Creates a file-system selection prompt and returns the selected path.\n *\n * **Details**\n *\n * The prompt can be configured to select files, directories, or either path\n * type.\n *\n * You can also type to filter the listed entries. Every printable character is\n * appended to the filter query, so navigation is bound to the arrow keys,\n * `tab`, and the `Ctrl+P` / `Ctrl+N` chords used by `readline` and `fzf`\n * (`Ctrl+K` also moves up). `Ctrl+U` clears the query.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const File = (options = {}) => {\n const opts = {\n ...options,\n type: options.type ?? \"file\",\n message: options.message ?? `Choose a file`,\n startingPath: Option.fromUndefinedOr(options.startingPath),\n default: Option.fromUndefinedOr(options.default),\n maxPerPage: options.maxPerPage ?? 10,\n filter: options.filter ?? (() => Effect.succeed(true))\n };\n const initialState = Effect.gen(function* () {\n const currentPath = yield* resolveCurrentPath(Option.none(), opts);\n const path = yield* Path.Path;\n const defaultPath = Option.map(opts.default, defaultValue => path.resolve(currentPath, defaultValue));\n const initialPath = Option.match(defaultPath, {\n onNone: () => currentPath,\n onSome: defaultPath => path.dirname(defaultPath)\n });\n const files = yield* getFileList(initialPath, opts);\n const cursor = Option.match(defaultPath, {\n onNone: () => 0,\n onSome: defaultPath => {\n const index = files.indexOf(path.basename(defaultPath));\n return index === -1 ? 0 : index;\n }\n });\n const confirm = FileConfirm.Hide();\n return {\n cursor,\n files,\n allFiles: files,\n query: \"\",\n path: Option.map(defaultPath, path.dirname),\n confirm\n };\n });\n return Custom(initialState, {\n render: handleFileRender(opts),\n process: handleFileProcess(opts),\n clear: handleFileClear(opts)\n });\n};\n/**\n * Composes prompts by using the output of this prompt to create the next prompt.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const flatMap = /*#__PURE__*/dual(2, (self, f) => {\n const op = Object.create(proto);\n op._tag = \"OnSuccess\";\n op.prompt = self;\n op.onSuccess = f;\n return op;\n});\n/**\n * Creates a floating-point number prompt.\n *\n * **Details**\n *\n * The prompt supports minimum and maximum bounds, keyboard step sizes, display\n * precision, and additional validation before submission.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Number = options => {\n const opts = {\n default: 0,\n min: globalThis.Number.NEGATIVE_INFINITY,\n max: globalThis.Number.POSITIVE_INFINITY,\n incrementBy: 1,\n decrementBy: 1,\n precision: 2,\n validate: n => {\n if (n < opts.min) {\n return Effect.fail(`${n} must be greater than or equal to ${opts.min}`);\n }\n if (n > opts.max) {\n return Effect.fail(`${n} must be less than or equal to ${opts.max}`);\n }\n return Effect.succeed(n);\n },\n ...options\n };\n const initialValue = options.default === undefined ? \"\" : `${opts.default}`;\n const initialState = {\n cursor: initialValue.length,\n value: initialValue,\n error: Option.none()\n };\n return Custom(initialState, {\n render: handleRenderFloat(opts),\n process: handleProcessFloat(opts),\n clear: handleNumberClear(opts)\n });\n};\n/**\n * Creates a text prompt that does not echo typed input and returns the\n * submitted value wrapped in `Redacted`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Hidden = options => basePrompt(options, \"hidden\").pipe(map(Redacted.make));\n/**\n * Creates an integer prompt.\n *\n * **Details**\n *\n * The prompt supports minimum and maximum bounds, keyboard step sizes, and\n * additional validation before submission.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Int = options => {\n const opts = {\n default: 0,\n min: globalThis.Number.NEGATIVE_INFINITY,\n max: globalThis.Number.POSITIVE_INFINITY,\n incrementBy: 1,\n decrementBy: 1,\n validate: n => {\n if (n < opts.min) {\n return Effect.fail(`${n} must be greater than or equal to ${opts.min}`);\n }\n if (n > opts.max) {\n return Effect.fail(`${n} must be less than or equal to ${opts.max}`);\n }\n return Effect.succeed(n);\n },\n ...options\n };\n const initialValue = options.default === undefined ? \"\" : `${opts.default}`;\n const initialState = {\n cursor: initialValue.length,\n value: initialValue,\n error: Option.none()\n };\n return Custom(initialState, {\n render: handleRenderInteger(opts),\n process: handleProcessInteger(opts),\n clear: handleNumberClear(opts)\n });\n};\n/**\n * Creates a text prompt that returns an array of strings by splitting the\n * submitted input on the configured delimiter.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const List = options => String(options).pipe(map(output => output.split(options.delimiter || \",\")));\n/**\n * Transforms the output value produced by a prompt.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => flatMap(self, a => succeed(f(a))));\n/**\n * Creates a password prompt that masks typed input and returns the submitted\n * value wrapped in `Redacted`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Password = options => basePrompt(options, \"password\").pipe(map(Redacted.make));\n/**\n * Runs a prompt by reading terminal input and rendering prompt frames until the\n * prompt submits a value.\n *\n * **Gotchas**\n *\n * The returned effect may fail with `Terminal.QuitError` if terminal input ends\n * or the prompt is quit.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const run = /*#__PURE__*/Effect.fnUntraced(function* (self) {\n const terminal = yield* Terminal.Terminal;\n const input = yield* Effect.cached(terminal.readInput);\n return yield* runWithInput(self, terminal, input);\n}, /*#__PURE__*/Effect.mapError(() => new Terminal.QuitError({})), Effect.scoped);\nconst getSelectInitialIndex = choices => {\n let initialIndex = 0;\n let seenSelected = -1;\n for (let i = 0; i < choices.length; i++) {\n const choice = choices[i];\n if (choice.selected === true) {\n if (seenSelected !== -1) {\n throw new Error(\"InvalidArgumentException: only a single choice can be selected by default for Prompt.Select\");\n }\n seenSelected = i;\n }\n }\n if (seenSelected !== -1) {\n initialIndex = seenSelected;\n }\n return initialIndex;\n};\n/**\n * Creates a prompt that lets the user select a single value from a list of\n * choices.\n *\n * **Gotchas**\n *\n * At most one choice may be marked as selected by default.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Select = options => {\n const opts = {\n maxPerPage: 10,\n ...options\n };\n const initialIndex = getSelectInitialIndex(opts.choices);\n return Custom(initialIndex, {\n render: handleSelectRender(opts),\n process: handleSelectProcess(opts),\n clear: handleSelectClear(opts)\n });\n};\n/**\n * Creates a prompt that lets users filter select choices by typing.\n *\n * **Details**\n *\n * Every printable character is appended to the filter query, so navigation is\n * bound to the arrow keys, `tab`, and the `Ctrl+P` / `Ctrl+N` chords used by\n * `readline` and `fzf` (`Ctrl+K` also moves up). `Ctrl+U` clears the query.\n *\n * **Example** (Filtering choices with autocomplete)\n *\n * ```ts import.meta.vitest\n * import { Prompt } from \"effect/cli\"\n *\n * const language = Prompt.AutoComplete({\n * message: \"Choose a language\",\n * choices: [\n * { title: \"TypeScript\", value: \"ts\" },\n * { title: \"Rust\", value: \"rs\" },\n * { title: \"Kotlin\", value: \"kt\" }\n * ]\n * })\n *\n * Prompt.isPrompt(language) // => true\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const AutoComplete = options => {\n const opts = {\n maxPerPage: 10,\n filterLabel: \"filter\",\n filterPlaceholder: \"type to filter\",\n emptyMessage: \"No matches\",\n ...options\n };\n const initialIndex = getSelectInitialIndex(opts.choices);\n const filtered = filterAutoCompleteChoices(opts.choices, \"\");\n const index = filtered.length === 0 ? 0 : filtered.includes(initialIndex) ? initialIndex : filtered[0];\n const initialState = {\n query: \"\",\n index,\n filtered\n };\n return Custom(initialState, {\n render: handleAutoCompleteRender(opts),\n process: handleAutoCompleteProcess(opts),\n clear: handleAutoCompleteClear(opts)\n });\n};\n/**\n * Creates a prompt that lets the user select multiple choices and returns their\n * values as an array.\n *\n * **Details**\n *\n * The prompt supports default selected choices, bulk-selection commands, and\n * minimum or maximum selection counts.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const MultiSelect = options => {\n const opts = {\n maxPerPage: 10,\n ...options\n };\n // Seed initial selection from choices marked as selected: true\n const initialSelected = new Set();\n for (let i = 0; i < opts.choices.length; i++) {\n const choice = opts.choices[i];\n if (choice.selected === true && !choice.disabled) {\n initialSelected.add(i);\n }\n }\n const initialState = {\n index: 0,\n selectedIndices: initialSelected,\n error: Option.none()\n };\n return Custom(initialState, {\n render: handleMultiSelectRender(opts),\n process: handleMultiSelectProcess(opts),\n clear: handleMultiSelectClear(opts)\n });\n};\n/**\n * Creates a `Prompt` which immediately succeeds with the specified value.\n *\n * **Details**\n *\n * This prompt does not attempt to obtain user input or render anything to the\n * screen.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const succeed = value => {\n const op = Object.create(proto);\n op._tag = \"Succeed\";\n op.value = value;\n return op;\n};\n/**\n * Creates a text-entry prompt that echoes input and returns the submitted\n * string after validation.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const String = options => basePrompt(options, \"text\");\n/**\n * Creates a toggle prompt that lets the user switch between active and inactive\n * states and returns the selected boolean value.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Toggle = options => {\n const opts = {\n initial: false,\n active: \"on\",\n inactive: \"off\",\n ...options\n };\n return Custom(opts.initial, {\n render: handleToggleRender(opts),\n process: handleToggleProcess,\n clear: () => handleToggleClear(opts)\n });\n};\nconst proto = {\n ... /*#__PURE__*/Effectable.Prototype({\n label: \"Prompt\",\n evaluate() {\n return run(this);\n }\n }),\n [TypeId]: {\n _Output: _ => _\n }\n};\nconst allTupled = arg => {\n if (arg.length === 0) {\n return succeed([]);\n }\n if (arg.length === 1) {\n return map(arg[0], x => [x]);\n }\n let result = map(arg[0], x => [x]);\n for (let i = 1; i < arg.length; i++) {\n const curr = arg[i];\n result = flatMap(result, tuple => map(curr, a => [...tuple, a]));\n }\n return result;\n};\nconst runWithInput = (prompt, terminal, input) => Effect.suspend(() => {\n const op = prompt;\n switch (op._tag) {\n case \"Loop\":\n {\n return Effect.flatMap(input, queue => runLoop(op, terminal, queue));\n }\n case \"OnSuccess\":\n {\n return Effect.flatMap(runWithInput(op.prompt, terminal, input), a => runWithInput(op.onSuccess(a), terminal, input));\n }\n case \"Succeed\":\n {\n return Effect.succeed(op.value);\n }\n }\n});\nconst runLoop = /*#__PURE__*/Effect.fnUntraced(function* (loop, terminal, input) {\n let state = Effect.isEffect(loop.initialState) ? yield* loop.initialState : loop.initialState;\n let action = Action.NextFrame({\n state\n });\n let clear = \"\";\n while (true) {\n const msg = yield* loop.render(state, action);\n yield* Effect.orDie(terminal.display(clear + msg));\n clear = \"\";\n if (loop.events) {\n const takeInput = Queue.take(input).pipe(Effect.map(input => ({\n _tag: \"Input\",\n input\n })));\n const result = yield* Effect.raceFirst(takeInput, Queue.take(loop.events).pipe(Effect.map(value => ({\n _tag: \"Event\",\n value\n }))));\n action = yield* loop.process(result, state);\n } else {\n const result = yield* Queue.take(input);\n action = yield* loop.process(result, state);\n }\n switch (action._tag) {\n case \"Beep\":\n continue;\n case \"NextFrame\":\n {\n clear = yield* loop.clear(state, action);\n state = action.state;\n continue;\n }\n case \"Submit\":\n {\n clear = yield* loop.clear(state, action);\n const msg = yield* loop.render(state, action);\n yield* Effect.orDie(terminal.display(clear + msg));\n return action.value;\n }\n }\n }\n}, (effect, _, terminal) => Effect.ensuring(effect, Effect.orDie(terminal.display(Ansi.cursorShow))));\nconst Action = /*#__PURE__*/Data.taggedEnum();\n/**\n * Clears all lines taken up by the specified `text`.\n */\nconst eraseText = (text, columns) => {\n if (columns === 0) {\n return Ansi.eraseLine + Ansi.cursorTo(0);\n }\n let rows = 0;\n const lines = text.split(NEWLINE_REGEXP);\n for (const line of lines) {\n rows += 1 + Math.floor(Math.max(line.length - 1, 0) / columns);\n }\n return Ansi.eraseLines(rows);\n};\nconst lines = (prompt, columns) => {\n const lines = prompt.split(NEWLINE_REGEXP);\n return columns === 0 ? lines.length : pipe(Arr.map(lines, line => Math.ceil(line.length / columns)), Arr.reduce(0, (left, right) => left + right));\n};\nconst clearOutputWithError = (outputText, columns, errorText) => {\n if (errorText !== undefined && errorText.length > 0) {\n return Ansi.cursorDown(lines(errorText, columns)) + eraseText(`\\n${errorText}`, columns) + eraseText(outputText, columns);\n }\n return eraseText(outputText, columns);\n};\nconst renderBeep = Ansi.beep;\nconst NEWLINE_REGEXP = /\\r?\\n/;\nconst handleConfirmClear = options => {\n return Effect.fnUntraced(function* (state, _) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const confirmMessage = state.value ? options.placeholder.defaultConfirm : options.placeholder.defaultDeny;\n const promptText = renderPrompt(confirmMessage, options.message, figures.prefix, figures.pointerSmall, figures, {\n plain: true\n });\n const clearOutput = eraseText(promptText, columns);\n const resetCurrentLine = Ansi.eraseLine + Ansi.cursorLeft;\n return clearOutput + resetCurrentLine;\n });\n};\nconst renderConfirmNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n // Marking these explicitly as present with `!` because they always will be\n // and there is really no value in adding a `DeepRequired` type helper just\n // for these internal cases\n const confirmMessage = state.value ? options.placeholder.defaultConfirm : options.placeholder.defaultDeny;\n const confirm = Ansi.annotate(figures.colors, confirmMessage, figures.mutedColor);\n const promptMsg = renderPrompt(confirm, options.message, leadingSymbol, trailingSymbol, figures);\n return Ansi.cursorHide + promptMsg;\n});\nconst renderConfirmSubmission = /*#__PURE__*/Effect.fnUntraced(function* (value, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const confirmMessage = value ? options.label.confirm : options.label.deny;\n const promptMsg = renderPrompt(confirmMessage, options.message, leadingSymbol, trailingSymbol, figures);\n return promptMsg + \"\\n\";\n});\nconst handleConfirmRender = options => {\n return (_, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderConfirmNextFrame(state, options),\n Submit: ({\n value\n }) => renderConfirmSubmission(value, options)\n });\n };\n};\nconst TRUE_VALUE_REGEXP = /^y|t$/;\nconst FALSE_VALUE_REGEXP = /^n|f$/;\nconst handleConfirmProcess = (input, defaultValue) => {\n const value = Option.getOrElse(input.input, () => \"\");\n if (input.key.name === \"enter\" || input.key.name === \"return\") {\n return Effect.succeed(Action.Submit({\n value: defaultValue\n }));\n }\n if (TRUE_VALUE_REGEXP.test(value.toLowerCase())) {\n return Effect.succeed(Action.Submit({\n value: true\n }));\n }\n if (FALSE_VALUE_REGEXP.test(value.toLowerCase())) {\n return Effect.succeed(Action.Submit({\n value: false\n }));\n }\n return Effect.succeed(Action.Beep());\n};\nconst handleDateClear = options => {\n return Effect.fnUntraced(function* (state, _) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const resetCurrentLine = Ansi.eraseLine + Ansi.cursorLeft;\n const parts = Arr.reduce(state.dateParts, \"\", (doc, part) => doc + part.toString());\n const promptText = renderPrompt(parts, options.message, figures.prefix, figures.pointerSmall, figures, {\n plain: true\n });\n const errorText = Option.isSome(state.error) ? Arr.match(state.error.value.split(NEWLINE_REGEXP), {\n onEmpty: () => \"\",\n onNonEmpty: errorLines => separateSymbol(figures.pointerSmall, errorLines.join(\"\\n\"))\n }) : \"\";\n const clearOutput = clearOutputWithError(promptText, columns, errorText);\n return clearOutput + resetCurrentLine;\n });\n};\nconst renderDateError = (state, pointer, theme) => {\n if (Option.isSome(state.error)) {\n const errorLines = state.error.value.split(NEWLINE_REGEXP);\n if (Arr.isReadonlyArrayNonEmpty(errorLines)) {\n const prefix = annotateSymbol(theme, pointer, theme.errorColor);\n const lines = Arr.map(errorLines, str => annotateErrorLine(theme, str));\n return Ansi.cursorSavePosition + \"\\n\" + separateSymbol(prefix, lines.join(\"\\n\")) + Ansi.cursorRestorePosition;\n }\n }\n return \"\";\n};\nconst renderParts = (state, theme, submitted = false) => {\n return Arr.reduce(state.dateParts, \"\", (doc, part, currentIndex) => {\n const partDoc = part.toString();\n if (currentIndex === state.cursor && !submitted) {\n const annotation = Ansi.combine(Ansi.underlined, theme.primaryColor);\n return doc + Ansi.annotate(theme.colors, partDoc, annotation);\n }\n return doc + partDoc;\n });\n};\nconst renderDateNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const parts = renderParts(state, figures);\n const promptMsg = renderPrompt(parts, options.message, leadingSymbol, trailingSymbol, figures);\n const errorMsg = renderDateError(state, figures.pointerSmall, figures);\n return Ansi.cursorHide + promptMsg + errorMsg;\n});\nconst renderDateSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const parts = renderParts(state, figures, true);\n const promptMsg = renderPrompt(parts, options.message, leadingSymbol, trailingSymbol, figures);\n return promptMsg + \"\\n\";\n});\nconst processUp = state => {\n state.dateParts[state.cursor].increment();\n return Action.NextFrame({\n state: {\n ...state,\n typed: \"\"\n }\n });\n};\nconst processDown = state => {\n state.dateParts[state.cursor].decrement();\n return Action.NextFrame({\n state: {\n ...state,\n typed: \"\"\n }\n });\n};\nconst processDateCursorLeft = state => {\n const previous = state.dateParts[state.cursor].previousPart();\n if (Option.isSome(previous)) {\n return Action.NextFrame({\n state: {\n ...state,\n typed: \"\",\n cursor: state.dateParts.indexOf(previous.value)\n }\n });\n }\n return Action.Beep();\n};\nconst processDateCursorRight = state => {\n const next = state.dateParts[state.cursor].nextPart();\n if (Option.isSome(next)) {\n return Action.NextFrame({\n state: {\n ...state,\n typed: \"\",\n cursor: state.dateParts.indexOf(next.value)\n }\n });\n }\n return Action.Beep();\n};\nconst processDateNext = state => {\n const next = state.dateParts[state.cursor].nextPart();\n const cursor = Option.match(next, {\n onNone: () => state.dateParts.findIndex(part => !part.isToken()),\n onSome: next => state.dateParts.indexOf(next)\n });\n return Action.NextFrame({\n state: {\n ...state,\n typed: \"\",\n cursor\n }\n });\n};\nconst defaultDateProcessor = (value, state) => {\n if (/\\d/.test(value)) {\n const typed = state.typed + value;\n state.dateParts[state.cursor].setValue(typed);\n return Action.NextFrame({\n state: {\n ...state,\n typed\n }\n });\n }\n return Action.Beep();\n};\nconst defaultLocales = {\n months: [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"],\n monthsShort: [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"],\n weekdays: [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"],\n weekdaysShort: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"]\n};\nconst handleDateRender = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderDateNextFrame(state, options),\n Submit: () => renderDateSubmission(state, options)\n });\n };\n};\nconst handleDateProcess = options => {\n return (input, state) => {\n switch (input.key.name) {\n case \"left\":\n {\n return Effect.succeed(processDateCursorLeft(state));\n }\n case \"right\":\n {\n return Effect.succeed(processDateCursorRight(state));\n }\n case \"k\":\n case \"up\":\n {\n return Effect.succeed(processUp(state));\n }\n case \"j\":\n case \"down\":\n {\n return Effect.succeed(processDown(state));\n }\n case \"tab\":\n {\n return Effect.succeed(processDateNext(state));\n }\n case \"enter\":\n case \"return\":\n {\n return Effect.match(options.validate(state.value), {\n onFailure: error => Action.NextFrame({\n state: {\n ...state,\n error: Option.some(error)\n }\n }),\n onSuccess: value => Action.Submit({\n value\n })\n });\n }\n default:\n {\n return Effect.succeed(defaultDateProcessor(Option.getOrElse(input.input, () => \"\"), state));\n }\n }\n };\n};\nconst DATE_PART_REGEXP = /\\\\(.)|\"((?:\\\\[\"\\\\]|[^\"])+)\"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g;\nconst regExpGroups = {\n 1: ({\n token,\n ...opts\n }) => new Token({\n token: token.replace(/\\\\(.)/g, \"$1\"),\n ...opts\n }),\n 2: opts => new Day(opts),\n 3: opts => new Month(opts),\n 4: opts => new Year(opts),\n 5: opts => new Meridiem(opts),\n 6: opts => new Hours(opts),\n 7: opts => new Minutes(opts),\n 8: opts => new Seconds(opts),\n 9: opts => new Milliseconds(opts)\n};\nconst makeDateParts = (dateMask, date, locales) => {\n const parts = [];\n let result = null;\n // oxlint-disable-next-line no-cond-assign\n while (result = DATE_PART_REGEXP.exec(dateMask)) {\n const match = result.shift();\n const index = result.findIndex(group => group !== undefined);\n if (index in regExpGroups) {\n const token = result[index] || match;\n parts.push(regExpGroups[index]({\n token,\n date,\n parts,\n locales\n }));\n } else {\n parts.push(new Token({\n token: result[index] || match,\n date,\n parts,\n locales\n }));\n }\n }\n const orderedParts = parts.reduce((array, element) => {\n const lastElement = array[array.length - 1];\n if (element.isToken() && lastElement !== undefined && lastElement.isToken()) {\n lastElement.setValue(element.token);\n } else {\n array.push(element);\n }\n return array;\n }, Arr.empty());\n parts.splice(0, parts.length, ...orderedParts);\n return parts;\n};\nclass DatePart {\n token;\n date;\n parts;\n locales;\n constructor(params) {\n this.token = params.token;\n this.locales = params.locales;\n this.date = params.date || new globalThis.Date();\n this.parts = params.parts || [this];\n }\n /**\n * Returns `true` if this `DatePart` is a `Token`, `false` otherwise.\n */\n isToken() {\n return false;\n }\n /**\n * Retrieves the next date part in the list of parts.\n */\n nextPart() {\n const currentPartIndex = Option.getOrElse(Arr.findFirstIndex(this.parts, part => part === this), () => 0);\n return Arr.findFirst(this.parts.slice(currentPartIndex + 1), part => !part.isToken());\n }\n /**\n * Retrieves the previous date part in the list of parts.\n */\n previousPart() {\n const currentPartIndex = Arr.findFirstIndex(this.parts, part => part === this);\n if (Option.isSome(currentPartIndex)) {\n return Arr.findLast(this.parts.slice(0, currentPartIndex.value), part => !part.isToken());\n }\n return Option.none();\n }\n toString() {\n return globalThis.String(this.date);\n }\n}\nclass Token extends DatePart {\n increment() {}\n decrement() {}\n setValue(value) {\n this.token = this.token + value;\n }\n isToken() {\n return true;\n }\n toString() {\n return this.token;\n }\n}\nclass Milliseconds extends DatePart {\n increment() {\n this.date.setMilliseconds(this.date.getMilliseconds() + 1);\n }\n decrement() {\n this.date.setMilliseconds(this.date.getMilliseconds() - 1);\n }\n setValue(value) {\n this.date.setMilliseconds(globalThis.Number.parseInt(value.slice(-this.token.length)));\n }\n toString() {\n const millis = `${this.date.getMilliseconds()}`;\n return millis.padStart(4, \"0\").substring(0, this.token.length);\n }\n}\nclass Seconds extends DatePart {\n increment() {\n this.date.setSeconds(this.date.getSeconds() + 1);\n }\n decrement() {\n this.date.setSeconds(this.date.getSeconds() - 1);\n }\n setValue(value) {\n this.date.setSeconds(globalThis.Number.parseInt(value.slice(-2)));\n }\n toString() {\n const seconds = `${this.date.getSeconds()}`;\n return this.token.length > 1 ? seconds.padStart(2, \"0\") : seconds;\n }\n}\nclass Minutes extends DatePart {\n increment() {\n this.date.setMinutes(this.date.getMinutes() + 1);\n }\n decrement() {\n this.date.setMinutes(this.date.getMinutes() - 1);\n }\n setValue(value) {\n this.date.setMinutes(globalThis.Number.parseInt(value.slice(-2)));\n }\n toString() {\n const minutes = `${this.date.getMinutes()}`;\n return this.token.length > 1 ? minutes.padStart(2, \"0\") : minutes;\n }\n}\nclass Hours extends DatePart {\n increment() {\n this.date.setHours(this.date.getHours() + 1);\n }\n decrement() {\n this.date.setHours(this.date.getHours() - 1);\n }\n setValue(value) {\n this.date.setHours(globalThis.Number.parseInt(value.slice(-2)));\n }\n toString() {\n const hours = /h/.test(this.token) ? this.date.getHours() % 12 || 12 : this.date.getHours();\n return this.token.length > 1 ? `${hours}`.padStart(2, \"0\") : `${hours}`;\n }\n}\nclass Day extends DatePart {\n increment() {\n this.date.setDate(this.date.getDate() + 1);\n }\n decrement() {\n this.date.setDate(this.date.getDate() - 1);\n }\n setValue(value) {\n this.date.setDate(globalThis.Number.parseInt(value.slice(-2)));\n }\n toString() {\n const date = this.date.getDate();\n const day = this.date.getDay();\n switch (this.token) {\n case \"DD\":\n return `${date}`.padStart(2, \"0\");\n case \"Do\":\n return `${date}${this.ordinalIndicator(date)}`;\n case \"d\":\n return `${day + 1}`;\n case \"ddd\":\n return this.locales.weekdaysShort[day];\n case \"dddd\":\n return this.locales.weekdays[day];\n default:\n return `${date}`;\n }\n }\n ordinalIndicator(day) {\n if (day >= 11 && day <= 13) {\n return \"th\";\n }\n switch (day % 10) {\n case 1:\n return \"st\";\n case 2:\n return \"nd\";\n case 3:\n return \"rd\";\n default:\n return \"th\";\n }\n }\n}\nclass Month extends DatePart {\n increment() {\n this.date.setMonth(this.date.getMonth() + 1);\n }\n decrement() {\n this.date.setMonth(this.date.getMonth() - 1);\n }\n setValue(value) {\n const month = globalThis.Number.parseInt(value.slice(-2)) - 1;\n this.date.setMonth(month < 0 ? 0 : month);\n }\n toString() {\n const month = this.date.getMonth();\n switch (this.token.length) {\n case 2:\n return `${month + 1}`.padStart(2, \"0\");\n case 3:\n return this.locales.monthsShort[month];\n case 4:\n return this.locales.months[month];\n default:\n return `${month + 1}`;\n }\n }\n}\nclass Year extends DatePart {\n increment() {\n this.date.setFullYear(this.date.getFullYear() + 1);\n }\n decrement() {\n this.date.setFullYear(this.date.getFullYear() - 1);\n }\n setValue(value) {\n this.date.setFullYear(globalThis.Number.parseInt(value.slice(-4)));\n }\n toString() {\n const year = `${this.date.getFullYear()}`.padStart(4, \"0\");\n return this.token.length === 2 ? year.slice(-2) : year;\n }\n}\nclass Meridiem extends DatePart {\n increment() {\n this.date.setHours((this.date.getHours() + 12) % 24);\n }\n decrement() {\n this.increment();\n }\n setValue(_value) {}\n toString() {\n const meridiem = this.date.getHours() >= 12 ? \"pm\" : \"am\";\n return /A/.test(this.token) ? meridiem.toUpperCase() : meridiem;\n }\n}\nconst CONFIRM_MESSAGE = \"The selected directory contains files. Would you like to traverse the selected directory?\";\nconst FILE_FILTER_LABEL = \"filter\";\nconst FILE_FILTER_PLACEHOLDER = \"type to filter\";\nconst FILE_EMPTY_MESSAGE = \"No matches\";\nconst FileConfirm = /*#__PURE__*/Data.taggedEnum();\nconst showConfirmation = /*#__PURE__*/FileConfirm.$is(\"Show\");\nconst resolveCurrentPath = (path, options) => {\n if (Option.isSome(path)) {\n return Effect.succeed(path.value);\n }\n if (Option.isSome(options.startingPath)) {\n const startingPath = options.startingPath.value;\n return Effect.flatMap(FileSystem.FileSystem, fs =>\n // Ensure the user provided starting path exists\n Effect.orDie(fs.exists(startingPath)).pipe(Effect.flatMap(exists => exists ? Effect.void : Effect.die(`The provided starting path '${startingPath}' does not exist`)), Effect.as(startingPath)));\n }\n return Effect.sync(() => process.cwd());\n};\nconst getFileList = /*#__PURE__*/Effect.fnUntraced(function* (directory, options) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const files = yield* Effect.orDie(fs.readDirectory(directory)).pipe(\n // Always prepend the `\"..\"` option to the file list but allow it\n // to be filtered out if the user so desires\n Effect.map(files => [\"..\", ...files]));\n return yield* Effect.filter(files, file => {\n const result = options.filter(file);\n const userDefinedFilter = Effect.isEffect(result) ? result : Effect.succeed(result);\n const directoryFilter = options.type === \"directory\" ? Effect.map(Effect.orDie(fs.stat(path.join(directory, file))), info => info.type === \"Directory\") : Effect.succeed(true);\n return Effect.zipWith(userDefinedFilter, directoryFilter, (a, b) => a && b);\n }, {\n concurrency: files.length\n });\n});\nconst filterFiles = (files, query) => {\n if (query.length === 0) {\n return files;\n }\n const normalizedQuery = query.toLowerCase();\n const filtered = [];\n for (let index = 0; index < files.length; index++) {\n if (files[index].toLowerCase().includes(normalizedQuery)) {\n filtered.push(files[index]);\n }\n }\n return filtered;\n};\nconst updateFileState = (state, query, allFiles = state.allFiles) => {\n const files = filterFiles(allFiles, query);\n if (files.length === 0) {\n return {\n ...state,\n query,\n allFiles,\n files,\n cursor: 0\n };\n }\n const selected = state.files[state.cursor];\n const cursor = selected === undefined ? 0 : files.indexOf(selected);\n return {\n ...state,\n query,\n allFiles,\n files,\n cursor: cursor === -1 ? 0 : cursor\n };\n};\nconst handleFileClear = options => {\n return Effect.fnUntraced(function* (state, _) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const path = yield* Path.Path;\n const figures = yield* getTheme(options);\n const currentPath = yield* resolveCurrentPath(state.path, options);\n const selectedPath = state.files[state.cursor];\n const resolvedPath = selectedPath === undefined ? currentPath : path.resolve(currentPath, selectedPath);\n const resolvedPathText = separateSymbol(figures.pointerSmall, resolvedPath);\n const isConfirming = showConfirmation(state.confirm);\n const promptText = isConfirming ? renderPrompt(\"(Y/n)\", CONFIRM_MESSAGE, figures.prefix, figures.pointerSmall, figures, {\n plain: true\n }) : renderPrompt(renderFileFilter(state, figures, {\n plain: true\n }), options.message, figures.tick, figures.ellipsis, figures, {\n plain: true\n });\n const filesText = isConfirming ? \"\" : renderFiles(state, state.files, figures, options, {\n plain: true\n });\n const outputText = isConfirming ? `${promptText}\\n${resolvedPathText}` : `${promptText}\\n${resolvedPathText}\\n${filesText}`;\n const clearOutput = eraseText(outputText, columns);\n const resetCurrentLine = Ansi.eraseLine + Ansi.cursorLeft;\n return clearOutput + resetCurrentLine;\n });\n};\nconst renderPrompt = (confirm, message, leadingSymbol, trailingSymbol, theme, options) => {\n const prefix = leadingSymbol.length === 0 ? \"\" : leadingSymbol + \" \";\n const renderLine = line => {\n let output = prefix + line;\n if (trailingSymbol.length > 0) {\n output += \" \" + trailingSymbol;\n }\n if (confirm.length > 0) {\n output += \" \" + confirm;\n } else if (trailingSymbol.length > 0) {\n output += \" \";\n }\n return output;\n };\n return Arr.match(message.split(NEWLINE_REGEXP), {\n onEmpty: () => renderLine(\"\"),\n onNonEmpty: promptLines => {\n const lines = options?.plain === true ? promptLines : Arr.map(promptLines, line => Ansi.annotate(theme.colors, line, Ansi.bold));\n return renderLine(lines.join(\"\\n\"));\n }\n });\n};\nconst renderPrefix = (state, toDisplay, currentIndex, length, figures, renderOptions) => {\n const prefix = renderPagingPrefix(figures, currentIndex === toDisplay.startIndex && toDisplay.startIndex > 0, currentIndex === toDisplay.endIndex - 1 && toDisplay.endIndex < length);\n if (state.cursor === currentIndex) {\n return renderOptions?.plain === true ? figures.pointer + prefix : annotateSymbol(figures, figures.pointer, figures.primaryColor) + prefix;\n }\n return prefix + \" \".repeat(figures.pointer.length);\n};\nconst renderFileName = (file, isSelected, theme, renderOptions) => {\n if (renderOptions?.plain === true) {\n return file;\n }\n return isSelected ? Ansi.annotate(theme.colors, file, Ansi.combine(Ansi.underlined, theme.primaryColor)) : file;\n};\nconst renderFileFilter = (state, theme, renderOptions) => {\n const filterValue = state.query.length === 0 ? renderOptions?.plain === true ? FILE_FILTER_PLACEHOLDER : Ansi.annotate(theme.colors, FILE_FILTER_PLACEHOLDER, theme.mutedColor) : renderOptions?.plain === true ? state.query : Ansi.annotate(theme.colors, state.query, Ansi.combine(Ansi.underlined, theme.primaryColor));\n return `[${FILE_FILTER_LABEL}: ${filterValue}]`;\n};\nconst renderFiles = (state, files, figures, options, renderOptions) => {\n const length = files.length;\n if (length === 0) {\n return renderOptions?.plain === true ? FILE_EMPTY_MESSAGE : Ansi.annotate(figures.colors, FILE_EMPTY_MESSAGE, figures.mutedColor);\n }\n const toDisplay = entriesToDisplay(state.cursor, length, options.maxPerPage);\n const documents = [];\n for (let index = toDisplay.startIndex; index < toDisplay.endIndex; index++) {\n const isSelected = state.cursor === index;\n const prefix = renderPrefix(state, toDisplay, index, length, figures, renderOptions);\n const fileName = renderFileName(files[index], isSelected, figures, renderOptions);\n documents.push(prefix + fileName);\n }\n return documents.join(\"\\n\");\n};\nconst renderFileNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const path = yield* Path.Path;\n const figures = yield* getTheme(options);\n const currentPath = yield* resolveCurrentPath(state.path, options);\n const selectedPath = state.files[state.cursor];\n const resolvedPath = selectedPath === undefined ? currentPath : path.resolve(currentPath, selectedPath);\n const resolvedPathMsg = Ansi.annotate(figures.colors, separateSymbol(figures.pointerSmall, resolvedPath), figures.mutedColor);\n if (showConfirmation(state.confirm)) {\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const confirm = Ansi.annotate(figures.colors, \"(Y/n)\", figures.mutedColor);\n const promptMsg = renderPrompt(confirm, CONFIRM_MESSAGE, leadingSymbol, trailingSymbol, figures);\n return Ansi.cursorHide + promptMsg + \"\\n\" + resolvedPathMsg;\n }\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const promptMsg = renderPrompt(renderFileFilter(state, figures), options.message, leadingSymbol, trailingSymbol, figures);\n const files = renderFiles(state, state.files, figures, options);\n return Ansi.cursorHide + promptMsg + \"\\n\" + resolvedPathMsg + \"\\n\" + files;\n});\nconst renderFileSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, value, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const promptMsg = renderPrompt(renderFileFilter(state, figures), options.message, leadingSymbol, trailingSymbol, figures);\n return promptMsg + \" \" + Ansi.annotate(figures.colors, value, figures.submittedColor) + \"\\n\";\n});\nconst handleFileRender = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderFileNextFrame(state, options),\n Submit: ({\n value\n }) => renderFileSubmission(state, value, options)\n });\n };\n};\nconst processFileCursorUp = state => {\n if (state.files.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const cursor = state.cursor - 1;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor: cursor < 0 ? state.files.length - 1 : cursor\n }\n }));\n};\nconst processFileCursorDown = state => {\n if (state.files.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor: (state.cursor + 1) % state.files.length\n }\n }));\n};\nconst processFileBackspace = state => {\n if (state.query.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const query = state.query.slice(0, state.query.length - 1);\n return Effect.succeed(Action.NextFrame({\n state: updateFileState(state, query)\n }));\n};\nconst processFileClear = state => Effect.succeed(Action.NextFrame({\n state: updateFileState(state, \"\")\n}));\nconst processFileInput = (input, state) => {\n if (input.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const query = state.query + input;\n return Effect.succeed(Action.NextFrame({\n state: updateFileState(state, query)\n }));\n};\nconst processSelection = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n if (state.files.length === 0) {\n return Action.Beep();\n }\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const currentPath = yield* resolveCurrentPath(state.path, options);\n const selectedPath = state.files[state.cursor];\n const resolvedPath = path.resolve(currentPath, selectedPath);\n const info = yield* Effect.orDie(fs.stat(resolvedPath));\n if (info.type === \"Directory\") {\n const files = yield* getFileList(resolvedPath, options);\n const filesWithoutParent = files.filter(file => file !== \"..\");\n // If the user selected a directory AND the prompt type can result with\n // a directory, we must confirm:\n // - If the selected directory has any files\n // - Confirm whether or not the user wants to traverse those files\n if (options.type === \"directory\" || options.type === \"either\") {\n return filesWithoutParent.length === 0\n // Directory is empty so it's safe to select it\n ? Action.Submit({\n value: resolvedPath\n })\n // Directory has contents - show confirmation to user\n : Action.NextFrame({\n state: {\n ...state,\n confirm: FileConfirm.Show()\n }\n });\n }\n return Action.NextFrame({\n state: {\n cursor: 0,\n files,\n allFiles: files,\n query: \"\",\n path: Option.some(resolvedPath),\n confirm: FileConfirm.Hide()\n }\n });\n }\n return Action.Submit({\n value: resolvedPath\n });\n});\nconst handleFileProcess = options => {\n return Effect.fnUntraced(function* (input, state) {\n // Navigation is bound to ctrl chords rather than bare `j`/`k`, so that every\n // printable character reaches the filter input.\n if (input.key.ctrl) {\n switch (input.key.name) {\n case \"u\":\n {\n if (showConfirmation(state.confirm)) {\n return Action.Beep();\n }\n return yield* processFileClear(state);\n }\n case \"p\":\n case \"k\":\n {\n return yield* processFileCursorUp(state);\n }\n case \"n\":\n {\n return yield* processFileCursorDown(state);\n }\n default:\n {\n return Action.Beep();\n }\n }\n }\n switch (input.key.name) {\n case \"up\":\n {\n return yield* processFileCursorUp(state);\n }\n case \"down\":\n case \"tab\":\n {\n return yield* processFileCursorDown(state);\n }\n case \"backspace\":\n {\n if (showConfirmation(state.confirm)) {\n return Action.Beep();\n }\n return yield* processFileBackspace(state);\n }\n case \"enter\":\n case \"return\":\n {\n return yield* processSelection(state, options);\n }\n case \"y\":\n case \"t\":\n {\n if (showConfirmation(state.confirm)) {\n const path = yield* Path.Path;\n const currentPath = yield* resolveCurrentPath(state.path, options);\n const selectedPath = state.files[state.cursor];\n const resolvedPath = path.resolve(currentPath, selectedPath);\n const files = yield* getFileList(resolvedPath, options);\n return Action.NextFrame({\n state: {\n cursor: 0,\n files,\n allFiles: files,\n query: \"\",\n path: Option.some(resolvedPath),\n confirm: FileConfirm.Hide()\n }\n });\n }\n return yield* processFileInput(Option.getOrElse(input.input, () => \"\"), state);\n }\n case \"n\":\n case \"f\":\n {\n if (showConfirmation(state.confirm)) {\n const path = yield* Path.Path;\n const currentPath = yield* resolveCurrentPath(state.path, options);\n const selectedPath = state.files[state.cursor];\n const resolvedPath = path.resolve(currentPath, selectedPath);\n return Action.Submit({\n value: resolvedPath\n });\n }\n return yield* processFileInput(Option.getOrElse(input.input, () => \"\"), state);\n }\n default:\n {\n if (showConfirmation(state.confirm)) {\n return Action.Beep();\n }\n return yield* processFileInput(Option.getOrElse(input.input, () => \"\"), state);\n }\n }\n });\n};\nconst renderMultiSelectError = (state, pointer, theme, renderOptions) => {\n if (Option.isSome(state.error)) {\n return Arr.match(state.error.value.split(NEWLINE_REGEXP), {\n onEmpty: () => \"\",\n onNonEmpty: errorLines => {\n if (renderOptions?.plain === true) {\n return separateSymbol(pointer, errorLines.join(\"\\n\"));\n }\n const prefix = annotateSymbol(theme, pointer, theme.errorColor);\n const lines = Arr.map(errorLines, str => annotateErrorLine(theme, str));\n return Ansi.cursorSavePosition + \"\\n\" + separateSymbol(prefix, lines.join(\"\\n\")) + Ansi.cursorRestorePosition;\n }\n });\n }\n return \"\";\n};\nconst renderChoiceDescription = (choice, isActive, theme, renderOptions) => {\n if (!choice.disabled && choice.description && isActive) {\n const text = theme.descriptionSeparator + choice.description;\n return renderOptions?.plain === true ? text : Ansi.annotate(theme.colors, text, theme.mutedColor);\n }\n return \"\";\n};\nconst metaOptionsCount = 2;\nconst renderMultiSelectTitle = (title, isHighlighted, theme, renderOptions) => {\n if (renderOptions?.plain === true || !isHighlighted) {\n return title;\n }\n return Ansi.annotate(theme.colors, title, Ansi.combine(Ansi.underlined, theme.primaryColor));\n};\nconst renderMultiSelectChoices = (state, options, figures, renderOptions) => {\n const choices = options.choices;\n const checkboxWidth = Math.max(figures.checkboxOn.length, figures.checkboxOff.length);\n const selectableCount = choices.filter(choice => !choice.disabled).length;\n const selectedCount = Array.from(state.selectedIndices).filter(index => !choices[index].disabled).length;\n const allSelected = selectedCount === selectableCount;\n const selectAllText = allSelected ? options?.selectNone ?? \"Select None\" : options?.selectAll ?? \"Select All\";\n const inverseSelectionText = options?.inverseSelection ?? \"Inverse Selection\";\n const metaOptions = [{\n title: selectAllText\n }, {\n title: inverseSelectionText\n }];\n const allChoices = [...metaOptions, ...choices];\n const toDisplay = entriesToDisplay(state.index, allChoices.length, options.maxPerPage);\n const documents = [];\n for (let index = toDisplay.startIndex; index < toDisplay.endIndex; index++) {\n const choice = allChoices[index];\n const isHighlighted = state.index === index;\n const prefix = renderPagingPrefix(figures, index === toDisplay.startIndex && toDisplay.startIndex > 0, index === toDisplay.endIndex - 1 && toDisplay.endIndex < allChoices.length);\n if (index < metaOptions.length) {\n // Meta options\n const title = renderMultiSelectTitle(choice.title, isHighlighted, figures, renderOptions);\n documents.push(prefix + (prefix.length === 0 ? \"\" : \" \") + title);\n } else {\n // Regular choices\n const choiceIndex = index - metaOptions.length;\n const isSelected = state.selectedIndices.has(choiceIndex);\n const checkbox = isSelected ? figures.checkboxOn : figures.checkboxOff;\n const annotatedCheckbox = isHighlighted && renderOptions?.plain !== true ? Ansi.annotate(figures.colors, checkbox, figures.primaryColor) : checkbox;\n const selectChoice = choice;\n const title = renderChoiceTitle(selectChoice, isHighlighted, figures, renderOptions);\n const description = renderChoiceDescription(selectChoice, isHighlighted, figures, renderOptions);\n const checkboxPrefix = checkboxWidth === 0 ? \"\" : annotatedCheckbox + \" \".repeat(checkboxWidth - checkbox.length + 1);\n documents.push(prefix + (prefix.length === 0 ? \"\" : \" \") + checkboxPrefix + title + \" \" + description);\n }\n }\n return documents.join(\"\\n\");\n};\nconst renderMultiSelectNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const choices = renderMultiSelectChoices(state, options, figures);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const promptMsg = renderSelectOutput(leadingSymbol, trailingSymbol, options, figures);\n const error = renderMultiSelectError(state, figures.pointer, figures);\n return Ansi.cursorHide + withSelectHeader(promptMsg, choices) + error;\n});\nconst renderMultiSelectSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const selectedChoices = Array.from(state.selectedIndices).sort(EffectNumber.Order).map(index => options.choices[index].title);\n const selectedText = selectedChoices.join(\", \");\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const promptMsg = renderSelectOutput(leadingSymbol, trailingSymbol, options, figures) ?? leadingSymbol;\n return promptMsg + \" \" + Ansi.annotate(figures.colors, selectedText, figures.submittedColor) + \"\\n\";\n});\nconst processMultiSelectCursorUp = (state, totalChoices) => {\n const newIndex = state.index === 0 ? totalChoices - 1 : state.index - 1;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n index: newIndex\n }\n }));\n};\nconst processMultiSelectCursorDown = (state, totalChoices) => {\n const newIndex = (state.index + 1) % totalChoices;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n index: newIndex\n }\n }));\n};\nconst processSpace = (state, options) => {\n const selectedIndices = new Set(state.selectedIndices);\n if (state.index === 0) {\n const selectableCount = options.choices.filter(choice => !choice.disabled).length;\n const selectedCount = Array.from(state.selectedIndices).filter(index => !options.choices[index].disabled).length;\n if (selectedCount === selectableCount) {\n selectedIndices.clear();\n } else {\n for (let i = 0; i < options.choices.length; i++) {\n if (!options.choices[i].disabled) {\n selectedIndices.add(i);\n }\n }\n }\n } else if (state.index === 1) {\n for (let i = 0; i < options.choices.length; i++) {\n if (options.choices[i].disabled || state.selectedIndices.has(i)) {\n selectedIndices.delete(i);\n } else {\n selectedIndices.add(i);\n }\n }\n } else {\n const choiceIndex = state.index - metaOptionsCount;\n if (options.choices[choiceIndex].disabled) {\n return Effect.succeed(Action.Beep());\n } else if (selectedIndices.has(choiceIndex)) {\n selectedIndices.delete(choiceIndex);\n } else {\n selectedIndices.add(choiceIndex);\n }\n }\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n selectedIndices\n }\n }));\n};\nconst handleMultiSelectClear = options => Effect.fnUntraced(function* (state, _) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const clearPrompt = Ansi.eraseLine + Ansi.cursorLeft;\n const promptText = renderSelectOutput(figures.prefix, figures.pointerSmall, options, figures, {\n plain: true\n });\n const choicesText = renderMultiSelectChoices(state, options, figures, {\n plain: true\n });\n const errorText = renderMultiSelectError(state, figures.pointer, figures, {\n plain: true\n });\n const clearOutput = clearOutputWithError(withSelectHeader(promptText, choicesText), columns, errorText);\n return clearOutput + clearPrompt;\n});\nconst handleMultiSelectProcess = options => {\n return (input, state) => {\n const totalChoices = options.choices.length + metaOptionsCount;\n switch (input.key.name) {\n case \"k\":\n case \"up\":\n {\n return processMultiSelectCursorUp({\n ...state,\n error: Option.none()\n }, totalChoices);\n }\n case \"j\":\n case \"down\":\n case \"tab\":\n {\n return processMultiSelectCursorDown({\n ...state,\n error: Option.none()\n }, totalChoices);\n }\n case \"space\":\n {\n return processSpace(state, options);\n }\n case \"enter\":\n case \"return\":\n {\n const selectedIndices = Array.from(state.selectedIndices).filter(index => !options.choices[index].disabled);\n const selectedCount = selectedIndices.length;\n if (options.min !== undefined && selectedCount < options.min) {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n error: Option.some(`At least ${options.min} are required`)\n }\n }));\n }\n if (options.max !== undefined && selectedCount > options.max) {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n error: Option.some(`At most ${options.max} choices are allowed`)\n }\n }));\n }\n const selectedValues = selectedIndices.sort(EffectNumber.Order).map(index => options.choices[index].value);\n return Effect.succeed(Action.Submit({\n value: selectedValues\n }));\n }\n default:\n {\n return Effect.succeed(Action.Beep());\n }\n }\n };\n};\nconst handleMultiSelectRender = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderMultiSelectNextFrame(state, options),\n Submit: () => renderMultiSelectSubmission(state, options)\n });\n };\n};\nconst handleNumberClear = options => {\n return Effect.fnUntraced(function* (state, _) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const resetCurrentLine = Ansi.eraseLine + Ansi.cursorLeft;\n const errorText = renderNumberError(state, figures.pointerSmall, figures, {\n plain: true\n });\n const promptText = renderNumberOutput(state, figures.prefix, figures.pointerSmall, options, figures, {\n plain: true\n });\n const clearOutput = clearOutputWithError(promptText, columns, errorText);\n return clearOutput + resetCurrentLine;\n });\n};\nconst renderNumberInput = (state, submitted, theme, renderOptions) => {\n const value = state.value === \"\" ? \"\" : `${state.value}`;\n if (submitted || renderOptions?.plain === true) {\n return value;\n }\n const annotation = Option.isSome(state.error) ? theme.errorColor : Ansi.combine(Ansi.underlined, theme.primaryColor);\n return Ansi.annotate(theme.colors, value, annotation);\n};\nconst renderNumberError = (state, pointer, theme, renderOptions) => {\n if (Option.isSome(state.error)) {\n return Arr.match(state.error.value.split(NEWLINE_REGEXP), {\n onEmpty: () => \"\",\n onNonEmpty: errorLines => {\n if (renderOptions?.plain === true) {\n return separateSymbol(pointer, errorLines.join(\"\\n\"));\n }\n const prefix = annotateSymbol(theme, pointer, theme.errorColor);\n const lines = Arr.map(errorLines, str => annotateErrorLine(theme, str));\n return Ansi.cursorSavePosition + \"\\n\" + separateSymbol(prefix, lines.join(\"\\n\")) + Ansi.cursorRestorePosition;\n }\n });\n }\n return \"\";\n};\nconst renderNumberOutput = (state, leadingSymbol, trailingSymbol, options, theme, renderOptions, submitted = false) => {\n const value = renderNumberInput(state, submitted, theme, renderOptions);\n return renderPrompt(value, options.message, leadingSymbol, trailingSymbol, theme, renderOptions);\n};\nconst renderNumberNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const errorMsg = renderNumberError(state, figures.pointerSmall, figures);\n const promptMsg = renderNumberOutput(state, leadingSymbol, trailingSymbol, options, figures);\n return promptMsg + errorMsg;\n});\nconst renderNumberSubmission = /*#__PURE__*/Effect.fnUntraced(function* (nextState, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const promptMsg = renderNumberOutput(nextState, leadingSymbol, trailingSymbol, options, figures, undefined, true);\n return promptMsg + \"\\n\";\n});\nconst processNumberBackspace = state => {\n if (state.value.length <= 0) {\n return Effect.succeed(Action.Beep());\n }\n const value = state.value.slice(0, state.value.length - 1);\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value,\n error: Option.none()\n }\n }));\n};\nconst processNumberClear = state => Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor: 0,\n value: \"\",\n error: Option.none()\n }\n}));\nconst defaultIntProcessor = (input, state) => {\n if (state.value.length === 0 && input === \"-\") {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: \"-\",\n error: Option.none()\n }\n }));\n }\n const parsed = globalThis.Number.parseInt(state.value + input);\n if (globalThis.Number.isNaN(parsed)) {\n return Effect.succeed(Action.Beep());\n } else {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: `${parsed}`,\n error: Option.none()\n }\n }));\n }\n};\nconst defaultFloatProcessor = (input, state) => {\n if (input === \".\" && state.value.includes(\".\")) {\n return Effect.succeed(Action.Beep());\n }\n if (state.value.length === 0 && input === \"-\") {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: \"-\",\n error: Option.none()\n }\n }));\n }\n const parsed = globalThis.Number.parseFloat(state.value + input);\n if (globalThis.Number.isNaN(parsed)) {\n return Effect.succeed(Action.Beep());\n } else {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: input === \".\" ? `${parsed}.` : state.value.includes(\".\") && /^\\d$/.test(input) ? state.value + input : `${parsed}`,\n error: Option.none()\n }\n }));\n }\n};\nconst handleRenderInteger = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderNumberNextFrame(state, options),\n Submit: () => renderNumberSubmission(state, options)\n });\n };\n};\nconst handleProcessInteger = options => {\n return (input, state) => {\n if (input.key.ctrl && input.key.name === \"u\") {\n return processNumberClear(state);\n }\n switch (input.key.name) {\n case \"backspace\":\n {\n return processNumberBackspace(state);\n }\n case \"k\":\n case \"up\":\n {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: state.value === \"\" || state.value === \"-\" ? `${options.incrementBy}` : `${globalThis.Number.parseInt(state.value) + options.incrementBy}`,\n error: Option.none()\n }\n }));\n }\n case \"j\":\n case \"down\":\n {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: state.value === \"\" || state.value === \"-\" ? `-${options.decrementBy}` : `${globalThis.Number.parseInt(state.value) - options.decrementBy}`,\n error: Option.none()\n }\n }));\n }\n case \"enter\":\n case \"return\":\n {\n const parsed = globalThis.Number.parseInt(state.value);\n if (globalThis.Number.isNaN(parsed)) {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n error: Option.some(\"Must provide an integer value\")\n }\n }));\n } else {\n return Effect.match(options.validate(parsed), {\n onFailure: error => Action.NextFrame({\n state: {\n ...state,\n error: Option.some(error)\n }\n }),\n onSuccess: value => Action.Submit({\n value\n })\n });\n }\n }\n default:\n {\n return defaultIntProcessor(Option.getOrElse(input.input, () => \"\"), state);\n }\n }\n };\n};\nconst handleRenderFloat = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderNumberNextFrame(state, options),\n Submit: () => renderNumberSubmission(state, options)\n });\n };\n};\nconst handleProcessFloat = options => {\n return (input, state) => {\n if (input.key.ctrl && input.key.name === \"u\") {\n return processNumberClear(state);\n }\n switch (input.key.name) {\n case \"backspace\":\n {\n return processNumberBackspace(state);\n }\n case \"k\":\n case \"up\":\n {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: state.value === \"\" || state.value === \"-\" ? `${options.incrementBy}` : `${globalThis.Number.parseFloat(state.value) + options.incrementBy}`,\n error: Option.none()\n }\n }));\n }\n case \"j\":\n case \"down\":\n {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value: state.value === \"\" || state.value === \"-\" ? `-${options.decrementBy}` : `${globalThis.Number.parseFloat(state.value) - options.decrementBy}`,\n error: Option.none()\n }\n }));\n }\n case \"enter\":\n case \"return\":\n {\n const parsed = globalThis.Number.parseFloat(state.value);\n if (globalThis.Number.isNaN(parsed)) {\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n error: Option.some(\"Must provide a floating point value\")\n }\n }));\n } else {\n return Effect.flatMap(Effect.sync(() => EffectNumber.round(parsed, options.precision)), rounded => Effect.match(options.validate(rounded), {\n onFailure: error => Action.NextFrame({\n state: {\n ...state,\n error: Option.some(error)\n }\n }),\n onSuccess: value => Action.Submit({\n value\n })\n }));\n }\n }\n default:\n {\n return defaultFloatProcessor(Option.getOrElse(input.input, () => \"\"), state);\n }\n }\n };\n};\nconst filterAutoCompleteChoices = (choices, query) => {\n const normalizedQuery = query.toLowerCase();\n const indices = [];\n for (let i = 0; i < choices.length; i++) {\n if (choices[i].title.toLowerCase().includes(normalizedQuery)) {\n indices.push(i);\n }\n }\n return indices;\n};\nconst updateAutoCompleteState = (state, options, query) => {\n const filtered = filterAutoCompleteChoices(options.choices, query);\n if (filtered.length === 0) {\n return {\n ...state,\n query,\n filtered,\n index: 0\n };\n }\n if (filtered.includes(state.index)) {\n return {\n ...state,\n query,\n filtered\n };\n }\n return {\n ...state,\n query,\n filtered,\n index: filtered[0]\n };\n};\nconst autoCompleteCursor = state => Option.getOrElse(Arr.findFirstIndex(state.filtered, index => index === state.index), () => 0);\nconst renderSelectOutput = (leadingSymbol, trailingSymbol, options, theme, renderOptions) => options.message === undefined ? undefined : renderPrompt(\"\", options.message, leadingSymbol, trailingSymbol, theme, renderOptions);\nconst withSelectHeader = (header, body) => header === undefined ? body : header + \"\\n\" + body;\nconst renderAutoCompleteFilter = (state, options, theme, renderOptions) => {\n const filterValue = state.query.length === 0 ? renderOptions?.plain === true ? options.filterPlaceholder : Ansi.annotate(theme.colors, options.filterPlaceholder, theme.mutedColor) : renderOptions?.plain === true ? state.query : Ansi.annotate(theme.colors, state.query, Ansi.combine(Ansi.underlined, theme.primaryColor));\n return `[${options.filterLabel}: ${filterValue}]`;\n};\nconst renderAutoCompleteOutput = (state, leadingSymbol, trailingSymbol, options, theme, renderOptions) => {\n const filter = renderAutoCompleteFilter(state, options, theme, renderOptions);\n return renderPrompt(filter, options.message, leadingSymbol, trailingSymbol, theme, renderOptions);\n};\nconst renderChoicePrefix = (state, choices, toDisplay, currentIndex, figures, renderOptions) => {\n const prefix = renderPagingPrefix(figures, currentIndex === toDisplay.startIndex && toDisplay.startIndex > 0, currentIndex === toDisplay.endIndex - 1 && toDisplay.endIndex < choices.length);\n if (renderOptions?.plain === true) {\n return state === currentIndex ? figures.pointer + prefix : prefix + \" \".repeat(figures.pointer.length);\n }\n if (choices[currentIndex].disabled) {\n const annotation = Ansi.combine(Ansi.bold, figures.mutedColor);\n return state === currentIndex ? annotateSymbol(figures, figures.pointer, annotation) + prefix : prefix + \" \".repeat(figures.pointer.length);\n }\n return state === currentIndex ? annotateSymbol(figures, figures.pointer, figures.primaryColor) + prefix : prefix + \" \".repeat(figures.pointer.length);\n};\nconst renderAutoCompleteChoicePrefix = (state, options, toDisplay, currentIndex, figures, renderOptions) => {\n const prefix = renderPagingPrefix(figures, currentIndex === toDisplay.startIndex && toDisplay.startIndex > 0, currentIndex === toDisplay.endIndex - 1 && toDisplay.endIndex < state.filtered.length);\n const choiceIndex = state.filtered[currentIndex];\n if (renderOptions?.plain === true) {\n return state.index === choiceIndex ? figures.pointer + prefix : prefix + \" \".repeat(figures.pointer.length);\n }\n const choice = options.choices[choiceIndex];\n if (choice.disabled) {\n const annotation = Ansi.combine(Ansi.bold, figures.mutedColor);\n return state.index === choiceIndex ? annotateSymbol(figures, figures.pointer, annotation) + prefix : prefix + \" \".repeat(figures.pointer.length);\n }\n return state.index === choiceIndex ? annotateSymbol(figures, figures.pointer, figures.primaryColor) + prefix : prefix + \" \".repeat(figures.pointer.length);\n};\nconst renderChoiceTitle = (choice, isSelected, theme, renderOptions) => {\n if (renderOptions?.plain === true) {\n return choice.title;\n }\n const title = choice.title;\n if (isSelected) {\n return choice.disabled ? Ansi.annotate(theme.colors, title, Ansi.combine(Ansi.underlined, theme.mutedColor)) : Ansi.annotate(theme.colors, title, Ansi.combine(Ansi.underlined, theme.primaryColor));\n }\n return choice.disabled ? Ansi.annotate(theme.colors, title, Ansi.combine(Ansi.strikethrough, theme.mutedColor)) : title;\n};\nconst renderSelectChoices = (state, options, figures, renderOptions) => {\n const choices = options.choices;\n const toDisplay = entriesToDisplay(state, choices.length, options.maxPerPage);\n const documents = [];\n for (let index = toDisplay.startIndex; index < toDisplay.endIndex; index++) {\n const choice = choices[index];\n const isSelected = state === index;\n const prefix = renderChoicePrefix(state, choices, toDisplay, index, figures, renderOptions);\n const title = renderChoiceTitle(choice, isSelected, figures, renderOptions);\n const description = renderChoiceDescription(choice, isSelected, figures, renderOptions);\n documents.push(prefix + title + \" \" + description);\n }\n return documents.join(\"\\n\");\n};\nconst renderAutoCompleteChoices = (state, options, figures, renderOptions) => {\n if (state.filtered.length === 0) {\n return renderOptions?.plain === true ? options.emptyMessage : Ansi.annotate(figures.colors, options.emptyMessage, figures.mutedColor);\n }\n const cursor = autoCompleteCursor(state);\n const toDisplay = entriesToDisplay(cursor, state.filtered.length, options.maxPerPage);\n const documents = [];\n for (let index = toDisplay.startIndex; index < toDisplay.endIndex; index++) {\n const choiceIndex = state.filtered[index];\n const choice = options.choices[choiceIndex];\n const isSelected = state.index === choiceIndex;\n const prefix = renderAutoCompleteChoicePrefix(state, options, toDisplay, index, figures, renderOptions);\n const title = renderChoiceTitle(choice, isSelected, figures, renderOptions);\n const description = renderChoiceDescription(choice, isSelected, figures, renderOptions);\n documents.push(prefix + title + \" \" + description);\n }\n return documents.join(\"\\n\");\n};\nconst renderSelectNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const choices = renderSelectChoices(state, options, figures);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const promptMsg = renderSelectOutput(leadingSymbol, trailingSymbol, options, figures);\n return Ansi.cursorHide + withSelectHeader(promptMsg, choices);\n});\nconst renderAutoCompleteNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const choices = renderAutoCompleteChoices(state, options, figures);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const promptMsg = renderAutoCompleteOutput(state, leadingSymbol, trailingSymbol, options, figures);\n return Ansi.cursorHide + promptMsg + \"\\n\" + choices;\n});\nconst renderSelectSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const selected = options.choices[state].title;\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const promptMsg = renderSelectOutput(leadingSymbol, trailingSymbol, options, figures) ?? leadingSymbol;\n return promptMsg + \" \" + Ansi.annotate(figures.colors, selected, figures.submittedColor) + \"\\n\";\n});\nconst renderAutoCompleteSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const selected = options.choices[state.index].title;\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const promptMsg = renderAutoCompleteOutput(state, leadingSymbol, trailingSymbol, options, figures);\n return promptMsg + \" \" + Ansi.annotate(figures.colors, selected, figures.submittedColor) + \"\\n\";\n});\nconst processSelectCursorUp = (state, choices) => {\n if (state === 0) {\n return Effect.succeed(Action.NextFrame({\n state: choices.length - 1\n }));\n }\n return Effect.succeed(Action.NextFrame({\n state: state - 1\n }));\n};\nconst processSelectCursorDown = (state, choices) => {\n if (state === choices.length - 1) {\n return Effect.succeed(Action.NextFrame({\n state: 0\n }));\n }\n return Effect.succeed(Action.NextFrame({\n state: state + 1\n }));\n};\nconst processSelectNext = (state, choices) => {\n return Effect.succeed(Action.NextFrame({\n state: (state + 1) % choices.length\n }));\n};\nconst processAutoCompleteCursorUp = state => {\n if (state.filtered.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const cursor = autoCompleteCursor(state);\n const nextCursor = cursor === 0 ? state.filtered.length - 1 : cursor - 1;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n index: state.filtered[nextCursor]\n }\n }));\n};\nconst processAutoCompleteCursorDown = state => {\n if (state.filtered.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const cursor = autoCompleteCursor(state);\n const nextCursor = (cursor + 1) % state.filtered.length;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n index: state.filtered[nextCursor]\n }\n }));\n};\nconst processAutoCompleteNext = state => processAutoCompleteCursorDown(state);\nconst processAutoCompleteBackspace = (state, options) => {\n if (state.query.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const query = state.query.slice(0, state.query.length - 1);\n return Effect.succeed(Action.NextFrame({\n state: updateAutoCompleteState(state, options, query)\n }));\n};\nconst processAutoCompleteClear = (state, options) => Effect.succeed(Action.NextFrame({\n state: updateAutoCompleteState(state, options, \"\")\n}));\nconst processAutoCompleteInput = (input, state, options) => {\n if (input.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const query = state.query + input;\n return Effect.succeed(Action.NextFrame({\n state: updateAutoCompleteState(state, options, query)\n }));\n};\nconst handleSelectRender = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderSelectNextFrame(state, options),\n Submit: () => renderSelectSubmission(state, options)\n });\n };\n};\nconst handleAutoCompleteRender = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderAutoCompleteNextFrame(state, options),\n Submit: () => renderAutoCompleteSubmission(state, options)\n });\n };\n};\nconst handleSelectClear = options => Effect.fnUntraced(function* (state, _) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const clearPrompt = Ansi.eraseLine + Ansi.cursorLeft;\n const promptText = renderSelectOutput(figures.prefix, figures.pointerSmall, options, figures, {\n plain: true\n });\n const choicesText = renderSelectChoices(state, options, figures, {\n plain: true\n });\n const clearOutput = eraseText(withSelectHeader(promptText, choicesText), columns);\n return clearOutput + clearPrompt;\n});\nconst handleAutoCompleteClear = options => Effect.fnUntraced(function* (state, _) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const clearPrompt = Ansi.eraseLine + Ansi.cursorLeft;\n const promptText = renderAutoCompleteOutput(state, figures.prefix, figures.pointerSmall, options, figures, {\n plain: true\n });\n const choicesText = renderAutoCompleteChoices(state, options, figures, {\n plain: true\n });\n const clearOutput = eraseText(`${promptText}\\n${choicesText}`, columns);\n return clearOutput + clearPrompt;\n});\nconst handleSelectProcess = options => {\n return (input, state) => {\n switch (input.key.name) {\n case \"k\":\n case \"up\":\n {\n return processSelectCursorUp(state, options.choices);\n }\n case \"j\":\n case \"down\":\n {\n return processSelectCursorDown(state, options.choices);\n }\n case \"tab\":\n {\n return processSelectNext(state, options.choices);\n }\n case \"enter\":\n case \"return\":\n {\n const selected = options.choices[state];\n if (selected.disabled) {\n return Effect.succeed(Action.Beep());\n }\n return Effect.succeed(Action.Submit({\n value: selected.value\n }));\n }\n default:\n {\n return Effect.succeed(Action.Beep());\n }\n }\n };\n};\nconst handleAutoCompleteProcess = options => {\n return (input, state) => {\n // Navigation is bound to ctrl chords rather than bare `j`/`k`, so that every\n // printable character reaches the filter input.\n if (input.key.ctrl) {\n switch (input.key.name) {\n case \"u\":\n {\n return processAutoCompleteClear(state, options);\n }\n case \"p\":\n case \"k\":\n {\n return processAutoCompleteCursorUp(state);\n }\n case \"n\":\n {\n return processAutoCompleteCursorDown(state);\n }\n default:\n {\n return Effect.succeed(Action.Beep());\n }\n }\n }\n switch (input.key.name) {\n case \"up\":\n {\n return processAutoCompleteCursorUp(state);\n }\n case \"down\":\n {\n return processAutoCompleteCursorDown(state);\n }\n case \"tab\":\n {\n return processAutoCompleteNext(state);\n }\n case \"backspace\":\n {\n return processAutoCompleteBackspace(state, options);\n }\n case \"enter\":\n case \"return\":\n {\n if (state.filtered.length === 0) {\n return Effect.succeed(Action.Beep());\n }\n const selected = options.choices[state.index];\n if (selected.disabled) {\n return Effect.succeed(Action.Beep());\n }\n return Effect.succeed(Action.Submit({\n value: selected.value\n }));\n }\n default:\n {\n return processAutoCompleteInput(Option.getOrElse(input.input, () => \"\"), state, options);\n }\n }\n };\n};\nconst renderClearScreen = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const resetCurrentLine = Ansi.eraseLine + Ansi.cursorLeft;\n const errorText = renderTextError(state, figures.pointerSmall, figures, {\n plain: true\n });\n const clearOutput = clearOutputWithError(renderTextOutput(state, figures.prefix, figures.pointerSmall, options, figures, {\n plain: true\n }), columns, errorText);\n return clearOutput + resetCurrentLine;\n});\nconst renderTextInput = (nextState, options, theme, submitted, renderOptions) => {\n const text = nextState.value;\n if (renderOptions?.plain === true) {\n switch (options.type) {\n case \"hidden\":\n {\n return \"\";\n }\n case \"password\":\n {\n return theme.passwordMask.repeat(text.length);\n }\n case \"text\":\n {\n return text;\n }\n }\n }\n if (text.length === 0) {\n // Avoid wrapping an empty value in ANSI codes, which would make renderPrompt\n // add spacing for content that occupies no terminal columns.\n return \"\";\n }\n const annotation = Option.isSome(nextState.error) ? theme.errorColor : submitted ? theme.submittedColor : Ansi.combine(Ansi.underlined, theme.primaryColor);\n switch (options.type) {\n case \"hidden\":\n {\n return \"\";\n }\n case \"password\":\n {\n return annotateSymbol(theme, theme.passwordMask.repeat(text.length), annotation);\n }\n case \"text\":\n {\n return Ansi.annotate(theme.colors, text, annotation);\n }\n }\n};\nconst renderTextError = (nextState, pointer, theme, renderOptions) => {\n if (Option.isSome(nextState.error)) {\n return Arr.match(nextState.error.value.split(NEWLINE_REGEXP), {\n onEmpty: () => \"\",\n onNonEmpty: errorLines => {\n if (renderOptions?.plain === true) {\n return separateSymbol(pointer, errorLines.join(\"\\n\"));\n }\n const prefix = annotateSymbol(theme, pointer, theme.errorColor);\n const lines = Arr.map(errorLines, str => annotateErrorLine(theme, str));\n return Ansi.cursorSavePosition + \"\\n\" + separateSymbol(prefix, lines.join(\"\\n\")) + Ansi.cursorRestorePosition;\n }\n });\n }\n return \"\";\n};\nconst renderTextOutput = (nextState, leadingSymbol, trailingSymbol, options, theme, renderOptions, submitted = false) => {\n const value = renderTextInput(nextState, options, theme, submitted, renderOptions);\n return renderPrompt(value, options.message, leadingSymbol, trailingSymbol, theme, renderOptions);\n};\nconst renderTextNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const promptMsg = renderTextOutput(state, leadingSymbol, trailingSymbol, options, figures);\n const errorMsg = renderTextError(state, figures.pointerSmall, figures);\n const cursorWidth = options.type === \"password\" ? figures.passwordMask.length : 1;\n const offset = (state.cursor - state.value.length) * cursorWidth;\n return promptMsg + errorMsg + Ansi.cursorMove(offset);\n});\nconst renderTextSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const promptMsg = renderTextOutput(state, leadingSymbol, trailingSymbol, options, figures, undefined, true);\n return promptMsg + \"\\n\";\n});\nconst processTextBackspace = state => {\n if (state.cursor <= 0) {\n return Effect.succeed(Action.Beep());\n }\n const beforeCursor = state.value.slice(0, state.cursor - 1);\n const afterCursor = state.value.slice(state.cursor);\n const cursor = state.cursor - 1;\n const value = `${beforeCursor}${afterCursor}`;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor,\n value,\n error: Option.none()\n }\n }));\n};\nconst processTextClear = state => Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor: 0,\n value: \"\",\n error: Option.none()\n }\n}));\nconst processTextCursorLeft = state => {\n if (state.cursor <= 0) {\n return Effect.succeed(Action.Beep());\n }\n const cursor = state.cursor - 1;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor,\n error: Option.none()\n }\n }));\n};\nconst processTextCursorRight = state => {\n if (state.cursor >= state.value.length) {\n return Effect.succeed(Action.Beep());\n }\n const cursor = Math.min(state.cursor + 1, state.value.length);\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor,\n error: Option.none()\n }\n }));\n};\nconst processTextCursorStart = state => Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor: 0,\n error: Option.none()\n }\n}));\nconst processTextCursorEnd = state => Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor: state.value.length,\n error: Option.none()\n }\n}));\nconst processTab = (state, options) => {\n if (state.value === options.default) {\n return Effect.succeed(Action.Beep());\n }\n const value = state.value.length === 0 ? options.default : state.value;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n value,\n cursor: value.length,\n error: Option.none()\n }\n }));\n};\nconst defaultTextProcessor = (input, state) => {\n const beforeCursor = state.value.slice(0, state.cursor);\n const afterCursor = state.value.slice(state.cursor);\n const value = `${beforeCursor}${input}${afterCursor}`;\n const cursor = state.cursor + input.length;\n return Effect.succeed(Action.NextFrame({\n state: {\n ...state,\n cursor,\n value,\n error: Option.none()\n }\n }));\n};\nconst handleTextRender = options => {\n return (state, action) => {\n return Action.$match(action, {\n Beep: () => Effect.succeed(renderBeep),\n NextFrame: ({\n state\n }) => renderTextNextFrame(state, options),\n Submit: () => renderTextSubmission(state, options)\n });\n };\n};\nconst handleTextProcess = options => {\n return (input, state) => {\n if (input.key.ctrl) {\n switch (input.key.name) {\n case \"u\":\n {\n return processTextClear(state);\n }\n case \"a\":\n {\n return processTextCursorStart(state);\n }\n case \"e\":\n {\n return processTextCursorEnd(state);\n }\n default:\n {\n return Effect.succeed(Action.Beep());\n }\n }\n }\n switch (input.key.name) {\n case \"backspace\":\n {\n return processTextBackspace(state);\n }\n case \"left\":\n {\n return processTextCursorLeft(state);\n }\n case \"right\":\n {\n return processTextCursorRight(state);\n }\n case \"home\":\n {\n return processTextCursorStart(state);\n }\n case \"end\":\n {\n return processTextCursorEnd(state);\n }\n case \"enter\":\n case \"return\":\n {\n const value = state.value;\n return Effect.match(options.validate(value), {\n onFailure: error => Action.NextFrame({\n state: {\n ...state,\n value,\n error: Option.some(error)\n }\n }),\n onSuccess: value => Action.Submit({\n value\n })\n });\n }\n case \"tab\":\n {\n return processTab(state, options);\n }\n default:\n {\n return defaultTextProcessor(Option.getOrElse(input.input, () => \"\"), state);\n }\n }\n };\n};\nconst handleTextClear = options => {\n return (state, _) => {\n return renderClearScreen(state, options);\n };\n};\nconst basePrompt = (options, type) => {\n const opts = {\n default: \"\",\n type,\n validate: Effect.succeed,\n ...options\n };\n const initialState = {\n cursor: opts.default.length,\n value: opts.default,\n error: Option.none()\n };\n return Custom(initialState, {\n render: handleTextRender(opts),\n process: handleTextProcess(opts),\n clear: handleTextClear(opts)\n });\n};\nconst handleToggleClear = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const terminal = yield* Terminal.Terminal;\n const columns = yield* terminal.columns;\n const figures = yield* getTheme(options);\n const clearPrompt = Ansi.eraseLine + Ansi.cursorLeft;\n const toggleText = options.active + \" \" + separateSymbol(figures.toggleSeparator, options.inactive);\n const promptText = renderPrompt(toggleText, options.message, figures.prefix, figures.pointerSmall, figures, {\n plain: true\n });\n const clearOutput = eraseText(promptText, columns);\n return clearOutput + clearPrompt;\n});\nconst renderToggle = (value, options, theme, submitted = false) => {\n const separator = annotateSymbol(theme, theme.toggleSeparator, theme.mutedColor);\n const selectedAnnotation = Ansi.combine(Ansi.underlined, submitted ? theme.submittedColor : theme.primaryColor);\n const inactive = value ? options.inactive : Ansi.annotate(theme.colors, options.inactive, selectedAnnotation);\n const active = value ? Ansi.annotate(theme.colors, options.active, selectedAnnotation) : options.active;\n return active + \" \" + separateSymbol(separator, inactive);\n};\nconst renderToggleNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.prefix, figures.primaryColor);\n const trailingSymbol = annotateSymbol(figures, figures.pointerSmall, figures.mutedColor);\n const toggle = renderToggle(state, options, figures);\n const promptMsg = renderPrompt(toggle, options.message, leadingSymbol, trailingSymbol, figures);\n return Ansi.cursorHide + promptMsg;\n});\nconst renderToggleSubmission = /*#__PURE__*/Effect.fnUntraced(function* (value, options) {\n const figures = yield* getTheme(options);\n const leadingSymbol = annotateSymbol(figures, figures.tick, figures.successColor);\n const trailingSymbol = annotateSymbol(figures, figures.ellipsis, figures.mutedColor);\n const toggle = renderToggle(value, options, figures, true);\n const promptMsg = renderPrompt(toggle, options.message, leadingSymbol, trailingSymbol, figures);\n return promptMsg + \"\\n\";\n});\nconst activate = /*#__PURE__*/Effect.succeed(/*#__PURE__*/Action.NextFrame({\n state: true\n}));\nconst deactivate = /*#__PURE__*/Effect.succeed(/*#__PURE__*/Action.NextFrame({\n state: false\n}));\nconst handleToggleRender = options => {\n return (state, action) => {\n switch (action._tag) {\n case \"Beep\":\n {\n return Effect.succeed(renderBeep);\n }\n case \"NextFrame\":\n {\n return renderToggleNextFrame(state, options);\n }\n case \"Submit\":\n {\n return renderToggleSubmission(state, options);\n }\n }\n };\n};\nconst handleToggleProcess = (input, state) => {\n switch (input.key.name) {\n case \"0\":\n case \"j\":\n case \"delete\":\n case \"right\":\n case \"down\":\n {\n return deactivate;\n }\n case \"1\":\n case \"k\":\n case \"left\":\n case \"up\":\n {\n return activate;\n }\n case \" \":\n case \"tab\":\n {\n return state ? deactivate : activate;\n }\n case \"enter\":\n case \"return\":\n {\n return Effect.succeed(Action.Submit({\n value: state\n }));\n }\n default:\n {\n return Effect.succeed(Action.Beep());\n }\n }\n};\nconst entriesToDisplay = (cursor, total, maxVisible) => {\n const max = maxVisible === undefined ? total : maxVisible;\n let startIndex = Math.min(total - max, cursor - Math.floor(max / 2));\n if (startIndex < 0) {\n startIndex = 0;\n }\n const endIndex = Math.min(startIndex + max, total);\n return {\n startIndex,\n endIndex\n };\n};\n//# sourceMappingURL=Prompt.js.map","/**\n * Defines the shared parameter model for CLI arguments and flags.\n *\n * A `Param<Kind, A>` describes how to consume parsed command-line input and\n * return a typed value. The `Kind` decides whether the parameter reads\n * positional arguments or named flags. `Argument` and `Flag` build on this\n * module to share parsing structure, primitive constructors, help metadata,\n * aliases, defaults, prompts, configuration fallbacks, validation, schema\n * decoding, fallback parameters, and traversal helpers.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Config from \"../Config.js\";\nimport * as Effect from \"../Effect.js\";\nimport { dual, identity } from \"../Function.js\";\nimport * as Option from \"../Option.js\";\nimport { pipeArguments } from \"../Pipeable.js\";\nimport * as Predicate from \"../Predicate.js\";\nimport * as Result from \"../Result.js\";\nimport * as Schema from \"../Schema.js\";\nimport * as CliError from \"./CliError.js\";\nimport * as Primitive from \"./Primitive.js\";\nimport * as Prompt from \"./Prompt.js\";\nconst TypeId = \"~effect/cli/Param\";\n/**\n * Defines the kind discriminator for positional argument parameters.\n *\n * **When to use**\n *\n * Use to build low-level `Param` constructors or type positions for positional\n * argument parameters.\n *\n * @see {@link flagKind} for the named flag parameter discriminator\n * @see {@link ParamKind} for the full parameter kind union\n *\n * @stability unstable\n * @category constants\n * @since 4.0.0\n */\nexport const argumentKind = \"argument\";\n/**\n * Defines the kind discriminator for flag parameters.\n *\n * **When to use**\n *\n * Use to build low-level `Param` constructors or type positions for named flag\n * parameters.\n *\n * @see {@link argumentKind} for the positional argument parameter discriminator\n *\n * @stability unstable\n * @category constants\n * @since 4.0.0\n */\nexport const flagKind = \"flag\";\nconst Proto = {\n [TypeId]: {\n _A: identity\n },\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\n/**\n * Type guard to check if a value is a Param.\n *\n * **Example** (Checking for params)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const maybeParam = Param.String(Param.flagKind, \"name\")\n *\n * Param.isParam(maybeParam) // => true\n * ```\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isParam = u => Predicate.hasProperty(u, TypeId);\n/**\n * Type guard to check if a param is a Single param (not composed).\n *\n * **Example** (Checking for single params)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const nameParam = Param.String(Param.flagKind, \"name\")\n * const optionalParam = Param.optional(nameParam)\n *\n * Param.isSingle(nameParam) // => true\n * Param.isSingle(optionalParam) // => false\n * ```\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isSingle = param => Predicate.isTagged(param, \"Single\");\n/**\n * Type guard to check if a Single param is a flag (not an argument).\n *\n * @internal\n */\nexport const isFlagParam = single => single.kind === \"flag\";\n/**\n * Constructs a leaf `Single` parameter from its kind, name, primitive parser,\n * and optional help metadata.\n *\n * **Details**\n *\n * The returned parser reads either one positional argument or the named flag,\n * depending on `kind`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeSingle = params => {\n const parse = args => params.kind === argumentKind ? parsePositional(params.name, params.primitiveType, args) : parseFlag(params.name, params.primitiveType, args);\n return Object.setPrototypeOf({\n _tag: \"Single\",\n ...params,\n description: params.description ?? Option.none(),\n aliases: params.aliases ?? [],\n hidden: params.hidden ?? false,\n parse\n }, Proto);\n};\n/**\n * Creates a string parameter.\n *\n * **Example** (Creating string parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Create a string flag\n * const nameFlag = Param.String(Param.flagKind, \"name\")\n *\n * // Create a string argument\n * const fileArg = Param.String(Param.argumentKind, \"file\")\n *\n * // Usage in CLI: --name \"John Doe\" or as positional argument\n * const kinds = [nameFlag.kind, fileArg.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const String = (kind, name) => makeSingle({\n name,\n primitiveType: Primitive.String,\n kind\n});\n/**\n * Creates a boolean parameter.\n *\n * **Example** (Creating boolean parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Create a boolean flag\n * const verboseFlag = Param.Boolean(Param.flagKind, \"verbose\")\n *\n * // Create a boolean argument\n * const enableArg = Param.Boolean(Param.argumentKind, \"enable\")\n *\n * // Usage in CLI: --verbose (true) or --no-verbose (false).\n * // The flag is required unless made optional or given a fallback.\n * // Boolean positional arguments accept true/false.\n * const kinds = [verboseFlag.kind, enableArg.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Boolean = (kind, name) => makeSingle({\n name,\n primitiveType: Primitive.Boolean,\n kind\n});\n/**\n * Creates an integer parameter.\n *\n * **Example** (Creating integer parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Create an integer flag\n * const portFlag = Param.Int(Param.flagKind, \"port\")\n *\n * // Create an integer argument\n * const countArg = Param.Int(Param.argumentKind, \"count\")\n *\n * // Usage in CLI: --port 8080 or as positional argument: 42\n * const kinds = [portFlag.kind, countArg.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Int = (kind, name) => makeSingle({\n name,\n primitiveType: Primitive.Int,\n kind\n});\n/**\n * Creates a finite number parameter.\n *\n * **Example** (Creating finite number parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const rateFlag = Param.Finite(Param.flagKind, \"rate\")\n *\n * const thresholdArg = Param.Finite(Param.argumentKind, \"threshold\")\n *\n * const kinds = [rateFlag.kind, thresholdArg.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Finite = (kind, name) => makeSingle({\n name,\n primitiveType: Primitive.Finite,\n kind\n});\n/**\n * Creates a date parameter that parses ISO date strings.\n *\n * **Example** (Creating date parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Create a date flag\n * const startFlag = Param.Date(Param.flagKind, \"start-date\")\n *\n * // Create a date argument\n * const dueDateArg = Param.Date(Param.argumentKind, \"due-date\")\n *\n * // Usage in CLI: --start-date \"2023-12-25\" or as positional: \"2023-01-01\"\n * // Parses to JavaScript Date object\n * const kinds = [startFlag.kind, dueDateArg.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Date = (kind, name) => makeSingle({\n name,\n primitiveType: Primitive.Date,\n kind\n});\n/**\n * Constructs command-line params that represent a choice between several\n * inputs. The input will be mapped to it's associated value during parsing.\n *\n * **Example** (Creating valued choices)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * type Animal = Dog | Cat\n *\n * interface Dog {\n * readonly _tag: \"Dog\"\n * }\n *\n * interface Cat {\n * readonly _tag: \"Cat\"\n * }\n *\n * const animal = Param.ChoiceWithValue(Param.flagKind, \"animal\", [\n * [\"dog\", { _tag: \"Dog\" }],\n * [\"cat\", { _tag: \"Cat\" }]\n * ])\n * animal.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const ChoiceWithValue = (kind, name, choices) => makeSingle({\n name,\n primitiveType: Primitive.Choice(choices),\n kind\n});\n/**\n * Constructs command-line params that represent a choice between several\n * string inputs.\n *\n * **Example** (Creating string choices)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const logLevel = Param.Literals(Param.flagKind, \"log-level\", [\n * \"debug\",\n * \"info\",\n * \"warn\",\n * \"error\"\n * ])\n * logLevel.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Literals = (kind, name, choices) => {\n const mappedChoices = choices.map(value => [value, value]);\n return ChoiceWithValue(kind, name, mappedChoices);\n};\n/**\n * Creates a path parameter that accepts file or directory paths.\n *\n * **Example** (Creating path parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Basic path parameter\n * const outputPath = Param.Path(Param.flagKind, \"output\")\n *\n * // Path that must exist\n * const inputPath = Param.Path(Param.flagKind, \"input\", { mustExist: true })\n *\n * // File-only path\n * const configFile = Param.Path(Param.flagKind, \"config\", {\n * pathType: \"file\",\n * mustExist: true,\n * typeName: \"config-file\"\n * })\n * const kinds = [outputPath.kind, inputPath.kind, configFile.kind] // => [\"flag\", \"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Path = (kind, name, options) => makeSingle({\n name,\n kind,\n primitiveType: Primitive.Path(options?.pathType ?? \"either\", options?.mustExist),\n typeName: options?.typeName\n});\n/**\n * Creates a directory path parameter.\n *\n * **Details**\n *\n * This is a convenience function that creates a path parameter with the\n * `pathType` set to `\"directory\"` and a default type name of `\"directory\"`.\n *\n * **Example** (Creating directory parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Basic directory parameter\n * const outputDir = Param.Directory(Param.flagKind, \"output-dir\")\n *\n * // Directory that must exist\n * const sourceDir = Param.Directory(Param.flagKind, \"source\", { mustExist: true })\n *\n * // Usage: --output-dir /path/to/dir --source /existing/dir\n * const kinds = [outputDir.kind, sourceDir.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Directory = (kind, name, options) => Path(kind, name, {\n pathType: \"directory\",\n typeName: \"directory\",\n mustExist: options?.mustExist\n});\n/**\n * Creates a file path parameter.\n *\n * **Details**\n *\n * This is a convenience function that creates a path parameter with a\n * `pathType` set to `\"file\"` and a default type name of `\"file\"`.\n *\n * **Example** (Creating file parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Basic file parameter\n * const outputFile = Param.File(Param.flagKind, \"output\")\n *\n * // File that must exist\n * const inputFile = Param.File(Param.flagKind, \"input\", { mustExist: true })\n *\n * // Usage: --output result.txt --input existing-file.txt\n * const kinds = [outputFile.kind, inputFile.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const File = (kind, name, options) => Path(kind, name, {\n pathType: \"file\",\n typeName: \"file\",\n mustExist: options?.mustExist\n});\n/**\n * Creates a redacted parameter for sensitive data like passwords.\n * The value is masked in help output and logging.\n *\n * **Example** (Creating redacted parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Create a password parameter\n * const password = Param.Redacted(Param.flagKind, \"password\")\n *\n * // Create an API key argument\n * const apiKey = Param.Redacted(Param.argumentKind, \"api-key\")\n *\n * // Usage: --password (value will be hidden in help/logs)\n * const kinds = [password.kind, apiKey.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Redacted = (kind, name) => makeSingle({\n name,\n primitiveType: Primitive.Redacted,\n kind\n});\n/**\n * Creates a parameter that reads and returns file content as a string.\n *\n * **Example** (Reading file text)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Read a config file as string\n * const configContent = Param.FileText(Param.flagKind, \"config\")\n *\n * // Read a template file as argument\n * const templateContent = Param.FileText(Param.argumentKind, \"template\")\n *\n * // Usage: --config config.txt (reads file content into string)\n * const kinds = [configContent.kind, templateContent.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileText = (kind, name) => makeSingle({\n name,\n primitiveType: Primitive.FileText,\n kind\n});\n/**\n * Creates a param that reads and parses the content of the specified file.\n *\n * **Details**\n *\n * The parser that is utilized will depend on the specified `format`, or the\n * extension of the file passed on the command-line if no `format` is specified.\n *\n * **Example** (Parsing file contents)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Will use the extension of the file passed on the command line to determine\n * // the parser to use\n * const config = Param.FileParse(Param.flagKind, \"config\")\n *\n * // Will use the JSON parser\n * const jsonConfig = Param.FileParse(Param.flagKind, \"json-config\", {\n * format: \"json\"\n * })\n * const kinds = [config.kind, jsonConfig.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileParse = (kind, name, options) => makeSingle({\n name,\n primitiveType: Primitive.FileParse(options),\n kind\n});\n/**\n * Creates a parameter that reads and validates file content using a schema.\n *\n * **Example** (Validating file contents)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Param } from \"effect/cli\"\n * // Parse JSON config file\n * const configSchema = Schema.Struct({\n * port: Schema.Number,\n * host: Schema.String\n * })\n *\n * const config = Param.FileSchema(Param.flagKind, \"config\", configSchema, {\n * format: \"json\"\n * })\n *\n * // Parse YAML file\n * const yamlConfig = Param.FileSchema(Param.flagKind, \"config\", configSchema, {\n * format: \"yaml\"\n * })\n *\n * // Usage: --config config.json (reads and validates file content)\n * const kinds = [config.kind, yamlConfig.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileSchema = (kind, name, schema, options) => makeSingle({\n name,\n primitiveType: Primitive.FileSchema(schema, options),\n kind\n});\n/**\n * Creates a param that parses key=value pairs.\n *\n * **When to use**\n *\n * Use when you need command-line options or arguments that collect `key=value`\n * configuration entries.\n *\n * **Details**\n *\n * Requires at least one key=value pair. The parsed pairs are merged into a\n * single record object.\n *\n * **Example** (Parsing key-value pairs)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const env = Param.KeyValuePair(Param.flagKind, \"env\")\n * // --env FOO=bar --env BAZ=qux will parse to { FOO: \"bar\", BAZ: \"qux\" }\n *\n * const props = Param.KeyValuePair(Param.flagKind, \"property\")\n * // --property name=value --property debug=true\n * const kinds = [env.kind, props.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const KeyValuePair = (kind, name) => map(variadic(makeSingle({\n name,\n primitiveType: Primitive.KeyValuePair,\n kind\n}), {\n min: 1\n}), objects => Object.fromEntries(objects.flatMap(Object.entries)));\n/**\n * A parameter that always fails to parse.\n *\n * **Example** (Creating sentinel parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const disabledDebugParam = Param.Never(Param.flagKind)\n *\n * const makeDebugParam = (enableDebug: boolean) =>\n * enableDebug ? Param.String(Param.flagKind, \"debug\") : disabledDebugParam\n *\n * makeDebugParam(true) === disabledDebugParam // => false\n * makeDebugParam(false) === disabledDebugParam // => true\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Never = kind => makeSingle({\n name: \"__never__\",\n primitiveType: Primitive.Never,\n kind\n});\nconst FLAG_DASH_REGEXP = /^-+/;\n/**\n * Adds an alias to an option.\n *\n * **When to use**\n *\n * Use when you need a CLI parameter to accept an alternate name, such as \"-f\"\n * for \"--force\".\n *\n * **Details**\n *\n * This works on any param structure by recursively finding the underlying\n * `Single` node and applying the alias there.\n *\n * **Example** (Adding parameter aliases)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const force = Param.Boolean(Param.flagKind, \"force\").pipe(\n * Param.withAlias(\"-f\"),\n * Param.withAlias(\"-F\")\n * )\n *\n * // Also works on composed params:\n * const count = Param.Int(Param.flagKind, \"count\").pipe(\n * Param.optional,\n * Param.withAlias(\"-c\") // finds the underlying Single and adds alias\n * )\n * const kinds = [force.kind, count.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withAlias = /*#__PURE__*/dual(2, (self, alias) => {\n return transformSingle(self, single => makeSingle({\n ...single,\n aliases: [...single.aliases, alias.replace(FLAG_DASH_REGEXP, \"\")]\n }));\n});\n/**\n * Adds a description to an option for help text.\n *\n * **Details**\n *\n * Descriptions provide users with information about what the option does\n * when they view help documentation.\n *\n * **Example** (Adding help descriptions)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const verbose = Param.Boolean(Param.flagKind, \"verbose\").pipe(\n * Param.withAlias(\"-v\"),\n * Param.withDescription(\"Enable verbose output\")\n * )\n * verbose.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withDescription = /*#__PURE__*/dual(2, (self, description) => {\n return transformSingle(self, single => makeSingle({\n ...single,\n description: Option.some(description)\n }));\n});\n/**\n * Hides a parameter from generated help output and completions while keeping\n * it parseable on the command line.\n *\n * **When to use**\n *\n * Use when experimental, internal, or deprecated flags should be accepted but\n * not advertised.\n *\n * **Example** (Hiding a flag from help)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const experimental = Param.Boolean(Param.flagKind, \"experimental-foo\").pipe(\n * Param.withHidden\n * )\n * experimental.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category metadata\n * @since 4.0.0\n */\nexport const withHidden = self => transformSingle(self, single => makeSingle({\n ...single,\n hidden: true\n}));\n/**\n * Transforms the parsed value of an option using a mapping function.\n *\n * **Example** (Mapping parsed values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const port = Param.Int(Param.flagKind, \"port\").pipe(\n * Param.map((n) => ({ port: n, url: `http://localhost:${n}` }))\n * )\n * port.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => {\n const parse = args => Effect.map(self.parse(args), ([operands, value]) => [operands, f(value)]);\n return Object.assign(Object.create(Proto), {\n _tag: \"Map\",\n kind: self.kind,\n param: self,\n f,\n parse\n });\n});\nconst transform = (self, f, alternatives = []) => {\n const alternativeParsers = alternatives.map(alternative => () => alternative().parse);\n return Object.assign(Object.create(Proto), {\n _tag: \"Transform\",\n kind: self.kind,\n param: self,\n alternatives,\n f,\n parse: f(self.parse, alternativeParsers)\n });\n};\n/**\n * Transforms the parsed value of an option using an effectful mapping function.\n *\n * **Example** (Mapping parsed values effectfully)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { CliError, Param } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const validatedEmail = Param.String(Param.flagKind, \"email\").pipe(\n * Param.mapEffect((email) =>\n * email.includes(\"@\")\n * ? Effect.succeed(email)\n * : Effect.fail(\n * new CliError.InvalidValue({\n * option: \"email\",\n * value: email,\n * expected: \"valid email format\",\n * kind: \"flag\"\n * })\n * )\n * )\n * )\n *\n * const [, value] = await Effect.runPromise(\n * validatedEmail.parse({\n * arguments: [],\n * flags: { email: [\"alice@example.com\"] }\n * }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => \"alice@example.com\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const mapEffect = /*#__PURE__*/dual(2, (self, f) => transform(self, parse => args => Effect.flatMap(parse(args), ([leftover, a]) => f(a).pipe(Effect.map(b => [leftover, b])))));\n/**\n * Transforms the parsed value of an option using a function that may throw,\n * converting any thrown errors into failure messages.\n *\n * **Example** (Mapping thrown errors)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Param } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const parsedJson = Param.String(Param.flagKind, \"config\").pipe(\n * Param.mapTryCatch(\n * (str) => JSON.parse(str),\n * (error) =>\n * `Invalid JSON: ${error instanceof Error ? error.message : String(error)}`\n * )\n * )\n *\n * const [, value] = await Effect.runPromise(\n * parsedJson.parse({\n * arguments: [],\n * flags: { config: ['{\"enabled\":true}'] }\n * }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => { enabled: true }\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const mapTryCatch = /*#__PURE__*/dual(3, (self, f, onError) => {\n const single = getUnderlyingSingleOrThrow(self);\n return transform(self, parse => args => Effect.flatMap(parse(args), ([leftover, a]) => Effect.try({\n try: () => f(a),\n catch: error => onError(error)\n }).pipe(Effect.mapError(error => new CliError.InvalidValue({\n option: single.name,\n value: globalThis.String(a),\n expected: error,\n kind: single.kind\n })), Effect.map(b => [leftover, b]))));\n});\n/**\n * Makes a flag or positional argument optional.\n *\n * **Details**\n *\n * When the parameter is absent, parsing succeeds with `Option.none()` instead\n * of failing with a missing option or missing argument error. When present, the\n * parsed value is wrapped in `Option.some()`.\n *\n * **Example** (Making parameters optional)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Create an optional port option\n * // - When not provided: returns Option.none()\n * // - When provided: returns Option.some(parsedValue)\n * const port = Param.optional(Param.Int(Param.flagKind, \"port\"))\n * port.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const optional = param => {\n const parse = args => param.parse(args).pipe(Effect.map(([leftover, value]) => [leftover, Option.some(value)]),\n // Catch both MissingOption (for flags) and MissingArgument (for positional arguments)\n Effect.catchTags({\n MissingOption: () => Effect.succeed([args.arguments, Option.none()]),\n MissingArgument: () => Effect.succeed([args.arguments, Option.none()])\n }));\n return Object.assign(Object.create(Proto), {\n _tag: \"Optional\",\n kind: param.kind,\n param,\n parse\n });\n};\n/**\n * Makes a flag or positional argument optional by supplying a fallback value.\n *\n * **Details**\n *\n * The fallback may be a pure value or an effect. It is used only when the\n * parameter is absent; provided values are parsed normally.\n *\n * **Example** (Providing default values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Using the pipe operator to make an option optional\n * const port = Param.Int(Param.flagKind, \"port\").pipe(\n * Param.withDefault(8080)\n * )\n *\n * // Can also be used with other combinators\n * const verbose = Param.Boolean(Param.flagKind, \"verbose\").pipe(\n * Param.withAlias(\"-v\"),\n * Param.withDescription(\"Enable verbose output\"),\n * Param.withDefault(false)\n * )\n * const kinds = [port.kind, verbose.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withDefault = /*#__PURE__*/dual(2, (self, defaultValue) => {\n if (!Effect.isEffect(defaultValue)) {\n return map(optional(self), Option.getOrElse(() => defaultValue));\n }\n return mapEffect(optional(self), Option.match({\n onNone: () => defaultValue,\n onSome: Effect.succeed\n }));\n});\n/**\n * Adds a fallback config that is loaded when a required parameter is missing.\n *\n * **When to use**\n *\n * Use when you need config to provide a fallback source for required flags or\n * arguments that are absent from CLI input.\n *\n * **Details**\n *\n * Provided CLI values win. Config is loaded only after a missing option or\n * missing argument error.\n *\n * **Gotchas**\n *\n * Missing config preserves the original missing-parameter error. Config parse\n * failure becomes `CliError.InvalidValue`.\n *\n * @see {@link withDefault} for a pure default value\n * @see {@link withFallbackPrompt} for prompting interactively when input is missing\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackConfig = /*#__PURE__*/dual(2, (self, config) => {\n const toInvalidValue = (error, configError) => new CliError.InvalidValue({\n option: error._tag === \"MissingOption\" ? error.option : error.argument,\n value: \"config\",\n expected: configError.message,\n kind: error._tag === \"MissingOption\" ? \"flag\" : \"argument\"\n });\n const runConfig = (error, args) => Config.option(config).pipe(Effect.mapError(configError => toInvalidValue(error, configError)), Effect.flatMap(Option.match({\n onNone: () => Effect.fail(error),\n onSome: value => Effect.succeed([args.arguments, value])\n })));\n return transform(self, parse => args => parse(args).pipe(Effect.catchTag([\"MissingOption\", \"MissingArgument\"], error => runConfig(error, args))));\n});\n/**\n * Adds a fallback prompt that is shown when a required parameter is missing.\n *\n * **When to use**\n *\n * Use when a CLI should ask interactively for a missing required flag or\n * argument.\n *\n * **Details**\n *\n * `FallbackPrompt` accepts either a `Prompt` or an effect that builds one.\n * Effectful prompt creation is lazy and runs only when the fallback is needed.\n *\n * **Gotchas**\n *\n * This only handles missing options and missing arguments. Invalid values do not\n * prompt, and prompt cancellation re-fails with the original missing error.\n *\n * @see {@link FallbackPrompt} for accepted fallback prompt forms\n * @see {@link withFallbackConfig} for loading a fallback from config\n * @see {@link withDefault} for a pure default value\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackPrompt = /*#__PURE__*/dual(2, (self, prompt) => {\n const runPrompt = (error, args) => Effect.flatMap(Prompt.isPrompt(prompt) ? Effect.succeed(prompt) : prompt, Prompt.run).pipe(Effect.map(value => [args.arguments, value]), Effect.catchTag(\"QuitError\", () => Effect.fail(error)));\n return transform(self, parse => args => parse(args).pipe(Effect.catchTag([\"MissingOption\", \"MissingArgument\"], error => runPrompt(error, args))));\n});\n/**\n * Creates a variadic parameter that can be specified multiple times.\n *\n * **Details**\n *\n * This is the base combinator for creating parameters that accept multiple values.\n * The `min` and `max` parameters are optional. When they are not provided, the\n * parameter can be specified any number of times, from 0 to infinity.\n *\n * **Example** (Accepting multiple values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Basic variadic parameter (0 to infinity)\n * const tags = Param.variadic(Param.String(Param.flagKind, \"tag\"))\n *\n * // Variadic with minimum count\n * const inputs = Param.variadic(\n * Param.String(Param.flagKind, \"input\"),\n * { min: 1 } // at least 1 required\n * )\n *\n * // Variadic with both min and max\n * const limited = Param.variadic(Param.String(Param.flagKind, \"item\"), {\n * min: 2, // at least 2 times\n * max: 2 // at most 2 times\n * })\n * const kinds = [tags.kind, inputs.kind, limited.kind] // => [\"flag\", \"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const variadic = (self, options) => {\n const single = getUnderlyingSingleOrThrow(self);\n const parse = args => {\n if (single.kind === \"argument\") {\n return parsePositionalVariadic(self, single, args, options);\n } else {\n return parseOptionVariadic(self, single, args, options);\n }\n };\n return Object.assign(Object.create(Proto), {\n _tag: \"Variadic\",\n kind: self.kind,\n param: self,\n min: Option.fromUndefinedOr(options?.min),\n max: Option.fromUndefinedOr(options?.max),\n parse\n });\n};\n/**\n * Wraps an option to allow it to be specified multiple times within a range.\n *\n * **Details**\n *\n * This combinator transforms an option to accept between `min` and `max`\n * occurrences on the command line, returning an array of all provided values.\n *\n * **Example** (Bounding repeated values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Allow 1-3 file inputs\n * const files = Param.String(Param.flagKind, \"file\").pipe(\n * Param.between(1, 3),\n * Param.withAlias(\"-f\")\n * )\n *\n * // Parse: --file a.txt --file b.txt\n * // Result: [\"a.txt\", \"b.txt\"]\n *\n * // Allow 0 or more tags\n * const tags = Param.String(Param.flagKind, \"tag\").pipe(\n * Param.between(0, Number.MAX_SAFE_INTEGER)\n * )\n *\n * // Parse: --tag dev --tag staging --tag v1.0\n * // Result: [\"dev\", \"staging\", \"v1.0\"]\n * const kinds = [files.kind, tags.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const between = /*#__PURE__*/dual(3, (self, min, max) => {\n if (min < 0) {\n throw new Error(\"between: min must be non-negative\");\n }\n if (max < min) {\n throw new Error(\"between: max must be greater than or equal to min\");\n }\n return variadic(self, {\n min,\n max\n });\n});\n/**\n * Wraps an option to allow it to be specified at most `max` times.\n *\n * **Details**\n *\n * This combinator transforms an option to accept between 0 and `max`\n * occurrences on the command line, returning an array of all provided values.\n *\n * **Example** (Limiting repeated values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Allow at most 3 warning suppressions\n * const suppressions = Param.String(Param.flagKind, \"suppress\").pipe(\n * Param.atMost(3)\n * )\n *\n * // Parse: --suppress warning1 --suppress warning2\n * // Result: [\"warning1\", \"warning2\"]\n * suppressions.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const atMost = /*#__PURE__*/dual(2, (self, max) => {\n if (max < 0) {\n throw new Error(\"atMost: max must be non-negative\");\n }\n return variadic(self, {\n max\n });\n});\n/**\n * Wraps an option to require it to be specified at least `min` times.\n *\n * **Details**\n *\n * This combinator transforms an option to accept at least `min`\n * occurrences on the command line, returning an array of all provided values.\n *\n * **Example** (Requiring repeated values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * // Require at least 2 input files\n * const inputs = Param.String(Param.flagKind, \"input\").pipe(\n * Param.atLeast(2),\n * Param.withAlias(\"-i\")\n * )\n *\n * // Parse: --input file1.txt --input file2.txt --input file3.txt\n * // Result: [\"file1.txt\", \"file2.txt\", \"file3.txt\"]\n * inputs.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const atLeast = /*#__PURE__*/dual(2, (self, min) => {\n if (min < 0) {\n throw new Error(\"atLeast: min must be non-negative\");\n }\n return variadic(self, {\n min\n });\n});\n/**\n * Filters and transforms parsed values, failing with a custom error message\n * if the filter function returns `Option.none()`.\n *\n * **When to use**\n *\n * Use when you need validation and transformation in a single parameter\n * combinator.\n *\n * **Example** (Filtering and transforming values)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n * import { Param } from \"effect/cli\"\n * const positiveInt = Param.Int(Param.flagKind, \"count\").pipe(\n * Param.filterMap(\n * (n) => n > 0 ? Option.some(n) : Option.none(),\n * (n) => `Expected positive integer, got ${n}`\n * )\n * )\n * positiveInt.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(3, (self, filter, onNone) => mapEffect(self, Effect.fnUntraced(function* (a) {\n const result = filter(a);\n if (Option.isSome(result)) {\n return result.value;\n }\n const single = getUnderlyingSingleOrThrow(self);\n return yield* new CliError.InvalidValue({\n option: single.name,\n value: globalThis.String(a),\n expected: onNone(a),\n kind: single.kind\n });\n})));\n/**\n * Filters parsed values, failing with a custom error message if the predicate returns false.\n *\n * **Example** (Filtering parsed values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const evenNumber = Param.Int(Param.flagKind, \"num\").pipe(\n * Param.filter(\n * (n) => n % 2 === 0,\n * (n) => `Expected even number, got ${n}`\n * )\n * )\n * evenNumber.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const filter = /*#__PURE__*/dual(3, (self, predicate, onFalse) => filterMap(self, Option.liftPredicate(predicate), onFalse));\n/**\n * Sets a custom metavar (placeholder name) for the param in help documentation.\n *\n * **Details**\n *\n * The metavar is displayed in usage text to indicate what value the user should provide.\n * For example, `--output FILE` shows `FILE` as the metavar.\n *\n * **Example** (Setting metavars)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const port = Param.Int(Param.flagKind, \"port\").pipe(\n * Param.withMetavar(\"PORT\"),\n * Param.filter(\n * (p) => p >= 1 && p <= 65535,\n * () => \"Port must be between 1 and 65535\"\n * )\n * )\n * port.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category metadata\n * @since 4.0.0\n */\nexport const withMetavar = /*#__PURE__*/dual(2, (self, metavar) => transformSingle(self, single => makeSingle({\n ...single,\n typeName: metavar\n})));\n/**\n * Lets a flag be given without a value, in which case `value` is used.\n *\n * **Details**\n *\n * Follows GNU-style optional values. An explicit value must be attached with\n * `=` (`--watch=until-done`), and a bare `--watch` is parsed as\n * `--watch=<value>`. The flag never consumes the next token. It is still\n * required unless it is made optional or given a default.\n *\n * **Example** (Flag with an optional value)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const watch = Param.String(Param.flagKind, \"watch\").pipe(\n * Param.withOptionalValue(\"first-failure\"),\n * Param.optional\n * )\n * watch.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.1.0\n */\nexport const withOptionalValue = /*#__PURE__*/dual(2, (self, value) => transformSingle(self, single => makeSingle({\n ...single,\n optionalValue: value\n})));\n/**\n * Validates parsed values against a Schema, providing detailed error messages.\n *\n * **Example** (Validating with schemas)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Param } from \"effect/cli\"\n * const isEmail = Schema.isPattern(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/)\n *\n * const Email = Schema.String.pipe(\n * Schema.check(isEmail)\n * )\n *\n * const email = Param.String(Param.flagKind, \"email\").pipe(\n * Param.withSchema(Email)\n * )\n * email.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withSchema = /*#__PURE__*/dual(2, (self, schema) => {\n const decodeParam = Schema.decodeUnknownEffect(schema);\n return mapEffect(self, value => Effect.mapError(decodeParam(value), error => {\n const single = getUnderlyingSingleOrThrow(self);\n return new CliError.InvalidValue({\n option: single.name,\n value: globalThis.String(value),\n expected: `Schema validation failed: ${error.message}`,\n kind: single.kind\n });\n }));\n});\n/**\n * Provides a fallback param to use if this param fails to parse.\n *\n * **Example** (Falling back to another parameter)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const config = Param.File(Param.flagKind, \"config\").pipe(\n * Param.orElse(() => Param.String(Param.flagKind, \"config-url\"))\n * )\n * config.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const orElse = /*#__PURE__*/dual(2, (self, orElse) => transform(self, (parse, alternatives) => args => Effect.catch(parse(args), () => alternatives[0]()(args)), [orElse]));\n/**\n * Provides a fallback param and returns a `Result` indicating which param\n * succeeded.\n *\n * **Details**\n *\n * The original param's value is returned as `Result.succeed`, while the\n * fallback param's value is returned as `Result.fail`.\n *\n * **Example** (Returning fallback results)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/cli\"\n *\n * const configSource = Param.File(Param.flagKind, \"config\").pipe(\n * Param.orElseResult(() => Param.String(Param.flagKind, \"config-url\"))\n * )\n * // Returns Result<string, string>\n * configSource.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const orElseResult = /*#__PURE__*/dual(2, (self, orElse) => {\n return transform(self, (parse, alternatives) => args => Effect.catch(Effect.map(parse(args), ([leftover, value]) => [leftover, Result.succeed(value)]), () => Effect.map(alternatives[0]()(args), ([leftover, value]) => [leftover, Result.fail(value)])), [orElse]);\n});\n// =============================================================================\n// Parsing Utilities\n// =============================================================================\nconst parsePositional = /*#__PURE__*/Effect.fnUntraced(function* (name, primitiveType, args) {\n if (args.arguments.length === 0) {\n return yield* new CliError.MissingArgument({\n argument: name\n });\n }\n const arg = args.arguments[0];\n const value = yield* Effect.mapError(primitiveType.parse(arg), error => new CliError.InvalidValue({\n option: name,\n value: arg,\n expected: error,\n kind: \"argument\"\n }));\n return [args.arguments.slice(1), value];\n});\nconst parseFlag = /*#__PURE__*/Effect.fnUntraced(function* (name, primitiveType, args) {\n const providedValues = args.flags[name];\n if (providedValues === undefined || providedValues.length === 0) {\n return yield* new CliError.MissingOption({\n option: name\n });\n }\n // Parse the first value (later we can handle multiple)\n const arg = providedValues[0];\n const value = yield* Effect.mapError(primitiveType.parse(arg), error => new CliError.InvalidValue({\n option: name,\n value: arg,\n expected: error,\n kind: \"flag\"\n }));\n return [args.arguments, value];\n});\nconst parsePositionalVariadic = /*#__PURE__*/Effect.fnUntraced(function* (self, single, args, options) {\n const results = [];\n const minValue = options?.min ?? 0;\n const maxValue = options?.max ?? Number.POSITIVE_INFINITY;\n let count = 0;\n let currentArgs = args.arguments;\n while (currentArgs.length > 0 && count < maxValue) {\n const [remainingArgs, value] = yield* self.parse({\n flags: args.flags,\n arguments: currentArgs\n });\n results.push(value);\n currentArgs = remainingArgs;\n count++;\n }\n if (count < minValue) {\n return yield* count === 0 ? new CliError.MissingArgument({\n argument: single.name\n }) : new CliError.InvalidValue({\n option: single.name,\n value: `${count} values`,\n expected: `at least ${minValue} value${minValue === 1 ? \"\" : \"s\"}`,\n kind: single.kind\n });\n }\n return [currentArgs, results];\n});\nconst parseOptionVariadic = /*#__PURE__*/Effect.fnUntraced(function* (self, single, args, options) {\n const results = [];\n const names = [single.name, ...single.aliases];\n const values = names.flatMap(name => args.flags[name] ?? []);\n const count = values.length;\n // Validate count constraints\n if (Predicate.isNotUndefined(options?.min) && count < options.min) {\n return yield* count === 0 ? new CliError.MissingOption({\n option: single.name\n }) : new CliError.InvalidValue({\n option: single.name,\n value: `${count} occurrences`,\n expected: `at least ${options.min} value${options.min === 1 ? \"\" : \"s\"}`,\n kind: single.kind\n });\n }\n if (Predicate.isNotUndefined(options?.max) && count > options.max) {\n return yield* new CliError.InvalidValue({\n option: single.name,\n value: `${count} occurrences`,\n expected: `at most ${options.max} value${options.max === 1 ? \"\" : \"s\"}`,\n kind: single.kind\n });\n }\n // Parse each value individually\n for (const value of values) {\n const [, parsedValue] = yield* self.parse({\n flags: {\n [single.name]: [value]\n },\n arguments: []\n });\n results.push(parsedValue);\n }\n return [args.arguments, results];\n});\n/**\n * Type-safe param matcher that handles the unsafe casting internally.\n * This provides a clean API for pattern matching on param types while\n * maintaining type safety at the call site.\n */\nconst matchParam = (param, patterns) => {\n const p = param;\n switch (p._tag) {\n case \"Single\":\n return patterns.Single(p);\n case \"Map\":\n return patterns.Map(p);\n case \"Transform\":\n return patterns.Transform(p);\n case \"Optional\":\n return patterns.Optional(p);\n case \"Variadic\":\n return patterns.Variadic(p);\n }\n};\n/**\n * Recursively transforms a param by applying a function to any `Single` nodes.\n * This is used internally by combinators like `withAlias` to traverse the param tree.\n */\nconst transformSingle = (param, f) => {\n return matchParam(param, {\n Single: single => f(single),\n Map: mapped => map(transformSingle(mapped.param, f), mapped.f),\n Transform: mapped => transform(transformSingle(mapped.param, f), mapped.f, mapped.alternatives.map(alternative => () => transformSingle(alternative(), f))),\n Optional: p => optional(transformSingle(p.param, f)),\n Variadic: p => variadic(transformSingle(p.param, f), {\n min: Option.getOrUndefined(p.min),\n max: Option.getOrUndefined(p.max)\n })\n });\n};\n/**\n * Extracts all Single params from a potentially nested param structure.\n * This handles all param combinators including Map, Transform, Optional, and Variadic.\n *\n * @internal\n */\nexport const extractSingleParams = param => {\n return matchParam(param, {\n Single: single => [single],\n Map: mapped => extractSingleParams(mapped.param),\n Transform: mapped => [...extractSingleParams(mapped.param), ...mapped.alternatives.flatMap(alternative => extractSingleParams(alternative()))],\n Optional: optional => extractSingleParams(optional.param),\n Variadic: variadic => extractSingleParams(variadic.param)\n });\n};\n/**\n * Gets the underlying Single param from a potentially nested param structure.\n * Throws an error if there are no singles or multiple singles found.\n *\n * @internal\n */\nexport const getUnderlyingSingleOrThrow = param => {\n const singles = extractSingleParams(param);\n if (singles.length === 0) {\n throw new Error(\"No Single param found in param structure\");\n }\n if (singles.length > 1) {\n throw new Error(`Multiple Single params found: ${singles.map(s => s.name).join(\", \")}`);\n }\n return singles[0];\n};\n/**\n * Gets param metadata by traversing the structure.\n *\n * @internal\n */\nexport const getParamMetadata = param => {\n return matchParam(param, {\n Single: () => ({\n isOptional: false,\n isVariadic: false,\n variadicMin: Option.none(),\n variadicMax: Option.none()\n }),\n Map: mapped => getParamMetadata(mapped.param),\n Transform: mapped => getParamMetadata(mapped.param),\n Optional: optional => ({\n ...getParamMetadata(optional.param),\n isOptional: true\n }),\n Variadic: variadic => ({\n ...getParamMetadata(variadic.param),\n isVariadic: true,\n variadicMin: variadic.min,\n variadicMax: variadic.max\n })\n });\n};\n//# sourceMappingURL=Param.js.map","import { dual } from \"../Function.js\";\nimport * as Param from \"./Param.js\";\n// -------------------------------------------------------------------------------------\n// constructors\n// -------------------------------------------------------------------------------------\n/**\n * Creates a positional string argument.\n *\n * **Example** (Creating a string argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const filename = Argument.String(\"filename\")\n * filename.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const String = name => Param.String(Param.argumentKind, name);\n/**\n * Creates a positional integer argument.\n *\n * **Example** (Creating an integer argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const count = Argument.Int(\"count\")\n * count.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Int = name => Param.Int(Param.argumentKind, name);\n/**\n * Creates a positional file path argument.\n *\n * **Example** (Creating file path arguments)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const inputFile = Argument.File(\"input\", { mustExist: true }) // Must exist\n * const outputFile = Argument.File(\"output\", { mustExist: false }) // Must not exist\n * const kinds = [inputFile.kind, outputFile.kind] // => [\"argument\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const File = (name, options) => Param.File(Param.argumentKind, name, options);\n/**\n * Creates a positional directory path argument.\n *\n * **Example** (Creating a directory path argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const workspace = Argument.Directory(\"workspace\", { mustExist: true }) // Must exist\n * workspace.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Directory = (name, options) => Param.Directory(Param.argumentKind, name, options);\n/**\n * Creates a positional argument that parses finite numbers.\n *\n * **Example** (Parsing a finite number)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const ratio = Argument.Finite(\"ratio\")\n * ratio.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Finite = name => Param.Finite(Param.argumentKind, name);\n/**\n * Creates a positional date argument.\n *\n * **Example** (Creating a date argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const startDate = Argument.Date(\"start-date\")\n * startDate.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Date = name => Param.Date(Param.argumentKind, name);\n/**\n * Creates a positional choice argument.\n *\n * **Example** (Creating a choice argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const environment = Argument.Literals(\"environment\", [\"dev\", \"staging\", \"prod\"])\n * environment.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Literals = (name, choices) => Param.Literals(Param.argumentKind, name, choices);\n/**\n * Creates a positional path argument.\n *\n * **Example** (Creating a path argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const configPath = Argument.Path(\"config\")\n * configPath.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Path = (name, options) => Param.Path(Param.argumentKind, name, options);\n/**\n * Creates a positional redacted argument that obscures its value.\n *\n * **Example** (Creating a redacted argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const secret = Argument.Redacted(\"secret\")\n * secret.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Redacted = name => Param.Redacted(Param.argumentKind, name);\n/**\n * Creates a positional argument that reads file content as a string.\n *\n * **Example** (Reading file text)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const config = Argument.FileText(\"config-file\")\n * config.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileText = name => Param.FileText(Param.argumentKind, name);\n/**\n * Creates a positional argument that reads a file and parses its content.\n *\n * **Details**\n *\n * The parser is chosen from the explicit `format` option or, when omitted, the\n * file extension. The parsed value is `unknown`; use `fileSchema` when the\n * parsed content should also be decoded with a Schema.\n *\n * **Example** (Parsing file content)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const config = Argument.FileParse(\"config\", { format: \"json\" })\n * config.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileParse = (name, options) => Param.FileParse(Param.argumentKind, name, options);\n/**\n * Creates a positional argument that reads and validates file content using a schema.\n *\n * **Example** (Validating file content with a schema)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Argument } from \"effect/cli\"\n *\n * const ConfigSchema = Schema.Struct({\n * port: Schema.Number,\n * host: Schema.String\n * })\n *\n * const config = Argument.FileSchema(\"config\", ConfigSchema)\n * config.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileSchema = (name, schema, options) => Param.FileSchema(Param.argumentKind, name, schema, options);\n/**\n * An argument that always fails to parse.\n *\n * **Example** (Creating a sentinel argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const noArg = Argument.Never\n * noArg.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Never = /*#__PURE__*/Param.Never(Param.argumentKind);\n// -------------------------------------------------------------------------------------\n// combinators\n// -------------------------------------------------------------------------------------\n/**\n * Makes a positional argument optional.\n *\n * **Example** (Making an argument optional)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const optionalVersion = Argument.String(\"version\").pipe(Argument.optional)\n * optionalVersion.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const optional = arg => Param.optional(arg);\n/**\n * Adds a description to a positional argument.\n *\n * **Example** (Adding an argument description)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const filename = Argument.String(\"filename\").pipe(\n * Argument.withDescription(\"The input file to process\")\n * )\n * filename.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withDescription = /*#__PURE__*/dual(2, (self, description) => Param.withDescription(self, description));\n/**\n * Provides a default value for a positional argument.\n *\n * **Example** (Providing a default value)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const port = Argument.Int(\"port\").pipe(Argument.withDefault(8080))\n * port.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withDefault = Param.withDefault;\n/**\n * Adds a fallback config that is loaded when a required argument is missing.\n *\n * **Example** (Loading a fallback config)\n *\n * ```ts import.meta.vitest\n * import { Config } from \"effect\"\n * import { Argument } from \"effect/cli\"\n *\n * const repository = Argument.String(\"repository\").pipe(\n * Argument.withFallbackConfig(Config.String(\"REPOSITORY\"))\n * )\n * repository.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackConfig = /*#__PURE__*/dual(2, (self, config) => Param.withFallbackConfig(self, config));\n/**\n * Adds a fallback prompt that is shown when a required argument is missing.\n *\n * **Example** (Showing a fallback prompt)\n *\n * ```ts import.meta.vitest\n * import { Argument, Prompt } from \"effect/cli\"\n *\n * const filename = Argument.String(\"filename\").pipe(\n * Argument.withFallbackPrompt(Prompt.String({ message: \"Filename\" }))\n * )\n * filename.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackPrompt = /*#__PURE__*/dual(2, (self, prompt) => Param.withFallbackPrompt(self, prompt));\n/**\n * Creates a variadic positional argument that accepts multiple values.\n *\n * **Example** (Accepting multiple values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * // Accept any number of files\n * const anyFiles = Argument.String(\"files\").pipe(Argument.variadic)\n *\n * // Accept at least 1 file\n * const atLeastOneFile = Argument.String(\"files\").pipe(\n * Argument.variadic({ min: 1 })\n * )\n *\n * // Accept between 1 and 5 files\n * const limitedFiles = Argument.String(\"files\").pipe(\n * Argument.variadic({ min: 1, max: 5 })\n * )\n *\n * const kinds = [anyFiles.kind, atLeastOneFile.kind, limitedFiles.kind] // => [\"argument\", \"argument\", \"argument\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const variadic = /*#__PURE__*/dual(args => Param.isParam(args[0]), (self, options) => Param.variadic(self, options));\n/**\n * Transforms the parsed value of a positional argument.\n *\n * **Example** (Mapping parsed values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const port = Argument.Int(\"port\").pipe(\n * Argument.map((p) => ({ port: p, url: `http://localhost:${p}` }))\n * )\n * port.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => Param.map(self, f));\n/**\n * Transforms the parsed value of a positional argument using an effectful function.\n *\n * **Example** (Validating values effectfully)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Argument, CliError } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const files = Argument.String(\"files\").pipe(\n * Argument.mapEffect((file) =>\n * file.endsWith(\".txt\")\n * ? Effect.succeed(file)\n * : Effect.fail(\n * new CliError.UserError({\n * cause: new Error(`Unsupported file extension: ${file}`),\n * userMessage: \"Only .txt files allowed\"\n * })\n * )\n * )\n * )\n *\n * const [, value] = await Effect.runPromise(\n * files.parse({ arguments: [\"notes.txt\"], flags: {} }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => \"notes.txt\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const mapEffect = /*#__PURE__*/dual(2, (self, f) => Param.mapEffect(self, f));\n/**\n * Transforms the parsed value of a positional argument using a function that may throw.\n *\n * **Example** (Mapping values that may throw)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Argument } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const json = Argument.String(\"data\").pipe(\n * Argument.mapTryCatch(\n * (str) => JSON.parse(str),\n * (error) =>\n * `Invalid JSON: ${error instanceof Error ? error.message : String(error)}`\n * )\n * )\n *\n * const [, value] = await Effect.runPromise(\n * json.parse({ arguments: ['{\"enabled\":true}'], flags: {} }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => { enabled: true }\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const mapTryCatch = /*#__PURE__*/dual(3, (self, f, onError) => Param.mapTryCatch(self, f, onError));\n/**\n * Creates a variadic argument that requires at least n values.\n *\n * **Example** (Requiring a minimum number of values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const files = Argument.String(\"files\").pipe(Argument.atLeast(1))\n * files.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const atLeast = /*#__PURE__*/dual(2, (self, min) => Param.atLeast(self, min));\n/**\n * Creates a variadic argument that accepts at most n values.\n *\n * **Example** (Limiting the maximum number of values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const files = Argument.String(\"files\").pipe(Argument.atMost(5))\n * files.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const atMost = /*#__PURE__*/dual(2, (self, max) => Param.atMost(self, max));\n/**\n * Creates a variadic argument that accepts between min and max values.\n *\n * **Example** (Requiring a range of values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const files = Argument.String(\"files\").pipe(Argument.between(1, 5))\n * files.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const between = /*#__PURE__*/dual(3, (self, min, max) => Param.between(self, min, max));\n/**\n * Validates parsed values against a Schema.\n *\n * **Example** (Validating parsed values with a schema)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Argument } from \"effect/cli\"\n *\n * const input = Argument.String(\"input\").pipe(\n * Argument.withSchema(Schema.NonEmptyString)\n * )\n * input.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withSchema = /*#__PURE__*/dual(2, (self, schema) => Param.withSchema(self, schema));\n/**\n * Creates a positional choice argument with custom value mapping.\n *\n * **Example** (Mapping choices to values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const logLevel = Argument.ChoiceWithValue(\"level\", [\n * [\"debug\", 0],\n * [\"info\", 1],\n * [\"warn\", 2],\n * [\"error\", 3]\n * ])\n * logLevel.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const ChoiceWithValue = (name, choices) => Param.ChoiceWithValue(Param.argumentKind, name, choices);\n// -------------------------------------------------------------------------------------\n// metadata\n// -------------------------------------------------------------------------------------\n/**\n * Sets a custom metavar (placeholder name) for the argument in help documentation.\n *\n * **Details**\n *\n * The metavar is displayed in usage text to indicate what value the user should provide.\n * For example, `<FILE>` shows `FILE` as the metavar.\n *\n * **Example** (Setting a metavar)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const port = Argument.Int(\"port\").pipe(\n * Argument.withMetavar(\"PORT\")\n * )\n * port.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category metadata\n * @since 4.0.0\n */\nexport const withMetavar = /*#__PURE__*/dual(2, (self, metavar) => Param.withMetavar(self, metavar));\n/**\n * Filters parsed values, failing with a custom error message if the predicate returns false.\n *\n * **Example** (Filtering parsed values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const positiveInt = Argument.Int(\"count\").pipe(\n * Argument.filter(\n * (n) => n > 0,\n * (n) => `Expected positive integer, got ${n}`\n * )\n * )\n * positiveInt.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const filter = /*#__PURE__*/dual(3, (self, predicate, onFalse) => Param.filter(self, predicate, onFalse));\n/**\n * Filters and transforms parsed values, failing with a custom error message\n * if the filter function returns None.\n *\n * **Example** (Filtering and mapping parsed values)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n * import { Argument } from \"effect/cli\"\n *\n * const positiveInt = Argument.Int(\"count\").pipe(\n * Argument.filterMap(\n * (n) => n > 0 ? Option.some(n) : Option.none(),\n * (n) => `Expected positive integer, got ${n}`\n * )\n * )\n * positiveInt.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(3, (self, f, onNone) => Param.filterMap(self, f, onNone));\n/**\n * Provides a fallback argument to use if this argument fails to parse.\n *\n * **Example** (Providing a fallback argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const value = Argument.Int(\"value\").pipe(\n * Argument.orElse(() => Argument.String(\"value\"))\n * )\n * value.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const orElse = /*#__PURE__*/dual(2, (self, that) => Param.orElse(self, that));\n/**\n * Provides a fallback argument, wrapping results in Result to distinguish which succeeded.\n *\n * **Example** (Returning which fallback succeeded)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/cli\"\n *\n * const source = Argument.File(\"source\").pipe(\n * Argument.orElseResult(() => Argument.String(\"url\"))\n * )\n * // Returns Result<string, string>\n * source.kind // => \"argument\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const orElseResult = /*#__PURE__*/dual(2, (self, that) => Param.orElseResult(self, that));\n//# sourceMappingURL=Argument.js.map","/**\n * Formats CLI help and errors as text.\n *\n * This module turns help documents, CLI errors, grouped errors, and version\n * information into strings. It does not write those strings to the terminal\n * itself. It includes the `Formatter` interface, the formatter service, a layer\n * for custom formatters, and the default formatter with configurable color\n * support.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"../Context.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as Option from \"../Option.js\";\nimport * as Ansi from \"./internal/ansi.js\";\n/**\n * Service reference for the CLI output formatter. Provides a default implementation\n * that can be overridden for custom formatting or testing.\n *\n * **Example** (Accessing the output formatter)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliOutput } from \"effect/cli\"\n *\n * // Access the formatter service\n * const program = Effect.gen(function*() {\n * const formatter = yield* CliOutput.Formatter\n *\n * // Format version information\n * return formatter.formatVersion(\"my-cli\", \"2.1.0\")\n * })\n *\n * // Run with default formatter\n * await Effect.runPromise(program.pipe(\n * Effect.provide(CliOutput.layer(CliOutput.defaultFormatter({ colors: false })))\n * )) // => \"my-cli v2.1.0\"\n * ```\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const Formatter = /*#__PURE__*/Context.Reference(\"effect/cli/CliOutput\", {\n defaultValue: () => defaultFormatter()\n});\n/**\n * Creates a Layer that provides a custom Formatter implementation.\n *\n * **Example** (Providing a custom formatter)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliOutput } from \"effect/cli\"\n *\n * // Create a custom formatter without colors\n * const noColorFormatter = CliOutput.defaultFormatter({ colors: false })\n * const NoColorLayer = CliOutput.layer(noColorFormatter)\n *\n * // Create a program that uses the custom formatter\n * const program = Effect.gen(function*() {\n * const formatter = yield* CliOutput.Formatter\n * return formatter.formatVersion(\"my-cli\", \"1.0.0\")\n * }).pipe(\n * Effect.provide(NoColorLayer)\n * )\n *\n * await Effect.runPromise(program) // => \"my-cli v1.0.0\"\n * ```\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = formatter => Layer.succeed(Formatter)(formatter);\nconst escapeControlCharacters = text =>\n// oxlint-disable-next-line no-control-regex\ntext.replace(/[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F]/g, character => `\\\\x${character.charCodeAt(0).toString(16).padStart(2, \"0\")}`);\n/**\n * Creates a default formatter with configurable options.\n *\n * **Example** (Creating default formatters)\n *\n * ```ts import.meta.vitest\n * import { CliError, CliOutput } from \"effect/cli\"\n *\n * // Create a formatter without colors for tests or CI environments\n * const noColorFormatter = CliOutput.defaultFormatter({ colors: false })\n *\n * // Create a formatter with colors forced on\n * const colorFormatter = CliOutput.defaultFormatter({ colors: true })\n *\n * // Auto-detect colors based on terminal support (default behavior)\n * const autoFormatter = CliOutput.defaultFormatter()\n *\n * const error = new CliError.InvalidValue({\n * option: \"foo\",\n * value: \"bar\",\n * expected: \"baz\",\n * kind: \"flag\"\n * })\n *\n * noColorFormatter.formatError(error).includes(\"Invalid value\") // => true\n * colorFormatter.formatVersion(\"my-tool\", \"1.2.3\").includes(\"my-tool\") // => true\n * autoFormatter.formatVersion(\"my-tool\", \"1.2.3\").includes(\"1.2.3\") // => true\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const defaultFormatter = options => {\n const useColor = options?.colors ?? Ansi.detectColors();\n // Color palette using ANSI escape codes\n const colors = useColor ? {\n bold: text => `\\x1b[1m${text}\\x1b[0m`,\n dim: text => `\\x1b[2m${text}\\x1b[0m`,\n cyan: text => `\\x1b[36m${text}\\x1b[0m`,\n green: text => `\\x1b[32m${text}\\x1b[0m`,\n blue: text => `\\x1b[34m${text}\\x1b[0m`,\n yellow: text => `\\x1b[33m${text}\\x1b[0m`,\n magenta: text => `\\x1b[35m${text}\\x1b[0m`\n } : {\n bold: text => text,\n dim: text => text,\n cyan: text => text,\n green: text => text,\n blue: text => text,\n yellow: text => text,\n magenta: text => text\n };\n const reset = useColor ? \"\\x1b[0m\" : \"\";\n const red = useColor ? \"\\x1b[31m\" : \"\";\n const bold = useColor ? \"\\x1b[1m\" : \"\";\n return {\n formatHelpDoc: doc => formatHelpDocImpl(doc, colors),\n formatCliError: error => escapeControlCharacters(error.message),\n formatError: error => {\n return `\\n${bold}${red}ERROR${reset}\\n ${escapeControlCharacters(error.message)}${reset}`;\n },\n formatErrors: errors => {\n if (errors.length === 0) return \"\";\n if (errors.length === 1) {\n return `\\n${bold}${red}ERROR${reset}\\n ${escapeControlCharacters(errors[0].message)}${reset}`;\n }\n // Group errors by _tag\n const grouped = new Map();\n for (const error of errors) {\n const tag = error._tag ?? \"Error\";\n const group = grouped.get(tag) ?? [];\n group.push(error);\n grouped.set(tag, group);\n }\n const sections = [];\n sections.push(`\\n${bold}${red}ERRORS${reset}`);\n for (const [, group] of grouped) {\n for (const error of group) {\n sections.push(` ${escapeControlCharacters(error.message)}${reset}`);\n }\n }\n return sections.join(\"\\n\");\n },\n formatVersion: (name, version) => `${colors.bold(name)} ${colors.dim(\"v\")}${colors.bold(version)}`\n };\n};\n/**\n * Strips ANSI escape codes from a string to calculate visual width.\n * @internal\n */\nconst stripAnsi = text => {\n // oxlint-disable-next-line no-control-regex\n return text.replace(/\\u001B\\[[0-9;]*m/g, \"\");\n};\n/**\n * Segments text into grapheme clusters.\n * @internal\n */\nconst graphemeSegmenter = /*#__PURE__*/new Intl.Segmenter(undefined, {\n granularity: \"grapheme\"\n});\nconst zeroWidthCodePoints = /[\\p{Mark}\\p{Control}\\p{Default_Ignorable_Code_Point}]/gu;\nconst emojiPresentation = /\\p{Emoji_Presentation}/u;\nconst isFullWidthCodePoint = codePoint => {\n if (codePoint < 0x1100) return false;\n return codePoint <= 0x115f || codePoint === 0x2329 || codePoint === 0x232a || codePoint >= 0x2e80 && codePoint <= 0x303e || codePoint >= 0x3040 && codePoint <= 0xa4cf || codePoint >= 0xac00 && codePoint <= 0xd7a3 || codePoint >= 0xf900 && codePoint <= 0xfaff || codePoint >= 0xfe10 && codePoint <= 0xfe19 || codePoint >= 0xfe30 && codePoint <= 0xfe6f || codePoint >= 0xff00 && codePoint <= 0xff60 || codePoint >= 0xffe0 && codePoint <= 0xffe6 || codePoint >= 0x1b000 && codePoint <= 0x1b2ff || codePoint >= 0x1f200 && codePoint <= 0x1f251 || codePoint >= 0x20000 && codePoint <= 0x3fffd;\n};\nconst graphemeWidth = grapheme => {\n const visible = grapheme.replace(zeroWidthCodePoints, \"\");\n if (visible.length === 0) return 0;\n if (emojiPresentation.test(grapheme) || grapheme.includes(\"\\uFE0F\")) return 2;\n return isFullWidthCodePoint(visible.codePointAt(0)) ? 2 : 1;\n};\n/**\n * Measures the number of terminal cells a string occupies.\n *\n * **Details**\n *\n * Uses the same measurement as built-in help and table rendering. ANSI styling\n * is stripped before measuring graphemes: zero-width graphemes count as `0`,\n * emoji presentation sequences and fullwidth characters as `2`, and other\n * graphemes as `1`.\n *\n * **Example** (Measuring terminal-cell widths)\n *\n * ```ts import.meta.vitest\n * import { CliOutput } from \"effect/cli\"\n *\n * CliOutput.displayWidth(\"file\") // => 4\n * CliOutput.displayWidth(\"ファイル\") // => 8\n * CliOutput.displayWidth(\"é\") // => 1\n * CliOutput.displayWidth(\"1️⃣\") // => 2\n * CliOutput.displayWidth(\"\\u001B[1mbold\\u001B[0m\") // => 4\n * ```\n *\n * @stability unstable\n * @category measuring\n * @since 4.0.3\n */\nexport const displayWidth = text => {\n let length = 0;\n for (const {\n segment\n } of graphemeSegmenter.segment(stripAnsi(text))) {\n length += graphemeWidth(segment);\n }\n return length;\n};\n/**\n * Helper function to pad strings to a specified width.\n * @internal\n */\nconst pad = (s, width) => {\n const actualLength = displayWidth(s);\n const padding = Math.max(0, width - actualLength);\n return s + \" \".repeat(padding);\n};\n/**\n * Renders a table with aligned columns.\n * @internal\n */\nconst renderTable = (rows, widthCap) => {\n const maxColumn = Math.max(...rows.map(r => displayWidth(r.left))) + 4;\n const col = widthCap === undefined ? maxColumn : Math.min(maxColumn, widthCap);\n return rows.map(({\n left,\n right\n }) => ` ${pad(left, Math.max(col, displayWidth(left) + 1))}${right}`).join(\"\\n\");\n};\nconst formatSubcommandName = (name, alias) => alias ? `${name}, ${alias}` : name;\n/**\n * Internal implementation of help formatting that accepts configurable color functions.\n * @internal\n */\nconst formatHelpDocImpl = (doc, colors) => {\n const sections = [];\n // Description section\n if (doc.description) {\n sections.push(colors.bold(\"DESCRIPTION\"));\n sections.push(` ${doc.description}`);\n sections.push(\"\");\n }\n // Usage section\n sections.push(colors.bold(\"USAGE\"));\n sections.push(` ${colors.cyan(doc.usage)}`);\n sections.push(\"\");\n // Arguments section\n if (doc.args && doc.args.length > 0) {\n sections.push(colors.bold(\"ARGUMENTS\"));\n const argRows = doc.args.map(arg => {\n let name = arg.name;\n if (arg.variadic) {\n name += \"...\";\n }\n const coloredName = colors.green(name);\n const coloredType = colors.dim(arg.type);\n const nameType = `${coloredName} ${coloredType}`;\n const optionalSuffix = arg.required ? \"\" : colors.dim(\" (optional)\");\n const description = Option.getOrElse(arg.description, () => \"\") + optionalSuffix;\n return {\n left: nameType,\n right: description\n };\n });\n sections.push(renderTable(argRows, 25));\n sections.push(\"\");\n }\n // Flags section\n if (doc.flags.length > 0) {\n sections.push(colors.bold(\"FLAGS\"));\n const flagRows = doc.flags.map(flag => {\n const names = [];\n // Add main name with -- prefix first\n names.push(colors.green(`--${flag.name}`));\n // Add aliases after (like -f) to match expected ordering\n for (const alias of flag.aliases) {\n names.push(colors.green(alias));\n }\n const namesPart = names.join(\", \");\n const typePart = flag.type !== \"boolean\" ? ` ${colors.dim(flag.type)}` : \"\";\n return {\n left: namesPart + typePart,\n right: Option.getOrElse(flag.description, () => \"\")\n };\n });\n sections.push(renderTable(flagRows));\n sections.push(\"\");\n }\n // Global Flags section\n if (doc.globalFlags && doc.globalFlags.length > 0) {\n sections.push(colors.bold(\"GLOBAL FLAGS\"));\n const globalFlagRows = doc.globalFlags.map(flag => {\n const names = [];\n // Add main name with -- prefix first\n names.push(colors.green(`--${flag.name}`));\n // Add aliases after (like -f) to match expected ordering\n for (const alias of flag.aliases) {\n names.push(colors.green(alias));\n }\n const namesPart = names.join(\", \");\n const typePart = flag.type !== \"boolean\" ? ` ${colors.dim(flag.type)}` : \"\";\n return {\n left: namesPart + typePart,\n right: Option.getOrElse(flag.description, () => \"\")\n };\n });\n sections.push(renderTable(globalFlagRows));\n sections.push(\"\");\n }\n // Subcommands section\n if (doc.subcommands && doc.subcommands.length > 0) {\n const ungrouped = doc.subcommands.find(group => group.group === undefined);\n if (ungrouped) {\n sections.push(colors.bold(\"SUBCOMMANDS\"));\n sections.push(renderTable(ungrouped.commands.map(sub => ({\n left: colors.cyan(formatSubcommandName(sub.name, sub.alias)),\n right: sub.shortDescription ?? sub.description\n })), 20));\n if (doc.subcommands.length > 1) {\n sections.push(\"\");\n }\n }\n for (const group of doc.subcommands) {\n if (group.group === undefined) continue;\n sections.push(colors.bold(`${group.group}:`));\n sections.push(renderTable(group.commands.map(sub => ({\n left: colors.cyan(formatSubcommandName(sub.name, sub.alias)),\n right: sub.shortDescription ?? sub.description\n })), 20));\n sections.push(\"\");\n }\n }\n // Examples section\n if (doc.examples && doc.examples.length > 0) {\n sections.push(colors.bold(\"EXAMPLES\"));\n let first = true;\n let previousHadDescription = false;\n for (const example of doc.examples) {\n if (example.description) {\n if (!first) sections.push(\"\");\n sections.push(` ${colors.dim(`# ${example.description}`)}`);\n } else if (previousHadDescription) {\n sections.push(\"\");\n }\n sections.push(` ${colors.cyan(example.command)}`);\n first = false;\n previousHadDescription = !!example.description;\n }\n sections.push(\"\");\n }\n // Remove trailing empty line if present\n if (sections[sections.length - 1] === \"\") {\n sections.pop();\n }\n return sections.join(\"\\n\");\n};\n//# sourceMappingURL=CliOutput.js.map","/**\n * Config Internal\n * ================\n *\n * The processed internal representation of a Command.Config declaration.\n * Separates the user's declared config shape from the flat parsing representation.\n *\n * Key concepts:\n * - ConfigInternal: The full processed form (flags, arguments, tree)\n * - ConfigInternal.Tree: Maps declaration keys to nodes\n * - ConfigInternal.Node: Param reference, Array, or Nested subtree\n *\n * Example transformation from Command.Config to Command.Config.Internal:\n *\n * ```ts\n * // User declares:\n * const config = {\n * verbose: Flag.Boolean(\"verbose\").pipe(Flag.withDefault(false)),\n * server: {\n * host: Flag.String(\"host\"),\n * port: Flag.Int(\"port\")\n * },\n * files: Argument.String(\"files\").pipe(Argument.variadic)\n * }\n *\n * // Becomes Config.Internal:\n * {\n * arguments: [filesParam], // Flat array of arguments\n * flags: [verboseParam, hostParam, portParam], // Flat array of flags\n * orderedParams: [verboseParam, hostParam, portParam, filesParam],\n * tree: { // Preserves nested structure\n * verbose: { _tag: \"Param\", index: 0 },\n * server: {\n * _tag: \"Nested\",\n * tree: {\n * host: { _tag: \"Param\", index: 1 },\n * port: { _tag: \"Param\", index: 2 }\n * }\n * },\n * files: { _tag: \"Param\", index: 3 }\n * }\n * }\n * ```\n *\n * This separation allows:\n * 1. Flat iteration over all params for parsing/validation\n * 2. Reconstruction of original nested shape for handler input\n */\nimport * as InternalRecord from \"../../internal/record.js\";\nimport * as Param from \"../Param.js\";\n/* ========================================================================== */\n/* Type ID */\n/* ========================================================================== */\nconst ConfigInternalTypeId = \"~effect/cli/Command/Config/Internal\";\n/**\n * Parses a Command.Config into a ConfigInternal.\n *\n * Walks the config structure and:\n * 1. Extracts all Params into flat arrays (flags, arguments, orderedParams)\n * 2. Builds a tree that remembers the original nested structure\n * 3. Assigns each Param an index to link parsed values back\n *\n * @internal\n */\nexport const parseConfig = config => {\n const orderedParams = [];\n const flags = [];\n const args = [];\n function parse(config) {\n const tree = Object.create(null);\n for (const key of Object.keys(config)) {\n tree[key] = parseValue(config[key]);\n }\n return tree;\n }\n function parseValue(value) {\n if (Array.isArray(value)) {\n return {\n _tag: \"Array\",\n children: value.map(v => parseValue(v))\n };\n } else if (Param.isParam(value)) {\n const index = orderedParams.length;\n orderedParams.push(value);\n if (value.kind === \"argument\") {\n args.push(value);\n } else {\n flags.push(value);\n }\n return {\n _tag: \"Param\",\n index\n };\n } else {\n return {\n _tag: \"Nested\",\n tree: parse(value)\n };\n }\n }\n return {\n [ConfigInternalTypeId]: ConfigInternalTypeId,\n flags,\n arguments: args,\n orderedParams,\n tree: parse(config)\n };\n};\n/**\n * @internal\n */\nexport const emptyConfig = /*#__PURE__*/parseConfig({});\nconst shiftNodeIndexes = (node, offset) => {\n switch (node._tag) {\n case \"Param\":\n return {\n _tag: \"Param\",\n index: node.index + offset\n };\n case \"Array\":\n return {\n _tag: \"Array\",\n children: node.children.map(child => shiftNodeIndexes(child, offset))\n };\n case \"Nested\":\n return {\n _tag: \"Nested\",\n tree: shiftTreeIndexes(node.tree, offset)\n };\n }\n};\nconst shiftTreeIndexes = (tree, offset) => {\n const output = Object.create(null);\n for (const key of Object.keys(tree)) {\n output[key] = shiftNodeIndexes(tree[key], offset);\n }\n return output;\n};\n/**\n * @internal\n */\nexport const mergeConfig = (left, right) => {\n const offset = left.orderedParams.length;\n return {\n [ConfigInternalTypeId]: ConfigInternalTypeId,\n flags: [...left.flags, ...right.flags],\n arguments: [...left.arguments, ...right.arguments],\n orderedParams: [...left.orderedParams, ...right.orderedParams],\n tree: Object.assign(Object.create(null), left.tree, shiftTreeIndexes(right.tree, offset))\n };\n};\n/* ========================================================================== */\n/* Reconstruction */\n/* ========================================================================== */\n/**\n * Reconstructs the original nested config shape from parsed values.\n *\n * Uses the tree as a blueprint to place each parsed value back into\n * its original position in the nested structure.\n *\n * @internal\n */\nexport const reconstructTree = (tree, results) => {\n const output = {};\n for (const key of Object.keys(tree)) {\n InternalRecord.assignProperty(output, key, nodeValue(tree[key]));\n }\n return output;\n function nodeValue(node) {\n switch (node._tag) {\n case \"Param\":\n return results[node.index];\n case \"Array\":\n return node.children.map(child => nodeValue(child));\n case \"Nested\":\n return reconstructTree(node.tree, results);\n }\n }\n};\n//# sourceMappingURL=config.js.map","/**\n * Command Implementation\n * ======================\n *\n * Internal implementation details for CLI commands.\n * Public API is in ../Command.ts\n */\nimport * as Arr from \"../../Array.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Effectable from \"../../Effectable.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as CliError from \"../CliError.js\";\nimport * as Param from \"../Param.js\";\nimport * as Primitive from \"../Primitive.js\";\nimport { emptyConfig, reconstructTree } from \"./config.js\";\n/* ========================================================================== */\n/* Type ID */\n/* ========================================================================== */\nexport const TypeId = \"~effect/cli/Command\";\n/* ========================================================================== */\n/* Casting */\n/* ========================================================================== */\n/**\n * Casts a Command to its internal implementation.\n * For use by internal modules that need access to config, parse, handle, etc.\n */\nexport const toImpl = self => self;\n/* ========================================================================== */\n/* Proto */\n/* ========================================================================== */\nexport const Proto = {\n ... /*#__PURE__*/Effectable.Prototype({\n label: \"Command\",\n evaluate() {\n return toImpl(this).service;\n }\n })\n};\n/* ========================================================================== */\n/* Constructor */\n/* ========================================================================== */\n/**\n * Internal command constructor. Only accepts already-parsed ConfigInternal.\n */\nexport const makeCommand = options => {\n const config = options.config;\n const contextConfig = options.contextConfig ?? emptyConfig;\n const service = options.service ?? Context.Service(`${TypeId}/${options.name}`);\n const annotations = options.annotations ?? Context.empty();\n const globalFlags = options.globalFlags ?? [];\n const subcommands = options.subcommands ?? [];\n const handle = (input, commandPath) => Predicate.isNotUndefined(options.handle) ? options.handle(input, commandPath) : Effect.fail(new CliError.ShowHelp({\n commandPath,\n errors: []\n }));\n const parse = options.parse ?? makeParser(config);\n const parseContext = options.parseContext ?? makeParser(contextConfig, {\n allowLeftovers: true\n });\n const buildHelpDoc = commandPath => {\n const args = [];\n const flags = [];\n for (const arg of config.arguments) {\n const singles = Param.extractSingleParams(arg);\n const metadata = Param.getParamMetadata(arg);\n for (const single of singles) {\n args.push({\n name: single.name,\n type: single.typeName ?? Primitive.getTypeName(single.primitiveType),\n description: single.description,\n required: !metadata.isOptional && (!metadata.isVariadic || Option.exists(metadata.variadicMin, min => min > 0)),\n variadic: metadata.isVariadic\n });\n }\n }\n let usage = commandPath.length > 0 ? commandPath.join(\" \") : options.name;\n // Only render `<subcommand>` in usage when at least one visible subcommand\n // exists; an all-unlisted subcommand tree should look like a leaf command.\n if (subcommands.some(group => group.commands.some(c => !c.unlisted))) {\n usage += \" <subcommand>\";\n }\n usage += \" [flags]\";\n for (const arg of args) {\n const argName = arg.variadic ? `<${arg.name}...>` : `<${arg.name}>`;\n usage += ` ${arg.required ? argName : `[${argName}]`}`;\n }\n for (const option of config.flags) {\n const singles = Param.extractSingleParams(option);\n const metadata = Param.getParamMetadata(option);\n for (const single of singles) {\n // Hidden flags still parse on the command line but are omitted from\n // generated --help output.\n if (single.hidden) continue;\n flags.push(toFlagDoc(single, metadata));\n }\n }\n const subcommandDocs = [];\n for (const group of subcommands) {\n // Unlisted subcommands still parse on the command line but are omitted\n // from --help. Drop the whole group when nothing visible remains so we\n // don't render an empty heading.\n const visible = group.commands.filter(c => !c.unlisted);\n if (visible.length === 0) continue;\n subcommandDocs.push({\n group: group.group,\n commands: Arr.map(visible, subcommand => ({\n name: subcommand.name,\n alias: subcommand.alias,\n shortDescription: subcommand.shortDescription,\n description: subcommand.description ?? \"\"\n }))\n });\n }\n const examples = options.examples ?? [];\n return {\n description: options.description ?? \"\",\n usage,\n flags,\n annotations,\n ...(args.length > 0 && {\n args\n }),\n ...(subcommandDocs.length > 0 && {\n subcommands: subcommandDocs\n }),\n ...(examples.length > 0 && {\n examples\n })\n };\n };\n return Object.assign(Object.create(Proto), {\n [TypeId]: TypeId,\n name: options.name,\n examples: options.examples ?? [],\n annotations,\n globalFlags,\n subcommands,\n unlisted: options.unlisted ?? false,\n config,\n contextConfig,\n service,\n parse,\n parseContext,\n handle,\n buildHelpDoc,\n ...(Predicate.isNotUndefined(options.description) ? {\n description: options.description\n } : {}),\n ...(Predicate.isNotUndefined(options.shortDescription) ? {\n shortDescription: options.shortDescription\n } : {}),\n ...(Predicate.isNotUndefined(options.alias) ? {\n alias: options.alias\n } : {})\n });\n};\n/* ========================================================================== */\n/* Helpers */\n/* ========================================================================== */\n/**\n * Converts a single flag param into a FlagDoc for help display.\n *\n * @internal\n */\nexport const toFlagDoc = (single, metadata) => {\n const formattedAliases = single.aliases.map(alias => alias.length === 1 ? `-${alias}` : `--${alias}`);\n const type = single.typeName ?? Primitive.getTypeName(single.primitiveType);\n return {\n name: single.name,\n aliases: formattedAliases,\n type: single.optionalValue === undefined ? type : `[=${type}]`,\n description: appendChoiceKeys(single.description, Primitive.getChoiceKeys(single.primitiveType)),\n required: single.primitiveType._tag !== \"Boolean\" && !metadata.isOptional\n };\n};\nconst appendChoiceKeys = (description, choiceKeys) => {\n if (choiceKeys === undefined || choiceKeys.length === 0) {\n return description;\n }\n const choiceSuffix = `(choices: ${choiceKeys.join(\", \")})`;\n return Option.match(description, {\n onNone: () => Option.some(choiceSuffix),\n onSome: value => Option.some(`${value} ${choiceSuffix}`)\n });\n};\n/**\n * Creates a parser for a given config. Used as the default for both `parse`\n * and `parseContext`, and also by `withSharedFlags` to avoid constructing a\n * full throwaway command.\n */\nexport const makeParser = (cfg, options) => Effect.fnUntraced(function* (input) {\n const parsedArgs = {\n flags: input.flags,\n arguments: input.arguments\n };\n const [remainingArguments, values] = yield* parseParams(parsedArgs, cfg.orderedParams);\n if (options?.allowLeftovers !== true && remainingArguments.length > 0) {\n return yield* new CliError.UnexpectedArgument({\n arguments: remainingArguments\n });\n }\n return reconstructTree(cfg.tree, values);\n});\n/**\n * Parses param values from parsed command arguments into their typed\n * representations.\n */\nconst parseParams = /*#__PURE__*/Effect.fnUntraced(function* (parsedArgs, params) {\n const results = [];\n let currentArguments = parsedArgs.arguments;\n for (const option of params) {\n const [remainingArguments, parsed] = yield* option.parse({\n flags: parsedArgs.flags,\n arguments: currentArguments\n });\n results.push(parsed);\n currentArguments = remainingArguments;\n }\n return [currentArguments, results];\n});\n/**\n * Checks that inherited parent context flags do not reuse names declared by\n * child command flags.\n *\n * When `contextConfig` is supplied, it is used as the inherited flag set;\n * otherwise the parent's current context config is checked.\n */\nexport const checkForDuplicateFlags = (parent, subcommands, options) => {\n const parentImpl = toImpl(parent);\n const parentOptionNames = new Set();\n const extractNames = flags => {\n for (const option of flags) {\n const singles = Param.extractSingleParams(option);\n for (const single of singles) {\n parentOptionNames.add(single.name);\n }\n }\n };\n extractNames((options?.contextConfig ?? parentImpl.contextConfig).flags);\n for (const subcommand of subcommands) {\n const subImpl = toImpl(subcommand);\n for (const option of subImpl.config.flags) {\n const singles = Param.extractSingleParams(option);\n for (const single of singles) {\n if (parentOptionNames.has(single.name)) {\n throw new CliError.DuplicateOption({\n option: single.name,\n parentCommand: parent.name,\n childCommand: subcommand.name\n });\n }\n }\n }\n }\n};\n//# sourceMappingURL=command.js.map","/**\n * CommandDescriptor — pure-data representation of a command tree for\n * shell completion generation.\n *\n * @internal\n */\nimport * as Option from \"../../../Option.js\";\nimport * as Param from \"../../Param.js\";\nimport * as Primitive from \"../../Primitive.js\";\nimport { toImpl } from \"../command.js\";\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\nconst toFlagType = single => {\n const tag = single.primitiveType._tag;\n switch (tag) {\n case \"Boolean\":\n return {\n _tag: \"Boolean\"\n };\n case \"Int\":\n return {\n _tag: \"Int\"\n };\n case \"Finite\":\n return {\n _tag: \"Finite\"\n };\n case \"Date\":\n return {\n _tag: \"Date\"\n };\n case \"Choice\":\n {\n const keys = Primitive.getChoiceKeys(single.primitiveType);\n return {\n _tag: \"Choice\",\n values: keys ?? []\n };\n }\n case \"Path\":\n return {\n _tag: \"Path\",\n pathType: Primitive.getPathType(single.primitiveType) ?? \"either\"\n };\n case \"FileText\":\n case \"FileParse\":\n case \"FileSchema\":\n return {\n _tag: \"Path\",\n pathType: \"file\"\n };\n default:\n return {\n _tag: \"String\"\n };\n }\n};\nconst toArgumentType = single => {\n const tag = single.primitiveType._tag;\n switch (tag) {\n case \"Int\":\n return {\n _tag: \"Int\"\n };\n case \"Finite\":\n return {\n _tag: \"Finite\"\n };\n case \"Date\":\n return {\n _tag: \"Date\"\n };\n case \"Choice\":\n {\n const keys = Primitive.getChoiceKeys(single.primitiveType);\n return {\n _tag: \"Choice\",\n values: keys ?? []\n };\n }\n case \"Path\":\n return {\n _tag: \"Path\",\n pathType: Primitive.getPathType(single.primitiveType) ?? \"either\"\n };\n case \"FileText\":\n case \"FileParse\":\n case \"FileSchema\":\n return {\n _tag: \"Path\",\n pathType: \"file\"\n };\n default:\n return {\n _tag: \"String\"\n };\n }\n};\n// ---------------------------------------------------------------------------\n// Extraction\n// ---------------------------------------------------------------------------\n/**\n * @internal\n */\nexport const fromCommand = (cmd, inheritedFlags = []) => {\n const impl = toImpl(cmd);\n const config = impl.config;\n const flags = [];\n const seen = new Set();\n // Match help's precedence: local flags first, then ancestors root to leaf.\n for (const [index, flag] of [...config.flags, ...inheritedFlags].entries()) {\n const singles = Param.extractSingleParams(flag);\n for (const single of singles) {\n if (single.kind !== \"flag\") continue;\n // Omit hidden flags from completion scripts so tab-completion in the\n // shell does not advertise flags that are absent from --help.\n if (single.hidden) continue;\n if (index >= config.flags.length && seen.has(single.name)) continue;\n seen.add(single.name);\n flags.push({\n name: single.name,\n aliases: single.aliases,\n description: Option.getOrUndefined(single.description),\n type: toFlagType(single),\n optionalValue: single.optionalValue !== undefined\n });\n }\n }\n const args = [];\n for (const arg of config.arguments) {\n const singles = Param.extractSingleParams(arg);\n const metadata = Param.getParamMetadata(arg);\n for (const single of singles) {\n if (single.kind !== \"argument\") continue;\n args.push({\n name: single.name,\n description: Option.getOrUndefined(single.description),\n required: !metadata.isOptional,\n variadic: metadata.isVariadic,\n type: toArgumentType(single)\n });\n }\n }\n const subcommands = [];\n const sharedFlags = [...inheritedFlags, ...impl.contextConfig.flags];\n for (const group of cmd.subcommands) {\n for (const subcommand of group.commands) {\n // Omit unlisted subcommands from completion scripts so tab-completion in\n // the shell does not advertise commands that are absent from --help.\n if (subcommand.unlisted) continue;\n const descriptor = fromCommand(subcommand, sharedFlags);\n subcommands.push(descriptor);\n if (subcommand.alias && subcommand.alias !== subcommand.name) {\n subcommands.push({\n ...descriptor,\n name: subcommand.alias\n });\n }\n }\n }\n return {\n name: cmd.name,\n description: cmd.shortDescription ?? cmd.description,\n flags,\n arguments: args,\n subcommands\n };\n};\n/**\n * Whether the flag reads its value from the next word.\n *\n * @internal\n */\nexport const takesSeparateValue = flag => flag.type._tag !== \"Boolean\" && flag.optionalValue !== true;\n//# sourceMappingURL=descriptor.js.map","import { takesSeparateValue } from \"./descriptor.js\";\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\nconst escapeForBash = s => s.replace(/'/g, \"'\\\\''\");\nconst sanitizeFunctionName = s => s.replace(/[^a-zA-Z0-9_]/g, \"_\");\nconst flagNamesForWordlist = flag => {\n const names = [`--${flag.name}`];\n for (const alias of flag.aliases) {\n names.push(alias.length === 1 ? `-${alias}` : `--${alias}`);\n }\n if (flag.type._tag === \"Boolean\") {\n names.push(`--no-${flag.name}`);\n }\n return names;\n};\n/** Emit a Bash 3.2-compatible used-flag filter. */\nconst buildFlagGroupDeclarations = (flags, lines) => {\n if (flags.length === 0) return;\n const groups = flags.map(flagNamesForWordlist);\n lines.push(` local ${groups.map((_, index) => `_used_${index}=\"\"`).join(\" \")}`);\n lines.push(` for ((i = 1; i < cword; i++)); do`);\n lines.push(` case \"\\${words[i]%%=*}\" in`);\n groups.forEach((forms, index) => {\n lines.push(` ${forms.join(\"|\")}) _used_${index}=1 ;;`);\n });\n lines.push(` esac`);\n lines.push(` done`);\n lines.push(` local _filtered_flags=\"\"`);\n groups.forEach((forms, index) => {\n lines.push(` [[ -n \"$_used_${index}\" ]] || _filtered_flags+=\" ${forms.join(\" \")}\"`);\n });\n lines.push(``);\n};\n/**\n * Complete choices without `compgen -W`, which reparses quoted values. Escape\n * only the portion readline replaces for the active quote context.\n *\n * `!` cannot be escaped inside a user-opened double quote without changing the\n * resulting argument.\n */\nconst choicesHelper = (helperName, lines) => {\n lines.push(`${helperName}()`);\n lines.push(`{`);\n lines.push(` local _cur=\"$1\" _word=\"$2\"; shift 2`);\n lines.push(``);\n lines.push(` local _head=\"\\${_cur%\"$_word\"}\"`);\n lines.push(` local _open=\"\"`);\n lines.push(` case \"$_head\" in`);\n lines.push(` *\\\\') _open=\"'\" ;;`);\n lines.push(` *\\\\\") _open='\"' ;;`);\n lines.push(` esac`);\n lines.push(``);\n lines.push(` local _prefix=\"$_cur\" _committed=\"$_head\"`);\n // Quoting these substitutions breaks quote matching on Bash 3.2.\n lines.push(` _prefix=\\${_prefix//\\\\\\\\/}; _prefix=\\${_prefix//\\\\\"/}; _prefix=\\${_prefix//\\\\'/}`);\n lines.push(` _committed=\\${_committed//\\\\\\\\/}; _committed=\\${_committed//\\\\\"/}; _committed=\\${_committed//\\\\'/}`);\n lines.push(``);\n lines.push(` COMPREPLY=()`);\n lines.push(` local _choice _rest _match`);\n lines.push(` for _choice in \"$@\"; do`);\n lines.push(` [[ \"$_choice\" == \"$_prefix\"* ]] || continue`);\n lines.push(` _rest=\"\\${_choice#\"$_committed\"}\"`);\n lines.push(` case \"$_open\" in`);\n lines.push(` \"'\")`);\n lines.push(` if [[ \"$_head\" == \"'\" ]]; then`);\n // Use a shell splice for a quote opened at the start of the word.\n lines.push(` _match=\\${_rest//\\\\'/\\\\'\\\\\\\\\\\\'\\\\'}`);\n lines.push(` else`);\n // A mid-word single-quote context cannot contain another single quote.\n lines.push(` [[ \"$_rest\" == *\\\\'* ]] && continue`);\n lines.push(` _match=\"$_rest\"`);\n lines.push(` fi`);\n lines.push(` ;;`);\n lines.push(` '\"')`);\n lines.push(` _match=\"\\${_rest//\\\\\\\\/\\\\\\\\\\\\\\\\}\"`);\n lines.push(` _match=\"\\${_match//\\\\$/\\\\\\\\$}\"`);\n lines.push(\" _match=\\\"${_match//\\\\`/\\\\\\\\\\\\`}\\\"\");\n lines.push(` _match=\"\\${_match//\\\\\"/\\\\\\\\\\\\\"}\"`);\n lines.push(` ;;`);\n lines.push(` *)`);\n lines.push(` printf -v _match '%q' \"$_rest\"`);\n // Bash 3.2 leaves a leading tilde unescaped.\n lines.push(` [[ -z \"$_head\" && \"$_match\" == '~'* ]] && _match=\"\\\\\\\\$_match\"`);\n lines.push(` ;;`);\n lines.push(` esac`);\n // Readline omits a closing quote already present in the match.\n lines.push(` [[ -n \"$_open\" && \"$_match\" == *\"$_open\" ]] && _match+=\"$_open\"`);\n lines.push(` COMPREPLY+=(\"$_match\")`);\n lines.push(` done`);\n lines.push(`}`);\n lines.push(``);\n};\nconst choiceCompletion = (helperName, values) => `${helperName} \"$cur\" \"$_comp_word\" ${values.map(value => `'${escapeForBash(value)}'`).join(\" \")}`;\nconst flagValueCompletion = (type, helperName) => {\n switch (type._tag) {\n case \"Boolean\":\n return undefined;\n case \"Choice\":\n return choiceCompletion(helperName, type.values);\n case \"Path\":\n if (type.pathType === \"directory\") return `COMPREPLY=( $(compgen -d -- \"$cur\") )`;\n return `COMPREPLY=( $(compgen -f -- \"$cur\") )`;\n default:\n return undefined;\n }\n};\nconst argCompletion = (type, helperName) => {\n switch (type._tag) {\n case \"Choice\":\n return choiceCompletion(helperName, type.values);\n case \"Path\":\n if (type.pathType === \"directory\") return `COMPREPLY=( $(compgen -d -- \"$cur\") )`;\n return `COMPREPLY=( $(compgen -f -- \"$cur\") )`;\n default:\n return undefined;\n }\n};\n// ---------------------------------------------------------------------------\n// Generator\n// ---------------------------------------------------------------------------\nconst generateFunction = (descriptor, parentPath, lines, helperName) => {\n const currentPath = [...parentPath, descriptor.name];\n const funcName = `_${currentPath.map(sanitizeFunctionName).join(\"_\")}`;\n lines.push(`${funcName}()`);\n lines.push(`{`);\n lines.push(` local cur prev words cword i`);\n lines.push(parentPath.length === 0 ? ` local _command_index=0` : ` local _command_index=\"$1\"`);\n // Keep values containing COMP_WORDBREAKS characters in one word.\n lines.push(` _init_completion -n \"$COMP_WORDBREAKS\" || return`);\n if (parentPath.length === 0) {\n // Subcommand functions inherit this through Bash's dynamic scope.\n lines.push(` local _comp_word=\"$2\"`);\n }\n lines.push(``);\n // Build flag-value dispatch\n const flagsWithValues = descriptor.flags.filter(takesSeparateValue);\n if (flagsWithValues.length > 0) {\n lines.push(` # Flag value completions`);\n lines.push(` case \"$prev\" in`);\n for (const flag of flagsWithValues) {\n const longNames = [`--${flag.name}`];\n for (const alias of flag.aliases) {\n longNames.push(alias.length === 1 ? `-${alias}` : `--${alias}`);\n }\n const completion = flagValueCompletion(flag.type, helperName);\n if (completion) {\n lines.push(` ${longNames.join(\"|\")})`);\n lines.push(` ${completion}`);\n lines.push(` return`);\n lines.push(` ;;`);\n }\n }\n lines.push(` esac`);\n lines.push(``);\n }\n // Subcommand dispatch\n if (descriptor.subcommands.length > 0) {\n lines.push(` # Subcommand dispatch`);\n lines.push(` local cmd _skip_next=0`);\n lines.push(` for ((i = _command_index + 1; i < cword; i++)); do`);\n lines.push(` if (( _skip_next )); then`);\n lines.push(` _skip_next=0`);\n lines.push(` continue`);\n lines.push(` fi`);\n lines.push(` case \"\\${words[i]}\" in`);\n for (const flag of descriptor.flags) {\n if (!takesSeparateValue(flag)) continue;\n const forms = flagNamesForWordlist(flag);\n lines.push(` ${forms.join(\"|\")}) _skip_next=1 ;;`);\n lines.push(` ${forms.map(form => `${form}=*`).join(\"|\")}) ;;`);\n }\n for (const sub of descriptor.subcommands) {\n const subFuncName = `_${[...currentPath, sub.name].map(sanitizeFunctionName).join(\"_\")}`;\n lines.push(` ${sub.name})`);\n lines.push(` ${subFuncName} \"$i\"`);\n lines.push(` return`);\n lines.push(` ;;`);\n }\n lines.push(` esac`);\n lines.push(` done`);\n lines.push(``);\n }\n // Filter already-used flags (entire alias group removed when any form is used)\n buildFlagGroupDeclarations(descriptor.flags, lines);\n if (descriptor.flags.length > 0 || descriptor.subcommands.length > 0) {\n lines.push(` # Complete flags (filtered) and subcommands`);\n lines.push(` if [[ \"$cur\" == -* ]]; then`);\n if (descriptor.flags.length > 0) {\n lines.push(` COMPREPLY=( $(compgen -W \"$_filtered_flags\" -- \"$cur\") )`);\n }\n lines.push(` return`);\n lines.push(` fi`);\n lines.push(``);\n }\n // Positional argument completion\n const argsWithCompletions = descriptor.arguments.flatMap((argument, index) => {\n const completion = argCompletion(argument.type, helperName);\n return completion === undefined ? [] : [{\n argument,\n completion,\n index\n }];\n });\n if (argsWithCompletions.length > 0) {\n lines.push(` # Positional argument completions`);\n lines.push(` local _position=0 _skip_next=0 _end_of_options=0`);\n lines.push(` for ((i = _command_index + 1; i < cword; i++)); do`);\n lines.push(` if (( _skip_next )); then`);\n lines.push(` _skip_next=0`);\n lines.push(` continue`);\n lines.push(` fi`);\n lines.push(` if (( _end_of_options )); then`);\n lines.push(` ((_position += 1))`);\n lines.push(` continue`);\n lines.push(` fi`);\n lines.push(` case \"\\${words[i]}\" in`);\n lines.push(` --) _end_of_options=1 ;;`);\n for (const flag of descriptor.flags) {\n const forms = flagNamesForWordlist(flag);\n if (!takesSeparateValue(flag)) {\n lines.push(` ${forms.join(\"|\")}) ;;`);\n } else {\n lines.push(` ${forms.join(\"|\")}) _skip_next=1 ;;`);\n lines.push(` ${forms.map(form => `${form}=*`).join(\"|\")}) ;;`);\n }\n }\n lines.push(` -*) ;;`);\n lines.push(` *) ((_position += 1)) ;;`);\n lines.push(` esac`);\n lines.push(` done`);\n lines.push(` case \"$_position\" in`);\n for (const {\n argument,\n completion,\n index\n } of argsWithCompletions) {\n if (argument.variadic) continue;\n lines.push(` ${index})`);\n lines.push(` ${completion}`);\n lines.push(` return`);\n lines.push(` ;;`);\n }\n lines.push(` esac`);\n const variadic = argsWithCompletions.find(({\n argument\n }) => argument.variadic);\n if (variadic !== undefined) {\n lines.push(` if (( _position >= ${variadic.index} )); then`);\n lines.push(` ${variadic.completion}`);\n lines.push(` return`);\n lines.push(` fi`);\n }\n } else if (descriptor.subcommands.length > 0) {\n const subNames = descriptor.subcommands.map(s => s.name);\n lines.push(` COMPREPLY=( $(compgen -W '${subNames.join(\" \")}' -- \"$cur\") )`);\n }\n lines.push(`}`);\n lines.push(``);\n // Recurse into subcommands\n for (const sub of descriptor.subcommands) {\n generateFunction(sub, currentPath, lines, helperName);\n }\n};\n/**\n * @internal\n */\nexport const generate = (executableName, descriptor) => {\n const lines = [];\n const safeName = sanitizeFunctionName(executableName);\n // Sanitized command names cannot contain `-`.\n const helperName = `_${safeName}--choices`;\n lines.push(`###-begin-${escapeForBash(executableName)}-completions-###`);\n lines.push(`#`);\n lines.push(`# Static completion script for Bash`);\n lines.push(`#`);\n lines.push(`# Installation:`);\n lines.push(`# ${escapeForBash(executableName)} --completions bash >> ~/.bashrc`);\n lines.push(`#`);\n lines.push(``);\n // Fallback for environments without bash-completion. Preserve word-break\n // characters inside values.\n lines.push(`if ! type _init_completion &>/dev/null; then`);\n lines.push(` _init_completion()`);\n lines.push(` {`);\n lines.push(` COMPREPLY=()`);\n lines.push(` local _i _j=0 _piece _line=\"$COMP_LINE\"`);\n lines.push(` words=(\"\\${COMP_WORDS[0]}\")`);\n lines.push(` cword=0`);\n lines.push(` _line=\"\\${_line#*\"\\${COMP_WORDS[0]}\"}\"`);\n lines.push(` for ((_i = 1; _i < \\${#COMP_WORDS[@]}; _i++)); do`);\n lines.push(` _piece=\"\\${COMP_WORDS[_i]}\"`);\n lines.push(` if [[ \"$_line\" == [[:blank:]]* ]]; then`);\n lines.push(` ((_j++))`);\n lines.push(` words[_j]=\"$_piece\"`);\n lines.push(` else`);\n lines.push(` words[_j]=\"\\${words[_j]}$_piece\"`);\n lines.push(` fi`);\n lines.push(` ((_i == COMP_CWORD)) && cword=$_j`);\n lines.push(` _line=\"\\${_line#*\"$_piece\"}\"`);\n lines.push(` done`);\n lines.push(` cur=\"\\${words[cword]}\"`);\n lines.push(` prev=\"\"`);\n lines.push(` ((cword > 0)) && prev=\"\\${words[cword-1]}\"`);\n lines.push(` return 0`);\n lines.push(` }`);\n lines.push(`fi`);\n lines.push(``);\n choicesHelper(helperName, lines);\n generateFunction(descriptor, [], lines, helperName);\n lines.push(`complete -F _${safeName} ${escapeForBash(executableName)}`);\n lines.push(`###-end-${escapeForBash(executableName)}-completions-###`);\n return lines.join(\"\\n\");\n};\n//# sourceMappingURL=bash.js.map","import { takesSeparateValue } from \"./descriptor.js\";\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\nconst escapeFishString = s => s.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\");\n/** Escape choices for Fish's second expansion of `complete -a`. */\nconst escapeFishChoice = s => escapeFishString(s.replace(/[^A-Za-z0-9_.,/@%+-]/gu, \"\\\\$&\"));\n/**\n * Build a Fish condition that checks the current subcommand context.\n *\n * For root-level completions with subcommands: `__fish_use_subcommand`\n * For nested commands: verify the full parent path is active AND none of its\n * child subcommands have been entered yet.\n */\nconst subcommandCondition = (parentPath, childSubcommandNames) => {\n if (parentPath.length === 0) {\n if (childSubcommandNames.length > 0) {\n return `__fish_use_subcommand`;\n }\n return ``;\n }\n const parentCondition = parentPath.map(parent => `__fish_seen_subcommand_from ${parent}`).join(\"; and \");\n if (childSubcommandNames.length > 0) {\n // Show only when the parent path is active but no child subcommand has been entered\n return `${parentCondition}; and not __fish_seen_subcommand_from ${childSubcommandNames.join(\" \")}`;\n }\n return parentCondition;\n};\n/**\n * Build a __fish_contains_opt condition that checks whether any form of this\n * flag has already been typed. Returns the condition string without wrapping\n * quotes (the caller adds those).\n */\nconst flagContainsOptCondition = flag => {\n const optArgs = [];\n for (const alias of flag.aliases) {\n if (alias.length === 1) {\n optArgs.push(`-s ${alias}`);\n }\n }\n // Long names (fish __fish_contains_opt uses bare words for long opts)\n optArgs.push(flag.name);\n for (const alias of flag.aliases) {\n if (alias.length > 1) {\n optArgs.push(alias);\n }\n }\n if (flag.type._tag === \"Boolean\") {\n optArgs.push(`no-${flag.name}`);\n }\n return `not __fish_contains_opt ${optArgs.join(\" \")}`;\n};\n/** Hide used value flags without suppressing their value completions. */\nconst valueFlagDedupCondition = flag => {\n const forms = [`--${flag.name}`];\n for (const alias of flag.aliases) {\n forms.push(alias.length === 1 ? `-${alias}` : `--${alias}`);\n }\n return `begin; ${flagContainsOptCondition(flag)}; or contains -- (commandline -poc)[-1] ${forms.join(\" \")}; end`;\n};\nconst flagCompletionArgs = flag => {\n const args = [`-l ${flag.name}`];\n for (const alias of flag.aliases) {\n if (alias.length === 1) {\n args.push(`-s ${alias}`);\n } else {\n args.push(`-l ${alias}`);\n }\n }\n if (flag.description) {\n args.push(`-d '${escapeFishString(flag.description)}'`);\n }\n const valueArgs = takesSeparateValue(flag) ? flagValueArgs(flag.type) : undefined;\n if (valueArgs) {\n args.push(valueArgs);\n }\n return args;\n};\nconst flagValueArgs = type => {\n switch (type._tag) {\n case \"Boolean\":\n return undefined;\n case \"Choice\":\n return `-r -f -a '${type.values.map(escapeFishChoice).join(\" \")}'`;\n case \"Path\":\n if (type.pathType === \"directory\") return `-r -F`;\n return `-r -F`;\n default:\n // -r: requires a value, -f: don't fall back to file completion\n return `-r -f`;\n }\n};\nconst argValueArgs = type => {\n switch (type._tag) {\n case \"Choice\":\n return `-r -f -a '${type.values.map(escapeFishChoice).join(\" \")}'`;\n case \"Path\":\n return `-r -F`;\n default:\n return undefined;\n }\n};\n// ---------------------------------------------------------------------------\n// Generator\n// ---------------------------------------------------------------------------\nconst generateCompletions = (executableName, descriptor, parentPath, lines) => {\n const allSubNames = descriptor.subcommands.map(s => s.name);\n const condition = subcommandCondition(parentPath, allSubNames);\n const conditionArg = condition ? `-n '${condition}'` : ``;\n // Suppress default file completion unless the command has path-type\n // positional arguments. Without this, fish falls back to listing files\n // even when only flags are valid.\n const hasPathArgs = descriptor.arguments.some(a => a.type._tag === \"Path\");\n if (!hasPathArgs) {\n const parts = [`complete -c ${executableName}`];\n if (conditionArg) parts.push(conditionArg);\n parts.push(`-f`);\n lines.push(parts.join(\" \"));\n }\n // Subcommand completions\n for (const sub of descriptor.subcommands) {\n const parts = [`complete -c ${executableName}`];\n if (conditionArg) parts.push(conditionArg);\n parts.push(`-f -a '${escapeFishString(sub.name)}'`);\n if (sub.description) {\n parts.push(`-d '${escapeFishString(sub.description)}'`);\n }\n lines.push(parts.join(\" \"));\n }\n // Flag completions\n for (const flag of descriptor.flags) {\n const dedup = takesSeparateValue(flag) ? valueFlagDedupCondition(flag) : flagContainsOptCondition(flag);\n const flagCondition = condition ? `${condition}; and ${dedup}` : dedup;\n const flagCondArg = flagCondition ? `-n '${flagCondition}'` : ``;\n const parts = [`complete -c ${executableName}`];\n if (flagCondArg) parts.push(flagCondArg);\n parts.push(...flagCompletionArgs(flag));\n lines.push(parts.join(\" \"));\n // Boolean negation\n if (flag.type._tag === \"Boolean\") {\n const negParts = [`complete -c ${executableName}`];\n if (flagCondArg) negParts.push(flagCondArg);\n negParts.push(`-l no-${flag.name}`);\n if (flag.description) {\n negParts.push(`-d '${escapeFishString(`Disable ${flag.name}`)}'`);\n }\n lines.push(negParts.join(\" \"));\n }\n }\n // Flags as -a entries for bare <TAB> visibility.\n // Fish only shows -l/-s entries when the current word starts with -, so\n // without this, flags are invisible on bare <TAB>. Guarded to only show\n // when NOT already typing an option (avoids duplication with -l/-s above)\n // and hidden once a flag has been used (__fish_contains_opt).\n if (descriptor.flags.length > 0) {\n const notDash = `not string match -q -- \"-*\" (commandline -ct)`;\n const bareBase = condition ? `${condition}; and ${notDash}` : notDash;\n for (const flag of descriptor.flags) {\n const bareCondition = `${bareBase}; and ${flagContainsOptCondition(flag)}`;\n const isBoolean = flag.type._tag === \"Boolean\";\n const parts = [`complete -c ${executableName}`];\n parts.push(`-n '${bareCondition}'`);\n parts.push(`-f -a '--${flag.name}'`);\n if (flag.description) {\n parts.push(`-d '${escapeFishString(flag.description)}'`);\n }\n lines.push(parts.join(\" \"));\n if (isBoolean) {\n const negParts = [`complete -c ${executableName}`];\n negParts.push(`-n '${bareCondition}'`);\n negParts.push(`-f -a '--no-${flag.name}'`);\n if (flag.description) {\n negParts.push(`-d '${escapeFishString(`Disable ${flag.name}`)}'`);\n }\n lines.push(negParts.join(\" \"));\n }\n }\n }\n // Argument completions (type hints only)\n for (const arg of descriptor.arguments) {\n const valueArg = argValueArgs(arg.type);\n if (valueArg) {\n const parts = [`complete -c ${executableName}`];\n if (conditionArg) parts.push(conditionArg);\n parts.push(valueArg);\n if (arg.description) {\n parts.push(`-d '${escapeFishString(arg.description)}'`);\n }\n lines.push(parts.join(\" \"));\n }\n }\n // Recurse into subcommands\n for (const sub of descriptor.subcommands) {\n generateCompletions(executableName, sub, [...parentPath, sub.name], lines);\n }\n};\n/**\n * @internal\n */\nexport const generate = (executableName, descriptor) => {\n const lines = [];\n lines.push(`###-begin-${executableName}-completions-###`);\n lines.push(`#`);\n lines.push(`# Static completion script for Fish`);\n lines.push(`#`);\n lines.push(`# Installation:`);\n lines.push(`# ${executableName} --completions fish > ~/.config/fish/completions/${executableName}.fish`);\n lines.push(`#`);\n lines.push(``);\n generateCompletions(executableName, descriptor, [], lines);\n lines.push(``);\n lines.push(`###-end-${executableName}-completions-###`);\n return lines.join(\"\\n\");\n};\n//# sourceMappingURL=fish.js.map","/**\n * Encode non-ASCII and control characters as `[char]` code units. Windows\n * PowerShell 5.1 can misread BOM-less UTF-8 as ANSI, turning some bytes into\n * PowerShell quote delimiters.\n */\nconst quotePs = s => {\n const parts = [];\n let literal = \"\";\n for (let i = 0; i < s.length; i++) {\n const code = s.charCodeAt(i);\n if (code >= 0x20 && code < 0x80) {\n literal += s[i] === \"'\" ? \"''\" : s[i];\n continue;\n }\n if (literal !== \"\" || parts.length === 0) parts.push(`'${literal}'`);\n literal = \"\";\n parts.push(`[char]0x${code.toString(16).toUpperCase().padStart(4, \"0\")}`);\n }\n if (literal !== \"\" || parts.length === 0) parts.push(`'${literal}'`);\n return parts.length === 1 ? parts[0] : `(${parts.join(\" + \")})`;\n};\nconst psArray = items => `@(${items.map(quotePs).join(\", \")})`;\nconst psOptional = s => s ? quotePs(s) : \"$null\";\nconst sanitize = s => s.replace(/[^a-zA-Z0-9_]/g, \"_\");\nconst flagForms = flag => [`--${flag.name}`, ...flag.aliases.map(alias => alias.length === 1 ? `-${alias}` : `--${alias}`)];\nconst valueFields = type => `values = ${psArray(type._tag === \"Choice\" ? type.values : [])}; ` + `pathType = ${type._tag === \"Path\" ? quotePs(type.pathType) : \"$null\"}`;\nconst flagEntry = flag => `@{ name = ${quotePs(flag.name)}; forms = ${psArray(flagForms(flag))}; ` + `takesValue = $${flag.type._tag !== \"Boolean\"}; ` + (flag.optionalValue === true ? `optionalValue = $true; ` : \"\") + `${valueFields(flag.type)}; ` + `description = ${psOptional(flag.description)} }`;\nconst argumentEntry = argument => `@{ name = ${quotePs(argument.name)}; variadic = $${argument.variadic}; ${valueFields(argument.type)}; ` + `description = ${psOptional(argument.description)} }`;\nconst pushList = (lines, field, entries) => {\n if (entries.length === 0) {\n lines.push(` ${field} = @()`);\n return;\n }\n lines.push(` ${field} = @(`);\n for (const entry of entries) {\n lines.push(` ${entry}`);\n }\n lines.push(` )`);\n};\n/**\n * Emit one context per subcommand path. Subcommands are case-sensitive, so\n * contexts go in an ordinal hashtable instead of a hash literal, whose keys\n * ignore case.\n */\nconst generateContexts = (dataName, descriptor, path, lines, seen) => {\n const key = path.join(\" \");\n if (seen.has(key)) return;\n seen.add(key);\n lines.push(`${dataName}[${quotePs(key)}] = @{`);\n pushList(lines, \"subcommands\", descriptor.subcommands.map(sub => `@{ name = ${quotePs(sub.name)}; description = ${psOptional(sub.description)} }`));\n pushList(lines, \"flags\", descriptor.flags.map(flagEntry));\n pushList(lines, \"arguments\", descriptor.arguments.map(argumentEntry));\n lines.push(`}`);\n for (const sub of descriptor.subcommands) {\n generateContexts(dataName, sub, [...path, sub.name], lines, seen);\n }\n};\n/**\n * Replay the committed words with the CLI lexer and parser rules: `--`, short\n * flag clusters, inline values, boolean literals, negative numbers, and\n * subcommand selection by the first value only.\n */\nconst completer = dataName => String.raw` param($wordToComplete, $commandAst, $cursorPosition)\n\n $spec = ${dataName}\n $results = [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new()\n $booleanLiterals = @('true', 'yes', 'on', '1', 'y', 'false', 'no', 'off', '0', 'n')\n\n $index = {\n param($context)\n $lookup = [hashtable]::new([System.StringComparer]::Ordinal)\n foreach ($flag in $context.flags) {\n foreach ($form in $flag.forms) { $lookup[$form] = $flag }\n }\n $lookup\n }\n\n $add = {\n param([string]$value, [string]$type, $tooltip, [string]$typed, [string]$textPrefix)\n if (-not $value.StartsWith($typed, [System.StringComparison]::OrdinalIgnoreCase)) { return }\n $text = $value\n if ($value -notmatch '^[\\w./:%+=\\\\-]+$') { $text = \"'\" + ($value -replace \"['\\u2018-\\u201b]\", '$0$0') + \"'\" }\n $text = $textPrefix + $text\n $label = $value\n if (-not $label) { $label = $text }\n if (-not $tooltip) { $tooltip = $label }\n $results.Add([System.Management.Automation.CompletionResult]::new($text, $label, $type, $tooltip))\n }\n\n $addValues = {\n param($entry, [string]$typed, [string]$textPrefix)\n foreach ($value in $entry.values) {\n if ($textPrefix -eq '' -and (& $optionLike $value)) { continue }\n & $add $value 'ParameterValue' $entry.description $typed $textPrefix\n }\n if ($entry.pathType) {\n foreach ($file in [System.Management.Automation.CompletionCompleters]::CompleteFilename($typed)) {\n if ($entry.pathType -eq 'directory' -and $file.ResultType -ne 'ProviderContainer') { continue }\n $results.Add([System.Management.Automation.CompletionResult]::new($textPrefix + $file.CompletionText, $file.ListItemText, $file.ResultType, $file.ToolTip))\n }\n }\n }\n\n $addFlags = {\n param([string]$typed)\n foreach ($flag in $context.flags) {\n if ($used.ContainsKey($flag.name)) { continue }\n foreach ($form in $flag.forms) {\n & $add $form 'ParameterName' $flag.description $typed ''\n }\n if (-not $flag.takesValue) {\n $tooltip = $null\n if ($flag.description) { $tooltip = 'Disable ' + $flag.name }\n & $add ('--no-' + $flag.name) 'ParameterName' $tooltip $typed ''\n }\n }\n }\n\n # As in the CLI lexer, nothing after '--' is an option, and negative numbers\n # and a lone '-' are values.\n $optionLike = {\n param([string]$word)\n -not $endOfOptions -and $word -match '^-.' -and $word -notmatch '^-(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$'\n }\n\n # A typed value that has no candidates completes to itself, so the engine\n # does not fall back to listing files.\n $keepTyped = {\n if ($results.Count -eq 0 -and $current) {\n $results.Add([System.Management.Automation.CompletionResult]::new($current, $current, 'ParameterValue', $current))\n }\n }\n\n $path = ''\n $context = $spec[$path]\n $lookup = & $index $context\n $used = [hashtable]::new([System.StringComparer]::Ordinal)\n $pending = $null\n $endOfOptions = $false\n $position = 0\n\n # The engine strips the quotes from a quoted word.\n $typed = [string]$wordToComplete\n if ($typed -match '^([''\"])(.*?)\\1?$') { $typed = $Matches[2] }\n $current = $null\n\n $elements = $commandAst.CommandElements\n for ($i = 1; $i -lt $elements.Count; $i++) {\n $element = $elements[$i]\n $word = $element.Extent.Text\n if ($element -is [System.Management.Automation.Language.StringConstantExpressionAst]) { $word = $element.Value }\n if ($element.Extent.EndOffset -ge $cursorPosition) {\n if ($element -is [System.Management.Automation.Language.ConstantExpressionAst] -and $element.Extent.StartOffset -le $cursorPosition) {\n $current = $element.Extent.Text\n if ($element.Extent.EndOffset -eq $cursorPosition) { $typed = $word }\n }\n break\n }\n\n # A flag takes the next word as its value unless it is an option or '--';\n # a boolean flag only takes a boolean literal.\n $isOption = & $optionLike $word\n if ($null -ne $pending) {\n $flag = $pending\n $pending = $null\n if ($flag.takesValue) {\n if (-not $isOption) { continue }\n } elseif ($booleanLiterals -ccontains $word) { continue }\n }\n if ($endOfOptions) { $position++; continue }\n if ($word -ceq '--') { $endOfOptions = $true; continue }\n\n if ($isOption) {\n $hasValue = $word.Contains('=')\n if ($hasValue) {\n $forms = @($word.Substring(0, $word.IndexOf('=')))\n } elseif ($word.StartsWith('--')) {\n $forms = @($word)\n } else {\n $forms = @(foreach ($char in $word.Substring(1).ToCharArray()) { '-' + $char })\n }\n foreach ($form in $forms) {\n $pending = $null\n $flag = $lookup[$form]\n if ($null -eq $flag) {\n if ($form.StartsWith('--no-')) {\n $name = $form.Substring(5)\n $flag = $lookup['--' + $name]\n if ($null -ne $flag -and -not $flag.takesValue -and $flag.name -ceq $name) { $used[$name] = $true }\n }\n continue\n }\n $used[$flag.name] = $true\n # A flag with an optional value only takes a value attached with '='.\n if (-not $hasValue -and -not $flag.optionalValue) { $pending = $flag }\n }\n continue\n }\n\n if ($position -eq 0 -and $context.subcommands.name -ccontains $word) {\n if ($path) { $path = $path + ' ' + $word } else { $path = $word }\n $context = $spec[$path]\n $lookup = & $index $context\n $used = [hashtable]::new([System.StringComparer]::Ordinal)\n continue\n }\n $position++\n }\n\n $typedIsOption = & $optionLike $typed\n if ($null -ne $pending -and $pending.takesValue -and -not $typedIsOption) {\n & $addValues $pending $typed ''\n & $keepTyped\n return $results\n }\n\n if ($typedIsOption) {\n if ($typed -match '^(-[^=]+)=(.*)$') {\n $form = $Matches[1]\n $flag = $lookup[$form]\n if ($null -ne $flag -and $flag.takesValue) {\n & $addValues $flag $Matches[2] ($form + '=')\n & $keepTyped\n }\n } else {\n & $addFlags $typed\n }\n return $results\n }\n\n if (-not $endOfOptions -and $position -eq 0) {\n foreach ($sub in $context.subcommands) {\n & $add $sub.name 'Command' $sub.description $typed ''\n }\n }\n\n $arguments = $context.arguments\n if ($position -lt $arguments.Count) {\n & $addValues $arguments[$position] $typed ''\n } elseif ($arguments.Count -gt 0 -and $arguments[-1].variadic) {\n & $addValues $arguments[-1] $typed ''\n }\n\n if (-not $endOfOptions) {\n & $addFlags $typed\n }\n return $results`;\n/** @internal */\nexport const generate = (executableName, descriptor) => {\n const dataName = `$global:_${sanitize(executableName)}_Completions`;\n const lines = [];\n lines.push(`###-begin-${executableName}-completions-###`);\n lines.push(`#`);\n lines.push(`# Static completion script for PowerShell`);\n lines.push(`#`);\n lines.push(`# Installation:`);\n // `>>` on Windows PowerShell 5.1 appends UTF-16LE to the profile, so the\n // script goes in its own file.\n lines.push(`# ${executableName} --completions powershell > ${executableName}-completion.ps1`);\n lines.push(`# then add this line to your $PROFILE (use the full path to the file):`);\n lines.push(`# . <PATH>\\\\${executableName}-completion.ps1`);\n lines.push(`#`);\n lines.push(``);\n lines.push(`${dataName} = [hashtable]::new([System.StringComparer]::Ordinal)`);\n generateContexts(dataName, descriptor, [], lines, new Set());\n lines.push(``);\n lines.push(`Register-ArgumentCompleter -Native -CommandName ${quotePs(executableName)} -ScriptBlock {`);\n lines.push(completer(dataName));\n lines.push(`}`);\n lines.push(``);\n lines.push(`###-end-${executableName}-completions-###`);\n return lines.join(\"\\n\");\n};\n//# sourceMappingURL=powershell.js.map","// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\nconst escapeZsh = s => s.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"'\\\\''\").replace(/:/g, \"\\\\:\");\nconst escapeZshExplanation = s => escapeZsh(s).replace(/]/g, \"\\\\]\");\n/** Escape choices for the second parse of a Zsh `_arguments` action. */\nconst escapeZshChoice = s => s.replace(/[^A-Za-z0-9_.,/@%+-]/gu, \"\\\\$&\").replace(/'/g, \"'\\\\''\");\nconst sanitize = s => s.replace(/[^a-zA-Z0-9_]/g, \"_\");\n/**\n * All forms of a flag (--name, -alias, --no-name) for the exclusion group.\n */\nconst allForms = flag => {\n const forms = [`--${flag.name}`];\n for (const alias of flag.aliases) {\n forms.push(alias.length === 1 ? `-${alias}` : `--${alias}`);\n }\n if (flag.type._tag === \"Boolean\") {\n forms.push(`--no-${flag.name}`);\n }\n return forms;\n};\nconst valueAction = type => {\n switch (type._tag) {\n case \"Boolean\":\n return \"\";\n case \"Choice\":\n return `:value:(${type.values.map(escapeZshChoice).join(\" \")})`;\n case \"Path\":\n return type.pathType === \"directory\" ? `:directory:_directories` : `:file:_files`;\n case \"Int\":\n return `:integer:`;\n case \"Finite\":\n return `:float:`;\n case \"Date\":\n return `:date:`;\n default:\n return `:value:`;\n }\n};\nconst argAction = type => {\n switch (type._tag) {\n case \"Choice\":\n return `(${type.values.map(escapeZshChoice).join(\" \")})`;\n case \"Path\":\n return type.pathType === \"directory\" ? `_directories` : `_files`;\n default:\n return ``;\n }\n};\n/**\n * Produce _arguments optspecs for a single flag. Each spec is a complete,\n * single-quoted string — no brace expansion, no line continuations.\n */\nconst flagSpecs = flag => {\n const specs = [];\n const desc = flag.description ? `[${escapeZshExplanation(flag.description)}]` : \"\";\n // An optional value must follow `=` in the same word (`--name=-`), and `::`\n // marks it optional.\n const optional = flag.optionalValue === true && flag.type._tag !== \"Boolean\";\n const valueSuffix = optional ? \"=-\" : \"\";\n const action = optional ? `:${valueAction(flag.type)}` : valueAction(flag.type);\n const excl = `(${allForms(flag).join(\" \")})`;\n // Primary long name\n specs.push(`'${excl}--${flag.name}${valueSuffix}${desc}${action}'`);\n // Aliases\n for (const alias of flag.aliases) {\n const prefix = alias.length === 1 ? \"-\" : \"--\";\n specs.push(`'${excl}${prefix}${alias}${valueSuffix}${desc}${action}'`);\n }\n // Boolean negation\n if (flag.type._tag === \"Boolean\") {\n const negDesc = flag.description ? `[${escapeZshExplanation(`Disable ${flag.name}`)}]` : \"\";\n specs.push(`'${excl}--no-${flag.name}${negDesc}'`);\n }\n return specs;\n};\nconst argSpec = arg => {\n const desc = arg.description ? escapeZsh(arg.description) : arg.name;\n const action = argAction(arg.type);\n const prefix = arg.variadic ? \"*\" : \"\";\n return `'${prefix}:${desc}:${action}'`;\n};\n// ---------------------------------------------------------------------------\n// Generator\n// ---------------------------------------------------------------------------\nconst generateFunction = (descriptor, parentPath, lines) => {\n const currentPath = [...parentPath, descriptor.name];\n const funcName = `_${currentPath.map(sanitize).join(\"_\")}`;\n lines.push(`${funcName}() {`);\n if (descriptor.subcommands.length > 0) {\n // _arguments -C requires these locals for the state machine\n lines.push(` local context state state_descr line`);\n lines.push(` typeset -A opt_args`);\n lines.push(``);\n // Subcommand list\n lines.push(` local -a commands`);\n lines.push(` commands=(`);\n for (const sub of descriptor.subcommands) {\n const desc = sub.description ? escapeZsh(sub.description) : \"\";\n lines.push(` '${sub.name}:${desc}'`);\n }\n lines.push(` )`);\n lines.push(``);\n // Build specs array to avoid brace expansion / line continuation issues\n lines.push(` local -a specs`);\n lines.push(` specs=(`);\n for (const flag of descriptor.flags) {\n for (const spec of flagSpecs(flag)) {\n lines.push(` ${spec}`);\n }\n }\n if (descriptor.arguments.length > 0) {\n lines.push(` -`);\n lines.push(` parent-arguments`);\n for (const arg of descriptor.arguments) {\n lines.push(` ${argSpec(arg)}`);\n }\n lines.push(` -`);\n lines.push(` subcommands`);\n }\n lines.push(` '1:command:->command'`);\n lines.push(` '*::arg:->args'`);\n lines.push(` )`);\n lines.push(``);\n lines.push(` _arguments -C \"\\${specs[@]}\"`);\n lines.push(``);\n // State dispatch\n lines.push(` case \"$state\" in`);\n lines.push(` command)`);\n lines.push(` _describe -t commands 'commands' commands`);\n lines.push(` ;;`);\n lines.push(` args)`);\n lines.push(` case \"$words[1]\" in`);\n for (const sub of descriptor.subcommands) {\n const subFunc = `_${[...currentPath, sub.name].map(sanitize).join(\"_\")}`;\n lines.push(` ${sub.name})`);\n lines.push(` ${subFunc}`);\n lines.push(` ;;`);\n }\n lines.push(` esac`);\n lines.push(` ;;`);\n lines.push(` esac`);\n } else {\n // Leaf command — no subcommands\n const allSpecs = [];\n for (const flag of descriptor.flags) {\n allSpecs.push(...flagSpecs(flag));\n }\n for (const arg of descriptor.arguments) {\n allSpecs.push(argSpec(arg));\n }\n if (allSpecs.length > 0) {\n lines.push(` local -a specs`);\n lines.push(` specs=(`);\n for (const spec of allSpecs) {\n lines.push(` ${spec}`);\n }\n lines.push(` )`);\n lines.push(` _arguments \"\\${specs[@]}\"`);\n }\n }\n lines.push(`}`);\n lines.push(``);\n for (const sub of descriptor.subcommands) {\n generateFunction(sub, currentPath, lines);\n }\n};\n/**\n * @internal\n */\nexport const generate = (executableName, descriptor) => {\n const lines = [];\n const safeName = sanitize(executableName);\n lines.push(`#compdef ${executableName}`);\n lines.push(`###-begin-${executableName}-completions-###`);\n lines.push(`#`);\n lines.push(`# Static completion script for Zsh`);\n lines.push(`#`);\n lines.push(`# Installation:`);\n lines.push(`# ${executableName} --completions zsh > ~/.zsh/completions/_${executableName}`);\n lines.push(`# then add ~/.zsh/completions to your fpath`);\n lines.push(`#`);\n lines.push(``);\n generateFunction(descriptor, [], lines);\n lines.push(`# Handle both direct invocation and autoload`);\n lines.push(`if [[ \"\\${zsh_eval_context[-1]}\" == \"loadautofunc\" ]]; then`);\n lines.push(` _${safeName} \"$@\"`);\n lines.push(`else`);\n lines.push(` compdef _${safeName} ${executableName}`);\n lines.push(`fi`);\n lines.push(`###-end-${executableName}-completions-###`);\n return lines.join(\"\\n\");\n};\n//# sourceMappingURL=zsh.js.map","/**\n * The `Completions` module turns a plain description of an Effect CLI command\n * tree into shell completion scripts for Bash, Zsh, Fish, and PowerShell. It\n * is the low-level script generation surface used by the unstable CLI package\n * and by the built-in completions global flag.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Bash from \"./internal/completions/bash.js\";\nimport * as Fish from \"./internal/completions/fish.js\";\nimport * as PowerShell from \"./internal/completions/powershell.js\";\nimport * as Zsh from \"./internal/completions/zsh.js\";\n/**\n * Generates a shell completion script for a command descriptor.\n *\n * **When to use**\n *\n * Use when you need an installable completion script from an existing\n * `CommandDescriptor`.\n *\n * **Details**\n *\n * Dispatches by `shell` to Bash, Zsh, Fish, or PowerShell generation and\n * returns a static script string for `executableName`.\n *\n * @see {@link Shell} for supported shell names\n * @see {@link CommandDescriptor} for the command shape used by completion generation\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const generate = (executableName, shell, descriptor) => {\n switch (shell) {\n case \"bash\":\n return Bash.generate(executableName, descriptor);\n case \"zsh\":\n return Zsh.generate(executableName, descriptor);\n case \"fish\":\n return Fish.generate(executableName, descriptor);\n case \"powershell\":\n return PowerShell.generate(executableName, descriptor);\n }\n};\n//# sourceMappingURL=Completions.js.map","import { dual } from \"../Function.js\";\nimport * as Param from \"./Param.js\";\n// -------------------------------------------------------------------------------------\n// constructors\n// -------------------------------------------------------------------------------------\n/**\n * Creates a string flag that accepts text input.\n *\n * **Example** (Creating string flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const nameFlag = Flag.String(\"name\")\n * // Usage: --name \"John Doe\"\n * nameFlag.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const String = name => Param.String(Param.flagKind, name);\n/**\n * Creates a boolean flag that can be enabled or disabled.\n *\n * **Example** (Creating boolean flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const verboseFlag = Flag.Boolean(\"verbose\")\n * // Usage: --verbose (true) or --no-verbose (false)\n * // Omission fails unless the flag is made optional or given a fallback.\n * verboseFlag.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Boolean = name => Param.Boolean(Param.flagKind, name);\n/**\n * Creates an integer flag that accepts whole number input.\n *\n * **Example** (Creating integer flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const portFlag = Flag.Int(\"port\")\n * // Usage: --port 8080\n * portFlag.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Int = name => Param.Int(Param.flagKind, name);\n/**\n * Creates a float flag that accepts decimal number input.\n *\n * **Example** (Creating float flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const rateFlag = Flag.Finite(\"rate\")\n * // Usage: --rate 3.14\n * rateFlag.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Finite = name => Param.Finite(Param.flagKind, name);\n/**\n * Creates a date flag that accepts date input in ISO format.\n *\n * **Example** (Creating date flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const startDateFlag = Flag.Date(\"start-date\")\n * // Usage: --start-date 2023-12-25\n * startDateFlag.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Date = name => Param.Date(Param.flagKind, name);\n/**\n * Constructs option parameters that represent a choice between several inputs.\n * Each tuple maps a string flag value to an associated typed value.\n *\n * **Example** (Creating flag choices with values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // simple enum like choice mapping directly to string union\n * const color = Flag.Literals(\"color\", [\"red\", \"green\", \"blue\"])\n *\n * // choice with custom value mapping\n * const logLevel = Flag.ChoiceWithValue(\"log-level\", [\n * [\"debug\", \"Debug\" as const],\n * [\"info\", \"Info\" as const],\n * [\"error\", \"Error\" as const]\n * ])\n * const kinds = [color.kind, logLevel.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const ChoiceWithValue = (name, choices) => Param.ChoiceWithValue(Param.flagKind, name, choices);\n/**\n * Accepts one of the provided strings. An empty array rejects all input.\n *\n * @see {@link ChoiceWithValue} for mapping accepted strings to different typed values\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Literals = (name, literals) => Param.Literals(Param.flagKind, name, literals);\n/**\n * Creates a path flag that accepts file system path input with validation options.\n *\n * **Example** (Creating path flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Basic path flag\n * const pathFlag = Flag.Path(\"config-path\")\n *\n * // File-only path that must exist\n * const fileFlag = Flag.Path(\"input-file\", {\n * pathType: \"file\",\n * mustExist: true\n * })\n *\n * // Directory path with custom type name\n * const dirFlag = Flag.Path(\"output-dir\", {\n * pathType: \"directory\",\n * typeName: \"OUTPUT_DIRECTORY\"\n * })\n * const kinds = [pathFlag.kind, fileFlag.kind, dirFlag.kind] // => [\"flag\", \"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Path = (name, options) => Param.Path(Param.flagKind, name, options);\n/**\n * Creates a file path flag that accepts file paths with optional existence validation.\n *\n * **Example** (Creating file flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Basic file flag\n * const inputFlag = Flag.File(\"input\")\n * // Usage: --input ./data.json\n *\n * // File that must exist\n * const configFlag = Flag.File(\"config\", { mustExist: true })\n * // Usage: --config ./config.yaml (file must exist)\n * const kinds = [inputFlag.kind, configFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const File = (name, options) => Param.File(Param.flagKind, name, options);\n/**\n * Creates a directory path flag that accepts directory paths with optional existence validation.\n *\n * **Example** (Creating directory flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Basic directory flag\n * const outputFlag = Flag.Directory(\"output\")\n * // Usage: --output ./build\n *\n * // Directory that must exist\n * const sourceFlag = Flag.Directory(\"source\", { mustExist: true })\n * // Usage: --source ./src (directory must exist)\n * const kinds = [outputFlag.kind, sourceFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Directory = (name, options) => Param.Directory(Param.flagKind, name, options);\n/**\n * Creates a string flag whose parsed value is wrapped in `Redacted.Redacted` so\n * stringification and logging redact the value.\n *\n * **Gotchas**\n *\n * Values supplied on the command line may still be visible to the operating\n * system or shell history.\n *\n * **Example** (Creating redacted flags)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Redacted, Stdio, Terminal } from \"effect\"\n * import { Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const passwordFlag = Flag.Redacted(\"password\")\n *\n * const program = Effect.gen(function*() {\n * const [, password] = yield* passwordFlag.parse({\n * arguments: [],\n * flags: { \"password\": [\"abc123\"] }\n * })\n * return Redacted.value(password).length\n * })\n *\n * await Effect.runPromise(program.pipe(Effect.provide(CliTestLayer))) // => 6\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Redacted = name => Param.Redacted(Param.flagKind, name);\n/**\n * Creates a flag that reads and returns file content as a string.\n *\n * **Example** (Reading file text)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const config = Flag.FileText(\"config-file\")\n * // --config-file ./app.json will read the file content\n * config.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileText = name => Param.FileText(Param.flagKind, name);\n/**\n * Creates a flag that reads and parses the content of the specified file.\n *\n * **Details**\n *\n * The parser that is utilized will depend on the specified `format`, or the\n * extension of the file passed on the command-line if no `format` is specified.\n *\n * **Example** (Parsing file contents)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Will use the extension of the file passed on the command line to determine\n * // the parser to use\n * const config = Flag.FileParse(\"config\")\n *\n * // Will use the JSON parser\n * const jsonConfig = Flag.FileParse(\"json-config\", { format: \"json\" })\n * const kinds = [config.kind, jsonConfig.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileParse = (name, options) => Param.FileParse(Param.flagKind, name, options);\n/**\n * Creates a flag that reads and validates file content using the specified\n * schema.\n *\n * **Example** (Validating file contents)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Flag } from \"effect/cli\"\n *\n * const ConfigSchema = Schema.Struct({\n * port: Schema.Number,\n * host: Schema.String\n * })\n *\n * const config = Flag.FileSchema(\"config\", ConfigSchema, { format: \"json\" })\n * config.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const FileSchema = (name, schema, options) => Param.FileSchema(Param.flagKind, name, schema, options);\n/**\n * Creates a flag that parses key=value pairs.\n *\n * **When to use**\n *\n * Use when you need a CLI flag that accepts one or more `key=value`\n * configuration entries.\n *\n * **Details**\n *\n * Requires at least one key=value pair. Multiple pairs are merged into a single\n * record.\n *\n * **Example** (Parsing key-value pairs)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const env = Flag.KeyValuePair(\"env\")\n * // --env FOO=bar --env BAZ=qux will parse to { FOO: \"bar\", BAZ: \"qux\" }\n * env.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const KeyValuePair = name => Param.KeyValuePair(Param.flagKind, name);\n/**\n * A flag that always fails to parse.\n *\n * **Example** (Creating sentinel flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const makeValueFlag = (includeValue: boolean) =>\n * includeValue ? Flag.String(\"value\") : Flag.Never\n *\n * makeValueFlag(true) === Flag.Never // => false\n * makeValueFlag(false) === Flag.Never // => true\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Never = /*#__PURE__*/Param.Never(Param.flagKind);\n// -------------------------------------------------------------------------------------\n// combinators\n// -------------------------------------------------------------------------------------\n/**\n * Adds an alias to a flag, allowing it to be referenced by multiple names.\n *\n * **Example** (Adding flag aliases)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Flag can be used as both --verbose and -v\n * const verboseFlag = Flag.Boolean(\"verbose\").pipe(\n * Flag.withAlias(\"v\")\n * )\n *\n * // Multiple aliases can be chained\n * const helpFlag = Flag.Boolean(\"help\").pipe(\n * Flag.withAlias(\"h\"),\n * Flag.withAlias(\"?\")\n * )\n * const kinds = [verboseFlag.kind, helpFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category aliasing\n * @since 4.0.0\n */\nexport const withAlias = /*#__PURE__*/dual(2, (self, alias) => Param.withAlias(self, alias));\n/**\n * Adds a description to a flag for help documentation.\n *\n * **Example** (Adding help descriptions)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const portFlag = Flag.Int(\"port\").pipe(\n * Flag.withDescription(\"The port number to listen on\")\n * )\n *\n * const configFlag = Flag.File(\"config\").pipe(\n * Flag.withDescription(\"Path to the configuration file\")\n * )\n * const kinds = [portFlag.kind, configFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category metadata\n * @since 4.0.0\n */\nexport const withDescription = /*#__PURE__*/dual(2, (self, description) => Param.withDescription(self, description));\n/**\n * Lets a flag be given without a value, in which case `value` is used.\n *\n * **Details**\n *\n * Follows GNU-style optional values, like `--color[=WHEN]`. An explicit value\n * must be attached with `=` (`--watch=until-done` or `-w=until-done`). A bare\n * `--watch` is parsed as `--watch=<value>`, so `value` is validated like any\n * other input. The flag never consumes the next token, so in `--watch build`,\n * `build` stays a positional argument or subcommand. The flag is still\n * required unless it is made optional or given a default.\n *\n * **Example** (Flag with an optional value)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const watch = Flag.Literals(\"watch\", [\"first-failure\", \"until-done\"]).pipe(\n * Flag.withOptionalValue(\"first-failure\"),\n * Flag.optional\n * )\n * // --watch => Option.some(\"first-failure\")\n * // --watch=until-done => Option.some(\"until-done\")\n * // (absent) => Option.none()\n * // In help: --watch [=choice]\n * watch.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.1.0\n */\nexport const withOptionalValue = /*#__PURE__*/dual(2, (self, value) => Param.withOptionalValue(self, value));\n// -------------------------------------------------------------------------------------\n// metadata\n// -------------------------------------------------------------------------------------\n/**\n * Sets a custom metavar (placeholder name) for the flag in help documentation.\n *\n * **Details**\n *\n * The metavar is displayed in usage text to indicate what value the user should\n * provide. For example, `--output FILE` shows `FILE` as the metavar.\n *\n * **Example** (Setting metavars)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const databaseFlag = Flag.String(\"database-url\").pipe(\n * Flag.withMetavar(\"URL\"),\n * Flag.withDescription(\"Database connection URL\")\n * )\n * // In help: --database-url URL\n *\n * const timeoutFlag = Flag.Int(\"timeout\").pipe(\n * Flag.withMetavar(\"SECONDS\")\n * )\n * // In help: --timeout SECONDS\n * const kinds = [databaseFlag.kind, timeoutFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category metadata\n * @since 4.0.0\n */\nexport const withMetavar = /*#__PURE__*/dual(2, (self, metavar) => Param.withMetavar(self, metavar));\n/**\n * Hides a flag from generated help output and shell completions while keeping\n * it fully parseable on the command line.\n *\n * **When to use**\n *\n * Use when experimental or internal flags should be accepted but not advertised, such as\n * `--experimental-foo`, debug toggles, or escape hatches that are not yet committed to the\n * public CLI surface.\n *\n * **Example** (Hiding a flag from help)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Flag still parses --experimental-foo, but it does not appear in --help.\n * const experimental = Flag.Boolean(\"experimental-foo\").pipe(\n * Flag.withHidden\n * )\n * experimental.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category metadata\n * @since 4.0.0\n */\nexport const withHidden = self => Param.withHidden(self);\n/**\n * Makes a flag optional, returning an Option type that can be None if not provided.\n *\n * **Example** (Making flags optional)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Option, Path, Stdio, Terminal } from \"effect\"\n * import { Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const optionalPort = Flag.optional(Flag.Int(\"port\"))\n *\n * const program = Effect.gen(function*() {\n * const [, port] = yield* optionalPort.parse({\n * arguments: [],\n * flags: { \"port\": [\"4000\"] }\n * })\n * return port\n * })\n *\n * await Effect.runPromise(program.pipe(Effect.provide(CliTestLayer))) // => Option.some(4000)\n * ```\n *\n * @stability unstable\n * @category optionality\n * @since 4.0.0\n */\nexport const optional = param => Param.optional(param);\n/**\n * Provides a default value for a flag when it's not specified.\n *\n * **Example** (Providing default values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const portFlag = Flag.Int(\"port\").pipe(\n * Flag.withDefault(8080)\n * )\n * // If --port is not provided, defaults to 8080\n *\n * const hostFlag = Flag.String(\"host\").pipe(\n * Flag.withDefault(\"localhost\")\n * )\n * // If --host is not provided, defaults to \"localhost\"\n * const kinds = [portFlag.kind, hostFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category optionality\n * @since 4.0.0\n */\nexport const withDefault = Param.withDefault;\n/**\n * Adds a fallback config that is loaded when a required flag is missing.\n *\n * **Example** (Falling back to config)\n *\n * ```ts import.meta.vitest\n * import { Config } from \"effect\"\n * import { Flag } from \"effect/cli\"\n *\n * const verbose = Flag.Boolean(\"verbose\").pipe(\n * Flag.withFallbackConfig(Config.Boolean(\"VERBOSE\"))\n * )\n * verbose.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackConfig = /*#__PURE__*/dual(2, (self, config) => Param.withFallbackConfig(self, config));\n/**\n * Adds a fallback prompt that is shown when a required flag is missing.\n *\n * **Example** (Falling back to prompts)\n *\n * ```ts import.meta.vitest\n * import { Flag, Prompt } from \"effect/cli\"\n *\n * const name = Flag.String(\"name\").pipe(\n * Flag.withFallbackPrompt(Prompt.String({ message: \"Name\" }))\n * )\n * name.kind // => \"flag\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackPrompt = /*#__PURE__*/dual(2, (self, prompt) => Param.withFallbackPrompt(self, prompt));\n/**\n * Transforms the parsed value of a flag using a mapping function.\n *\n * **Example** (Mapping parsed values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Convert string to uppercase\n * const nameFlag = Flag.String(\"name\").pipe(\n * Flag.map((name) => name.toUpperCase())\n * )\n *\n * // Convert port to URL\n * const urlFlag = Flag.Int(\"port\").pipe(\n * Flag.map((port) => `http://localhost:${port}`)\n * )\n * const kinds = [nameFlag.kind, urlFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => Param.map(self, f));\n/**\n * Transforms the parsed value using an Effect that can perform IO operations.\n *\n * **Example** (Mapping parsed values effectfully)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const upperName = Flag.String(\"name\").pipe(\n * Flag.mapEffect((name) => Effect.succeed(name.toUpperCase()))\n * )\n *\n * const [, value] = await Effect.runPromise(\n * upperName.parse({\n * arguments: [],\n * flags: { name: [\"alice\"] }\n * }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => \"ALICE\"\n * ```\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const mapEffect = /*#__PURE__*/dual(2, (self, f) => Param.mapEffect(self, f));\n/**\n * Transforms the parsed value using a function that might throw, with error handling.\n *\n * **Example** (Mapping thrown errors)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * // Parse JSON string with error handling\n * const jsonFlag = Flag.String(\"config\").pipe(\n * Flag.mapTryCatch(\n * (json) => JSON.parse(json),\n * (error) => `Invalid JSON: ${error}`\n * )\n * )\n *\n * // Parse URL with error handling\n * const urlFlag = Flag.String(\"url\").pipe(\n * Flag.mapTryCatch(\n * (url) => new URL(url),\n * (error) => `Invalid URL: ${error}`\n * )\n * )\n *\n * const [, value] = await Effect.runPromise(\n * jsonFlag.parse({\n * arguments: [],\n * flags: { config: ['{\"enabled\":true}'] }\n * }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => { enabled: true }\n * ```\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const mapTryCatch = /*#__PURE__*/dual(3, (self, f, onError) => Param.mapTryCatch(self, f, onError));\n/**\n * Ensures a flag is specified at least a minimum number of times.\n *\n * **Example** (Requiring repeated values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const sourceFlag = Flag.atLeast(Flag.File(\"source\"), 2)\n * // Requires at least 2 source files\n * // Usage: --source file1.ts --source file2.ts\n *\n * const tagFlag = Flag.String(\"tag\").pipe(\n * Flag.atLeast(1)\n * )\n * // Requires at least 1 tag\n * const kinds = [sourceFlag.kind, tagFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category repetition\n * @since 4.0.0\n */\nexport const atLeast = /*#__PURE__*/dual(2, (self, min) => Param.atLeast(self, min));\n/**\n * Ensures a flag is specified at most a maximum number of times.\n *\n * **Example** (Limiting repeated values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const warningFlag = Flag.atMost(Flag.String(\"warning\"), 3)\n * // Allows up to 3 warning flags\n * // Usage: --warning w1 --warning w2 --warning w3\n *\n * const debugFlag = Flag.String(\"debug\").pipe(\n * Flag.atMost(1)\n * )\n * // Allows at most 1 debug flag\n * const kinds = [warningFlag.kind, debugFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category repetition\n * @since 4.0.0\n */\nexport const atMost = /*#__PURE__*/dual(2, (self, max) => Param.atMost(self, max));\n/**\n * Ensures a flag is specified between a minimum and maximum number of times.\n *\n * **Example** (Bounding repeated values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * const hostFlag = Flag.between(Flag.String(\"host\"), 1, 3)\n * // Requires 1-3 host flags\n * // Usage: --host host1 --host host2\n *\n * const excludeFlag = Flag.String(\"exclude\").pipe(\n * Flag.between(0, 5)\n * )\n * // Allows 0-5 exclude patterns\n * const kinds = [hostFlag.kind, excludeFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category repetition\n * @since 4.0.0\n */\nexport const between = /*#__PURE__*/dual(3, (self, min, max) => Param.between(self, min, max));\n/**\n * Transforms and filters a flag value, failing with a custom error if the transformation returns None.\n *\n * **Example** (Filtering and transforming values)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n * import { Flag } from \"effect/cli\"\n *\n * // Parse positive integers only\n * const positiveInt = Flag.Int(\"count\").pipe(\n * Flag.filterMap(\n * (n) => n > 0 ? Option.some(n) : Option.none(),\n * (n) => `Expected positive integer, got ${n}`\n * )\n * )\n *\n * // Parse valid email addresses\n * const emailFlag = Flag.String(\"email\").pipe(\n * Flag.filterMap(\n * (email) => email.includes(\"@\") ? Option.some(email) : Option.none(),\n * (email) => `Invalid email address: ${email}`\n * )\n * )\n * const kinds = [positiveInt.kind, emailFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(3, (self, f, onNone) => Param.filterMap(self, f, onNone));\n/**\n * Filters a flag value based on a predicate, failing with a custom error if the predicate returns false.\n *\n * **Example** (Filtering parsed values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Ensure port is in valid range\n * const portFlag = Flag.Int(\"port\").pipe(\n * Flag.filter(\n * (port) => port >= 1 && port <= 65535,\n * (port) => `Port ${port} is out of range (1-65535)`\n * )\n * )\n *\n * // Ensure non-empty string\n * const nameFlag = Flag.String(\"name\").pipe(\n * Flag.filter(\n * (name) => name.trim().length > 0,\n * () => \"Name cannot be empty\"\n * )\n * )\n * const kinds = [portFlag.kind, nameFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filter = /*#__PURE__*/dual(3, (self, predicate, onFalse) => Param.filter(self, predicate, onFalse));\n/**\n * Provides an alternative flag if the first one fails to parse.\n *\n * **Example** (Falling back to another flag)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/cli\"\n *\n * // Try parsing as integer, fallback to string\n * const valueFlag = Flag.orElse(\n * Flag.Int(\"value\"),\n * () => Flag.String(\"value\")\n * )\n *\n * // Multiple input sources with fallback\n * const configFlag = Flag.orElse(\n * Flag.File(\"config\"),\n * () => Flag.String(\"config-url\")\n * )\n * const kinds = [valueFlag.kind, configFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category alternatives\n * @since 4.0.0\n */\nexport const orElse = /*#__PURE__*/dual(2, (self, that) => Param.orElse(self, that));\n/**\n * Tries to parse with the first flag, then the second, returning a Result that indicates which succeeded.\n *\n * **Example** (Returning fallback results)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Result, Stdio, Terminal } from \"effect\"\n * import { Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const sourceFlag = Flag.orElseResult(\n * Flag.String(\"source\"),\n * () => Flag.String(\"source-url\")\n * )\n *\n * const program = Effect.gen(function*() {\n * const [, source] = yield* sourceFlag.parse({\n * arguments: [],\n * flags: { \"source-url\": [\"https://example.com\"] }\n * })\n * return source\n * })\n *\n * await Effect.runPromise(program.pipe(Effect.provide(CliTestLayer))) // => Result.fail(\"https://example.com\")\n * ```\n *\n * @stability unstable\n * @category alternatives\n * @since 4.0.0\n */\nexport const orElseResult = /*#__PURE__*/dual(2, (self, that) => Param.orElseResult(self, that));\n/**\n * Validates and transforms a flag value using a Schema codec.\n *\n * **Example** (Validating with schemas)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Flag } from \"effect/cli\"\n *\n * const isEmail = Schema.isPattern(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/, {\n * message: \"Must be a valid email address\"\n * })\n *\n * // Parse and validate email with custom schema\n * const EmailSchema = Schema.String.pipe(\n * Schema.check(isEmail)\n * )\n *\n * const emailFlag = Flag.String(\"email\").pipe(\n * Flag.withSchema(EmailSchema)\n * )\n *\n * // Parse JSON configuration with schema validation\n * const ConfigSchema = Schema.Struct({\n * port: Schema.Number,\n * host: Schema.String,\n * ssl: Schema.optional(Schema.Boolean)\n * }).pipe(Schema.fromJsonString)\n *\n * const configFlag = Flag.String(\"config\").pipe(\n * Flag.withSchema(ConfigSchema)\n * )\n * const kinds = [emailFlag.kind, configFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const withSchema = /*#__PURE__*/dual(2, (self, schema) => Param.withSchema(self, schema));\n//# sourceMappingURL=Flag.js.map","/**\n * Help Documentation\n * ================\n *\n * Internal helpers for generating help documentation.\n * Extracted from command.ts to avoid circular dependencies.\n */\nimport * as Effect from \"../../Effect.js\";\nimport * as Param from \"../Param.js\";\nimport { toFlagDoc, toImpl } from \"./command.js\";\nconst dedupeGlobalFlags = flags => {\n const seen = new Set();\n const deduped = [];\n for (const flag of flags) {\n if (seen.has(flag)) {\n continue;\n }\n seen.add(flag);\n deduped.push(flag);\n }\n return deduped;\n};\n/**\n * Returns the resolved command lineage for the provided path.\n * Includes the root command as the first element.\n */\nexport const getCommandsForCommandPath = (command, commandPath) => {\n const commands = [command];\n let currentCommand = command;\n for (let i = 1; i < commandPath.length; i++) {\n const subcommandName = commandPath[i];\n let subcommand = undefined;\n for (const group of currentCommand.subcommands) {\n subcommand = group.commands.find(sub => sub.name === subcommandName);\n if (subcommand) {\n break;\n }\n }\n if (!subcommand) {\n break;\n }\n commands.push(subcommand);\n currentCommand = subcommand;\n }\n return commands;\n};\n/**\n * Returns active global flags for a command path.\n * Built-ins are prepended and declarations are collected root -> leaf.\n */\nexport const getGlobalFlagsForCommandPath = (command, commandPath, builtIns) => {\n const commands = getCommandsForCommandPath(command, commandPath);\n const declared = commands.flatMap(current => toImpl(current).globalFlags);\n return dedupeGlobalFlags([...builtIns, ...declared]);\n};\nconst collectDeclaredGlobalFlags = command => {\n const collected = [];\n const visit = current => {\n const impl = toImpl(current);\n for (const flag of impl.globalFlags) {\n collected.push(flag);\n }\n for (const group of current.subcommands) {\n for (const subcommand of group.commands) {\n visit(subcommand);\n }\n }\n };\n visit(command);\n return dedupeGlobalFlags(collected);\n};\nconst getSharedFlagsForCommandPath = (commands, currentFlags) => {\n if (commands.length <= 1) {\n return [];\n }\n const seen = new Set(currentFlags.map(flag => flag.name));\n const sharedFlags = [];\n for (const ancestor of commands.slice(0, -1)) {\n const ancestorImpl = toImpl(ancestor);\n for (const flag of ancestorImpl.contextConfig.flags) {\n const singles = Param.extractSingleParams(flag);\n const metadata = Param.getParamMetadata(flag);\n for (const single of singles) {\n if (seen.has(single.name)) {\n continue;\n }\n // Hidden ancestor flags are excluded from the shared-flags section\n // of subcommand help, the same way they're excluded from the owning\n // command's own help output.\n if (single.hidden) {\n continue;\n }\n seen.add(single.name);\n sharedFlags.push(toFlagDoc(single, metadata));\n }\n }\n }\n return sharedFlags;\n};\n/**\n * Returns all global flags declared in a command tree.\n * Built-ins are prepended and command declarations are deduplicated by identity.\n */\nexport const getGlobalFlagsForCommandTree = (command, builtIns) => dedupeGlobalFlags([...builtIns, ...collectDeclaredGlobalFlags(command)]);\n/**\n * Helper function to get help documentation for a specific command path.\n * Navigates through the command hierarchy to find the right command.\n * Reads active global flags for the path and includes them in the help doc.\n */\nexport const getHelpForCommandPath = (command, commandPath, builtIns) => Effect.gen(function* () {\n const commands = getCommandsForCommandPath(command, commandPath);\n const currentCommand = commands.length > 0 ? commands[commands.length - 1] : command;\n const baseDoc = toImpl(currentCommand).buildHelpDoc(commandPath);\n const sharedFlags = getSharedFlagsForCommandPath(commands, baseDoc.flags);\n const flags = getGlobalFlagsForCommandPath(command, commandPath, builtIns);\n const globalFlagDocs = [];\n for (const flag of flags) {\n const singles = Param.extractSingleParams(flag.flag);\n const metadata = Param.getParamMetadata(flag.flag);\n for (const single of singles) {\n // Same rule as command-local flags: hidden globals are still parsed\n // and still trigger their handlers, they just don't appear under\n // \"GLOBAL FLAGS\" in --help.\n if (single.hidden) continue;\n globalFlagDocs.push({\n ...toFlagDoc(single, metadata),\n required: false\n });\n }\n }\n return {\n ...baseDoc,\n flags: [...sharedFlags, ...baseDoc.flags],\n globalFlags: globalFlagDocs\n };\n});\n//# sourceMappingURL=help.js.map","/**\n * Global flags for Effect CLI command trees. Global flags are parsed outside a\n * single command's local flags and can apply to a command and its descendants.\n *\n * This module defines two kinds of global flags: action flags, which run an\n * effect and stop normal command execution, and setting flags, which provide a\n * parsed value to the command handler through the Effect context. It also\n * defines the built-in help, version, wizard, shell-completion, and log-level flags\n * used by `Command.run` and `Command.runWith`.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Console from \"../Console.js\";\nimport * as Context from \"../Context.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Option from \"../Option.js\";\nimport * as CliOutput from \"./CliOutput.js\";\nimport * as Completions_ from \"./Completions.js\";\nimport * as Flag from \"./Flag.js\";\nimport * as CommandDescriptor from \"./internal/completions/descriptor.js\";\nimport * as HelpInternal from \"./internal/help.js\";\n/* ========================================================================== */\n/* Constructors */\n/* ========================================================================== */\n/**\n * Creates an Action flag that performs a side effect and exits.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Action = options => ({\n _tag: \"Action\",\n flag: options.flag,\n run: options.run\n});\n/**\n * Creates a Setting flag that configures the command handler's environment.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const Setting = id => options => {\n settingIdCounter += 1;\n const ref = Context.Service(`effect/cli/GlobalFlag/${id}/${settingIdCounter}`);\n return Object.assign(ref, {\n _tag: \"Setting\",\n id,\n flag: options.flag\n });\n};\nlet settingIdCounter = 0;\n/* ========================================================================== */\n/* Built-in Flag References */\n/* ========================================================================== */\n/**\n * Defines the `--help` / `-h` global flag, which shows help documentation for the\n * active command path.\n *\n * @see {@link BuiltIns} for the default list containing this flag\n * @see {@link Action} for defining custom action global flags\n *\n * @stability unstable\n * @category references\n * @since 4.0.0\n */\nexport const Help = /*#__PURE__*/Action({\n flag: /*#__PURE__*/Flag.Boolean(\"help\").pipe(/*#__PURE__*/Flag.withAlias(\"h\"), /*#__PURE__*/Flag.withDescription(\"Show help information\"), /*#__PURE__*/Flag.withDefault(false)),\n run: /*#__PURE__*/Effect.fnUntraced(function* (_, {\n builtIns,\n command,\n commandPath\n }) {\n const formatter = yield* CliOutput.Formatter;\n const helpDoc = yield* HelpInternal.getHelpForCommandPath(command, commandPath, builtIns);\n yield* Console.log(formatter.formatHelpDoc(helpDoc));\n })\n});\n/**\n * Defines the global action flag for showing command version information.\n *\n * **When to use**\n *\n * Use to add a built-in `--version / -v` flag to a command runner.\n *\n * @stability unstable\n * @category references\n * @since 4.0.0\n */\nexport const Version = /*#__PURE__*/Action({\n flag: /*#__PURE__*/Flag.Boolean(\"version\").pipe(/*#__PURE__*/Flag.withAlias(\"v\"), /*#__PURE__*/Flag.withDescription(\"Show version information\"), /*#__PURE__*/Flag.withDefault(false)),\n run: /*#__PURE__*/Effect.fnUntraced(function* (_, {\n command,\n version\n }) {\n const formatter = yield* CliOutput.Formatter;\n yield* Console.log(formatter.formatVersion(command.name, version));\n })\n});\n/**\n * Defines the global action flag for starting interactive wizard mode.\n *\n * **Details**\n *\n * `Command.run` and `Command.runWith` handle this action specially so the\n * generated arguments can be passed back through the command parser.\n *\n * @stability unstable\n * @category references\n * @since 4.0.0\n */\nexport const Wizard = /*#__PURE__*/Action({\n flag: /*#__PURE__*/Flag.Boolean(\"wizard\").pipe(/*#__PURE__*/Flag.withDescription(\"Start wizard mode for a command\"), /*#__PURE__*/Flag.withDefault(false)),\n run: () => Effect.void\n});\n/**\n * Defines the `--completions` global flag, which prints a shell completion script for\n * the given shell.\n *\n * **Details**\n *\n * Accepted values are `bash`, `zsh`, `fish`, `powershell`, `sh`, and `pwsh`;\n * `sh` is normalized to `bash` and `pwsh` to `powershell`.\n *\n * @stability unstable\n * @category references\n * @since 4.0.0\n */\nexport const Completions = /*#__PURE__*/Action({\n flag: /*#__PURE__*/Flag.ChoiceWithValue(\"completions\", [[\"bash\", \"bash\"], [\"zsh\", \"zsh\"], [\"fish\", \"fish\"], [\"powershell\", \"powershell\"], [\"sh\", \"bash\"], [\"pwsh\", \"powershell\"]]).pipe(Flag.optional, /*#__PURE__*/Flag.withMetavar(\"<bash|zsh|fish|powershell|sh|pwsh>\"), /*#__PURE__*/Flag.withDescription(\"Print shell completion script\")),\n run: /*#__PURE__*/Effect.fnUntraced(function* (shell, {\n command\n }) {\n if (Option.isNone(shell)) return;\n const descriptor = CommandDescriptor.fromCommand(command);\n yield* Console.log(Completions_.generate(command.name, shell.value, descriptor));\n })\n});\n/**\n * Defines the global setting flag for command log level.\n *\n * **When to use**\n *\n * Use to add a built-in `--log-level` option that configures the minimum log\n * level for the command.\n *\n * @stability unstable\n * @category references\n * @since 4.0.0\n */\nexport const LogLevel = /*#__PURE__*/Setting(\"log-level\")({\n flag: /*#__PURE__*/Flag.ChoiceWithValue(\"log-level\", [[\"all\", \"All\"], [\"trace\", \"Trace\"], [\"debug\", \"Debug\"], [\"info\", \"Info\"], [\"warn\", \"Warn\"], [\"warning\", \"Warn\"], [\"error\", \"Error\"], [\"fatal\", \"Fatal\"], [\"none\", \"None\"]]).pipe(Flag.optional, /*#__PURE__*/Flag.withDescription(\"Sets the minimum log level\"), /*#__PURE__*/Flag.withMetavar(\"<all|trace|debug|info|warn|warning|error|fatal|none>\"))\n});\n/* ========================================================================== */\n/* References */\n/* ========================================================================== */\n/**\n * Built-in global flags in default precedence order.\n *\n * **When to use**\n *\n * Use when extending or inspecting the default global-flag set that\n * `Command.runWith` prepends before user-defined global flags.\n *\n * **Details**\n *\n * The built-ins are `Help`, `Version`, `Wizard`, `Completions`, and `LogLevel`.\n * `Command.runWith` prepends these built-ins when collecting and parsing global\n * flags.\n *\n * **Gotchas**\n *\n * Action flags are processed in active flag order and the first present action\n * exits, so this array controls built-in action precedence.\n *\n * @see {@link Help} for the help action flag\n * @see {@link Version} for the version action flag\n * @see {@link Completions} for the shell-completions action flag\n * @see {@link LogLevel} for the built-in log-level setting flag\n *\n * @stability unstable\n * @category references\n * @since 4.0.0\n */\nexport const BuiltIns = [Help, Version, Wizard, Completions, LogLevel];\n//# sourceMappingURL=GlobalFlag.js.map","/**\n * Configuration for Effect CLI command execution.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"../Context.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as GlobalFlag from \"./GlobalFlag.js\";\n/**\n * Context reference for configuration shared by CLI parsing, help generation,\n * and command execution.\n *\n * **When to use**\n *\n * Use when you need to customize runner-wide CLI behavior, such as which\n * built-in global flags are available.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class CliConfig extends /*#__PURE__*/Context.Reference(\"effect/cli/CliConfig\", {\n defaultValue: () => defaults\n}) {}\n/**\n * Default CLI configuration containing every built-in global flag.\n *\n * @stability unstable\n * @category defaults\n * @since 4.0.0\n */\nexport const defaults = {\n builtIns: GlobalFlag.BuiltIns\n};\n/**\n * Creates CLI configuration by merging the provided options over `defaults`.\n *\n * **When to use**\n *\n * Use when you need a configuration value to provide directly through the\n * `CliConfig` context reference.\n *\n * @see {@link layer} for providing configuration as a layer\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = options => ({\n ...defaults,\n ...options\n});\n/**\n * Creates a layer that provides CLI configuration merged over `defaults`.\n *\n * **When to use**\n *\n * Use when wiring customized CLI behavior into an application layer.\n *\n * @see {@link make} for creating a configuration value directly\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = options => Layer.succeed(CliConfig, make(options));\n//# sourceMappingURL=CliConfig.js.map","/**\n * @internal\n */\nexport function lex(argv) {\n const endIndex = argv.indexOf(\"--\");\n if (endIndex === -1) {\n // No -- delimiter, lex everything normally\n return {\n tokens: lexTokens(argv),\n trailingOperands: []\n };\n }\n // Split at -- delimiter\n return {\n tokens: lexTokens(argv.slice(0, endIndex)),\n trailingOperands: argv.slice(endIndex + 1)\n };\n}\nconst negativeNumberRegex = /^-(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?$/;\nconst lexTokens = args => {\n const tokens = [];\n for (const arg of args) {\n if (!arg.startsWith(\"-\") || negativeNumberRegex.test(arg)) {\n tokens.push({\n _tag: \"Value\",\n value: arg\n });\n } else if (arg.startsWith(\"--\")) {\n const equalIndex = arg.indexOf(\"=\");\n if (equalIndex !== -1) {\n const name = arg.slice(2, equalIndex);\n const value = arg.slice(equalIndex + 1);\n tokens.push({\n _tag: \"LongOption\",\n name,\n raw: arg,\n value\n });\n } else {\n tokens.push({\n _tag: \"LongOption\",\n name: arg.slice(2),\n raw: arg\n });\n }\n } else if (arg.length > 1) {\n const flags = arg.slice(1);\n const equalIndex = flags.indexOf(\"=\");\n if (equalIndex !== -1) {\n const flag = flags.slice(0, equalIndex);\n const value = flags.slice(equalIndex + 1);\n tokens.push({\n _tag: \"ShortOption\",\n flag,\n raw: `-${flag}`,\n value\n });\n } else {\n for (const ch of flags) {\n tokens.push({\n _tag: \"ShortOption\",\n flag: ch,\n raw: `-${ch}`\n });\n }\n }\n } else {\n tokens.push({\n _tag: \"Value\",\n value: arg\n });\n }\n }\n return tokens;\n};\n//# sourceMappingURL=lexer.js.map","/**\n * Simple Levenshtein distance implementation (small N, no perf worries)\n */\nconst levenshtein = (a, b) => {\n const m = a.length;\n const n = b.length;\n const dp = Array.from({\n length: m + 1\n }, () => new Array(n + 1).fill(0));\n for (let i = 0; i <= m; i++) dp[i][0] = i;\n for (let j = 0; j <= n; j++) dp[0][j] = j;\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);\n }\n }\n return dp[m][n];\n};\n/**\n * Return suggestions with minimum distance found, up to distance 2.\n *\n * @internal\n */\nexport const suggest = (input, candidates) => {\n const distances = candidates.map(c => [levenshtein(input, c), c]).filter(([d]) => d <= 2) // Stricter threshold\n .sort(([a], [b]) => a - b);\n if (distances.length === 0) return [];\n // Only return suggestions with the minimum distance found\n const minDistance = distances[0][0];\n return distances.filter(([d]) => d === minDistance).map(([, c]) => c);\n};\n//# sourceMappingURL=auto-suggest.js.map","/**\n * Parsing Pipeline for CLI Commands\n * ==================================\n *\n * The parser transforms raw argv tokens into structured command input through\n * three main phases:\n *\n * 1. **Lexer** (external): Converts argv strings into typed tokens\n * - LongOption: --name or --name=value\n * - ShortOption: -n or -n=value (also handles -abc as three flags)\n * - Value: positional arguments\n *\n * 2. **Built-in Extraction**: Peels off built-in flags (help/version/completions)\n * before command-specific parsing begins.\n *\n * 3. **Command Parsing**: Recursively processes command levels:\n * - Collects flags defined at this level\n * - Detects subcommand from first value token\n * - Forwards remaining tokens to child command\n *\n * Key Behaviors\n * -------------\n * - Inherited parent flags may appear before OR after the subcommand name (npm-style)\n * - Only the first Value token can open a subcommand\n * - Errors accumulate rather than throwing exceptions\n */\nimport * as Effect from \"../../Effect.js\";\nimport * as Option from \"../../Option.js\";\nimport * as CliError from \"../CliError.js\";\nimport * as Param from \"../Param.js\";\nimport * as Primitive from \"../Primitive.js\";\nimport { suggest } from \"./auto-suggest.js\";\nimport { toImpl } from \"./command.js\";\n/* ========================================================================== */\n/* Public API */\n/* ========================================================================== */\n/**\n * @internal\n */\nexport const getCommandPath = parsedInput => Option.match(parsedInput.subcommand, {\n onNone: () => [],\n onSome: subcommand => [subcommand.name, ...getCommandPath(subcommand.parsedInput)]\n});\n/**\n * @internal\n */\nexport const parseArgs = (lexResult, command, commandPath = []) => Effect.gen(function* () {\n const {\n tokens,\n trailingOperands: afterEndOfOptions\n } = lexResult;\n const newCommandPath = [...commandPath, command.name];\n const commandImpl = toImpl(command);\n const singles = commandImpl.config.flags.flatMap(Param.extractSingleParams);\n const flagParams = singles.filter(Param.isFlagParam);\n const flagRegistry = createFlagRegistry(flagParams);\n const inheritedSingles = commandImpl.contextConfig.flags.flatMap(Param.extractSingleParams);\n const inheritedFlagParams = inheritedSingles.filter(Param.isFlagParam);\n const inheritedFlagRegistry = createFlagRegistry(inheritedFlagParams);\n const inheritedNames = new Set(inheritedFlagParams.map(param => param.name));\n const context = {\n command,\n commandPath: newCommandPath,\n flagRegistry,\n inheritedFlagRegistry,\n localFlagNames: flagParams.filter(param => !inheritedNames.has(param.name)).map(param => param.name)\n };\n const result = scanCommandLevel(tokens, context);\n if (result._tag === \"Leaf\") {\n return {\n flags: result.flags,\n arguments: [...result.arguments, ...afterEndOfOptions],\n subcommand: Option.none(),\n ...(result.errors.length > 0 && {\n errors: result.errors\n })\n };\n }\n const subLex = {\n tokens: result.childTokens,\n trailingOperands: afterEndOfOptions\n };\n const subParsed = yield* parseArgs(subLex, result.sub, newCommandPath);\n const allErrors = [...result.errors, ...(subParsed.errors ?? [])];\n return {\n flags: result.flags,\n arguments: [],\n subcommand: Option.some({\n name: result.sub.name,\n parsedInput: subParsed\n }),\n ...(allErrors.length > 0 && {\n errors: allErrors\n })\n };\n});\nconst makeCursor = tokens => {\n let i = 0;\n return {\n peek: () => tokens[i],\n take: () => tokens[i++],\n rest: () => tokens.slice(i)\n };\n};\n/* ========================================================================== */\n/* Flag Registry */\n/* ========================================================================== */\n/**\n * Creates a registry for O(1) flag lookup by name or alias.\n * @internal\n */\nexport const createFlagRegistry = params => {\n const index = new Map();\n for (const param of params) {\n if (index.has(param.name)) {\n throw new Error(`Duplicate flag name \"${param.name}\" in command definition`);\n }\n index.set(param.name, param);\n for (const alias of param.aliases) {\n if (index.has(alias)) {\n throw new Error(`Duplicate flag/alias \"${alias}\" in command definition (conflicts with \"${index.get(alias).name}\")`);\n }\n index.set(alias, param);\n }\n }\n return {\n params,\n index\n };\n};\nconst buildSubcommandIndex = subcommands => {\n const index = new Map();\n const setKey = (key, command) => {\n const existing = index.get(key);\n if (existing && existing !== command) {\n throw new Error(`Duplicate subcommand name/alias \"${key}\" in command definition (conflicts with \"${existing.name}\")`);\n }\n index.set(key, command);\n };\n for (const group of subcommands) {\n for (const subcommand of group.commands) {\n setKey(subcommand.name, subcommand);\n if (subcommand.alias && subcommand.alias !== subcommand.name) {\n setKey(subcommand.alias, subcommand);\n }\n }\n }\n return index;\n};\n/* ========================================================================== */\n/* Flag Accumulator */\n/* ========================================================================== */\n/** Creates an empty flag map with all known flag names initialized to [].\n * @internal\n */\nexport const createEmptyFlagMap = params => Object.fromEntries(params.map(p => [p.name, []]));\n/**\n * Creates a mutable accumulator for collecting flag values.\n * Pre-initializes empty arrays for all known flags.\n */\nconst createFlagAccumulator = params => {\n const map = createEmptyFlagMap(params);\n return {\n add: (name, raw) => {\n if (raw !== undefined) map[name].push(raw);\n },\n merge: from => {\n for (const key in from) {\n const values = from[key];\n if (values?.length) {\n for (let i = 0; i < values.length; i++) {\n map[key].push(values[i]);\n }\n }\n }\n },\n snapshot: () => map\n };\n};\nconst isFlagToken = t => t._tag === \"LongOption\" || t._tag === \"ShortOption\";\nconst getFlagName = t => t._tag === \"LongOption\" ? t.name : t.flag;\nconst resolveFlag = (token, registry) => {\n const tokenName = getFlagName(token);\n const direct = registry.index.get(tokenName);\n if (direct && direct.name === tokenName) {\n return {\n param: direct,\n negated: false\n };\n }\n if (token._tag === \"LongOption\" && token.name.startsWith(\"no-\")) {\n const canonicalName = token.name.slice(3);\n const param = registry.index.get(canonicalName);\n if (param && param.name === canonicalName && Primitive.isBoolean(param.primitiveType)) {\n return {\n param,\n negated: true\n };\n }\n }\n if (direct) {\n return {\n param: direct,\n negated: false\n };\n }\n return undefined;\n};\nconst invalidNegatedFlagValue = (token, spec, value) => new CliError.InvalidValue({\n option: spec.name,\n value,\n expected: `omit the value and use ${token.raw} by itself to set --${spec.name} to false`,\n kind: \"flag\"\n});\nconst missingFlagValue = spec => {\n const choices = Primitive.getChoiceKeys(spec.primitiveType);\n return new CliError.InvalidValue({\n option: spec.name,\n value: \"\",\n expected: choices === undefined ? spec.typeName ?? Primitive.getTypeName(spec.primitiveType) : choices.join(\" | \"),\n kind: \"flag\"\n });\n};\n/**\n * Checks whether a token is a boolean literal value.\n * Recognizes: true/false, yes/no, on/off, 1/0\n */\nconst asBooleanLiteral = token => token?._tag === \"Value\" && (Primitive.isTrueLiteral(token.value) || Primitive.isFalseLiteral(token.value)) ? token.value : undefined;\n/* ========================================================================== */\n/* Flag Value Consumption */\n/* ========================================================================== */\n/**\n * Reads a flag's value from the token stream.\n *\n * Value resolution order:\n * 1. Inline value: --flag=value or -f=value\n * 2. Optional value: the flag's configured value, without consuming a token\n * 3. Boolean special case: implicit \"true\" or explicit boolean literal\n * 4. Next token: consume following Value token if present\n */\nconst consumeFlagValue = (cursor, token, spec, negated = false) => {\n const consumed = consumeFlagValueWithTokens(cursor, token, spec, negated);\n switch (consumed._tag) {\n case \"Value\":\n return {\n _tag: \"Value\",\n value: consumed.value\n };\n case \"Error\":\n return {\n _tag: \"Error\",\n error: consumed.error\n };\n }\n};\nconst consumeFlagValueWithTokens = (cursor, token, spec, negated = false) => {\n // Inline value has highest priority\n if (negated) {\n if (token.value !== undefined) {\n return {\n _tag: \"Error\",\n error: invalidNegatedFlagValue(token, spec, token.value),\n tokens: []\n };\n }\n const literal = spec.optionalValue === undefined ? asBooleanLiteral(cursor.peek()) : undefined;\n if (literal !== undefined) {\n const literalToken = cursor.take();\n return {\n _tag: \"Error\",\n error: invalidNegatedFlagValue(token, spec, literal),\n tokens: literalToken === undefined ? [] : [literalToken]\n };\n }\n return {\n _tag: \"Value\",\n value: \"false\",\n tokens: []\n };\n }\n if (token.value !== undefined) {\n return {\n _tag: \"Value\",\n value: token.value,\n tokens: []\n };\n }\n if (spec.optionalValue !== undefined) {\n return {\n _tag: \"Value\",\n value: spec.optionalValue,\n tokens: []\n };\n }\n // Boolean flags: check for explicit literal or default to \"true\"\n if (Primitive.isBoolean(spec.primitiveType)) {\n const literal = asBooleanLiteral(cursor.peek());\n const literalToken = literal !== undefined ? cursor.take() : undefined;\n return {\n _tag: \"Value\",\n value: literal ?? \"true\",\n tokens: literalToken === undefined ? [] : [literalToken]\n };\n }\n // Non-boolean: try to consume next Value token\n const next = cursor.peek();\n if (next?._tag === \"Value\") {\n const valueToken = cursor.take();\n return {\n _tag: \"Value\",\n value: next.value,\n tokens: valueToken === undefined ? [] : [valueToken]\n };\n }\n return {\n _tag: \"Error\",\n error: missingFlagValue(spec),\n tokens: []\n };\n};\n/**\n * Consumes known flags from a token stream.\n * Unrecognized tokens are passed through to remainder.\n * Used for both global flag extraction and npm-style parent flag collection.\n * @internal\n */\nexport const consumeKnownFlags = (tokens, registry) => {\n const flagMap = createEmptyFlagMap(registry.params);\n const remainder = [];\n const errors = [];\n const cursor = makeCursor(tokens);\n for (let t = cursor.take(); t; t = cursor.take()) {\n if (!isFlagToken(t)) {\n remainder.push(t);\n continue;\n }\n const resolved = resolveFlag(t, registry);\n if (!resolved) {\n remainder.push(t);\n continue;\n }\n const consumed = consumeFlagValue(cursor, t, resolved.param, resolved.negated);\n if (consumed._tag === \"Error\") {\n errors.push(consumed.error);\n continue;\n }\n if (consumed.value !== undefined) {\n flagMap[resolved.param.name].push(consumed.value);\n }\n }\n return {\n flagMap,\n remainder,\n errors\n };\n};\nconst extractFlagParams = command => {\n const commandImpl = toImpl(command);\n const singles = commandImpl.config.flags.flatMap(Param.extractSingleParams);\n return singles.filter(Param.isFlagParam);\n};\nconst extractContextFlagParams = command => {\n const commandImpl = toImpl(command);\n const singles = commandImpl.contextConfig.flags.flatMap(Param.extractSingleParams);\n return singles.filter(Param.isFlagParam);\n};\nconst resolveFromRegistries = (token, registries) => {\n for (const registry of registries) {\n const resolved = resolveFlag(token, registry);\n if (resolved !== undefined) {\n return resolved;\n }\n }\n return undefined;\n};\nconst preserveFlag = (remainder, cursor, token, resolved) => {\n remainder.push(token);\n const consumed = consumeFlagValueWithTokens(cursor, token, resolved.param, resolved.negated);\n remainder.push(...consumed.tokens);\n};\nconst localFlagWouldPrecedeSubcommand = (token, remainingTokens, resolved, subIndex, registries) => {\n const cursor = makeCursor(remainingTokens);\n consumeFlagValueWithTokens(cursor, token, resolved.param, resolved.negated);\n for (let token = cursor.take(); token; token = cursor.take()) {\n if (isFlagToken(token)) {\n const known = resolveFromRegistries(token, registries);\n if (known !== undefined) {\n consumeFlagValueWithTokens(cursor, token, known.param, known.negated);\n }\n continue;\n }\n if (token._tag === \"Value\") {\n return subIndex.has(token.value);\n }\n }\n return false;\n};\n/**\n * Consumes global flags while walking the command tree.\n *\n * Command-local flags take precedence over global flags at the selected command\n * level. This lets commands reuse a global flag name, for example a subcommand\n * with its own `--version <value>` flag overriding the built-in global\n * `--version` action.\n * @internal\n */\nexport const consumeGlobalFlags = (tokens, command, registry) => {\n const flagMap = createEmptyFlagMap(registry.params);\n const errors = [];\n const consumeLevel = (tokens, command, ignoredRegistries) => {\n const localRegistry = createFlagRegistry(extractFlagParams(command));\n const inheritedRegistry = createFlagRegistry(extractContextFlagParams(command));\n const subIndex = buildSubcommandIndex(command.subcommands);\n const cursor = makeCursor(tokens);\n const remainder = [];\n let awaitingFirstValue = true;\n for (let token = cursor.take(); token; token = cursor.take()) {\n if (isFlagToken(token)) {\n const ignored = resolveFromRegistries(token, ignoredRegistries);\n if (ignored !== undefined) {\n preserveFlag(remainder, cursor, token, ignored);\n continue;\n }\n const inherited = resolveFlag(token, inheritedRegistry);\n if (inherited !== undefined) {\n preserveFlag(remainder, cursor, token, inherited);\n continue;\n }\n const local = resolveFlag(token, localRegistry);\n const global = resolveFlag(token, registry);\n if (local !== undefined) {\n if (global === undefined || !awaitingFirstValue || !localFlagWouldPrecedeSubcommand(token, cursor.rest(), local, subIndex, [localRegistry, inheritedRegistry, registry])) {\n preserveFlag(remainder, cursor, token, local);\n continue;\n }\n }\n if (global !== undefined) {\n const consumed = consumeFlagValueWithTokens(cursor, token, global.param, global.negated);\n if (consumed._tag === \"Error\") {\n errors.push(consumed.error);\n continue;\n }\n if (consumed.value !== undefined) {\n flagMap[global.param.name].push(consumed.value);\n }\n continue;\n }\n remainder.push(token);\n continue;\n }\n if (token._tag === \"Value\" && awaitingFirstValue) {\n const sub = subIndex.get(token.value);\n if (sub !== undefined) {\n remainder.push(token);\n remainder.push(...consumeLevel(cursor.rest(), sub, [...ignoredRegistries, inheritedRegistry]));\n return remainder;\n }\n awaitingFirstValue = false;\n }\n remainder.push(token);\n }\n return remainder;\n };\n return {\n flagMap,\n remainder: consumeLevel(tokens, command, []),\n errors\n };\n};\n/* ========================================================================== */\n/* Error Creation */\n/* ========================================================================== */\nconst createUnrecognizedFlagError = (token, params, commandPath) => {\n const printable = token._tag === \"LongOption\" ? `--${token.name}` : `-${token.flag}`;\n const validNames = [];\n for (const p of params) {\n // Exclude hidden flags so a near-miss typo cannot reveal a flag name\n // that was intentionally kept out of --help.\n if (p.hidden) continue;\n validNames.push(p.name);\n if (Primitive.isBoolean(p.primitiveType)) {\n validNames.push(`no-${p.name}`);\n }\n for (const alias of p.aliases) {\n validNames.push(alias);\n }\n }\n const suggestions = suggest(getFlagName(token), validNames).map(n => n.length === 1 ? `-${n}` : `--${n}`);\n return new CliError.UnrecognizedOption({\n option: printable,\n suggestions,\n command: commandPath\n });\n};\n/* ========================================================================== */\n/* Parse State */\n/* ========================================================================== */\nconst createParseState = registry => ({\n flags: createFlagAccumulator(registry.params),\n arguments: [],\n errors: [],\n mode: {\n _tag: \"AwaitingFirstValue\"\n }\n});\nconst toLeafResult = state => ({\n _tag: \"Leaf\",\n flags: state.flags.snapshot(),\n arguments: state.arguments,\n errors: state.errors\n});\n/* ========================================================================== */\n/* First Value Resolution */\n/* ========================================================================== */\n/**\n * Determines how to handle the first value token.\n *\n * If it matches a known subcommand:\n * - Collect inherited parent flags from remaining tokens (npm-style)\n * - Return SubcommandResult with child tokens\n *\n * Otherwise:\n * - Return Argument to treat it as a positional argument\n * - Report error if command expects subcommand but got unknown value\n */\nconst resolveFirstValue = (value, cursor, context, state) => {\n const {\n command,\n commandPath,\n inheritedFlagRegistry,\n localFlagNames\n } = context;\n const subIndex = buildSubcommandIndex(command.subcommands);\n const sub = subIndex.get(value);\n if (sub) {\n const selectedPath = [...commandPath, sub.name];\n // Local flags are not inherited by subcommands.\n const parentFlags = state.flags.snapshot();\n for (const localFlagName of localFlagNames) {\n const values = parentFlags[localFlagName];\n if (values !== undefined && values.length > 0) {\n state.errors.push(new CliError.UnrecognizedOption({\n option: `--${localFlagName}`,\n suggestions: [],\n command: selectedPath\n }));\n }\n }\n // npm-style: inherited parent flags can appear after subcommand name\n const tail = consumeKnownFlags(cursor.rest(), inheritedFlagRegistry);\n state.flags.merge(tail.flagMap);\n state.errors.push(...tail.errors);\n return {\n _tag: \"Subcommand\",\n result: {\n _tag: \"Sub\",\n flags: state.flags.snapshot(),\n sub,\n childTokens: tail.remainder,\n errors: state.errors\n }\n };\n }\n // Not a subcommand. Check if this looks like a typo.\n const expectsArgs = toImpl(command).config.arguments.length > 0;\n if (!expectsArgs && subIndex.size > 0) {\n // Exclude unlisted subcommands so a typo cannot reveal a subcommand name\n // that was intentionally kept out of --help. Unlisted commands still\n // resolve via subIndex when invoked by exact name.\n const visibleKeys = [];\n for (const [key, sub] of subIndex) {\n if (!sub.unlisted) visibleKeys.push(key);\n }\n const suggestions = suggest(value, visibleKeys);\n state.errors.push(new CliError.UnknownSubcommand({\n subcommand: value,\n parent: commandPath,\n suggestions\n }));\n }\n return {\n _tag: \"Argument\"\n };\n};\n/* ========================================================================== */\n/* Token Processing */\n/* ========================================================================== */\n/**\n * Processes a flag token: looks up in registry, consumes value, records it.\n * Reports unrecognized flags as errors.\n */\nconst processFlag = (token, cursor, context, state) => {\n const {\n commandPath,\n flagRegistry\n } = context;\n const resolved = resolveFlag(token, flagRegistry);\n if (!resolved) {\n state.errors.push(createUnrecognizedFlagError(token, flagRegistry.params, commandPath));\n return;\n }\n const consumed = consumeFlagValue(cursor, token, resolved.param, resolved.negated);\n if (consumed._tag === \"Error\") {\n state.errors.push(consumed.error);\n return;\n }\n state.flags.add(resolved.param.name, consumed.value);\n};\n/**\n * Processes a value token based on current parsing mode.\n *\n * In AwaitingFirstValue mode:\n * - Check if value is a subcommand\n * - If so, return SubcommandResult to exit scanning\n * - If not, switch to CollectingArguments mode\n *\n * In CollectingArguments mode:\n * - Simply add value to arguments list\n */\nconst processValue = (value, cursor, context, state) => {\n if (state.mode._tag === \"AwaitingFirstValue\") {\n const result = resolveFirstValue(value, cursor, context, state);\n if (result._tag === \"Subcommand\") {\n return result.result;\n }\n state.mode = {\n _tag: \"CollectingArguments\"\n };\n }\n state.arguments.push(value);\n return undefined;\n};\n/* ========================================================================== */\n/* Command Level Scanning */\n/* ========================================================================== */\n/**\n * Scans a single command level, processing all tokens.\n *\n * For each token:\n * - Flags: Look up, consume value, record in accumulator\n * - Values: Check for subcommand (first value only), then collect as arguments\n *\n * Returns LeafResult if no subcommand detected, SubcommandResult otherwise.\n */\nconst scanCommandLevel = (tokens, context) => {\n const cursor = makeCursor(tokens);\n const state = createParseState(context.flagRegistry);\n for (let token = cursor.take(); token; token = cursor.take()) {\n if (isFlagToken(token)) {\n processFlag(token, cursor, context, state);\n continue;\n }\n if (token._tag === \"Value\") {\n const subResult = processValue(token.value, cursor, context, state);\n if (subResult) return subResult;\n }\n }\n return toLeafResult(state);\n};\n//# sourceMappingURL=parser.js.map","import * as Console from \"../../Console.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Redacted from \"../../Redacted.js\";\nimport * as Param from \"../Param.js\";\nimport * as Primitive from \"../Primitive.js\";\nimport * as Prompt from \"../Prompt.js\";\nimport * as Ansi from \"./ansi.js\";\nimport { toImpl } from \"./command.js\";\nexport const run = /*#__PURE__*/Effect.fnUntraced(function* (command, options) {\n const commandPath = options?.commandPath ?? [command.name];\n const selected = getCommandAtPath(command, commandPath);\n const commandLine = (options?.prefix ?? commandPath).map(value => commandLineArg(value));\n const {\n colors\n } = yield* Prompt.Theme;\n yield* logCurrentCommand(commandLine, colors);\n yield* promptCommand(selected, commandLine, selected === command ? \"ROOT\" : selected.name, colors);\n return {\n args: commandLine.map(arg => arg.value),\n displayArgs: commandLine.map(arg => arg.displayValue)\n };\n});\nconst getCommandAtPath = (command, commandPath) => {\n let current = command;\n for (const name of commandPath.slice(1)) {\n const child = current.subcommands.flatMap(group => group.commands).find(candidate => candidate.name === name || candidate.alias === name);\n if (child === undefined) {\n break;\n }\n current = child;\n }\n return current;\n};\nconst promptCommand = /*#__PURE__*/Effect.fnUntraced(function* (command, commandLine, sectionName, colors) {\n const impl = toImpl(command);\n const visibleSubcommands = command.subcommands.flatMap(group => group.commands.filter(child => !child.unlisted));\n const config = visibleSubcommands.length === 0 ? impl.config : impl.contextConfig;\n if (config.flags.length > 0) {\n yield* Console.log(renderSection(sectionName, \"FLAGS\", colors));\n for (const param of config.flags) {\n commandLine.push(...(yield* promptParam(param)));\n }\n if (config.arguments.length > 0 || visibleSubcommands.length > 0) {\n yield* logCurrentCommand(commandLine, colors);\n }\n }\n if (config.arguments.length > 0) {\n yield* Console.log(renderSection(sectionName, \"ARGUMENTS\", colors));\n for (const param of config.arguments) {\n commandLine.push(...(yield* promptParam(param)));\n }\n if (visibleSubcommands.length > 0) {\n yield* logCurrentCommand(commandLine, colors);\n }\n }\n if (visibleSubcommands.length === 0) {\n return;\n }\n const child = yield* Prompt.run(Prompt.Select({\n message: \"Command\",\n choices: visibleSubcommands.map(command => ({\n title: command.name,\n value: command,\n ...(command.shortDescription !== undefined ? {\n description: command.shortDescription\n } : command.description !== undefined ? {\n description: command.description\n } : {})\n }))\n }));\n yield* Console.log();\n commandLine.push(commandLineArg(child.name));\n if (hasWizardSteps(child)) {\n yield* logCurrentCommand(commandLine, colors);\n }\n yield* promptCommand(child, commandLine, child.name, colors);\n});\nconst hasWizardSteps = command => {\n const hasVisibleSubcommands = command.subcommands.some(group => group.commands.some(child => !child.unlisted));\n return hasVisibleSubcommands || toImpl(command).config.orderedParams.length > 0;\n};\nconst promptParam = /*#__PURE__*/Effect.fnUntraced(function* (param) {\n const single = Param.getUnderlyingSingleOrThrow(param);\n const metadata = Param.getParamMetadata(param);\n if (metadata.isOptional) {\n const include = yield* Prompt.run(Prompt.Confirm({\n message: `Set ${renderParamLabel(single)}?`,\n initial: false\n }));\n if (!include) {\n yield* Console.log();\n return [];\n }\n }\n const count = !metadata.isVariadic ? 1 : yield* Prompt.run(Prompt.Int({\n message: `${renderParamLabel(single)} count`,\n default: Option.getOrElse(metadata.variadicMin, () => 0),\n min: Option.getOrElse(metadata.variadicMin, () => 0),\n ...(Option.isSome(metadata.variadicMax) ? {\n max: metadata.variadicMax.value\n } : {})\n }));\n const values = [];\n for (let i = 0; i < count; i++) {\n values.push(yield* promptSingle(single));\n }\n const parsed = single.kind === Param.flagKind ? {\n flags: {\n [single.name]: values.map(arg => arg.value)\n },\n arguments: []\n } : {\n flags: {},\n arguments: values.map(arg => arg.value)\n };\n yield* param.parse(parsed);\n yield* Console.log();\n if (single.kind === Param.argumentKind) {\n return values;\n }\n // Inline option-looking values so the lexer cannot interpret them as flags or the -- delimiter.\n // Flags with an optional value only accept an inline value.\n return values.flatMap(value => single.optionalValue !== undefined || value.value.startsWith(\"-\") && value.value.length > 1 ? [commandLineArg(`--${single.name}=${value.value}`, `--${single.name}=${value.displayValue}`)] : [commandLineArg(`--${single.name}`), value]);\n});\nconst promptSingle = single => {\n const message = renderParamMessage(single);\n switch (single.primitiveType._tag) {\n case \"Boolean\":\n return Effect.map(Prompt.run(Prompt.Confirm({\n message,\n label: {\n confirm: \"true\",\n deny: \"false\"\n },\n placeholder: {\n defaultConfirm: \"(T/f)\",\n defaultDeny: \"(t/F)\"\n }\n })), value => commandLineArg(String(value)));\n case \"Choice\":\n {\n const choices = Primitive.getChoiceKeys(single.primitiveType) ?? [];\n return Effect.map(Prompt.run(Prompt.Select({\n message,\n choices: choices.map(choice => ({\n title: choice,\n value: choice\n }))\n })), commandLineArg);\n }\n case \"Date\":\n return Effect.map(Prompt.run(Prompt.Date({\n message\n })), date => commandLineArg(date.toISOString()));\n case \"Finite\":\n return Effect.map(Prompt.run(Prompt.Number({\n message\n })), value => commandLineArg(String(value)));\n case \"Int\":\n return Effect.map(Prompt.run(Prompt.Int({\n message\n })), value => commandLineArg(String(value)));\n case \"Redacted\":\n return Effect.map(Prompt.run(Prompt.Password({\n message\n })), value => commandLineArg(Redacted.value(value), \"<redacted>\"));\n default:\n return Effect.map(Prompt.run(Prompt.String({\n message\n })), commandLineArg);\n }\n};\nconst commandLineArg = (value, displayValue = value) => ({\n value,\n displayValue\n});\nconst formatName = single => single.kind === Param.flagKind ? `--${single.name}` : single.name;\nconst renderParamMessage = single => renderParamLabel(single);\nconst renderParamLabel = single => {\n const description = Option.getOrUndefined(single.description)?.trim();\n const label = single.kind === Param.flagKind && description !== undefined && description.length <= 32 ? description : humanize(single.name);\n return single.kind === Param.flagKind ? `${label} (${formatName(single)})` : label;\n};\nconst humanize = name => {\n const words = name.split(/[-_]+/).filter(word => word.length > 0);\n if (words.length === 0) return name;\n return [words[0][0].toUpperCase() + words[0].slice(1), ...words.slice(1)].join(\" \");\n};\nconst logCurrentCommand = (commandLine, colors) => Console.log(renderCommandBlock(\"Current command\", commandLine.map(arg => arg.displayValue), colors, Ansi.magenta));\nconst renderSection = (commandName, section, colors) => `${Ansi.annotate(colors, commandName.toUpperCase(), Ansi.bold, Ansi.cyanBright)} ${Ansi.annotate(colors, \"·\", Ansi.blackBright)} ${Ansi.annotate(colors, section, Ansi.bold, Ansi.white)}`;\nexport const renderIntroduction = (name, version, summary, colors) => {\n const title = `${Ansi.annotate(colors, name, Ansi.bold, Ansi.cyanBright)} ${Ansi.annotate(colors, `v${version}`, Ansi.white)} ${Ansi.annotate(colors, \"· Command wizard\", Ansi.bold, Ansi.white)}`;\n return [title, ...(summary === undefined || summary.length === 0 ? [] : [summary]), Ansi.annotate(colors, \"Build a command interactively. Press Ctrl+C to cancel.\", Ansi.blackBright), \"\"].join(\"\\n\");\n};\nexport const renderCompletion = (commandLine, colors) => renderCommandBlock(\"Command ready\", commandLine, colors, Ansi.cyanBright, Ansi.green);\nexport const renderQuit = colors => `\\n${Ansi.annotate(colors, \"Wizard cancelled.\", Ansi.red)}`;\nconst renderCommandBlock = (label, commandLine, colors, commandColor, labelColor = Ansi.white) => {\n const lines = wrapCommand(commandLine);\n return [Ansi.annotate(colors, label, Ansi.bold, labelColor), ...lines.map(line => Ansi.annotate(colors, line, commandColor)), \"\"].join(\"\\n\");\n};\nconst wrapCommand = commandLine => {\n const width = 88;\n const firstIndent = \" $ \";\n const continuationIndent = \" \";\n const args = commandLine.map(formatShellArg);\n const lines = [];\n let current = firstIndent;\n for (const arg of args) {\n const separator = current === firstIndent || current === continuationIndent ? \"\" : \" \";\n if (current.length + separator.length + arg.length > width && current !== firstIndent) {\n lines.push(`${current} \\\\`);\n current = `${continuationIndent}${arg}`;\n } else {\n current += `${separator}${arg}`;\n }\n }\n if (current !== firstIndent) {\n lines.push(current);\n }\n return lines;\n};\nconst formatShellArg = arg => /^[A-Za-z0-9_./:@%+=,-]+$/.test(arg) ? arg : `'${arg.replaceAll(\"'\", `'\"'\"'`)}'`;\n//# sourceMappingURL=wizard.js.map","import * as Console from \"../Console.js\";\nimport * as Context from \"../Context.js\";\nimport * as Effect from \"../Effect.js\";\nimport { dual } from \"../Function.js\";\nimport * as Option from \"../Option.js\";\nimport * as Predicate from \"../Predicate.js\";\nimport * as References from \"../References.js\";\nimport * as Result from \"../Result.js\";\nimport * as Runtime from \"../Runtime.js\";\nimport * as Stdio from \"../Stdio.js\";\nimport * as Terminal from \"../Terminal.js\";\nimport * as CliConfig from \"./CliConfig.js\";\nimport * as CliError from \"./CliError.js\";\nimport * as CliOutput from \"./CliOutput.js\";\nimport * as GlobalFlag from \"./GlobalFlag.js\";\nimport { checkForDuplicateFlags, makeCommand, makeParser, toImpl, TypeId } from \"./internal/command.js\";\nimport { mergeConfig, parseConfig } from \"./internal/config.js\";\nimport { getGlobalFlagsForCommandPath, getGlobalFlagsForCommandTree, getHelpForCommandPath } from \"./internal/help.js\";\nimport * as Lexer from \"./internal/lexer.js\";\nimport * as Parser from \"./internal/parser.js\";\nimport * as Wizard from \"./internal/wizard.js\";\nimport * as Param from \"./Param.js\";\nimport * as Prompt from \"./Prompt.js\";\n/**\n * Returns `true` if the provided value is a `Command`.\n *\n * **Gotchas**\n *\n * This checks for the `Command` type-id property; it does not validate the full\n * command shape.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isCommand = u => Predicate.hasProperty(u, TypeId);\n/* ========================================================================== */\n/* Constructors */\n/* ========================================================================== */\n/**\n * Creates a `Command` from a name, an optional configuration, and an optional\n * handler.\n *\n * **Details**\n *\n * Use `withDescription` and related metadata combinators to add help text. The\n * overloads support simple commands, configured commands, and commands with\n * effectful handlers.\n *\n * **Example** (Creating commands)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Argument, Command, Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * // Simple command with no configuration\n * const version = Command.make(\"version\")\n *\n * // Command with simple flags\n * const greet = Command.make(\"greet\", {\n * name: Flag.String(\"name\"),\n * count: Flag.Int(\"count\").pipe(Flag.withDefault(1))\n * })\n *\n * // Command with nested configuration\n * const deploy = Command.make(\"deploy\", {\n * environment: Flag.String(\"env\").pipe(\n * Flag.withDescription(\"Target environment\")\n * ),\n * server: {\n * host: Flag.String(\"host\").pipe(Flag.withDefault(\"localhost\")),\n * port: Flag.Int(\"port\").pipe(Flag.withDefault(3000))\n * },\n * files: Argument.String(\"files\").pipe(Argument.variadic),\n * force: Flag.Boolean(\"force\").pipe(\n * Flag.withDescription(\"Force deployment\"),\n * Flag.withDefault(false)\n * )\n * })\n *\n * // Command with handler\n * const output: Array<string> = []\n * const deployWithHandler = Command.make(\"deploy\", {\n * environment: Flag.String(\"env\"),\n * force: Flag.Boolean(\"force\").pipe(Flag.withDefault(false))\n * }, (config) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => output.push(`Starting deployment to ${config.environment}`))\n *\n * if (!config.force && config.environment === \"production\") {\n * return yield* Effect.fail(\"Production deployments require --force flag\")\n * }\n *\n * yield* Effect.sync(() => output.push(\"Deployment completed successfully\"))\n * }))\n *\n * await Effect.runPromise(\n * Command.runWith(deployWithHandler, { version: \"1.0.0\" })([\n * \"--env\",\n * \"staging\",\n * \"--force\"\n * ]).pipe(Effect.provide(CliTestLayer))\n * )\n * output // => [\"Starting deployment to staging\", \"Deployment completed successfully\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = (name, config, handler) => {\n const parsedConfig = parseConfig(config ?? {});\n return makeCommand({\n name,\n config: parsedConfig,\n ...(Predicate.isNotUndefined(handler) ? {\n handle: handler\n } : {})\n });\n};\n/* ========================================================================== */\n/* Combinators */\n/* ========================================================================== */\n/**\n * Adds or replaces the handler for a command.\n *\n * **Example** (Adding command handlers)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * // Command without initial handler\n * const greet = Command.make(\"greet\", {\n * name: Flag.String(\"name\")\n * })\n *\n * // Add handler later\n * const output: Array<string> = []\n * const greetWithHandler = greet.pipe(\n * Command.withHandler((config: { readonly name: string }) =>\n * Effect.sync(() => output.push(`Hello, ${config.name}!`)).pipe(Effect.asVoid)\n * )\n * )\n *\n * await Effect.runPromise(\n * Command.runWith(greetWithHandler, { version: \"1.0.0\" })([\"--name\", \"Alice\"]).pipe(\n * Effect.provide(CliTestLayer)\n * )\n * )\n * output // => [\"Hello, Alice!\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withHandler = /*#__PURE__*/dual(2, (self, handler) => makeCommand({\n ...toImpl(self),\n handle: handler\n}));\nconst normalizeSubcommandEntries = entries => {\n const flat = [];\n const grouped = new Map();\n const addToGroup = (group, command) => {\n flat.push(command);\n const existing = grouped.get(group);\n if (existing) {\n existing.push(command);\n } else {\n grouped.set(group, [command]);\n }\n };\n for (const entry of entries) {\n if (isCommand(entry)) {\n addToGroup(undefined, entry);\n continue;\n }\n for (const command of entry.commands) {\n addToGroup(entry.group, command);\n }\n }\n const groups = [];\n const ungroupedCommands = grouped.get(undefined);\n if (ungroupedCommands && ungroupedCommands.length > 0) {\n groups.push({\n group: undefined,\n commands: ungroupedCommands\n });\n }\n for (const [group, commands] of grouped) {\n if (group === undefined) {\n continue;\n }\n groups.push({\n group,\n commands\n });\n }\n return {\n flat,\n groups\n };\n};\n/**\n * Adds subcommands to a command, creating a hierarchical command structure.\n *\n * **Details**\n *\n * Subcommands can access their parent's parsed configuration by yielding the parent\n * command within their handler. This enables shared parent flags that affect\n * all subcommands.\n *\n * **Example** (Adding subcommands)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * // Parent command with shared flags\n * const git = Command.make(\"git\").pipe(\n * Command.withSharedFlags({\n * verbose: Flag.Boolean(\"verbose\").pipe(Flag.withDefault(false))\n * })\n * )\n *\n * // Subcommand that accesses parent config\n * const output: Array<string> = []\n * const clone = Command.make(\"clone\", {\n * repository: Flag.String(\"repo\")\n * }, (config) =>\n * Effect.gen(function*() {\n * const parent = yield* git // Access parent's parsed config\n * if (parent.verbose) {\n * yield* Effect.sync(() => output.push(\"Verbose mode enabled\"))\n * }\n * yield* Effect.sync(() => output.push(`Cloning ${config.repository}`))\n * }))\n *\n * const app = git.pipe(Command.withSubcommands([clone]))\n *\n * await Effect.runPromise(\n * Command.runWith(app, { version: \"1.0.0\" })([\n * \"--verbose\",\n * \"clone\",\n * \"--repo\",\n * \"github.com/foo/bar\"\n * ]).pipe(Effect.provide(CliTestLayer))\n * )\n * output // => [\"Verbose mode enabled\", \"Cloning github.com/foo/bar\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withSubcommands = /*#__PURE__*/dual(2, (self, subcommands) => {\n const normalized = normalizeSubcommandEntries(subcommands);\n checkForDuplicateFlags(self, normalized.flat);\n const impl = toImpl(self);\n const byName = new Map(normalized.flat.map(s => [s.name, toImpl(s)]));\n const SubcommandStateSymbol = Symbol(\"effect/cli/SubcommandState\");\n const parse = Effect.fnUntraced(function* (raw) {\n if (Option.isNone(raw.subcommand)) {\n return yield* impl.parse(raw);\n }\n const sub = byName.get(raw.subcommand.value.name);\n if (!sub) {\n return yield* impl.parse(raw);\n }\n const context = yield* impl.parseContext(raw);\n const result = yield* sub.parse(raw.subcommand.value.parsedInput);\n return {\n ...context,\n [SubcommandStateSymbol]: {\n name: sub.name,\n result\n }\n };\n });\n const handle = Effect.fnUntraced(function* (input, path) {\n const internal = input;\n const selectedSubcommand = internal[SubcommandStateSymbol];\n if (selectedSubcommand) {\n const child = byName.get(selectedSubcommand.name);\n if (!child) {\n return yield* new CliError.ShowHelp({\n commandPath: path,\n errors: []\n });\n }\n return yield* child.handle(selectedSubcommand.result, [...path, child.name]).pipe(Effect.provideService(impl.service, input));\n }\n return yield* impl.handle(input, path);\n });\n return makeCommand({\n name: impl.name,\n config: impl.config,\n contextConfig: impl.contextConfig,\n description: impl.description,\n shortDescription: impl.shortDescription,\n alias: impl.alias,\n unlisted: impl.unlisted,\n annotations: impl.annotations,\n globalFlags: impl.globalFlags,\n examples: impl.examples,\n service: impl.service,\n subcommands: normalized.groups,\n parse,\n parseContext: impl.parseContext,\n handle\n });\n});\n/**\n * Adds flags that are inherited by subcommands.\n *\n * **Details**\n *\n * Shared flags are available to this command's handler and to descendant\n * handlers via `yield* parentCommand`. Shared flags are accepted both before\n * and after a selected subcommand name (npm-style).\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withSharedFlags = /*#__PURE__*/dual(2, (self, sharedFlags) => {\n const impl = toImpl(self);\n const sharedConfig = parseConfig(sharedFlags);\n const mergedConfig = mergeConfig(impl.config, sharedConfig);\n const mergedContextConfig = mergeConfig(impl.contextConfig, sharedConfig);\n if (impl.subcommands.length > 0) {\n const flatSubcommands = impl.subcommands.flatMap(group => group.commands);\n checkForDuplicateFlags(self, flatSubcommands, {\n contextConfig: mergedContextConfig\n });\n }\n const parseShared = makeParser(sharedConfig, {\n allowLeftovers: true\n });\n const parse = Effect.fnUntraced(function* (raw) {\n const base = yield* impl.parse(raw);\n const shared = yield* parseShared(raw);\n return {\n ...base,\n ...shared\n };\n });\n const parseContext = Effect.fnUntraced(function* (raw) {\n const base = yield* impl.parseContext(raw);\n const shared = yield* parseShared(raw);\n return {\n ...base,\n ...shared\n };\n });\n const handle = (input, commandPath) => impl.handle(input, commandPath);\n return makeCommand({\n name: impl.name,\n config: mergedConfig,\n contextConfig: mergedContextConfig,\n description: impl.description,\n shortDescription: impl.shortDescription,\n alias: impl.alias,\n unlisted: impl.unlisted,\n annotations: impl.annotations,\n globalFlags: impl.globalFlags,\n examples: impl.examples,\n service: impl.service,\n subcommands: impl.subcommands,\n parse,\n parseContext,\n handle\n });\n});\n/**\n * Adds global flags to a command scope.\n *\n * **Details**\n *\n * Declared global flags apply to the command and all of its descendants.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withGlobalFlags = /*#__PURE__*/dual(2, (self, globalFlags) => {\n const impl = toImpl(self);\n const next = Array.from(new Set([...impl.globalFlags, ...globalFlags]));\n return makeCommand({\n ...impl,\n globalFlags: next\n });\n});\n/**\n * Sets the description for a command.\n *\n * **Details**\n *\n * Descriptions provide users with information about what the command does\n * when they view help documentation.\n *\n * **Example** (Setting descriptions)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const output: Array<string> = []\n * const deploy = Command.make(\"deploy\", {\n * environment: Flag.String(\"env\")\n * }, (config) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => output.push(`Deploying to ${config.environment}`))\n * })).pipe(\n * Command.withDescription(\"Deploy the application to a specified environment\")\n * )\n *\n * await Effect.runPromise(\n * Command.runWith(deploy, { version: \"1.0.0\" })([\"--env\", \"staging\"]).pipe(Effect.provide(CliTestLayer))\n * )\n * output // => [\"Deploying to staging\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withDescription = /*#__PURE__*/dual(2, (self, description) => makeCommand({\n ...toImpl(self),\n description\n}));\n/**\n * Sets a short description for a command.\n *\n * **Details**\n *\n * Short descriptions are used when listing subcommands in help output and\n * shell completions. If no short description is provided, the full\n * `description` is used as a fallback.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withShortDescription = /*#__PURE__*/dual(2, (self, shortDescription) => makeCommand({\n ...toImpl(self),\n shortDescription\n}));\n/**\n * Sets an alias for a command.\n *\n * **Details**\n *\n * Aliases are accepted as alternate subcommand names during parsing and are\n * shown in help output as `name, alias`.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withAlias = /*#__PURE__*/dual(2, (self, alias) => makeCommand({\n ...toImpl(self),\n alias\n}));\n/**\n * Omits a subcommand from parent help output, shell completions, and\n * \"did you mean?\" suggestions while keeping it fully invocable by exact name.\n *\n * **When to use**\n *\n * Use when experimental or internal subcommands should be accepted but not advertised on\n * the public CLI surface.\n *\n * **Example** (Unlisting a subcommand)\n *\n * ```ts import.meta.vitest\n * import { Command } from \"effect/cli\"\n *\n * // `experimental` still runs when invoked as `mycli experimental`,\n * // but it does not appear under SUBCOMMANDS in `mycli --help`.\n * const experimental = Command.make(\"experimental\").pipe(\n * Command.unlisted\n * )\n *\n * const root = Command.make(\"mycli\").pipe(\n * Command.withSubcommands([experimental])\n * )\n *\n * root.subcommands[0].commands[0].unlisted // => true\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const unlisted = self => makeCommand({\n ...toImpl(self),\n unlisted: true\n});\n/**\n * Adds a custom annotation to a command.\n *\n * **When to use**\n *\n * Use to attach one command-scoped metadata value under a `Context.Key`,\n * especially for consumers such as custom help formatters.\n *\n * **Details**\n *\n * Annotations are stored on the command's annotation context and flow into\n * generated help document annotations.\n *\n * **Gotchas**\n *\n * Adding the same `Context.Key` again replaces the earlier value.\n *\n * @see {@link annotateMerge} for merging an existing annotation context\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const annotate = /*#__PURE__*/dual(3, (self, service, value) => {\n const impl = toImpl(self);\n return makeCommand({\n ...impl,\n annotations: Context.add(impl.annotations, service, value)\n });\n});\n/**\n * Merges a Context of annotations into a command.\n *\n * **When to use**\n *\n * Use when you need to attach an already-built `Context.Context` of command\n * annotations.\n *\n * **Details**\n *\n * Merged annotations are stored on the command and exposed through generated\n * help document annotations.\n *\n * **Gotchas**\n *\n * If both contexts contain the same `Context.Key`, the incoming annotations\n * context wins.\n *\n * @see {@link annotate} for adding a single annotation without constructing a `Context`\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const annotateMerge = /*#__PURE__*/dual(2, (self, annotations) => {\n const impl = toImpl(self);\n return makeCommand({\n ...impl,\n annotations: Context.merge(impl.annotations, annotations)\n });\n});\n/**\n * Sets usage examples for a command.\n *\n * **Details**\n *\n * Examples are exposed in structured `HelpDoc` data and rendered by the\n * default formatter in an `EXAMPLES` section.\n *\n * **Example** (Adding usage examples)\n *\n * ```ts import.meta.vitest\n * import { Command } from \"effect/cli\"\n *\n * const login = Command.make(\"login\").pipe(\n * Command.withExamples([\n * { command: \"myapp login\", description: \"Log in with browser OAuth\" },\n * { command: \"myapp login --token sbp_abc123\", description: \"Log in with a token\" }\n * ])\n * )\n *\n * login.examples.map((example) => example.command) // => [\"myapp login\", \"myapp login --token sbp_abc123\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const withExamples = /*#__PURE__*/dual(2, (self, examples) => makeCommand({\n ...toImpl(self),\n examples\n}));\n/* ========================================================================== */\n/* Providing Services */\n/* ========================================================================== */\n// Internal helper: transforms a command's handler while preserving other properties\nconst mapHandler = (self, f) => {\n const impl = toImpl(self);\n return makeCommand({\n ...impl,\n handle: (input, path) => f(impl.handle(input, path), input)\n });\n};\n/**\n * Provides the handler of a command with the services produced by a layer\n * that optionally depends on the command-line input to be created.\n *\n * **Example** (Providing command services)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, PlatformError, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const output: Array<string> = []\n * const deploy = Command.make(\"deploy\", {\n * env: Flag.String(\"env\")\n * }, (config) =>\n * Effect.gen(function*() {\n * const fs = yield* FileSystem.FileSystem\n * yield* Effect.sync(() => output.push(`Using file system for ${config.env}`))\n * })).pipe(\n * // Provide FileSystem based on the --env flag\n * Command.provide((config) =>\n * config.env === \"local\"\n * ? FileSystem.layerNoop({})\n * : FileSystem.layerNoop({\n * access: () =>\n * Effect.fail(\n * PlatformError.badArgument({\n * module: \"FileSystem\",\n * method: \"access\"\n * })\n * )\n * })\n * )\n * )\n *\n * await Effect.runPromise(\n * Command.runWith(deploy, { version: \"1.0.0\" })([\"--env\", \"local\"]).pipe(Effect.provide(CliTestLayer))\n * )\n * output // => [\"Using file system for local\"]\n * ```\n *\n * @stability unstable\n * @category providing services\n * @since 4.0.0\n */\nexport const provide = /*#__PURE__*/dual(args => isCommand(args[0]), (self, layer, options) => mapHandler(self, (handler, input) => Effect.provide(handler, typeof layer === \"function\" ? layer(input) : layer, options)));\n/**\n * Provides the handler of a command with the implementation of a service that\n * optionally depends on the command-line input to be constructed.\n *\n * **When to use**\n *\n * Use when a command handler needs a pure service implementation, optionally\n * derived from the parsed command input.\n *\n * @stability unstable\n * @category providing services\n * @since 4.0.0\n */\nexport const provideSync = /*#__PURE__*/dual(3, (self, service, implementation) => mapHandler(self, (handler, input) => Effect.provideService(handler, service, typeof implementation === \"function\" ? implementation(input) : implementation)));\n/**\n * Provides the handler of a command with the service produced by an effect\n * that optionally depends on the command-line input to be created.\n *\n * **When to use**\n *\n * Use to acquire a service effectfully for each command run, optionally using\n * parsed command input.\n *\n * @see {@link provideSync} for synchronous service acquisition\n * @see {@link provide} for providing an already-available service\n * @see {@link provideEffectDiscard} for running an effect before the handler without providing a service\n *\n * @stability unstable\n * @category providing services\n * @since 4.0.0\n */\nexport const provideEffect = /*#__PURE__*/dual(3, (self, service, effect) => mapHandler(self, (handler, input) => Effect.provideServiceEffect(handler, service, typeof effect === \"function\" ? effect(input) : effect)));\n/**\n * Allows for execution of an effect, which optionally depends on command-line\n * input to be created, prior to executing the handler of a command.\n *\n * @stability unstable\n * @category providing services\n * @since 4.0.0\n */\nexport const provideEffectDiscard = /*#__PURE__*/dual(2, (self, effect) => mapHandler(self, (handler, input) => Effect.andThen(typeof effect === \"function\" ? effect(input) : effect, handler)));\n/* ========================================================================== */\n/* Execution */\n/* ========================================================================== */\n/**\n * Interactively constructs command-line arguments for a command.\n *\n * **Details**\n *\n * The returned arguments include the command name and can be inspected,\n * modified, or passed to another command runner by the caller.\n *\n * **Example** (Constructing command arguments)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const command = Command.make(\"app\")\n * const silentConsole: Console.Console = Object.assign(Object.create(console), {\n * log: () => {}\n * })\n *\n * const program = Command.wizard(command).pipe(\n * Effect.provideService(Console.Console, silentConsole),\n * Effect.provide(CliTestLayer)\n * )\n *\n * await Effect.runPromise(program) // => [\"app\"]\n * ```\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const wizard = (command, options) => Effect.map(Wizard.run(command, options), result => result.args);\nconst getOutOfScopeGlobalFlagErrors = (allFlags, activeFlags, flagMap, commandPath) => {\n const activeSet = new Set(activeFlags);\n const errors = [];\n const seen = new Set();\n for (const flag of allFlags) {\n if (activeSet.has(flag)) {\n continue;\n }\n const singles = Param.extractSingleParams(flag.flag);\n for (const single of singles) {\n const entries = flagMap[single.name];\n if (!entries || entries.length === 0) {\n continue;\n }\n const option = `--${single.name}`;\n if (seen.has(option)) {\n continue;\n }\n seen.add(option);\n errors.push(new CliError.UnrecognizedOption({\n option,\n suggestions: [],\n command: commandPath\n }));\n }\n }\n return errors;\n};\nconst showHelp = (command, error, renderErrors) => Effect.gen(function* () {\n const {\n builtIns\n } = yield* CliConfig.CliConfig;\n const formatter = yield* CliOutput.Formatter;\n const helpDoc = yield* getHelpForCommandPath(command, error.commandPath, builtIns);\n yield* Console.log(formatter.formatHelpDoc(helpDoc));\n if (renderErrors && error.errors.length > 0) {\n yield* Console.error(formatter.formatErrors(error.errors));\n }\n});\nconst showUserError = error => Effect.gen(function* () {\n const formatter = yield* CliOutput.Formatter;\n yield* Console.error(formatter.formatError(error));\n error[Runtime.errorReported] = false;\n});\n/**\n * Runs a command using the arguments supplied by the `Stdio` service.\n *\n * **When to use**\n *\n * Use when command-line arguments should come from `Stdio` at the application\n * entry point.\n *\n * Help documents are always rendered. By default, parse error details and\n * `CliError.UserError` failures are also rendered with the installed\n * `CliOutput.Formatter` before the error is rethrown. Set `renderErrors` to\n * `false` when the host application owns error rendering.\n *\n * **Example** (Running commands with standard input)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({\n * args: Effect.succeed([\"--name\", \"Alice\"])\n * }),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const output: Array<string> = []\n * const greetCommand = Command.make(\"greet\", {\n * name: Flag.String(\"name\")\n * }, (config) =>\n * Effect.gen(function*() {\n * yield* Effect.sync(() => output.push(`Hello, ${config.name}!`))\n * }))\n *\n * // Automatically gets args from the Stdio service\n * const program = Command.run(greetCommand, {\n * version: \"1.0.0\"\n * })\n *\n * await Effect.runPromise(program.pipe(Effect.provide(CliTestLayer)))\n * output // => [\"Hello, Alice!\"]\n * ```\n *\n * @see {@link runWith} for running a command with an explicit argument array\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const run = /*#__PURE__*/dual(2, (command, config) => Stdio.Stdio.use(({\n args\n}) => Effect.flatMap(args, args => runWith(command, config)(args))));\n/**\n * Runs a command with explicitly provided arguments instead of using arguments from `Stdio`.\n *\n * **When to use**\n *\n * Use when you need to test CLI applications or programmatically execute\n * commands with specific arguments.\n *\n * Help documents are always rendered. By default, parse error details and\n * `CliError.UserError` failures are also rendered with the installed\n * `CliOutput.Formatter` before the error is rethrown. Set `renderErrors` to\n * `false` when the host application owns error rendering.\n *\n * **Example** (Running commands with explicit arguments)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/cli\"\n * import { ChildProcessSpawner } from \"effect/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n * FileSystem.layerNoop({}),\n * Path.layer,\n * Stdio.layerTest({}),\n * Layer.succeed(Terminal.Terminal, Terminal.make({\n * columns: Effect.succeed(80),\n * rows: Effect.succeed(24),\n * readInput: Effect.die(\"unused\"),\n * readLine: Effect.die(\"unused\"),\n * display: () => Effect.void\n * })),\n * Layer.succeed(\n * ChildProcessSpawner.ChildProcessSpawner,\n * ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n * )\n * )\n *\n * const output: Array<string> = []\n * const greet = Command.make(\"greet\", {\n * name: Flag.String(\"name\"),\n * count: Flag.Int(\"count\").pipe(Flag.withDefault(1))\n * }, (config) =>\n * Effect.gen(function*() {\n * for (let i = 0; i < config.count; i++) {\n * yield* Effect.sync(() => output.push(`Hello, ${config.name}!`))\n * }\n * }))\n *\n * // Test with specific arguments\n * const testProgram = Effect.gen(function*() {\n * const runCommand = Command.runWith(greet, { version: \"1.0.0\" })\n *\n * yield* runCommand([\"--name\", \"Alice\", \"--count\", \"2\"])\n * })\n *\n * await Effect.runPromise(testProgram.pipe(Effect.provide(CliTestLayer)))\n * output // => [\"Hello, Alice!\", \"Hello, Alice!\"]\n * ```\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const runWith = (command, config) => {\n const commandImpl = toImpl(command);\n return Effect.fnUntraced(function* (args) {\n const {\n builtIns\n } = yield* CliConfig.CliConfig;\n const {\n tokens,\n trailingOperands\n } = Lexer.lex(args);\n // 1. Collect known global flags from the command tree\n const allFlags = getGlobalFlagsForCommandTree(command, builtIns);\n // 2. Extract global flag tokens\n const allFlagParams = allFlags.flatMap(f => Param.extractSingleParams(f.flag));\n const globalRegistry = Parser.createFlagRegistry(allFlagParams.filter(Param.isFlagParam));\n const {\n flagMap,\n remainder,\n errors: globalFlagErrors\n } = Parser.consumeGlobalFlags(tokens, command, globalRegistry);\n const emptyArgs = {\n flags: flagMap,\n arguments: []\n };\n // 3. Parse command arguments from remaining tokens\n const parsedArgs = yield* Parser.parseArgs({\n tokens: remainder,\n trailingOperands\n }, command);\n const commandPath = [command.name, ...Parser.getCommandPath(parsedArgs)];\n const handlerCtx = {\n builtIns,\n command,\n commandPath,\n version: config.version\n };\n const activeFlags = getGlobalFlagsForCommandPath(command, commandPath, builtIns);\n // 4. Reject globals that were passed outside the active command scope\n const outOfScopeErrors = getOutOfScopeGlobalFlagErrors(allFlags, activeFlags, flagMap, commandPath);\n if (outOfScopeErrors.length > 0 || globalFlagErrors.length > 0) {\n const parseErrors = parsedArgs.errors ?? [];\n return yield* new CliError.ShowHelp({\n commandPath,\n errors: [...globalFlagErrors, ...outOfScopeErrors, ...parseErrors]\n });\n }\n // 5. Process action flags — first present action wins, then exit\n for (const flag of activeFlags) {\n if (flag._tag !== \"Action\") continue;\n const singles = Param.extractSingleParams(flag.flag);\n const hasEntry = singles.some(s => {\n const entries = flagMap[s.name];\n return entries !== undefined && entries.length > 0;\n });\n if (!hasEntry) continue;\n const [, value] = yield* flag.flag.parse(emptyArgs);\n if (flag === GlobalFlag.Wizard) {\n const {\n colors\n } = yield* Prompt.Theme;\n return yield* Effect.gen(function* () {\n yield* Console.log(Wizard.renderIntroduction(command.name, config.version, command.description, colors));\n const prefix = [command.name, ...args.filter(arg => arg !== \"--wizard\" && !arg.startsWith(\"--wizard=\"))];\n const wizardResult = yield* Wizard.run(command, {\n commandPath,\n prefix\n });\n yield* Console.log(Wizard.renderCompletion(wizardResult.displayArgs, colors));\n const shouldRun = yield* Prompt.run(Prompt.Toggle({\n message: \"Run this command?\",\n initial: true,\n active: \"yes\",\n inactive: \"no\"\n }));\n if (shouldRun) {\n yield* Console.log();\n yield* runWith(command, {\n ...config,\n renderErrors: false\n })(wizardResult.args.slice(1));\n }\n }).pipe(Effect.catchTag(\"QuitError\", () => Console.log(Wizard.renderQuit(colors))));\n }\n yield* flag.run(value, handlerCtx);\n return;\n }\n // 6. Handle parsing errors\n if (parsedArgs.errors && parsedArgs.errors.length > 0) {\n return yield* new CliError.ShowHelp({\n commandPath,\n errors: parsedArgs.errors\n });\n }\n const parseResult = yield* Effect.result(commandImpl.parse(parsedArgs));\n if (parseResult._tag === \"Failure\") {\n return yield* new CliError.ShowHelp({\n commandPath,\n errors: [parseResult.failure]\n });\n }\n // 7. Provide setting values\n let program = commandImpl.handle(parseResult.success, [command.name]);\n const logLevel = activeFlags.includes(GlobalFlag.LogLevel) ? (yield* GlobalFlag.LogLevel.flag.parse(emptyArgs))[1] : Option.none();\n program = Effect.provideService(program, GlobalFlag.LogLevel, logLevel);\n for (const flag of activeFlags) {\n if (flag._tag !== \"Setting\" || flag === GlobalFlag.LogLevel) continue;\n const [, value] = yield* flag.flag.parse(emptyArgs);\n program = Effect.provideService(program, flag, value);\n }\n // 8. Apply built-in setting behavior\n const services = Option.match(logLevel, {\n onNone: () => Context.empty(),\n onSome: level => Context.make(References.MinimumLogLevel, level)\n });\n // 9. Run command handler with composed context\n yield* Effect.provideContext(program, services);\n }, Effect.catchFilter(error => CliError.isCliError(error) && error._tag === \"ShowHelp\" ? Result.succeed(error) : Result.fail(error), error => Effect.andThen(showHelp(command, error, config.renderErrors !== false), Effect.fail(error))), Effect.catchFilter(error => config.renderErrors !== false && CliError.isCliError(error) && error._tag === \"UserError\" ? Result.succeed(error) : Result.fail(error), error => Effect.andThen(showUserError(error), Effect.fail(error))), Effect.catchFilter(e => Terminal.isQuitError(e) ? Result.succeed(e) : Result.fail(e), _ => Effect.interrupt));\n};\n//# sourceMappingURL=Command.js.map","/**\n * Service boundary for starting and controlling child processes.\n *\n * `ChildProcessSpawner` is the service used by `ChildProcess` commands to start\n * operating-system processes. A spawner turns a command description into a\n * handle that can write to stdin, read stdout and stderr, wait for exit, kill\n * the process, and manage whether the process keeps its parent alive. Platform\n * backends implement this service, while most application code uses the higher\n * level `ChildProcess` module.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Brand from \"../Brand.js\";\nimport * as Context from \"../Context.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Inspectable from \"../Inspectable.js\";\nimport * as Stream from \"../Stream.js\";\n/**\n * Constructs branded child process `ExitCode` values.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const ExitCode = /*#__PURE__*/Brand.nominal();\n/**\n * Constructs branded child process `ProcessId` values.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const ProcessId = /*#__PURE__*/Brand.nominal();\nconst HandleTypeId = \"~effect/process/ChildProcessSpawner/ChildProcessHandle\";\nconst HandleProto = {\n [HandleTypeId]: HandleTypeId,\n ...Inspectable.BaseProto,\n toJSON() {\n return {\n _id: \"ChildProcessHandle\",\n pid: this.pid\n };\n }\n};\n/**\n * Constructs a new `ChildProcessHandle`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeHandle = params => Object.setPrototypeOf({\n ...params\n}, HandleProto);\n/**\n * Creates a `ChildProcessSpawner` service from a `spawn` function, deriving\n * helpers for exit codes and output collection from that implementation.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = spawn => {\n const streamString = (command, options) => spawn(command).pipe(Effect.map(handle => Stream.decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), Stream.unwrap);\n const streamLines = (command, options) => Stream.splitLines(streamString(command, options));\n return ChildProcessSpawner.of({\n spawn,\n exitCode: command => Effect.scoped(Effect.flatMap(spawn(command), handle => handle.exitCode)),\n streamString,\n streamLines,\n lines: (command, options) => Stream.runCollect(streamLines(command, options)),\n string: (command, options) => Stream.mkString(streamString(command, options))\n });\n};\n/**\n * Service tag for child process spawning.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class ChildProcessSpawner extends /*#__PURE__*/Context.Service()(\"effect/process/ChildProcessSpawner\") {}\n//# sourceMappingURL=ChildProcessSpawner.js.map","/**\n * Describes child processes before they are started.\n *\n * A `Command` stores the executable, arguments, environment, standard streams,\n * working directory, and other process options. Commands can also be piped\n * together. A command is an `Effect`; running it asks the\n * `ChildProcessSpawner` service to start the process and returns a\n * `ChildProcessHandle`.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"../Context.js\";\nimport * as Effectable from \"../Effectable.js\";\nimport { dual } from \"../Function.js\";\nimport * as Predicate from \"../Predicate.js\";\nimport { ChildProcessSpawner } from \"./ChildProcessSpawner.js\";\nconst TypeId = \"~effect/process/ChildProcess\";\n// =============================================================================\n// Constructors\n// =============================================================================\nconst Proto = {\n ... /*#__PURE__*/Effectable.Prototype({\n label: \"Command\",\n evaluate(fiber) {\n return Context.getUnsafe(fiber.context, ChildProcessSpawner).spawn(this);\n }\n }),\n [TypeId]: TypeId\n};\n/**\n * Checks whether a value is a `Command`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isCommand = u => Predicate.hasProperty(u, TypeId);\n/**\n * Checks whether a command is a `StandardCommand`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isStandardCommand = command => command._tag === \"StandardCommand\";\n/**\n * Checks whether a command is a `PipedCommand`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isPipedCommand = command => command._tag === \"PipedCommand\";\nconst makeStandardCommand = (command, args, options) => Object.assign(Object.create(Proto), {\n _tag: \"StandardCommand\",\n command,\n args,\n options\n});\nconst makePipedCommand = (left, right, options = {}) => Object.assign(Object.create(Proto), {\n _tag: \"PipedCommand\",\n left,\n right,\n options\n});\n/**\n * Create a command from a template literal, options + template, or array form.\n *\n * **Details**\n *\n * This function supports three calling conventions:\n * 1. Template literal: `make\\`npm run build\\``\n * 2. Options + template literal: `make({ cwd: \"/app\" })\\`npm run build\\``\n * 3. Array form: `make(\"npm\", [\"run\", \"build\"], options?)`\n *\n * Template literals are not parsed until execution time, allowing parsing\n * errors to flow through Effect's error channel.\n *\n * **Example** (Creating commands)\n *\n * ```ts import.meta.vitest\n * import { ChildProcess } from \"effect/process\"\n *\n * // Template literal form\n * const cmd1 = ChildProcess.make`echo \"hello\"`\n *\n * // With options\n * const cmd2 = ChildProcess.make({ cwd: \"/tmp\" })`ls -la`\n *\n * // Array form\n * const cmd3 = ChildProcess.make(\"git\", [\"status\"])\n *\n * const result = [cmd1.command, cmd2.options.cwd, cmd3.args[0]] // => [\"echo\", \"/tmp\", \"status\"]\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = function make(...args) {\n // Template literal form: make`command`\n if (isTemplateString(args[0])) {\n const [templates, ...expressions] = args;\n const tokens = parseTemplates(templates, expressions);\n return makeStandardCommand(tokens[0] ?? \"\", tokens.slice(1), {});\n }\n // Options form: make({ cwd: \"/tmp\" })`command`\n if (typeof args[0] === \"object\" && !Array.isArray(args[0]) && !isTemplateString(args[0])) {\n const options = args[0];\n return function (templates, ...expressions) {\n const tokens = parseTemplates(templates, expressions);\n return makeStandardCommand(tokens[0] ?? \"\", tokens.slice(1), options);\n };\n }\n // Standard form without arguments: make(\"command\", options?)\n if (typeof args[0] === \"string\" && !Array.isArray(args[1])) {\n const [command, options = {}] = args;\n return makeStandardCommand(command, [], options);\n }\n // Standard form with arguments: make(\"command\", [\"arg1\", \"arg2\"], options?)\n const [command, cmdArgs = [], options = {}] = args;\n return makeStandardCommand(command, cmdArgs, options);\n};\n/**\n * Pipes the output of one command to the input of another.\n *\n * **Details**\n *\n * By default, pipes `stdout` from the source to `stdin` of the destination.\n * Use the `options` parameter to customize which streams are connected.\n *\n * **Example** (Piping command output)\n *\n * ```ts import.meta.vitest\n * import { ChildProcess } from \"effect/process\"\n *\n * // Pipe stdout (default)\n * const pipeline1 = ChildProcess.make`cat file.txt`.pipe(\n * ChildProcess.pipeTo(ChildProcess.make`grep pattern`)\n * )\n *\n * // Pipe stderr instead of stdout\n * const pipeline2 = ChildProcess.make`my-program`.pipe(\n * ChildProcess.pipeTo(ChildProcess.make`grep error`, { from: \"stderr\" })\n * )\n *\n * // Pipe combined stdout and stderr\n * const pipeline3 = ChildProcess.make`my-program`.pipe(\n * ChildProcess.pipeTo(ChildProcess.make`tee output.log`, { from: \"all\" })\n * )\n *\n * const result = [pipeline1._tag, pipeline2.options.from, pipeline3.options.from]\n * result // => [\"PipedCommand\", \"stderr\", \"all\"]\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const pipeTo = /*#__PURE__*/dual(args => isCommand(args[0]) && isCommand(args[1]), (self, that, options) => makePipedCommand(self, that, options ?? {}));\n/**\n * Prepends another command to a command.\n *\n * **Details**\n *\n * For pipelines, only the leftmost command is prefixed.\n *\n * **Example** (Prefixing commands)\n *\n * ```ts import.meta.vitest\n * import { ChildProcess } from \"effect/process\"\n *\n * const command = ChildProcess.make`echo \"foo\"`\n *\n * const prefixed = command.pipe(\n * ChildProcess.prefix`time`\n * )\n *\n * // now prefixed will execute `time echo \"foo\"`\n * const result = prefixed._tag === \"StandardCommand\" ? `${prefixed.command} ${prefixed.args[0]}` : prefixed._tag\n * result // => \"time echo\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const prefix = function prefix(...args) {\n if (isCommand(args[0]) && args.length > 1) {\n const [self, ...rest] = args;\n const prefixSpec = parsePrefixArgs(rest);\n return applyPrefix(self, prefixSpec);\n }\n const prefixSpec = parsePrefixArgs(args);\n return self => applyPrefix(self, prefixSpec);\n};\nconst parsePrefixArgs = args => {\n if (isTemplateString(args[0])) {\n const [templates, ...expressions] = args;\n const tokens = parseTemplates(templates, expressions);\n return {\n command: tokens[0] ?? \"\",\n args: tokens.slice(1)\n };\n }\n const [command, cmdArgs = []] = args;\n return {\n command,\n args: cmdArgs\n };\n};\nconst applyPrefix = (self, prefixSpec) => {\n switch (self._tag) {\n case \"StandardCommand\":\n {\n return makeStandardCommand(prefixSpec.command, [...prefixSpec.args, self.command, ...self.args], self.options);\n }\n case \"PipedCommand\":\n {\n return makePipedCommand(applyPrefix(self.left, prefixSpec), self.right, self.options);\n }\n }\n};\n/**\n * Sets the current working directory for a command.\n *\n * **Details**\n *\n * For pipelines, applies to each command in the pipeline.\n *\n * **Example** (Setting command working directories)\n *\n * ```ts import.meta.vitest\n * import { ChildProcess } from \"effect/process\"\n *\n * const cmd = ChildProcess.make`ls -la`.pipe(\n * ChildProcess.setCwd(\"/tmp\")\n * )\n * const result = cmd._tag === \"StandardCommand\" && cmd.options.cwd // => \"/tmp\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setCwd = /*#__PURE__*/dual(2, (self, cwd) => {\n switch (self._tag) {\n case \"StandardCommand\":\n {\n return makeStandardCommand(self.command, self.args, {\n ...self.options,\n cwd\n });\n }\n case \"PipedCommand\":\n {\n return makePipedCommand(setCwd(self.left, cwd), setCwd(self.right, cwd), self.options);\n }\n }\n});\n/**\n * Adds environment variables to a command, merging them with any existing\n * command environment and overriding duplicate keys.\n *\n * **Details**\n *\n * For pipelines, applies to each command in the pipeline.\n *\n * **Example** (Setting command environment variables)\n *\n * ```ts import.meta.vitest\n * import { ChildProcess } from \"effect/process\"\n *\n * const cmd = ChildProcess.make`node script.js`.pipe(\n * ChildProcess.setEnv({ NODE_ENV: \"test\" })\n * )\n * const result = cmd._tag === \"StandardCommand\" && cmd.options.env?.NODE_ENV // => \"test\"\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setEnv = /*#__PURE__*/dual(2, (self, env) => {\n switch (self._tag) {\n case \"StandardCommand\":\n {\n const nextEnv = self.options.env === undefined ? env : {\n ...self.options.env,\n ...env\n };\n return makeStandardCommand(self.command, self.args, {\n ...self.options,\n env: nextEnv\n });\n }\n case \"PipedCommand\":\n {\n return makePipedCommand(setEnv(self.left, env), setEnv(self.right, env), self.options);\n }\n }\n});\nconst isTemplateString = u => Array.isArray(u) && \"raw\" in u && Array.isArray(u.raw);\n// =============================================================================\n// Utilities\n// =============================================================================\n/**\n * Parses an fd name like \"fd3\" to its numeric index.\n * Returns undefined if the name is invalid.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const parseFdName = name => {\n const match = /^fd(\\d+)$/.exec(name);\n if (match === null) return undefined;\n const fd = parseInt(match[1], 10);\n return fd >= 3 ? fd : undefined;\n};\n/**\n * Create an fd name from its numeric index.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const fdName = fd => `fd${fd}`;\n// =============================================================================\n// Template Parsing\n// =============================================================================\nconst parseTemplates = (templates, expressions) => {\n let tokens = [];\n for (const [index, template] of templates.entries()) {\n tokens = parseTemplate(templates, expressions, tokens, template, index);\n }\n return tokens;\n};\nconst parseTemplate = (templates, expressions, prevTokens, template, index) => {\n const rawTemplate = templates.raw[index];\n if (rawTemplate === undefined) {\n throw new Error(`Invalid backslash sequence: ${templates.raw[index]}`);\n }\n const {\n hasLeadingWhitespace,\n hasTrailingWhitespace,\n tokens\n } = splitByWhitespaces(template, rawTemplate);\n const nextTokens = concatTokens(prevTokens, tokens, hasLeadingWhitespace);\n if (index === expressions.length) {\n return nextTokens;\n }\n const expression = expressions[index];\n const expressionTokens = Array.isArray(expression) ? expression.map(expression => parseExpression(expression)) : [parseExpression(expression)];\n return concatTokens(nextTokens, expressionTokens, hasTrailingWhitespace);\n};\n/**\n * Convert valid expressions defined in a template string command (i.e. using\n * `${expression}` into strings.\n */\nconst parseExpression = expression => {\n const type = typeof expression;\n if (type === \"string\") {\n return expression; // Return strings directly\n }\n return String(expression); // Convert numbers to strings\n};\nconst DELIMITERS = /*#__PURE__*/new Set([\" \", \"\\t\", \"\\r\", \"\\n\"]);\n/**\n * Number of characters in backslash escape sequences: \\0 \\xXX or \\uXXXX\n * \\cX is allowed in RegExps but not in strings\n * Octal sequences are not allowed in strict mode\n */\nconst ESCAPE_LENGTH = {\n x: 3,\n u: 5\n};\n/**\n * Splits a template string by whitespace while also properly handling escape\n * sequences.\n *\n * As an example, let's review the following valid commands:\n *\n * ```ts\n * ChildProcess.exec`echo foo\\n bar`\n * // We should run `[\"echo\", \"foo\\n\", \"bar\"]`\n *\n * ChildProcess.exec`echo foo\n * bar`\n * // We should run `[\"echo\", \"foo\", \"bar]`\n * ```\n *\n * The problem is that when we evaluate the template string for both of the above\n * commands, we will end up with the same string \"echo foo\\n bar\".\n *\n * What we really want is to include the escaped character in the arguments for\n * the first command, since it was written explicitly by the user.\n *\n * This is why also having access to the raw template string is useful - in a\n * template string, there are two representations of the same string:\n * 1. `template` - The processed string (escape sequences are evaluated).\n * 2. `template.raw` - The raw string (escape sequences are literal).\n */\nconst splitByWhitespaces = (template, rawTemplate) => {\n if (rawTemplate.length === 0) {\n return {\n tokens: [],\n hasLeadingWhitespace: false,\n hasTrailingWhitespace: false\n };\n }\n const hasLeadingWhitespace = DELIMITERS.has(rawTemplate[0]);\n const tokens = [];\n // Given that escape sequences will have different lengths in the template\n // versus the raw template, we must maintain two indices:\n // - One for the index into the template string\n // - One for the index into the raw template string\n // We also maintain the current cursor position for where we are in the template\n let templateCursor = 0;\n for (let templateIndex = 0, rawIndex = 0; templateIndex < template.length; templateIndex += 1, rawIndex += 1) {\n // Use the raw template character to check for actual whitespace\n const rawCharacter = rawTemplate[rawIndex];\n if (DELIMITERS.has(rawCharacter)) {\n // Whitespace found, extract token from template if necessary\n if (templateCursor !== templateIndex) {\n tokens.push(template.slice(templateCursor, templateIndex));\n }\n // Advance the template start index to the current position\n templateCursor = templateIndex + 1;\n } else if (rawCharacter === \"\\\\\") {\n // Escape sequence detected, check the next raw character\n const nextRawCharacter = rawTemplate[rawIndex + 1];\n if (nextRawCharacter === \"\\n\") {\n // Handle `\\` character followed by a newline (i.e. a line continuation) by:\n // - Reversing the template index (backslash-newline is erased in template)\n // - Advancing the raw template index past the line continuation\n templateIndex -= 1;\n rawIndex += 1;\n } else if (nextRawCharacter === \"u\" && rawTemplate[rawIndex + 2] === \"{\") {\n // Handle variable-length unicode escape sequences (i.e. `\\u{1F600}`) by:\n // - Advancing the template index an extra code unit for astral code points\n // - Advancing the raw template index past the unicode escape sequence\n const end = rawTemplate.indexOf(\"}\", rawIndex + 3);\n if (parseInt(rawTemplate.slice(rawIndex + 3, end), 16) > 0xffff) {\n templateIndex += 1;\n }\n rawIndex = end;\n } else {\n // Advance raw template index past fixed-length escape sequences:\n // - \\n → 2 chars (backslash + n)\n // - \\t → 2 chars (backslash + t)\n // - \\xHH → 4 chars (backslash + x + H + H)\n // - \\uHHHH → 6 chars (backslash + u + H + H + H + H)\n rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;\n }\n }\n }\n // Trailing whitespace only exists if the template cursor is equivalent to the\n // length of the template\n const hasTrailingWhitespace = templateCursor === template.length;\n // If we did not end with trailing whitespace, ensure the final token is added\n if (!hasTrailingWhitespace) {\n tokens.push(template.slice(templateCursor));\n }\n return {\n tokens,\n hasLeadingWhitespace,\n hasTrailingWhitespace\n };\n};\n/**\n * Concatenates two separate sets of string tokens together.\n *\n * If either set is empty or `isSeparated=false`, the last element of `prevTokens`\n * and the first element of `nextTokens` will be joined into a single token.\n */\nconst concatTokens = (prevTokens, nextTokens, isSeparated) => isSeparated || prevTokens.length === 0 || nextTokens.length === 0\n// Keep the previous and next tokens separate from one another\n? [...prevTokens, ...nextTokens]\n// Join the last token from the previous set and the first token from the next set\n: [...prevTokens.slice(0, -1), `${prevTokens.at(-1)}${nextTokens.at(0)}`, ...nextTokens.slice(1)];\n//# sourceMappingURL=ChildProcess.js.map","export const buildSpawnOptions = (options, base, platform) => {\n const detached = options.detached ?? platform !== \"win32\";\n return {\n ...base,\n detached,\n shell: options.shell,\n windowsHide: options.windowsHide ?? !detached\n };\n};\n//# sourceMappingURL=nodeChildProcessSpawner.js.map","import * as PlatformError from \"effect/PlatformError\";\n/** @internal */\nexport const handleErrnoException = (module, method) => (err, [path]) => {\n let reason = \"Unknown\";\n switch (err.code) {\n case \"ENOENT\":\n reason = \"NotFound\";\n break;\n case \"EACCES\":\n reason = \"PermissionDenied\";\n break;\n case \"EEXIST\":\n reason = \"AlreadyExists\";\n break;\n case \"EISDIR\":\n reason = \"BadResource\";\n break;\n case \"ENOTDIR\":\n reason = \"BadResource\";\n break;\n case \"EBUSY\":\n reason = \"Busy\";\n break;\n case \"ELOOP\":\n reason = \"BadResource\";\n break;\n }\n return PlatformError.systemError({\n _tag: reason,\n module,\n method,\n pathOrDescriptor: path,\n syscall: err.syscall,\n cause: err\n });\n};\n//# sourceMappingURL=utils.js.map","import * as Cause from \"effect/Cause\";\nimport * as Channel from \"effect/Channel\";\nimport * as Effect from \"effect/Effect\";\nimport { identity } from \"effect/Function\";\nimport * as Pull from \"effect/Pull\";\nimport * as Sink from \"effect/Sink\";\n/**\n * Creates a `Sink` that writes chunks to a Node writable stream, respecting\n * backpressure, mapping writable errors with `onError`, and ending the stream\n * on completion unless `endOnDone` is `false`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromWritable = options => Sink.fromChannel(Channel.mapDone(fromWritableChannel(options), _ => [_]));\n/**\n * Creates a `Channel` that pulls chunks from upstream and writes them to a\n * Node writable stream, respecting backpressure and optionally ending the\n * writable when upstream is done.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromWritableChannel = options => Channel.fromTransform(pull => {\n const writable = options.evaluate();\n return Effect.succeed(pullIntoWritable({\n ...options,\n writable,\n pull\n }));\n});\n/**\n * Writes Effect chunks into a Node writable stream.\n *\n * **When to use**\n *\n * Use to implement custom Node stream adapters that already have an upstream\n * pull and need direct control over a writable stream.\n *\n * **Details**\n *\n * The loop waits for `drain` when needed, fails on writable errors, and ends\n * the writable on upstream completion unless `endOnDone` is `false`.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const pullIntoWritable = options => options.pull.pipe(Effect.flatMap(chunk => {\n let i = 0;\n return Effect.callback(resume => {\n let cancelled = false;\n const loop = () => {\n for (; i < chunk.length;) {\n if (cancelled) {\n return;\n }\n const success = options.writable.write(chunk[i++], options.encoding);\n if (!success) {\n if (!cancelled) {\n options.writable.once(\"drain\", loop);\n }\n return;\n }\n }\n if (!cancelled) {\n resume(Effect.void);\n }\n };\n loop();\n return Effect.sync(() => {\n cancelled = true;\n options.writable.off(\"drain\", loop);\n });\n });\n}), Effect.forever({\n disableYield: true\n}), options.endOnDone !== false ? Pull.catchDone(_ => {\n if (\"closed\" in options.writable && options.writable.closed) {\n return Cause.done(_);\n }\n return Effect.callback(resume => {\n const onFinish = () => resume(Cause.done(_));\n options.writable.once(\"finish\", onFinish);\n options.writable.end();\n return Effect.sync(() => {\n options.writable.off(\"finish\", onFinish);\n });\n });\n}) : identity, Effect.raceFirst(Effect.callback(resume => {\n const onError = error => resume(Effect.fail(options.onError(error)));\n options.writable.once(\"error\", onError);\n return Effect.sync(() => {\n options.writable.off(\"error\", onError);\n });\n})));\n//# sourceMappingURL=NodeSink.js.map","/**\n * Adapters between Node streams and Effect streams, channels, and readables.\n *\n * This module is the stream boundary for Node APIs. It wraps `Readable` and\n * `Duplex` values as Effect `Stream`s and `Channel`s, pipes Effect streams\n * through Node duplex streams, exposes an Effect `Stream` back to Node as a\n * `Readable`, and collects readable payloads into strings, array buffers, or\n * `Uint8Array`s with optional byte limits.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Arr from \"effect/Array\";\nimport * as ByteSize from \"effect/ByteSize\";\nimport * as Cause from \"effect/Cause\";\nimport * as Channel from \"effect/Channel\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport { dual } from \"effect/Function\";\nimport * as Latch from \"effect/Latch\";\nimport * as MutableRef from \"effect/MutableRef\";\nimport * as Pull from \"effect/Pull\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport { Readable } from \"node:stream\";\nimport { pullIntoWritable } from \"./NodeSink.js\";\n/**\n * Converts a Node readable stream into an Effect `Stream`, reading chunks with\n * an optional chunk size, mapping stream errors with `onError`, and destroying\n * the readable on completion unless `closeOnDone` is `false`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromReadable = options => Stream.fromChannel(fromReadableChannel(options));\n/**\n * Creates a `Channel` that pulls chunks from a Node readable stream, mapping\n * errors with `onError` and destroying the readable on completion unless\n * `closeOnDone` is `false`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromReadableChannel = options => Channel.fromTransform((_, scope) => readableToPullUnsafe({\n scope,\n readable: options.evaluate(),\n onError: options.onError ?? defaultOnError,\n chunkSize: options.chunkSize,\n closeOnDone: options.closeOnDone\n}));\n/**\n * Creates a `Channel` over a Node `Duplex`, writing upstream chunks with\n * backpressure while emitting chunks read from the duplex and optionally ending\n * the writable side when upstream completes.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromDuplex = options => Channel.fromTransform((upstream, scope) => {\n const duplex = options.evaluate();\n const exit = MutableRef.make(undefined);\n const latch = Latch.makeUnsafe(false);\n return pullIntoWritable({\n pull: upstream,\n writable: duplex,\n onError: options.onError ?? defaultOnError,\n endOnDone: options.endOnDone,\n encoding: options.encoding\n }).pipe(Effect.catchCause(cause => {\n if (Pull.isDoneCause(cause)) return Effect.void;\n exit.current = Exit.failCause(cause);\n latch.openUnsafe();\n return Effect.void;\n }), Effect.forkIn(scope), Effect.flatMap(() => readableToPullUnsafe({\n scope,\n exit,\n latch,\n readable: duplex,\n onError: options.onError ?? defaultOnError,\n chunkSize: options.chunkSize\n })));\n});\n/**\n * Pipes an Effect `Stream` through a Node `Duplex`, writing the stream's\n * chunks to the duplex and emitting chunks read back from it.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const pipeThroughDuplex = /*#__PURE__*/dual(2, (self, options) => Stream.pipeThroughChannelOrFail(self, fromDuplex(options)));\n/**\n * Pipes a stream of strings or bytes through a Node `Duplex` using default\n * options and `Cause.UnknownError` for stream failures.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const pipeThroughSimple = /*#__PURE__*/dual(2, (self, duplex) => pipeThroughDuplex(self, {\n evaluate: duplex\n}));\n/**\n * Converts an Effect `Stream` into a Node `Readable`, using the caller's\n * Effect context to run the stream and destroying the readable if the stream\n * fails.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toReadable = stream => Effect.map(Effect.context(), context => new StreamAdapter(context, stream));\n/**\n * Converts a service-free Effect `Stream` into a Node `Readable` using an\n * empty Effect context.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toReadableNever = stream => new StreamAdapter(Context.empty(), stream);\n/**\n * Consumes a Node readable stream into a string using the selected encoding,\n * failing through `onError` on stream errors or when `maxBytes` is exceeded\n * and destroying the stream on interruption or failure.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toString = (readable, options) => {\n const maxBytesNumber = toMaxBytes(options?.maxBytes);\n const onError = options?.onError ?? defaultOnError;\n const encoding = options?.encoding ?? \"utf8\";\n return Effect.callback(resume => {\n const stream = readable();\n stream.setEncoding(encoding);\n stream.once(\"error\", err => {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n resume(Effect.fail(onError(err)));\n });\n let string = \"\";\n let bytes = 0;\n stream.once(\"end\", () => {\n resume(Effect.succeed(string));\n });\n stream.on(\"data\", chunk => {\n string += chunk;\n bytes += Buffer.byteLength(chunk);\n if (maxBytesNumber !== undefined && bytes > maxBytesNumber) {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n resume(Effect.fail(onError(new Error(\"maxBytes exceeded\"))));\n }\n });\n return Effect.sync(() => {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n });\n });\n};\n/**\n * Consumes a Node readable stream into an `ArrayBuffer`, failing through\n * `onError` on stream errors or when `maxBytes` is exceeded and destroying the\n * stream on interruption or failure.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toArrayBuffer = (readable, options) => {\n const maxBytesNumber = toMaxBytes(options?.maxBytes);\n const onError = options?.onError ?? defaultOnError;\n return Effect.callback(resume => {\n const stream = readable();\n const buffers = [];\n let bytes = 0;\n stream.once(\"error\", err => {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n resume(Effect.fail(onError(err)));\n });\n stream.once(\"end\", () => {\n const buffer = buffers.length === 1 ? buffers[0] : Buffer.concat(buffers);\n if (buffer.byteOffset === 0 && buffer.buffer.byteLength === buffer.byteLength) {\n return resume(Effect.succeed(buffer.buffer));\n }\n resume(Effect.succeed(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)));\n });\n stream.on(\"data\", chunk => {\n buffers.push(chunk);\n bytes += chunk.length;\n if (maxBytesNumber !== undefined && bytes > maxBytesNumber) {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n resume(Effect.fail(onError(new Error(\"maxBytes exceeded\"))));\n }\n });\n return Effect.sync(() => {\n if (\"closed\" in stream && !stream.closed) {\n stream.destroy();\n }\n });\n });\n};\n/**\n * Consumes a Node readable stream into a `Uint8Array`, using the same error\n * mapping and `maxBytes` handling as `toArrayBuffer`.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toUint8Array = (readable, options) => Effect.map(toArrayBuffer(readable, options), buffer => new Uint8Array(buffer));\n// ----------------------------------------------------------------------------\n// internal\n// ----------------------------------------------------------------------------\nconst readableToPullUnsafe = options => {\n const readable = options.readable;\n const closeOnDone = options.closeOnDone ?? true;\n const exit = options.exit ?? MutableRef.make(undefined);\n const latch = options.latch ?? Latch.makeUnsafe(false);\n function onReadable() {\n latch.openUnsafe();\n }\n function onError(error) {\n exit.current = Exit.fail(options.onError(error));\n latch.openUnsafe();\n }\n function onEnd() {\n exit.current = Exit.fail(Cause.Done());\n latch.openUnsafe();\n }\n readable.on(\"readable\", onReadable);\n readable.once(\"error\", onError);\n readable.once(\"end\", onEnd);\n const pull = Effect.suspend(function loop() {\n let item = options.readable.read(options.chunkSize);\n if (item === null) {\n if (exit.current) {\n return exit.current;\n }\n if (readable.readableEnded) {\n return Effect.fail(Cause.Done());\n }\n latch.closeUnsafe();\n return Effect.flatMap(latch.await, loop);\n }\n const chunk = Arr.of(item);\n while (true) {\n item = options.readable.read(options.chunkSize);\n if (item === null) break;\n chunk.push(item);\n }\n return Effect.succeed(chunk);\n });\n return Effect.as(Scope.addFinalizer(options.scope, Effect.sync(() => {\n readable.off(\"readable\", onReadable);\n readable.off(\"error\", onError);\n readable.off(\"end\", onEnd);\n if (closeOnDone && \"closed\" in options.readable && !options.readable.closed) {\n options.readable.destroy();\n }\n })), pull);\n};\nclass StreamAdapter extends Readable {\n readLatch;\n fiber = undefined;\n constructor(context, stream) {\n super({});\n this.readLatch = Latch.makeUnsafe(false);\n this.fiber = Stream.runForEachArray(stream, chunk => this.readLatch.whenOpen(Effect.sync(() => {\n this.readLatch.closeUnsafe();\n for (let i = 0; i < chunk.length; i++) {\n const item = chunk[i];\n if (typeof item === \"string\") {\n this.push(item, \"utf8\");\n } else {\n this.push(item);\n }\n }\n }))).pipe(this.readLatch.whenOpen, Effect.provideContext(context), Effect.runFork);\n this.fiber.addObserver(exit => {\n this.fiber = undefined;\n if (Exit.isSuccess(exit)) {\n this.push(null);\n } else {\n this.destroy(Cause.squash(exit.cause));\n }\n });\n }\n _read(_size) {\n this.readLatch.openUnsafe();\n }\n _destroy(error, callback) {\n if (!this.fiber) {\n return callback(error);\n }\n Effect.runFork(Fiber.interrupt(this.fiber)).addObserver(exit => {\n callback(exit._tag === \"Failure\" ? Cause.squash(exit.cause) : error);\n });\n }\n}\nconst defaultOnError = error => new Cause.UnknownError(error);\nconst toMaxBytes = maxBytes => maxBytes === undefined || maxBytes === Infinity ? undefined : Number(ByteSize.fromInputUnsafe(maxBytes));\n//# sourceMappingURL=NodeStream.js.map","import * as Deferred from \"effect/Deferred\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as ChildProcess from \"effect/process/ChildProcess\";\nimport { ChildProcessSpawner, ExitCode, make as makeSpawner, makeHandle, ProcessId } from \"effect/process/ChildProcessSpawner\";\nimport * as Sink from \"effect/Sink\";\nimport * as Stream from \"effect/Stream\";\nimport * as NodeChildProcess from \"node:child_process\";\nimport { PassThrough } from \"node:stream\";\nimport { buildSpawnOptions } from \"./internal/nodeChildProcessSpawner.js\";\nimport { handleErrnoException } from \"./internal/utils.js\";\nimport * as NodeSink from \"./NodeSink.js\";\nimport * as NodeStream from \"./NodeStream.js\";\nconst toError = error => error instanceof globalThis.Error ? error : new globalThis.Error(String(error));\nconst toPlatformError = (method, error, command) => {\n const {\n commands\n } = flattenCommand(command);\n const commandStr = commands.reduce((acc, curr) => {\n const cmd = `${curr.command} ${curr.args.join(\" \")}`;\n return acc.length === 0 ? cmd : `${acc} | ${cmd}`;\n }, \"\");\n return handleErrnoException(\"ChildProcess\", method)(error, [commandStr]);\n};\nconst processGroupGraceMillis = 1_000;\nconst processGroupPollIntervalMillis = 10;\n// Buffered writes can fail after the sink has been interrupted and removed its\n// error listener. Keep a fallback until close, without replacing the sink\n// listener that propagates errors while it is active.\nconst handleInputErrors = writable => {\n const onError = () => {};\n writable.on(\"error\", onError);\n writable.once(\"close\", () => writable.off(\"error\", onError));\n};\n/** The leader has not exited, or a member of its process group still exists. */\nconst isProcessAlive = (childProcess, exitSignal) => {\n if (!Deferred.isDoneUnsafe(exitSignal)) {\n return true;\n }\n if (globalThis.process.platform === \"win32\") {\n return false;\n }\n try {\n globalThis.process.kill(-childProcess.pid, 0);\n return true;\n } catch {\n return false;\n }\n};\nconst taskkill = (childProcess, onExit = () => {}) => {\n // After the leader exits, its PID may be reused by an unrelated process.\n if (childProcess.exitCode !== null || childProcess.signalCode !== null) {\n onExit(null);\n return;\n }\n NodeChildProcess.execFile(\"taskkill\", [\"/pid\", String(childProcess.pid), \"/T\", \"/F\"], {\n windowsHide: true\n }, onExit);\n};\nconst make = /*#__PURE__*/Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const resolveWorkingDirectory = Effect.fnUntraced(function* (options) {\n if (Predicate.isUndefined(options.cwd)) return undefined;\n // Validate that the specified directory is accessible\n yield* fs.access(options.cwd);\n return path.resolve(options.cwd);\n });\n const resolveEnvironment = options => {\n return options.extendEnv ? {\n ...globalThis.process.env,\n ...options.env\n } : options.env;\n };\n const inputToStdioOption = input => Stream.isStream(input) ? \"pipe\" : input;\n const outputToStdioOption = input => Sink.isSink(input) ? \"pipe\" : input;\n const resolveStdinOption = options => {\n const defaultConfig = {\n stream: \"pipe\",\n encoding: \"utf-8\",\n endOnDone: true\n };\n if (Predicate.isUndefined(options.stdin)) {\n return defaultConfig;\n }\n if (typeof options.stdin === \"string\") {\n return {\n ...defaultConfig,\n stream: options.stdin\n };\n }\n if (Stream.isStream(options.stdin)) {\n return {\n ...defaultConfig,\n stream: options.stdin\n };\n }\n return {\n stream: options.stdin.stream,\n encoding: options.stdin.encoding ?? defaultConfig.encoding,\n endOnDone: options.stdin.endOnDone ?? defaultConfig.endOnDone\n };\n };\n const resolveOutputOption = (options, streamName) => {\n const option = options[streamName];\n if (Predicate.isUndefined(option)) {\n return {\n stream: \"pipe\"\n };\n }\n if (typeof option === \"string\") {\n return {\n stream: option\n };\n }\n if (Sink.isSink(option)) {\n return {\n stream: option\n };\n }\n return {\n stream: option.stream\n };\n };\n const resolveAdditionalFds = options => {\n if (Predicate.isUndefined(options.additionalFds)) {\n return [];\n }\n const result = [];\n for (const [name, config] of Object.entries(options.additionalFds)) {\n const fd = ChildProcess.parseFdName(name);\n if (Predicate.isNotUndefined(fd)) {\n result.push({\n fd,\n config\n });\n }\n }\n // Sort by fd number to ensure correct ordering\n return result.sort((a, b) => a.fd - b.fd);\n };\n const buildStdioArray = (stdinConfig, stdoutConfig, stderrConfig, additionalFds) => {\n const stdio = [inputToStdioOption(stdinConfig.stream), outputToStdioOption(stdoutConfig.stream), outputToStdioOption(stderrConfig.stream)];\n if (additionalFds.length === 0) {\n return stdio;\n }\n // Find the maximum fd number to size the array correctly\n const maxFd = additionalFds.reduce((max, {\n fd\n }) => Math.max(max, fd), 2);\n // Fill gaps with \"ignore\"\n for (let i = 3; i <= maxFd; i++) {\n stdio[i] = \"ignore\";\n }\n // Set up additional fds as \"pipe\"\n for (const {\n fd\n } of additionalFds) {\n stdio[fd] = \"pipe\";\n }\n return stdio;\n };\n const setupAdditionalFds = Effect.fnUntraced(function* (command, childProcess, additionalFds) {\n if (additionalFds.length === 0) {\n return {\n getInputFd: () => Sink.drain,\n getOutputFd: () => Stream.empty\n };\n }\n const inputSinks = new Map();\n const outputStreams = new Map();\n for (const {\n config,\n fd\n } of additionalFds) {\n const nodeStream = childProcess.stdio[fd];\n switch (config.type) {\n case \"input\":\n {\n // Create a sink to write to for input file descriptors\n let sink = Sink.drain;\n if (nodeStream && \"write\" in nodeStream) {\n handleInputErrors(nodeStream);\n sink = NodeSink.fromWritable({\n evaluate: () => nodeStream,\n onError: error => toPlatformError(`fromWritable(fd${fd})`, toError(error), command)\n });\n }\n // If user provided a stream, pipe it into the sink\n if (config.stream) {\n yield* Effect.forkScoped(Stream.run(config.stream, sink));\n }\n inputSinks.set(fd, sink);\n break;\n }\n case \"output\":\n {\n // Create a stream to read from for output file descriptors\n let stream = Stream.empty;\n if (nodeStream && \"read\" in nodeStream) {\n const passThrough = new PassThrough();\n nodeStream.on(\"error\", error => passThrough.destroy(error));\n nodeStream.pipe(passThrough);\n stream = NodeStream.fromReadable({\n evaluate: () => passThrough,\n onError: error => toPlatformError(`fromReadable(fd${fd})`, toError(error), command)\n });\n }\n // If user provided a sink, transduce the stream through it\n if (config.sink) {\n stream = Stream.transduce(stream, config.sink);\n }\n outputStreams.set(fd, stream);\n break;\n }\n }\n }\n return {\n getInputFd: fd => inputSinks.get(fd) ?? Sink.drain,\n getOutputFd: fd => outputStreams.get(fd) ?? Stream.empty\n };\n });\n const setupChildStdin = (command, childProcess, config) => Effect.suspend(() => {\n // If the child process has a standard input stream, connect it to the\n // sink that will attached to the process handle\n let sink = Sink.drain;\n if (Predicate.isNotNull(childProcess.stdin)) {\n handleInputErrors(childProcess.stdin);\n sink = NodeSink.fromWritable({\n evaluate: () => childProcess.stdin,\n onError: error => toPlatformError(\"fromWritable(stdin)\", toError(error), command),\n endOnDone: config.endOnDone,\n encoding: config.encoding\n });\n }\n // If the user provided a `Stream`, run it into the stdin sink\n if (Stream.isStream(config.stream)) {\n return Effect.as(Effect.forkScoped(Stream.run(config.stream, sink)), sink);\n }\n return Effect.succeed(sink);\n });\n const setupChildOutputStreams = (command, childProcess, stdoutConfig, stderrConfig) => {\n let stdout = childProcess.stdout ? (() => {\n const passThrough = new PassThrough();\n childProcess.stdout.on(\"error\", error => passThrough.destroy(error));\n childProcess.stdout.pipe(passThrough);\n return NodeStream.fromReadable({\n evaluate: () => passThrough,\n onError: error => toPlatformError(\"fromReadable(stdout)\", toError(error), command)\n });\n })() : Stream.empty;\n let stderr = childProcess.stderr ? (() => {\n const passThrough = new PassThrough();\n childProcess.stderr.on(\"error\", error => passThrough.destroy(error));\n childProcess.stderr.pipe(passThrough);\n return NodeStream.fromReadable({\n evaluate: () => passThrough,\n onError: error => toPlatformError(\"fromReadable(stderr)\", toError(error), command)\n });\n })() : Stream.empty;\n if (Sink.isSink(stdoutConfig.stream)) {\n stdout = Stream.transduce(stdout, stdoutConfig.stream);\n }\n if (Sink.isSink(stderrConfig.stream)) {\n stderr = Stream.transduce(stderr, stderrConfig.stream);\n }\n const all = Stream.merge(stdout, stderr);\n return {\n stdout,\n stderr,\n all\n };\n };\n const spawn = (command, spawnOptions) => Effect.callback(resume => {\n const deferred = Deferred.makeUnsafe();\n const handle = NodeChildProcess.spawn(command.command, command.args, spawnOptions);\n handle.on(\"error\", error => {\n resume(Effect.fail(toPlatformError(\"spawn\", error, command)));\n });\n handle.on(\"exit\", (...args) => {\n Deferred.doneUnsafe(deferred, Exit.succeed(args));\n });\n handle.on(\"spawn\", () => {\n resume(Effect.succeed([handle, deferred]));\n });\n return Effect.sync(() => {\n handle.kill(\"SIGTERM\");\n });\n });\n const killProcessGroup = (command, childProcess, signal) => {\n if (globalThis.process.platform === \"win32\") {\n return Effect.callback(resume => {\n taskkill(childProcess, error => {\n if (error) {\n resume(Effect.fail(toPlatformError(\"kill\", toError(error), command)));\n } else {\n resume(Effect.void);\n }\n });\n });\n }\n return Effect.try({\n try: () => {\n globalThis.process.kill(-childProcess.pid, signal);\n },\n catch: error => toPlatformError(\"kill\", toError(error), command)\n });\n };\n const killProcessGroupOnExit = (childProcess, signal) => {\n if (globalThis.process.platform === \"win32\") {\n // ignore errors during best-effort cleanup\n taskkill(childProcess);\n return;\n }\n try {\n globalThis.process.kill(-childProcess.pid, signal);\n } catch {\n // ignore errors during best-effort cleanup\n }\n };\n const killProcess = (command, childProcess, signal) => Effect.suspend(() => {\n const killed = childProcess.kill(signal);\n if (!killed) {\n const error = new globalThis.Error(\"Failed to kill child process\");\n return Effect.fail(toPlatformError(\"kill\", error, command));\n }\n return Effect.void;\n });\n /** Waits for the leader and its process group, bounded by native time. */\n const awaitProcessExit = (childProcess, exitSignal, timeoutMillis) => Effect.callback(resume => {\n const deadline = Date.now() + timeoutMillis;\n let timer;\n const stop = () => {\n clearTimeout(timer);\n childProcess.removeListener(\"exit\", poll);\n };\n const poll = () => {\n clearTimeout(timer);\n if (Date.now() >= deadline || !isProcessAlive(childProcess, exitSignal)) {\n stop();\n resume(Effect.void);\n return;\n }\n timer = setTimeout(poll, processGroupPollIntervalMillis);\n };\n // spawn's exit listener completes exitSignal before this listener runs\n childProcess.on(\"exit\", poll);\n poll();\n return Effect.sync(stop);\n });\n const terminateProcessGroup = Effect.fnUntraced(function* (command, childProcess, exitSignal, options) {\n const signalGroup = signal => killProcessGroup(command, childProcess, signal).pipe(Effect.catch(() => killProcess(command, childProcess, signal)));\n yield* signalGroup(options?.killSignal ?? \"SIGTERM\");\n if (Predicate.isUndefined(options?.forceKillAfter)) {\n yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis);\n } else {\n yield* awaitProcessExit(childProcess, exitSignal, Duration.toMillis(options.forceKillAfter));\n if (isProcessAlive(childProcess, exitSignal)) {\n yield* signalGroup(\"SIGKILL\");\n yield* awaitProcessExit(childProcess, exitSignal, processGroupGraceMillis);\n }\n }\n yield* Deferred.await(exitSignal);\n });\n /**\n * Get the appropriate source stream from a process handle based on the\n * `from` pipe option.\n */\n const getSourceStream = (handle, from) => {\n const fromOption = from ?? \"stdout\";\n switch (fromOption) {\n case \"stdout\":\n return handle.stdout;\n case \"stderr\":\n return handle.stderr;\n case \"all\":\n return handle.all;\n default:\n {\n // Handle fd3, fd4, etc.\n const fd = ChildProcess.parseFdName(fromOption);\n if (Predicate.isNotUndefined(fd)) {\n return handle.getOutputFd(fd);\n }\n // Fallback to stdout for invalid fd names\n return handle.stdout;\n }\n }\n };\n const spawnCommand = Effect.fnUntraced(function* (cmd) {\n switch (cmd._tag) {\n case \"StandardCommand\":\n {\n const stdinConfig = resolveStdinOption(cmd.options);\n const stdoutConfig = resolveOutputOption(cmd.options, \"stdout\");\n const stderrConfig = resolveOutputOption(cmd.options, \"stderr\");\n const resolvedAdditionalFds = resolveAdditionalFds(cmd.options);\n let isReferenced = true;\n const cwd = yield* resolveWorkingDirectory(cmd.options);\n const env = resolveEnvironment(cmd.options);\n const stdio = buildStdioArray(stdinConfig, stdoutConfig, stderrConfig, resolvedAdditionalFds);\n const [childProcess, exitSignal] = yield* Effect.acquireRelease(spawn(cmd, buildSpawnOptions(cmd.options, {\n cwd,\n env,\n stdio\n }, process.platform)), Effect.fnUntraced(function* ([childProcess, exitSignal]) {\n const exited = yield* Deferred.isDone(exitSignal);\n if (exited) {\n const [code] = yield* Deferred.await(exitSignal);\n if (code !== 0 && Predicate.isNotNull(code)) {\n yield* Effect.ignore(terminateProcessGroup(cmd, childProcess, exitSignal, cmd.options));\n } else if (isReferenced && process.platform !== \"win32\" && cmd.options.detached !== false) {\n yield* Effect.ignore(terminateProcessGroup(cmd, childProcess, exitSignal, cmd.options));\n }\n return;\n }\n if (!isReferenced) {\n return;\n }\n yield* Effect.ignore(terminateProcessGroup(cmd, childProcess, exitSignal, cmd.options));\n }));\n const pid = ProcessId(childProcess.pid);\n childProcess.on(\"exit\", code => {\n if (code !== 0 && Predicate.isNotNull(code)) {\n killProcessGroupOnExit(childProcess, cmd.options.killSignal ?? \"SIGTERM\");\n }\n });\n const reref = Effect.sync(() => {\n if (!isReferenced) {\n childProcess.ref();\n isReferenced = true;\n }\n });\n const unref = Effect.sync(() => {\n if (isReferenced) {\n childProcess.unref();\n isReferenced = false;\n }\n return reref;\n });\n const stdin = yield* setupChildStdin(cmd, childProcess, stdinConfig);\n const {\n all,\n stderr,\n stdout\n } = setupChildOutputStreams(cmd, childProcess, stdoutConfig, stderrConfig);\n const {\n getInputFd,\n getOutputFd\n } = yield* setupAdditionalFds(cmd, childProcess, resolvedAdditionalFds);\n const isRunning = Effect.map(Deferred.isDone(exitSignal), done => !done);\n const exitCode = Effect.flatMap(Deferred.await(exitSignal), ([code, signal]) => {\n if (Predicate.isNotNull(code)) {\n return Effect.succeed(ExitCode(code));\n }\n // If code is `null`, then `signal` must be defined. See the NodeJS\n // documentation for the `\"exit\"` event on a `child_process`.\n // https://nodejs.org/api/child_process.html#child_process_event_exit\n const error = new globalThis.Error(`Process interrupted due to receipt of signal: '${signal}'`);\n return Effect.fail(toPlatformError(\"exitCode\", error, cmd));\n });\n const kill = options => terminateProcessGroup(cmd, childProcess, exitSignal, options);\n return makeHandle({\n pid,\n exitCode,\n isRunning,\n kill,\n stdin,\n stdout,\n stderr,\n all,\n getInputFd,\n getOutputFd,\n unref\n });\n }\n case \"PipedCommand\":\n {\n const {\n commands,\n pipeOptions\n } = flattenCommand(cmd);\n const [root, ...pipeline] = commands;\n const handles = [yield* spawnCommand(root)];\n for (let i = 0; i < pipeline.length; i++) {\n const command = pipeline[i];\n const options = pipeOptions[i] ?? {};\n const stdinConfig = resolveStdinOption(command.options);\n // Get the appropriate stream from the source based on `from` option\n const sourceStream = Stream.unwrap(Effect.succeed(getSourceStream(handles[handles.length - 1], options.from)));\n // Determine where to pipe: stdin or custom fd\n const toOption = options.to ?? \"stdin\";\n if (toOption === \"stdin\") {\n // Pipe to stdin (default behavior)\n handles.push(yield* spawnCommand(ChildProcess.make(command.command, command.args, {\n ...command.options,\n stdin: {\n ...stdinConfig,\n stream: sourceStream\n }\n })));\n } else {\n // Pipe to custom fd (fd3, fd4, etc.)\n const fd = ChildProcess.parseFdName(toOption);\n if (Predicate.isNotUndefined(fd)) {\n const fdName = ChildProcess.fdName(fd);\n const existingFds = command.options.additionalFds ?? {};\n handles.push(yield* spawnCommand(ChildProcess.make(command.command, command.args, {\n ...command.options,\n additionalFds: {\n ...existingFds,\n [fdName]: {\n type: \"input\",\n stream: sourceStream\n }\n }\n })));\n } else {\n // Invalid fd name, fall back to stdin\n handles.push(yield* spawnCommand(ChildProcess.make(command.command, command.args, {\n ...command.options,\n stdin: {\n ...stdinConfig,\n stream: sourceStream\n }\n })));\n }\n }\n }\n const handle = handles[handles.length - 1];\n const kill = options => Effect.forEach([...handles].reverse(), handle => Effect.ignore(handle.kill(options)), {\n discard: true\n });\n const unref = Effect.gen(function* () {\n const rerefs = [];\n for (const handle of handles) {\n rerefs.push(yield* handle.unref);\n }\n return Effect.forEach([...rerefs].reverse(), reref => reref, {\n discard: true\n });\n });\n return makeHandle({\n pid: handle.pid,\n exitCode: handle.exitCode,\n isRunning: handle.isRunning,\n kill,\n stdin: handles[0].stdin,\n stdout: handle.stdout,\n stderr: handle.stderr,\n all: handle.all,\n getInputFd: handle.getInputFd,\n getOutputFd: handle.getOutputFd,\n unref\n });\n }\n }\n });\n return makeSpawner(spawnCommand);\n});\n/**\n * Layer that provides the `NodeChildProcessSpawner` implementation.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.effect(ChildProcessSpawner, make);\n/**\n * Flattens a `Command` into an array of `StandardCommand`s along with pipe\n * options for each connection.\n *\n * @stability unstable\n * @category transforming\n * @since 4.0.0\n */\nexport const flattenCommand = command => {\n const commands = [];\n const pipeOptions = [];\n const flatten = cmd => {\n switch (cmd._tag) {\n case \"StandardCommand\":\n {\n commands.push(cmd);\n break;\n }\n case \"PipedCommand\":\n {\n // Recursively flatten left side first\n flatten(cmd.left);\n // Store the pipe options for this connection\n pipeOptions.push(cmd.options);\n // Then flatten right side\n flatten(cmd.right);\n break;\n }\n }\n };\n flatten(command);\n // The commands array is guaranteed to be non-empty since we always have at\n // least one command in the input. We validate this at runtime and return a\n // properly typed tuple.\n if (commands.length === 0) {\n // This should never happen given a valid Command input\n throw new Error(\"flattenCommand produced empty commands array\");\n }\n const [first, ...rest] = commands;\n const nonEmptyCommands = [first, ...rest];\n return {\n commands: nonEmptyCommands,\n pipeOptions\n };\n};\n//# sourceMappingURL=NodeChildProcessSpawner.js.map","/**\n * Node-compatible implementation of Effect's `Crypto` service.\n *\n * This module builds the service from `node:crypto`, using `randomBytes` for\n * random data and `createHash` for supported digest algorithms. It exports\n * `make` as the concrete service value and `layer` for providing it through\n * Effect context.\n *\n * @stability unstable\n * @since 1.0.0\n */\nimport * as EffectCrypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as NodeCrypto from \"node:crypto\";\nconst toHashAlgorithm = algorithm => {\n switch (algorithm) {\n case \"SHA-1\":\n return \"sha1\";\n case \"SHA-256\":\n return \"sha256\";\n case \"SHA-384\":\n return \"sha384\";\n case \"SHA-512\":\n return \"sha512\";\n }\n};\nconst digest = (algorithm, data) => Effect.try({\n try: () => Uint8Array.from(NodeCrypto.createHash(toHashAlgorithm(algorithm)).update(data).digest()),\n catch: cause => PlatformError.systemError({\n module: \"Crypto\",\n method: \"digest\",\n _tag: \"Unknown\",\n description: \"Could not compute digest\",\n cause\n })\n});\n/**\n * The default Node.js Crypto service implementation.\n *\n * @stability unstable\n * @category constructors\n * @since 1.0.0\n */\nexport const make = /*#__PURE__*/EffectCrypto.make({\n randomBytes: NodeCrypto.randomBytes,\n digest\n});\n/**\n * Layer that provides the Node.js Crypto service implementation.\n *\n * @stability unstable\n * @category layers\n * @since 1.0.0\n */\nexport const layer = /*#__PURE__*/Layer.succeed(EffectCrypto.Crypto, make);\n//# sourceMappingURL=NodeCrypto.js.map","/**\n * The `NodeCrypto` module provides the Node.js `Crypto` service layer for\n * Effect programs. Provide {@link layer} at the edge of a Node application,\n * CLI, script, or test to satisfy `effect/Crypto` with Node's `node:crypto`\n * implementation for secure random bytes, UUID generation, random values, and\n * SHA digest operations.\n *\n * This module is the public Node adapter around the shared Node-compatible\n * implementation. Digest failures are reported as platform errors, and SHA-1\n * remains available only for interoperability with existing protocols.\n *\n * @stability unstable\n * @since 1.0.0\n */\nimport * as NodeCrypto from \"@effect/platform-node-shared/NodeCrypto\";\n/**\n * Layer that provides the Node.js Crypto service implementation.\n *\n * @stability unstable\n * @category layers\n * @since 1.0.0\n */\nexport const layer = NodeCrypto.layer;\n//# sourceMappingURL=NodeCrypto.js.map","/**\n * Shared Node-compatible implementation of Effect's `FileSystem` service.\n *\n * This module adapts Node's `node:fs`, `node:os`, and `node:path` APIs into a\n * `FileSystem` layer for Effect programs running on Node-compatible runtimes.\n * Platform packages use it to provide file and directory I/O, permissions,\n * links, metadata, temporary files and directories, and file watching through\n * the shared `FileSystem` service.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as BI from \"effect/BigInt\";\nimport * as ByteSize from \"effect/ByteSize\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport { effectify } from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport { pipe } from \"effect/Function\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Error from \"effect/PlatformError\";\nimport * as Queue from \"effect/Queue\";\nimport * as Stream from \"effect/Stream\";\nimport * as Crypto from \"node:crypto\";\nimport * as NFS from \"node:fs\";\nimport * as OS from \"node:os\";\nimport * as Path from \"node:path\";\nimport { handleErrnoException } from \"./internal/utils.js\";\nconst handleBadArgument = method => err => Error.badArgument({\n module: \"FileSystem\",\n method,\n description: err.message ?? String(err)\n});\nconst bigintToNumber = (value, field) => {\n const number = Number(value);\n if (!Number.isSafeInteger(number)) {\n throw new RangeError(`${field} exceeds the safe integer range: ${value}`);\n }\n return number;\n};\nconst bigintToNumberOption = value => Option.flatMap(Option.fromNullishOr(value), BI.toNumber);\n// Node fills bigint stats from a BigInt64Array, so unsigned 64-bit values such\n// as dev_t and ino_t at or above 2^63 are reported as negative.\nconst toUint64 = value => BigInt.asUintN(64, value);\nconst toUint64Option = value => Option.map(Option.fromNullishOr(value), toUint64);\n// fs.write ignores bigint positions.\nconst positionToNumber = (position, method) => Effect.try({\n try: () => bigintToNumber(position, \"position\"),\n catch: handleBadArgument(method)\n});\n// == access\nconst access = /*#__PURE__*/(() => {\n const nodeAccess = /*#__PURE__*/effectify(NFS.access, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"access\"), /*#__PURE__*/handleBadArgument(\"access\"));\n return (path, options) => {\n let mode = NFS.constants.F_OK;\n if (options?.readable) {\n mode |= NFS.constants.R_OK;\n }\n if (options?.writable) {\n mode |= NFS.constants.W_OK;\n }\n return nodeAccess(path, mode);\n };\n})();\n// == copy\nconst copy = /*#__PURE__*/(() => {\n const nodeCp = /*#__PURE__*/effectify(NFS.cp, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"copy\"), /*#__PURE__*/handleBadArgument(\"copy\"));\n return (fromPath, toPath, options) => nodeCp(fromPath, toPath, {\n force: options?.overwrite ?? false,\n preserveTimestamps: options?.preserveTimestamps ?? false,\n recursive: true\n });\n})();\n// == copyFile\nconst copyFile = /*#__PURE__*/(() => {\n const nodeCopyFile = /*#__PURE__*/effectify(NFS.copyFile, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"copyFile\"), /*#__PURE__*/handleBadArgument(\"copyFile\"));\n return (fromPath, toPath) => nodeCopyFile(fromPath, toPath);\n})();\n// == chmod\nconst chmod = /*#__PURE__*/(() => {\n const nodeChmod = /*#__PURE__*/effectify(NFS.chmod, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"chmod\"), /*#__PURE__*/handleBadArgument(\"chmod\"));\n return (path, mode) => nodeChmod(path, mode);\n})();\n// == chown\nconst chown = /*#__PURE__*/(() => {\n const nodeChown = /*#__PURE__*/effectify(NFS.chown, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"chown\"), /*#__PURE__*/handleBadArgument(\"chown\"));\n return (path, uid, gid) => nodeChown(path, uid, gid);\n})();\n// == glob\nconst glob = /*#__PURE__*/(() => {\n const nodeGlob = /*#__PURE__*/effectify(NFS.glob, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"glob\"), /*#__PURE__*/handleBadArgument(\"glob\"));\n return (pattern, options) => nodeGlob(pattern, {\n cwd: options?.root,\n exclude: options?.exclude\n });\n})();\n// == link\nconst link = /*#__PURE__*/(() => {\n const nodeLink = /*#__PURE__*/effectify(NFS.link, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"link\"), /*#__PURE__*/handleBadArgument(\"link\"));\n return (existingPath, newPath) => nodeLink(existingPath, newPath);\n})();\n// == makeDirectory\nconst makeDirectory = /*#__PURE__*/(() => {\n const nodeMkdir = /*#__PURE__*/effectify(NFS.mkdir, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"makeDirectory\"), /*#__PURE__*/handleBadArgument(\"makeDirectory\"));\n return (path, options) => nodeMkdir(path, {\n recursive: options?.recursive ?? false,\n mode: options?.mode\n });\n})();\n// == makeTempDirectory\nconst makeTempDirectoryFactory = method => {\n const nodeMkdtemp = effectify(NFS.mkdtemp, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n return options => Effect.suspend(() => {\n const prefix = options?.prefix ?? \"\";\n const directory = typeof options?.directory === \"string\" ? Path.join(options.directory, \".\") : OS.tmpdir();\n return nodeMkdtemp(prefix ? Path.join(directory, prefix) : directory + \"/\");\n });\n};\nconst makeTempDirectory = /*#__PURE__*/makeTempDirectoryFactory(\"makeTempDirectory\");\n// == remove\nconst removeFactory = method => {\n const nodeRm = effectify(NFS.rm, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n return (path, options) => nodeRm(path, {\n recursive: options?.recursive ?? false,\n force: options?.force ?? false\n });\n};\nconst remove = /*#__PURE__*/removeFactory(\"remove\");\n// == makeTempDirectoryScoped\nconst makeTempDirectoryScoped = /*#__PURE__*/(() => {\n const makeDirectory = /*#__PURE__*/makeTempDirectoryFactory(\"makeTempDirectoryScoped\");\n const removeDirectory = /*#__PURE__*/removeFactory(\"makeTempDirectoryScoped\");\n return options => Effect.acquireRelease(makeDirectory(options), directory => Effect.orDie(removeDirectory(directory, {\n recursive: true\n })));\n})();\n// == open\nconst openFlagBits = flag => {\n const {\n O_APPEND,\n O_CREAT,\n O_EXCL,\n O_RDONLY,\n O_RDWR,\n O_TRUNC,\n O_WRONLY\n } = NFS.constants;\n switch (flag) {\n case \"r\":\n return O_RDONLY;\n case \"r+\":\n return O_RDWR;\n case \"w\":\n return O_TRUNC | O_CREAT | O_WRONLY;\n case \"wx\":\n return O_TRUNC | O_CREAT | O_WRONLY | O_EXCL;\n case \"w+\":\n return O_TRUNC | O_CREAT | O_RDWR;\n case \"wx+\":\n return O_TRUNC | O_CREAT | O_RDWR | O_EXCL;\n case \"a\":\n return O_APPEND | O_CREAT | O_WRONLY;\n case \"ax\":\n return O_APPEND | O_CREAT | O_WRONLY | O_EXCL;\n case \"a+\":\n return O_APPEND | O_CREAT | O_RDWR;\n case \"ax+\":\n return O_APPEND | O_CREAT | O_RDWR | O_EXCL;\n }\n};\n// Reject unsupported platforms: libuv silently ignores unknown flags on Windows.\nconst noFollowFlags = (method, flag) => Effect.suspend(() => {\n const {\n O_NOFOLLOW\n } = NFS.constants;\n if (process.platform === \"win32\" || typeof O_NOFOLLOW !== \"number\" || O_NOFOLLOW === 0) {\n return Effect.fail(Error.badArgument({\n module: \"FileSystem\",\n method,\n description: \"noFollow is not supported on this platform\"\n }));\n }\n return Effect.succeed(openFlagBits(flag) | O_NOFOLLOW);\n});\nconst openFactory = method => {\n const nodeOpen = effectify(NFS.open, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n const nodeClose = effectify(NFS.close, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n return (path, options) => pipe(Effect.acquireRelease(options?.noFollow === true ? Effect.flatMap(noFollowFlags(method, options.flag ?? \"r\"), flags => nodeOpen(path, flags, options.mode)) : nodeOpen(path, options?.flag ?? \"r\", options?.mode), fd => Effect.orDie(nodeClose(fd))), Effect.map(fd => makeFile(fd, options?.flag?.startsWith(\"a\") ?? false)));\n};\nconst open = /*#__PURE__*/openFactory(\"open\");\nconst negativePosition = method => Error.badArgument({\n module: \"FileSystem\",\n method,\n description: \"Cannot read before the start of the file\"\n});\nconst makeFile = /*#__PURE__*/(() => {\n const nodeReadFactory = method => effectify(NFS.read, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n const nodeRead = /*#__PURE__*/nodeReadFactory(\"read\");\n const nodeReadAlloc = /*#__PURE__*/nodeReadFactory(\"readAlloc\");\n const nodeStat = /*#__PURE__*/effectify(NFS.fstat, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"stat\"), /*#__PURE__*/handleBadArgument(\"stat\"));\n const nodeTruncate = /*#__PURE__*/effectify(NFS.ftruncate, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"truncate\"), /*#__PURE__*/handleBadArgument(\"truncate\"));\n const nodeSync = /*#__PURE__*/effectify(NFS.fsync, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"sync\"), /*#__PURE__*/handleBadArgument(\"sync\"));\n const nodeWriteFactory = method => effectify(NFS.write, handleErrnoException(\"FileSystem\", method), handleBadArgument(method));\n const nodeWrite = /*#__PURE__*/nodeWriteFactory(\"write\");\n const nodeWriteAll = /*#__PURE__*/nodeWriteFactory(\"writeAll\");\n class FileImpl {\n [FileSystem.FileTypeId];\n fd;\n append;\n position = /*#__PURE__*/BigInt(0);\n constructor(fd, append) {\n this[FileSystem.FileTypeId] = FileSystem.FileTypeId;\n this.fd = fd;\n this.append = append;\n }\n get stat() {\n return Effect.flatMap(nodeStat(this.fd, {\n bigint: true\n }), makeFileInfo);\n }\n get sync() {\n return nodeSync(this.fd);\n }\n seek(offset, from) {\n return Effect.suspend(() => {\n const position = from === \"start\" ? offset : this.position + offset;\n if (position < BigInt(0)) {\n return Effect.fail(Error.badArgument({\n module: \"FileSystem\",\n method: \"seek\",\n description: \"Cannot seek before the start of the file\"\n }));\n }\n this.position = position;\n return Effect.succeed(position);\n });\n }\n read(buffer, options) {\n return Effect.suspend(() => {\n const explicit = options?.position;\n if (explicit !== undefined) {\n return explicit < BigInt(0) ? Effect.fail(negativePosition(\"read\")) : nodeRead(this.fd, {\n buffer,\n position: explicit\n });\n }\n const position = this.position;\n return Effect.map(nodeRead(this.fd, {\n buffer,\n position\n }), bytesRead => {\n this.position = position + BigInt(bytesRead);\n return bytesRead;\n });\n });\n }\n readAlloc(size, options) {\n return Effect.suspend(() => {\n try {\n if (!Number.isInteger(size) || size < 0) {\n throw new RangeError(\"size must be a non-negative integer\");\n }\n const explicit = options?.position;\n if (explicit !== undefined && explicit < BigInt(0)) {\n return Effect.fail(negativePosition(\"readAlloc\"));\n }\n const buffer = Buffer.allocUnsafeSlow(size);\n const position = explicit ?? this.position;\n return Effect.map(nodeReadAlloc(this.fd, {\n buffer,\n position\n }), bytesRead => {\n if (bytesRead === 0) {\n return Option.none();\n }\n if (explicit === undefined) {\n this.position = position + BigInt(bytesRead);\n }\n if (bytesRead === size) {\n return Option.some(buffer);\n }\n const dst = Buffer.allocUnsafeSlow(bytesRead);\n buffer.copy(dst, 0, 0, bytesRead);\n return Option.some(dst);\n });\n } catch (cause) {\n return Effect.fail(handleBadArgument(\"readAlloc\")(cause));\n }\n });\n }\n truncate(length) {\n return Effect.map(nodeTruncate(this.fd, length || undefined), () => {\n if (!this.append) {\n const len = BigInt(length ?? 0);\n if (this.position > len) {\n this.position = len;\n }\n }\n });\n }\n write(buffer) {\n return Effect.suspend(() => {\n const position = this.position;\n return Effect.flatMap(this.append ? Effect.succeed(undefined) : positionToNumber(position, \"write\"), nodePosition => Effect.map(nodeWrite(this.fd, buffer, undefined, undefined, nodePosition), bytesWritten => {\n if (!this.append) {\n this.position = position + BigInt(bytesWritten);\n }\n return bytesWritten;\n }));\n });\n }\n writeAllChunk(buffer) {\n return Effect.suspend(() => {\n const position = this.position;\n return Effect.flatMap(this.append ? Effect.succeed(undefined) : positionToNumber(position, \"writeAll\"), nodePosition => Effect.flatMap(nodeWriteAll(this.fd, buffer, undefined, undefined, nodePosition), bytesWritten => {\n if (bytesWritten === 0) {\n return Effect.fail(Error.systemError({\n module: \"FileSystem\",\n method: \"writeAll\",\n _tag: \"WriteZero\",\n pathOrDescriptor: this.fd,\n description: \"write returned 0 bytes written\"\n }));\n }\n if (!this.append) {\n this.position = position + BigInt(bytesWritten);\n }\n return bytesWritten < buffer.length ? this.writeAllChunk(buffer.subarray(bytesWritten)) : Effect.void;\n }));\n });\n }\n writeAll(buffer) {\n return buffer.length === 0 ? Effect.void : this.writeAllChunk(buffer);\n }\n }\n return (fd, append) => new FileImpl(fd, append);\n})();\n// == makeTempFile\nconst makeTempFileFactory = method => {\n const makeDirectory = makeTempDirectoryFactory(method);\n return Effect.fnUntraced(function* (options) {\n const directory = yield* makeDirectory(options);\n const random = Crypto.randomBytes(6).toString(\"hex\");\n const name = Path.join(directory, options?.suffix ? `${random}${options.suffix}` : random);\n yield* writeFile(name, new Uint8Array(0));\n return name;\n });\n};\nconst makeTempFile = /*#__PURE__*/makeTempFileFactory(\"makeTempFile\");\n// == makeTempFileScoped\nconst makeTempFileScoped = /*#__PURE__*/(() => {\n const makeFile = /*#__PURE__*/makeTempFileFactory(\"makeTempFileScoped\");\n const removeDirectory = /*#__PURE__*/removeFactory(\"makeTempFileScoped\");\n return options => Effect.acquireRelease(makeFile(options), file => Effect.orDie(removeDirectory(Path.dirname(file), {\n recursive: true\n })));\n})();\n// == readDirectory\nconst readDirectory = (path, options) => Effect.tryPromise({\n try: () => NFS.promises.readdir(path, options),\n catch: err => handleErrnoException(\"FileSystem\", \"readDirectory\")(err, [path])\n});\n// == readFile\nconst readFile = path => Effect.callback((resume, signal) => {\n try {\n NFS.readFile(path, {\n signal\n }, (err, data) => {\n if (err) {\n resume(Effect.fail(handleErrnoException(\"FileSystem\", \"readFile\")(err, [path])));\n } else {\n resume(Effect.succeed(data));\n }\n });\n } catch (err) {\n resume(Effect.fail(handleBadArgument(\"readFile\")(err)));\n }\n});\n// == readLink\nconst readLink = /*#__PURE__*/(() => {\n const nodeReadLink = /*#__PURE__*/effectify(NFS.readlink, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"readLink\"), /*#__PURE__*/handleBadArgument(\"readLink\"));\n return path => nodeReadLink(path);\n})();\n// == realPath\nconst realPath = /*#__PURE__*/(() => {\n const nodeRealPath = /*#__PURE__*/effectify(NFS.realpath, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"realPath\"), /*#__PURE__*/handleBadArgument(\"realPath\"));\n return path => nodeRealPath(path);\n})();\n// == rename\nconst rename = /*#__PURE__*/(() => {\n const nodeRename = /*#__PURE__*/effectify(NFS.rename, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"rename\"), /*#__PURE__*/handleBadArgument(\"rename\"));\n return (oldPath, newPath) => nodeRename(oldPath, newPath);\n})();\n// == stat\nconst makeFileInfo = stat => Effect.try({\n try: () => ({\n type: stat.isFile() ? \"File\" : stat.isDirectory() ? \"Directory\" : stat.isSymbolicLink() ? \"SymbolicLink\" : stat.isBlockDevice() ? \"BlockDevice\" : stat.isCharacterDevice() ? \"CharacterDevice\" : stat.isFIFO() ? \"FIFO\" : stat.isSocket() ? \"Socket\" : \"Unknown\",\n mtime: Option.fromNullishOr(stat.mtime),\n atime: Option.fromNullishOr(stat.atime),\n birthtime: Option.fromNullishOr(stat.birthtime),\n dev: toUint64(stat.dev),\n rdev: toUint64Option(stat.rdev),\n ino: toUint64Option(stat.ino),\n mode: bigintToNumber(stat.mode, \"mode\"),\n nlink: toUint64Option(stat.nlink),\n uid: bigintToNumberOption(stat.uid),\n gid: bigintToNumberOption(stat.gid),\n size: ByteSize.bytes(stat.size),\n blksize: stat.blksize !== undefined ? Option.some(ByteSize.bytes(stat.blksize)) : Option.none(),\n blocks: Option.fromNullishOr(stat.blocks)\n }),\n catch: handleBadArgument(\"stat\")\n});\nconst stat = /*#__PURE__*/(() => {\n const nodeStat = /*#__PURE__*/effectify(NFS.stat, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"stat\"), /*#__PURE__*/handleBadArgument(\"stat\"));\n return path => Effect.flatMap(nodeStat(path, {\n bigint: true\n }), makeFileInfo);\n})();\n// == symlink\nconst symlink = /*#__PURE__*/(() => {\n const nodeSymlink = /*#__PURE__*/effectify(NFS.symlink, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"symlink\"), /*#__PURE__*/handleBadArgument(\"symlink\"));\n return (target, path) => nodeSymlink(target, path);\n})();\n// == truncate\nconst truncate = /*#__PURE__*/(() => {\n const nodeTruncate = /*#__PURE__*/effectify(NFS.truncate, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"truncate\"), /*#__PURE__*/handleBadArgument(\"truncate\"));\n return (path, length) => nodeTruncate(path, length);\n})();\n// == utimes\nconst utimes = /*#__PURE__*/(() => {\n const nodeUtimes = /*#__PURE__*/effectify(NFS.utimes, /*#__PURE__*/handleErrnoException(\"FileSystem\", \"utime\"), /*#__PURE__*/handleBadArgument(\"utime\"));\n return (path, atime, mtime) => nodeUtimes(path, atime, mtime);\n})();\n// == watch\nconst watchNode = (path, info, options) => Stream.callback(queue => Effect.acquireRelease(Effect.sync(() => {\n const directory = info.type === \"Directory\" ? path : Path.dirname(path);\n const watcher = NFS.watch(path, {\n recursive: options?.recursive ?? false\n }, (event, path) => {\n if (!path) return;\n switch (event) {\n case \"rename\":\n {\n Effect.runFork(Effect.matchEffect(stat(Path.resolve(directory, path)), {\n onSuccess: _ => Queue.offer(queue, {\n _tag: \"Create\",\n path\n }),\n onFailure: _ => Queue.offer(queue, {\n _tag: \"Remove\",\n path\n })\n }));\n return;\n }\n case \"change\":\n {\n Queue.offerUnsafe(queue, {\n _tag: \"Update\",\n path\n });\n return;\n }\n }\n });\n watcher.on(\"error\", error => {\n Queue.failCauseUnsafe(queue, Cause.fail(Error.systemError({\n module: \"FileSystem\",\n _tag: \"Unknown\",\n method: \"watch\",\n pathOrDescriptor: path,\n cause: error\n })));\n });\n watcher.on(\"close\", () => {\n Queue.endUnsafe(queue);\n });\n return watcher;\n}), watcher => Effect.sync(() => watcher.close())).pipe(Effect.tap(() => Effect.sync(() => options?.onReady?.()))));\nconst watch = (backend, path, options) => Effect.all([stat(path), Effect.serviceOption(FileSystem.WatchBackend)]).pipe(Effect.map(([stat, callerBackend]) => Option.orElse(callerBackend, () => backend).pipe(Option.flatMap(_ => _.register(path, stat, options)), Option.getOrElse(() => watchNode(path, stat, options)))), Stream.unwrap);\n// == writeFile\nconst writeFile = (path, data, options) => Effect.callback((resume, signal) => {\n try {\n NFS.writeFile(path, data, {\n signal,\n flag: options?.flag,\n mode: options?.mode\n }, err => {\n if (err) {\n resume(Effect.fail(handleErrnoException(\"FileSystem\", \"writeFile\")(err, [path])));\n } else {\n resume(Effect.void);\n }\n });\n } catch (err) {\n resume(Effect.fail(handleBadArgument(\"writeFile\")(err)));\n }\n});\nconst makeFileSystem = /*#__PURE__*/Effect.map(/*#__PURE__*/Effect.serviceOption(FileSystem.WatchBackend), backend => FileSystem.make({\n access,\n chmod,\n chown,\n copy,\n copyFile,\n glob,\n link,\n makeDirectory,\n makeTempDirectory,\n makeTempDirectoryScoped,\n makeTempFile,\n makeTempFileScoped,\n open,\n readDirectory,\n readFile,\n readLink,\n realPath,\n remove,\n rename,\n stat,\n symlink,\n truncate,\n utimes,\n watch(path, options) {\n return watch(backend, path, options);\n },\n writeFile\n}));\n/**\n * Provides the `FileSystem` service backed by Node filesystem APIs, including\n * file operations, directory operations, links, metadata, and file watching.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.effect(FileSystem.FileSystem)(makeFileSystem);\n//# sourceMappingURL=NodeFileSystem.js.map","/**\n * Node.js `FileSystem` layer for programs that perform real filesystem I/O.\n *\n * The exported layer satisfies the platform-independent `FileSystem` service\n * with Node-backed operations for files, directories, metadata, permissions,\n * links, temporary paths, and path watching. Effects still call the service from\n * `effect/FileSystem`; this module only chooses the Node implementation.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as NodeFileSystem from \"@effect/platform-node-shared/NodeFileSystem\";\n/**\n * Provides the `FileSystem` service backed by Node filesystem APIs.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodeFileSystem.layer;\n//# sourceMappingURL=NodeFileSystem.js.map","/**\n * Node-backed provider for Effect's `Path` service.\n *\n * This module turns Node's `node:path` and `node:url` APIs into `Path` layers.\n * `layer` uses the host platform path implementation, while `layerPosix` and\n * `layerWin32` provide fixed POSIX and Windows variants. All three layers also\n * include helpers for converting between file paths and file URLs.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { make, Path } from \"effect/Path\";\nimport { BadArgument } from \"effect/PlatformError\";\nimport * as NodePath from \"node:path\";\nimport * as NodeUrl from \"node:url\";\nconst fileUrlOps = windows => ({\n fromFileUrl: url => Effect.try({\n try: () => NodeUrl.fileURLToPath(url, {\n windows\n }),\n catch: cause => new BadArgument({\n module: \"Path\",\n method: \"fromFileUrl\",\n cause\n })\n }),\n toFileUrl: path => Effect.try({\n try: () => NodeUrl.pathToFileURL(path, {\n windows\n }),\n catch: cause => new BadArgument({\n module: \"Path\",\n method: \"toFileUrl\",\n cause\n })\n })\n});\n/**\n * Provides the `Path` service using Node's POSIX path implementation plus\n * file URL conversion helpers.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerPosix = /*#__PURE__*/Layer.succeed(Path)(/*#__PURE__*/make({\n ...NodePath.posix,\n ... /*#__PURE__*/fileUrlOps(false)\n}));\n/**\n * Provides the `Path` service using Node's Windows path implementation plus\n * file URL conversion helpers.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerWin32 = /*#__PURE__*/Layer.succeed(Path)(/*#__PURE__*/make({\n ...NodePath.win32,\n ... /*#__PURE__*/fileUrlOps(true)\n}));\n/**\n * Provides the default `Path` service using the host platform's Node path\n * implementation plus file URL conversion helpers.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.succeed(Path)(/*#__PURE__*/make({\n ...NodePath,\n ... /*#__PURE__*/fileUrlOps(undefined)\n}));\n//# sourceMappingURL=NodePath.js.map","/**\n * Node.js layers for Effect's `Path` service.\n *\n * This module provides the default, POSIX, and Windows variants of the\n * platform-independent `Path` service by reusing the shared Node path\n * implementation. The provided path services include Node file URL conversion\n * behavior.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as NodePath from \"@effect/platform-node-shared/NodePath\";\n/**\n * Provides the default Node `Path` service using the platform's `node:path`\n * implementation.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodePath.layer;\n/**\n * Provides the `Path` service using Node's POSIX path implementation,\n * regardless of the host platform.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerPosix = NodePath.layerPosix;\n/**\n * Provides the `Path` service using Node's Windows path implementation,\n * regardless of the host platform.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerWin32 = NodePath.layerWin32;\n//# sourceMappingURL=NodePath.js.map","/**\n * Shared Node.js implementation of the Effect `Stdio` service.\n *\n * `NodeStdio` provides {@link Stdio.Stdio} from the current Node process. The\n * exported {@link layer} reads command-line arguments from `process.argv`,\n * consumes input from `process.stdin`, and writes normal and error output to\n * `process.stdout` and `process.stderr`. Standard input remains open, and\n * standard output and error output are not ended unless requested.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { systemError } from \"effect/PlatformError\";\nimport * as Stdio from \"effect/Stdio\";\nimport { fromWritable } from \"./NodeSink.js\";\nimport { fromReadable } from \"./NodeStream.js\";\n/**\n * Provides `Stdio` from `process.argv`, `process.stdin`, `process.stdout`,\n * and `process.stderr`; stdin remains open and stdout/stderr are not ended by\n * default.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.succeed(Stdio.Stdio, /*#__PURE__*/Stdio.make({\n args: /*#__PURE__*/Effect.sync(() => process.argv.slice(2)),\n stdinIsTerminal: /*#__PURE__*/Effect.sync(() => process.stdin.isTTY === true),\n stdoutIsTerminal: /*#__PURE__*/Effect.sync(() => process.stdout.isTTY === true),\n stderrIsTerminal: /*#__PURE__*/Effect.sync(() => process.stderr.isTTY === true),\n stdout: options => fromWritable({\n evaluate: () => process.stdout,\n onError: cause => systemError({\n module: \"Stdio\",\n method: \"stdout\",\n _tag: \"Unknown\",\n cause\n }),\n endOnDone: options?.endOnDone ?? false\n }),\n stderr: options => fromWritable({\n evaluate: () => process.stderr,\n onError: cause => systemError({\n module: \"Stdio\",\n method: \"stderr\",\n _tag: \"Unknown\",\n cause\n }),\n endOnDone: options?.endOnDone ?? false\n }),\n stdin: /*#__PURE__*/fromReadable({\n evaluate: () => process.stdin,\n onError: cause => systemError({\n module: \"Stdio\",\n method: \"stdin\",\n _tag: \"Unknown\",\n cause\n }),\n closeOnDone: false\n })\n}));\n//# sourceMappingURL=NodeStdio.js.map","/**\n * Node.js `Stdio` layer for the current process.\n *\n * The exported layer reuses the shared Node stdio implementation. It satisfies\n * the platform-independent `Stdio` service by reading command-line arguments\n * from `process.argv`, consuming input from `process.stdin`, and writing output\n * streams to `process.stdout` and `process.stderr`.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as NodeStdio from \"@effect/platform-node-shared/NodeStdio\";\n/**\n * Provides the `Stdio` service backed by the current process arguments,\n * stdin, stdout, and stderr streams.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodeStdio.layer;\n//# sourceMappingURL=NodeStdio.js.map","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport { badArgument } from \"effect/PlatformError\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Queue from \"effect/Queue\";\nimport * as RcRef from \"effect/RcRef\";\nimport * as Terminal from \"effect/Terminal\";\nimport * as readline from \"node:readline\";\n/**\n * Creates a scoped process-backed `Terminal` using Node `readline` and TTY raw mode.\n * By default, Esc, Ctrl+C, and Ctrl+D end key input. Supply `shouldQuit` to\n * override these quit keys.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (shouldQuit = defaultShouldQuit) {\n const stdin = process.stdin;\n const stdout = process.stdout;\n const lines = yield* Queue.make();\n // stdin \"end\" fires once per process, so remember end-of-input for readers\n // created after the event (Bun never sets `readableEnded`).\n let inputEnded = stdin.readableEnded;\n let readlineActive = false;\n const onStdinEnd = () => {\n inputEnded = true;\n if (!readlineActive) {\n Queue.endUnsafe(lines);\n }\n };\n stdin.once(\"end\", onStdinEnd);\n yield* Effect.addFinalizer(() => Effect.sync(() => stdin.off(\"end\", onStdinEnd)));\n const rlRef = yield* RcRef.make({\n acquire: Effect.acquireRelease(Effect.sync(() => {\n const rl = readline.createInterface({\n input: stdin,\n escapeCodeTimeout: 50\n });\n const onLine = line => Queue.offerUnsafe(lines, line);\n const onClose = () => {\n readlineActive = false;\n Queue.endUnsafe(lines);\n };\n readlineActive = true;\n readline.emitKeypressEvents(stdin, rl);\n rl.on(\"line\", onLine);\n rl.once(\"close\", onClose);\n if (stdin.isTTY) {\n stdin.setRawMode(true);\n }\n return {\n rl,\n onClose,\n onLine\n };\n }), ({\n rl,\n onClose,\n onLine\n }) => Effect.sync(() => {\n readlineActive = false;\n rl.off(\"line\", onLine);\n rl.off(\"close\", onClose);\n if (stdin.isTTY) {\n stdin.setRawMode(false);\n }\n rl.close();\n if (inputEnded) {\n Queue.endUnsafe(lines);\n }\n })),\n idleTimeToLive: \"10 millis\"\n });\n const columns = Effect.sync(() => stdout.columns ?? 0);\n const rows = Effect.sync(() => stdout.rows ?? 0);\n const readInput = Effect.gen(function* () {\n const queue = yield* Queue.make();\n const handleKeypress = (s, k) => {\n const userInput = {\n input: Option.fromUndefinedOr(s),\n key: {\n name: k.name ?? \"\",\n ctrl: !!k.ctrl,\n meta: !!k.meta,\n shift: !!k.shift\n }\n };\n Queue.offerUnsafe(queue, userInput);\n if (shouldQuit(userInput)) {\n Queue.endUnsafe(queue);\n }\n };\n // Deno's `process.stdin` shim does not keep the event loop alive, so a\n // program blocked on input can exit before `end` is ever delivered. A\n // timer holds the loop open for as long as this reader is active.\n const keepAlive = setInterval(() => {}, 2147483647);\n // Without this, consumers (e.g. `Prompt.run`) hang forever on closed stdin.\n const handleEnd = () => {\n clearInterval(keepAlive);\n Queue.endUnsafe(queue);\n };\n yield* Effect.addFinalizer(() => Effect.sync(() => {\n clearInterval(keepAlive);\n stdin.off(\"keypress\", handleKeypress);\n stdin.off(\"end\", handleEnd);\n }));\n stdin.on(\"keypress\", handleKeypress);\n if (inputEnded) {\n handleEnd();\n } else {\n yield* RcRef.get(rlRef);\n stdin.once(\"end\", handleEnd);\n }\n return queue;\n });\n const readLine = Effect.suspend(() => Queue.poll(lines).pipe(Effect.flatMap(Option.match({\n onNone: () => Effect.scoped(Effect.andThen(RcRef.get(rlRef), Queue.take(lines))),\n onSome: Effect.succeed\n })), Effect.mapError(() => new Terminal.QuitError({}))));\n const display = prompt => Effect.uninterruptible(Effect.callback(resume => {\n stdout.write(prompt, err => Predicate.isNullish(err) ? resume(Effect.void) : resume(Effect.fail(badArgument({\n module: \"Terminal\",\n method: \"display\",\n description: \"Failed to write prompt to stdout\",\n cause: err\n }))));\n }));\n return Terminal.make({\n columns,\n rows,\n readInput,\n readLine,\n display\n });\n});\n/**\n * Provides the default process-backed `Terminal` service, ending key input on\n * bare Esc, Ctrl+C, or Ctrl+D.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.effect(Terminal.Terminal, /*#__PURE__*/make(defaultShouldQuit));\nfunction defaultShouldQuit(input) {\n const key = input.key;\n return key.name === \"escape\" || key.ctrl && (key.name === \"c\" || key.name === \"d\");\n}\n//# sourceMappingURL=NodeTerminal.js.map","/**\n * Node.js implementation of the Effect `Terminal` service.\n *\n * This module reuses the shared Node terminal implementation. `make` creates a\n * scoped process-backed `Terminal` service, and `layer` provides the default\n * service with the standard quit behavior for key input.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as NodeTerminal from \"@effect/platform-node-shared/NodeTerminal\";\n/**\n * Creates a scoped `Terminal` service backed by process stdin/stdout.\n * By default, Esc, Ctrl+C, and Ctrl+D end key input. Supply `shouldQuit` to\n * override these quit keys.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = NodeTerminal.make;\n/**\n * Provides the default process-backed `Terminal` service, ending key input on\n * bare Esc, Ctrl+C, or Ctrl+D.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = NodeTerminal.layer;\n//# sourceMappingURL=NodeTerminal.js.map","import * as Layer from \"effect/Layer\";\nimport * as NodeChildProcessSpawner from \"./NodeChildProcessSpawner.js\";\nimport * as NodeCrypto from \"./NodeCrypto.js\";\nimport * as NodeFileSystem from \"./NodeFileSystem.js\";\nimport * as NodePath from \"./NodePath.js\";\nimport * as NodeStdio from \"./NodeStdio.js\";\nimport * as NodeTerminal from \"./NodeTerminal.js\";\n/**\n * Provides the default Node implementations for child process spawning,\n * filesystem, path, stdio, and terminal services.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.provideMerge(NodeChildProcessSpawner.layer, /*#__PURE__*/Layer.mergeAll(NodeFileSystem.layer, NodeCrypto.layer, NodePath.layer, NodeStdio.layer, NodeTerminal.layer));\n//# sourceMappingURL=NodeServices.js.map","import * as Runtime from \"effect/Runtime\";\n/**\n * Runs an Effect as the Node process main program, interrupting the fiber on\n * `SIGINT` or `SIGTERM` and invoking the configured teardown to determine the\n * process exit code.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const runMain = /*#__PURE__*/Runtime.makeRunMain(({\n fiber,\n teardown\n}) => {\n let receivedSignal = false;\n fiber.addObserver(exit => {\n process.removeListener(\"SIGINT\", onSigint);\n process.removeListener(\"SIGTERM\", onSigint);\n teardown(exit, code => {\n if (receivedSignal || code !== 0) {\n process.exit(code);\n }\n });\n });\n function onSigint() {\n receivedSignal = true;\n fiber.interruptUnsafe(fiber.id);\n }\n process.on(\"SIGINT\", onSigint);\n process.on(\"SIGTERM\", onSigint);\n});\n//# sourceMappingURL=NodeRuntime.js.map","/**\n * Node.js process runner for Effect programs.\n *\n * This module exports `runMain`, which runs one Effect as the main process\n * fiber in Node.js. It reuses the shared Node runtime runner, including its\n * error reporting, `SIGINT` / `SIGTERM` interruption, and optional teardown\n * behavior.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as NodeRuntime from \"@effect/platform-node-shared/NodeRuntime\";\n/**\n * Helps you run a main effect with built-in error handling, logging, and signal management.\n *\n * **When to use**\n *\n * Use to run a Node.js application's main Effect with structured error\n * handling, log management, interrupt support, or advanced teardown\n * capabilities.\n *\n * **Details**\n *\n * This function launches an Effect as the main entry point, setting exit codes\n * based on success or failure, handling interrupts (e.g., Ctrl+C), and optionally\n * logging errors. By default, it logs errors and uses a \"pretty\" format, but both\n * behaviors can be turned off. You can also provide custom teardown logic to\n * finalize resources or produce different exit codes.\n *\n * The optional configuration object can include:\n * - `disableErrorReporting`: Turn off automatic error logging.\n * - `teardown`: Provide custom finalization logic.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const runMain = NodeRuntime.runMain;\n//# sourceMappingURL=NodeRuntime.js.map","import { Array, Order, Schema, pipe } from 'effect'\n\nexport const LoomLockSchema = Schema.Struct({\n version: Schema.Literal(1),\n tangled: Schema.Array(Schema.String),\n})\n\nexport type LoomLock = typeof LoomLockSchema.Type\n\nexport const emptyLock: LoomLock = { version: 1, tangled: [] }\n\nexport const orphansOf = (lock: LoomLock, produced: ReadonlySet<string>): ReadonlyArray<string> =>\n Array.filter(lock.tangled, (path) => !produced.has(path))\n\nconst sortedUnique = (paths: ReadonlyArray<string>): ReadonlyArray<string> =>\n pipe(paths, Array.dedupe, Array.sort(Order.String))\n\nexport const recorded = (lock: LoomLock, produced: ReadonlyArray<string>): LoomLock => ({\n version: 1,\n tangled: sortedUnique([...lock.tangled, ...produced]),\n})\n\nexport const pruned = (produced: ReadonlyArray<string>): LoomLock => ({\n version: 1,\n tangled: sortedUnique(produced),\n})\n","import { Array, Context, Effect, FileSystem, Layer, Option, Result, Schema, Stream } from 'effect'\nimport { dirname, relative, resolve as resolvePath } from 'node:path'\nimport { type Path } from '@athrio/loom-ast/LoomCorpusAst'\nimport { workspaceRoot } from '@athrio/loom-lang-services/LoomStore'\nimport { LoomCompiler, type TangledFile, type TangleError } from './LoomCompiler'\nimport { PackageConfig } from './PackageConfig'\nimport { holds, loomsIn, projectIn, storeDirs, type LoomProject } from './LoomProject'\nimport { emptyLock, orphansOf, pruned, recorded, LoomLockSchema, type LoomLock } from './LoomLock'\n\nconst isStorePath = (name: string): boolean =>\n name.split('/').some((segment) => storeDirs.has(segment))\n\nexport class LoomTangler extends Context.Service<LoomTangler>()('LoomTangler', {\n make: Effect.gen(function* () {\n const compiler = yield* LoomCompiler\n const fs = yield* FileSystem.FileSystem\n const config = yield* PackageConfig\n\n const matchesDisk = (file: TangledFile): Effect.Effect<boolean> =>\n fs.readFileString(file.path).pipe(Effect.option, Effect.map(Option.contains(file.content)))\n\n const writeFile = (file: TangledFile): Effect.Effect<TangledFile> =>\n matchesDisk(file).pipe(\n Effect.flatMap((same) =>\n same\n ? Effect.void\n : fs\n .makeDirectory(dirname(file.path), { recursive: true })\n .pipe(Effect.andThen(fs.writeFileString(file.path, file.content))),\n ),\n Effect.orDie,\n Effect.as(file),\n )\n\n const tangleFile = (entry: Path): Effect.Effect<ReadonlyArray<TangledFile>, TangleError> =>\n compiler.tangle(entry).pipe(Effect.flatMap((files) => Effect.forEach(files, writeFile)))\n\n const projectOf = (path: Path): Effect.Effect<Option.Option<LoomProject>> =>\n config.resolve(path).pipe(Effect.map(projectIn))\n\n const loomsOf = (path: Path): Effect.Effect<ReadonlyArray<Path>> =>\n fs.stat(path).pipe(\n Effect.orDie,\n Effect.flatMap((info) =>\n info.type === 'Directory'\n ? projectOf(path).pipe(Effect.map((project) => loomsIn(path, project)))\n : Effect.succeed<ReadonlyArray<Path>>([path]),\n ),\n )\n\n const recordsFor = (path: Path): Effect.Effect<boolean> =>\n fs.stat(path).pipe(\n Effect.orDie,\n Effect.flatMap((info) =>\n info.type === 'Directory'\n ? Effect.succeed(true)\n : projectOf(path).pipe(\n Effect.map(\n Option.match({\n onNone: () => true,\n onSome: (project) => holds(project, path),\n }),\n ),\n ),\n ),\n )\n\n const workspaceOf = (path: Path): Effect.Effect<Path> =>\n fs.stat(path).pipe(\n Effect.orDie,\n Effect.map((info) => workspaceRoot(info.type === 'Directory' ? path : dirname(path))),\n )\n\n const lockFile = (root: Path): Path => resolvePath(root, '.loom', 'loom.lock')\n\n const readLock = (root: Path): Effect.Effect<LoomLock> =>\n fs.readFileString(lockFile(root)).pipe(\n Effect.flatMap((text) => Effect.try(() => JSON.parse(text) as unknown)),\n Effect.flatMap(Schema.decodeUnknownEffect(LoomLockSchema)),\n Effect.orElseSucceed(() => emptyLock),\n )\n\n const writeLock = (root: Path, lock: LoomLock): Effect.Effect<void> =>\n fs\n .makeDirectory(dirname(lockFile(root)), { recursive: true })\n .pipe(\n Effect.andThen(fs.writeFileString(lockFile(root), JSON.stringify(lock, null, 2) + '\\n')),\n Effect.orDie,\n )\n\n const tangle = (path: Path): Effect.Effect<ReadonlyArray<TangledFile>, TangleError> =>\n Effect.gen(function* () {\n const looms = yield* loomsOf(path)\n const written = (yield* Effect.forEach(looms, tangleFile)).flat()\n if (yield* recordsFor(path)) {\n const root = yield* workspaceOf(path)\n const lock = yield* readLock(root)\n yield* writeLock(\n root,\n recorded(\n lock,\n Array.map(written, (file) => relative(root, file.path)),\n ),\n )\n }\n return written\n })\n\n const orphanState = (\n from: Path,\n ): Effect.Effect<\n {\n readonly root: Path\n readonly produced: ReadonlyArray<string>\n readonly orphans: ReadonlyArray<string>\n },\n TangleError\n > =>\n Effect.gen(function* () {\n const root = workspaceRoot(from)\n const looms = loomsIn(root, yield* projectOf(root))\n const files = (yield* Effect.forEach(looms, (loom) => compiler.tangle(loom))).flat()\n const produced = Array.map(files, (file) => relative(root, file.path))\n const lock = yield* readLock(root)\n return { root, produced, orphans: orphansOf(lock, new Set(produced)) }\n })\n\n const orphans = (from: Path): Effect.Effect<ReadonlyArray<Path>, TangleError> =>\n orphanState(from).pipe(\n Effect.map(({ root, orphans }) => Array.map(orphans, (rel) => resolvePath(root, rel))),\n )\n\n const prune = (from: Path): Effect.Effect<ReadonlyArray<Path>, TangleError> =>\n Effect.gen(function* () {\n const { root, produced, orphans } = yield* orphanState(from)\n yield* Effect.forEach(orphans, (rel) =>\n fs.remove(resolvePath(root, rel), { force: true }).pipe(Effect.orDie),\n )\n yield* writeLock(root, pruned(produced))\n return Array.map(orphans, (rel) => resolvePath(root, rel))\n })\n\n const batchWindow = '50 millis'\n const batchLimit = 1000\n\n const isLoomEvent = (event: FileSystem.WatchEvent): boolean =>\n event.path.endsWith('.loom') && !isStorePath(event.path)\n\n const watchRoot = (path: Path): Effect.Effect<Path> =>\n fs.stat(path).pipe(\n Effect.orDie,\n Effect.flatMap((info) =>\n info.type === 'Directory'\n ? Effect.succeed(path)\n : config\n .resolve(path)\n .pipe(\n Effect.map(({ corpusDir }) =>\n Option.getOrElse(Option.fromNullishOr(corpusDir), () => dirname(path)),\n ),\n ),\n ),\n )\n\n const watch = (path: Path): Stream.Stream<Result.Result<ReadonlyArray<TangledFile>, TangleError>> =>\n Stream.unwrap(\n watchRoot(path).pipe(\n Effect.map((root) =>\n Stream.concat(\n Stream.fromEffect(Effect.result(tangle(path))),\n fs.watch(root).pipe(\n Stream.filter(isLoomEvent),\n Stream.groupedWithin(batchLimit, batchWindow),\n Stream.mapEffect((events) =>\n Effect.forEach(\n Array.dedupe(Array.map(events, (event) => resolvePath(root, event.path))),\n (changed) => compiler.invalidate(changed),\n { discard: true },\n ).pipe(Effect.andThen(Effect.result(tangle(path)))),\n ),\n Stream.orDie,\n ),\n ),\n ),\n ),\n )\n\n return { tangle, orphans, prune, watch }\n }),\n}) {\n static readonly layer = Layer.effect(this, this.make).pipe(Layer.provide(LoomCompiler.layer))\n}\n","import { Context, Effect, FileSystem, Layer } from 'effect'\nimport { dirname } from 'node:path'\nimport { type Path } from '@athrio/loom-ast/LoomCorpusAst'\nimport { LoomCompiler } from '../LoomCompiler'\n\nexport class LoomWeaver extends Context.Service<LoomWeaver>()('LoomWeaver', {\n make: Effect.gen(function* () {\n const compiler = yield* LoomCompiler\n const fs = yield* FileSystem.FileSystem\n\n const weave = (entry: Path, out: Path): Effect.Effect<Path> =>\n compiler.weave(entry).pipe(\n Effect.map((corpus) => JSON.stringify(corpus, null, 2)),\n Effect.flatMap((json) =>\n fs\n .makeDirectory(dirname(out), { recursive: true })\n .pipe(Effect.andThen(fs.writeFileString(out, json)), Effect.orDie, Effect.as(out)),\n ),\n )\n\n return { weave }\n }),\n}) {\n static readonly layer = Layer.effect(this, this.make).pipe(Layer.provide(LoomCompiler.layer))\n}\n","import { Context, Effect, FileSystem, Layer } from 'effect'\nimport { type Path } from '@athrio/loom-ast/LoomCorpusAst'\nimport { LoomCompiler } from '../LoomCompiler'\n\nexport class LoomContents extends Context.Service<LoomContents>()('LoomContents', {\n make: Effect.gen(function* () {\n const compiler = yield* LoomCompiler\n const fs = yield* FileSystem.FileSystem\n\n const write = (entry: Path): Effect.Effect<Path> =>\n compiler\n .contents(entry)\n .pipe(\n Effect.flatMap((text) =>\n fs.writeFileString(entry, text).pipe(Effect.orDie, Effect.as(entry)),\n ),\n )\n\n return { write }\n }),\n}) {\n static readonly layer = Layer.effect(this, this.make).pipe(Layer.provide(LoomCompiler.layer))\n}\n","import {\n Array,\n Cause,\n Console,\n Data,\n Effect,\n Equal,\n Match,\n Option,\n Order,\n Result,\n Schema,\n type Scope,\n Stream,\n pipe,\n} from 'effect'\nimport { Argument, Command, Flag, Prompt } from 'effect/cli'\nimport { ChildProcess } from 'effect/process'\nimport { NodeRuntime, NodeServices } from '@effect/platform-node'\nimport { createHash } from 'node:crypto'\nimport {\n cpSync,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n realpathSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { homedir, tmpdir } from 'node:os'\nimport { delimiter, dirname, resolve as resolvePath } from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { gunzipSync } from 'node:zlib'\nimport { DocumentSource, type TangledFile, type TangleError } from '@athrio/loom-lang/LoomCompiler'\nimport { LoomTangler } from '@athrio/loom-lang/LoomTangler'\nimport { LoomWeaver } from '@athrio/loom-lang/weave/LoomWeaver'\nimport { LoomContents } from '@athrio/loom-lang/weave/LoomContents'\nimport { LoomFormatter } from '@athrio/loom-lang/LoomFormatter'\nimport { PackageConfig } from '@athrio/loom-lang/PackageConfig'\nimport { defaultWidth, LoomConfig } from '@athrio/loom-config/LoomConfig'\nimport {\n installedVersion,\n installService,\n embeddedFile,\n installTypeScript,\n removeService,\n ServiceInstall,\n type StoreError,\n servicePackage,\n serviceVersion,\n standalone,\n storeDir,\n storeTypeScript,\n typeScriptRange,\n workspaceOf,\n workspaceRoot,\n} from '@athrio/loom-lang-services/LoomStore'\nimport type { LanguageService } from '@athrio/loom-lang-services/LanguageService'\n\nconst reset = '\\x1b[0m'\nconst teal = (s: string): string => `\\x1b[38;5;44m${s}${reset}`\nconst dim = (s: string): string => `\\x1b[2m${s}${reset}`\n\nconst wordmark = [\n ' ██╗ ██████╗ ██████╗ ███╗ ███╗',\n ' ██║ ██╔═══██╗██╔═══██╗████╗ ████║',\n ' ██║ ██║ ██║██║ ██║██╔████╔██║',\n ' ██║ ██║ ██║██║ ██║██║╚██╔╝██║',\n ' ███████╗╚██████╔╝╚██████╔╝██║ ╚═╝ ██║',\n ' ╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝',\n].join('\\n')\n\nconst banner = Console.log(`\\n${teal(wordmark)}\\n ${dim('a literate framework')}\\n`)\n\nconst reportWritten = (written: ReadonlyArray<TangledFile>): Effect.Effect<void> =>\n written.length === 0\n ? Console.log('loom: no {path} sinks to tangle')\n : Effect.forEach(written, (f) => Console.log(`loom: tangled ${f.section} → ${f.path}`), {\n discard: true,\n })\n\nconst tangleOnce = (file: string) =>\n Effect.gen(function* () {\n const tangler = yield* LoomTangler\n const written = yield* tangler.tangle(resolvePath(process.cwd(), file))\n yield* reportWritten(written)\n }).pipe(\n Effect.catchTag('TangleError', (e) =>\n Console.error(e.message).pipe(Effect.andThen(Effect.sync(() => void (process.exitCode = 1)))),\n ),\n )\n\nconst tangleWatch = (file: string) =>\n Effect.gen(function* () {\n const tangler = yield* LoomTangler\n yield* Console.log(`loom: watching ${file} — re-tangling on change`)\n yield* Stream.runForEach(\n tangler.watch(resolvePath(process.cwd(), file)),\n Result.match({\n onSuccess: reportWritten,\n onFailure: (error: TangleError) => Console.error(error.message),\n }),\n )\n })\n\nconst tangle = (file: string, watch: boolean) => (watch ? tangleWatch(file) : tangleOnce(file))\n\nconst orphans = (prune: boolean) =>\n Effect.gen(function* () {\n const tangler = yield* LoomTangler\n if (prune) {\n const removed = yield* tangler.prune(process.cwd())\n yield* removed.length === 0\n ? Console.log('loom: no orphans to prune')\n : Effect.forEach(removed, (path) => Console.log(`loom: pruned ${path}`))\n } else {\n const found = yield* tangler.orphans(process.cwd())\n yield* Effect.forEach(found, (path) => Console.log(path))\n }\n }).pipe(\n Effect.catchTag('TangleError', (e) =>\n Console.error(e.message).pipe(Effect.andThen(Effect.sync(() => void (process.exitCode = 1)))),\n ),\n )\n\nconst weave = (file: string, out: string) =>\n Effect.gen(function* () {\n const weaver = yield* LoomWeaver\n const written = yield* weaver.weave(\n resolvePath(process.cwd(), file),\n resolvePath(process.cwd(), out),\n )\n yield* Console.log(`loom: wove ${file} → ${written}`)\n })\n\nconst toc = (file: string) =>\n Effect.gen(function* () {\n const contents = yield* LoomContents\n const written = yield* contents.write(resolvePath(process.cwd(), file))\n yield* Console.log(`loom: wrote the table of contents into ${written}`)\n })\n\nconst format = (path: string, check: boolean) =>\n Effect.gen(function* () {\n const formatter = yield* LoomFormatter\n const target = resolvePath(process.cwd(), path)\n const languages = yield* formatLanguages(target)\n const looms = yield* formatter.looms(target)\n const changed = yield* Effect.filter(looms, (loom) =>\n Effect.gen(function* () {\n const text = yield* Effect.sync(() => readFileSync(loom, 'utf8'))\n const formatted = yield* formatter.format(loom, text, languages)\n if (formatted === text) return false\n if (!check) yield* Effect.sync(() => writeFileSync(loom, formatted))\n return true\n }),\n )\n yield* changed.length === 0\n ? Console.log('loom: every loom is formatted')\n : Effect.forEach(\n changed,\n (loom) => Console.log(`loom: ${check ? 'would format' : 'formatted'} ${loom}`),\n { discard: true },\n )\n if (check && changed.length > 0) yield* Effect.sync(() => void (process.exitCode = 1))\n })\n\nconst typeScriptFrom = (from: string): Option.Option<string> =>\n Option.liftThrowable(() => createRequire(from).resolve('typescript/lib/typescript.js'))()\n\nconst foundTypeScript = (root: string): Option.Option<string> =>\n pipe(\n typeScriptFrom(resolvePath(root, 'package.json')),\n Option.orElse(() => (standalone ? Option.none() : typeScriptFrom(import.meta.url))),\n Option.orElse(() => storeTypeScript(root)),\n )\n\nconst storedTypeScript = (root: string): Effect.Effect<string, StoreError> =>\n Console.error(`loom: installing TypeScript ${typeScriptRange} into ${storeDir(root)}`).pipe(\n Effect.andThen(installTypeScript(root)),\n Effect.tapError((error) =>\n Console.error(`loom: could not install TypeScript — ${String(error.cause)}`),\n ),\n )\n\nconst projectTypeScript = (\n root: string,\n): Effect.Effect<Option.Option<typeof import('typescript')>> =>\n Option.match(foundTypeScript(root), {\n onNone: () => storedTypeScript(root),\n onSome: Effect.succeed,\n }).pipe(\n Effect.flatMap((file) => Effect.tryPromise(() => import(pathToFileURL(file).href))),\n Effect.map((module) => Option.some(module.default ?? module)),\n Effect.orElseSucceed(() => Option.none()),\n )\n\nconst formatLanguages = (target: string) =>\n Effect.gen(function* () {\n const config = yield* LoomConfig\n const root = workspaceRoot(dirname(target))\n const manifest = yield* config.manifest(root)\n const ids = Object.keys(manifest?.languages ?? {})\n if (ids.length === 0) return [] as ReadonlyArray<LanguageService>\n const typescript = yield* projectTypeScript(root)\n return yield* Option.match(typescript, {\n onNone: () =>\n Console.error(\n 'loom: found no TypeScript to load the language services with, so code sections stay as written',\n ).pipe(Effect.as([] as ReadonlyArray<LanguageService>)),\n onSome: (ts) =>\n Effect.gen(function* () {\n yield* Effect.sync(() => {\n ;(globalThis as { require?: unknown }).require ??= createRequire(import.meta.url)\n })\n const { installHostRuntime } = yield* Effect.promise(\n () => import('@athrio/loom-lang-services/Runtime'),\n )\n const { loadActive } = yield* Effect.promise(\n () => import('@athrio/loom-lang-services/LanguageLoader'),\n )\n yield* Effect.sync(() => installHostRuntime(ts))\n return yield* loadActive(ids, root)\n }),\n })\n })\n\nconst mergeMcpConfig = (root: string): void => {\n const path = resolvePath(root, '.mcp.json')\n const existing = existsSync(path)\n ? (JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>)\n : {}\n const servers = (existing.mcpServers as Record<string, unknown> | undefined) ?? {}\n const merged = {\n ...existing,\n mcpServers: {\n ...servers,\n loom: { type: 'http', url: 'http://localhost:5710/mcp' },\n },\n }\n writeFileSync(path, JSON.stringify(merged, null, 2) + '\\n')\n}\n\ninterface ManagedBlock {\n readonly begin: string\n readonly end: string\n readonly lines: ReadonlyArray<string>\n readonly owned: RegExp\n}\n\nconst withManagedBlock = (text: string, managed: ManagedBlock): Option.Option<string> => {\n const block = [managed.begin, ...managed.lines, managed.end].join('\\n')\n const start = text.indexOf(managed.begin)\n const end = text.indexOf(managed.end, start)\n if (start >= 0 && end > start)\n return Option.some(text.slice(0, start) + block + text.slice(end + managed.end.length))\n if (managed.owned.test(text)) return Option.none()\n const kept = text.replace(/\\s*$/, '')\n return Option.some(kept === '' ? `${block}\\n` : `${kept}\\n\\n${block}\\n`)\n}\n\nconst editorconfigBlock = (width: number): ManagedBlock => ({\n begin: '# Loom: written by `loom init`, which replaces this block on every run',\n end: '# Loom: end',\n lines: ['[*.loom]', `max_line_length = ${width}`],\n owned: /^\\s*\\[\\*\\.loom\\]\\s*$/m,\n})\n\nconst init = (dir: Option.Option<string>) =>\n Effect.gen(function* () {\n const root = resolvePath(\n process.cwd(),\n Option.getOrElse(dir, () => '.'),\n )\n const config = yield* LoomConfig\n yield* banner\n\n const configFile = resolvePath(root, '.loom', 'config.yaml')\n const configured = yield* Effect.sync(() => existsSync(configFile))\n\n if (configured) {\n yield* Console.log(`\\n ${dim(`✓ using the configuration at ${configFile}`)}\\n`)\n } else {\n const language = yield* Prompt.run(\n Prompt.String({\n message: 'Primary language for specifier-less sections',\n default: 'typescript',\n }),\n )\n const activation = yield* Prompt.run(\n Prompt.String({\n message: 'Activate editor services for (space-separated language ids)',\n default: language,\n }),\n )\n const ids = activation.split(/\\s+/).filter((id) => id.length > 0)\n yield* config.materialize(root, {\n corpus: 'corpus',\n languages: Object.fromEntries(ids.map((id) => [id, {}])),\n primary: language,\n ignore: [],\n })\n yield* Effect.sync(() =>\n writeFileSync(resolvePath(root, '.loom', '.gitignore'), 'services/\\n'),\n )\n yield* Console.log(\n `\\n ${teal('✓')} wrote ${configFile}\\n` +\n ` ${dim(`primary language: ${language}`)}\\n` +\n ` ${dim(`activated: ${ids.join(', ') || 'none'}`)}\\n`,\n )\n }\n\n const manifest = yield* config.manifest(root)\n const corpusDir = resolvePath(root, manifest?.corpus ?? 'corpus')\n yield* Effect.sync(() => mkdirSync(corpusDir, { recursive: true }))\n yield* Console.log(` ${teal('✓')} corpus at ${corpusDir}\\n`)\n\n yield* Effect.sync(() => mergeMcpConfig(root))\n yield* Console.log(` ${teal('✓')} wrote ${resolvePath(root, '.mcp.json')}\\n`)\n\n const editorconfig = resolvePath(root, '.editorconfig')\n const current = yield* Effect.sync(() =>\n existsSync(editorconfig) ? readFileSync(editorconfig, 'utf8') : '',\n )\n const block = editorconfigBlock(manifest?.width ?? defaultWidth)\n yield* Option.match(withManagedBlock(current, block), {\n onNone: () => Console.log(` ${dim(`✓ kept the [*.loom] section in ${editorconfig}`)}\\n`),\n onSome: (text) =>\n Effect.sync(() => writeFileSync(editorconfig, text)).pipe(\n Effect.andThen(Console.log(` ${teal('✓')} wrote ${editorconfig}\\n`)),\n ),\n })\n }).pipe(Effect.catchTag('QuitError', () => Console.log(dim('\\n Cancelled.\\n'))))\n\nconst updateLanguages = (\n config: LoomConfig['Service'],\n dir: string,\n change: (ids: ReadonlyArray<string>) => ReadonlyArray<string>,\n): Effect.Effect<void> =>\n Effect.gen(function* () {\n const workspace = workspaceRoot(dir)\n const current = yield* config.manifest(workspace)\n const ids = change(Object.keys(current?.languages ?? {}))\n const languages = Object.fromEntries(ids.map((id) => [id, current?.languages?.[id] ?? {}]))\n yield* config.edit(workspace, ['languages'], languages)\n })\n\nconst activatedLanguages = (\n config: LoomConfig['Service'],\n dir: string,\n): Effect.Effect<ReadonlyArray<string>> =>\n config\n .manifest(workspaceRoot(dir))\n .pipe(Effect.map((manifest) => Object.keys(manifest?.languages ?? {})))\n\nconst installNote = (language: string, change: ServiceInstall): string =>\n ServiceInstall.$match(change, {\n Current: () => `${servicePackage(language)} ${serviceVersion} is already in the store`,\n Installed: () => `installed ${servicePackage(language)} ${serviceVersion}`,\n Updated: ({ from }) => `updated ${servicePackage(language)} from ${from} to ${serviceVersion}`,\n })\n\nconst failedInstall = (error: StoreError) =>\n refuse(`loom: could not install ${error.packageName} — ${String(error.cause)}`)\n\nconst alreadyActive = (language: string, dir: string) =>\n Console.log(\n `\\n ${teal('✓')} ${language} is already activated\\n` +\n Option.match(installedVersion(language, dir), {\n onNone: () =>\n ` ${dim(`its service is not in the store; \\`loom update ${language}\\` installs it`)}\\n`,\n onSome: (version) =>\n version === serviceVersion\n ? ''\n : ` ${dim(`the store holds its service at ${version}; \\`loom update ${language}\\` brings it to ${serviceVersion}`)}\\n`,\n }),\n )\n\nconst add = (language: string) =>\n Effect.gen(function* () {\n const config = yield* LoomConfig\n const dir = process.cwd()\n const activated = yield* activatedLanguages(config, dir)\n if (activated.includes(language)) return yield* alreadyActive(language, dir)\n const change = yield* installService(language, dir)\n yield* updateLanguages(config, dir, (ids) => [...ids, language])\n yield* Console.log(\n `\\n ${teal('✓')} activated ${language}\\n` +\n ` ${dim(installNote(language, change))}\\n` +\n ` ${dim(`store: ${storeDir(dir)}`)}\\n`,\n )\n }).pipe(Effect.catchTag('StoreError', failedInstall))\n\nconst remove = (language: string) =>\n Effect.gen(function* () {\n const config = yield* LoomConfig\n const dir = process.cwd()\n yield* removeService(language, dir)\n yield* updateLanguages(config, dir, (ids) => ids.filter((id) => id !== language))\n yield* Console.log(`\\n ${teal('✓')} removed ${language}\\n`)\n })\n\nconst updateUsage = 'usage: loom update <language>… | loom update --all'\n\nconst update = (languages: ReadonlyArray<string>, all: boolean) =>\n Effect.gen(function* () {\n if (languages.length === 0 && !all)\n return yield* refuse(\n `loom: name the languages to update, or use --all — ${updateUsage}\\n` +\n ' To upgrade Loom itself, run `loom upgrade`.',\n )\n if (languages.length > 0 && all)\n return yield* refuse(`loom: name languages or use --all, not both — ${updateUsage}`)\n const config = yield* LoomConfig\n const dir = process.cwd()\n const activated = yield* activatedLanguages(config, dir)\n const inactive = languages.filter((id) => !activated.includes(id))\n if (inactive.length > 0)\n return yield* Effect.forEach(\n inactive,\n (id) => refuse(`loom: ${id} is not activated; \\`loom add ${id}\\` turns it on`),\n { discard: true },\n )\n const ids = all ? activated : languages\n if (ids.length === 0) return yield* Console.log(`\\n ${dim('no languages are activated')}\\n`)\n yield* Console.log('')\n yield* Effect.forEach(ids, (id) =>\n installService(id, dir).pipe(\n Effect.flatMap((change) => Console.log(` ${teal('✓')} ${dim(installNote(id, change))}`)),\n ),\n )\n yield* Console.log(` ${dim(`store: ${storeDir(dir)}`)}\\n`)\n }).pipe(Effect.catchTag('StoreError', failedInstall))\n\ntype ProjectManager = 'npm' | 'bun' | 'pnpm' | 'yarn'\n\ntype Installation = Data.TaggedEnum<{\n Executable: {}\n Unowned: {}\n Homebrew: {}\n Npm: {}\n Bun: {}\n Pnpm: {}\n Project: { readonly root: string; readonly manager: ProjectManager }\n}>\nconst Installation = Data.taggedEnum<Installation>()\n\nconst lockfiles: ReadonlyArray<readonly [string, ProjectManager]> = [\n ['bun.lock', 'bun'],\n ['bun.lockb', 'bun'],\n ['pnpm-lock.yaml', 'pnpm'],\n ['yarn.lock', 'yarn'],\n]\n\nconst projectManager = (root: string): ProjectManager =>\n pipe(\n Array.findFirst(lockfiles, ([lockfile]) => existsSync(resolvePath(root, lockfile))),\n Option.match({ onNone: (): ProjectManager => 'npm', onSome: ([, manager]) => manager }),\n )\n\nconst projectAt = (path: string): Option.Option<string> =>\n pipe(\n Option.fromNullishOr(/^(.*?)[\\\\/]node_modules[\\\\/]/.exec(path)),\n Option.flatMap((found) => Option.fromNullishOr(found[1])),\n Option.filter((root) => existsSync(resolvePath(root, 'package.json'))),\n )\n\nconst marked = (mark: RegExp) => (path: string) => mark.test(path)\n\nconst installationAt = (path: string, otherwise: Installation): Installation =>\n Match.value(path).pipe(\n Match.when(marked(/[\\\\/]Cellar[\\\\/]/), () => Installation.Homebrew()),\n Match.when(marked(/[\\\\/]\\.bun[\\\\/]/), () => Installation.Bun()),\n Match.when(marked(/[\\\\/]pnpm[\\\\/]/), () => Installation.Pnpm()),\n Match.when(marked(/[\\\\/]node_modules[\\\\/]/), (p) =>\n Option.match(projectAt(p), {\n onNone: () => Installation.Npm(),\n onSome: (root) => Installation.Project({ root, manager: projectManager(root) }),\n }),\n ),\n Match.when(marked(/[\\\\/]npm[\\\\/][^\\\\/]+$/), () => Installation.Npm()),\n Match.orElse(() => otherwise),\n )\n\nconst realOf = (path: string): string =>\n Option.getOrElse(Option.liftThrowable(() => realpathSync(path))(), () => path)\n\nconst thisFile = standalone ? process.execPath : fileURLToPath(import.meta.url)\n\nconst thisInstallation: Installation = installationAt(\n realOf(thisFile),\n standalone ? Installation.Executable() : Installation.Npm(),\n)\n\nconst describedInstallation = Installation.$match({\n Executable: () => 'a standalone executable',\n Unowned: () => 'a file no installer owns',\n Homebrew: () => 'installed by Homebrew',\n Npm: () => 'installed by npm',\n Bun: () => 'installed by Bun',\n Pnpm: () => 'installed by pnpm',\n Project: ({ root, manager }) => `installed by ${manager} in the project at ${root}`,\n})\n\nconst quoted = (path: string): string => `\"${path}\"`\n\nconst projectCommands: Record<ProjectManager, { readonly add: string; readonly remove: string }> = {\n npm: { add: 'npm install', remove: 'npm uninstall' },\n bun: { add: 'bun add', remove: 'bun remove' },\n pnpm: { add: 'pnpm add', remove: 'pnpm remove' },\n yarn: { add: 'yarn add', remove: 'yarn remove' },\n}\n\nconst installerUpgrade = Installation.$match({\n Executable: () => Option.none<string>(),\n Unowned: () => Option.none<string>(),\n Homebrew: () => Option.some('brew upgrade loom'),\n Npm: () => Option.some('npm install -g @athrio/loom@latest'),\n Bun: () => Option.some('bun add -g @athrio/loom@latest'),\n Pnpm: () => Option.some('pnpm add -g @athrio/loom@latest'),\n Project: ({ root, manager }) =>\n Option.some(`cd ${quoted(root)} && ${projectCommands[manager].add} @athrio/loom@latest`),\n})\n\nconst loomVersion = '0.0.14'\n\nconst releases = process.env.LOOM_RELEASES ?? 'https://api.github.com/repos/athrio-com/loom/releases'\n\nconst ReleaseSchema = Schema.Struct({\n tag_name: Schema.String,\n assets: Schema.Array(Schema.Struct({ name: Schema.String, browser_download_url: Schema.String })),\n})\n\ntype Release = typeof ReleaseSchema.Type\n\nconst versionOrder: Order.Order<string> = Order.mapInput(\n Order.Array(Order.Number),\n (version: string) => version.split('.').map(Number),\n)\n\nclass ReleaseUnreachable extends Data.TaggedError('ReleaseUnreachable')<{\n readonly url: string\n readonly cause: unknown\n}> {}\n\nconst fetched = (url: string): Effect.Effect<Response, ReleaseUnreachable> =>\n Effect.tryPromise({\n try: () => fetch(url, { headers: { 'user-agent': 'loom' } }),\n catch: (cause) => new ReleaseUnreachable({ url, cause }),\n }).pipe(\n Effect.filterOrFail(\n (response) => response.ok,\n (response) =>\n new ReleaseUnreachable({ url, cause: `${response.status} ${response.statusText}` }),\n ),\n )\n\nconst latestRelease: Effect.Effect<Release, ReleaseUnreachable> = Effect.gen(function* () {\n const url = `${releases}/latest`\n const response = yield* fetched(url)\n const body = yield* Effect.tryPromise({\n try: () => response.json(),\n catch: (cause) => new ReleaseUnreachable({ url, cause }),\n })\n return yield* Schema.decodeUnknownEffect(ReleaseSchema)(body).pipe(\n Effect.mapError((cause) => new ReleaseUnreachable({ url, cause })),\n )\n})\n\nconst bytesAt = (url: string): Effect.Effect<Uint8Array, ReleaseUnreachable> =>\n fetched(url).pipe(\n Effect.flatMap((response) =>\n Effect.tryPromise({\n try: async () => new Uint8Array(await response.arrayBuffer()),\n catch: (cause) => new ReleaseUnreachable({ url, cause }),\n }),\n ),\n )\n\nconst executableName =\n process.platform === 'win32'\n ? `loom-windows-${process.arch}.exe`\n : `loom-${process.platform}-${process.arch}`\n\nconst assetName = `${executableName}.gz`\n\nclass ReleaseLacksAsset extends Data.TaggedError('ReleaseLacksAsset')<{\n readonly version: string\n readonly asset: string\n}> {}\n\nclass ChecksumMismatch extends Data.TaggedError('ChecksumMismatch')<{\n readonly asset: string\n}> {}\n\nconst assetUrl = (release: Release, asset: string): Effect.Effect<string, ReleaseLacksAsset> =>\n Option.match(\n Array.findFirst(release.assets, (candidate) => candidate.name === asset),\n {\n onNone: () => Effect.fail(new ReleaseLacksAsset({ version: release.tag_name, asset })),\n onSome: (found) => Effect.succeed(found.browser_download_url),\n },\n )\n\nconst listedChecksum = (sums: string, asset: string): Option.Option<string> =>\n pipe(\n sums.split('\\n'),\n Array.map((line) => line.trim().split(/\\s+/)),\n Array.findFirst((fields) => fields[1] === asset || fields[1] === `*${asset}`),\n Option.flatMap((fields) => Option.fromNullishOr(fields[0])),\n )\n\nconst verified = (\n bytes: Uint8Array,\n sums: string,\n asset: string,\n): Effect.Effect<Uint8Array, ChecksumMismatch> =>\n Option.contains(listedChecksum(sums, asset), createHash('sha256').update(bytes).digest('hex'))\n ? Effect.succeed(bytes)\n : Effect.fail(new ChecksumMismatch({ asset }))\n\nclass UnpackFailed extends Data.TaggedError('UnpackFailed')<{\n readonly asset: string\n readonly cause: unknown\n}> {}\n\nconst unpacked = (archive: Uint8Array): Effect.Effect<Uint8Array, UnpackFailed> =>\n Effect.try({\n try: () => new Uint8Array(gunzipSync(archive)),\n catch: (cause) => new UnpackFailed({ asset: assetName, cause }),\n })\n\nclass ReplaceFailed extends Data.TaggedError('ReplaceFailed')<{\n readonly path: string\n readonly cause: unknown\n}> {}\n\nconst moveAside = (target: string): void => {\n if (process.platform !== 'win32') return\n rmSync(`${target}.old`, { force: true })\n renameSync(target, `${target}.old`)\n}\n\nconst replaceExecutable = (bytes: Uint8Array): Effect.Effect<void, ReplaceFailed> => {\n const target = process.execPath\n const partial = `${target}.${process.pid}`\n return Effect.try({\n try: () => {\n writeFileSync(partial, bytes, { mode: 0o755 })\n moveAside(target)\n renameSync(partial, target)\n },\n catch: (cause) => new ReplaceFailed({ path: target, cause }),\n }).pipe(Effect.tapError(() => Effect.sync(() => rmSync(partial, { force: true }))))\n}\n\nconst upgradeStandalone = Effect.gen(function* () {\n const release = yield* latestRelease\n const latest = release.tag_name.replace(/^v/, '')\n if (!Order.isGreaterThan(versionOrder)(latest, loomVersion))\n return yield* Console.log(\n `\\n ${teal('✓')} Loom ${loomVersion} is up to date; the latest release is ${latest}\\n`,\n )\n const archive = yield* assetUrl(release, assetName).pipe(Effect.flatMap(bytesAt))\n const sums = yield* assetUrl(release, 'SHA256SUMS').pipe(\n Effect.flatMap(bytesAt),\n Effect.map((bytes) => new TextDecoder().decode(bytes)),\n )\n yield* verified(archive, sums, assetName).pipe(\n Effect.flatMap(unpacked),\n Effect.flatMap(replaceExecutable),\n )\n yield* Console.log(\n `\\n ${teal('✓')} upgraded Loom from ${loomVersion} to ${latest}\\n` +\n ` ${dim('run `loom update --all` in each workspace to bring its services along')}\\n`,\n )\n})\n\nconst upgrade = Effect.gen(function* () {\n const command = installerUpgrade(thisInstallation)\n if (Option.isNone(command)) return yield* upgradeStandalone\n yield* Console.log(\n `\\n Loom was ${describedInstallation(thisInstallation)}. Upgrade it with:\\n\\n` +\n ` ${command.value}\\n\\n` +\n ` ${dim('then run `loom update --all` in each workspace to bring its services along')}\\n`,\n )\n}).pipe(\n Effect.catchTags({\n ReleaseUnreachable: (error) =>\n refuse(`loom: could not reach the latest release at ${error.url} — ${String(error.cause)}`),\n ReleaseLacksAsset: (error) =>\n refuse(`loom: release ${error.version} carries no ${error.asset}`),\n ChecksumMismatch: (error) =>\n refuse(\n `loom: the checksum of the downloaded ${error.asset} does not match the release's list, so Loom was left as it was`,\n ),\n UnpackFailed: (error) =>\n refuse(`loom: could not unpack ${error.asset} — ${String(error.cause)}`),\n ReplaceFailed: (error) =>\n refuse(\n `loom: could not replace ${error.path} — ${String(error.cause)}\\n` +\n ' Run the install script again, or move Loom somewhere you can write to.',\n ),\n }),\n)\n\nconst status = Effect.gen(function* () {\n const config = yield* LoomConfig\n const dir = process.cwd()\n const manifest = yield* config.manifest(workspaceRoot(dir))\n const primary = manifest?.primary\n const languages = Object.keys(manifest?.languages ?? {})\n const mark = (id: string): string =>\n Option.match(installedVersion(id, dir), {\n onNone: () => ` ${dim('○')} ${id}${dim(` — run \\`loom update ${id}\\``)}`,\n onSome: (version) =>\n version === serviceVersion\n ? ` ${teal('●')} ${id}`\n : ` ${dim('◐')} ${id}${dim(` — ${version} is installed; run \\`loom update ${id}\\` for ${serviceVersion}`)}`,\n })\n yield* Console.log(\n `\\n ${dim('store')} ${storeDir(dir)}\\n` +\n ` ${dim('primary')} ${primary ?? dim('(none)')}\\n` +\n ` ${dim('activated')} ${languages.length === 0 ? dim('(none)') : languages.join(', ')}\\n`,\n )\n if (languages.length > 0) yield* Console.log(`${languages.map(mark).join('\\n')}\\n`)\n})\n\ntype Finding = Data.TaggedEnum<{\n Fine: { readonly note: string }\n Problem: { readonly note: string; readonly fix: string }\n}>\nconst Finding = Data.taggedEnum<Finding>()\n\nconst commandNames = (command: string): ReadonlyArray<string> =>\n process.platform === 'win32' ? [`${command}.exe`, `${command}.cmd`] : [command]\n\nconst isProgram = (file: string): boolean =>\n pipe(\n Option.liftThrowable(() => statSync(file))(),\n Option.exists(\n (stats) => stats.isFile() && (process.platform === 'win32' || (stats.mode & 0o111) !== 0),\n ),\n )\n\nconst programsOnPath = (command: string): ReadonlyArray<string> =>\n pipe(\n (process.env.PATH ?? '').split(delimiter),\n Array.filter((folder) => folder !== ''),\n Array.flatMap((folder) =>\n Array.map(commandNames(command), (name) => resolvePath(folder, name)),\n ),\n Array.filter(isProgram),\n Array.dedupeWith((one, other) => realOf(one) === realOf(other)),\n )\n\nconst loomsOnPath = (): ReadonlyArray<string> => programsOnPath('loom')\n\nconst installationOf = (file: string): Installation =>\n installationAt(realOf(file), Installation.Unowned())\n\nconst isThisLoom = (file: string): boolean =>\n realOf(file) === realOf(thisFile) || Equal.equals(installationOf(file), thisInstallation)\n\nconst installLine =\n 'curl -fsSL https://github.com/athrio-com/loom/releases/latest/download/install.sh | sh'\n\nconst installerRemoval = (installation: Installation, file: string): string =>\n Installation.$match(installation, {\n Executable: () => `rm ${quoted(file)}`,\n Unowned: () => `rm ${quoted(file)}`,\n Homebrew: () => 'brew uninstall loom',\n Npm: () => 'npm uninstall -g @athrio/loom',\n Bun: () => 'bun remove -g @athrio/loom',\n Pnpm: () => 'pnpm remove -g @athrio/loom',\n Project: ({ root, manager }) =>\n `cd ${quoted(root)} && ${projectCommands[manager].remove} @athrio/loom`,\n })\n\nconst otherLoom = (file: string, note: string): Finding =>\n Finding.Problem({\n note: `${note}, ${describedInstallation(installationOf(file))}`,\n fix: installerRemoval(installationOf(file), file),\n })\n\nconst thisLoomFinding = Finding.Fine({\n note: `loom v${loomVersion} runs from ${thisFile}, ${describedInstallation(thisInstallation)}`,\n})\n\nconst pathFindings = (looms: ReadonlyArray<string>): ReadonlyArray<Finding> =>\n Array.match(looms, {\n onEmpty: () => [\n Finding.Problem({\n note: 'no loom is on PATH, so a terminal finds none to run',\n fix: installLine,\n }),\n ],\n onNonEmpty: ([first, ...rest]) => [\n isThisLoom(first)\n ? Finding.Fine({ note: `a terminal runs this loom, at ${first}` })\n : otherLoom(first, `a terminal runs ${first} instead`),\n ...pipe(\n rest,\n Array.filter((file) => !isThisLoom(file)),\n Array.map((file) => otherLoom(file, `${file} is on PATH too`)),\n ),\n ],\n })\n\nconst serviceFinding = (id: string, root: string): Finding =>\n Option.match(installedVersion(id, root), {\n onNone: () =>\n Finding.Problem({ note: `the store holds no service for ${id}`, fix: `loom update ${id}` }),\n onSome: (version) =>\n version === serviceVersion\n ? Finding.Fine({ note: `the store holds ${id}'s service at this Loom's ${serviceVersion}` })\n : Finding.Problem({\n note: `the store holds ${id}'s service at ${version}, and this Loom needs ${serviceVersion}`,\n fix: `loom update ${id}`,\n }),\n })\n\nconst serviceFindings = (languages: ReadonlyArray<string>, root: string): ReadonlyArray<Finding> =>\n Array.match(languages, {\n onEmpty: () => [\n Finding.Fine({ note: 'no language is activated, so the store needs no service' }),\n ],\n onNonEmpty: (ids) => Array.map(ids, (id) => serviceFinding(id, root)),\n })\n\nconst missingTypeScript = (root: string): Finding =>\n Match.value({ standalone, npm: programsOnPath('npm').length > 0 }).pipe(\n Match.when({ standalone: true }, () =>\n Finding.Fine({\n note: `the language server unpacks the TypeScript Loom carries into ${storeDir(root)} when it first starts`,\n }),\n ),\n Match.when({ npm: true }, () =>\n Finding.Fine({\n note: `the language server installs TypeScript ${typeScriptRange} into ${storeDir(root)} with npm when it first starts`,\n }),\n ),\n Match.orElse(() =>\n Finding.Problem({\n note: 'the language server finds no TypeScript, and has no npm to install one with',\n fix: installLine,\n }),\n ),\n )\n\nconst typeScriptFinding = (root: string): Finding =>\n Option.match(foundTypeScript(root), {\n onNone: () => missingTypeScript(root),\n onSome: (file) =>\n Finding.Fine({ note: `the language server finds TypeScript in ${dirname(dirname(file))}` }),\n })\n\nconst workspaceFindings = (\n root: string,\n): Effect.Effect<ReadonlyArray<Finding>, never, LoomConfig> =>\n Effect.gen(function* () {\n const config = yield* LoomConfig\n const manifest = yield* config.manifest(root)\n return [\n ...serviceFindings(Object.keys(manifest?.languages ?? {}), root),\n typeScriptFinding(root),\n ]\n })\n\nconst amber = (s: string): string => `\\x1b[38;5;214m${s}${reset}`\n\nconst findingLines = (findings: ReadonlyArray<Finding>): string =>\n Array.map(\n findings,\n Finding.$match({\n Fine: ({ note }) => ` ${teal('✓')} ${note}`,\n Problem: ({ note, fix }) => ` ${amber('✗')} ${note}\\n ${fix}`,\n }),\n ).join('\\n')\n\nconst doctor = Effect.gen(function* () {\n const dir = process.cwd()\n const machine = [thisLoomFinding, ...pathFindings(loomsOnPath())]\n const workspace = workspaceOf(dir)\n const inWorkspace = yield* Option.match(workspace, {\n onNone: () => Effect.succeed([] as ReadonlyArray<Finding>),\n onSome: workspaceFindings,\n })\n const problems = Array.filter([...machine, ...inWorkspace], Finding.$is('Problem')).length\n yield* Console.log(\n `\\n ${dim('this machine')}\\n${findingLines(machine)}\\n\\n` +\n Option.match(workspace, {\n onNone: () => ` ${dim(`no workspace holds ${dir}, so no services to check`)}\\n`,\n onSome: (root) => ` ${dim(`the workspace at ${root}`)}\\n${findingLines(inWorkspace)}\\n`,\n }),\n )\n if (problems === 0) return yield* Console.log(` ${teal('✓')} no problems found\\n`)\n yield* Console.log(` ${problems === 1 ? '1 problem' : `${problems} problems`} found\\n`)\n yield* Effect.sync(() => void (process.exitCode = 1))\n})\n\nconst set = (name: string, value: string) =>\n Effect.gen(function* () {\n const config = yield* LoomConfig\n const tangler = yield* LoomTangler\n const workspace = workspaceRoot(process.cwd())\n const usage = 'usage: loom set <name> <value>'\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n yield* Console.error(`loom: \\`${name}\\` is not a variable name — ${usage}`)\n yield* Effect.sync(() => void (process.exitCode = 1))\n return\n }\n if (value.startsWith('=')) {\n yield* Console.error(\n `loom: a value cannot begin with \\`=\\`; give the name and value with a space, no \\`=\\` — ${usage}`,\n )\n yield* Effect.sync(() => void (process.exitCode = 1))\n return\n }\n const current = yield* config.manifest(workspace)\n yield* config.edit(workspace, ['variables', name], value)\n const corpus = resolvePath(workspace, current?.corpus ?? 'corpus')\n const written = yield* tangler.tangle(corpus)\n yield* Console.log(`loom: set ${name} = ${value} (re-tangled ${written.length} files)`)\n }).pipe(\n Effect.catchTag('TangleError', (e) =>\n Console.error(e.message).pipe(Effect.andThen(Effect.sync(() => void (process.exitCode = 1)))),\n ),\n )\n\nclass DesignMissing extends Data.TaggedError('DesignMissing')<{\n readonly directory: string\n}> {}\n\nconst manifestOf = (base: string) =>\n Effect.try(() => createRequire(base).resolve('@athrio/loom-design/package.json'))\n\nconst designBinary = Effect.gen(function* () {\n const directory = process.cwd()\n const manifest = yield* manifestOf(resolvePath(directory, 'index.js')).pipe(\n Effect.catch(() => manifestOf(import.meta.url)),\n Effect.mapError(() => new DesignMissing({ directory })),\n )\n return resolvePath(dirname(manifest), 'dist', 'loom-design.js')\n})\n\nconst design = (project: string, application: string, port: number) =>\n Effect.gen(function* () {\n const binary = yield* designBinary\n const code = yield* Effect.scoped(\n Effect.flatMap(\n ChildProcess.make(binary, [project, application, '--port', String(port)], {\n stdin: 'inherit',\n stdout: 'inherit',\n stderr: 'inherit',\n }),\n (running) => running.exitCode,\n ),\n )\n yield* Effect.sync(() => void (process.exitCode = code))\n }).pipe(\n Effect.catchTag('DesignMissing', () =>\n Console.error(\n 'loom: Loom Design is not installed.\\n' +\n ' Add it with `bun add -d @athrio/loom-design`, then run this again.',\n ).pipe(Effect.andThen(Effect.sync(() => void (process.exitCode = 1)))),\n ),\n Effect.catchCause((cause) =>\n Console.error(`loom: Loom Design could not start\\n${Cause.pretty(cause)}`).pipe(\n Effect.andThen(Effect.sync(() => void (process.exitCode = 1))),\n ),\n ),\n )\n\nconst embeddedGrammar: Effect.Effect<Option.Option<Readonly<Record<string, string>>>> =\n Effect.tryPromise(() => import('virtual:tree-sitter-loom')).pipe(\n Effect.map((module) => Option.some(module.default)),\n Effect.orElseSucceed(() => Option.none()),\n )\n\nconst unpackedGrammar = (\n files: Readonly<Record<string, string>>,\n): Effect.Effect<string, never, Scope.Scope> =>\n Effect.acquireRelease(\n Effect.sync(() => mkdtempSync(resolvePath(tmpdir(), 'loom-grammar-'))),\n (dir) => Effect.sync(() => rmSync(dir, { recursive: true, force: true })),\n ).pipe(\n Effect.tap((dir) =>\n Effect.forEach(\n Object.entries(files),\n ([path, text]) =>\n Effect.sync(() => {\n mkdirSync(dirname(resolvePath(dir, path)), { recursive: true })\n writeFileSync(resolvePath(dir, path), text)\n }),\n { discard: true },\n ),\n ),\n )\n\nclass GrammarMissing extends Data.TaggedError('GrammarMissing')<{}> {}\n\nconst grammarIn = (dir: string): Option.Option<string> =>\n existsSync(resolvePath(dir, 'src', 'parser.c')) ? Option.some(dir) : Option.none()\n\nconst workspaceGrammar = (): Option.Option<string> =>\n Option.flatMap(\n Option.liftThrowable(() =>\n createRequire(import.meta.url).resolve('tree-sitter-loom/package.json'),\n )(),\n (manifest) => grammarIn(dirname(manifest)),\n )\n\nconst shippedGrammar: Effect.Effect<string, GrammarMissing, Scope.Scope> = embeddedGrammar.pipe(\n Effect.flatMap(\n Option.match({\n onSome: unpackedGrammar,\n onNone: () =>\n Option.match(workspaceGrammar(), {\n onNone: () => Effect.fail(new GrammarMissing()),\n onSome: (dir) => Effect.succeed(dir),\n }),\n }),\n ),\n)\n\nclass GrammarCompileFailed extends Data.TaggedError('GrammarCompileFailed')<{\n readonly compiler: string\n}> {}\n\nconst compileGrammar = (grammar: string, library: string) =>\n Effect.gen(function* () {\n const compiler = process.env.CC ?? 'cc'\n const partial = `${library}.${process.pid}`\n const source = resolvePath(grammar, 'src')\n const code = yield* Effect.scoped(\n Effect.flatMap(\n ChildProcess.make(\n compiler,\n [\n '-shared',\n '-fPIC',\n '-O2',\n '-I',\n source,\n resolvePath(source, 'parser.c'),\n resolvePath(source, 'scanner.c'),\n '-o',\n partial,\n ],\n { stdin: 'inherit', stdout: 'inherit', stderr: 'inherit' },\n ),\n (running) => running.exitCode,\n ),\n ).pipe(Effect.catchCause(() => Effect.succeed(-1)))\n if (code !== 0) return yield* Effect.fail(new GrammarCompileFailed({ compiler }))\n yield* Effect.sync(() => renameSync(partial, library))\n })\n\nconst grammarLibrary = process.platform === 'win32' ? 'loom.dll' : 'loom.so'\n\nconst writeLibrary = (prebuilt: Blob, library: string): Effect.Effect<void> =>\n Effect.promise(() => prebuilt.arrayBuffer()).pipe(\n Effect.flatMap((bytes) =>\n Effect.sync(() => {\n const partial = `${library}.${process.pid}`\n writeFileSync(partial, new Uint8Array(bytes), { mode: 0o755 })\n renameSync(partial, library)\n }),\n ),\n )\n\nconst buildGrammar = (grammar: string, library: string) =>\n Option.match(embeddedFile(grammarLibrary), {\n onSome: (prebuilt) => writeLibrary(prebuilt, library),\n onNone: () => compileGrammar(grammar, library),\n })\n\nconst refuse = (message: string) =>\n Console.error(message).pipe(Effect.andThen(Effect.sync(() => void (process.exitCode = 1))))\n\nconst cannotCompile = (error: GrammarCompileFailed) =>\n refuse(\n `loom: could not compile the grammar with \\`${error.compiler}\\`.\\n` +\n ' Install a C compiler, or name one in the CC variable, then run this again.',\n )\n\nconst helixConfigDir = (): string =>\n process.platform === 'win32'\n ? resolvePath(process.env.APPDATA ?? homedir(), 'helix')\n : resolvePath(process.env.XDG_CONFIG_HOME ?? resolvePath(homedir(), '.config'), 'helix')\n\nconst helixBlock: ManagedBlock = {\n begin: '# Loom: written by `loom helix`, which replaces this block on every run',\n end: '# Loom: end',\n lines: [\n '[[language]]',\n 'name = \"loom\"',\n 'scope = \"source.loom\"',\n 'file-types = [\"loom\"]',\n 'roots = [\".loom/config.yaml\"]',\n 'injection-regex = \"^loom$\"',\n 'language-servers = [\"loom\"]',\n 'soft-wrap = { enable = true, wrap-at-text-width = true }',\n `text-width = ${defaultWidth}`,\n '',\n '[language-server.loom]',\n 'command = \"loom\"',\n 'args = [\"lsp\", \"--stdio\"]',\n ],\n owned: /^\\s*name\\s*=\\s*\"loom\"/m,\n}\n\nclass HelixConfigClash extends Data.TaggedError('HelixConfigClash')<{\n readonly file: string\n}> {}\n\nconst withLoomLanguages = (file: string, text: string): Effect.Effect<string, HelixConfigClash> =>\n Option.match(withManagedBlock(text, helixBlock), {\n onNone: () => Effect.fail(new HelixConfigClash({ file })),\n onSome: Effect.succeed,\n })\n\nconst helix = Effect.gen(function* () {\n const config = helixConfigDir()\n const languagesFile = resolvePath(config, 'languages.toml')\n const grammar = yield* shippedGrammar\n const current = yield* Effect.sync(() =>\n existsSync(languagesFile) ? readFileSync(languagesFile, 'utf8') : '',\n )\n const languages = yield* withLoomLanguages(languagesFile, current)\n\n const library = resolvePath(config, 'runtime', 'grammars', grammarLibrary)\n yield* Effect.sync(() => mkdirSync(dirname(library), { recursive: true }))\n yield* buildGrammar(grammar, library)\n yield* Console.log(`\\n ${teal('✓')} built the grammar into ${library}`)\n\n const queries = resolvePath(config, 'runtime', 'queries', 'loom')\n yield* Effect.sync(() =>\n cpSync(resolvePath(grammar, 'editors', 'helix', 'queries', 'loom'), queries, {\n recursive: true,\n }),\n )\n yield* Console.log(` ${teal('✓')} copied the queries into ${queries}`)\n\n yield* Effect.sync(() => writeFileSync(languagesFile, languages))\n yield* Console.log(\n ` ${teal('✓')} added Loom to ${languagesFile}\\n` +\n ` ${dim('check it with `hx --health loom`')}\\n`,\n )\n}).pipe(\n Effect.scoped,\n Effect.catchTags({\n GrammarMissing: () => refuse('loom: this installation of Loom carries no grammar for Helix.'),\n GrammarCompileFailed: cannotCompile,\n HelixConfigClash: (error) =>\n refuse(\n `loom: ${error.file} already sets up Loom.\\n` +\n ' Remove its Loom entries, then run this again to replace them with the managed block.',\n ),\n }),\n)\n\nconst nvimSiteDir = (): string => {\n const name = process.env.NVIM_APPNAME ?? 'nvim'\n return process.platform === 'win32'\n ? resolvePath(process.env.LOCALAPPDATA ?? homedir(), `${name}-data`, 'site')\n : resolvePath(\n process.env.XDG_DATA_HOME ?? resolvePath(homedir(), '.local', 'share'),\n name,\n 'site',\n )\n}\n\nconst nvimHeader = '-- Loom: written by `loom nvim`, which replaces this file on every run'\n\nconst nvimPlugin = [\n nvimHeader,\n \"vim.filetype.add({ extension = { loom = 'loom' } })\",\n '',\n \"vim.lsp.config('loom', {\",\n \" cmd = { 'loom', 'lsp', '--stdio' },\",\n \" filetypes = { 'loom' },\",\n ' root_dir = function(bufnr, on_dir)',\n ' local workspace = function(name, path)',\n \" local config = vim.fs.joinpath(path, name, 'config.yaml')\",\n \" return name == '.loom' and vim.uv.fs_stat(config) ~= nil\",\n ' end',\n \" on_dir(vim.fs.root(bufnr, workspace) or vim.fs.root(bufnr, '.git'))\",\n ' end,',\n '})',\n \"vim.lsp.enable('loom')\",\n '',\n \"vim.api.nvim_create_autocmd('FileType', {\",\n \" pattern = 'loom',\",\n ' callback = function()',\n ' vim.treesitter.start()',\n \" vim.opt_local.formatoptions:remove({ 't', 'c' })\",\n ' end,',\n '})',\n '',\n].join('\\n')\n\nclass NvimConfigClash extends Data.TaggedError('NvimConfigClash')<{\n readonly file: string\n}> {}\n\nconst nvim = Effect.gen(function* () {\n const site = nvimSiteDir()\n const pluginFile = resolvePath(site, 'plugin', 'loom.lua')\n const grammar = yield* shippedGrammar\n const current = yield* Effect.sync(() =>\n existsSync(pluginFile) ? Option.some(readFileSync(pluginFile, 'utf8')) : Option.none<string>(),\n )\n if (Option.exists(current, (text) => !text.startsWith(nvimHeader)))\n return yield* Effect.fail(new NvimConfigClash({ file: pluginFile }))\n\n const parser = resolvePath(site, 'parser', 'loom.so')\n yield* Effect.sync(() => mkdirSync(dirname(parser), { recursive: true }))\n yield* buildGrammar(grammar, parser)\n yield* Console.log(`\\n ${teal('✓')} built the grammar into ${parser}`)\n\n const queries = resolvePath(site, 'queries', 'loom')\n yield* Effect.sync(() => cpSync(resolvePath(grammar, 'queries'), queries, { recursive: true }))\n yield* Console.log(` ${teal('✓')} copied the queries into ${queries}`)\n\n yield* Effect.sync(() => {\n mkdirSync(dirname(pluginFile), { recursive: true })\n writeFileSync(pluginFile, nvimPlugin)\n })\n yield* Console.log(\n ` ${teal('✓')} added Loom to ${pluginFile}\\n` +\n ` ${dim('check it with `:checkhealth vim.treesitter` in Neovim')}\\n`,\n )\n}).pipe(\n Effect.scoped,\n Effect.catchTags({\n GrammarMissing: () => refuse('loom: this installation of Loom carries no grammar for Neovim.'),\n GrammarCompileFailed: cannotCompile,\n NvimConfigClash: (error) =>\n refuse(\n `loom: ${error.file} was not written by \\`loom nvim\\`.\\n` +\n ' Move it aside, then run this again.',\n ),\n }),\n)\n\nconst tangleCommand = Command.make(\n 'tangle',\n { path: Argument.String('path'), watch: Flag.Boolean('watch').pipe(Flag.withDefault(false)) },\n ({ path, watch }) => tangle(path, watch),\n)\n\nconst orphansCommand = Command.make(\n 'orphans',\n { prune: Flag.Boolean('prune').pipe(Flag.withDefault(false)) },\n ({ prune }) => orphans(prune),\n)\n\nconst weaveCommand = Command.make(\n 'weave',\n { path: Argument.String('path'), out: Argument.String('out') },\n ({ path, out }) => weave(path, out),\n)\n\nconst formatCommand = Command.make(\n 'format',\n { path: Argument.String('path'), check: Flag.Boolean('check').pipe(Flag.withDefault(false)) },\n ({ path, check }) => format(path, check),\n)\n\nconst tocCommand = Command.make('toc', { path: Argument.String('path') }, ({ path }) => toc(path))\n\nconst initCommand = Command.make(\n 'init',\n { dir: Argument.optional(Argument.Directory('dir')) },\n ({ dir }) => init(dir),\n)\n\nconst addCommand = Command.make('add', { language: Argument.String('language') }, ({ language }) =>\n add(language),\n)\n\nconst removeCommand = Command.make(\n 'remove',\n { language: Argument.String('language') },\n ({ language }) => remove(language),\n)\n\nconst updateCommand = Command.make(\n 'update',\n {\n languages: Argument.String('language').pipe(Argument.variadic()),\n all: Flag.Boolean('all').pipe(Flag.withDefault(false)),\n },\n ({ languages, all }) => update(languages, all),\n)\n\nconst upgradeCommand = Command.make('upgrade', {}, () => upgrade)\n\nconst statusCommand = Command.make('status', {}, () => status)\n\nconst doctorCommand = Command.make('doctor', {}, () => doctor)\n\nconst setCommand = Command.make(\n 'set',\n { name: Argument.String('name'), value: Argument.String('value') },\n ({ name, value }) => set(name, value),\n)\n\nconst designCommand = Command.make(\n 'design',\n {\n project: Argument.String('name'),\n application: Argument.String('address'),\n port: Flag.Int('port').pipe(Flag.withDefault(5710)),\n },\n ({ project, application, port }) => design(project, application, port),\n)\n\nconst helixCommand = Command.make('helix', {}, () => helix)\n\nconst nvimCommand = Command.make('nvim', {}, () => nvim)\n\nconst loom = Command.make('loom').pipe(\n Command.withSubcommands([\n tangleCommand,\n orphansCommand,\n weaveCommand,\n tocCommand,\n formatCommand,\n initCommand,\n addCommand,\n removeCommand,\n updateCommand,\n upgradeCommand,\n statusCommand,\n doctorCommand,\n setCommand,\n designCommand,\n helixCommand,\n nvimCommand,\n ]),\n)\n\nconst program = Command.run(loom, { version: loomVersion }).pipe(\n Effect.provide(LoomTangler.layer),\n Effect.provide(LoomWeaver.layer),\n Effect.provide(LoomContents.layer),\n Effect.provide(LoomFormatter.layer),\n Effect.provide(DocumentSource.layer),\n Effect.provide(PackageConfig.layer),\n Effect.provide(LoomConfig.layer),\n Effect.provide(NodeServices.layer),\n)\n\nif (process.argv[2] === 'lsp') {\n ;(globalThis as { require?: unknown }).require = createRequire(import.meta.url)\n const { startLanguageServer } = await import('@athrio/loom-lang/LoomServer')\n startLanguageServer()\n} else {\n NodeRuntime.runMain(program)\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,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