hostctl 0.1.32 → 0.1.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/hostctl.js +1 -1
- package/dist/bin/hostctl.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/bin/hostctl.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli.ts","../../src/app.ts","../../src/handlebars.ts","../../src/config.ts","../../src/config-file.ts","../../src/flex/function.ts","../../src/flex/protocol.ts","../../src/flex/type.ts","../../src/flex/compactable.ts","../../src/flex/enumerator.ts","../../src/flex/enumerable.ts","../../src/flex/mappable.ts","../../src/flex/selectable.ts","../../src/flex/array-protocols.ts","../../src/flex/map.ts","../../src/flex/map-protocols.ts","../../src/flex/object.ts","../../src/flex/object-protocols.ts","../../src/flex/path.ts","../../src/flex/platform.ts","../../src/flex/string.ts","../../src/flex/range.ts","../../src/flex/equal.ts","../../src/flex/range-protocols.ts","../../src/flex/set-protocols.ts","../../src/flex/array.ts","../../src/flex/set.ts","../../src/flex/pipe.ts","../../src/tempfile.ts","../../src/flex/file.ts","../../src/host.ts","../../src/age-encryption.ts","../../src/process.ts","../../src/config-url.ts","../../src/interaction-handler.ts","../../src/task.model.ts","../../src/stacktrace.ts","../../src/runtime-base.ts","../../src/command.ts","../../src/local-runtime.ts","../../src/ruspty-command.ts","../../src/util/input-helpers.ts","../../src/remote-runtime.ts","../../src/ssh-session.ts","../../src/node-runtime.ts","../../src/http.ts","../../src/shell-command.ts","../../src/unarchive.ts","../../src/zip.ts","../../src/hash.ts","../../src/param-map.ts","../../src/version.ts","../../src/core/remote/runAllRemote.ts","../../src/cli/run-resolver.ts","../../src/bin/hostctl.ts"],"sourcesContent":["import process from 'node:process';\nimport * as cmdr from 'commander';\n\nimport { App, Verbosity } from './app';\nimport { File } from './flex/file';\nimport { version } from './version';\n\nimport JSON5 from 'json5';\nimport { Path } from './flex/path';\n\nimport { resolveScriptPath } from './cli/run-resolver';\n\n/**\n * Type guard to check if an `unknown` value is an `Error` object.\n *\n * @param value - The value to check.\n *\n * @returns `true` if the value is an `Error` object, otherwise `false`.\n */\nexport const isError = (value: unknown): value is Error =>\n !!value &&\n typeof value === 'object' &&\n 'message' in value &&\n typeof value.message === 'string' &&\n 'stack' in value &&\n typeof value.stack === 'string';\n\nconst logError = (message: string, error: unknown): void => {\n console.error(`Error: ${message}`); // Print the primary message to stderr\n if (isError(error)) {\n console.error(error.stack); // Print stack to stderr\n } else {\n try {\n // For unknown errors, create a new error to get a stack trace pointing to this logError call\n const unknownError = new Error(\n `Unexpected value thrown: ${typeof error === 'object' ? JSON.stringify(error) : String(error)}`,\n );\n console.error(unknownError.stack);\n } catch {\n console.error(new Error(`Unexpected value thrown: non-stringifiable object`).stack);\n }\n }\n};\n\nfunction isValidUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch (_) {\n return false;\n }\n}\n\n// per example at https://github.com/tj/commander.js/blob/HEAD/examples/options-custom-processing.js\nfunction increaseVerbosity(dummyValue: any, previous: number) {\n return previous + 1;\n}\n\nfunction decreaseVerbosity(dummyValue: any, previous: number) {\n return previous - 1;\n}\n\nexport class Cli {\n public app: App;\n public program: cmdr.Command;\n\n constructor() {\n this.app = new App();\n\n this.program = new cmdr.Command();\n\n this.program\n .configureHelp({ showGlobalOptions: true })\n .name('hostctl')\n .version(version)\n .option('-q, --quiet', 'quiet; be less verbose; may be specified multiple times', decreaseVerbosity, 0)\n .option(\n '-v, --verbose',\n 'verbose; may be specified multiple times for increased verbosity',\n increaseVerbosity,\n Verbosity.WARN,\n )\n .option('-c, --config <file path>', 'config file path or http endpoint')\n .option('--json', 'output should be json formatted')\n .option('-p, --password', 'should prompt for sudo password?', false)\n .option('-t, --tag <tags...>', 'specify a tag (repeat for multiple tags)');\n\n this.program\n .command('bundle')\n .alias('b')\n .argument('[path]', `the path to bundle (e.g. hostctl bundle .)`, '.')\n .description('bundle the given path as an npm project')\n .action(this.handleBundle.bind(this));\n\n this.program\n .command('exec')\n .alias('e')\n .argument(\n '<command...>',\n `the command string to run, with optional arguments (e.g. hostctl exec sudo sh -c 'echo \"$(whoami)\"')`,\n )\n .description('execute a command on the selected hosts (default)')\n .action(this.handleExec.bind(this));\n\n const inventoryCmd = this.program.command('inventory').alias('i').description('manage inventory and view reports');\n\n inventoryCmd\n .command('report', { isDefault: true })\n .description('print out an inventory report (default)')\n .action(this.handleInventory.bind(this));\n\n inventoryCmd\n .command('encrypt')\n .alias('e')\n .description('encrypt the inventory file')\n .action(this.handleInventoryEncrypt.bind(this));\n\n inventoryCmd\n .command('decrypt')\n .alias('d')\n .description('decrypt the inventory file')\n .action(this.handleInventoryDecrypt.bind(this));\n\n inventoryCmd\n .command('list')\n .alias('ls')\n .description('list the hosts in the inventory file')\n .action(this.handleInventoryList.bind(this));\n\n this.program\n .command('run')\n .alias('r')\n .argument(\n '[package_or_bundle]',\n `the package or bundle to run the specified <script> from.\n The package or bundle may be either:\n - a directory in the local filesystem, e.g. /my/package/foo\n - a git repository, e.g. https://github.com/hostctl/core\n - a zipped package (a bundle), e.g. packagebundle123.zip\n `,\n )\n .argument(\n '[script]',\n `the hostctl script to run (e.g. hostctl run myscript OR hostctl run mypackage myscript).\n The script may be specified as either:\n - a package followed by the script, e.g. hostctl run github.com/hostctl/core echo args:hello,world\n - a script, e.g. hostctl run main.ts\n - a zipped package (a bundle), e.g. hostctl run packagebundle.zip echo args:hello,world`,\n )\n .argument('[script arguments...]', 'the runtime arguments to the script.')\n .description('run a hostctl script (default)')\n .option(\n '-f, --file <path>',\n 'runtime parameters should be read from file at <path> containing json object representing params to supply to the script',\n )\n .option(\n '-p, --params \"<json object>\"',\n 'runtime parameters supplied as a string to be parsed as a json object representing params to supply to the script',\n )\n .option('-r, --remote', 'run the script on remote hosts specified by tags via SSH orchestration')\n .action(this.handleRun.bind(this));\n\n const runtimeCmd = this.program\n .command('runtime')\n .alias('rt')\n .description('print out a report of the runtime environment')\n .action(this.handleRuntime.bind(this));\n\n runtimeCmd\n .command('install')\n .alias('i')\n .description('install a temporary runtime environment on the local host if needed')\n .action(this.handleRuntimeInstall.bind(this));\n }\n\n async handleBundle(path: string, options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n this.app.bundleProject(path);\n }\n\n async handleInventory(options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n this.app.printInventoryReport();\n }\n\n async handleInventoryEncrypt(options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n await this.app.encryptInventoryFile();\n }\n\n async handleInventoryDecrypt(options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n await this.app.decryptInventoryFile();\n }\n\n async handleInventoryList(options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n if (!this.app.config) {\n console.log('Configuration could not be loaded. Cannot list hosts.');\n if (!this.app.configRef) {\n console.log('(Also, no configuration file path was found by the app instance)');\n }\n return;\n }\n\n console.log('Config file: ' + this.app.configRef);\n\n const hosts = this.app.selectedInventory(); // Use tags from options if provided\n if (hosts.length > 0) {\n console.log('\\nHosts in inventory:');\n hosts.forEach((host) => {\n let hostIdentifier = host.shortName || '(Unnamed host)';\n console.log(` - ${hostIdentifier}`);\n if (host.tags && host.tags.length > 0) {\n console.log(` Tags: ${host.tags.join(', ')}`);\n }\n });\n } else {\n const selectedTagsSet = this.app.selectedTags;\n const selectedTagsArray = Array.from(selectedTagsSet);\n if (selectedTagsArray.length > 0) {\n console.log(`No hosts found matching tags: ${selectedTagsArray.join(', ')}`);\n } else {\n console.log('No hosts found in the inventory.');\n }\n }\n }\n\n async handleExec(commandParts: string | string[], options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n this.app.warn(`Executing command: ${commandParts}`);\n\n const success = await this.app.execute(commandParts);\n\n // Propagate exit status so that callers can detect failures\n if (!success) {\n // Non-zero indicates at least one host failed\n process.exitCode = 1;\n }\n }\n\n async handleRun(\n packageOrBundle: string | null,\n scriptRef: string | undefined,\n scriptArgs: string[],\n options: Record<string, any>,\n cmd: cmdr.Command,\n ) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n this.app.debug(`tags: ${opts.tag}, remote: ${opts.remote}`);\n\n // Resolve script path using helper\n const resolved = await resolveScriptPath(this.app, packageOrBundle, scriptRef, scriptArgs);\n scriptRef = resolved.scriptRef;\n scriptArgs = resolved.scriptArgs;\n\n let params: object = {};\n try {\n if (options.params) {\n params = JSON5.parse(options.params);\n } else if (options.file) {\n const contents = File.readSync(options.file);\n params = JSON5.parse(contents);\n } else {\n params = this.app.parseParams(scriptArgs);\n }\n } catch (err) {\n this.app.error(\n `Failed to parse params as JSON5: ${(err as Error).message}`,\n `params: ${JSON5.stringify(options.params)}`,\n );\n throw new Error(`Failed to parse params as JSON5: ${(err as Error).message}`);\n }\n\n if (!scriptRef) {\n this.program.help();\n }\n\n this.app.debug(`Resolved script: ${scriptRef}`);\n this.app.debug(`Script params: ${JSON.stringify(params)}`);\n\n if (opts.remote) {\n await this.app.runScriptRemote(scriptRef, params);\n } else {\n await this.app.runScript(scriptRef, params);\n }\n }\n\n deriveConfigRef(suppliedConfigRef?: string): string {\n // 1. If suppliedConfigRef is an existing file, use it.\n if (suppliedConfigRef && Path.new(suppliedConfigRef).isFile()) {\n return Path.new(suppliedConfigRef).toString();\n }\n\n // 2. Search CWD and ancestors for hostctl.yaml\n const foundPath = Path.cwd()\n .selfAndAncestors()\n .find((p) => p.join('hostctl.yaml').isFile());\n if (foundPath) {\n return foundPath.join('hostctl.yaml').toString();\n }\n\n // 3. Check for ~/.hostctl/hostctl.yaml\n const homeConfigPath = Path.homeDir().join('.hostctl', 'hostctl.yaml');\n if (homeConfigPath.isFile()) {\n return homeConfigPath.toString();\n }\n\n // 4. If a configRef was supplied (e.g. -c URL or -c non-existent-file), use that.\n // This allows `load()` to handle it as a ConfigUrl or report non-existence.\n if (suppliedConfigRef && isValidUrl(suppliedConfigRef)) {\n return suppliedConfigRef;\n }\n\n // 5. Otherwise, error out\n throw new Error(\n \"Could not find a hostctl configuration file. Searched for 'hostctl.yaml' in the current directory, ancestor directories, and '~/.hostctl/hostctl.yaml'. If you intended to use a URL or a specific file path, please ensure it's correct and accessible via the -c option.\",\n );\n }\n\n async loadApp(opts: Record<string, any>) {\n const derivedConfigRef = this.deriveConfigRef(opts.config);\n await this.app.loadConfig(derivedConfigRef);\n\n const verbosity = opts.quiet + opts.verbose;\n this.app.setVerbosity(verbosity);\n if (opts.json) {\n this.app.setOutputStyle('json');\n } else {\n this.app.setOutputStyle('plain');\n }\n let tagsToSet: string[] = [];\n if (typeof opts.tag === 'string') {\n tagsToSet = [opts.tag];\n } else if (Array.isArray(opts.tag)) {\n tagsToSet = opts.tag;\n }\n this.app.setSelectedTags(tagsToSet);\n }\n\n async run() {\n try {\n await this.program.parseAsync(process.argv);\n } catch (e) {\n logError('hostctl error:', e);\n }\n }\n\n async handleRuntime(options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n await this.app.printRuntimeReport();\n }\n\n async handleRuntimeInstall(options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n await this.app.installRuntime();\n }\n}\n","import process from 'node:process';\nimport * as fs from 'node:fs';\nimport { homedir } from 'node:os';\nimport Handlebars from './handlebars';\n\n// import Emittery from \"emittery\"; // Believed to be unused\nimport { type Config, load } from './config';\nimport type { Secret, RecipientGroup } from './config-file';\n\nexport type AppConfig = Config; // Alias for the main application configuration type\nimport { Host } from './host';\nimport { InteractionHandler } from './interaction-handler';\n\nimport { A } from './flex/array';\nimport { Path } from './flex/path';\nimport * as util from 'node:util';\nimport { ConfigFile } from './config-file';\nimport chalk from 'chalk';\nimport { S } from './flex/set';\nimport { password as promptPassword } from '@inquirer/prompts';\nimport { Listr } from 'listr2';\nimport { isError } from './cli';\nimport { LocalRuntime } from './runtime';\nimport { TmpFileRegistry } from './tempfile';\nimport { NodeRuntime } from './node-runtime';\nimport { zipDirectory } from './zip';\nimport { sha256 } from './hash';\nimport { ParamMap } from './param-map';\nimport {\n type IInvocation,\n type LocalInvocation,\n type RunFnReturnValue,\n type TaskFn,\n type TaskContext,\n type LogLevel,\n type TaskParams,\n RemoteInvocation,\n RemoteRuntime,\n type TaskPartialFn,\n type RunFn,\n} from './runtime';\nimport { version } from './version';\nimport { retryUntilDefined } from 'ts-retry';\nimport { Mutex } from 'async-mutex';\nimport { Command } from './command';\nimport { task } from './runtime'; // Added for executeShellCommandTask\nimport { type CommandResult, type EnvVarObj } from './command'; // EnvVarObj from command.ts\nimport { VP } from './flex/pipe';\nimport { match } from 'ts-pattern';\nimport { SSHSession } from './ssh-session';\nimport runAllRemote from './core/remote/runAllRemote';\nimport { CHECKMARK, withSudo, XMARK } from './util/input-helpers';\n\nexport type TaskTreeNode = {\n id: string;\n parentId: string | null;\n parent: TaskTreeNode | undefined;\n children: Set<TaskTreeNode>;\n name: string;\n result?: Promise<string | Error | undefined>;\n};\ntype NewTaskEvent = { id: string; parentId: string; name: string };\ntype TaskCompleteEvent = { id: string; result: any };\n\nexport class TaskTree {\n // private taskEventBus: Emittery<{ newTask: NewTaskEvent; taskComplete: TaskCompleteEvent }>;\n private listr: Listr;\n private subLists: Map<string, Promise<Listr>>;\n private nodes: Map<string, TaskTreeNode>;\n private mutex: Mutex;\n\n constructor() {\n this.mutex = new Mutex();\n this.nodes = new Map();\n this.subLists = new Map();\n // this.taskEventBus = new Emittery();\n // this.taskEventBus.on(\"newTask\", (newTaskEvent) => {\n // this.handleNewTask(newTaskEvent);\n // });\n // this.taskEventBus.on(\"taskComplete\", (taskCompleteEvent) => {\n // this.handleTaskComplete(taskCompleteEvent);\n // });\n this.listr = new Listr([], {\n // exitOnError: false,\n concurrent: true,\n rendererOptions: { collapseSubtasks: false },\n });\n }\n\n clear() {\n this.nodes.clear();\n this.subLists.clear();\n this.listr = new Listr([], {\n // exitOnError: false,\n concurrent: true,\n rendererOptions: { collapseSubtasks: false },\n });\n }\n\n async add(\n id: string,\n parentId: string | null,\n name: string,\n result?: Promise<string | Error | undefined>,\n ): Promise<TaskTreeNode> {\n return await this.mutex.runExclusive(async () => {\n const parent = this.get(parentId as string);\n const newNode: TaskTreeNode = { id, parentId, parent, children: new Set(), name, result };\n this.nodes.set(id, newNode);\n\n this.listr.add({\n title: newNode.name,\n task: async (ctx, task): Promise<void> => {\n await result;\n },\n });\n\n return newNode;\n });\n }\n\n get(id: string): TaskTreeNode | undefined {\n return this.nodes.get(id);\n }\n\n async getWithTimeout(id: string): Promise<TaskTreeNode | undefined> {\n try {\n return await retryUntilDefined(\n () => {\n return this.get(id);\n },\n { delay: 50, maxTry: 5 },\n );\n } catch (err) {\n return undefined;\n }\n }\n\n // setResult(id: string, result: Promise<string | Error | undefined>): TaskTreeNode | undefined {\n // const node = this.get(id);\n // if (node) {\n // node.result = result;\n // }\n // return node;\n // }\n\n run(ctx?: any) {\n return this.listr.run(ctx);\n }\n\n // emit(name: any, event: any) {\n // this.taskEventBus.emit(name, event);\n // }\n}\n\nexport const Verbosity = {\n ERROR: 0,\n WARN: 1,\n INFO: 2,\n DEBUG: 3,\n TRACE: 4,\n};\n\nexport class App {\n public configRef?: string;\n private _config?: Config;\n public selectedTags: Set<string>;\n private outputStyle: 'plain' | 'json';\n private _tmpDir?: Path;\n private tmpFileRegistry: TmpFileRegistry;\n\n public taskTree: TaskTree;\n public verbosity = Verbosity.ERROR;\n\n constructor() {\n this.taskTree = new TaskTree();\n this.selectedTags = new Set([]);\n this.outputStyle = 'plain';\n this.tmpFileRegistry = new TmpFileRegistry(this.hostctlTmpDir());\n this.configRef = undefined;\n process.on('exit', (code) => this.appExitCallback());\n }\n\n appExitCallback() {\n // This callback is registered for the process 'exit' event.\n // Cleanup tasks, if any, can be performed here.\n // The TmpFileRegistry has its own exit handler to cleanup temporary files.\n }\n\n get config(): Config {\n if (!this._config) {\n throw new Error('Configuration has not been loaded. Call loadConfig() first.');\n }\n return this._config;\n }\n\n get tmpDir(): Path {\n if (!this._tmpDir) {\n // Ensure hostctlDir exists before creating a subdirectory in it.\n if (!fs.existsSync(this.hostctlDir().toString())) {\n fs.mkdirSync(this.hostctlDir().toString(), { recursive: true });\n }\n this._tmpDir = this.createNamedTmpDir(version);\n }\n return this._tmpDir;\n }\n\n async loadConfig(configString?: string) {\n this.configRef = configString;\n this._config = await load(configString);\n }\n\n log(level: LogLevel, ...args: any[]): void {\n if (this.outputStyle === 'plain' && this.verbosity >= level) {\n console.log(...args);\n }\n }\n\n debug(...args: any[]): void {\n this.log(Verbosity.DEBUG, ...args);\n }\n\n info(...args: any[]): void {\n this.log(Verbosity.INFO, ...args);\n }\n\n warn(...args: any[]): void {\n this.log(Verbosity.WARN, ...args);\n }\n\n error(...args: any[]): void {\n this.log(Verbosity.ERROR, ...args);\n }\n\n osHomeDir(): Path {\n return Path.new(homedir()).absolute();\n }\n\n hostctlDir(): Path {\n return this.osHomeDir().join('.hostctl');\n }\n\n hostctlTmpDir() {\n return this.hostctlDir().join('tmp');\n }\n\n randName(): string {\n return Math.random().toString(36).slice(-5) + Math.random().toString(36).slice(-5);\n }\n\n hostctlTmpPath(tmpName?: string) {\n tmpName ??= this.randName();\n return this.hostctlTmpDir().join(tmpName);\n }\n\n // this directory will be automatically cleaned up at program exit\n createNamedTmpDir(subDirName?: string): Path {\n return this.tmpFileRegistry.createNamedTmpDir(subDirName);\n }\n\n // this file will be automatically cleaned up at program exit\n writeTmpFile(fileContent: string): Path {\n return this.tmpFileRegistry.writeTmpFile(fileContent);\n }\n\n shouldRunRemote(): boolean {\n // If any explicitly selected host is remote, assume remote intent for those.\n // If all selected hosts are local or no hosts are specified (implying local), run locally.\n const selectedHosts = this.selectedInventory();\n if (selectedHosts.length === 0 && this.selectedTags.size === 0) return false; // Default to local if no tags/hosts specified\n return selectedHosts.some((h) => !h.isLocal()); // True if any selected host is remote\n }\n\n logHostCommandResult(\n host: Host,\n command: string | string[],\n cmdOrErr: Command | Error,\n isErrorResult: boolean = false,\n ) {\n const hostName = host.uri || (host.isLocal() ? 'localhost' : 'unknown-host');\n if (cmdOrErr instanceof Error || isErrorResult) {\n const error = cmdOrErr as Error;\n this.debug(chalk.red(`[${hostName}] Error executing command \"${command}\": ${error.message}`));\n if (error.stack && this.verbosity >= Verbosity.DEBUG) {\n this.debug(chalk.red(error.stack));\n }\n } else {\n const cmdRes = cmdOrErr.result!;\n this.debug(chalk.green(`[${hostName}] Success executing \"${command}\" (exit code: ${cmdRes.exitCode})`));\n if (cmdRes.stdout) {\n this.debug(chalk.cyan(`[${hostName}] STDOUT:\\n${cmdRes.stdout.trim()}`));\n }\n if (cmdRes.stderr) {\n this.debug(chalk.yellow(`[${hostName}] STDERR:\\n${cmdRes.stderr.trim()}`));\n }\n }\n }\n\n defaultSshUser(): string | undefined {\n // TODO: Implement logic to get default SSH user from config\n // For example, look for a global default or a host-specific override\n // return this.config?.globalSettings?.defaultSshUser;\n return undefined; // Placeholder\n }\n\n // entrypoint for the cli: AGE_IDS=~/.secrets/age/test-jill.priv tsx bin/ops.ts e whoami -t ubuntu\n // e.g. AGE_IDS=~/.secrets/age/david.priv tsx bin/ops.ts -c david.yaml exec \"whoami\" -t synology blog 4gb web1\n async execute(cmd: string | string[]): Promise<boolean> {\n const selectedHosts = this.selectedInventory();\n\n // this.warn(`exec: ${chalk.cyan(cmd)}`);\n const cmdResults: Array<Promise<Command | Error>> = A(selectedHosts).map((host: Host) => this.runRemote(host, cmd));\n\n const hostResultQuads = await VP(selectedHosts)\n .a.zip(cmdResults)\n .a.map(([host, cmdPromise]: [Host, Promise<Command | Error>]) => {\n return cmdPromise.then((cmd) =>\n match(cmd)\n .when(isError, (err) => [host, false, '', chalk.red(err.message)])\n .otherwise((cmd) => [host, cmd.result?.success ?? false, cmd.result?.stdout, cmd.result?.stderr]),\n );\n })\n .waitAll().value;\n\n if (this.outputStyle === 'plain') {\n this.warn(chalk.yellow('=== Result ==='));\n A(hostResultQuads).each(([host, success, stdout, stderr]: [Host, boolean, string, string]) => {\n this.warn(\n `${success ? chalk.green(CHECKMARK) : chalk.red(XMARK)} ${chalk.cyan(host.hostname)}${host.alias ? ` (${host.alias})` : ''}`,\n );\n if (stdout) {\n this.warn(stdout);\n }\n if (stderr) {\n this.warn(chalk.red(stderr));\n }\n this.warn(chalk.yellow('--------------'));\n });\n } else if (this.outputStyle === 'json') {\n const result = A(hostResultQuads).reduce(\n (\n acc: Record<string, { alias: string; success: boolean; stdout: string; stderr: string }>,\n [host, success, stdout, stderr]: [Host, boolean, string, string],\n ) => {\n acc[host.hostname] = {\n alias: host.alias || '',\n success,\n stdout,\n stderr,\n };\n return acc;\n },\n {} as Record<string, { alias: string; success: boolean; stdout: string; stderr: string }>,\n );\n console.log(JSON.stringify(result, null, 2));\n }\n\n return hostResultQuads.every(([_, success]: [Host, boolean]) => success);\n }\n\n // used by execute to run a command on the remote host\n async runRemote(host: Host, cmd: string | string[]): Promise<Command | Error> {\n try {\n const hostPassword = await host.decryptedPassword();\n const sshConnection = {\n host: host.uri,\n username: host.user,\n password: hostPassword,\n privateKeyPath: await host.plaintextSshKeyPath(),\n };\n\n const interactionHandler = InteractionHandler.with(withSudo(hostPassword));\n\n const session = new SSHSession();\n await session.connect(sshConnection);\n\n const commandObj = await session.run(cmd, interactionHandler);\n\n session.disconnect();\n\n return commandObj;\n } catch (e) {\n return e as Error;\n }\n }\n\n getSecretsForHost(hostId: string): Map<string | RegExp, string> {\n const secretsMap = new Map<string | RegExp, string>();\n if (!this._config) {\n return secretsMap; // No config loaded\n }\n // Placeholder: Actual logic to populate secretsMap based on hostId and _config needed here.\n // For now, it correctly returns an empty map if no config or no specific secrets found.\n return secretsMap;\n }\n\n public taskContextForRunFn<TParams extends TaskParams>(\n invocation: IInvocation<TParams>,\n params: TParams,\n hostForContext?: Host, // Optional host, primarily for remote tasks. The invocation itself might have a host.\n ): TaskContext<TParams> {\n const effectiveHost = hostForContext || invocation.host;\n\n return {\n // Properties from TaskContext\n params,\n id: invocation.id,\n host: effectiveHost,\n config: invocation.config, // Delegated from invocation\n\n // Methods from TaskContext, delegating to invocation\n log: (level: LogLevel, ...message: any[]) => {\n invocation.log(level, ...message);\n },\n info: (...message: any[]) => {\n invocation.info(...message);\n },\n debug: (...message: any[]) => {\n invocation.debug(...message);\n },\n warn: (...message: any[]) => {\n invocation.warn(...message);\n },\n error: (...message: any[]) => {\n invocation.error(...message);\n },\n exec: async (\n command: string | string[],\n options?: {\n input?: Record<string, string>;\n sudo?: boolean;\n stdin?: string | Buffer;\n env?: EnvVarObj;\n cwd?: string;\n user?: string;\n pty?: boolean;\n },\n ) => {\n return await invocation.exec(command, options);\n },\n ssh: async <TRemoteParams extends TaskParams, TRemoteReturn extends RunFnReturnValue>(\n tags: string[],\n remoteTaskFn: (remoteContext: TaskContext<TRemoteParams>) => Promise<TRemoteReturn>,\n ): Promise<Record<string, TRemoteReturn | Error>> => {\n return await invocation.ssh(tags, remoteTaskFn);\n },\n run: async <TRunReturn extends RunFnReturnValue>(\n taskPartialFn: TaskPartialFn<TRunReturn>,\n ): Promise<TRunReturn> => {\n return await invocation.run(taskPartialFn);\n },\n getPassword: async (): Promise<string | undefined> => {\n return await invocation.getPassword();\n },\n getSecret: async (name: string): Promise<string | undefined> => {\n return await invocation.getSecret(name);\n },\n exit: (exitCode: number, message?: string): void => {\n invocation.exit(exitCode, message);\n },\n inventory: (tags: string[]): Host[] => {\n return invocation.inventory(tags);\n },\n file: invocation.file,\n };\n }\n\n setSelectedTags(selectedTags: string[]) {\n this.selectedTags = new Set(selectedTags);\n }\n\n setOutputStyle(outputStyle: 'plain' | 'json') {\n this.outputStyle = outputStyle;\n }\n\n setVerbosity(level: number) {\n this.verbosity = level;\n }\n\n outputJson() {\n return this.outputStyle == 'json';\n }\n\n outputPlain() {\n return this.outputStyle == 'plain';\n }\n\n querySelectedInventory(tags: string[] = []): Host[] {\n return this.selectInventory(this.selectedInventory(), new Set(tags));\n }\n\n selectedInventory(): Host[] {\n return this.queryInventory(this.selectedTags);\n }\n\n // returns hosts that have *all* of the given tags\n // each tag is a string of the form:\n // - foo\n // - bar+baz\n // the tags are interpreted to be in disjunctive-normal-form: a disjunction of conjunctions\n queryInventory(tags: Set<string> = new Set()): Host[] {\n if (!this._config) {\n this.warn('Warning: Configuration not loaded, cannot query inventory.');\n return [];\n }\n const allHosts = this._config.hosts(); // Changed from inventory() to hosts()\n if (tags.size === 0) {\n return allHosts;\n }\n return this.selectInventory(allHosts, new Set(tags));\n }\n\n selectInventory(hosts: Host[], tags: Set<string> = new Set()): Host[] {\n if (S(tags).isEmpty()) {\n return hosts;\n }\n\n return A(hosts).select((host: Host) => host.hasAnyTag(tags));\n }\n\n // entrypoint for the cli: AGE_IDS=~/.secrets/age/test-jill.priv tsx bin/hostctl.ts inventory -t ubuntu\n printInventoryReport() {\n const configFromGetter = this.config;\n const config: Config = configFromGetter; // Explicitly type 'config'\n const allHosts = config.hosts(); // Gets all hosts if no tags are specified\n const allSecrets = config.secrets(); // Map<string, Secret>\n const allIds = config.ids(); // Map<string, RecipientGroup>\n\n if (this.outputPlain()) {\n let output = 'Config file: ' + this.configRef + '\\n\\nHosts:\\n';\n if (allHosts.length > 0) {\n allHosts.forEach((host) => {\n output += ` - ${host.uri}:\\n`;\n output += ` alias: ${host.alias || ''}\\n`;\n output += ` user: ${host.user || ''}\\n`;\n output += ` port: ${host.port || ''}\\n`;\n output += ` tags: ${host.tags.join(', ')}\\n`;\n });\n } else {\n output += ' {}\\n';\n }\n\n output += '\\nSecrets:\\n';\n if (allSecrets.size > 0) {\n allSecrets.forEach((secret: Secret, name: string) => {\n output += ` - ${name}:\\n`;\n output += ` encrypted: ${secret.value.isEncrypted()}\\n`;\n });\n } else {\n output += ' {}\\n';\n }\n\n output += '\\nIdentities (Public Keys):\\n';\n if (allIds.size > 0) {\n allIds.forEach((idGroup: RecipientGroup, name: string) => {\n output += ` - ${name}:\\n`;\n output += ` publicKeys: ${idGroup.publicKeys.join(', ')}\\n`;\n });\n } else {\n output += ' {}\\n';\n }\n console.log(output.trim());\n } else if (this.outputJson()) {\n const jsonData: any = {\n hosts: allHosts.map((h) => h.toObject()),\n secrets: {},\n identities: {},\n };\n allSecrets.forEach((secret: Secret, name: string) => {\n jsonData.secrets[name] = {\n name: secret.name,\n encrypted: secret.value.isEncrypted(),\n // Consider if ids/recipients should be exposed here\n };\n });\n allIds.forEach((idGroup: RecipientGroup, name: string) => {\n jsonData.identities[name] = {\n name: (idGroup as any).name || name, // Assuming NamedRecipientGroup has a name property\n publicKeys: idGroup.publicKeys,\n idRefs: idGroup.idRefs,\n };\n });\n console.log(JSON.stringify(jsonData, null, 2));\n }\n }\n\n // entrypoint for the cli: AGE_IDS=~/.secrets/age/test-david.priv tsx bin/hostctl.ts inventory encrypt\n async encryptInventoryFile() {\n if (!this.configRef) {\n throw new Error('Cannot encrypt inventory: Configuration file reference is not set.');\n }\n const currentConfigRef = this.configRef; // this.configRef is now guaranteed to be a string\n this.warn(`Encrypting inventory file: ${currentConfigRef}`);\n const configFile = new ConfigFile(currentConfigRef);\n await configFile.load();\n await configFile.encryptAll();\n await configFile.save(currentConfigRef);\n }\n\n // entrypoint for the cli: AGE_IDS=~/.secrets/age/david.priv tsx bin/hostctl.ts inventory decrypt\n async decryptInventoryFile() {\n if (!this.configRef) {\n throw new Error('Cannot decrypt inventory: Configuration file reference is not set.');\n }\n const currentConfigRef = this.configRef;\n const configFile = new ConfigFile(currentConfigRef);\n await configFile.load();\n\n let hasEncryptedSecrets = false;\n for (const secret of configFile._secrets.values()) {\n if (secret.value.isEncrypted()) {\n hasEncryptedSecrets = true;\n break;\n }\n }\n\n if (!hasEncryptedSecrets) {\n this.info('No encrypted secrets found to decrypt. Inventory is already decrypted.');\n return;\n }\n\n // Only warn if we are actually proceeding with decryption\n this.warn(`Decrypting inventory file: ${currentConfigRef}`);\n\n try {\n await configFile.decryptAllIfPossible();\n\n // Log successfully used keys. This part might need refinement if loadPrivateKeys doesn't accurately reflect *used* keys.\n const successfullyUsedIdentityPaths = configFile\n .loadPrivateKeys() // This loads all keys specified by AGE_IDS\n .filter((identity) => {\n // A more robust check would be to see if AgeEncryption.decrypt reported success with this key.\n // For now, just checking existence, assuming if it was bad, decryptAllIfPossible would have failed.\n try {\n return fs.existsSync(identity.identityFilePath);\n } catch (e) {\n return false;\n }\n })\n .map((i) => i.identityFilePath)\n .join('\\n');\n\n if (this.verbosity >= Verbosity.INFO && successfullyUsedIdentityPaths.length > 0) {\n this.info(`Decrypted with one or more of the following private keys:\\n${successfullyUsedIdentityPaths}`);\n } else if (\n this.verbosity >= Verbosity.INFO &&\n hasEncryptedSecrets &&\n successfullyUsedIdentityPaths.length === 0\n ) {\n // This case implies decryption was attempted but no specified keys worked or were found,\n // though decryptAllIfPossible should ideally throw if it can't decrypt anything it needs to.\n this.warn('Encrypted secrets found, but no specified AGE identities were successfully used or found.');\n }\n\n await configFile.save(currentConfigRef);\n } catch (error: any) {\n if (error.message?.includes('Unable to read identity file')) {\n // Match the test's expected error message pattern for unreadable/missing keys\n throw new Error('Decryption failed: no identity matched or failed to decrypt due to key issue.');\n }\n // Handle cases where decryption fails for other reasons e.g. no matching identity for a secret\n if (error.message?.includes('No identity matched secret')) {\n // Assuming AgeEncryption.decrypt might throw this\n throw new Error('Decryption failed: no identity matched the encrypted secrets.');\n }\n throw error; // Re-throw other errors\n }\n }\n\n // entrypoint for the cli: AGE_IDS=~/.secrets/age/david.priv tsx bin/hostctl.ts -t ubuntu -- script.ts\n // e.g. AGE_IDS=~/.secrets/age/david.priv tsx bin/hostctl.ts -c david.yaml -t synology blog 4gb web1 -- script.ts\n async runScript(scriptRef: string, params: TaskParams) {\n const selectedHosts = this.selectedInventory();\n this.info(`Selected hosts: ${selectedHosts.length}`);\n\n const absoluteScriptRef = Path.new(scriptRef).absolute();\n this.debug(`absoluteScriptRef=${absoluteScriptRef}`);\n this.debug(`params=${util.inspect(params)}`);\n const mod = await this.loadScriptAsModule(absoluteScriptRef.toString());\n\n this.debug(`mod=${util.inspect(mod)}`);\n\n const packageFileDir = this.pathOfPackageJsonFile(absoluteScriptRef.toString());\n if (!packageFileDir) {\n console.error(\n chalk.red(`Bundle failure. \"${absoluteScriptRef}\" nor any ancestor directory contains a package.json file.`),\n );\n return;\n }\n\n const taskFn: TaskFn = mod.default;\n\n const interactionHandler = new InteractionHandler();\n const localRuntime = new LocalRuntime(this, absoluteScriptRef, interactionHandler);\n\n if (this.outputPlain()) {\n this.info(`run: ${chalk.yellow(absoluteScriptRef.toString())} ${chalk.cyan(util.inspect(params))}`);\n }\n\n let invocation: LocalInvocation<any, any> | undefined;\n let scriptResult: RunFnReturnValue | Error;\n try {\n invocation = await (localRuntime as LocalRuntime).invokeRootTask(taskFn, params, `Running ${scriptRef}`);\n if (!invocation) {\n this.error(`Failed to invoke task for script: ${scriptRef}`);\n scriptResult = new Error(`Failed to invoke task for script: ${scriptRef}`);\n } else {\n scriptResult = await invocation.result;\n this.reportScriptResult(invocation, scriptResult);\n }\n } catch (e) {\n scriptResult = e as Error;\n if (this.outputPlain()) {\n this.error(`Error running script ${scriptRef}: ${scriptResult.message}`);\n if (this.verbosity >= Verbosity.DEBUG && scriptResult.stack) {\n this.error(scriptResult.stack);\n }\n }\n if (invocation) {\n this.reportScriptResult(invocation, scriptResult);\n }\n }\n\n if (scriptResult instanceof Error) {\n process.exit(1);\n }\n }\n\n // entrypoint for the cli: AGE_IDS=~/.secrets/age/david.priv tsx bin/hostctl.ts -t ubuntu -- script.ts\n // e.g. AGE_IDS=~/.secrets/age/david.priv tsx bin/hostctl.ts -c david.yaml -t synology blog 4gb web1 -- script.ts\n async runScriptRemote(scriptRef: string, params: TaskParams) {\n const selectedHosts = this.selectedInventory();\n this.info(`Selected hosts: ${selectedHosts.length}`);\n\n const absoluteScriptRef = Path.new(scriptRef).absolute();\n this.debug(`absoluteScriptRef=${absoluteScriptRef}`);\n this.debug(`params=${util.inspect(params)}`);\n const mod = await this.loadScriptAsModule(absoluteScriptRef.toString());\n\n this.debug(`mod=${util.inspect(mod)}`);\n\n const packageFileDir = this.pathOfPackageJsonFile(absoluteScriptRef.toString());\n if (!packageFileDir) {\n console.error(\n chalk.red(`Bundle failure. \"${absoluteScriptRef}\" nor any ancestor directory contains a package.json file.`),\n );\n return;\n }\n\n const taskFn: TaskFn = mod.default;\n\n const interactionHandler = new InteractionHandler();\n const localRuntime = new LocalRuntime(this, absoluteScriptRef, interactionHandler);\n\n this.info(`run: ${chalk.yellow(absoluteScriptRef.toString())} ${chalk.cyan(util.inspect(params))}`);\n\n let invocation: LocalInvocation<any, any> | undefined;\n let scriptResult: RunFnReturnValue | Error;\n try {\n const runAllRemoteParams = { taskFn, params };\n invocation = await (localRuntime as LocalRuntime).invokeRootTask(\n runAllRemote,\n runAllRemoteParams,\n `Running ${scriptRef} on selected hosts`,\n );\n if (!invocation) {\n this.error(`Failed to invoke task for script: ${scriptRef}`);\n scriptResult = new Error(`Failed to invoke task for script: ${scriptRef}`);\n } else {\n scriptResult = await invocation.result;\n this.reportScriptResult(invocation, scriptResult);\n }\n } catch (e) {\n scriptResult = e as Error;\n if (this.outputPlain()) {\n this.error(`Error running script ${scriptRef}: ${scriptResult.message}`);\n if (this.verbosity >= Verbosity.DEBUG && scriptResult.stack) {\n this.error(scriptResult.stack);\n }\n }\n if (invocation) {\n this.reportScriptResult(invocation, scriptResult);\n }\n }\n\n if (scriptResult instanceof Error) {\n process.exit(1);\n }\n }\n\n async walkInvocationTreePreorder(\n invocation: IInvocation<any>,\n visitFn: (invocation: IInvocation<any>, depth: number) => Promise<void>,\n visited: Set<IInvocation<any>> = new Set(),\n depth = 0,\n ) {\n if (visited.has(invocation)) return;\n\n visited.add(invocation);\n await visitFn(invocation, depth);\n\n for (const childInvocation of invocation.getChildren() as IInvocation<any>[]) {\n await this.walkInvocationTreePreorder(childInvocation, visitFn, visited, depth + 1);\n }\n }\n\n async reportScriptResult(invocation: LocalInvocation<any, any>, scriptResult: RunFnReturnValue | Error) {\n if (this.outputPlain()) {\n this.warn('=== Evaluation ===');\n await this.walkInvocationTreePreorder(invocation, async (invocation, depth) => {\n const indent = ' '.repeat(depth);\n if (invocation.getDescription() || invocation.id) {\n const err = await invocation.resultError();\n if (err) {\n if (this.verbosity >= Verbosity.WARN) {\n this.warn(\n `${indent}${chalk.red(XMARK)} ${invocation.getDescription() || invocation.id} ${chalk.red(util.inspect(err))}`,\n );\n if (this.verbosity >= Verbosity.INFO) {\n this.info(`${indent} ${chalk.red(err.message)}`);\n if (this.verbosity >= Verbosity.DEBUG) {\n invocation.stdout && this.debug(`${indent} ${chalk.bgGreen(invocation.stdout.trimEnd())}`);\n invocation.stderr && this.debug(`${indent} ${chalk.bgRed(invocation.stderr.trimEnd())}`);\n }\n }\n }\n } else {\n if (this.verbosity >= Verbosity.WARN) {\n this.warn(`${indent}${chalk.green(CHECKMARK)} ${invocation.getDescription() || invocation.id}`);\n if (this.verbosity >= Verbosity.INFO) {\n this.info(`${indent} ${chalk.green(util.inspect(await invocation.getResultPromise()))}`);\n if (this.verbosity >= Verbosity.DEBUG) {\n invocation.stdout && this.debug(`${indent} ${chalk.bgGreen(invocation.stdout.trimEnd())}`);\n invocation.stderr && this.debug(`${indent} ${chalk.bgRed(invocation.stderr.trimEnd())}`);\n }\n }\n }\n }\n }\n });\n\n this.warn('=== Result ===');\n if (isError(scriptResult)) {\n this.warn(chalk.red(`${invocation.getDescription() || invocation.id} failed:`));\n this.warn(chalk.red(scriptResult.message));\n if (scriptResult.stack) {\n this.warn(chalk.red(scriptResult.stack));\n }\n } else if (\n scriptResult &&\n typeof scriptResult === 'object' &&\n 'exitCode' in scriptResult &&\n typeof scriptResult.exitCode === 'number'\n ) {\n // This case handles an intentional exit requested by the script returning an object like { exitCode: number, message?: string }\n const exitCode = scriptResult.exitCode;\n const message = (scriptResult as any).message || '';\n this.warn(\n chalk.yellow(\n `${invocation.getDescription() || invocation.id} requested exit with code ${exitCode}: ${message}`,\n ),\n );\n } else if (scriptResult === undefined) {\n this.warn(chalk.green(`${invocation.getDescription() || invocation.id} completed successfully.`));\n } else {\n this.warn(\n chalk.green(\n `${invocation.getDescription() || invocation.id} completed with result: ${util.inspect(scriptResult, { depth: 3 })}`,\n ),\n );\n }\n } else if (this.outputJson()) {\n // When JSON output is requested, print the stringified result directly,\n // bypassing the general verbosity-controlled logging system.\n if (!(scriptResult instanceof Error)) {\n console.log(JSON.stringify(scriptResult, null, 2));\n } else {\n // For errors in JSON mode, output a JSON error object to stdout\n const errorJson = {\n error: scriptResult.message,\n stack: scriptResult.stack,\n };\n console.log(JSON.stringify(errorJson, null, 2));\n }\n }\n }\n\n async loadScriptAsModule(scriptRef: string) {\n const mod = await import(scriptRef);\n return mod;\n }\n\n parseParams(scriptArgs: string[]): Object {\n return ParamMap.parse(scriptArgs).toObject();\n }\n\n // this function creates a bundle of a given directory\n async bundleProject(entrypointPath: string) {\n const nodeRuntime = new NodeRuntime(this.tmpDir);\n\n const entrypointDir = this.pathOfPackageJsonFile(entrypointPath);\n\n if (!entrypointDir) {\n console.error(\n chalk.red(`Bundle failure. \"${entrypointPath}\" nor any ancestor directory contains a package.json file.`),\n );\n return;\n }\n // this.info(`Bundle: ${chalk.yellow(directory)}`);\n\n const tasks = new Listr([], {\n exitOnError: false,\n concurrent: true,\n });\n tasks.add([\n {\n title: `Bundling ${entrypointDir.toString()}`,\n task: async (ctx): Promise<void> => {\n await this.generateBundle(nodeRuntime, entrypointDir);\n // await nodeRuntime.installIfNeeded();\n\n // // run npm install on the specified package directory\n // const result = await nodeRuntime.npmInstall(true, entrypointDir.toString());\n // if (result.failure) throw new Error(result.err);\n\n // // zip the package directory\n // const absoluteDirPath = entrypointDir.toString();\n // const dirNameHash = sha256(absoluteDirPath).slice(0, 10);\n // const bundleZipFile = File.join(this.tmpDir, `bundle${dirNameHash}.zip`);\n // await zipDirectory(entrypointDir.toString(), bundleZipFile);\n },\n },\n ]);\n try {\n await tasks.run();\n } catch (e) {\n console.error(e);\n }\n }\n\n async generateBundle(nodeRuntime: NodeRuntime, packageFileDir: Path): Promise<Path> {\n await nodeRuntime.installIfNeeded();\n\n // run npm install on the specified package directory\n const result = await nodeRuntime.npmInstall(true, packageFileDir.toString());\n if (result.failure) throw new Error(result.err);\n\n // zip the package directory\n const absoluteDirPath = packageFileDir.toString();\n const dirNameHash = sha256(absoluteDirPath).slice(0, 10);\n const bundleZipFile = this.tmpDir.join(`bundle${dirNameHash}.zip`);\n const zipPath = await zipDirectory(packageFileDir.toString(), bundleZipFile.toString());\n\n return Path.new(zipPath);\n }\n\n // walks the directory tree that contains the given path from leaf to root searching for the deepest directory\n // containing a package.json file and returns the absolute path of that directory\n pathOfPackageJsonFile(path: string): Path | null {\n let p = Path.new(path);\n while (true) {\n if (p.dirContains('package.json')) {\n return p.absolute();\n }\n if (p.isRoot()) {\n return null;\n }\n\n p = p.parent();\n }\n }\n\n async printRuntimeReport() {\n const nodeRuntime = new NodeRuntime(this.tmpDir);\n\n const reportObj = {\n nodePath: await nodeRuntime.nodePath(),\n npmPath: await nodeRuntime.npmPath(),\n // summary: report?.getReport(),\n };\n this.info(reportObj);\n }\n\n async promptPassword(message = 'Enter your password') {\n return await promptPassword({ message });\n }\n\n async installRuntime() {\n this.info(`creating node runtime with ${this.tmpDir.toString()}`);\n const nodeRuntime = new NodeRuntime(this.tmpDir);\n await nodeRuntime.installIfNeeded();\n }\n\n async bootstrap() {}\n}\n","import Handlebars from 'handlebars';\n\n// per https://github.com/handlebars-lang/handlebars.js/issues/133#issuecomment-2585143\nHandlebars.registerHelper('join', function (items, block) {\n var delimiter = block.hash.delimiter || ',',\n start = block.hash.start || 0,\n len = items ? items.length : 0,\n end = block.hash.end || len,\n out = '';\n\n if (end > len) end = len;\n\n if ('function' === typeof block) {\n for (let i = start; i < end; i++) {\n if (i > start) out += delimiter;\n if ('string' === typeof items[i]) out += items[i];\n else out += block(items[i]);\n }\n return out;\n } else {\n return [].concat(items).slice(start, end).join(delimiter);\n }\n});\nexport default Handlebars;\n","import * as fs from 'node:fs';\nimport { ConfigFile } from './config-file';\nimport { Host } from './host';\nimport { ConfigUrl } from './config-url';\nimport type { Secret, RecipientGroup } from './config-file';\n\nexport interface ISecret {\n name: string;\n recipients(): string[]; // array of strings representing public keys of the identities that may decrypt the secret\n ciphertext(): Promise<string>;\n plaintext(): Promise<string | undefined>;\n}\n\nexport interface IRecipientGroup {\n recipients(): string[]; // returns an array of public keys associated with all immediate and transitive recipients\n}\n\nexport interface Config {\n hosts(): Host[]; // Renamed from inventory()\n secrets(): Map<string, Secret>; // Changed from property to method\n ids(): Map<string, RecipientGroup>; // Changed from property to method\n getSecret(name: string): ISecret | undefined; // Unchanged\n getRecipientGroups(idRefs: string[]): IRecipientGroup[]; // Unchanged\n}\n\nexport async function load(configRef: string | undefined): Promise<Config> {\n if (configRef && fs.existsSync(configRef)) {\n const configFile = new ConfigFile(configRef);\n await configFile.load();\n return configFile;\n } else if (configRef) {\n return new ConfigUrl(configRef);\n } else {\n throw new Error('No config specified.');\n }\n}\n","import fsa from 'node:fs/promises';\nimport fs from 'node:fs';\nimport { glob, globSync, globStream, globStreamSync, Glob } from 'glob';\nimport { base16, base32, base64, base58, bech32 } from '@scure/base';\nimport * as R from 'rambda';\nimport yaml from 'js-yaml';\n// import * as yaml from \"yaml\";\nimport { Host } from './host';\nimport { AgeEncryption, Identity } from './age-encryption';\nimport { A } from './flex/array';\nimport { File } from './flex/file';\nimport { S } from './flex/set';\nimport { VP } from './flex/pipe';\nimport type { Config, IRecipientGroup, ISecret } from './config';\nimport { Undefined, V } from './flex/type';\nimport { M } from './flex/map';\n\ntype YamlHost = {\n alias?: string;\n user?: string;\n password?: SecretRef | string;\n 'ssh-key'?: SecretRef | string;\n tags?: string[];\n};\n\ntype YamlHostsMapping = { [key: string]: YamlHost };\n\ntype YamlSecret = {\n ids: string | string[];\n value: string;\n};\n\ntype YamlSecretsMapping = { [key: string]: YamlSecret };\n\ntype YamlIdsMapping = { [key: string]: string | string[] };\n\ntype YamlConfigFile = {\n hosts?: YamlHostsMapping;\n secrets?: YamlSecretsMapping;\n ids?: YamlIdsMapping;\n};\n\nexport class SecretRef {\n constructor(public name: string) {}\n\n toYAML() {\n return this;\n }\n}\n\nexport class SecretValue {\n constructor(private value: string) {}\n\n async encrypt(recipients: string[]): Promise<string> {\n if (!this.isEncrypted()) {\n this.value = await AgeEncryption.encrypt(this.value, recipients);\n // console.log(`encrypted: ${this.value}`)\n }\n return this.value;\n }\n\n async decrypt(identities: Identity[]): Promise<string | undefined> {\n if (this.isEncrypted()) {\n const decryptedValue = await AgeEncryption.decrypt(\n this.value,\n identities.map((i) => i.identityFilePath),\n );\n if (!decryptedValue) {\n return undefined;\n }\n this.value = decryptedValue;\n }\n return this.value;\n }\n\n isEncrypted() {\n return this.value.includes('AGE ENCRYPTED FILE');\n }\n\n toYAML() {\n return this.value;\n }\n}\n\nexport class Secret implements ISecret {\n constructor(\n public config: ConfigFile,\n public name: string,\n public ids: RecipientGroup,\n public value: SecretValue,\n ) {}\n\n recipients(): string[] {\n return this.ids.recipients();\n }\n\n async ciphertext(): Promise<string> {\n // console.log(`encrypting ${this.name} with ${this.recipients()}`);\n return await this.value.encrypt(this.recipients());\n }\n\n async plaintext(): Promise<string | undefined> {\n const identities = this.config.loadPrivateKeys();\n return await this.value.decrypt(identities);\n }\n\n async encrypt(): Promise<string> {\n return await this.ciphertext();\n }\n\n async decrypt(): Promise<string | undefined> {\n return await this.plaintext();\n }\n\n toYAML() {\n return {\n ids: this.ids.toYAML(),\n value: this.value.toYAML(),\n };\n }\n}\n\nexport class RecipientGroup implements IRecipientGroup {\n constructor(\n public config: ConfigFile,\n public publicKeys: string[],\n public idRefs: string[],\n ) {}\n\n // returns an array of public keys associated with all immediate and transitive recipients\n recipients(): string[] {\n const accumulatedPublicKeys: Set<string> = A(this.publicKeys).toSet();\n\n // console.log(\"111\")\n this.walkRecipientGroups((rg: RecipientGroup) => {\n // console.log(\"222\")\n // VP(accumulatedPublicKeys).pipe(S.addAll(rg.publicKeys));\n S(accumulatedPublicKeys).addAll(rg.publicKeys);\n });\n\n return S(accumulatedPublicKeys).toArray();\n }\n\n walkRecipientGroups(visitFn: (rg: RecipientGroup) => void, visited: Set<RecipientGroup> = new Set()) {\n if (visited.has(this)) return;\n\n visited.add(this);\n visitFn(this);\n\n this.config.getRecipientGroups(this.idRefs).forEach((rg) => rg.walkRecipientGroups(visitFn, visited));\n }\n\n toYAML() {\n return this.publicKeys.concat(this.idRefs);\n }\n}\n\nexport class NamedRecipientGroup extends RecipientGroup {\n constructor(\n public config: ConfigFile,\n public name: string,\n public publicKeys: string[],\n public idRefs: string[],\n ) {\n super(config, publicKeys, idRefs);\n }\n}\n\nconst SecretRefYamlType = new yaml.Type('!secret', {\n kind: 'scalar', // 'scalar' means string\n\n // Loader must check if the input object is suitable for this type.\n resolve(data): boolean {\n return !!data && typeof data === 'string' && data.trim().length > 0;\n },\n\n // If a node is resolved, use it to create a SecretRef instance.\n construct(yamlObj) {\n return new SecretRef(yamlObj); // yamlObj should be a string\n },\n\n // Dumper must process instances of Point by rules of this YAML type.\n instanceOf: SecretRef,\n\n // Dumper must represent SecretRef objects as string in YAML.\n represent(secretRef) {\n return (secretRef as SecretRef).name;\n },\n});\n\nconst HOSTCTL_CONFIG_SCHEMA = yaml.DEFAULT_SCHEMA.extend([SecretRefYamlType]);\n\nexport class ConfigFile implements Config {\n public _hosts: Map<string, Host>;\n public _ids: Map<string, RecipientGroup>;\n public _secrets: Map<string, Secret>;\n\n constructor(public path: string) {\n this._hosts = new Map();\n this._ids = new Map();\n this._secrets = new Map();\n }\n\n // serialization and deserialization\n\n async load() {\n if (!File.exists(this.path)) {\n throw new Error(`Config file ${this.path} doesn't exist. Unable to load.`);\n }\n\n const yamlFileContents = await fsa.readFile(this.path, {\n encoding: 'utf8',\n });\n\n const yamlDocument: YamlConfigFile = yaml.load(yamlFileContents, {\n schema: HOSTCTL_CONFIG_SCHEMA,\n }) as YamlConfigFile;\n\n this.parse(yamlDocument);\n }\n\n parse(yamlDocument: YamlConfigFile) {\n this._hosts = this.parseHosts(yamlDocument.hosts || {});\n this._ids = this.parseIdsMap(yamlDocument.ids || {});\n this._secrets = this.parseSecrets(yamlDocument.secrets || {});\n }\n\n parseSecretValue(yamlSecretValue: SecretRef | string | undefined): SecretRef | string | undefined {\n switch (V(yamlSecretValue).kind()) {\n case Undefined:\n return yamlSecretValue as undefined;\n case SecretRef:\n return yamlSecretValue as SecretRef;\n case String:\n return yamlSecretValue as string;\n // return new SecretValue(yamlSecretValue as string);\n default:\n throw new Error(`unknown secret type: ${V.inspect(yamlSecretValue)}`);\n }\n }\n\n // yamlHosts is an object\n parseHosts(yamlHosts: YamlHostsMapping): Map<string, Host> {\n const hosts = Object.entries(yamlHosts).reduce((hostMap: Map<string, Host>, [hostUri, hostObj]) => {\n hostObj ||= {};\n const password = this.parseSecretValue(hostObj.password);\n const sshKey = this.parseSecretValue(hostObj['ssh-key']);\n // console.log(\n // `parse host: ${JSON.stringify(hostObj)}; ${hostObj[\"ssh-key\"]}; password ${V(password).inspect()} ; sshkey ${V(sshKey).inspect()}`\n // );\n hostMap.set(\n hostUri,\n new Host(this, {\n ...(hostObj as any), // Use 'as any' to allow spread of hostObj properties\n hostname: hostUri, // The YAML map key is always the hostname\n password,\n sshKey,\n }),\n );\n return hostMap;\n }, new Map());\n return hosts;\n }\n\n parseIdsMap(yamlIds: YamlIdsMapping): Map<string, RecipientGroup> {\n const ids = Object.entries(yamlIds).reduce((secretsMap: Map<string, RecipientGroup>, [name, value]) => {\n value ||= [];\n const rg = this.parseRecipients(value as string[]);\n secretsMap.set(name, new NamedRecipientGroup(this, name, rg.publicKeys, rg.idRefs));\n return secretsMap;\n }, new Map());\n return ids;\n }\n\n parseRecipients(ids: string | string[] | (string | string[])[]): RecipientGroup {\n let idStrings: string[];\n if (V(ids).isA(String)) {\n idStrings = [ids as string];\n } else if (Array.isArray(ids) && ids.every((item: any) => V(item).isA(String))) {\n idStrings = ids as string[]; // ids is string[]\n } else if (Array.isArray(ids)) {\n // Handles (string | string[])[]\n idStrings = (ids as (string | string[])[]).flat(1) as string[];\n } else {\n // ids is not a string and not an array (e.g. undefined, null from YAML parsing)\n // This situation should ideally be handled based on how YAML treats missing/null recipient lists.\n // For now, default to an empty array to prevent further errors, with a warning.\n // console.warn(`[ConfigFile.parseRecipients] 'ids' field has unexpected type: ${typeof ids}. Expected string or array. Defaulting to empty recipient list.`);\n idStrings = [];\n }\n const publicKeysAndIdRefs = idStrings.flatMap((str) => str.split(',')).map((str) => str.trim());\n const [publicKeys, idRefs] = A(publicKeysAndIdRefs).partition(this.isValidPublicKey);\n return new RecipientGroup(this, publicKeys, idRefs);\n }\n\n // returns true if the key is an Age encryption public key (i.e. a bech32 key with a prefix of 'age')\n isValidPublicKey(str: string): boolean {\n try {\n const { prefix, words } = bech32.decode(str as any);\n return prefix === 'age';\n } catch (e) {\n return false;\n }\n }\n\n // yamlSecrets is an object\n parseSecrets(yamlSecrets: YamlSecretsMapping): Map<string, Secret> {\n const secrets = Object.entries(yamlSecrets).reduce((secretsMap: Map<string, Secret>, [name, yamlSecret]) => {\n // yamlSecret ||= {};\n\n const recipients = this.parseRecipients(yamlSecret.ids);\n\n secretsMap.set(name, new Secret(this, name, recipients, new SecretValue(yamlSecret.value)));\n return secretsMap;\n }, new Map());\n return secrets;\n }\n\n async save(destinationPath: string = this.path) {\n const hosts = this.serializeHosts();\n const secrets = this.serializeSecrets();\n const ids = this.serializeIds();\n const yamlFileObj = {\n hosts,\n secrets,\n ids,\n };\n const yamlFileContents = yaml.dump(yamlFileObj, {\n schema: HOSTCTL_CONFIG_SCHEMA,\n noRefs: true,\n });\n await fsa.writeFile(destinationPath, yamlFileContents);\n }\n\n serializeHosts() {\n // return M.toObject(M.map(([name, host]) => [name, host.toYAML()])(this.hosts));\n return VP(this._hosts)\n .map(([name, host]: [string, Host]) => [name, host.toYAML()])\n .m.toObject().value;\n }\n\n serializeSecrets() {\n // return M.toObject(\n // M.map(([name, secret]) => [name, secret.toYAML()])(this.secrets)\n // );\n return VP(this._secrets)\n .map(([name, secret]) => [name, secret.toYAML()])\n .m.toObject().value;\n }\n\n serializeIds() {\n // return M.toObject(M.map(([name, id]) => [name, id.toYAML()])(this.ids));\n return VP(this._ids)\n .map(([name, id]) => [name, id.toYAML()])\n .m.toObject().value;\n }\n\n // domain logic\n\n // loads private keys from the AGE_IDS environment variable\n loadPrivateKeys(): Identity[] {\n const ageIds = process.env.AGE_IDS;\n // console.log(`AGE_IDS=${ageIds}`);\n if (ageIds) {\n const paths = globSync(ageIds);\n // console.log(`Loading private keys from ${ageIds}: ${paths}`);\n const ids = paths.map((path) => new Identity({ path }));\n // console.log(`Loaded ${V(ids).inspect()}`);\n return ids;\n }\n return [];\n }\n\n getSecret(name: string): Secret | undefined {\n return this._secrets.get(name);\n }\n\n getRecipientGroups(idRefs: string[]): RecipientGroup[] {\n // return pipe(idRefs, A.map(this.ids.get), A.compact());\n return VP(idRefs)\n .map((idRef: string) => this._ids.get(idRef))\n .compact().value;\n }\n\n async decryptAllIfPossible(): Promise<void> {\n await VP(this._secrets)\n .m.values()\n .map((secret: Secret) => secret.decrypt())\n .waitAll().value;\n }\n\n async encryptAll(): Promise<void> {\n await VP(this._secrets)\n .m.values()\n .map((secret: Secret) => secret.encrypt())\n .waitAll().value;\n }\n\n // Config interface\n\n hosts(): Host[] {\n return M(this._hosts).values();\n }\n\n secrets(): Map<string, Secret> {\n return this._secrets;\n }\n\n ids(): Map<string, RecipientGroup> {\n return this._ids;\n }\n}\n","export const GeneratorFunction = function* () {}.constructor;\n\nexport interface BaseWrapperProxy {\n <T>(wrappedValue: T): any; // Generic call signature for the proxy itself\n registerUncurriedFns: (fns: FunctionBag) => void;\n registerCurriedFns: (fns: FunctionBag) => void;\n registerStatic: (fns: FunctionBag) => void;\n}\n\ninterface InternalFunctionWithRegMethods extends Function {\n registerUncurriedFns: (fns: FunctionBag) => void;\n registerCurriedFns: (fns: FunctionBag) => void;\n registerStatic: (fns: FunctionBag) => void;\n}\n\n// export function buildPipeThroughFunction() {\n// function func(wrappedValue) {\n// // wrappedValue is the value passed to the object wrapper function. e.g. A([1,2,3]) the wrappedValue is [1,2,3] and A is the wrapper function called func in this context\n// return new Proxy(wrappedValue, {\n// get(target, property, receiver) {\n// // function objects, like O, don't have any properties, so the only properties present will be the function objects we assign to the 'O' function object\n// const fn = Reflect.get(func, property, receiver);\n// if (fn === undefined) {\n// return Reflect.get(target, property, receiver); // target === wrappedValue\n// }\n// const fnParams = parameters(fn);\n// const noParameters = fnParams.length === 0;\n// return function (...args: any) {\n// if (noParameters || args.length === 0) {\n// // then we are going to treat fn as a function expecting the obj to be supplied as an argument\n// return fn.call(receiver, target);\n// } else {\n// // otherwise, we are going to treat fn as a function expecting the args to be supplied as the argument, which will return a second function that expects the obj to be supplied as its argument\n// return fn.apply(receiver, args)(target);\n// }\n// };\n// },\n// });\n// }\n// return func;\n// }\n\nexport type FunctionBag = { [key: string]: Function };\nexport class MethodBag {\n public methods: Map<string, [Function, number]>;\n public staticMethods: Map<string, Function>;\n constructor() {\n this.methods = new Map();\n this.staticMethods = new Map();\n }\n registerUncurriedFns(fnBag: FunctionBag) {\n Object.entries(fnBag).forEach(([functionName, functionObj]) => {\n this.methods.set(functionName, [functionObj, 1]);\n });\n }\n registerCurriedFns(fnBag: FunctionBag) {\n Object.entries(fnBag).forEach(([functionName, functionObj]) => {\n this.methods.set(functionName, [functionObj, 2]);\n });\n }\n registerStatic(fnBag: FunctionBag) {\n Object.entries(fnBag).forEach(([functionName, functionObj]) => {\n this.staticMethods.set(functionName, functionObj);\n });\n }\n lookup(fnName: string): [Function, number] | undefined {\n const pair = this.methods.get(fnName);\n if (!pair) {\n return undefined;\n }\n return pair;\n }\n lookupStatic(fnName: string): Function | undefined {\n const fn = this.staticMethods.get(fnName);\n if (!fn) {\n return undefined;\n }\n return fn;\n }\n}\n\nexport function buildWrapperProxy(): BaseWrapperProxy {\n const methods = new MethodBag();\n function func(wrappedValue: any): any {\n // wrappedValue is the value passed to the object wrapper function. e.g. A([1,2,3]) the wrappedValue is [1,2,3] and A is the wrapper function called func in this context\n return new Proxy(wrappedValue, {\n get(target: any, property: string | symbol, receiver: any) {\n // function objects, like O, don't have any properties, so the only properties present will be the function objects we assign to the 'O' function object\n const fnArityPair = methods.lookup(property.toString());\n if (fnArityPair === undefined) {\n return Reflect.get(target, property, receiver); // target === wrappedValue\n }\n const [fn, arity] = fnArityPair;\n return function (...args: any) {\n if (arity === 1) {\n // then we are going to treat fn as a function expecting the obj to be supplied as an argument\n return fn.call(receiver, target);\n } else {\n // otherwise, we are going to treat fn as a function expecting the args to be supplied as the argument, which will return a second function that expects the obj to be supplied as its argument\n return fn.apply(receiver, args)(target);\n }\n };\n },\n });\n }\n Object.assign(func, {\n registerUncurriedFns: (fnBag: FunctionBag): void => {\n methods.registerUncurriedFns(fnBag);\n },\n registerCurriedFns: (fnBag: FunctionBag): void => {\n methods.registerCurriedFns(fnBag);\n },\n registerStatic: (fnBag: FunctionBag): void => {\n methods.registerStatic(fnBag);\n },\n });\n const funcWithMethods = func as unknown as InternalFunctionWithRegMethods;\n return new Proxy(funcWithMethods, {\n get(target: any, property: string | symbol, receiver: any) {\n const fn = methods.lookupStatic(property.toString());\n if (fn === undefined) {\n return Reflect.get(target, property, receiver); // target === func\n }\n return fn;\n },\n }) as BaseWrapperProxy;\n}\n\n// taken from https://javascript.info/currying-partials\nexport function curry(func: (...args: any[]) => any) {\n return function curried(this: any, ...args: any[]): any {\n if (args.length >= func.length) {\n return func.apply(this, args);\n } else {\n return function (this: any, ...args2: any[]): any {\n return curried.apply(this, args.concat(args2));\n };\n }\n };\n}\n\nexport function identity(val: any): any {\n return val;\n}\n\n// taken from https://stackoverflow.com/questions/1007981/how-to-get-function-parameter-names-values-dynamically\nexport function parameters(func: any): string[] {\n const ARROW = true;\n const FUNC_ARGS = ARROW ? /^(function)?\\s*[^\\(]*\\(\\s*([^\\)]*)\\)/m : /^(function)\\s*[^\\(]*\\(\\s*([^\\)]*)\\)/m;\n const FUNC_ARG_SPLIT = /,/;\n const FUNC_ARG = /^\\s*(_?)(.+?)\\1\\s*$/;\n const STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/gm;\n\n return ((func || '').toString().replace(STRIP_COMMENTS, '').match(FUNC_ARGS) || ['', '', ''])[2]\n .split(FUNC_ARG_SPLIT)\n .map(function (arg: string) {\n return arg.replace(FUNC_ARG, function (all: string, underscore: string, name: string) {\n return name.split('=')[0].trim();\n });\n })\n .filter(String);\n}\n\nexport function thread(...args: ((arg: any) => any)[]) {\n return function (firstArg: any | undefined = undefined) {\n let pipeline = args;\n if (firstArg !== undefined) {\n pipeline.unshift(firstArg);\n }\n return pipeline.reduce((arg: any, fn: (arg: any) => any) => fn(arg));\n };\n}\n\nexport function threadR(...fns: ((arg: any) => any)[]) {\n return function (firstArg: any = undefined) {\n let pipeline = fns;\n if (firstArg !== undefined) {\n pipeline.push(firstArg);\n }\n return pipeline.reduceRight((arg: any, fn: (arg: any) => any) => fn(arg));\n };\n}\n\nexport interface FunctionUtilWrapperProxy extends BaseWrapperProxy {\n curry: (func: (...args: any[]) => any) => (...args: any[]) => any;\n identity: (val: any) => any;\n parameters: (func: any) => string[];\n thread: (...args: any[]) => (firstArg?: any) => any;\n threadR: (...fns: any[]) => (firstArg?: any) => any;\n}\n\n// export const F = {\n// curry,\n// identity,\n// thread,\n// };\n\nexport const F = buildWrapperProxy() as FunctionUtilWrapperProxy;\nF.registerUncurriedFns({ parameters });\n// F.registerCurriedFns({ });\nF.registerStatic({\n curry,\n identity,\n parameters,\n thread,\n threadR,\n});\n","import { Mutex } from 'async-mutex';\n\nimport { V, kind } from './type';\n\nexport type AnyConstructor = new (...args: any[]) => any;\n\n// This represents a set of implementations of the same protocol for the same type.\n// The implementations are named for disambuation purposes.\nclass NamedImplementations<StoredItemType> {\n constructor(\n public impls: Map<string, StoredItemType> = new Map(),\n public defaultImpl: string = '',\n ) {}\n\n register<SpecificItemType extends StoredItemType>(\n name: string,\n implClass: SpecificItemType,\n makeDefault: boolean = false,\n ) {\n if (this.impls.size === 0 || makeDefault) {\n this.setDefaultImpl(name);\n }\n this.impls.set(name, implClass);\n }\n\n get(name?: string): StoredItemType | undefined {\n return this.impls.get(name || this.defaultImpl);\n }\n\n setDefaultImpl(name: string) {\n this.defaultImpl = name;\n }\n}\n\n// This class captures all the named implementations of a particular typeclass/protocol associated with a given type.\n// There will be one of these ImplementationRegistry objects for every typeclass/protocol.\n// This class is responsible for associating types with their corresponding implementations of the typeclass/protocol that this\n// instance represents.\n// For example:\n// const mappableImplementations = new ImplementationRegistry(\"Mappable\");\n// In this example, mappableImplementations would represent all of the named implementations of the Mappable typeclass/protocol\n// for any type. The implementations private member would store all of the per-type named implementations of the Mappable typeclass/protocol\n// as (type => named implementations) pairs.\nclass ImplementationRegistry {\n // implementations is a Map of (type constructor function => ProtocolImplGroup) pairs\n // It stores all the named implementations of the typeclass/protocol associated with the type stored in the key of the map\n private implementations: Map<AnyConstructor, NamedImplementations<AnyConstructor>> = new Map();\n\n constructor(public name: string) {}\n\n register(classConstructor: AnyConstructor, implClass: AnyConstructor, makeDefault: boolean = false) {\n let protocolImplGroup = this.implementations.get(classConstructor);\n if (!protocolImplGroup) {\n protocolImplGroup = new NamedImplementations<AnyConstructor>();\n this.implementations.set(classConstructor, protocolImplGroup);\n }\n\n protocolImplGroup.register(implClass.name, implClass, makeDefault);\n }\n\n use(classConstructor: AnyConstructor, implClass: AnyConstructor) {\n this.register(classConstructor, implClass, true);\n }\n\n public clear() {\n this.implementations.clear();\n }\n\n // returns a class object that implements the typeclass/protocol - this is an implementation of the typeclass/protocol for a given type\n get(classConstructor: AnyConstructor, name?: string) {\n const protocolImplGroup = this.implementations.get(classConstructor);\n if (!protocolImplGroup) {\n throw new Error(`Protocol ${this.name} not implemented by ${classConstructor}`);\n }\n const impl = protocolImplGroup.get(name);\n if (!impl) {\n throw new Error(\n `Named implementation '${\n name || protocolImplGroup.defaultImpl\n }' of protocol ${this.name} not implemented by ${classConstructor}`,\n );\n }\n return impl;\n }\n}\n\n// declare global {\n// var protocolRegistry: Map<string, ImplementationRegistry>;\n// var protocolRegistryLock: Mutex;\n// }\n// global.protocolRegistryLock = global.protocolRegistryLock || new Mutex();\n// await global.protocolRegistryLock.runExclusive(async () => {\n// global.protocolRegistry = global.protocolRegistry || new Map();\n// });\n\n// Every implementation of the protocol must conform to the same interface.\n// The interface defines which methods a user of the protocol implementation may invoke.\nexport class Protocol {\n static protocolRegistryLock: Mutex;\n static registry: Map<string, ImplementationRegistry>;\n\n static {\n Protocol.protocolRegistryLock = Protocol.protocolRegistryLock || new Mutex();\n Protocol.registry = Protocol.registry || new Map();\n }\n\n static getTypeclass(): ImplementationRegistry {\n if (this.registry.has(this.name)) {\n return this.registry.get(this.name) as ImplementationRegistry;\n } else {\n const newTypeclass = new ImplementationRegistry(this.name);\n this.registry.set(this.name, newTypeclass);\n return newTypeclass;\n }\n }\n\n // static getTypeclass(): ImplementationRegistry {\n // if (global.protocolRegistry.has(this.name)) {\n // return global.protocolRegistry.get(this.name) as ImplementationRegistry;\n // } else {\n // const newTypeclass = new ImplementationRegistry(this.name);\n // global.protocolRegistry.set(this.name, newTypeclass);\n // return newTypeclass;\n // }\n // }\n\n static async register(classConstructor: AnyConstructor, implClass: AnyConstructor, makeDefault: boolean = false) {\n await Protocol.protocolRegistryLock.runExclusive(async () => {\n let typeclass = this.getTypeclass();\n typeclass.register(classConstructor, implClass, makeDefault);\n });\n }\n\n static async use(classConstructor: AnyConstructor, implClass: AnyConstructor) {\n await Protocol.protocolRegistryLock.runExclusive(async () => {\n let typeclass = this.getTypeclass();\n typeclass.use(classConstructor, implClass);\n });\n }\n\n // returns a class object that implements the typeclass - this is an implementation of the typeclass for a given type\n static get(classConstructor: AnyConstructor, name?: string) {\n const typeclass = this.getTypeclass();\n // console.log(`looking up typeclass ${typeclass.name} implementation for ${classConstructor.name} named ${name}`)\n return typeclass.get(classConstructor, name);\n }\n\n // returns an instance of the class that implements the typeclass\n // For example, Enumerable.for([1,2,3]) returns a new instance of the EnumerableArray implementation of the\n // Enumerable typeclass on the Array type, initialized with [1,2,3] in the constructor\n static for<S extends Protocol>(\n instance: any,\n // Allow passing the implementation class constructor directly.\n // The 'implClass' parameter from the original signature was used for named lookup,\n // which is handled by this.get() when explicitImplClass is not provided.\n explicitImplClass?: new (self: any) => S,\n ) {\n let finalImplConstructor: new (self: any) => S;\n\n if (explicitImplClass) {\n finalImplConstructor = explicitImplClass;\n } else {\n // Lookup in registry if no explicit class is provided.\n // this.get will retrieve the default implementation for kind(instance).\n finalImplConstructor = this.get(\n kind(instance),\n // No name needed here for the default lookup via this.get(typeConstructor)\n ) as new (self: any) => S;\n }\n return new finalImplConstructor(instance);\n }\n}\n\n// // TC is the class that represents the typeclass, e.g. Mappable\n// class NamedImplementations<TC extends Protocol> {\n// constructor(\n// // new () => TypeclassClass means the constructor function for the TypeclassClass\n// public impls: Map<string, ImplCtor<any, TC>> = new Map(), // this map stores named references to implementations of typeclass classes, e.g. 'MappableArray' -> MappableArray class that extends Mappable, etc.\n// public defaultImpl: string = \"\"\n// ) {}\n\n// register<Impl extends TC>(\n// name: string,\n// implClass: ImplCtor<TC, Impl>,\n// makeDefault: boolean = false\n// ) {\n// if (this.impls.size === 0 || makeDefault) {\n// this.setDefaultImpl(name);\n// }\n// this.impls.set(name, implClass);\n// }\n\n// get<Impl extends TC>(name?: string): Impl | undefined {\n// return this.impls.get(name || this.defaultImpl) as Impl | undefined;\n// }\n\n// setDefaultImpl(name: string) {\n// this.defaultImpl = name;\n// }\n// }\n\n// type EmptyConstructorFor<T> = {\n// new (): T;\n// }\n\n// type ImplCtor<TC extends Protocol, ImplClass extends TC> = EmptyConstructorFor<ImplClass>\n\n// type TCCtor<TC extends Protocol> = EmptyConstructorFor<TC>;\n\n// type TypeThatImplementsATypeclass = Function;\n\n// // Every implementation of the protocol must conform to the same interface.\n// // The interface defines which methods a user of the protocol implementation may invoke.\n// export abstract class Protocol {\n// // // Protocl has two parts, static and instance.\n// // // the static bits have to do with the registry at the class level, e.g. Mappable is a static registry for Mappable implementations\n// // // the instance bits are the implementation of the Mappable\n\n// // // this field is shared among all subclasses of Protocol\n// // private static registry: Map<string, Protocol> = new Map(); // this is a map of (typeclass name -> typeclass instance) pairs.\n\n// // static getTypeclass<TC extends Protocol>(): TC {\n// // if (this.registry.has(this.name)) {\n// // // in this context, this will not be `Protocol`, it will be a subclass of `Protocol`, like `Mappable`.\n// // return this.registry.get(this.name) as unknown as TC;\n// // } else {\n// // const newTypeclass = new (this as unknown as TCCtor<TC>)(); // in this context, this will not be `Protocol`, it will be a subclass of `Protocol`, like `Mappable`.\n// // this.registry.set(this.name, newTypeclass);\n// // return newTypeclass;\n// // }\n// // }\n\n// // static register(\n// // classConstructor: TypeThatImplementsATypeclass,\n// // implClass,\n// // makeDefault: boolean = false\n// // ) {\n// // let typeclass = this.getTypeclass<TC>();\n// // typeclass.register(classConstructor, implClass, makeDefault);\n// // }\n\n// // static use(classConstructor: TypeThatImplementsATypeclass, implClass) {\n// // let typeclass = this.getTypeclass();\n// // typeclass.use(classConstructor, implClass);\n// // }\n\n// // // returns a class object that implements the typeclass - this is an implementation of the typeclass for a given type\n// // static get<TC extends Protocol, ImplClass extends TC>(\n// // classConstructor: TypeThatImplementsATypeclass,\n// // name?: string\n// // ): ImplCtor<TC, ImplClass> {\n// // const typeclass = this.getTypeclass();\n// // // console.log(`looking up typeclass ${typeclass.name} implementation for ${classConstructor.name} named ${name}`)\n// // return typeclass.get(classConstructor, name);\n// // }\n\n// // returns an instance of the class that implements the typeclass\n// // For example, Enumerable.for([1,2,3]) returns a new instance of the EnumerableArray implementation of the\n// // Enumerable typeclass on the Array type, initialized with [1,2,3] in the constructor\n// static for<TC extends Protocol, ImplClass extends TC>(\n// instance,\n// implClassConstructor = undefined\n// ): ImplClass {\n// const implConstructor = ProtocolRegistry.get(this, kind(instance), implClassConstructor?.name);\n// return new implConstructor(instance);\n// }\n\n// // implementations is a Map of (type => NamedImplementations<typeclass class>) pairs\n// // e.g. 'String' -> NamedImplementations<Mappable>\n// // It stores all the named implementations of the typeclass/protocol associated with the type stored in the key of the map\n// private implementations: Map<\n// TypeThatImplementsATypeclass,\n// NamedImplementations<typeof this>\n// > = new Map();\n\n// // constructor(public name: string) {} // we don't need the name anymore because the this.constructor.name is the name of the typeclass, e.g. class Mappable extends Protocol; new Mappable().name is the name \"Mappable\"\n\n// register<ImplClass extends typeof this>(\n// classConstructor: TypeThatImplementsATypeclass,\n// implClassConstructor: EmptyConstructorFor<ImplClass>,\n// makeDefault: boolean = false\n// ) {\n// let protocolImplGroup = this.implementations.get(classConstructor);\n// if (!protocolImplGroup) {\n// protocolImplGroup = new NamedImplementations<typeof this>();\n// this.implementations.set(classConstructor, protocolImplGroup);\n// }\n\n// protocolImplGroup.register(\n// implClassConstructor.name,\n// implClassConstructor,\n// makeDefault\n// );\n// }\n\n// use<ImplClass extends typeof this>(\n// classConstructor: TypeThatImplementsATypeclass,\n// implClassConstructor: EmptyConstructorFor<ImplClass>,\n// ) {\n// this.register(classConstructor, implClassConstructor, true);\n// }\n\n// // returns a class object that implements the typeclass/protocol - this is an implementation of the typeclass/protocol for a given type\n// get(\n// classConstructor: TypeThatImplementsATypeclass,\n// name?: string\n// ): typeof this {\n// const protocolImplGroup = this.implementations.get(classConstructor);\n// if (!protocolImplGroup) {\n// throw `Protocol ${this.constructor.name} not implemented by ${classConstructor}`;\n// }\n// const impl = protocolImplGroup.get(name);\n// if (!impl) {\n// throw `Named implementation '${\n// name || protocolImplGroup.defaultImpl\n// }' of protocol ${\n// this.constructor.name\n// } not implemented by ${classConstructor}`;\n// }\n// return impl;\n// }\n// }\n\n// // Every implementation of the protocol must conform to the same interface.\n// // The interface defines which methods a user of the protocol implementation may invoke.\n// export abstract class ProtocolRegistry {\n// private static registry: Map<string, Protocol> = new Map(); // this is a map of (typeclass name -> typeclass instance) pairs.\n\n// static getTypeclassForImpl<TC extends Protocol>(implClassCtor): TC {\n// const typeclassCtor = V(implClassCtor).superclass();\n// return this.getTypeclass(typeclassCtor.name);\n// }\n\n// static getTypeclass<TC extends Protocol>(typeclassName): TC {\n// if (this.registry.has(typeclassName)) {\n// return this.registry.get(typeclassName) as unknown as TC;\n// } else {\n// const newTypeclass = new (this as unknown as TCCtor<TC>)(); // in this context, this will not be `Protocol`, it will be a subclass of `Protocol`, like `Mappable`.\n// this.registry.set(typeclassName, newTypeclass);\n// return newTypeclass;\n// }\n// }\n\n// static register(\n// classConstructor: TypeThatImplementsATypeclass,\n// implClassCtor,\n// makeDefault: boolean = false\n// ) {\n// let typeclass = this.getTypeclassForImpl<typeof implClassCtor>(implClassCtor);\n// typeclass.register(classConstructor, implClassCtor, makeDefault);\n// }\n\n// static use(classConstructor: TypeThatImplementsATypeclass, implClassCtor) {\n// let typeclass = this.getTypeclassForImpl<typeof implClassCtor>(implClassCtor);\n// typeclass.use(classConstructor, implClassCtor);\n// }\n\n// // returns a class object that implements the typeclass - this is an implementation of the typeclass for a given type\n// static get<TC extends Protocol, ImplClass extends TC>(\n// typeclassCtor,\n// classConstructor: TypeThatImplementsATypeclass,\n// name?: string\n// ) {\n// // console.log(`looking up typeclass ${typeclass.name} implementation for ${classConstructor.name} named ${name}`)\n// const typeclass = this.registry.get(typeclassCtor.name) as Protocol;\n// return typeclass.get(classConstructor, name);\n// }\n// }\n","import { inspect as nodeInspect } from 'node:util';\nimport { MethodBag, type FunctionBag } from './function';\n\nexport class End {\n private static _instance: End;\n\n private constructor() {}\n\n public static get instance(): End {\n if (!this._instance) {\n this._instance = new End();\n }\n return this._instance;\n }\n}\nexport class Undefined {}\nexport class Null {}\nexport class Class {}\n\nexport function inspect(valueToInspect: any) {\n return nodeInspect(valueToInspect, { showProxy: true });\n}\n\nexport function isA(predicateType: any) {\n return function (value: any): boolean {\n return (\n value instanceof predicateType ||\n kind(value) === predicateType ||\n (value != null &&\n (value.constructor === predicateType || (predicateType.name === 'Object' && typeof value === 'object')))\n );\n };\n}\n\nexport function isAbsent(value: any): boolean {\n return value === null || value === undefined;\n}\n\nexport function isDefined(value: any): boolean {\n return value !== undefined;\n}\n\nconst BUILT_IN_CONSTRUCTORS = [\n String,\n Number,\n Boolean,\n Array,\n Object,\n Function,\n Date,\n RegExp,\n Map,\n Set,\n Error,\n Promise,\n Symbol,\n BigInt,\n];\n\nexport function isClass(fn: any): boolean {\n if (typeof fn !== 'function') {\n return false;\n }\n // Check for class keyword syntax for user-defined classes\n if (/^class\\s/.test(Function.prototype.toString.call(fn))) {\n return true;\n }\n // Check if it's one of the built-in constructors that should be treated as a class\n if (BUILT_IN_CONSTRUCTORS.includes(fn)) {\n return true;\n }\n return false;\n}\n\n// true for arrays, functions, objects\nexport function isObject(val: any): boolean {\n return val !== null && (typeof val === 'function' || typeof val === 'object');\n}\n\nexport function isPresent(value: any): boolean {\n return !isAbsent(value);\n}\n\n// returns Null | Undefined | Boolean | Number | BigInt | String | Symbol | Function | Class | class object\n// the returned type should always have a name property\n// kind(new Set()).name -> 'Set'\n// kind(new Set()).name -> 'Set'\nexport function kind(value: any) {\n if (value === null) {\n return Null;\n }\n switch (typeof value) {\n case 'undefined':\n return Undefined;\n case 'boolean':\n return Boolean;\n case 'number':\n return Number;\n case 'bigint':\n return BigInt;\n case 'string':\n return String;\n case 'symbol':\n return Symbol;\n case 'function': // matches class constructors (class objects) and functions\n if (isClass(value)) {\n return Class;\n } else {\n return value.constructor;\n }\n break;\n case 'object': // matches instances of classes (e.g. arrays, ) and objects\n return value.constructor;\n break;\n }\n}\n\nexport function klass(objOrClass: any) {\n if (isClass(objOrClass)) {\n // Use the updated isClass\n return Function; // The 'class' of a class is Function, as per tests\n }\n // It's an instance or a non-class function/object\n const proto = Object.getPrototypeOf(objOrClass);\n if (proto === null || proto === undefined) {\n return undefined; // Or handle as appropriate if tests cover this\n }\n return proto.constructor;\n}\n\nexport function superclass(objOrClass: any) {\n if (objOrClass === Object) {\n return null; // Object has no superclass, as per tests\n }\n\n if (isClass(objOrClass)) {\n // Use the updated isClass\n const proto = Object.getPrototypeOf(objOrClass);\n // For built-ins like String, or base user classes like 'class A {}',\n // their prototype is Function.prototype. Their superclass is Object.\n if (proto === Function.prototype) {\n return Object;\n }\n // For derived classes like 'class C extends B {}', proto is B.\n return proto;\n } else {\n // It's an instance\n const instanceProto = Object.getPrototypeOf(objOrClass);\n if (instanceProto === null || instanceProto === undefined) {\n return undefined;\n }\n const superProto = Object.getPrototypeOf(instanceProto);\n if (superProto === null || superProto === undefined) {\n // This instance's class directly inherits from Object (or has no explicit superclass)\n // or it's an object created with Object.create(null)\n return superProto === null ? null : undefined; // if superProto is null, its constructor is undefined. if it's Object.prototype, constructor is Object\n }\n // If superProto is Object.prototype, then superProto.constructor is Object.\n // If instanceProto is, e.g. an Array instance, instanceProto is Array.prototype.\n // superProto is Object.prototype. superProto.constructor is Object.\n return superProto.constructor;\n }\n}\n\n// export const T = buildPipeThroughFunction();\n// Object.assign(T, {\n// kind,\n// });\n\nclass Value<T> {\n public isWrappedValue = true;\n constructor(public value: T) {}\n\n // isA(predicateType: any): boolean {\n // return isA(predicateType)(this.value);\n // }\n\n // isAbsent(value: any) {\n // return isAbsent(value);\n // }\n\n // isClass(value: unknown) {\n // isClass(value);\n // }\n\n // isPresent(value: any) {\n // return isPresent(value);\n // }\n\n // isError(value: unknown): value is Error {\n // return isError(value);\n // }\n\n // inspect() {\n // return inspect(this.value);\n // }\n\n // kind() {\n // return kind(this.value);\n // }\n\n // klass() {\n // return klass(this.value);\n // }\n\n // superclass() {\n // return superclass(this.value);\n // }\n}\n\n// export const V = function <T>(value: T): Value<T> {\n// return new Value(value);\n// };\n\n// Object.assign(V, {\n// isA,\n// isAbsent,\n// isClass,\n// isPresent,\n// inspect,\n// kind,\n// klass,\n// superclass,\n// });\n\ninterface FunctionWithRegistrationMethods {\n (wrappedValue: any): any; // Original signature of func\n registerUncurriedFns: (fns: FunctionBag) => void;\n registerCurriedFns: (fns: FunctionBag) => void;\n registerStatic: (fns: FunctionBag) => void;\n}\n\nexport interface ValueWrapperProxy extends FunctionWithRegistrationMethods {\n <T>(wrappedValue: T): any; // Represents the function signature of V itself\n registerUncurriedFns: (fns: FunctionBag) => void;\n registerCurriedFns: (fns: FunctionBag) => void;\n registerStatic: (fns: FunctionBag) => void;\n // Add other static methods if V is supposed to have them directly, e.g., isA, inspect, etc.\n // For now, focusing on the registration methods as per the errors.\n // Static methods registered via V.registerStatic\n isA: (predicateType: any) => (value: any) => boolean;\n isAbsent: (value: any) => boolean;\n isClass: (fn: any) => boolean;\n isDefined: (value: any) => boolean;\n isObject: (val: any) => boolean;\n isPresent: (value: any) => boolean;\n inspect: (valueToInspect: any) => string;\n kind: (value: any) => any; // Adjust 'any' to the actual return type of kind if more specific\n klass: (objOrClass: any) => any; // Adjust 'any' if more specific\n superclass: (objOrClass: any) => any; // Adjust 'any' if more specific\n}\n\nexport function buildValueWrapperProxy(): ValueWrapperProxy {\n const methods = new MethodBag();\n function func(wrappedValue: any): any {\n // wrappedValue is the value passed to the object wrapper function. e.g. A([1,2,3]) the wrappedValue is [1,2,3] and A is the wrapper function called func in this context\n if (!isObject(wrappedValue)) {\n wrappedValue = new Value(wrappedValue);\n }\n return new Proxy(wrappedValue, {\n get(target, property, receiver) {\n // function objects, like O, don't have any properties, so the only properties present will be the function objects we assign to the 'O' function object\n const fnArityPair = methods.lookup(property.toString());\n if (fnArityPair === undefined) {\n if (target.isWrappedValue) {\n return Reflect.get(target.value, property, receiver); // target === Value(wrappedValue)\n } else {\n return Reflect.get(target, property, receiver); // target === wrappedValue\n }\n }\n const [fn, arity] = fnArityPair;\n return function (...args: any) {\n if (arity === 1) {\n // then we are going to treat fn as a function expecting the obj to be supplied as an argument\n if (target.isWrappedValue) {\n // console.log(`111. ${fn}.call(${inspect(receiver)}, ${inspect(target.value)})`);\n\n // target === Value(wrappedValue)\n return fn.call(receiver, target.value);\n } else {\n // console.log(`222. ${fn}.call(${inspect(receiver)}, ${inspect(target)})`);\n return fn.call(receiver, target);\n }\n } else {\n // otherwise, we are going to treat fn as a function expecting the args to be supplied as the argument, which will return a second function that expects the obj to be supplied as its argument\n if (target.isWrappedValue) {\n // console.log(`333. ${fn}.apply(${inspect(receiver)}, ${inspect(args)})(${inspect(target.value)})`);\n return fn.apply(receiver, args)(target.value);\n } else {\n // console.log(`444. ${fn}.apply(${inspect(receiver)}, ${inspect(args)})(${inspect(target)})`);\n return fn.apply(receiver, args)(target);\n }\n }\n };\n },\n });\n }\n Object.assign(func, {\n registerUncurriedFns(fnBag: FunctionBag) {\n return methods.registerUncurriedFns(fnBag);\n },\n registerCurriedFns(fnBag: FunctionBag) {\n return methods.registerCurriedFns(fnBag);\n },\n registerStatic(fnBag: FunctionBag) {\n return methods.registerStatic(fnBag);\n },\n });\n const funcWithMethods = func as FunctionWithRegistrationMethods;\n return new Proxy(funcWithMethods, {\n get(target: any, property: string | symbol, receiver: any) {\n const fn = methods.lookupStatic(property.toString());\n if (fn === undefined) {\n // If the property is not a registered static method,\n // delegate to the target (funcWithMethods), which has registerUncurriedFns etc.\n return Reflect.get(target, property, receiver);\n }\n return fn;\n },\n }) as ValueWrapperProxy;\n}\n\nexport const V = buildValueWrapperProxy() as ValueWrapperProxy;\nV.registerUncurriedFns({\n isAbsent,\n isClass,\n isDefined,\n isObject,\n isPresent,\n inspect,\n kind,\n klass,\n superclass,\n});\nV.registerCurriedFns({ isA });\nV.registerStatic({\n isA,\n isAbsent,\n isClass,\n isDefined,\n isObject,\n isPresent,\n inspect,\n kind,\n klass,\n superclass,\n});\n","import { Protocol } from './protocol';\n\nexport class Compactable<S> extends Protocol {\n constructor(public self: S) {\n super();\n }\n\n compact(omit?: any[]): any {\n throw new Error('not implemented');\n }\n}\n\nexport function compact(omit?: any[]) {\n return function <V>(compactableVal: V | V[]): V | V[] | undefined {\n return Compactable.for<Compactable<V | V[]>>(compactableVal).compact(omit);\n };\n}\n","import { identity } from './function';\nimport { End } from './type';\n\nexport class Enumerator<T> implements IterableIterator<T> {\n static for<U>(iterator: Iterator<U>): Enumerator<U> {\n return new Enumerator(iterator);\n }\n\n constructor(private iterator: Iterator<T>) {}\n\n all(predFn: (v: T) => boolean): boolean {\n for (const elem of this) {\n if (!predFn(elem)) {\n return false;\n }\n }\n return true;\n }\n\n any(predFn: (v: T) => boolean): boolean {\n for (const elem of this) {\n if (predFn(elem)) {\n return true;\n }\n }\n return false;\n }\n\n each(visitorFn: (v: T) => any) {\n for (const e of this) {\n visitorFn(e);\n }\n }\n\n first<U>(predFn: (v: T) => any = identity, defaultIfAbsesnt: U | undefined = undefined): T | U | undefined {\n for (const e of this) {\n if (predFn(e)) return e;\n }\n return defaultIfAbsesnt;\n }\n\n map<U>(mapFn: (v: T) => U): Enumerator<U> {\n function* gen(iterator: Enumerator<T>) {\n for (const e of iterator) {\n yield mapFn(e);\n }\n }\n return Enumerator.for(gen(this));\n }\n\n // per https://typescript.tv/hands-on/all-you-need-to-know-about-iterators-and-generators/#the-iterator-protocol\n // implement the IterableIterator interface by implementing [Symbol.iterator]() and next()\n [Symbol.iterator](): IterableIterator<T> {\n return this;\n }\n // per https://typescript.tv/hands-on/all-you-need-to-know-about-iterators-and-generators/#the-iterator-protocol\n // implement the IterableIterator interface by implementing [Symbol.iterator]() and next()\n next(): IteratorResult<T> {\n const val = this.produce();\n if (val instanceof End) {\n return { done: true, value: End.instance };\n }\n return { done: false, value: val };\n }\n\n // this produces either the next value in the Enumerator, or it returns End\n produce(): T | End {\n const val: IteratorResult<T> = this.iterator.next();\n if (val.done) {\n return End.instance;\n }\n return val.value;\n }\n\n select(predFn: (v: T) => boolean): Enumerator<T> {\n function* gen(iterator: Enumerator<T>) {\n for (const e of iterator) {\n if (predFn(e)) yield e;\n }\n }\n return Enumerator.for(gen(this));\n }\n\n toArray(): T[] {\n return Array.from(this);\n }\n\n toMap<K, V>(kvMapFn: (v: T) => [K, V]): Map<K, V> {\n return new Map(this.map(kvMapFn));\n }\n\n toSet(): Set<T> {\n return new Set(this);\n }\n}\n","import { Protocol } from './protocol';\nimport type { AnyConstructor } from './protocol';\nimport { Enumerator } from './enumerator';\n\nexport type ImplementsEnumerable = {};\n\nexport class Enumerable<S, T> extends Protocol {\n static each = each;\n\n constructor(public self: S) {\n super();\n }\n\n each(visitorFn: (v: T) => any) {\n return this.toEnumerator().each(visitorFn);\n }\n\n *emit(): Generator<T> {\n throw new Error('emit not implemented');\n }\n\n toArray(): T[] {\n return this.toEnumerator().toArray();\n }\n\n toEnumerator(): Enumerator<T> {\n return Enumerator.for(this.emit());\n }\n\n toSet(): Set<T> {\n return this.toEnumerator().toSet();\n }\n}\n\nexport function each<T>(visitorFn: (v: T) => any) {\n return function (enumerableVal: Iterable<T>, implClass?: AnyConstructor) {\n return Enumerable.for(enumerableVal, implClass).each(visitorFn);\n };\n}\n","import { Protocol, type AnyConstructor } from './protocol';\n\n/**\n * The interpretation of the generic type parameters is:\n * S is the self type. For example: T[]\n *\n * T is the element type that is being iterated over from the self type, S.\n * For example, when S is T[], then the element type is likely going to be T.\n *\n * U is the type that we are transforming T into.\n * For example, when S is T[], then the element type is likely going to be T,\n * and the mapping function from T -> U means that the transformation type is U.\n */\nexport class Mappable<S, T, U> extends Protocol {\n constructor(public self: S) {\n super();\n }\n\n map(mapFn: (v: T) => U): any {\n throw new Error('not implemented');\n }\n}\n\nexport function map<T, U>(mapFn: (v: T) => U) {\n return function (mappableVal: any, explicitImplClass?: new (self: any) => Mappable<any, T, U>) {\n return Mappable.for(mappableVal, explicitImplClass).map(mapFn);\n };\n}\n\nexport class AsyncMappable<S, T, U> extends Protocol {\n constructor(public self: S) {\n super();\n }\n\n async map(mapFn: (v: T) => Promise<U>): Promise<any> {\n throw new Error('not implemented');\n }\n}\n\nexport function asyncMap<T, U>(mapFn: (v: T) => Promise<U>) {\n return async function (mappableVal: any, explicitImplClass?: new (self: any) => AsyncMappable<any, T, U>) {\n return await AsyncMappable.for(mappableVal, explicitImplClass).map(mapFn);\n };\n}\n","import { Protocol, type AnyConstructor } from './protocol';\n\nexport class Selectable<S, T> extends Protocol {\n constructor(public self: S) {\n super();\n }\n\n select(predFn: (e: T) => boolean): any {\n throw new Error('not implemented');\n }\n}\n\nexport function select<T>(predFn: (e: T) => boolean) {\n return function <S>(selectableVal: S, implClass?: AnyConstructor) {\n return Selectable.for(selectableVal, implClass).select(predFn);\n };\n}\n","import { toSet } from './array';\nimport { Compactable } from './compactable';\nimport { Enumerable } from './enumerable';\nimport { Mappable, AsyncMappable } from './mappable';\nimport { Selectable } from './selectable';\n\nclass CompactableArray<T> extends Compactable<T[]> {\n compact(omit?: any[]) {\n omit ||= [null, undefined];\n\n const omitSet = toSet(omit);\n const newArr: any[] = [];\n for (const val of this.self) {\n if (!omitSet.has(val)) {\n newArr.push(val);\n }\n }\n return newArr;\n }\n}\nawait Compactable.register(Array, CompactableArray, true);\n\nclass MappableArray<T, U> extends Mappable<T[], T, U> {\n map(mapFn: (v: T) => U): any {\n return this.self.map(mapFn);\n }\n}\nawait Mappable.register(Array, MappableArray, true);\n\nexport class AsyncMappableArray<T, U> extends AsyncMappable<T[], T, U> {\n async map(mapFn: (v: T) => Promise<U>) {\n const arr: U[] = [];\n for await (const v of this.self) {\n const mappedValue = await mapFn(v);\n arr.push(mappedValue);\n }\n return arr;\n }\n}\nawait AsyncMappable.register(Array, AsyncMappableArray, true);\n\nclass EnumerableArray<T> extends Enumerable<T[], T> {\n *emit() {\n for (const e of this.self) yield e;\n }\n}\nawait Enumerable.register(Array, EnumerableArray, true);\n\nclass SelectableArray<T> extends Selectable<T[], T> {\n select(predFn: (v: T) => boolean): T[] {\n return this.self.filter(predFn);\n }\n}\nawait Selectable.register(Array, SelectableArray, true);\n","import { buildWrapperProxy } from './function';\n\nexport function each<K, V>(eachFn: (pair: [K, V]) => void) {\n return function (map: Map<K, V>): void {\n map.forEach((value, key) => {\n eachFn([key, value]);\n });\n };\n}\n\nexport function isEmpty<K, V>(map: Map<K, V>): boolean {\n return map.size === 0;\n}\n\n/**\n * @returns An array of the map's keys.\n *\n * ```ts\n * keys(\n * new Map([\n * [\"foo\", [1, 2, 3]],\n * [\"bar\", [4, 6, 7]],\n * ])\n * )\n * // [ 'foo', 'bar' ]\n * ```\n */\nexport function keys<K, V>(map: Map<K, V>): K[] {\n return Array.from(map.keys());\n}\n\nexport function map<K, V, T>(mapFn: (pair: [K, V]) => [K, T]) {\n return function (map: Map<K, V>): Map<K, T> {\n const m = new Map<K, T>();\n map.forEach((value, key) => {\n const [newKey, newValue] = mapFn([key, value]);\n m.set(newKey, newValue);\n });\n return m;\n };\n}\n\nexport function select<K, V>(predFn: (pair: [K, V]) => boolean) {\n return function (map: Map<K, V>): Map<K, V> {\n const newMap = new Map<K, V>();\n map.forEach((value, key) => {\n if (predFn([key, value])) {\n newMap.set(key, value);\n }\n });\n return newMap;\n };\n}\n\nexport function toObject<K, V>(map: Map<K, V>): object {\n return Object.fromEntries(map.entries());\n}\n\nexport function values<K, V>(map: Map<K, V>): V[] {\n return Array.from(map.values());\n}\n\n// export const M = buildPipeThroughFunction();\n\n// Object.assign(M, {\n// each,\n// isEmpty,\n// keys,\n// map,\n// select,\n// toObject,\n// values,\n// });\n\nexport const M = buildWrapperProxy();\nM.registerUncurriedFns({ isEmpty, keys, toObject, values });\nM.registerCurriedFns({ each, map, select });\nM.registerStatic({\n each,\n isEmpty,\n keys,\n map,\n select,\n toObject,\n values,\n});\n\nimport './all-protocols';\n","import { Enumerable } from './enumerable';\nimport { M } from './map';\nimport { Mappable, AsyncMappable } from './mappable';\nimport { Selectable } from './selectable';\n\nexport class MapToMap<K, V, T, U> extends Mappable<Map<K, V>, [K, V], [T, U]> {\n map(mapFn: (pair: [K, V]) => [T, U]) {\n const m = new Map<T, U>();\n this.self.forEach((value, key) => {\n const [newKey, newValue] = mapFn([key, value]);\n m.set(newKey, newValue);\n });\n return m;\n }\n}\n\nexport class MapToArray<K, V, T> extends Mappable<Map<K, V>, [K, V], T> {\n map(mapFn: (pair: [K, V]) => T) {\n const arr: T[] = [];\n this.self.forEach((value, key) => {\n const mappedValue = mapFn([key, value]);\n arr.push(mappedValue);\n });\n return arr;\n }\n}\n\nawait Mappable.register(Map, MapToMap, true);\nawait Mappable.register(Map, MapToArray);\n\nexport class AsyncMapToMap<K, V, T, U> extends AsyncMappable<Map<K, V>, [K, V], [T, U]> {\n async map(mapFn: (pair: [K, V]) => Promise<[T, U]>) {\n const m = new Map<T, U>();\n for await (const [key, value] of this.self) {\n const [newKey, newValue] = await mapFn([key, value]);\n m.set(newKey, newValue);\n }\n return m;\n }\n}\n\nexport class AsyncMapToArray<K, V, T> extends AsyncMappable<Map<K, V>, [K, V], T> {\n async map(mapFn: (pair: [K, V]) => Promise<T>) {\n const arr: T[] = [];\n for await (const [key, value] of this.self) {\n const mappedValue = await mapFn([key, value]);\n arr.push(mappedValue);\n }\n return arr;\n }\n}\n\nawait AsyncMappable.register(Map, AsyncMapToMap, true);\nawait AsyncMappable.register(Map, AsyncMapToArray);\n\nexport class EnumerablePair<K, V> extends Enumerable<Map<K, V>, [K, V]> {\n *emit(): Generator<[K, V]> {\n for (const [k, v] of this.self.entries()) {\n yield [k, v];\n }\n }\n}\n\nexport class EnumerableKey<K, V> extends Enumerable<Map<K, V>, K> {\n *emit() {\n for (const k of this.self.keys()) {\n yield k;\n }\n }\n}\n\nexport class EnumerableValue<K, V> extends Enumerable<Map<K, V>, V> {\n *emit() {\n for (const v of this.self.values()) {\n yield v;\n }\n }\n}\n\nawait Enumerable.register(Map, EnumerablePair, true);\nawait Enumerable.register(Map, EnumerableKey);\nawait Enumerable.register(Map, EnumerableValue);\n\nexport class SelectableMap<K, V> extends Selectable<Map<K, V>, [K, V]> {\n select(predFn: (v: [K, V]) => boolean): Map<K, V> {\n return M(this.self).select(predFn);\n }\n}\nawait Selectable.register(Map, SelectableMap, true);\n","import { buildWrapperProxy, type FunctionBag, type BaseWrapperProxy } from './function';\n\n// Interface for the wrapped object O(obj)\nexport interface WrappedObject<V> {\n each: (eachFn: (pair: [string, V]) => void) => void;\n keys: () => string[];\n map: <T>(mapFn: (pair: [string, V]) => [string, T]) => { [s: string]: T };\n pick: (keysToPick: Set<string>) => { [s: string]: V };\n select: (predFn: (pair: [string, V]) => boolean) => { [s: string]: V };\n toMap: () => Map<string, V>;\n values: () => V[];\n}\n\n// Interface for the O proxy object\nexport interface ObjectWrapperProxy extends BaseWrapperProxy {\n <V>(wrappedValue: { [s: string]: V }): WrappedObject<V>;\n\n // Static methods on O - these match the exported function signatures\n each: <V>(eachFn: (pair: [string, V]) => void) => (object: { [s: string]: V }) => void;\n keys: <V>(object: { [s: string]: V }) => string[];\n map: <V, T>(mapFn: (pair: [string, V]) => [string, T]) => (object: { [s: string]: V }) => { [s: string]: T };\n pick: (keys: Set<string>) => <V>(object: { [s: string]: V }) => { [s: string]: V };\n select: <V>(predFn: (pair: [string, V]) => boolean) => (object: { [s: string]: V }) => { [s: string]: V };\n toMap: <V>(object: { [s: string]: V }) => Map<string, V>;\n values: <V>(object: { [s: string]: V }) => V[];\n\n // Note: registerUncurriedFns, registerCurriedFns, registerStatic are inherited from BaseWrapperProxy\n}\n\nexport function each<V>(eachFn: (pair: [string, V]) => void) {\n return function (object: { [s: string]: V }): void {\n Object.entries<V>(object).forEach((kvPair) => {\n eachFn(kvPair);\n });\n };\n}\n\nexport function keys<V>(object: { [s: string]: V }): string[] {\n return Object.keys(object);\n}\n\nexport function map<V, T>(mapFn: (pair: [string, V]) => [string, T]) {\n return function (object: { [s: string]: V }): { [s: string]: T } {\n const obj: { [s: string]: T } = {};\n Object.entries<V>(object).forEach((kvPair) => {\n const [newKey, newValue] = mapFn(kvPair);\n obj[newKey] = newValue;\n });\n return obj;\n };\n}\n\nexport function pick(keysToPick: Set<string>) {\n // Renamed 'keys' to 'keysToPick' for clarity with WrappedObject.pick\n return select<any>(([key, _]) => keysToPick.has(key)); // Use 'any' as placeholder, select's V will be the actual type\n}\n\nexport function select<V>(predFn: (pair: [string, V]) => boolean) {\n return function (object: { [s: string]: V }): { [s: string]: V } {\n const obj: { [s: string]: V } = {};\n Object.entries<V>(object).forEach((kvPair) => {\n if (predFn(kvPair)) {\n const [k, v] = kvPair;\n obj[k] = v;\n }\n });\n return obj;\n };\n}\n\nexport function toMap<V>(object: { [s: string]: V }): Map<string, V> {\n return new Map(Object.entries<V>(object));\n}\n\nexport function values<V>(object: { [s: string]: V }): V[] {\n return Object.values<V>(object);\n}\n\n// const _O = buildPipeThroughFunction();\n\n// Object.assign(_O, {\n// each, // (eachFn)(obj) => ...\n// keys, // (obj) => ...\n// map,\n// pick,\n// select,\n// toMap,\n// values,\n// });\n\n// export const O = _O;\n\nexport const O = buildWrapperProxy() as ObjectWrapperProxy;\nO.registerUncurriedFns({ keys, toMap, values });\nO.registerCurriedFns({ each, map, pick, select });\nO.registerStatic({\n each, // (eachFn)(obj) => ...\n keys, // (obj) => ...\n map,\n pick,\n select,\n toMap,\n values,\n});\n\nimport './all-protocols';\n","import { O } from './object';\nimport { Selectable } from './selectable';\n\nclass SelectableObject<V> extends Selectable<object, [string, V]> {\n select(predFn: (v: [string, V]) => boolean): object {\n return O(this.self).select(predFn);\n }\n}\nawait Selectable.register(Object, SelectableObject, true);\n","import { copyFile, cp, readFile } from 'node:fs/promises';\nimport { existsSync, readFileSync, lstatSync } from 'node:fs';\nimport { win32, posix } from 'node:path';\nimport type { ParsedPath } from 'node:path';\nimport { homedir } from 'node:os';\nimport { glob, globSync, globStream, globStreamSync, Glob } from 'glob';\nimport { isWindows } from './platform';\nimport { A } from './array';\nimport { Str } from './string';\nimport { Range } from './range';\nimport { Equal } from './equal';\n\nexport class Path {\n static new(path: Path | string, isWindowsPath: boolean = isWindows()): Path {\n if (path instanceof Path) {\n return path;\n }\n return new Path(path, isWindowsPath);\n }\n\n static cwd(): Path {\n return Path.new(process.cwd());\n }\n\n static homeDir(): Path {\n return Path.new(homedir());\n }\n\n static sep(isWindowsPath: boolean = isWindows()) {\n if (isWindowsPath) {\n return win32.sep;\n } else {\n return posix.sep;\n }\n }\n\n constructor(\n public path: string,\n public isWindowsPath: boolean = isWindows(),\n ) {}\n\n absolute(): Path {\n return this.resolve();\n }\n\n ancestors(): Path[] {\n if (this.isRoot()) {\n return [];\n }\n\n const ancestors: Path[] = [];\n let current: Path = this.directory();\n\n while (true) {\n ancestors.push(current);\n\n if (current.isRoot()) {\n break;\n }\n\n current = current.parent();\n }\n return ancestors;\n }\n\n basename(suffix?: string): Path {\n if (this.isWindowsPath) {\n return this.build(win32.basename(this.path, suffix));\n } else {\n return this.build(posix.basename(this.path, suffix));\n }\n }\n\n build(path: string): Path {\n return new Path(path, this.isWindowsPath);\n }\n\n // returns the path to the destination on success; null otherwise\n async copy(destPath: Path | string, mode?: number): Promise<Path | null> {\n destPath = Path.new(destPath).normalize();\n try {\n if (this.isDirectory()) {\n await cp(this.toString(), destPath.toString(), { mode, recursive: true });\n } else {\n await copyFile(this.toString(), destPath.toString(), mode);\n }\n return destPath;\n } catch (e) {\n return null;\n }\n }\n\n dirContains(filename: string): boolean {\n return this.isDirectory() && this.glob(filename).length > 0;\n }\n\n directory(): Path {\n return this.absolute().dirname();\n }\n\n // given a path like \"bar/bas\", this method converts the path to an absolute path (e.g. \"/foo/bar/bas\"),\n // and then returns the directory tree as an array of the form [\"foo\", \"bar\", \"bas\"]\n directorySegments(): string[] {\n return this.absolute().dirname().split();\n }\n\n dirname(): Path {\n if (this.isWindowsPath) {\n return this.build(win32.dirname(this.path));\n } else {\n return this.build(posix.dirname(this.path));\n }\n }\n\n equals(other: any): boolean {\n if (!(other instanceof Path)) {\n return false;\n }\n return this.path === other.path && this.isWindowsPath === other.isWindowsPath;\n }\n\n exists(): boolean {\n return existsSync(this.path);\n }\n\n ext(): string {\n return this.parse().ext;\n }\n\n glob(pattern: string) {\n const cwd = this.absolute().toString();\n return globSync(pattern, { cwd }).map((path) => this.build(path));\n }\n\n isAbsolute(): boolean {\n if (this.isWindowsPath) {\n return win32.isAbsolute(this.path);\n } else {\n return posix.isAbsolute(this.path);\n }\n }\n\n isDirectory(): boolean {\n return this.exists() && lstatSync(this.path).isDirectory();\n }\n\n isFile(): boolean {\n return this.exists() && lstatSync(this.path).isFile();\n }\n\n isPosix(): boolean {\n return !this.isWindowsPath;\n }\n\n isRoot(): boolean {\n return this.parse().root === this.normalize().toString();\n }\n\n isWindows(): boolean {\n return this.isWindowsPath;\n }\n\n join(...paths: string[]): Path {\n if (this.isWindowsPath) {\n return this.build(win32.join(this.path, ...paths));\n } else {\n return this.build(posix.join(this.path, ...paths));\n }\n }\n\n normalize(): Path {\n if (this.isWindowsPath) {\n return this.build(win32.normalize(this.path));\n } else {\n return this.build(posix.normalize(this.path));\n }\n }\n\n parent(count: number = 1) {\n let path = this.absolute();\n Range.new(1, count).each((i) => {\n path = path.resolve('..');\n });\n return path;\n }\n\n // returns an object of the form: { root, dir, base, ext, name }\n //\n // Posix:\n // >>> path.parse('/home/user/dir/file.txt')\n // { root: '/',\n // dir: '/home/user/dir',\n // base: 'file.txt',\n // ext: '.txt',\n // name: 'file' }\n // ┌─────────────────────┬────────────┐\n // │ dir │ base │\n // ├──────┬ ├──────┬─────┤\n // │ root │ │ name │ ext │\n // \" / home/user/dir / file .txt \"\n // └──────┴──────────────┴──────┴─────┘\n // (All spaces in the \"\" line should be ignored. They are purely for formatting.)\n //\n // Windows:\n // >>> path.parse('C:\\\\path\\\\dir\\\\file.txt');\n // { root: 'C:\\\\',\n // dir: 'C:\\\\path\\\\dir',\n // base: 'file.txt',\n // ext: '.txt',\n // name: 'file' }\n // ┌─────────────────────┬────────────┐\n // │ dir │ base │\n // ├──────┬ ├──────┬─────┤\n // │ root │ │ name │ ext │\n // \" C:\\ path\\dir \\ file .txt \"\n // └──────┴──────────────┴──────┴─────┘\n // (All spaces in the \"\" line should be ignored. They are purely for formatting.)\n parse(): ParsedPath {\n if (this.isWindowsPath) {\n return win32.parse(this.path);\n } else {\n return posix.parse(this.path);\n }\n }\n\n pop(count: number = 1): Path {\n return this.parent(count);\n }\n\n relative(to: string): Path {\n if (this.isWindowsPath) {\n return this.build(win32.relative(this.path, to));\n } else {\n return this.build(posix.relative(this.path, to));\n }\n }\n\n resolve(...paths: string[]): Path {\n if (this.isWindowsPath) {\n return this.build(win32.resolve(this.path, ...paths));\n } else {\n return this.build(posix.resolve(this.path, ...paths));\n }\n }\n\n root(): Path {\n const { root } = this.parse();\n return this.build(root);\n }\n\n selfAndAncestors(): Path[] {\n const ancestors: Path[] = [];\n let current: Path = this.absolute();\n\n while (true) {\n ancestors.push(current);\n\n if (current.isRoot()) {\n break;\n }\n\n current = current.parent();\n }\n return ancestors;\n }\n\n // returns the parts of the path, excluding the root if applicable\n // /home/user/dir/file.txt -> [\"home\", \"user\", \"dir\", \"file.txt\"]\n // C:\\home\\user\\dir\\file.txt -> [\"home\", \"user\", \"dir\", \"file.txt\"]\n // user/dir/file.txt -> [\"user\", \"dir\", \"file.txt\"]\n // user\\dir\\file.txt -> [\"user\", \"dir\", \"file.txt\"]\n split(): string[] {\n const normalized = this.normalize();\n if (normalized.isAbsolute()) {\n const { root } = normalized.parse();\n const relPath = Str(normalized.toString()).trimPrefix(root);\n return relPath.split(Path.sep(this.isWindowsPath));\n } else {\n return normalized.toString().split(Path.sep(this.isWindowsPath));\n }\n }\n\n toString(): string {\n return this.path;\n }\n}\n\nclass PathEqualImpl extends Equal<Path> {\n equal(val: Path): boolean {\n return this.self.equals(val);\n }\n}\n\nawait Equal.register(Path, PathEqualImpl, true);\n","import { platform as nodePlatform } from 'node:process';\n\nexport function isPosix(): boolean {\n const posixPlatforms: NodeJS.Platform[] = ['darwin', 'freebsd', 'linux', 'netbsd', 'openbsd', 'sunos'];\n return posixPlatforms.includes(platform());\n}\n\nexport function isWindows(): boolean {\n return platform() == 'win32';\n}\n\nexport function platform(): NodeJS.Platform {\n return nodePlatform;\n}\n","import { V } from './type';\n\n// Define an interface for the Str object/function\ninterface StringWrapper {\n (str: string): StringProxy; // Callable signature\n isEmpty: typeof isEmpty;\n isNumeric: typeof isNumeric;\n matches: typeof matches;\n}\n\nexport function isEmpty(str: string): boolean {\n return str.length == 0;\n}\n\nexport function isNumeric(str: string): boolean {\n if (typeof str !== 'string') return false;\n const trimmedStr = str.trim();\n if (trimmedStr === '') return false; // Empty or whitespace-only string is not numeric\n const num = Number(trimmedStr);\n // Check if it's a number, finite, and if the string version of the number matches the trimmed original string\n return !isNaN(num) && isFinite(num) && String(num) === trimmedStr;\n}\n\n/**\n * @param regexp must be a global regexp, e.g. /foo/g, and not just /foo/\n * @returns array of matches, or null if no matches present\n * Example:\n * const regexp = /t(e)(st(\\d?))/g;\n * const str = 'test1test2';\n *\n * const array = matches(regexp)(str)\n *\n * > matches(regexp)(str)\n * [\n * [\n * 'test1',\n * 'e',\n * 'st1',\n * '1',\n * index: 0,\n * input: 'test1test2',\n * groups: undefined\n * ],\n * [\n * 'test2',\n * 'e',\n * 'st2',\n * '2',\n * index: 5,\n * input: 'test1test2',\n * groups: undefined\n * ]\n * ]\n *\n * > matches(/foo/g)(\"blah\")\n * null\n */\nexport function matches(regexp: RegExp) {\n const globalRegex = regexp.global ? regexp : new RegExp(regexp.source, regexp.flags + 'g');\n return function (str: string) {\n const matches = [...str.matchAll(globalRegex)];\n if (matches.length == 0) return null;\n return matches;\n };\n}\n\nexport class StringProxy {\n // Add common string properties/methods for TypeScript\n public get length(): number {\n return this.str.length;\n }\n\n public toUpperCase(): string {\n return this.str.toUpperCase();\n }\n\n constructor(public str: string) {}\n\n isEmpty() {\n return isEmpty(this.str);\n }\n\n isNumeric() {\n return isNumeric(this.str);\n }\n\n matches(regexp: RegExp) {\n return matches(regexp)(this.str);\n }\n\n trimPrefix(prefix: string): string {\n if (this.str.startsWith(prefix)) {\n return this.str.slice(prefix.length);\n }\n return this.str;\n }\n\n trimSuffix(suffix: string): string {\n if (this.str.endsWith(suffix)) {\n return this.str.slice(0, this.str.length - suffix.length);\n }\n return this.str;\n }\n}\n\n// Cast Str to the StringWrapper interface\nexport const Str = function (str: string): StringProxy {\n const handler = {\n get(target: StringProxy, property: string | symbol, receiver: any) {\n // target is instance of StringProxy\n // Check if property exists on StringProxy instance itself (e.g. isEmpty, isNumeric)\n // or on its prototype chain.\n const propOnTarget = Reflect.get(target, property, receiver);\n\n if (V.isPresent(propOnTarget)) {\n // V.isPresent checks for null or undefined\n // If propOnTarget is a function (method of StringProxy), it's already correctly bound or doesn't need special binding.\n return propOnTarget;\n }\n\n // Property not found on StringProxy instance. Try the underlying string.\n const underlyingString = target.str;\n // Access the property directly from the string primitive.\n // Using `as any` to allow indexing with symbol, though typical string properties are strings.\n const valueFromPrimitive = (underlyingString as any)[property];\n\n if (typeof valueFromPrimitive === 'function') {\n // If it's a method from the string (e.g., toUpperCase, charAt), bind it to the underlying string.\n return valueFromPrimitive.bind(underlyingString);\n }\n\n // For non-function properties (e.g., 'length'), or if the property doesn't exist on a string (valueFromPrimitive will be undefined).\n return valueFromPrimitive;\n },\n };\n\n return new Proxy(new StringProxy(str), handler);\n} as StringWrapper;\n\nObject.assign(Str, {\n isEmpty,\n isNumeric,\n matches,\n});\n","import { Enumerable } from './enumerable';\n\nexport class Range {\n static new(start: number, end: number, inclusive: boolean = true): Range {\n return new Range(start, end, inclusive);\n }\n\n constructor(\n public start: number,\n public end: number,\n public inclusive: boolean = true,\n ) {}\n\n each(visitorFn: (num: number) => any) {\n const exclusiveEnd = this.inclusive ? this.end + 1 : this.end;\n for (let i = this.start; i < exclusiveEnd; i++) {\n visitorFn(i);\n }\n }\n\n equals(other: any): boolean {\n if (!(other instanceof Range)) {\n return false;\n }\n return this.start === other.start && this.end === other.end && this.inclusive === other.inclusive;\n }\n\n map<T>(mapFn: (num: number) => T): T[] {\n const arr: T[] = [];\n this.each((num) => {\n arr.push(mapFn(num));\n });\n return arr;\n }\n\n toArray(): number[] {\n return Enumerable.for<Enumerable<Range, number>>(this).toArray();\n }\n}\n","import { Protocol } from './protocol';\n\nexport class Equal<S> extends Protocol {\n constructor(public self: S) {\n super();\n }\n\n equal(val: S): boolean {\n throw new Error('equal not implemented');\n }\n\n notEqual(val: S): boolean {\n return !this.equal(val);\n }\n\n eq(val: S): boolean {\n return this.equal(val);\n }\n\n neq(val: S): boolean {\n return this.notEqual(val);\n }\n}\n\nexport function equal<T>(self: T, other: T, implClass?: new (self: T) => Equal<T>) {\n return Equal.for(self, implClass).equal(other);\n}\n\nexport function notEqual<T>(self: T, other: T, implClass?: new (self: T) => Equal<T>) {\n return Equal.for(self, implClass).notEqual(other);\n}\n\nexport function eq<T>(self: T, other: T, implClass?: new (self: T) => Equal<T>) {\n return Equal.for(self, implClass).equal(other);\n}\n\nexport function neq<T>(self: T, other: T, implClass?: new (self: T) => Equal<T>) {\n return Equal.for(self, implClass).neq(other);\n}\n","import { Range } from './range';\nimport { Enumerable } from './enumerable';\nimport { Mappable, AsyncMappable } from './mappable';\nimport { Selectable } from './selectable';\nimport { Equal } from './equal';\n\nclass MappableRange<T> extends Mappable<Range, number, T> {\n map(mapFn: (v: number) => T): T[] {\n return this.self.map(mapFn);\n }\n}\nawait Mappable.register(Range, MappableRange, true);\n\n// export class AsyncMappableRange<T, U> extends AsyncMappable<T[], T, U> {\n// async map(mapFn: (v: T) => Promise<U>) {\n// const arr: U[] = [];\n// for await (const v of this.self) {\n// const mappedValue = await mapFn(v);\n// arr.push(mappedValue);\n// }\n// return arr;\n// }\n// }\n// await AsyncMappable.register(Range, AsyncMappableRange, true);\n\nclass EnumerableRange extends Enumerable<Range, number> {\n *emit() {\n const exclusiveEnd = this.self.inclusive ? this.self.end + 1 : this.self.end;\n for (let i = this.self.start; i < exclusiveEnd; i++) {\n yield i;\n }\n }\n}\nawait Enumerable.register(Range, EnumerableRange, true);\n\nclass EqualRange extends Equal<Range> {\n equal(other: Range): boolean {\n return this.self.equals(other);\n }\n}\nawait Equal.register(Range, EqualRange, true);\n\nclass SelectableRange extends Selectable<Range, number> {\n select(predFn: (v: number) => boolean): number[] {\n let arr: number[] = [];\n this.self.each((num) => {\n if (predFn(num)) {\n arr.push(num);\n }\n });\n return arr;\n }\n}\nawait Selectable.register(Range, SelectableRange, true);\n","import { Enumerable } from './enumerable';\nimport { Mappable } from './mappable';\n\nclass MappableSet<T, U> extends Mappable<Set<T>, T, U> {\n map(mapFn: (v: T) => U) {\n const s = new Set<U>();\n this.self.forEach((value) => {\n const newValue = mapFn(value);\n s.add(newValue);\n });\n return s;\n }\n}\nawait Mappable.register(Set, MappableSet, true);\n\nclass EnumerableSet<T> extends Enumerable<Set<T>, T> {\n // each(visitorFn: (v: T) => any): any {\n // return this.self.forEach((v) => visitorFn(v));\n // }\n *emit() {\n for (const e of this.self) {\n yield e;\n }\n }\n}\nawait Enumerable.register(Set, EnumerableSet, true);\n","import { buildWrapperProxy, identity, type BaseWrapperProxy } from './function';\n\nexport function compact(omit: any[] = [null, undefined]) {\n return function (arr: any[]): any[] {\n const omitSet = toSet(omit);\n const newArr: any[] = [];\n for (const val of arr) {\n if (!omitSet.has(val)) {\n newArr.push(val);\n }\n }\n return newArr;\n };\n}\n\nexport function concat<T>(tail: T[]) {\n return function (arr: T[]): T[] {\n return arr.concat(tail);\n };\n}\n\nexport function each<T>(eachFn: (value: T) => void) {\n return function (arr: Array<T>): void {\n arr.forEach((value) => {\n eachFn(value);\n });\n };\n}\n\nexport function find<T>(predicateFn: (v: T) => any) {\n return function (arr: Array<T>): T | undefined {\n for (const val of arr) {\n if (predicateFn(val)) {\n return val;\n }\n }\n return undefined;\n };\n}\n\n// returns the first n elements\nexport function first<T>(n: number) {\n return function (arr: T[]): T[] {\n return arr.slice(0, n);\n };\n}\n\nexport function head<T>(arr: T[]): T | undefined {\n return arr[0];\n}\n\nexport function isEmpty<T>(arr: Array<T>): boolean {\n return arr.length === 0;\n}\n\nexport function join(separator?: string) {\n return function <T>(arr: T[]): string {\n return arr.join(separator);\n };\n}\n\n// returns the last n elements\nexport function last<T>(n: number) {\n return function (arr: T[]): T[] {\n return arr.slice(arr.length - n, arr.length);\n };\n}\n\nexport function map<T, U>(mapFn: (value: T) => U) {\n return function (arr: Array<T>): Array<U> {\n return arr.map(mapFn);\n };\n}\n\nexport function nth(n: number) {\n return function <T>(arr: T[]): T | undefined {\n return arr[n];\n };\n}\n\nexport function partition<T>(predFn: (e: T) => boolean) {\n return function (arr: T[]): [T[], T[]] {\n const trueArr: T[] = [];\n const falseArr: T[] = [];\n for (const val of arr) {\n if (predFn(val)) {\n trueArr.push(val);\n } else {\n falseArr.push(val);\n }\n }\n return [trueArr, falseArr];\n };\n}\n\nexport function prepend<T>(...values: T[]) {\n return function (arr: T[]): T[] {\n arr.splice(0, 0, ...values);\n return arr;\n };\n}\n\nexport function select<T>(predFn: (e: T) => boolean) {\n return function (arr: T[]): T[] {\n return arr.filter(predFn);\n };\n}\n\n// returns the trailing elements of the array except for the leading n elements\nexport function skipFirst<T>(n: number) {\n return function (arr: T[]): T[] {\n if (n > arr.length) {\n n = arr.length;\n }\n return arr.slice(n, arr.length);\n };\n}\n\n// returns the leading elements of the array except for the trailing n elements\nexport function skipLast<T>(n: number) {\n return function (arr: T[]): T[] {\n if (n > arr.length) {\n n = arr.length;\n }\n return arr.slice(0, arr.length - n);\n };\n}\n\nexport function toSet(arr: Array<any>) {\n return new Set(arr);\n}\n\nexport function uniq(arr: Array<any>) {\n return uniqBy(identity)(arr);\n}\n\nexport function uniqBy<T, U>(comparisonValueFn: (value: T) => U) {\n return function (arr: Array<T>): Array<T> {\n const map = new Map<U, T>();\n for (const val of arr) {\n const key = comparisonValueFn(val);\n if (!map.has(key)) {\n map.set(key, val);\n }\n }\n return Array.from(map.values());\n };\n}\n\nexport function zip<T, U>(other: Array<U>) {\n return function (arr: Array<T>): Array<[T, U]> {\n var len = Math.min(arr.length, other.length);\n var result = Array(len);\n var idx = 0;\n while (idx < len) {\n result[idx] = [arr[idx], other[idx]];\n idx += 1;\n }\n return result;\n };\n}\n\n// export const A = {\n// compact,\n// concat,\n// each,\n// first,\n// map,\n// nth,\n// toSet,\n// uniq,\n// uniqBy,\n// };\n\nexport interface ArrayWrapperProxy extends BaseWrapperProxy {\n // Static methods registered via A.registerStatic\n compact: (omit?: any[]) => (arr: any[]) => any[];\n concat: <T>(tail: T[]) => (arr: T[]) => T[];\n each: <T>(eachFn: (value: T) => void) => (arr: Array<T>) => void;\n filter: <T>(predFn: (e: T) => boolean) => (arr: T[]) => T[]; // alias for select\n find: <T>(predicateFn: (v: T) => any) => (arr: Array<T>) => T | undefined;\n first: <T>(n: number) => (arr: T[]) => T[];\n head: <T>(arr: T[]) => T | undefined;\n isEmpty: <T>(arr: Array<T>) => boolean;\n join: (separator?: string) => <T>(arr: T[]) => string;\n last: <T>(n: number) => (arr: T[]) => T[];\n map: <T, U>(mapFn: (value: T) => U) => (arr: Array<T>) => Array<U>;\n nth: (n: number) => <T>(arr: T[]) => T | undefined;\n partition: <T>(predFn: (e: T) => boolean) => (arr: T[]) => [T[], T[]];\n prepend: <T>(...values: T[]) => (arr: T[]) => T[];\n select: <T>(predFn: (e: T) => boolean) => (arr: T[]) => T[];\n skipFirst: <T>(n: number) => (arr: T[]) => T[];\n skipLast: <T>(n: number) => (arr: T[]) => T[];\n toSet: <T>(arr: Array<T>) => Set<T>;\n uniq: <T>(arr: Array<T>) => T[];\n uniqBy: <T, U>(comparisonValueFn: (value: T) => U) => (arr: Array<T>) => Array<T>;\n zip: <T, U>(other: Array<U>) => (arr: Array<T>) => Array<[T, U]>;\n}\n\nexport const A = buildWrapperProxy() as ArrayWrapperProxy;\n\nA.registerUncurriedFns({ head, isEmpty, toSet, uniq });\nA.registerCurriedFns({\n compact,\n concat,\n each,\n filter: select,\n find,\n first,\n join,\n last,\n map,\n nth,\n partition,\n prepend,\n select,\n skipFirst,\n skipLast,\n uniqBy,\n zip,\n});\nA.registerStatic({\n compact,\n concat,\n each,\n filter: select,\n find,\n first,\n head,\n isEmpty,\n join,\n last,\n map,\n nth,\n partition,\n prepend,\n select,\n skipFirst,\n skipLast,\n toSet,\n uniq,\n uniqBy,\n zip,\n});\n\nimport './all-protocols';\n","import { Enumerable } from './enumerable';\nimport { buildWrapperProxy, type FunctionBag } from './function';\n\nexport interface SetWrapperProxy {\n <T>(wrappedValue: Set<T>): any; // Represents the function signature of S itself\n registerUncurriedFns: (fns: FunctionBag) => void;\n registerCurriedFns: (fns: FunctionBag) => void;\n registerStatic: (fns: FunctionBag) => void;\n\n // Static methods registered via S.registerStatic\n addAll: (enumerableVal: any) => <T>(set: Set<T>) => Set<T>;\n each: <V>(eachFn: (value: V) => void) => (set: Set<V>) => void;\n intersection: (enumerableVal: any) => <T>(set: Set<T>) => Set<T>;\n isEmpty: <V>(set: Set<V>) => boolean;\n isSubsetOf: (enumerableSuperset: any) => <T>(set: Set<T>) => boolean;\n isSupersetOf: (enumerableSubset: any) => <T>(set: Set<T>) => boolean;\n map: <V, T>(mapFn: (value: V) => T) => (set: Set<V>) => Set<T>;\n toArray: <V>(set: Set<V>) => V[];\n union: (enumerableVal: any) => <T>(set: Set<T>) => Set<T>;\n}\n\nexport function addAll(enumerableVal: any) {\n // console.log(`------------- addAll: ${V(enumerableVal).inspect()}`)\n const enumerable = Enumerable.for<Enumerable<any, any>>(enumerableVal);\n return function <T>(set: Set<T>): Set<T> {\n enumerable.each((item: T) => set.add(item));\n return set;\n };\n}\n\nexport function each<V>(eachFn: (value: V) => void) {\n return function (set: Set<V>): void {\n set.forEach((value) => {\n eachFn(value);\n });\n };\n}\n\nexport function intersection(enumerableVal: any) {\n const enumerable = Enumerable.for<Enumerable<any, any>>(enumerableVal);\n return function <T>(set: Set<T>): Set<T> {\n return set.intersection(enumerable.toSet());\n };\n}\n\nexport function isEmpty<V>(set: Set<V>): boolean {\n return set.size === 0;\n}\n\nexport function isSubsetOf(enumerableSuperset: any) {\n const enumerable = Enumerable.for<Enumerable<any, any>>(enumerableSuperset);\n return function <T>(set: Set<T>): boolean {\n return set.isSubsetOf(enumerable.toSet());\n };\n}\n\nexport function isSupersetOf(enumerableSubset: any) {\n const enumerable = Enumerable.for<Enumerable<any, any>>(enumerableSubset);\n return function <T>(set: Set<T>): boolean {\n return set.isSupersetOf(enumerable.toSet());\n };\n}\n\nexport function map<V, T>(mapFn: (value: V) => T) {\n return function (set: Set<V>): Set<T> {\n const s = new Set<T>();\n set.forEach((value) => {\n const newValue = mapFn(value);\n s.add(newValue);\n });\n return s;\n };\n}\n\nexport function toArray<V>(set: Set<V>): V[] {\n return Array.from(set.values());\n}\n\nexport function union(enumerableVal: any) {\n const enumerable = Enumerable.for<Enumerable<any, any>>(enumerableVal);\n return function <T>(set: Set<T>): Set<T> {\n return set.union(enumerable.toSet());\n };\n}\n\n// export const S = buildPipeThroughFunction();\n\n// Object.assign(S, {\n// addAll,\n// each,\n// intersection,\n// isEmpty,\n// isSubsetOf,\n// isSupersetOf,\n// map,\n// toArray,\n// union,\n// });\n\nexport const S = buildWrapperProxy() as SetWrapperProxy;\nS.registerUncurriedFns({ isEmpty, toArray });\nS.registerCurriedFns({ addAll, each, intersection, map, union, isSubsetOf, isSupersetOf });\nS.registerStatic({\n addAll,\n each,\n intersection,\n isEmpty,\n isSubsetOf,\n isSupersetOf,\n map,\n toArray,\n union,\n});\n\nimport './all-protocols';\n","import { A } from './array';\nimport { compact } from './compactable';\nimport { Enumerable, each } from './enumerable';\nimport { F } from './function';\nimport { M } from './map';\nimport { asyncMap, map } from './mappable';\nimport { O } from './object';\nimport { select } from './selectable';\nimport { S } from './set';\nimport { Str } from './string';\nimport { V } from './type';\nimport type { AnyConstructor } from './protocol';\n\nclass Pipe {\n constructor(public value: any) {}\n\n // e.g. convertMethodsToPipeline(A([1,2,3]))\n // returns a function that proxies method invocations through to the A([1,2,3]) object but assigns their return value\n // to this.value in the pipeline, and then returns the pipe object, enabling stuff like this:\n // P([1,2,3]).A.compact().A.first().value\n _convertMethodsToPipeline(wrappedValue: any, nameOfMethodBag: string) {\n const self = this;\n\n return new Proxy(wrappedValue, {\n get(target, property, receiver) {\n // function objects, like those returned from `A([1,2,3])`, have function properties attached to them that when invoked\n // will operate on the value supplied to the A function (e.g. [1,2,3]),\n // so we want to return a function that invokes the requested function property specified by the get handler\n // and assigns the result of the evaluation of that function property to the `this.value` member of the Pipe object\n const fn = Reflect.get(target, property, receiver);\n if (fn === undefined) {\n throw Error(`${nameOfMethodBag} does not have a method named ${String(property)}`);\n }\n // we return a function that wraps the function property that is being accessed, such that when invoked, the return value is\n // assigned to self.value and then the pipe object is returned\n return function (...args: any) {\n self.value = fn.apply(receiver, args);\n return self;\n };\n },\n });\n }\n\n get A() {\n return A(this.value);\n }\n\n get a() {\n return this._convertMethodsToPipeline(A(this.value), 'A');\n }\n\n compact(...args: any[]) {\n this.value = compact(...args)(this.value);\n return this;\n }\n\n each(visitorFn: (v: any) => any) {\n this.value = each(visitorFn)(this.value);\n return this;\n }\n\n get F() {\n return F(this.value);\n }\n\n get f() {\n return this._convertMethodsToPipeline(F(this.value), 'F');\n }\n\n // enumerable() {\n // this.value = Enumerable.for(this.value);\n // return this;\n // }\n\n // enumerator() {\n // this.value = Enumerator.for(this.value);\n // return this;\n // }\n\n log() {\n console.log(V.inspect(this.value));\n return this;\n }\n\n get M() {\n return M(this.value);\n }\n\n get m() {\n return this._convertMethodsToPipeline(M(this.value), 'M');\n }\n\n map(mapFn: (v: any) => any, implClass?: AnyConstructor) {\n this.value = map(mapFn)(this.value, implClass);\n return this;\n }\n\n asyncMap(mapFn: (v: any) => Promise<any> | any, implClass?: AnyConstructor) {\n this.value = asyncMap(mapFn)(this.value, implClass);\n return this;\n }\n\n get O() {\n return O(this.value);\n }\n\n get o() {\n return this._convertMethodsToPipeline(O(this.value), 'O');\n }\n\n pipe(fn: (value: any) => any) {\n this.value = fn(this.value);\n return this;\n }\n\n get S() {\n return S(this.value);\n }\n\n get s() {\n return this._convertMethodsToPipeline(S(this.value), 'S');\n }\n\n get Str() {\n return Str(this.value);\n }\n\n get str() {\n return this._convertMethodsToPipeline(Str(this.value), 'Str');\n }\n\n select(predFn: (v: any) => boolean, implClass?: AnyConstructor) {\n this.value = select(predFn)(this.value, implClass);\n return this;\n }\n\n toArray() {\n this.value = Enumerable.for<Enumerable<any, any>>(this.value).toArray();\n return this;\n }\n\n waitAll() {\n this.value = Promise.allSettled(this.value).then((results) => {\n return results.map((result) => {\n if (result.status === 'fulfilled') {\n return result.value;\n } else {\n return new Error(result.reason);\n }\n });\n });\n // .finally(() => {\n // console.log(\"Experiment completed\");\n // });\n return this;\n }\n}\n\nexport const VP = function (initial: any) {\n return new Pipe(initial);\n};\n\n// P([1,2,3,4]).map(v => v * 2).compact().value\n// P([1,2,3,4]).map(v => v * 2).A.compact()\n// P([1,2,3,4]).map(v => v * 2).a.compact().value\n// P([1,2,3,4]).map(v => v * 2).pipe(A.compact).value\n","import { homedir } from 'node:os';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { File } from './flex/file';\nimport { Path } from './flex/path';\n\nexport class TmpFileRegistry {\n private static _instance?: TmpFileRegistry;\n static get instance() {\n const path = File.join(osHomeDir(), '.hostctl', 'tmpstatic');\n this._instance ??= new TmpFileRegistry(path);\n return this._instance;\n }\n\n private rootPath: Path;\n private tempFilePaths: string[];\n\n constructor(rootPath: string | Path) {\n // console.log(`TmpFileRegistry: ${rootPath}`);\n this.rootPath = Path.new(rootPath);\n this.tempFilePaths = [];\n process.on('exit', (code) => this.exitCallback());\n }\n\n randName(): string {\n return Math.random().toString(36).slice(-5) + Math.random().toString(36).slice(-5);\n }\n\n tmpPath(tmpName?: string) {\n tmpName ??= this.randName();\n return this.rootPath.join(tmpName);\n }\n\n // this directory will be automatically cleaned up at program exit\n createNamedTmpDir(subDirName?: string): Path {\n const path = this.tmpPath(subDirName);\n fs.mkdirSync(path.toString(), { recursive: true });\n this.registerTempFileOrDir(path.toString());\n return path;\n }\n\n // this file will be automatically cleaned up at program exit\n writeTmpFile(fileContent: string): Path {\n const path = this.tmpPath();\n fs.writeFileSync(path.toString(), fileContent);\n this.registerTempFileOrDir(path.toString());\n return path;\n }\n\n exitCallback() {\n this.cleanupTempFiles();\n }\n\n registerTempFileOrDir(path: string) {\n this.tempFilePaths.push(path);\n }\n\n cleanupTempFiles() {\n this.tempFilePaths.forEach((path) => {\n this.rmFile(path);\n });\n this.tempFilePaths = [];\n }\n\n rmFile(path: string) {\n try {\n // console.log(`rm tmp file: ${path}`)\n fs.rmSync(path, { force: true, recursive: true });\n } catch (e) {\n // no-op\n }\n }\n}\n\n/**\n * Returns the currently configured tmp dir from os.tmpdir().\n */\nexport function osTmpDir() {\n return path.resolve(os.tmpdir());\n}\n\nexport function osHomeDir() {\n return path.resolve(os.homedir());\n}\n\n// export function createHostCtlDir(): string {\n// const path = File.join(osHomeDir(), \".hostctl\");\n// fs.mkdirSync(path, { recursive: true });\n// return path;\n// }\n\n// export function createNamedTmpDir(subDirName: string = \"tmp\"): string {\n// // const path = File.join(osTmpDir(), subDirName);\n// const path = File.join(osHomeDir(), \".hostctl\", subDirName);\n// fs.mkdirSync(path, { recursive: true });\n// return path;\n// }\n\n// returns the full path to the temp file on disk\nexport function writeTmpFile(fileContents: string): Path {\n return TmpFileRegistry.instance.writeTmpFile(fileContents);\n // return temporaryWriteSync(fileContents);\n}\n\n// export function rmTmpFile(path: string) {\n// try {\n// fs.rmSync(path, { force: true, recursive: true });\n// } catch (e) {\n// // no-op\n// }\n// }\n\n// export function createTmpFile(): string {\n// tmp.setGracefulCleanup();\n\n// return tmp.tmpNameSync();\n// }\n\n// export function createTmpDir(): string {\n// tmp.setGracefulCleanup();\n\n// const tmpDir = tmp.dirSync();\n// return tmpDir.name;\n// }\n","import type { PathLike } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { win32, posix } from 'node:path';\nimport { isWindows } from './platform';\n\nexport function exists(path: PathLike): boolean {\n return existsSync(path);\n}\n\nexport class File {\n static absolutePath(...paths: string[]): string {\n if (isWindows()) {\n return win32.resolve(...paths);\n } else {\n return posix.resolve(...paths);\n }\n }\n\n // basename(\"c:\\\\foo\\\\bar\\\\baz.txt\") => \"baz.txt\"\n // basename(\"/tmp/myfile.html\") => \"myfile.html\"\n static basename(path: string, suffix?: string): string {\n if (isWindows()) {\n return win32.basename(path, suffix);\n } else {\n return posix.basename(path, suffix);\n }\n }\n\n static exists(path: PathLike): boolean {\n return exists(path);\n }\n\n static join(...paths: string[]): string {\n if (isWindows()) {\n return win32.join(...paths);\n } else {\n return posix.join(...paths);\n }\n }\n\n static readSync(path: PathLike): string {\n return readFileSync(path, {\n encoding: 'utf8',\n });\n }\n\n static async readAsync(path: PathLike): Promise<string> {\n return await readFile(path, {\n encoding: 'utf8',\n });\n }\n}\n","import { Perc } from './flex';\nimport { A } from './flex/array';\nimport { O } from './flex/object';\nimport { VP } from './flex/pipe';\nimport { Undefined, V, kind } from './flex/type';\nimport { S } from './flex/set';\nimport { ConfigFile, Secret, SecretRef, SecretValue } from './config-file';\nimport { writeTmpFile } from './tempfile';\n\nexport class Host {\n public hostname: string; // The network hostname or IP address, from the YAML hosts map key\n public alias?: string;\n public port: number;\n public user?: string;\n public password?: SecretRef | string;\n public sshKey?: SecretRef | string;\n public tags: string[];\n public tagSet: Set<string>;\n\n constructor(\n public config: ConfigFile,\n opts: {\n hostname: string; // The network hostname or IP from the YAML hosts map key\n alias?: string;\n port?: number;\n user?: string;\n password?: SecretRef | string;\n sshKey?: SecretRef | string;\n tags?: string[];\n },\n ) {\n this.hostname = opts.hostname;\n this.alias = opts.alias;\n this.port = opts.port || 22;\n this.user = opts.user;\n this.password = opts.password;\n this.sshKey = opts.sshKey;\n this.tags = opts.tags ?? [];\n this.tagSet = new Set(this.tags);\n }\n\n async decryptedPassword(): Promise<string | undefined> {\n switch (kind(this.password)) {\n case String:\n return this.password as string;\n case SecretRef:\n const secretRef = this.password as SecretRef;\n const secret = this.config.getSecret(secretRef.name);\n return await secret?.plaintext();\n }\n // otherwise, it's undefined, so implicitly return undefined\n }\n\n async decryptedSshKey(): Promise<string | undefined> {\n if (V(this.sshKey).isA(SecretRef)) {\n const secretRef = this.sshKey as SecretRef;\n const secret = this.config.getSecret(secretRef.name);\n return await secret?.plaintext();\n }\n // otherwise, it's either undefined or a string path to a key that is already on the filesystem, so implicitly return undefined\n }\n\n toYAML() {\n let passwordForYaml: string | ReturnType<SecretRef['toYAML']> | undefined = this.password;\n if (this.password && V(this.password).isA(SecretRef)) {\n passwordForYaml = (this.password as SecretRef).toYAML();\n }\n\n let sshKeyForYaml: string | ReturnType<SecretRef['toYAML']> | undefined = this.sshKey;\n if (this.sshKey && V(this.sshKey).isA(SecretRef)) {\n sshKeyForYaml = (this.sshKey as SecretRef).toYAML();\n }\n\n return {\n alias: this.alias,\n user: this.user,\n port: this.port === 22 ? undefined : this.port, // Only include port if not default\n password: passwordForYaml,\n 'ssh-key': sshKeyForYaml,\n tags: this.tags,\n };\n }\n\n // domain logic\n\n get shortName(): string {\n return this.alias || this.hostname;\n }\n\n isLocal(): boolean {\n // A host is local if its hostname is 'localhost' or '127.0.0.1'.\n // More robust checks could involve os.hostname(), but this is a common simple check.\n return this.hostname === 'localhost' || this.hostname === '127.0.0.1';\n }\n\n get uri(): string {\n return this.hostname;\n }\n\n // returns the temporary path to the decrypted ssh key\n async writeTmpDecryptedSshKey(): Promise<string | undefined> {\n const content = await this.decryptedSshKey();\n if (content) {\n return writeTmpFile(content).toString();\n }\n }\n\n private _plaintextSshKeyPath: string | undefined = undefined;\n async plaintextSshKeyPath(): Promise<string | undefined> {\n if (this._plaintextSshKeyPath) {\n return this._plaintextSshKeyPath;\n }\n\n switch (kind(this.sshKey)) {\n case String:\n this._plaintextSshKeyPath = this.sshKey as string;\n break;\n case SecretRef:\n this._plaintextSshKeyPath = await this.writeTmpDecryptedSshKey();\n break;\n }\n return this._plaintextSshKeyPath;\n }\n\n toObject() {\n return {\n hostname: this.hostname,\n port: this.port,\n alias: this.alias,\n user: this.user,\n tags: this.tags,\n };\n }\n\n hasTag(tag: string): boolean {\n return this.tagSet.has(tag);\n }\n\n // each tag is a string of the form:\n // - foo\n // - bar,baz\n // the interpretation of a 'bar,baz' tag is that the host must have either the 'bar' tag or the 'baz' tag in order to consider the 'bar,baz' tag present\n hasAllTags(tags: Set<string>): boolean {\n for (const tag of tags) {\n const tagParts = tag.split(',');\n const anyTagPartPresent = S(this.tagSet).intersection(tagParts).size > 0;\n if (!anyTagPartPresent) return false;\n }\n return true;\n }\n\n // each tag is a string of the form:\n // - foo\n // - bar+baz\n // the interpretation of a 'bar+baz' tag is that the host must have both the 'bar' tag and the 'baz' tag in order to consider the 'bar+baz' tag present\n hasAnyTag(tags: Set<string>): boolean {\n const effectiveTagsForMatching = S(new Set(this.tagSet)).addAll(A([this.hostname, this.alias]).compact());\n for (const tag of tags) {\n const tagParts = tag.split('+');\n const allTagPartsPresent = S(effectiveTagsForMatching).isSupersetOf(tagParts);\n if (allTagPartsPresent) return true;\n }\n return false;\n }\n}\n","// import { encrypt_with_x25519, decrypt_with_x25519 } from \"@kanru/rage-wasm\";\nimport fs from 'node:fs';\nimport * as age from 'age-encryption';\n\nimport { Process } from './process';\nimport { writeTmpFile } from './tempfile';\n\nconst AGE_ENCRYPTED_FILE_HEADER = '-----BEGIN AGE ENCRYPTED FILE-----';\n\n// Define a common interface for encryption drivers\ninterface IAgeDriver {\n encrypt(valueToEncrypt: string, publicKeys: string[]): Promise<string>;\n decrypt(valueToDecrypt: string, privateKeyFilePaths: string[]): Promise<string | null>;\n}\n\n// Helper function to read identity string from a file (used by LibraryDriver)\nfunction readIdentityStringFromFile(path: string): string {\n const contents = fs.readFileSync(path, {\n encoding: 'utf8',\n });\n const identityString = contents\n .split(/\\r?\\n|\\r|\\n/g)\n .map((line) => line.trim())\n .find((line) => line.startsWith('AGE-SECRET-KEY-1'));\n if (!identityString) throw new Error(`Unable to read identity from file: ${path}`);\n return identityString;\n}\n\nexport class CliDriver implements IAgeDriver {\n async encrypt(valueToEncrypt: string, publicKeys: string[]): Promise<string> {\n const recipientArgs = publicKeys.flatMap((key) => ['-r', key]);\n // Capture stderr for better error reporting\n const { stdout, success, stderr } = await Process.spawn('age', ['-e', '-a'].concat(recipientArgs), valueToEncrypt);\n\n if (!success) {\n // Use new Error and include stderr if available\n throw new Error(`Failed to encrypt with age CLI: ${stderr || stdout}`);\n }\n return stdout;\n }\n\n async decrypt(valueToDecrypt: string, privateKeyFilePaths: string[]): Promise<string | null> {\n if (privateKeyFilePaths.length === 0) {\n // Use new Error for consistency\n throw new Error('Unable to decrypt: No age encryption identity (private key) specified.');\n }\n const identityArgs = privateKeyFilePaths.flatMap((path) => ['-i', path]);\n // Capture stderr for better error reporting\n const { stdout, success, stderr } = await Process.spawn('age', ['-d'].concat(identityArgs), valueToDecrypt);\n\n if (!success) {\n // console.error(`Failed to decrypt with age CLI: ${stderr || stdout}`); // Optional for debugging\n return null; // Return null on failure\n }\n return stdout;\n }\n}\n\n// New LibraryDriver using age-encryption package, implementing IAgeDriver\nexport class LibraryDriver implements IAgeDriver {\n async encrypt(valueToEncrypt: string, publicKeys: string[]): Promise<string> {\n const e = new age.Encrypter();\n publicKeys.forEach((key) => e.addRecipient(key));\n const ciphertextBytes = await e.encrypt(valueToEncrypt); // Returns Uint8Array\n return age.armor.encode(ciphertextBytes); // Armor the Uint8Array to string\n }\n\n async decrypt(valueToDecryptArmored: string, privateKeyFilePaths: string[]): Promise<string | null> {\n if (privateKeyFilePaths.length === 0) {\n throw new Error('Unable to decrypt: No age encryption identity (private key) specified.');\n }\n\n const d = new age.Decrypter();\n let identitiesAdded = 0;\n for (const path of privateKeyFilePaths) {\n try {\n const identityString = readIdentityStringFromFile(path);\n d.addIdentity(identityString);\n identitiesAdded++;\n } catch (err) {\n // Log and continue: an invalid key path shouldn't prevent other valid keys from being tried.\n console.warn(`Failed to read or parse identity file ${path}, skipping: ${(err as Error).message}`);\n }\n }\n\n if (identitiesAdded === 0) {\n // console.error(\"Decryption failed: No valid identities could be loaded.\");\n return null; // No valid keys were loaded to attempt decryption.\n }\n\n try {\n const ciphertextBytes = age.armor.decode(valueToDecryptArmored); // De-armor string to Uint8Array\n const decryptedText = await d.decrypt(ciphertextBytes, 'text'); // Decrypts to string\n return decryptedText;\n } catch (error) {\n // Handles errors from age.armor.decode or d.decrypt (e.g., bad armor, no matching identity, corrupted data)\n // console.error(\"Library decryption failed:\", error); // Optional: for debugging\n return null; // Return null on any decryption failure\n }\n }\n}\n\nexport class Identity {\n public identityFilePath: string;\n private identity: string;\n\n // either the path to an identity file or an identity string must be supplied\n constructor({ path, identity }: { path?: string; identity?: string }) {\n if (identity) {\n this.identity = identity;\n this.identityFilePath = this.writeTmpIdentityFile(identity);\n } else if (path) {\n this.identity = this.readIdentityFromFile(path);\n this.identityFilePath = path;\n } else {\n throw 'Either an identity string or an identity file path must be supplied to create an Age Encryption identity';\n }\n }\n\n public get recipient(): Promise<string> {\n return age.identityToRecipient(this.identity);\n }\n\n // returns the path to the temp file\n private writeTmpIdentityFile(identity: string) {\n return writeTmpFile(identity).toString();\n }\n\n private readIdentityFromFile(path: string): string {\n const contents = fs.readFileSync(path, {\n encoding: 'utf8',\n });\n\n const identityString = contents\n .split(/\\r?\\n|\\r|\\n/g)\n .map((line) => line.trim())\n .find((line) => line.startsWith('AGE-SECRET-KEY-1'));\n\n if (!identityString) throw new Error(`Unable to read identity file: ${path}`);\n\n return identityString;\n }\n\n get privateKey(): string {\n return this.identity;\n }\n\n get publicKey(): Promise<string> {\n return this.recipient;\n }\n\n decrypt(encryptedString: string): Promise<string | null> {\n return AgeEncryption.decrypt(encryptedString, [this.identityFilePath]);\n\n ///////////////////////////////////\n\n // const encryptedBytes = new TextEncoder().encode(encryptedString);\n // const plaintextBytes = await decrypt_with_x25519(this.identity, encryptedBytes);\n // return new TextDecoder().decode(plaintextBytes);\n\n ///////////////////////////////////\n\n // const d = new Decrypter();\n // d.addIdentity(this.identity);\n\n // const encryptedBytes = new TextEncoder().encode(encryptedString);\n // return d.decrypt(encryptedBytes, \"text\");\n }\n\n async encrypt(plaintext: string): Promise<string> {\n return AgeEncryption.encrypt(plaintext, [await this.recipient]);\n\n ///////////////////////////////////\n\n // const plaintextBytes = new TextEncoder().encode(plaintext);\n // const encryptedBytes = await encrypt_with_x25519(\n // this.recipient,\n // plaintextBytes,\n // true\n // );\n // return new TextDecoder().decode(encryptedBytes);\n\n ///////////////////////////////////\n\n // const e = new Encrypter();\n // e.addRecipient(this.recipient);\n\n // const encryptedBytes = e.encrypt(plaintext);\n // return new TextDecoder().decode(encryptedBytes);\n }\n}\n\nexport class AgeEncryption {\n static instance: IAgeDriver = new LibraryDriver(); // Use LibraryDriver by default\n\n static async encrypt(valueToEncrypt: string, publicKeys: string[]): Promise<string> {\n const encrypted = await this.instance.encrypt(valueToEncrypt, publicKeys);\n // console.log(`encrypting ${valueToEncrypt} with keys ${publicKeys}: ${encrypted}`)\n return encrypted;\n }\n\n static async decrypt(valueToDecrypt: string, privateKeyFilePaths: string[]): Promise<string | null> {\n return await this.instance.decrypt(valueToDecrypt, privateKeyFilePaths);\n }\n}\n\n// const id = new Identity({ path: \"/home/david/.secrets/age/david.priv\" });\n// console.log(\"identity\", id.privateKey);\n// console.log(\"recipient\", id.publicKey);\n// const encrypted = await id.encrypt(\"food\");\n// console.log(\"encrypt 'food' =>\", encrypted);\n// const plain = await id.decrypt(encrypted);\n// console.log(`decrypt '${encrypted}' =>`, plain);\n","import spawnAsync, { type SpawnResult } from '@expo/spawn-async';\n\nexport type ProcessResult = SpawnResult & { success: boolean };\nexport class Process {\n static spawn(cmd: string, args: string[], stdin?: string): Promise<ProcessResult> {\n return new Process(cmd, args, stdin).spawn();\n }\n\n constructor(\n public cmd: string,\n public args: string[],\n public stdin?: string,\n ) {}\n\n async spawn(): Promise<ProcessResult> {\n try {\n const spawnOptions = {\n ignoreStdio: false,\n // detached: true, // if we wanted to keep child alive after parent exits\n };\n const promise = spawnAsync(this.cmd, this.args, spawnOptions);\n\n if (this.stdin && promise.child) {\n promise.child.stdin?.write(this.stdin);\n promise.child.stdin?.end();\n }\n const result: SpawnResult = await promise;\n\n // const child = procp.child;\n // const stdout = new StringBuilder();\n // const stderr = new StringBuilder();\n\n // child.stdout?.on('data', (data) => {\n // stdout.append(data);\n // });\n\n // child.stderr?.on('data', (data) => {\n // stderr.append(data);\n // });\n\n // child.on('exit', (code, signal) => {\n // console.log(`child process exited with code ${code} and signal ${signal}`);\n // });\n\n return { ...result, success: result.status === 0 };\n } catch (e) {\n // The error object also has the same properties as the result object\n // console.error(e.stack);\n const errorResult = e as SpawnResult;\n return { ...errorResult, success: errorResult.status === 0 };\n }\n }\n}\n","import { Host } from './host';\nimport type { Config, IRecipientGroup, ISecret } from './config';\nimport type { Secret, RecipientGroup } from './config-file'; // Import concrete types for Map values\n\nexport class ConfigUrl implements Config {\n public _hosts: Map<string, Host>;\n public _secrets: Map<string, Secret>;\n public _ids: Map<string, RecipientGroup>;\n\n constructor(public url: string) {\n this._hosts = new Map();\n this._secrets = new Map();\n this._ids = new Map();\n }\n\n // Config interface\n\n hosts(): Host[] {\n return [];\n }\n\n getSecret(name: string): ISecret | undefined {\n return undefined; // ConfigUrl does not manage individual secrets\n }\n\n getRecipientGroups(idRefs: string[]): IRecipientGroup[] {\n return []; // ConfigUrl does not manage recipient groups\n }\n\n secrets(): Map<string, Secret> {\n return this._secrets;\n }\n\n ids(): Map<string, RecipientGroup> {\n return this._ids;\n }\n}\n","import { Readable } from 'node:stream';\nimport { StreamRegex } from 'stream-regex';\nimport { M } from './flex/map';\nimport { VP } from './flex/pipe';\nimport { A } from './flex/array';\nimport type { InputMap } from './util/input-helpers';\n\nexport class InteractionHandler {\n static with(inputs: InputMap): InteractionHandler {\n return new InteractionHandler(new Map(Object.entries(inputs)));\n }\n\n private patternInputMappings: Map<string, string>; // pairs of pattern -> response\n private inputStreamForRegexMatcher: Readable | undefined;\n // private streamRegex: StreamRegex;\n // private matches: Readable;\n private writeFn: ((str: string) => void) | undefined;\n constructor(patternInputMappings: Map<string | RegExp, string> = new Map()) {\n this.patternInputMappings = M(patternInputMappings).map(([pattern, v]: [string | RegExp, string]) => [\n pattern instanceof RegExp ? pattern.source : pattern,\n v,\n ]);\n }\n clone(): InteractionHandler {\n return new InteractionHandler(this.patternInputMappings);\n }\n with(inputs: InputMap): InteractionHandler {\n const clone = this.clone();\n clone.mapInput(inputs);\n return clone;\n }\n mapInput(inputMap: InputMap): InteractionHandler {\n Object.entries(inputMap).forEach(([pattern, response]) => {\n this.map(pattern, response);\n });\n return this;\n }\n map(pattern: RegExp | string, response: string) {\n if (pattern instanceof RegExp) {\n this.patternInputMappings.set(pattern.source, response);\n } else {\n this.patternInputMappings.set(pattern, response);\n }\n return this;\n }\n // builds a regex of the form /(alternative 1)|(alternative 2)|...|(alternative N)/\n compositeRegex(): RegExp | undefined {\n if (M(this.patternInputMappings).isEmpty()) return undefined;\n const compositePattern: string = VP(this.patternInputMappings)\n .m.keys()\n .map((pattern: string) => `(${pattern})`)\n .a.join('|').value;\n return new RegExp(compositePattern, 'g');\n }\n // returns the first pattern that matches\n // the matching pattern will be a key in ioMappings\n firstMatchingPattern(matchStr: string): string | undefined {\n // we know this will not return undefined because the pattern has already been observed, we just need to figure out which regex matched it\n return Array.from(this.patternInputMappings.keys()).find((pattern) => matchStr.match(pattern));\n }\n findReplacementForMatch(matchStr: string): string | undefined {\n const matchingPattern = this.firstMatchingPattern(matchStr);\n if (!matchingPattern) return undefined; // we know this will not return undefined because the pattern has already been observed, we just need to figure out which regex matched it\n const replacementValue = this.patternInputMappings.get(matchingPattern);\n return replacementValue;\n }\n begin() {\n this.inputStreamForRegexMatcher = new Readable();\n this.inputStreamForRegexMatcher._read = () => {};\n const compositeRegex = this.compositeRegex();\n if (compositeRegex) {\n // this.streamRegex = new StreamRegex(compositeRegex);\n // this.matches = this.streamRegex.match(this.inputStreamForRegexMatcher);\n // this.matches.on(\"data\", (matchStr) => {\n const streamRegex = new StreamRegex(compositeRegex);\n const matches: Readable = streamRegex.match(this.inputStreamForRegexMatcher);\n matches.on('data', (matchStr) => {\n // console.log(\"interaction handler match\", matchStr);\n const inputToWrite: string | undefined = this.findReplacementForMatch(matchStr);\n if (inputToWrite !== undefined) {\n this.emitInput(inputToWrite);\n }\n });\n }\n }\n handleInput(inputChunk: string) {\n // console.log(\"interaction handler handle input\", inputChunk);\n if (this.inputStreamForRegexMatcher) {\n this.inputStreamForRegexMatcher.push(inputChunk);\n }\n }\n // either use setOutputToNewReadable XOR setOutputWriter; not both\n setOutputToNewReadable(): Readable {\n const stdinReadable = new Readable();\n this.setOutputWriter((str) => stdinReadable.push(str));\n stdinReadable._read = () => {};\n return stdinReadable;\n }\n // either use setOutputToNewReadable XOR setOutputWriter; not both\n setOutputWriter(writeFn: (str: string) => void) {\n this.writeFn = writeFn;\n }\n private emitInput(input: string): void {\n if (this.writeFn) {\n this.writeFn(input);\n }\n }\n end() {\n if (this.inputStreamForRegexMatcher) {\n this.inputStreamForRegexMatcher.push(null);\n }\n }\n}\n","// src/task.model.ts\nimport type { TaskContext } from './runtime-base'; // Type-only import for RunFn definition\n\n/**\n * Generic object type for parameters and return values.\n */\nexport type ObjectType = { [key: string]: any };\n\n/**\n * Base type for task-specific parameters.\n */\nexport type TaskParams = ObjectType;\n\n/**\n * Represents the possible return values of a task's run function.\n */\nexport type RunFnReturnValue = ObjectType | void | undefined | null | Error;\n\n/**\n * Defines the signature of a task's main execution function.\n * It receives a TaskContext and returns a Promise of a RunFnReturnValue.\n */\nexport interface RunFn<TParams extends TaskParams = TaskParams, TReturn extends RunFnReturnValue = RunFnReturnValue> {\n (context: TaskContext<TParams>): Promise<TReturn>;\n}\n\n/**\n * Represents a task definition, including its run function and metadata.\n * This class is instantiated by the `task` factory function.\n */\nexport class Task<TParams extends TaskParams = TaskParams, TReturn extends RunFnReturnValue = RunFnReturnValue> {\n constructor(\n public runFn: RunFn<TParams, TReturn>,\n public taskModuleAbsolutePath?: string,\n public description?: string,\n public name?: string,\n ) {}\n}\n","import StackTracey from 'stacktracey';\n\n// StackTracey {\n// items: [\n// {\n// beforeParse: 'at REPL36:1:1',\n// callee: '',\n// index: false,\n// native: false,\n// file: 'REPL36',\n// line: 1,\n// column: 1,\n// calleeShort: '',\n// fileRelative: 'REPL36',\n// fileShort: 'REPL36',\n// fileName: 'REPL36',\n// thirdParty: false,\n// externalDomain: undefined\n// },\n// {\n// beforeParse: 'at ContextifyScript.runInThisContext (node:vm:136:12)',\n// callee: 'ContextifyScript.runInThisContext',\n// index: false,\n// native: false,\n// file: 'node:vm',\n// line: 136,\n// column: 12,\n// calleeShort: 'runInThisContext',\n// fileRelative: 'node:vm',\n// fileShort: 'node:vm',\n// fileName: 'node:vm',\n// thirdParty: false,\n// externalDomain: undefined\n// },\n// {\n// beforeParse: 'at REPLServer.defaultEval (node:repl:598:22)',\n// callee: 'REPLServer.defaultEval',\n// index: false,\n// native: false,\n// file: 'node:repl',\n// line: 598,\n// column: 22,\n// calleeShort: 'defaultEval',\n// fileRelative: 'node:repl',\n// fileShort: 'node:repl',\n// fileName: 'node:repl',\n// thirdParty: false,\n// externalDomain: undefined\n// },\n// {\n// beforeParse: 'at bound (node:domain:432:15)',\n// callee: 'bound',\n// index: false,\n// native: false,\n// file: 'node:domain',\n// line: 432,\n// column: 15,\n// calleeShort: 'bound',\n// fileRelative: 'node:domain',\n// fileShort: 'node:domain',\n// fileName: 'node:domain',\n// thirdParty: false,\n// externalDomain: undefined\n// },\n// {\n// beforeParse: 'at REPLServer.runBound (node:domain:443:12)',\n// callee: 'REPLServer.runBound',\n// index: false,\n// native: false,\n// file: 'node:domain',\n// line: 443,\n// column: 12,\n// calleeShort: 'runBound',\n// fileRelative: 'node:domain',\n// fileShort: 'node:domain',\n// fileName: 'node:domain',\n// thirdParty: false,\n// externalDomain: undefined\n// },\n// {\n// beforeParse: 'at REPLServer.preEval [as eval] (/home/david/.local/share/mise/installs/node/22.7.0/lib/node_modules/tsx/dist/patch-repl.cjs:1:366)',\n// callee: 'REPLServer.preEval [as eval]',\n// index: false,\n// native: false,\n// file: '/home/david/.local/share/mise/installs/node/22.7.0/lib/node_modules/tsx/dist/patch-repl.cjs',\n// line: 1,\n// column: 366,\n// calleeShort: 'preEval [as eval]',\n// fileRelative: '../../../../.local/share/mise/installs/node/22.7.0/lib/node_modules/tsx/dist/patch-repl.cjs',\n// fileShort: '../../../../.local/share/mise/installs/node/22.7.0/lib/node_modules/tsx/dist/patch-repl.cjs',\n// fileName: 'patch-repl.cjs',\n// thirdParty: false,\n// externalDomain: undefined\n// },\n// {\n// beforeParse: 'at process.processTicksAndRejections (node:internal/process/task_queues:105:5)',\n// callee: 'process.processTicksAndRejections',\n// index: false,\n// native: false,\n// file: 'node:internal/process/task_queues',\n// line: 105,\n// column: 5,\n// calleeShort: 'processTicksAndRejections',\n// fileRelative: 'node:internal/process/task_queues',\n// fileShort: 'node:internal/process/task_queues',\n// fileName: 'task_queues',\n// thirdParty: false,\n// externalDomain: undefined\n// }\n// ]\n// }\nexport function callstack() {\n return new StackTracey();\n}\n","import { callstack } from './stacktrace';\nimport { Path } from './flex/path';\nimport { Host } from './host'; // For TaskContext and IInvocation\nimport { Mutex } from 'async-mutex'; // For Invocation\nimport { type CommandResult, type EnvVarObj } from './command'; // For IInvocation & TaskContext\nimport { StringBuilder } from 'typescript-string-operations'; // For Invocation\nimport { Verbosity, type App, type AppConfig } from './app'; // For IRuntime and TaskContext\nimport type { ConfigFile } from './config-file'; // For IRuntime\nimport type { InteractionHandler } from './interaction-handler'; // For IRuntime\nimport type { SSHSession } from './ssh-session'; // For IRuntime\nimport chalk from 'chalk'; // For Invocation.exit logging\nimport {\n Task, // Value import\n type ObjectType, // Type import for use within this module\n type TaskParams, // Type import for use within this module\n type RunFnReturnValue, // Type import for use within this module\n type RunFn, // Type import for use within this module\n} from './task.model';\n\nexport type LogLevel = number; // Numerical log levels, compatible with Verbosity in app.ts\n// ObjectType, TaskParams, RunFnReturnValue, RunFn are now imported from task.model.ts\n\nexport interface FileSystemOperations {\n read: (path: string) => Promise<string>;\n write: (\n path: string,\n content: string,\n options?: { mode?: string | number; user?: string; group?: string },\n ) => Promise<void>;\n exists: (path: string) => Promise<boolean>;\n mkdir: (path: string, options?: { recursive?: boolean; mode?: string | number }) => Promise<void>;\n rm: (path: string, options?: { recursive?: boolean; force?: boolean }) => Promise<void>;\n // Consider adding stat, ls, etc. later\n}\n\nexport interface TaskContext<TParams extends TaskParams = TaskParams> {\n params: TParams;\n readonly id: string;\n readonly host?: Host;\n readonly config: AppConfig; // Access to resolved application configuration\n log: (level: LogLevel, ...message: any[]) => void; // Unified logging with level\n info: (...message: any[]) => void;\n debug: (...message: any[]) => void;\n warn: (...message: any[]) => void;\n error: (...message: any[]) => void;\n\n // exec is for running shell commands on the host\n exec: (\n command: string | string[],\n options?: {\n input?: Record<string, string>;\n sudo?: boolean;\n stdin?: string | Buffer;\n env?: EnvVarObj;\n cwd?: string;\n user?: string;\n pty?: boolean;\n },\n ) => Promise<CommandResult>; // Renamed from sh\n\n // ssh will ssh into a set of hosts and evaluate the given function for each host\n ssh: <TRemoteParams extends TaskParams = {}, TRemoteReturn extends RunFnReturnValue = RunFnReturnValue>(\n tags: string[],\n remoteTaskFn: (remoteContext: TaskContext<TRemoteParams>) => Promise<TRemoteReturn>,\n ) => Promise<Record<string, TRemoteReturn | Error>>;\n\n // run will run a given task script\n run: <TRunReturn extends RunFnReturnValue>(taskPartialFn: TaskPartialFn<TRunReturn>) => Promise<TRunReturn>;\n\n // getPassword will prompt the user for a password\n getPassword: () => Promise<string | undefined>;\n\n // getSecret will retrieve a secret from the application configuration\n getSecret: (name: string) => Promise<string | undefined>;\n\n // exit will exit the application\n exit: (exitCode: number, message?: string) => void;\n\n // inventory will return a list of hosts that match the given tags\n inventory: (tags: string[]) => Host[];\n file: FileSystemOperations; // File system operations contextualized to host\n}\n\n// RunFn and Task class are now imported from task.model.ts\n\nexport type TaskPartialFn<TReturn extends RunFnReturnValue = RunFnReturnValue> = (\n parentInvocation: IInvocation,\n) => Promise<TReturn>;\n\n// Task class is imported from task.model.ts\n\nexport interface TaskFn<TParams extends TaskParams = TaskParams, TReturn extends RunFnReturnValue = RunFnReturnValue> {\n (params?: TParams): TaskPartialFn<TReturn>;\n task: Task<TParams, TReturn>;\n}\n\nexport function task<TParams extends TaskParams, TReturn extends RunFnReturnValue>(\n runFn: RunFn<TParams, TReturn>,\n options?: { description?: string; name?: string },\n): TaskFn<TParams, TReturn> {\n const moduleThatTaskIsDefinedIn = Path.new(callstack().items[2].file).absolute().toString();\n const taskName = options?.name || 'anonymous_task';\n const taskInstance = new Task<TParams, TReturn>(runFn, moduleThatTaskIsDefinedIn, options?.description, taskName);\n\n const taskFnObject: TaskFn<TParams, TReturn> = function (params?: TParams) {\n return function (parentInvocation: IInvocation): Promise<TReturn> {\n return parentInvocation.invokeChildTask(taskFnObject, params ?? ({} as TParams)) as Promise<TReturn>;\n };\n } as TaskFn<TParams, TReturn>;\n Object.assign(taskFnObject, { task: taskInstance });\n\n return taskFnObject;\n}\n\nexport interface IInvocation<TParams extends TaskParams = any> {\n id: string;\n runtime: IRuntime;\n host?: Host;\n readonly config: AppConfig;\n log(level: LogLevel, ...message: any[]): void;\n info(...message: any[]): void;\n debug(...message: any[]): void;\n warn(...message: any[]): void;\n error(...message: any[]): void;\n exec(\n command: string | string[],\n options?: {\n input?: Record<string, string>;\n sudo?: boolean;\n stdin?: string | Buffer;\n env?: EnvVarObj;\n cwd?: string;\n user?: string;\n pty?: boolean;\n },\n ): Promise<CommandResult>;\n readonly file: FileSystemOperations;\n ssh<TRemoteParams extends TaskParams = {}, TRemoteReturn extends RunFnReturnValue = RunFnReturnValue>(\n tags: string[],\n remoteTaskFn: (remoteContext: TaskContext<TRemoteParams>) => Promise<TRemoteReturn>,\n ): Promise<Record<string, TRemoteReturn | Error>>;\n run<TRunReturn extends RunFnReturnValue>(taskPartialFn: TaskPartialFn<TRunReturn>): Promise<TRunReturn>;\n invokeChildTask<TTaskParams extends TaskParams, TTaskReturn extends RunFnReturnValue>(\n childTaskFn: TaskFn<TTaskParams, TTaskReturn>,\n params: TTaskParams,\n ): Promise<TTaskReturn>;\n getPassword(): Promise<string | undefined>;\n getSecret(name: string): Promise<string | undefined>;\n exit(exitCode: number, message?: string): void;\n inventory(tags: string[]): Host[];\n setDescription(description: string): void;\n setFutureResult(resultPromise: Promise<RunFnReturnValue>): void;\n appendChildInvocation(childInvocation: IInvocation<any>): Promise<void>;\n readonly stderr: string;\n readonly stdout: string;\n resultError(): Promise<Error | undefined>;\n getDescription(): string | undefined;\n getChildren(): ReadonlyArray<IInvocation<any>>;\n getResultPromise(): Promise<RunFnReturnValue>;\n}\n\nexport abstract class Invocation<TParams extends TaskParams = any> implements IInvocation<TParams> {\n public id: string;\n public children: Array<IInvocation<any>>; // Children can have any params\n private childrenMutex: Mutex;\n public description?: string;\n public stderrSB: StringBuilder;\n public stdoutSB: StringBuilder;\n public host?: Host;\n public result: Promise<RunFnReturnValue>;\n public resolveResult: (value: RunFnReturnValue | PromiseLike<RunFnReturnValue>) => void;\n public rejectResult: (reason?: any) => void;\n\n constructor(\n public runtime: IRuntime,\n public taskFnDefinition: TaskFn<TParams, any>,\n public parent?: IInvocation<any>,\n ) {\n this.id = crypto.randomUUID();\n this.children = [];\n this.childrenMutex = new Mutex();\n const { promise, resolve, reject } = Promise.withResolvers<RunFnReturnValue>();\n this.result = promise;\n this.resolveResult = resolve;\n this.rejectResult = reject;\n this.stdoutSB = new StringBuilder();\n this.stderrSB = new StringBuilder();\n }\n\n // Constructor and fields are above\n\n // Concrete method implementations\n getPassword(): Promise<string | undefined> {\n return this.runtime.getPassword();\n }\n\n async getSecret(name: string): Promise<string | undefined> {\n // Ensure config is available, typically via this.runtime.app.config\n // This might need adjustment if 'this.config' is the direct source.\n const secret = this.runtime.app.config.getSecret(name);\n if (!secret) {\n return undefined;\n }\n return secret.plaintext();\n }\n\n get stderr(): string {\n return this.stderrSB.toString();\n }\n\n get stdout(): string {\n return this.stdoutSB.toString();\n }\n\n info(...message: any[]) {\n this.log(Verbosity.INFO, ...message);\n }\n\n debug(...message: any[]) {\n this.log(Verbosity.DEBUG, ...message);\n }\n\n warn(...message: any[]) {\n this.log(Verbosity.WARN, ...message);\n }\n\n error(...message: any[]) {\n this.log(Verbosity.ERROR, ...message);\n }\n\n async resultError(): Promise<Error | undefined> {\n try {\n await this.result;\n return undefined;\n } catch (e) {\n return e as Error;\n }\n }\n\n setDescription(description: string) {\n this.description = description;\n }\n\n setFutureResult(resultPromise: Promise<RunFnReturnValue>) {\n resultPromise.then(this.resolveResult, this.rejectResult);\n }\n\n public getDescription(): string | undefined {\n return this.description;\n }\n public getChildren(): ReadonlyArray<IInvocation<any>> {\n return this.children;\n }\n public getResultPromise(): Promise<RunFnReturnValue> {\n return this.result;\n }\n\n public exit(exitCode: number, message?: string): void {\n if (message) {\n this.runtime.app.warn(\n chalk.yellow(`Task ${this.description || this.id} requested exit with code ${exitCode}: ${message}`),\n );\n }\n process.exit(exitCode);\n }\n\n inventory(tags: string[]): Host[] {\n return this.runtime.inventory(tags);\n }\n\n async appendChildInvocation(childInvocation: IInvocation<any>) {\n // Ensure IInvocation<any>\n await this.childrenMutex.runExclusive(async () => {\n this.children.push(childInvocation);\n });\n }\n\n // Abstract method declarations (must be implemented by subclasses)\n public abstract readonly config: AppConfig;\n public abstract log(level: LogLevel, ...message: any[]): void;\n public abstract exec(\n command: string | string[],\n options?: {\n input?: Record<string, string>;\n sudo: boolean;\n stdin?: string | Buffer;\n env?: EnvVarObj;\n cwd?: string;\n user?: string;\n pty?: boolean;\n },\n ): Promise<CommandResult>;\n public abstract readonly file: FileSystemOperations;\n public abstract ssh<TRemoteParams extends TaskParams = {}, TRemoteReturn extends RunFnReturnValue = RunFnReturnValue>(\n tags: string[],\n remoteTaskFn: (remoteContext: TaskContext<TRemoteParams>) => Promise<TRemoteReturn>,\n ): Promise<Record<string, TRemoteReturn | Error>>;\n public abstract run<TRunReturn extends RunFnReturnValue>(\n taskPartialFn: TaskPartialFn<TRunReturn>,\n ): Promise<TRunReturn>;\n public abstract invokeChildTask<TTaskParams extends TaskParams, TTaskReturn extends RunFnReturnValue>(\n childTaskFn: TaskFn<TTaskParams, TTaskReturn>,\n params: TTaskParams,\n ): Promise<TTaskReturn>;\n // Note: 'exit' has a concrete implementation above, so it's not abstract here.\n // Note: 'inventory' has a concrete implementation above, so it's not abstract here.\n}\n\nexport interface IRuntime {\n app: App;\n config?: { cwd?: string; configFile?: ConfigFile };\n interactionHandler: InteractionHandler;\n tmpDirRootPath: Path;\n\n getPassword(): Promise<string | undefined>;\n getSecret(name: string): Promise<string | undefined>;\n getTmpDir(): Path;\n getTmpFile(prefix?: string, postfix?: string, dir?: Path): Path;\n inventory(tags: string[]): Host[];\n invokeRootTask<TParams extends TaskParams, TReturn extends RunFnReturnValue>(\n taskFnDefinition: TaskFn<TParams, TReturn>,\n params: TParams,\n description?: string,\n ): Promise<IInvocation<TParams>>;\n}\n","import type { Signal } from 'human-signals';\nexport type { Signal };\nimport { A } from './flex/array';\nimport { V } from './flex/type';\nimport { parse, quote } from 'shell-quote';\nimport Shellwords from 'shellwords-ts';\n\nexport type EnvVarObj = Record<string, string>;\n\nexport class CommandResult {\n constructor(\n public stdout: string,\n public stderr: string,\n public exitCode: number,\n public signal?: Signal,\n ) {}\n\n toJSON() {\n return {\n stdout: this.stdout,\n stderr: this.stderr,\n exitCode: this.exitCode,\n signal: this.signal,\n success: this.success,\n failure: this.failure,\n };\n }\n get out() {\n return this.stdout;\n }\n get err() {\n return this.stderr;\n }\n get exit() {\n return this.exitCode;\n }\n get sig() {\n return this.signal;\n }\n get success() {\n return this.exitCode === 0;\n }\n get failure() {\n return !this.success;\n }\n}\n\nexport class Command {\n static parse(\n commandString: string,\n env?: EnvVarObj,\n ): {\n cmd: string;\n args: string[];\n env?: EnvVarObj;\n } {\n if (!commandString || commandString.trim() === '') {\n throw new Error('Command string cannot be empty.');\n }\n // const quotedCmd = quote([commandString]);\n // console.log(`parse: ${commandString} -> ${quotedCmd}`);\n // const parts = parse(quotedCmd);\n // console.log(`parts: ${parts}`);\n\n const parts = Shellwords.split(commandString);\n // console.log(`parts: ${JSON.stringify(parts)}`);\n\n const cmd_unsafe = A.head(parts);\n if (cmd_unsafe === undefined) {\n // This case should be prevented by the check for empty commandString earlier\n throw new Error(`Failed to parse command from string: \"${commandString}\". Resulted in no command part.`);\n }\n const cmd: string = cmd_unsafe;\n // console.log(cmd);\n const parsedArgs = A(parts).skipFirst(1);\n // console.log(parsedArgs);\n\n const args: string[] = A(parsedArgs).compact();\n // console.log(args);\n\n return {\n cmd,\n args,\n env,\n };\n }\n\n public cmd;\n public args?;\n public cwd?: string;\n public env?: Record<string, string>;\n public result?: CommandResult;\n\n constructor(opts: {\n cmd: string;\n args?: string[];\n cwd?: string;\n env?: Record<string, string>;\n result?: CommandResult;\n }) {\n const { cmd, args, cwd, env, result } = opts;\n this.cmd = cmd;\n this.args = args;\n this.cwd = cwd;\n this.env = env;\n this.result = result;\n }\n\n isRunning(): boolean {\n return !!this.result;\n }\n\n toJSON() {\n return {\n cmd: this.cmd,\n args: this.args,\n cwd: this.cwd,\n env: this.env,\n result: this.result?.toJSON(),\n };\n }\n}\n","import Handlebars from 'handlebars';\nimport {\n type IInvocation,\n Invocation,\n type IRuntime,\n type TaskContext,\n type TaskFn,\n type TaskParams,\n type RunFnReturnValue,\n type TaskPartialFn,\n type LogLevel,\n RemoteRuntime,\n RemoteInvocation,\n task,\n type RunFn, // Consolidate LogLevel import here\n} from './runtime'; // Source all from ./runtime\nimport { Host } from './host';\nimport { Path } from './flex/path';\nimport { type App, type AppConfig, Verbosity } from './app';\n// LogLevel is now imported from ./runtime\nimport * as fs from 'node:fs';\nimport { ConfigFile } from './config-file';\n// CommandResult is now a value import, Command class is also imported directly\nimport { Command, CommandResult, type EnvVarObj } from './command';\nimport { InteractionHandler } from './interaction-handler';\n// import { PtyCommand } from \"./pty-command\";\nimport { RusPtyCommand } from './ruspty-command';\nimport { O } from './flex/object';\nimport { VP } from './flex/pipe';\nimport { A } from './flex/array';\nimport chalk from 'chalk';\nimport { V } from './flex/type';\nimport { withSudo } from './util/input-helpers';\n\nexport interface FileSystemOperations {\n read: (path: string) => Promise<string>;\n write: (\n path: string,\n content: string,\n options?: { mode?: string | number | undefined; user?: string | undefined; group?: string | undefined },\n ) => Promise<void>;\n exists: (path: string) => Promise<boolean>;\n mkdir: (\n path: string,\n options?: { recursive?: boolean | undefined; mode?: string | number | undefined },\n ) => Promise<void>;\n rm: (path: string, options?: { recursive?: boolean | undefined; force?: boolean | undefined }) => Promise<void>;\n}\n\nexport class LocalInvocation<TParams extends TaskParams, TReturn extends RunFnReturnValue> extends Invocation<TParams> {\n public readonly config: AppConfig;\n public readonly file: FileSystemOperations;\n constructor(\n public runtime: LocalRuntime,\n public taskFnDefinition: TaskFn<TParams, TReturn>,\n params: TParams,\n parent?: IInvocation<any>,\n ) {\n super(runtime, taskFnDefinition, parent);\n this.description = Handlebars.compile(\n taskFnDefinition.task.description || taskFnDefinition.task.name || 'anonymous_local_task',\n )(params);\n this.config = this.runtime.app.config; // Access getter, not method\n // this.host is undefined for LocalInvocation, which is fine as TaskContext.host is optional.\n\n this.file = {\n read: async (path: string): Promise<string> => fs.promises.readFile(path, 'utf-8'),\n write: async (\n path: string,\n content: string,\n options?: { mode?: string | number | undefined; user?: string | undefined; group?: string | undefined },\n ): Promise<void> => fs.promises.writeFile(path, content, { mode: options?.mode as fs.Mode | undefined }),\n exists: async (path: string): Promise<boolean> => {\n try {\n await fs.promises.access(path);\n return true;\n } catch {\n return false;\n }\n },\n mkdir: async (\n path: string,\n options?: { recursive?: boolean | undefined; mode?: string | number | undefined },\n ): Promise<void> => {\n await fs.promises.mkdir(path, options as fs.MakeDirectoryOptions | undefined);\n },\n rm: async (\n path: string,\n options?: { recursive?: boolean | undefined; force?: boolean | undefined },\n ): Promise<void> => fs.promises.rm(path, options as fs.RmOptions | undefined),\n };\n }\n\n public log(level: LogLevel, ...message: any[]): void {\n this.runtime.app.log(level, ...message);\n }\n\n override async exec(\n command: string | string[],\n options: {\n input?: Record<string, string>;\n sudo?: boolean;\n stdin?: string | Buffer;\n env?: EnvVarObj;\n cwd?: string;\n user?: string;\n pty?: boolean;\n } = {},\n ): Promise<CommandResult> {\n options = options || {};\n\n const interactionHandler = this.runtime.interactionHandler.clone();\n const stdinForCommand: string | Buffer | undefined = options.stdin;\n\n if (options.input && typeof options.input === 'object') {\n // Input is for interaction handler patterns\n O(options.input).each(([pattern, value]: [string, string]) => {\n interactionHandler.map(pattern, value);\n });\n }\n\n if (options.sudo) {\n const hostPassword = await this.runtime.getPassword();\n interactionHandler.mapInput(withSudo(hostPassword));\n }\n\n // InteractionHandler is for responding to prompts, not for initial stdin.\n\n // TODO: Handle options.user if specified (e.g., via sudo -u)\n // TODO: options.pty is implicitly true due to PtyCommand. If false, would need a non-PTY command runner.\n\n const cwd = options.cwd ?? process.cwd();\n let finalEnv: EnvVarObj = {};\n\n if (options.env) {\n finalEnv = options.env;\n } else {\n // Ensure process.env values are filtered for undefined\n Object.keys(process.env).forEach((key) => {\n const value = process.env[key];\n if (value !== undefined) {\n finalEnv[key] = value;\n }\n });\n }\n\n let commandInstance: RusPtyCommand;\n if (command instanceof Array) {\n // command = PtyCommand.fromArray(cmd, finalEnv, cwd);\n commandInstance = RusPtyCommand.fromArray(command, finalEnv, cwd);\n } else {\n // command = PtyCommand.fromString(cmd, finalEnv, cwd);\n commandInstance = RusPtyCommand.fromString(command, finalEnv, cwd);\n }\n\n this.log(\n Verbosity.DEBUG as LogLevel,\n `Executing command: ${Array.isArray(command) ? command.join(' ') : command}${options.stdin ? ' with stdin' : ''}${options.input ? ' with interaction patterns' : ''}`,\n );\n await commandInstance.run(interactionHandler, stdinForCommand);\n\n const cmdResult = commandInstance.result;\n if (!cmdResult) {\n this.log(Verbosity.ERROR as LogLevel, 'Command execution resulted in undefined result.');\n // Return a new CommandResult instance for the error case\n return new CommandResult('', 'Command execution resulted in undefined result.', -1, undefined);\n }\n // Output is already captured by PtyCommand and available in cmdResult.stdout/stderr\n // Task authors can log it if they wish using this.log(LogLevel.INFO, cmdResult.stdout)\n // For now, we don't auto-log stdout/stderr here to avoid duplication if task also logs.\n\n return cmdResult;\n }\n\n override async ssh<TRemoteParams extends TaskParams = {}, TRemoteReturn extends RunFnReturnValue = RunFnReturnValue>(\n tags: string[],\n remoteTaskFn: (remoteContext: TaskContext<TRemoteParams>) => Promise<TRemoteReturn>,\n ): Promise<Record<string, TRemoteReturn | Error>> {\n const targetHosts: Host[] = this.runtime.app.querySelectedInventory(tags);\n\n if (targetHosts.length === 0) {\n this.runtime.app.warn(`No hosts found for tags: ${tags.join(', ')} in ssh call from ${this.id}`);\n return {};\n }\n\n const entryPromises = VP(targetHosts).map(async (host: Host): Promise<[string, TRemoteReturn | Error]> => {\n const result = await this.runRemoteTaskOnHost<TRemoteParams, TRemoteReturn>(host, remoteTaskFn);\n return [host.hostname, result];\n }).value;\n\n const entries = await Promise.all(entryPromises);\n const record: Record<string, TRemoteReturn | Error> = Object.fromEntries(entries);\n return record;\n }\n\n async runRemoteTaskOnHost<TRemoteParams extends TaskParams, TRemoteReturn extends RunFnReturnValue>(\n host: Host,\n remoteTaskFn: RunFn<TRemoteParams, TRemoteReturn>,\n ): Promise<TRemoteReturn | Error> {\n this.debug(`Run function on: ${chalk.yellow(V.inspect(host.toObject()))}`);\n\n const interactionHandler = new InteractionHandler(this.runtime.app.getSecretsForHost(host.hostname));\n\n const remoteRuntime = new RemoteRuntime(\n this.runtime.app,\n host,\n this.runtime, // The LocalRuntime instance of this LocalInvocation\n interactionHandler,\n );\n\n try {\n const connected = await remoteRuntime.connect();\n if (!connected) {\n throw new Error(`Unable to connect to ${host.uri}`);\n }\n\n const adHocRemoteInvocationTaskFn = task<TRemoteParams, TRemoteReturn>(\n async function (context: TaskContext<TRemoteParams>): Promise<TRemoteReturn> {\n return remoteTaskFn(context);\n },\n { description: `Ad-hoc task on ${host.uri} via ssh from ${this.taskFnDefinition.task.name} (${this.id})` },\n );\n\n const rootRemoteInvocation = new RemoteInvocation(\n remoteRuntime,\n adHocRemoteInvocationTaskFn, // This TaskFn is for the container of the ad-hoc operation on this host\n {} as TRemoteParams,\n this, // Parent is the current LocalInvocation\n host,\n );\n await this.appendChildInvocation(rootRemoteInvocation);\n\n const rootRemoteContext = this.runtime.app.taskContextForRunFn(\n rootRemoteInvocation,\n {} as TRemoteParams,\n host,\n ) as TaskContext<TRemoteParams>;\n const resultPromise = remoteTaskFn(rootRemoteContext);\n rootRemoteInvocation.setFutureResult(resultPromise);\n rootRemoteInvocation.setDescription(`SSH to ${host.uri}`);\n\n return await resultPromise;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n this.runtime.app.error(\n `Error during SSH operation to ${host.uri}: ${errorMessage}`,\n error instanceof Error ? error.stack : undefined,\n );\n return error instanceof Error ? error : new Error(errorMessage);\n } finally {\n await remoteRuntime.disconnect();\n }\n }\n\n public exit(exitCode: number, message?: string): void {\n if (message) {\n this.log(exitCode === 0 ? (Verbosity.INFO as LogLevel) : (Verbosity.ERROR as LogLevel), message);\n }\n // In a library context, actually calling process.exit() is often undesirable.\n // Throwing a specific error might be better for the app to handle.\n // For now, keeping it simple, but this could be a point of future refinement.\n this.runtime.app.warn(`Task ${this.id} requested exit with code ${exitCode}. Forcing process exit.`);\n process.exit(exitCode);\n }\n\n public inventory(tags: string[]): Host[] {\n return this.runtime.app.queryInventory(new Set(tags));\n }\n\n override async run<TRunReturn extends RunFnReturnValue>(\n taskPartialFn: TaskPartialFn<TRunReturn>,\n ): Promise<TRunReturn> {\n return taskPartialFn(this);\n }\n\n override async invokeChildTask<TTaskParams extends TaskParams, TTaskReturn extends RunFnReturnValue>(\n childTaskFnDefinition: TaskFn<TTaskParams, TTaskReturn>,\n params: TTaskParams,\n ): Promise<TTaskReturn> {\n const childInvocation = new LocalInvocation(this.runtime, childTaskFnDefinition, params, this);\n await this.appendChildInvocation(childInvocation);\n\n const loggedChildResultPromise = childInvocation.result\n .then((value) => {\n if (value instanceof Error) return value;\n if (value === undefined || value === null) return undefined;\n return String(value);\n })\n .catch((error) => error);\n this.runtime.app.taskTree.add(\n childInvocation.id,\n this.id,\n childTaskFnDefinition.task.name || 'anonymous_child_task',\n loggedChildResultPromise,\n );\n\n const taskContext = this.runtime.app.taskContextForRunFn(\n childInvocation,\n params,\n undefined /* host is undefined for local */,\n ) as TaskContext<TTaskParams>;\n\n try {\n const result = await childTaskFnDefinition.task.runFn.call(childInvocation, taskContext);\n childInvocation.resolveResult(result);\n return result as TTaskReturn;\n } catch (error) {\n childInvocation.rejectResult(error as Error);\n throw error;\n }\n }\n}\n\nexport class LocalRuntime implements IRuntime {\n public config?: { cwd?: string; configFile?: ConfigFile };\n public host: Host; // Represents the local machine\n private memoizedPassword?: string;\n\n constructor(\n public app: App,\n public localBundlePath: Path,\n public interactionHandler: InteractionHandler = new InteractionHandler(),\n ) {\n const appConfigInstance = this.app.config;\n if (appConfigInstance instanceof ConfigFile) {\n this.host = new Host(appConfigInstance, { hostname: 'localhost' });\n } else {\n const configType = appConfigInstance?.constructor?.name || typeof appConfigInstance;\n this.app.error(\n `CRITICAL ERROR: LocalRuntime could not initialize its 'localhost' Host object. The application's configuration (type: ${configType}) is not a file-based configuration (expected ConfigFile).`,\n );\n throw new Error(\n `LocalRuntime init failed: Expected app.config to be an instance of ConfigFile for 'localhost' Host, but got ${configType}.`,\n );\n }\n this.config = {\n cwd: process.cwd(),\n configFile: appConfigInstance instanceof ConfigFile ? appConfigInstance : undefined,\n };\n }\n\n get tmpDirRootPath(): Path {\n return this.app.hostctlTmpDir();\n }\n\n async getPassword(): Promise<string | undefined> {\n if (this.memoizedPassword) {\n return this.memoizedPassword;\n }\n this.memoizedPassword = await this.app.promptPassword('Enter local sudo password:');\n return this.memoizedPassword;\n }\n\n async getSecret(name: string): Promise<string | undefined> {\n const secret = this.app.config.getSecret(name);\n if (!secret) {\n this.app.warn(`Secret ${name} not found in config.`);\n return undefined;\n }\n return secret.plaintext();\n }\n\n getTmpDir(): Path {\n return this.app.createNamedTmpDir();\n }\n\n getTmpFile(prefix?: string | undefined, postfix?: string | undefined, dir?: Path | undefined): Path {\n const tmpDir = dir || this.getTmpDir();\n // Use crypto.randomUUID() for a unique filename component\n const randomName = prefix ? `${prefix}-${crypto.randomUUID()}` : crypto.randomUUID();\n const finalName = postfix ? `${randomName}-${postfix}` : randomName;\n return tmpDir.join(finalName);\n }\n\n inventory(tags: string[]): Host[] {\n return this.app.queryInventory(new Set(tags));\n }\n\n async invokeRootTask<TParams extends TaskParams, TReturn extends RunFnReturnValue>(\n taskFnDefinition: TaskFn<TParams, TReturn>,\n params: TParams,\n description?: string,\n ): Promise<LocalInvocation<TParams, TReturn>> {\n const rootInvocation = new LocalInvocation<TParams, TReturn>(\n this,\n taskFnDefinition,\n params,\n undefined /* no parent */,\n );\n if (description) {\n rootInvocation.description = description;\n }\n const loggedRootResultPromise = rootInvocation.result\n .then((value) => {\n if (value instanceof Error) return value;\n if (value === undefined || value === null) return undefined;\n return String(value);\n })\n .catch((error) => error);\n this.app.taskTree.add(\n rootInvocation.id,\n null,\n taskFnDefinition.task.name || 'anonymous_root_task',\n loggedRootResultPromise,\n );\n\n // Corrected to call taskContextForRunFn on this.app instead of this.app.taskTree\n const taskContext = this.app.taskContextForRunFn(\n rootInvocation,\n params,\n undefined /* host is undefined */,\n ) as TaskContext<TParams>;\n\n taskFnDefinition.task.runFn\n .call(rootInvocation, taskContext)\n .then(rootInvocation.resolveResult)\n .catch(rootInvocation.rejectResult);\n\n return rootInvocation;\n }\n}\n","import { Pty } from '@replit/ruspty';\nimport { StringBuilder } from 'typescript-string-operations';\n\nimport { Command, CommandResult, type EnvVarObj } from './command';\nimport { InteractionHandler } from './interaction-handler';\nimport { signalsByNumber } from 'human-signals';\nimport { O } from './flex/object';\nimport { A } from './flex/array';\n\nexport class RusPtyCommand extends Command {\n static fromArray(commandWithArgs: string[], env?: EnvVarObj, cwd?: string): RusPtyCommand {\n const envObj: EnvVarObj = O(env || {}).map(([key, value]: [string, string | undefined]) => [key, String(value)]);\n const cmd: string = commandWithArgs[0] || ''; // Use direct access and provide a fallback\n const parsedArgs = commandWithArgs.slice(1);\n const args: string[] = parsedArgs.filter((arg) => arg !== null && arg !== undefined && arg !== ''); // Simplified compact\n\n return new RusPtyCommand({ cmd, args, cwd, env: envObj });\n }\n\n static fromString(command: string, env?: EnvVarObj, cwd?: string): RusPtyCommand {\n const envObj: EnvVarObj = O(env || {}).map(([key, value]: [string, string | undefined]) => [key, String(value)]);\n const { cmd, args } = this.parse(command, envObj);\n return new RusPtyCommand({ cmd, args, cwd, env: envObj });\n }\n\n public process!: Pty; // Definite assignment assertion\n\n async run(interactionHandler = new InteractionHandler(), stdin?: string | Buffer): Promise<CommandResult> {\n const self = this;\n return new Promise<CommandResult>(function (resolve, reject) {\n const stdout = new StringBuilder();\n // console.log(`Pty> ${self.cmd} ${self.args}`);\n self.process = new Pty({\n command: self.cmd,\n args: self.args,\n dir: self.cwd,\n envs: self.env as Record<string, string>,\n interactive: true,\n size: { rows: 30, cols: 80 },\n onExit: (err: null | Error, exitCode: number) => {\n interactionHandler.end();\n // console.log(`exit code: ${exitCode}`);\n // console.log(`exit signal: ${signal}`);\n // const signalObj = signalsByNumber[signal || 10000];\n const signalObj = undefined;\n const commandResult = new CommandResult(stdout.toString(), '', exitCode, signalObj);\n self.result = commandResult;\n resolve(commandResult);\n },\n });\n\n const read = self.process.read;\n const write = self.process.write;\n\n if (stdin) {\n // console.log(`Pty> stdin: ${stdin}`);\n write.write(stdin);\n // Consider self.process.end() or write.write('\\x04') if EOF is needed.\n }\n\n interactionHandler.begin();\n interactionHandler.setOutputWriter((str) => write.write(str));\n\n read.on('data', (chunk) => {\n stdout.append(chunk);\n interactionHandler.handleInput(chunk);\n });\n });\n }\n}\n","/**\n * An object representing the mapping of expected output (as a regex string)\n * to the input that should be provided in response.\n */\nexport type InputMap = Record<string, string>;\n\nexport const CHECKMARK = '\\u2713';\nexport const XMARK = '\\u2717';\n\n/**\n * A collection of regular expressions to detect various sudo/doas password prompts\n * across different operating systems.\n */\nexport const SUDO_PROMPT_REGEX = {\n /**\n * Matches the default sudo prompt on most Linux distributions.\n * Example: `[sudo] password for <username>:`\n */\n LINUX: '\\\\[sudo\\\\] password',\n\n /**\n * Matches the default sudo prompt on macOS and some BSD systems.\n * Example: `Password:`\n */\n MAC_BSD: '^Password:',\n\n /**\n * Matches the default prompt for `doas` on OpenBSD.\n * Example: `doas (username@hostname) password:`\n */\n DOAS: 'doas \\\\(.*\\\\) password:',\n};\n\n/**\n * A helper function that builds an input map to handle various sudo/doas password prompts.\n * This is useful for building up interaction handlers for commands that require privilege escalation\n * across different operating systems.\n *\n * @param password The sudo/doas password to provide.\n * @param existingInputMap An optional existing map of interactions.\n * @returns A new input map containing the sudo/doas prompt interactions and any existing interactions.\n */\nexport function withSudo(password: string | undefined, existingInputMap: InputMap = {}): InputMap {\n if (!password) {\n return existingInputMap;\n }\n const passwordResponse = `${password}\\n`;\n return {\n ...existingInputMap,\n [SUDO_PROMPT_REGEX.LINUX]: passwordResponse,\n [SUDO_PROMPT_REGEX.MAC_BSD]: passwordResponse,\n [SUDO_PROMPT_REGEX.DOAS]: passwordResponse,\n };\n}\n","import Handlebars from 'handlebars';\nimport {\n type IInvocation,\n Invocation,\n type IRuntime,\n type TaskFn,\n type TaskContext,\n type TaskParams,\n type RunFnReturnValue,\n type ObjectType,\n type TaskPartialFn,\n Task, // Use Task directly\n type FileSystemOperations,\n type LogLevel, // Consolidate LogLevel import here\n} from './runtime'; // Source all from ./runtime\nimport * as path from 'node:path';\nimport type { LocalRuntime } from './local-runtime'; // For config inheritance\nimport { Host } from './host';\nimport type { Config as NodeSSHConfig } from 'node-ssh'; // For SSH connection options\nimport { Path } from './flex/path';\nimport { Verbosity, type App, type AppConfig } from './app';\n// LogLevel is now imported from ./runtime\nimport { CommandResult, type EnvVarObj, Command, type Signal } from './command';\nimport { InteractionHandler } from './interaction-handler';\nimport { SSHSession } from './ssh-session';\nimport { isError } from './error';\nimport chalk from 'chalk';\nimport * as util from 'node:util';\nimport { StringBuilder } from 'typescript-string-operations';\nimport { ConfigFile } from './config-file';\nimport { O } from './flex/object';\nimport { match, P } from 'ts-pattern';\nimport { V } from './flex/type';\nimport { withSudo, type InputMap } from './util/input-helpers';\n\nexport class RemoteInvocation<\n TParams extends TaskParams = any,\n TReturn extends RunFnReturnValue = any,\n> extends Invocation<TParams> {\n public readonly config: AppConfig;\n public readonly file: FileSystemOperations;\n // sshSession is removed from RemoteInvocation, it will be managed by RemoteRuntime\n\n constructor(\n runtime: IRuntime,\n public taskFnDefinition: TaskFn<TParams, TReturn>,\n params: TParams,\n public parent: IInvocation<any>,\n public hostInstance?: Host,\n ) {\n super(runtime, taskFnDefinition, parent);\n this.description = Handlebars.compile(\n taskFnDefinition.task.description || taskFnDefinition.task.name || 'anonymous_remote_task',\n )(params);\n this.host = hostInstance || parent.host; // Inherit host from parent if not provided\n if (!this.host) {\n throw new Error('RemoteInvocation must have a host.');\n }\n this.config = this.runtime.app.config;\n\n this.file = {\n read: async (filePath: string): Promise<string> => {\n const sftp = await this.ensureSftp();\n const remotePath = this.resolveRemotePath(filePath);\n return new Promise<string>((resolve, reject) => {\n sftp.readFile(remotePath, (err: Error | null, data: Buffer | undefined) => {\n if (err) {\n return reject(err);\n }\n if (!data) {\n // Should not happen if err is null, but good practice\n return reject(new Error(`SFTP readFile returned no data for ${remotePath}`));\n }\n resolve(data.toString('utf-8'));\n });\n });\n },\n write: async (filePath: string, content: string, options?: { mode?: string | number }): Promise<void> => {\n const sftp = await this.ensureSftp();\n const remotePath = this.resolveRemotePath(filePath);\n await sftp.writeFile(remotePath, content, { mode: options?.mode as number | undefined });\n },\n exists: async (filePath: string): Promise<boolean> => {\n const sftp = await this.ensureSftp();\n const remotePath = this.resolveRemotePath(filePath);\n return new Promise((resolve, reject) => {\n sftp.stat(remotePath, (err: Error | null, stats: any) => {\n // stats type might need refinement from ssh2 types\n if (err) {\n // Common SFTP error codes for 'No such file' are 2 (SSH_FX_NO_SUCH_FILE from ssh2-streams constants)\n // node-ssh might wrap this, check error object structure\n const sftpError = err as any;\n if (\n sftpError.code === 2 ||\n sftpError.code === 'ENOENT' ||\n (typeof err.message === 'string' &&\n (err.message.includes('No such file') || err.message.includes('No such entity')))\n ) {\n resolve(false);\n } else {\n reject(err);\n }\n } else {\n resolve(true);\n }\n });\n });\n },\n mkdir: async (dirPath: string, options?: { recursive?: boolean; mode?: string | number }): Promise<void> => {\n const remoteDir = this.resolveRemotePath(dirPath);\n let command = `mkdir ${options?.recursive ? '-p ' : ''}${this.quoteRemoteArg(remoteDir)}`;\n await this.exec(command); // Use this.exec for consistency\n if (options?.mode) {\n await this.exec(`chmod ${this.quoteRemoteArg(String(options.mode))} ${this.quoteRemoteArg(remoteDir)}`);\n }\n },\n rm: async (itemPath: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> => {\n const remoteItem = this.resolveRemotePath(itemPath);\n const command = `rm ${options?.recursive ? '-r ' : ''}${options?.force ? '-f ' : ''}${this.quoteRemoteArg(remoteItem)}`;\n await this.exec(command); // Use this.exec for consistency\n },\n };\n }\n\n private async ensureSftp(): Promise<any> {\n // Return type should be the actual SFTP client type from node-ssh\n if (!(this.runtime instanceof RemoteRuntime)) {\n throw new Error('Runtime is not a RemoteRuntime instance, cannot ensure SFTP.');\n }\n // Delegate to RemoteRuntime to get the SFTP client\n return this.runtime.getSftpClient();\n }\n\n private resolveRemotePath(p: string): string {\n // Assuming paths are either absolute or relative to the user's home directory on the remote host\n // node-ssh's SFTP methods generally treat non-absolute paths as relative to home.\n // For exec, CWD handling is separate.\n return p; // Keep it simple for now, let node-ssh handle path resolution relative to home for SFTP.\n }\n\n private quoteRemoteArg(arg: string): string {\n return \"'\" + arg.replace(/'/g, \"'\\\\''\") + \"'\";\n }\n\n public log(level: LogLevel, ...message: any[]): void {\n const hostUri = this.host ? `${this.host.user || ''}@${this.host.hostname}` : 'unknown-host'; // Changed host to hostname\n this.runtime.app.log(level, `[${hostUri}|${this.id}|${this.description || 'task'}]`, ...message);\n }\n\n uri(): string {\n if (!this.host) throw new Error('Host is not defined for this remote invocation.');\n return `${this.host.user || this.runtime.app.defaultSshUser()}@${this.host.hostname}`; // Changed host to hostname\n }\n\n override async exec(\n command: string | string[],\n options?: {\n input?: InputMap;\n sudo?: boolean;\n stdin?: string | Buffer;\n env?: Record<string, string>;\n cwd?: string;\n user?: string;\n pty?: boolean;\n },\n ): Promise<CommandResult> {\n if (!this.host) throw new Error('Host is not defined for exec command in RemoteInvocation.');\n\n if (!(this.runtime instanceof RemoteRuntime)) {\n throw new Error('Runtime is not a RemoteRuntime instance, cannot execute remote command.');\n }\n\n const stdinForRemoteCommand: string | Buffer | undefined = options?.stdin;\n // Start with a clone of the runtime's default handler.\n // This handler can be augmented with exec-specific patterns.\n const execSpecificInteractionHandler = this.runtime.interactionHandler.clone();\n\n if (options?.input) {\n execSpecificInteractionHandler.mapInput(options.input);\n }\n\n if (options?.sudo) {\n const hostPassword = await this.runtime.getPassword();\n execSpecificInteractionHandler.mapInput(withSudo(hostPassword));\n }\n\n // TODO: Add support to run command as another user\n // let commandToRun = Array.isArray(command) ? command.join(\" \") : command;\n // if (options?.user) {\n // commandToRun = `sudo -u ${this.quoteRemoteArg(options.user)} -- /bin/sh -c ${this.quoteRemoteArg(commandToRun)}`;\n // }\n\n this.debug(`Executing remote command on ${this.host.hostname}: ${command}`); // Changed host to hostname\n\n const cmdOrErr = await this.runtime.executeCommand(command, {\n cwd: options?.cwd,\n stdin: stdinForRemoteCommand,\n pty: options?.pty,\n env: options?.env,\n interactionHandler: execSpecificInteractionHandler, // Pass the potentially augmented handler\n });\n\n return match(cmdOrErr)\n .with(P.instanceOf(Error), (err: Error) => {\n throw err;\n })\n .with(P.instanceOf(Command), (command: Command) => {\n return command.result!;\n })\n .exhaustive();\n }\n\n public exit(exitCode: number, message?: string): void {\n const hostUri = this.host ? `${this.host.user || ''}@${this.host.hostname}` : 'unknown-host'; // Changed host to hostname\n const msg = `Remote task ${this.id} on ${hostUri} requested exit with code ${exitCode}${message ? ': ' + message : ''}`;\n this.log(Verbosity.WARN as LogLevel, msg);\n // Throwing an error is more appropriate than trying to force a remote process.exit()\n throw new Error(msg);\n }\n\n public inventory(tags: string[]): Host[] {\n return this.runtime.app.queryInventory(new Set(tags));\n }\n\n override async run<TRunReturn extends RunFnReturnValue>(\n taskPartialFn: TaskPartialFn<TRunReturn>,\n ): Promise<TRunReturn> {\n return taskPartialFn(this);\n }\n\n override async invokeChildTask<TTaskParams extends TaskParams, TTaskReturn extends RunFnReturnValue>(\n childTaskFnDefinition: TaskFn<TTaskParams, TTaskReturn>,\n params: TTaskParams,\n ): Promise<TTaskReturn> {\n if (!this.host) throw new Error('Host is not defined for invokeChildTask in RemoteInvocation.');\n\n const childInvocation = new RemoteInvocation(this.runtime, childTaskFnDefinition, params, this, this.host);\n await this.appendChildInvocation(childInvocation);\n\n this.runtime.app.taskTree.add(\n childInvocation.id,\n this.id,\n childTaskFnDefinition.task.name || 'anonymous_remote_child_task',\n childInvocation.result.then((r) => (r === null ? undefined : r)) as Promise<string | Error | undefined>,\n );\n\n const taskContext = this.runtime.app.taskContextForRunFn(\n childInvocation,\n params,\n this.host,\n ) as TaskContext<TTaskParams>;\n\n try {\n const result = await childTaskFnDefinition.task.runFn.call(childInvocation, taskContext);\n childInvocation.resolveResult(result);\n return result as TTaskReturn;\n } catch (error) {\n childInvocation.rejectResult(error as Error);\n throw error;\n } // End of catch block for invokeChildTask\n } // End of invokeChildTask method\n\n override ssh<TRemoteParams extends TaskParams = {}, TRemoteReturn extends RunFnReturnValue = RunFnReturnValue>(\n tags: string[],\n remoteTaskFn: (remoteContext: TaskContext<TRemoteParams>) => Promise<TRemoteReturn>,\n ): Promise<Record<string, TRemoteReturn | Error>> {\n throw new Error('ssh from a remote host is not currently supported.');\n }\n} // End of RemoteInvocation class\n\nexport class RemoteRuntime implements IRuntime {\n private sftpClientInstance?: any; // Type should be SFTPWrapper from 'node-ssh'\n public readonly app: App;\n public readonly host: Host;\n public readonly interactionHandler: InteractionHandler;\n private sshSession: SSHSession;\n\n constructor(\n app: App,\n host: Host,\n _localRuntime: LocalRuntime,\n interactionHandler: InteractionHandler = new InteractionHandler(),\n ) {\n this.app = app;\n this.host = host;\n this.interactionHandler = interactionHandler;\n this.sshSession = new SSHSession(); // Initialize SSH session for this host for context\n }\n\n get tmpDirRootPath(): Path {\n return new Path('/tmp');\n }\n\n async getPassword(): Promise<string | undefined> {\n return await this.host.decryptedPassword();\n }\n\n async getSecret(name: string): Promise<string | undefined> {\n const secret = this.app.config.getSecret(name);\n if (!secret) {\n this.app.warn(`Secret ${name} not found in config.`);\n return undefined;\n }\n return secret.plaintext();\n }\n\n getTmpDir(): Path {\n return this.tmpDirRootPath.join(this.app.randName());\n }\n\n getTmpFile(prefix?: string | undefined, postfix?: string | undefined, dir?: Path | undefined): Path {\n const tmpDir = dir || this.getTmpDir();\n return tmpDir.join(this.app.randName());\n }\n\n inventory(tags: string[]): Host[] {\n return this.app.queryInventory(new Set(tags));\n }\n\n async connect(): Promise<boolean> {\n if (this.sshSession.isConnected() && this.sftpClientInstance) {\n this.app.debug(`RemoteRuntime: SSH session and SFTP already connected to ${this.host.uri}`);\n return true;\n }\n\n this.app.debug(`RemoteRuntime: Connecting SSH to ${this.host.uri}...`);\n\n const sshConnectOpts: NodeSSHConfig = {\n host: this.host.hostname, // Changed from this.host.host\n username: this.host.user || this.app.defaultSshUser(), // Assuming defaultSshUser on App\n port: this.host.port, // node-ssh parses port from host string if present\n privateKey: await this.host.plaintextSshKeyPath(),\n password: await this.host.decryptedPassword(),\n };\n\n try {\n if (!this.sshSession.isConnected()) {\n await this.sshSession.connect(sshConnectOpts);\n this.app.debug(`RemoteRuntime: SSH connected to ${this.host.uri}`);\n }\n\n this.app.debug(`RemoteRuntime: Requesting SFTP client for ${this.host.uri}`);\n this.sftpClientInstance = await this.sshSession.sftp();\n this.app.debug(`RemoteRuntime: SFTP client ready for ${this.host.uri}`);\n } catch (e: any) {\n this.app.error(`RemoteRuntime: SSH connection or SFTP setup to ${this.host.uri} failed: ${e.message}`);\n if (this.sshSession.isConnected()) {\n await this.sshSession.disconnect().catch((err: Error) => {\n this.app.error(`RemoteRuntime: Error during disconnect after failed connect/sftp: ${err.message}`);\n });\n }\n this.sftpClientInstance = undefined; // Clear sftp client on error\n throw e;\n }\n\n return this.sshSession.isConnected();\n }\n\n async getSftpClient(): Promise<any> {\n // Replace 'any' with actual SFTP client type (e.g., from 'node-ssh')\n await this.connect(); // Ensures connection and SFTP client are active and ready\n if (!this.sftpClientInstance) {\n // This should ideally be caught by connect(), but as a safeguard\n throw new Error(`SFTP client not available on SSHSession for ${this.host.uri} after connect call.`);\n }\n return this.sftpClientInstance;\n }\n\n async executeCommand(\n command: string | string[],\n options?: {\n cwd?: string;\n stdin?: string | Buffer;\n pty?: boolean;\n env?: Record<string, string>;\n interactionHandler?: InteractionHandler;\n },\n ): Promise<Command | Error> {\n this.app.debug(`RemoteRuntime: Executing on ${this.host.uri}: ${command}`);\n\n const handlerToUse = options?.interactionHandler || this.interactionHandler;\n let cmdOrErr: Command | Error;\n\n try {\n if (options?.pty || handlerToUse !== this.interactionHandler) {\n this.app.debug(`RemoteRuntime: Executing command on ${this.host.uri} via sshSession.run (PTY/custom handler)`);\n const commandObj: Command = await this.sshSession.run(command, handlerToUse, {\n cwd: options?.cwd,\n stdin: options?.stdin,\n pty: options?.pty,\n env: options?.env,\n });\n cmdOrErr = commandObj;\n } else {\n this.app.debug(\n `RemoteRuntime: Executing command on ${this.host.uri} via sshSession.execCommand (no PTY/default handler)`,\n );\n const actualCommand = Array.isArray(command) ? command.join(' ') : command;\n const commandObj: Command = await this.sshSession.execCommand(actualCommand, {\n cwd: options?.cwd,\n stdin: options?.stdin,\n env: options?.env,\n });\n cmdOrErr = commandObj;\n }\n this.app.logHostCommandResult(this.host, command, cmdOrErr);\n } catch (e: any) {\n this.app.error(`RemoteRuntime: executeCommand failed for '${command}': ${e.message}`);\n this.app.error(e.stack);\n cmdOrErr = e;\n this.app.logHostCommandResult(this.host, command, cmdOrErr);\n }\n\n return cmdOrErr;\n }\n\n async disconnect(): Promise<void> {\n if (this.sshSession.isConnected()) {\n this.app.debug(`RemoteRuntime: Disconnecting SSH from ${this.host.uri}`);\n this.sftpClientInstance = undefined; // Clear SFTP client instance\n await this.sshSession.disconnect();\n }\n }\n\n async invokeRootTask<TParams extends TaskParams, TReturn extends RunFnReturnValue>(\n taskFnDefinition: TaskFn<TParams, TReturn>,\n params: TParams,\n ): Promise<IInvocation> {\n await this.connect();\n if (!this.sshSession) throw new Error('SSH session not established for invokeRootTask.');\n\n // RemoteInvocation will use this RemoteRuntime instance for SSH operations\n const rootInvocation = new RemoteInvocation(\n this,\n taskFnDefinition,\n params,\n { runtime: this, host: this.host } as any,\n this.host,\n );\n\n this.app.taskTree.add(\n rootInvocation.id,\n null,\n taskFnDefinition.task.name || `remote_root_task_on_${this.host.hostname}`, // Changed host to hostname\n rootInvocation.result.then((r) => (r === null ? undefined : r)) as Promise<string | Error | undefined>,\n );\n\n const taskContext = this.app.taskContextForRunFn(rootInvocation, params, this.host) as TaskContext<TParams>;\n\n taskFnDefinition.task.runFn\n .call(rootInvocation, taskContext)\n .then(rootInvocation.resolveResult)\n .catch(rootInvocation.rejectResult);\n\n return rootInvocation;\n }\n}\n","import { signalsByName } from 'human-signals';\nimport { NodeSSH, type Config } from 'node-ssh';\nimport { InteractionHandler } from './interaction-handler';\nimport { PassThrough } from 'stream'; // Added for combining stdin\nimport { Command, CommandResult, type Signal } from './command';\n\nexport class SSHSession {\n public ssh: NodeSSH;\n\n constructor() {\n this.ssh = new NodeSSH();\n }\n\n connect(sshConnectOpts: Config): Promise<NodeSSH> {\n return this.ssh.connect(sshConnectOpts);\n }\n\n async deleteFile(remotePath: string) {\n const self = this;\n return new Promise(function (resolve, reject) {\n self.ssh.withSFTP(async (sftp) => {\n sftp.unlink(remotePath, (err: Error | null | undefined) => {\n if (err) {\n // err is Error | null | undefined; if non-null/undefined, it's an Error\n // ENOENT (No such file or directory) often has errno 2 or code 'ENOENT'.\n const errnoError = err as NodeJS.ErrnoException;\n if (errnoError.errno === 2 || errnoError.code === 'ENOENT') {\n resolve(true); // Consider \"file not found\" as success for delete\n } else {\n const errnoError = err as NodeJS.ErrnoException;\n const errorCodeDisplay =\n errnoError.code !== undefined\n ? errnoError.code\n : errnoError.errno !== undefined\n ? errnoError.errno\n : 'N/A';\n reject(`${errnoError.message} (code ${errorCodeDisplay}) ${remotePath}`);\n }\n } else {\n // No error means unlink was successful\n resolve(true);\n }\n });\n });\n });\n }\n\n async sftp() {\n return this.ssh.requestSFTP();\n }\n\n async execCommand(\n command: string,\n options?: { cwd?: string; stdin?: string | Buffer; pty?: boolean | object; env?: Record<string, string> },\n ) {\n // The existing 'run' method is more complex due to InteractionHandler.\n // For execCommand, we'll use a simpler ssh.execCommand which directly returns stdout/stderr.\n // Note: node-ssh's execCommand doesn't directly support 'env' in the same way as exec.\n // We might need to prepend env vars to the command string if 'env' is critical here.\n\n const nodeSshCmdOptions: any = {\n // Using 'any' temporarily to build up, then will cast or ensure type compatibility\n cwd: options?.cwd,\n stdin:\n typeof options?.stdin === 'string'\n ? options.stdin\n : Buffer.isBuffer(options?.stdin)\n ? options.stdin.toString()\n : undefined,\n };\n\n if (options?.pty !== undefined) {\n // pty and other ssh2-specific options go into a nested 'options' object\n nodeSshCmdOptions.options = {\n ...(nodeSshCmdOptions.options || {}), // Preserve other potential ssh2 options if they were there\n pty: options.pty,\n };\n }\n\n const result = await this.ssh.execCommand(command, nodeSshCmdOptions as import('node-ssh').SSHExecCommandOptions);\n const exitCode = result.code === null ? -1 : result.code; // Handle null exit code\n const signalString = result.signal; // string | null\n const signalObject = signalString ? (signalsByName as Record<string, Signal>)[signalString] : undefined;\n\n const commandResult = new CommandResult(result.stdout, result.stderr, exitCode, signalObject);\n\n return new Command({ cmd: command, args: [], cwd: options?.cwd, env: options?.env, result: commandResult });\n }\n\n async getFile(remotePath: string, localPath: string) {\n await this.ssh.getFile(localPath, remotePath);\n }\n\n /**\n * Executes a command on the remote host.\n * @param command The command to execute. Can be a string or an array of strings. If an array, the first element is\n * the command and the rest are arguments. Otherwise, the string is parsed as a command.\n * @param interactionHandler The interaction handler to use.\n * @param execOptions The options for the execution.\n * @returns A promise that resolves to the result of the command.\n */\n async run(\n command: string | string[],\n interactionHandler = new InteractionHandler(),\n execOptions: {\n cwd?: string;\n stdin?: string | Buffer;\n pty?: boolean | object; // pty option from caller\n env?: Record<string, string>;\n } = {},\n ): Promise<Command> {\n // Return type reflects node-ssh's ExecResult extended with cmd and args\n const self = this;\n\n const combinedStdin = new PassThrough();\n if (execOptions.stdin) {\n combinedStdin.write(execOptions.stdin);\n // If it's a one-off stdin, we might want to end this part of the stream,\n // but PassThrough will stay open for interactionHandler's pipe.\n // For simplicity, let interactionHandler control the end of its piped content.\n }\n interactionHandler.setOutputToNewReadable().pipe(combinedStdin);\n\n interactionHandler.begin();\n\n let cmd: string, args: string[];\n if (command instanceof Array) {\n cmd = command[0] || '';\n args = command.slice(1).filter((arg) => !!arg);\n } else {\n // Assuming Command.parse is a static method from hostctl's Command class\n // This might need adjustment if Command is from node-ssh or has a different API\n const parsedCommand = Command.parse(command); // Ensure this Command.parse is what's intended\n cmd = parsedCommand.cmd;\n args = parsedCommand.args;\n }\n\n const ptyOption = execOptions.pty ?? true; // Default to PTY if run is called, as it implies interaction\n\n const { stdout, stderr, code, signal } = await self.ssh.exec(cmd, args, {\n cwd: execOptions.cwd,\n execOptions: { pty: ptyOption, env: execOptions.env },\n stream: 'both',\n stdin: combinedStdin,\n onStdout: (chunk: Buffer) => {\n const output = chunk.toString('utf8');\n interactionHandler.handleInput(output);\n },\n onStderr: (chunk: Buffer) => {\n const errorOutput = chunk.toString('utf8');\n interactionHandler.handleInput(errorOutput); // Send stderr to handler too\n // node-ssh's `exec` still collects stderr for the final result.stderr string\n // so we don't need to explicitly return it from here for collection purposes.\n },\n });\n\n interactionHandler.end();\n\n const signalName = signal as keyof typeof signalsByName | null;\n const signalObj = signalName ? signalsByName[signalName] : undefined;\n const result = new CommandResult(stdout, stderr, code || 0, signalObj);\n\n return new Command({ cmd, args, cwd: execOptions.cwd, env: execOptions.env, result });\n }\n\n async sendFile(localPath: string, remotePath: string): Promise<boolean> {\n try {\n await this.ssh.putFile(localPath, remotePath);\n return true;\n } catch (e) {\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n this.ssh.dispose();\n }\n\n isConnected() {\n return this.ssh.isConnected();\n }\n}\n","import os from 'node:os';\nimport axios, { type AxiosInstance } from 'axios';\nimport * as cheerio from 'cheerio';\nimport { File } from './flex/file';\nimport { A } from './flex/array';\nimport { O } from './flex/object';\nimport { V } from './flex/type';\nimport { match } from 'ts-pattern';\nimport which from 'which';\nimport { downloadFile } from './http';\nimport { ShellCommand } from './shell-command';\nimport { unarchive } from './unarchive';\nimport type { CommandResult } from './command';\nimport type { Path } from './flex/path';\n\nexport class NodeRuntime {\n static Name = 'nodejs';\n\n private client: AxiosInstance;\n private alreadyInstalled: boolean;\n private localNode: Path;\n private localNpm: Path;\n\n constructor(public tmpDir: Path) {\n this.client = axios.create({\n baseURL: 'https://nodejs.org/',\n });\n this.alreadyInstalled = false;\n this.localNode = this.tmpDir.join(NodeRuntime.Name, 'bin', 'node');\n this.localNpm = this.tmpDir.join(NodeRuntime.Name, 'bin', 'npm');\n }\n\n async isNodeInstalledGlobally() {\n const result = await ShellCommand.fromString(`node --version`).run();\n // console.log(`isNodeInstalledGlobally result: ${V.inspect(result.toJSON())}`);\n return result.success;\n }\n\n async isNodeInstalledLocally() {\n const result = await ShellCommand.fromString(`${this.localNode} --version`).run();\n // console.log(`isNodeInstalledLocally result: ${V.inspect(result.toJSON())}`);\n return result.success;\n }\n\n async isNpmInstalledGlobally() {\n const result = await ShellCommand.fromString(`npm --version`).run();\n // console.log(`isNpmInstalledGlobally result: ${V.inspect(result.toJSON())}`);\n return result.success;\n }\n\n async isNpmInstalledLocally() {\n const result = await ShellCommand.fromString(`${this.localNpm} --version`).run();\n // console.log(`isNpmInstalledLocally result: ${V.inspect(result.toJSON())}`);\n // console.log(result.err);\n return result.success;\n }\n\n async nodeCmd() {\n if (await this.isNodeInstalledGlobally()) return 'node';\n\n if (await this.isNodeInstalledLocally()) return this.localNode.toString();\n\n throw new Error('node not installed');\n }\n\n async nodePath(): Promise<string | null> {\n if (await this.isNodeInstalledGlobally()) {\n return await which('node', { nothrow: true });\n }\n\n if (await this.isNodeInstalledLocally()) return this.localNode.toString();\n\n return null;\n }\n\n async npmCmd() {\n if (await this.isNpmInstalledGlobally()) return 'npm';\n\n if (await this.isNpmInstalledLocally()) return this.localNpm.toString();\n\n throw new Error('npm not installed');\n }\n\n async npmPath(): Promise<string | null> {\n if (await this.isNpmInstalledGlobally()) {\n return await which('npm', { nothrow: true });\n }\n\n if (await this.isNpmInstalledLocally()) return this.localNpm.toString();\n\n return null;\n }\n\n async installIfNeeded() {\n if (this.alreadyInstalled || (await this.isNodeInstalledGlobally()) || (await this.isNodeInstalledLocally())) {\n this.alreadyInstalled = true;\n return;\n }\n\n return this.install();\n }\n\n async install() {\n const platform = os.platform();\n const arch = os.arch();\n const packagePath = await this.downloadNodePackage(platform, arch);\n const unzipDir = await this.unzipPackage(packagePath);\n\n this.alreadyInstalled = true;\n\n return unzipDir;\n }\n\n async listPackages(): Promise<string[]> {\n const response = await this.client.get(`/dist/latest/`);\n const doc = await cheerio.load(response.data);\n const allFileLinks = doc('a')\n .map((i, el) => doc(el).attr('href'))\n .toArray();\n const archiveFiles = A(allFileLinks).select((filename: string) => filename.match(/.*\\.(gz|zip|xz)/));\n const urls = A(archiveFiles).map((filename: string) => `https://nodejs.org/dist/latest/${filename}`);\n return urls;\n }\n\n // returns the path to the downloaded zip file\n async downloadNodePackage(platform: string, arch: string): Promise<string> {\n // const url = match([platform, arch])\n // .with([\"linux\", \"x64\"], () => \"https://nodejs.org/dist/v22.4.1/node-v22.4.1-linux-x64.tar.xz\")\n // .with([\"linux\", \"arm\"], () => \"https://nodejs.org/dist/v22.4.1/node-v22.4.1-linux-armv7l.tar.xz\")\n // .with([\"linux\", \"arm64\"], () => \"https://nodejs.org/dist/v22.4.1/node-v22.4.1-linux-arm64.tar.xz\")\n // .with([\"win32\", \"x64\"], () => \"https://nodejs.org/dist/v22.4.1/node-v22.4.1-win-x64.zip\")\n // .with([\"win32\", \"arm64\"], () => \"https://nodejs.org/dist/v22.4.1/node-v22.4.1-win-arm64.zip\")\n // .with([\"darwin\", \"x64\"], () => \"https://nodejs.org/dist/v22.4.1/node-v22.4.1-darwin-x64.tar.gz\")\n // .with([\"darwin\", \"arm64\"], () => \"https://nodejs.org/dist/v22.4.1/node-v22.4.1-darwin-arm64.tar.gz\")\n // .otherwise(() => {\n // throw new Error(`Unable to download node for OS/architecture: ${os}/${arch}`);\n // });\n\n const platformInFilename = match(platform)\n .with('linux', () => 'linux')\n .with('win32', () => 'win')\n .with('darwin', () => 'darwin')\n .otherwise(() => 'unknown-platform');\n\n const archInFilename = match(arch)\n .with('x64', () => 'x64')\n .with('x86', () => 'x86')\n .with('arm', () => 'armv7l')\n .with('arm64', () => 'arm64')\n .otherwise(() => 'unknown-arch');\n\n const packages = await this.listPackages();\n const url = A(packages).find((url: string) => url.match(`node-v.*-${platformInFilename}-${archInFilename}`));\n if (V.isAbsent(url)) {\n throw new Error(`Unable to download node for ${os}/${arch} OS/architecture`);\n }\n\n const filename = File.basename(url);\n const path = this.tmpDir.join(filename);\n\n if (path.exists()) return path.toString();\n\n // console.log(`downloading ${url} to ${path}`);\n return await downloadFile(url, path.toString());\n }\n\n // returns the path to the unzipped package directory\n async unzipPackage(packagePath: string): Promise<string> {\n const dir = this.tmpDir.join(NodeRuntime.Name);\n\n if (dir.exists()) return dir.toString();\n\n // console.log(`unzipping ${packagePath} to ${dir}`);\n await unarchive(packagePath, dir.toString());\n return dir.toString();\n }\n\n async npmInstall(omitDev = true, cwd?: string): Promise<CommandResult> {\n // const result = await ShellCommand.fromString(`bun install --no-save --production`, {}, directory).run();\n // const result = await ShellCommand.fromString(`npm install --omit=dev`, {}, directory).run();\n\n if (omitDev) {\n return this.npm('install --omit=dev', cwd);\n } else {\n return this.npm('install', cwd);\n }\n }\n\n async npm(npmArgs: string, cwd?: string): Promise<CommandResult> {\n const npmCmd = await this.npmCmd();\n\n const env: Record<string, string> = O(process.env).select(([_, v]) => !!v) as Record<string, string>;\n return ShellCommand.fromString(`${npmCmd} ${npmArgs}`.trim(), env, cwd).run();\n }\n\n async node(nodeArgs: string, cwd?: string): Promise<CommandResult> {\n const nodeCmd = await this.nodeCmd();\n\n const env: Record<string, string> = O(process.env).select(([_, v]) => !!v) as Record<string, string>;\n return ShellCommand.fromString(`${nodeCmd} ${nodeArgs}`.trim(), env, cwd).run();\n }\n}\n","import type { PathLike } from 'node:fs';\nimport { createWriteStream, unlink } from 'node:fs';\nimport { get } from 'node:https';\n\nexport async function downloadFile(url: string, dest: PathLike): Promise<string> {\n return new Promise((resolve, reject) => {\n const file = createWriteStream(dest, { flags: 'wx' });\n\n const request = get(url, (response) => {\n if (response.statusCode === 200) {\n response.pipe(file);\n } else {\n file.close();\n unlink(dest, () => {}); // Delete temp file\n reject(`Server responded with ${response.statusCode}: ${response.statusMessage}`);\n }\n });\n\n request.on('error', (err) => {\n file.close();\n unlink(dest, () => {}); // Delete temp file\n reject(err.message);\n });\n\n file.on('finish', () => {\n resolve(dest.toString());\n });\n\n file.on('error', (err: NodeJS.ErrnoException) => {\n file.close();\n\n if (err.code === 'EEXIST') {\n reject(new Error('File already exists'));\n } else {\n unlink(dest, () => {}); // Delete temp file\n reject(err.message);\n }\n });\n });\n}\n","import spawnAsync from '@expo/spawn-async';\n// import { execa, ExecaError, type Result, type ResultPromise } from \"execa\";\nimport { Command, CommandResult } from './command';\nimport { signalsByName, type SignalName } from 'human-signals';\nimport { V } from './flex/type';\n\ninterface SpawnAsyncError extends Error {\n pid?: number;\n stdout?: string;\n stderr?: string;\n status?: number | null;\n signal?: string | null;\n // message and stack are inherited from Error\n}\n\nexport class ShellCommand extends Command {\n static fromString(command: string, env?: Record<string, string>, cwd?: string): ShellCommand {\n const { cmd, args } = this.parse(command, env);\n return new ShellCommand({ cmd, args, cwd, env });\n }\n\n async run(): Promise<CommandResult> {\n try {\n // console.log(V.inspect(this.args));\n // console.log(`(${this.cwd})> ${this.cmd} ${this.args}`);\n const resultPromise = spawnAsync(this.cmd, this.args, {\n cwd: this.cwd,\n env: this.env,\n // shell: true\n });\n\n let { pid, stdout, stderr, status, signal } = await resultPromise;\n\n const signalObj = (signal && signalsByName[signal as SignalName]) || undefined;\n const commandResult = new CommandResult(stdout || '', stderr || '', status || 0, signalObj);\n this.result = commandResult;\n } catch (e: unknown) {\n const error = e as SpawnAsyncError;\n // The error object also has the same properties as the result object (see https://github.com/expo/spawn-async/blob/main/src/spawnAsync.ts#L84)\n // console.log(`---------------------------------`);\n // console.log(`(${this.cwd})> ${this.cmd} ${this.args}`);\n if (error.message) console.error(error.message);\n if (error.stack) console.error(error.stack);\n let { pid, stdout, stderr, status, signal } = error;\n\n const signalObj = (signal && signalsByName[signal as SignalName]) || undefined;\n const commandResult = new CommandResult(stdout || '', stderr || '', status || 1, signalObj);\n this.result = commandResult;\n }\n return this.result;\n }\n}\n","import { File } from './flex/file';\nimport decompress from 'decompress';\nimport decompressTarGzPlugin from 'decompress-targz';\nimport decompressZipPlugin from 'decompress-unzip';\nimport { match, P } from 'ts-pattern';\n\n// these are for the tar.xz decompress functionality\nimport decompressTarPlugin from 'decompress-tar';\nimport { fileTypeFromBuffer } from 'file-type';\nimport { getStreamAsBuffer } from 'get-stream';\nimport xzdecompress from 'xz-decompress';\n\nexport async function unarchive(inputPath: string, outputPath: string): Promise<void> {\n const filename = File.basename(inputPath);\n return await match(filename)\n .with(P.string.regex(/.tar.xz$/), () => decompressTarXz(inputPath, outputPath))\n .with(P.string.regex(/.tar.gz$/), () => decompressTarGz(inputPath, outputPath))\n .with(P.string.regex(/.zip$/), () => decompressZip(inputPath, outputPath))\n .otherwise(() => {\n throw new Error(`unable to decompress unknown file type: ${inputPath}`);\n });\n}\n\nexport async function decompressTarGz(inputPath: string, outputPath: string, dropRootDir = 1) {\n await decompress(inputPath, outputPath, {\n plugins: [decompressTarGzPlugin()],\n strip: dropRootDir,\n });\n}\n\nasync function decompressTarXzPlugin(input: Buffer): Promise<decompress.File[]> {\n const type = await fileTypeFromBuffer(input);\n\n if (!type || type.ext !== 'xz') {\n // Not an XZ file, or unknown type; plugin should return an empty array.\n return [];\n }\n\n // Input is a Buffer and is an XZ file.\n const blob = new Blob([input]);\n const webReadableStream = blob.stream(); // blob.stream() is ReadableStream<Uint8Array>\n const xzStream = new xzdecompress.XzReadableStream(webReadableStream);\n\n // decompressTarPlugin() returns a function that expects a Buffer.\n // getStreamAsBuffer(xzStream) converts the decompressed stream back to a Buffer.\n const decompressedBuffer = await getStreamAsBuffer(xzStream);\n return decompressTarPlugin()(decompressedBuffer);\n}\n\nexport async function decompressTarXz(inputPath: string, outputPath: string, dropRootDir = 1) {\n await decompress(inputPath, outputPath, {\n plugins: [decompressTarXzPlugin],\n strip: dropRootDir,\n });\n}\n\nexport async function decompressZip(inputPath: string, outputPath: string, dropRootDir = 1) {\n await decompress(inputPath, outputPath, {\n plugins: [decompressZipPlugin()],\n strip: dropRootDir,\n });\n}\n","import AdmZip from 'adm-zip';\n\nexport async function zipDirectory(sourceDir: string, outputFilePath: string): Promise<string> {\n const zip = new AdmZip();\n zip.addLocalFolder(sourceDir);\n await zip.writeZipPromise(outputFilePath);\n // console.log(`Zip file created: ${outputFilePath}`);\n return outputFilePath;\n}\n\nexport async function unzipDirectory(inputFilePath: string, outputDirectory: string): Promise<string> {\n const zip = new AdmZip(inputFilePath);\n return new Promise((resolve, reject) => {\n zip.extractAllToAsync(outputDirectory, true, false, (error?: Error) => {\n if (error) {\n // console.log(error);\n reject(error);\n } else {\n // console.log(`Extracted to \"${outputDirectory}\" successfully`);\n resolve(outputDirectory);\n }\n });\n });\n}\n","import { createHash } from 'node:crypto';\n\n/**\n * Returns a SHA256 hash using SHA-2 for the given `content`.\n */\nexport function sha256(str: string): string {\n return createHash('sha256').update(str).digest('hex');\n}\n","import { A } from './flex/array';\nimport { M } from './flex/map';\nimport { VP } from './flex/pipe';\nimport { Str, isNumeric, matches } from './flex/string';\nimport { V } from './flex/type';\nimport { match } from 'ts-pattern';\n\nexport class ParamMap {\n static parse(cliArguments: string[]): ParamMap {\n const root = new ParamMap();\n\n A(cliArguments).each((arg: string) => {\n // Expect tokens like \"key:value\" – only split on the FIRST colon so that\n // values may themselves contain colons (or additional comma-separated data).\n const idx = arg.indexOf(':');\n if (idx === -1) {\n // No colon – treat entire token as key with boolean true (or empty string)\n root.set(arg, 'true');\n return;\n }\n\n const key = arg.slice(0, idx);\n const value = arg.slice(idx + 1);\n root.set(key, value);\n });\n\n return root;\n }\n\n public map: Map<string, string | ParamMap>;\n\n constructor() {\n this.map = new Map();\n }\n\n get(keyPath: string): string | ParamMap | undefined {\n try {\n return A(keyPath.split(':')).reduce(\n (node: Map<string, string | ParamMap> | ParamMap, key: string) => node.get(key),\n this.map,\n );\n } catch (e) {\n return undefined;\n }\n }\n\n set(keyPath: string, value: string | ParamMap) {\n const keyParts = keyPath.split(':');\n const paramMap: ParamMap = A(keyParts)\n .skipLast(1)\n .reduce((node: Map<string, string | ParamMap> | ParamMap, key: string) => {\n let nextNode = node.get(key);\n if (nextNode) return nextNode;\n const newParamMap = new ParamMap();\n node.set(key, newParamMap);\n return newParamMap;\n }, this.map);\n const key = A(keyParts).last(1)[0];\n paramMap.set(key, value);\n }\n\n toObject(): Object {\n let obj: any = {};\n M(this.map).each(([k, v]: [string, string | ParamMap]) => {\n obj[k] = match(v)\n .when(V.isA(String), (str) => this.stringToJsonObj(str))\n .otherwise(() => {\n return (v as ParamMap).toObject();\n });\n });\n return obj;\n }\n\n private stringToJsonObj(str: string) {\n return match(str)\n .when(matches(/(.*,)+/g), (str: string) => {\n return VP(str.split(','))\n .map((s: string) => s.trim())\n .compact([''])\n .map((s: string) => this.stringToJsonObj(s)).value;\n })\n .when(isNumeric, (str: string) => parseFloat(str))\n .otherwise(() => str);\n }\n}\n","export const version = '0.1.32';\n","import { task, type TaskContext, type TaskFn } from '../../runtime';\n\ninterface RunParams {\n taskFn: TaskFn;\n params: any;\n}\n\ntype RunResult = Record<string, any>;\n\nasync function run(context: TaskContext<RunParams>): Promise<RunResult> {\n const { params, ssh } = context;\n const { taskFn, params: taskParams } = params;\n\n // The callback to context.ssh runs on the remote host, receiving its own TaskContext.\n return await ssh([], async (remoteContext: TaskContext<RunParams>) => {\n const hostIdentifier = remoteContext.host?.alias || remoteContext.host?.shortName || 'unknown_remote_host';\n remoteContext.debug(`[${hostIdentifier}] Connected via SSH.`);\n\n try {\n const result = await remoteContext.run(taskFn(taskParams));\n remoteContext.debug(`[${hostIdentifier}] Remote task result:`, JSON.stringify(result));\n return result;\n } catch (e: any) {\n remoteContext.debug(`[${hostIdentifier}] Failed to run remote task:`, e.message);\n return e;\n }\n });\n}\n\nexport default task(run, {\n description: 'run a task on all selected hosts',\n});\n","import { simpleGit, type SimpleGit } from 'simple-git';\nimport filenamify from 'filenamify';\nimport { match } from 'ts-pattern';\nimport { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { unzipDirectory } from '../zip';\nimport { Path } from '../flex/path';\nimport { A } from '../flex/array';\nimport { App } from '../app';\n\n/**\n * Resolves the script reference provided to the `hostctl run` command.\n *\n * This helper centralises the previously in–line logic that lived in\n * `Cli.handleRun`. In addition it adds support for invoking built-in\n * core tasks using dot-notation, e.g. `core.pkg.install` will resolve\n * to `src/core/pkg/install.ts`.\n *\n * @param app The current App instance (for tmpDir access).\n * @param packageOrBundle The first positional arg (package / bundle path or URL).\n * @param scriptRef The second positional arg (script ref) – may be undefined.\n * @param scriptArgs Any additional positional args intended for the script.\n *\n * @returns The resolved absolute script path together with the (possibly\n * mutated) scriptArgs array.\n */\nexport async function resolveScriptPath(\n app: App,\n packageOrBundle: string | null,\n scriptRef: string | undefined,\n scriptArgs: string[],\n): Promise<{ scriptRef: string; scriptArgs: string[] }> {\n // 1. Support built-in core task names like `core.pkg.install`\n if (\n (packageOrBundle && packageOrBundle.startsWith('core.')) ||\n (!packageOrBundle && scriptRef && scriptRef.startsWith('core.'))\n ) {\n const name = packageOrBundle?.startsWith('core.') ? packageOrBundle : (scriptRef as string);\n const relPath = name\n .replace(/^core\\./, '')\n .split('.')\n .join(Path.sep());\n\n // Resolve path relative to current module directory (works under ESM)\n const moduleDir = Path.new(dirname(fileURLToPath(import.meta.url)));\n const coreRoot = moduleDir.parent().join('core');\n const candidate = coreRoot.join(`${relPath}.ts`);\n\n if (!candidate.isFile()) {\n throw new Error(`Core task script not found: ${candidate}`);\n }\n\n // If the core task name came via packageOrBundle, then any token that commander\n // placed into the `scriptRef` positional argument is actually the first script\n // argument. Prepend it back onto the list so that downstream param parsing\n // sees it.\n if (packageOrBundle?.startsWith('core.') && scriptRef) {\n scriptArgs = [scriptRef, ...scriptArgs];\n }\n\n return { scriptRef: candidate.toString(), scriptArgs };\n }\n\n // Existing resolution logic from previous implementation\n if (!packageOrBundle) {\n throw new Error('No bundle or package specified.');\n }\n const currentPackageOrBundle = packageOrBundle; // freeze value for pattern matching\n let resolvedScriptRef = scriptRef ?? '';\n\n await match(currentPackageOrBundle)\n .when(\n (path) => Path.new(path).isFile() && Path.new(path).ext() === '.zip',\n async () => {\n const tmpName = filenamify(currentPackageOrBundle);\n const destPath = app.tmpDir.join(tmpName);\n await unzipDirectory(currentPackageOrBundle, destPath.toString());\n resolvedScriptRef = destPath.resolve(resolvedScriptRef).toString();\n },\n )\n .when(\n (path) => Path.new(path).isDirectory(),\n async () => {\n const tmpName = filenamify(currentPackageOrBundle);\n const destPath = app.tmpDir.join(tmpName);\n const pkgPath = Path.new(currentPackageOrBundle);\n await pkgPath.copy(destPath.toString());\n resolvedScriptRef = destPath.resolve(resolvedScriptRef).toString();\n },\n )\n .when(isValidUrl, async () => {\n const tmpName = filenamify(currentPackageOrBundle);\n const destPath = app.tmpDir.join(tmpName);\n const git: SimpleGit = simpleGit();\n await git.clone(currentPackageOrBundle, destPath.toString());\n resolvedScriptRef = destPath.resolve(resolvedScriptRef).toString();\n })\n .otherwise(async () => {\n if (resolvedScriptRef) {\n // previous behaviour – treat <script> as first arg and push back into args list\n A(scriptArgs).prepend(resolvedScriptRef);\n }\n resolvedScriptRef = currentPackageOrBundle;\n });\n\n return { scriptRef: resolvedScriptRef, scriptArgs };\n}\n\nfunction isValidUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n}\n","#!/usr/bin/env -S npx tsx\n\n// #!/usr/bin/env node\n// #!/usr/bin/env -S npx tsx\n// #!/usr/bin/env -S node --import=tsx/esm\n\nimport { Cli } from '../cli';\n\nconst cli = new Cli();\ncli.program.parseAsync(process.argv).catch((error) => {\n // Minimal top-level error handling for the binary,\n // more detailed errors should be handled within Cli/App.\n console.error('Unhandled error in hostctl binary:', error);\n process.exit(1);\n});\n"],"mappings":";;;AAAA,OAAOA,cAAa;AACpB,YAAY,UAAU;;;ACDtB,OAAOC,cAAa;AACpB,YAAYC,SAAQ;AACpB,SAAS,WAAAC,gBAAe;;;ACFxB,OAAO,gBAAgB;AAGvB,WAAW,eAAe,QAAQ,SAAU,OAAO,OAAO;AACxD,MAAI,YAAY,MAAM,KAAK,aAAa,KACtC,QAAQ,MAAM,KAAK,SAAS,GAC5B,MAAM,QAAQ,MAAM,SAAS,GAC7B,MAAM,MAAM,KAAK,OAAO,KACxB,MAAM;A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OAAO,IAAI,gBAAgB;AACjC,UAAM,KAAK,QAAQ,IAAI;AAEvB,UAAM,KAAK,IAAI,mBAAmB;AAAA,EACpC;AAAA,EAEA,MAAM,qBAAqB,SAA8B,KAAmB;AAC1E,UAAM,OAAO,IAAI,gBAAgB;AACjC,UAAM,KAAK,QAAQ,IAAI;AAEvB,UAAM,KAAK,IAAI,eAAe;AAAA,EAChC;AACF;;;AsD9WA,IAAM,MAAM,IAAI,IAAI;AACpB,IAAI,QAAQ,WAAW,QAAQ,IAAI,EAAE,MAAM,CAAC,UAAU;AAGpD,UAAQ,MAAM,sCAAsC,KAAK;AACzD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["process","process","fs","homedir","fs","globSync","each","map","select","each","keys","map","select","values","isEmpty","matches","path","compact","each","isEmpty","map","values","select","A","each","isEmpty","map","A","process","readFile","existsSync","readFileSync","win32","posix","path","existsSync","win32","posix","readFileSync","readFile","path","process","A","fs","path","fs","path","identity","fs","SecretValue","Secret","A","ConfigFile","path","globSync","ConfigFile","matches","util","chalk","Mutex","A","Mutex","Handlebars","fs","StringBuilder","StringBuilder","chalk","Handlebars","path","chalk","ConfigFile","Handlebars","errnoError","Handlebars","command","os","match","spawnAsync","signalsByName","spawnAsync","signalsByName","match","P","platform","os","A","match","url","path","zip","match","A","key","str","Mutex","match","Mutex","task","process","homedir","chalk","A","cmd","match","isError","ConfigFile","identity","invocation","path","match","match","path","A","isError","isValidUrl","path","process"]}
|
|
1
|
+
{"version":3,"sources":["../../src/cli.ts","../../src/app.ts","../../src/handlebars.ts","../../src/config.ts","../../src/config-file.ts","../../src/flex/function.ts","../../src/flex/protocol.ts","../../src/flex/type.ts","../../src/flex/compactable.ts","../../src/flex/enumerator.ts","../../src/flex/enumerable.ts","../../src/flex/mappable.ts","../../src/flex/selectable.ts","../../src/flex/array-protocols.ts","../../src/flex/map.ts","../../src/flex/map-protocols.ts","../../src/flex/object.ts","../../src/flex/object-protocols.ts","../../src/flex/path.ts","../../src/flex/platform.ts","../../src/flex/string.ts","../../src/flex/range.ts","../../src/flex/equal.ts","../../src/flex/range-protocols.ts","../../src/flex/set-protocols.ts","../../src/flex/array.ts","../../src/flex/set.ts","../../src/flex/pipe.ts","../../src/tempfile.ts","../../src/flex/file.ts","../../src/host.ts","../../src/age-encryption.ts","../../src/process.ts","../../src/config-url.ts","../../src/interaction-handler.ts","../../src/task.model.ts","../../src/stacktrace.ts","../../src/runtime-base.ts","../../src/command.ts","../../src/local-runtime.ts","../../src/ruspty-command.ts","../../src/util/input-helpers.ts","../../src/remote-runtime.ts","../../src/ssh-session.ts","../../src/node-runtime.ts","../../src/http.ts","../../src/shell-command.ts","../../src/unarchive.ts","../../src/zip.ts","../../src/hash.ts","../../src/param-map.ts","../../src/version.ts","../../src/core/remote/runAllRemote.ts","../../src/cli/run-resolver.ts","../../src/bin/hostctl.ts"],"sourcesContent":["import process from 'node:process';\nimport * as cmdr from 'commander';\n\nimport { App, Verbosity } from './app';\nimport { File } from './flex/file';\nimport { version } from './version';\n\nimport JSON5 from 'json5';\nimport { Path } from './flex/path';\n\nimport { resolveScriptPath } from './cli/run-resolver';\n\n/**\n * Type guard to check if an `unknown` value is an `Error` object.\n *\n * @param value - The value to check.\n *\n * @returns `true` if the value is an `Error` object, otherwise `false`.\n */\nexport const isError = (value: unknown): value is Error =>\n !!value &&\n typeof value === 'object' &&\n 'message' in value &&\n typeof value.message === 'string' &&\n 'stack' in value &&\n typeof value.stack === 'string';\n\nconst logError = (message: string, error: unknown): void => {\n console.error(`Error: ${message}`); // Print the primary message to stderr\n if (isError(error)) {\n console.error(error.stack); // Print stack to stderr\n } else {\n try {\n // For unknown errors, create a new error to get a stack trace pointing to this logError call\n const unknownError = new Error(\n `Unexpected value thrown: ${typeof error === 'object' ? JSON.stringify(error) : String(error)}`,\n );\n console.error(unknownError.stack);\n } catch {\n console.error(new Error(`Unexpected value thrown: non-stringifiable object`).stack);\n }\n }\n};\n\nfunction isValidUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch (_) {\n return false;\n }\n}\n\n// per example at https://github.com/tj/commander.js/blob/HEAD/examples/options-custom-processing.js\nfunction increaseVerbosity(dummyValue: any, previous: number) {\n return previous + 1;\n}\n\nfunction decreaseVerbosity(dummyValue: any, previous: number) {\n return previous - 1;\n}\n\nexport class Cli {\n public app: App;\n public program: cmdr.Command;\n\n constructor() {\n this.app = new App();\n\n this.program = new cmdr.Command();\n\n this.program\n .configureHelp({ showGlobalOptions: true })\n .name('hostctl')\n .version(version)\n .option('-q, --quiet', 'quiet; be less verbose; may be specified multiple times', decreaseVerbosity, 0)\n .option(\n '-v, --verbose',\n 'verbose; may be specified multiple times for increased verbosity',\n increaseVerbosity,\n Verbosity.WARN,\n )\n .option('-c, --config <file path>', 'config file path or http endpoint')\n .option('--json', 'output should be json formatted')\n .option('-p, --password', 'should prompt for sudo password?', false)\n .option('-t, --tag <tags...>', 'specify a tag (repeat for multiple tags)');\n\n this.program\n .command('bundle')\n .alias('b')\n .argument('[path]', `the path to bundle (e.g. hostctl bundle .)`, '.')\n .description('bundle the given path as an npm project')\n .action(this.handleBundle.bind(this));\n\n this.program\n .command('exec')\n .alias('e')\n .argument(\n '<command...>',\n `the command string to run, with optional arguments (e.g. hostctl exec sudo sh -c 'echo \"$(whoami)\"')`,\n )\n .description('execute a command on the selected hosts (default)')\n .action(this.handleExec.bind(this));\n\n const inventoryCmd = this.program.command('inventory').alias('i').description('manage inventory and view reports');\n\n inventoryCmd\n .command('report', { isDefault: true })\n .description('print out an inventory report (default)')\n .action(this.handleInventory.bind(this));\n\n inventoryCmd\n .command('encrypt')\n .alias('e')\n .description('encrypt the inventory file')\n .action(this.handleInventoryEncrypt.bind(this));\n\n inventoryCmd\n .command('decrypt')\n .alias('d')\n .description('decrypt the inventory file')\n .action(this.handleInventoryDecrypt.bind(this));\n\n inventoryCmd\n .command('list')\n .alias('ls')\n .description('list the hosts in the inventory file')\n .action(this.handleInventoryList.bind(this));\n\n this.program\n .command('run')\n .alias('r')\n .argument(\n '[package_or_bundle]',\n `the package or bundle to run the specified <script> from.\n The package or bundle may be either:\n - a directory in the local filesystem, e.g. /my/package/foo\n - a git repository, e.g. https://github.com/hostctl/core\n - a zipped package (a bundle), e.g. packagebundle123.zip\n `,\n )\n .argument(\n '[script]',\n `the hostctl script to run (e.g. hostctl run myscript OR hostctl run mypackage myscript).\n The script may be specified as either:\n - a package followed by the script, e.g. hostctl run github.com/hostctl/core echo args:hello,world\n - a script, e.g. hostctl run main.ts\n - a zipped package (a bundle), e.g. hostctl run packagebundle.zip echo args:hello,world`,\n )\n .argument('[script arguments...]', 'the runtime arguments to the script.')\n .description('run a hostctl script (default)')\n .option(\n '-f, --file <path>',\n 'runtime parameters should be read from file at <path> containing json object representing params to supply to the script',\n )\n .option(\n '-p, --params \"<json object>\"',\n 'runtime parameters supplied as a string to be parsed as a json object representing params to supply to the script',\n )\n .option('-r, --remote', 'run the script on remote hosts specified by tags via SSH orchestration')\n .action(this.handleRun.bind(this));\n\n const runtimeCmd = this.program\n .command('runtime')\n .alias('rt')\n .description('print out a report of the runtime environment')\n .action(this.handleRuntime.bind(this));\n\n runtimeCmd\n .command('install')\n .alias('i')\n .description('install a temporary runtime environment on the local host if needed')\n .action(this.handleRuntimeInstall.bind(this));\n }\n\n async handleBundle(path: string, options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n this.app.bundleProject(path);\n }\n\n async handleInventory(options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n this.app.printInventoryReport();\n }\n\n async handleInventoryEncrypt(options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n await this.app.encryptInventoryFile();\n }\n\n async handleInventoryDecrypt(options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n await this.app.decryptInventoryFile();\n }\n\n async handleInventoryList(options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n if (!this.app.config) {\n console.log('Configuration could not be loaded. Cannot list hosts.');\n if (!this.app.configRef) {\n console.log('(Also, no configuration file path was found by the app instance)');\n }\n return;\n }\n\n console.log('Config file: ' + this.app.configRef);\n\n const hosts = this.app.selectedInventory(); // Use tags from options if provided\n if (hosts.length > 0) {\n console.log('\\nHosts in inventory:');\n hosts.forEach((host) => {\n let hostIdentifier = host.shortName || '(Unnamed host)';\n console.log(` - ${hostIdentifier}`);\n if (host.tags && host.tags.length > 0) {\n console.log(` Tags: ${host.tags.join(', ')}`);\n }\n });\n } else {\n const selectedTagsSet = this.app.selectedTags;\n const selectedTagsArray = Array.from(selectedTagsSet);\n if (selectedTagsArray.length > 0) {\n console.log(`No hosts found matching tags: ${selectedTagsArray.join(', ')}`);\n } else {\n console.log('No hosts found in the inventory.');\n }\n }\n }\n\n async handleExec(commandParts: string | string[], options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n this.app.warn(`Executing command: ${commandParts}`);\n\n const success = await this.app.execute(commandParts);\n\n // Propagate exit status so that callers can detect failures\n if (!success) {\n // Non-zero indicates at least one host failed\n process.exitCode = 1;\n }\n }\n\n async handleRun(\n packageOrBundle: string | null,\n scriptRef: string | undefined,\n scriptArgs: string[],\n options: Record<string, any>,\n cmd: cmdr.Command,\n ) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n this.app.debug(`tags: ${opts.tag}, remote: ${opts.remote}`);\n\n // Resolve script path using helper\n const resolved = await resolveScriptPath(this.app, packageOrBundle, scriptRef, scriptArgs);\n scriptRef = resolved.scriptRef;\n scriptArgs = resolved.scriptArgs;\n\n let params: object = {};\n try {\n if (options.params) {\n params = JSON5.parse(options.params);\n } else if (options.file) {\n const contents = File.readSync(options.file);\n params = JSON5.parse(contents);\n } else {\n params = this.app.parseParams(scriptArgs);\n }\n } catch (err) {\n this.app.error(\n `Failed to parse params as JSON5: ${(err as Error).message}`,\n `params: ${JSON5.stringify(options.params)}`,\n );\n throw new Error(`Failed to parse params as JSON5: ${(err as Error).message}`);\n }\n\n if (!scriptRef) {\n this.program.help();\n }\n\n this.app.debug(`Resolved script: ${scriptRef}`);\n this.app.debug(`Script params: ${JSON.stringify(params)}`);\n\n if (opts.remote) {\n await this.app.runScriptRemote(scriptRef, params);\n } else {\n await this.app.runScript(scriptRef, params);\n }\n }\n\n deriveConfigRef(suppliedConfigRef?: string): string {\n // 1. If suppliedConfigRef is an existing file, use it.\n if (suppliedConfigRef && Path.new(suppliedConfigRef).isFile()) {\n return Path.new(suppliedConfigRef).toString();\n }\n\n // 2. Search CWD and ancestors for hostctl.yaml\n const foundPath = Path.cwd()\n .selfAndAncestors()\n .find((p) => p.join('hostctl.yaml').isFile());\n if (foundPath) {\n return foundPath.join('hostctl.yaml').toString();\n }\n\n // 3. Check for ~/.hostctl/hostctl.yaml\n const homeConfigPath = Path.homeDir().join('.hostctl', 'hostctl.yaml');\n if (homeConfigPath.isFile()) {\n return homeConfigPath.toString();\n }\n\n // 4. If a configRef was supplied (e.g. -c URL or -c non-existent-file), use that.\n // This allows `load()` to handle it as a ConfigUrl or report non-existence.\n if (suppliedConfigRef && isValidUrl(suppliedConfigRef)) {\n return suppliedConfigRef;\n }\n\n // 5. Otherwise, error out\n throw new Error(\n \"Could not find a hostctl configuration file. Searched for 'hostctl.yaml' in the current directory, ancestor directories, and '~/.hostctl/hostctl.yaml'. If you intended to use a URL or a specific file path, please ensure it's correct and accessible via the -c option.\",\n );\n }\n\n async loadApp(opts: Record<string, any>) {\n const derivedConfigRef = this.deriveConfigRef(opts.config);\n await this.app.loadConfig(derivedConfigRef);\n\n const verbosity = opts.quiet + opts.verbose;\n this.app.setVerbosity(verbosity);\n if (opts.json) {\n this.app.setOutputStyle('json');\n } else {\n this.app.setOutputStyle('plain');\n }\n let tagsToSet: string[] = [];\n if (typeof opts.tag === 'string') {\n tagsToSet = [opts.tag];\n } else if (Array.isArray(opts.tag)) {\n tagsToSet = opts.tag;\n }\n this.app.setSelectedTags(tagsToSet);\n }\n\n async run() {\n try {\n await this.program.parseAsync(process.argv);\n } catch (e) {\n logError('hostctl error:', e);\n }\n }\n\n async handleRuntime(options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n await this.app.printRuntimeReport();\n }\n\n async handleRuntimeInstall(options: Record<string, any>, cmd: cmdr.Command) {\n const opts = cmd.optsWithGlobals();\n await this.loadApp(opts);\n\n await this.app.installRuntime();\n }\n}\n","import process from 'node:process';\nimport * as fs from 'node:fs';\nimport { homedir } from 'node:os';\nimport Handlebars from './handlebars';\n\n// import Emittery from \"emittery\"; // Believed to be unused\nimport { type Config, load } from './config';\nimport type { Secret, RecipientGroup } from './config-file';\n\nexport type AppConfig = Config; // Alias for the main application configuration type\nimport { Host } from './host';\nimport { InteractionHandler } from './interaction-handler';\n\nimport { A } from './flex/array';\nimport { Path } from './flex/path';\nimport * as util from 'node:util';\nimport { ConfigFile } from './config-file';\nimport chalk from 'chalk';\nimport { S } from './flex/set';\nimport { password as promptPassword } from '@inquirer/prompts';\nimport { Listr } from 'listr2';\nimport { isError } from './cli';\nimport { LocalRuntime } from './runtime';\nimport { TmpFileRegistry } from './tempfile';\nimport { NodeRuntime } from './node-runtime';\nimport { zipDirectory } from './zip';\nimport { sha256 } from './hash';\nimport { ParamMap } from './param-map';\nimport {\n type IInvocation,\n type LocalInvocation,\n type RunFnReturnValue,\n type TaskFn,\n type TaskContext,\n type LogLevel,\n type TaskParams,\n RemoteInvocation,\n RemoteRuntime,\n type TaskPartialFn,\n type RunFn,\n} from './runtime';\nimport { version } from './version';\nimport { retryUntilDefined } from 'ts-retry';\nimport { Mutex } from 'async-mutex';\nimport { Command } from './command';\nimport { task } from './runtime'; // Added for executeShellCommandTask\nimport { type CommandResult, type EnvVarObj } from './command'; // EnvVarObj from command.ts\nimport { VP } from './flex/pipe';\nimport { match } from 'ts-pattern';\nimport { SSHSession } from './ssh-session';\nimport runAllRemote from './core/remote/runAllRemote';\nimport { CHECKMARK, withSudo, XMARK } from './util/input-helpers';\n\nexport type TaskTreeNode = {\n id: string;\n parentId: string | null;\n parent: TaskTreeNode | undefined;\n children: Set<TaskTreeNode>;\n name: string;\n result?: Promise<string | Error | undefined>;\n};\ntype NewTaskEvent = { id: string; parentId: string; name: string };\ntype TaskCompleteEvent = { id: string; result: any };\n\nexport class TaskTree {\n // private taskEventBus: Emittery<{ newTask: NewTaskEvent; taskComplete: TaskCompleteEvent }>;\n private listr: Listr;\n private subLists: Map<string, Promise<Listr>>;\n private nodes: Map<string, TaskTreeNode>;\n private mutex: Mutex;\n\n constructor() {\n this.mutex = new Mutex();\n this.nodes = new Map();\n this.subLists = new Map();\n // this.taskEventBus = new Emittery();\n // this.taskEventBus.on(\"newTask\", (newTaskEvent) => {\n // this.handleNewTask(newTaskEvent);\n // });\n // this.taskEventBus.on(\"taskComplete\", (taskCompleteEvent) => {\n // this.handleTaskComplete(taskCompleteEvent);\n // });\n this.listr = new Listr([], {\n // exitOnError: false,\n concurrent: true,\n rendererOptions: { collapseSubtasks: false },\n });\n }\n\n clear() {\n this.nodes.clear();\n this.subLists.clear();\n this.listr = new Listr([], {\n // exitOnError: false,\n concurrent: true,\n rendererOptions: { collapseSubtasks: false },\n });\n }\n\n async add(\n id: string,\n parentId: string | null,\n name: string,\n result?: Promise<string | Error | undefined>,\n ): Promise<TaskTreeNode> {\n return await this.mutex.runExclusive(async () => {\n const parent = this.get(parentId as string);\n const newNode: TaskTreeNode = { id, parentId, parent, children: new Set(), name, result };\n this.nodes.set(id, newNode);\n\n this.listr.add({\n title: newNode.name,\n task: async (ctx, task): Promise<void> => {\n await result;\n },\n });\n\n return newNode;\n });\n }\n\n get(id: string): TaskTreeNode | undefined {\n return this.nodes.get(id);\n }\n\n async getWithTimeout(id: string): Promise<TaskTreeNode | undefined> {\n try {\n return await retryUntilDefined(\n () => {\n return this.get(id);\n },\n { delay: 50, maxTry: 5 },\n );\n } catch (err) {\n return undefined;\n }\n }\n\n // setResult(id: string, result: Promise<string | Error | undefined>): TaskTreeNode | undefined {\n // const node = this.get(id);\n // if (node) {\n // node.result = result;\n // }\n // return node;\n // }\n\n run(ctx?: any) {\n return this.listr.run(ctx);\n }\n\n // emit(name: any, event: any) {\n // this.taskEventBus.emit(name, event);\n // }\n}\n\nexport const Verbosity = {\n ERROR: 0,\n WARN: 1,\n INFO: 2,\n DEBUG: 3,\n TRACE: 4,\n};\n\nexport class App {\n public configRef?: string;\n private _config?: Config;\n public selectedTags: Set<string>;\n private outputStyle: 'plain' | 'json';\n private _tmpDir?: Path;\n private tmpFileRegistry: TmpFileRegistry;\n\n public taskTree: TaskTree;\n public verbosity = Verbosity.ERROR;\n\n constructor() {\n this.taskTree = new TaskTree();\n this.selectedTags = new Set([]);\n this.outputStyle = 'plain';\n this.tmpFileRegistry = new TmpFileRegistry(this.hostctlTmpDir());\n this.configRef = undefined;\n process.on('exit', (code) => this.appExitCallback());\n }\n\n appExitCallback() {\n // This callback is registered for the process 'exit' event.\n // Cleanup tasks, if any, can be performed here.\n // The TmpFileRegistry has its own exit handler to cleanup temporary files.\n }\n\n get config(): Config {\n if (!this._config) {\n throw new Error('Configuration has not been loaded. Call loadConfig() first.');\n }\n return this._config;\n }\n\n get tmpDir(): Path {\n if (!this._tmpDir) {\n // Ensure hostctlDir exists before creating a subdirectory in it.\n if (!fs.existsSync(this.hostctlDir().toString())) {\n fs.mkdirSync(this.hostctlDir().toString(), { recursive: true });\n }\n this._tmpDir = this.createNamedTmpDir(version);\n }\n return this._tmpDir;\n }\n\n async loadConfig(configString?: string) {\n this.configRef = configString;\n this._config = await load(configString);\n }\n\n log(level: LogLevel, ...args: any[]): void {\n if (this.outputStyle === 'plain' && this.verbosity >= level) {\n console.log(...args);\n }\n }\n\n debug(...args: any[]): void {\n this.log(Verbosity.DEBUG, ...args);\n }\n\n info(...args: any[]): void {\n this.log(Verbosity.INFO, ...args);\n }\n\n warn(...args: any[]): void {\n this.log(Verbosity.WARN, ...args);\n }\n\n error(...args: any[]): void {\n this.log(Verbosity.ERROR, ...args);\n }\n\n osHomeDir(): Path {\n return Path.new(homedir()).absolute();\n }\n\n hostctlDir(): Path {\n return this.osHomeDir().join('.hostctl');\n }\n\n hostctlTmpDir() {\n return this.hostctlDir().join('tmp');\n }\n\n randName(): string {\n return Math.random().toString(36).slice(-5) + Math.random().toString(36).slice(-5);\n }\n\n hostctlTmpPath(tmpName?: string) {\n tmpName ??= this.randName();\n return this.hostctlTmpDir().join(tmpName);\n }\n\n // this directory will be automatically cleaned up at program exit\n createNamedTmpDir(subDirName?: string): Path {\n return this.tmpFileRegistry.createNamedTmpDir(subDirName);\n }\n\n // this file will be automatically cleaned up at program exit\n writeTmpFile(fileContent: string): Path {\n return this.tmpFileRegistry.writeTmpFile(fileContent);\n }\n\n shouldRunRemote(): boolean {\n // If any explicitly selected host is remote, assume remote intent for those.\n // If all selected hosts are local or no hosts are specified (implying local), run locally.\n const selectedHosts = this.selectedInventory();\n if (selectedHosts.length === 0 && this.selectedTags.size === 0) return false; // Default to local if no tags/hosts specified\n return selectedHosts.some((h) => !h.isLocal()); // True if any selected host is remote\n }\n\n logHostCommandResult(\n host: Host,\n command: string | string[],\n cmdOrErr: Command | Error,\n isErrorResult: boolean = false,\n ) {\n const hostName = host.uri || (host.isLocal() ? 'localhost' : 'unknown-host');\n if (cmdOrErr instanceof Error || isErrorResult) {\n const error = cmdOrErr as Error;\n this.debug(chalk.red(`[${hostName}] Error executing command \"${command}\": ${error.message}`));\n if (error.stack && this.verbosity >= Verbosity.DEBUG) {\n this.debug(chalk.red(error.stack));\n }\n } else {\n const cmdRes = cmdOrErr.result!;\n this.debug(chalk.green(`[${hostName}] Success executing \"${command}\" (exit code: ${cmdRes.exitCode})`));\n if (cmdRes.stdout) {\n this.debug(chalk.cyan(`[${hostName}] STDOUT:\\n${cmdRes.stdout.trim()}`));\n }\n if (cmdRes.stderr) {\n this.debug(chalk.yellow(`[${hostName}] STDERR:\\n${cmdRes.stderr.trim()}`));\n }\n }\n }\n\n defaultSshUser(): string | undefined {\n // TODO: Implement logic to get default SSH user from config\n // For example, look for a global default or a host-specific override\n // return this.config?.globalSettings?.defaultSshUser;\n return undefined; // Placeholder\n }\n\n // entrypoint for the cli: AGE_IDS=~/.secrets/age/test-jill.priv tsx bin/ops.ts e whoami -t ubuntu\n // e.g. AGE_IDS=~/.secrets/age/david.priv tsx bin/ops.ts -c david.yaml exec \"whoami\" -t synology blog 4gb web1\n async execute(cmd: string | string[]): Promise<boolean> {\n const selectedHosts = this.selectedInventory();\n\n // this.warn(`exec: ${chalk.cyan(cmd)}`);\n const cmdResults: Array<Promise<Command | Error>> = A(selectedHosts).map((host: Host) => this.runRemote(host, cmd));\n\n const hostResultQuads = await VP(selectedHosts)\n .a.zip(cmdResults)\n .a.map(([host, cmdPromise]: [Host, Promise<Command | Error>]) => {\n return cmdPromise.then((cmd) =>\n match(cmd)\n .when(isError, (err) => [host, false, '', chalk.red(err.message)])\n .otherwise((cmd) => [host, cmd.result?.success ?? false, cmd.result?.stdout, cmd.result?.stderr]),\n );\n })\n .waitAll().value;\n\n if (this.outputStyle === 'plain') {\n this.warn(chalk.yellow('=== Result ==='));\n A(hostResultQuads).each(([host, success, stdout, stderr]: [Host, boolean, string, string]) => {\n this.warn(\n `${success ? chalk.green(CHECKMARK) : chalk.red(XMARK)} ${chalk.cyan(host.hostname)}${host.alias ? ` (${host.alias})` : ''}`,\n );\n if (stdout) {\n this.warn(stdout);\n }\n if (stderr) {\n this.warn(chalk.red(stderr));\n }\n this.warn(chalk.yellow('--------------'));\n });\n } else if (this.outputStyle === 'json') {\n const result = A(hostResultQuads).reduce(\n (\n acc: Record<string, { alias: string; success: boolean; stdout: string; stderr: string }>,\n [host, success, stdout, stderr]: [Host, boolean, string, string],\n ) => {\n acc[host.hostname] = {\n alias: host.alias || '',\n success,\n stdout,\n stderr,\n };\n return acc;\n },\n {} as Record<string, { alias: string; success: boolean; stdout: string; stderr: string }>,\n );\n console.log(JSON.stringify(result, null, 2));\n }\n\n return hostResultQuads.every(([_, success]: [Host, boolean]) => success);\n }\n\n // used by execute to run a command on the remote host\n async runRemote(host: Host, cmd: string | string[]): Promise<Command | Error> {\n try {\n const hostPassword = await host.decryptedPassword();\n const sshConnection = {\n host: host.uri,\n username: host.user,\n password: hostPassword,\n privateKeyPath: await host.plaintextSshKeyPath(),\n };\n\n const interactionHandler = InteractionHandler.with(withSudo(hostPassword));\n\n const session = new SSHSession();\n await session.connect(sshConnection);\n\n const commandObj = await session.run(cmd, interactionHandler);\n\n session.disconnect();\n\n return commandObj;\n } catch (e) {\n return e as Error;\n }\n }\n\n getSecretsForHost(hostId: string): Map<string | RegExp, string> {\n const secretsMap = new Map<string | RegExp, string>();\n if (!this._config) {\n return secretsMap; // No config loaded\n }\n // Placeholder: Actual logic to populate secretsMap based on hostId and _config needed here.\n // For now, it correctly returns an empty map if no config or no specific secrets found.\n return secretsMap;\n }\n\n public taskContextForRunFn<TParams extends TaskParams>(\n invocation: IInvocation<TParams>,\n params: TParams,\n hostForContext?: Host, // Optional host, primarily for remote tasks. The invocation itself might have a host.\n ): TaskContext<TParams> {\n const effectiveHost = hostForContext || invocation.host;\n\n return {\n // Properties from TaskContext\n params,\n id: invocation.id,\n host: effectiveHost,\n config: invocation.config, // Delegated from invocation\n\n // Methods from TaskContext, delegating to invocation\n log: (level: LogLevel, ...message: any[]) => {\n invocation.log(level, ...message);\n },\n info: (...message: any[]) => {\n invocation.info(...message);\n },\n debug: (...message: any[]) => {\n invocation.debug(...message);\n },\n warn: (...message: any[]) => {\n invocation.warn(...message);\n },\n error: (...message: any[]) => {\n invocation.error(...message);\n },\n exec: async (\n command: string | string[],\n options?: {\n input?: Record<string, string>;\n sudo?: boolean;\n stdin?: string | Buffer;\n env?: EnvVarObj;\n cwd?: string;\n user?: string;\n pty?: boolean;\n },\n ) => {\n return await invocation.exec(command, options);\n },\n ssh: async <TRemoteParams extends TaskParams, TRemoteReturn extends RunFnReturnValue>(\n tags: string[],\n remoteTaskFn: (remoteContext: TaskContext<TRemoteParams>) => Promise<TRemoteReturn>,\n ): Promise<Record<string, TRemoteReturn | Error>> => {\n return await invocation.ssh(tags, remoteTaskFn);\n },\n run: async <TRunReturn extends RunFnReturnValue>(\n taskPartialFn: TaskPartialFn<TRunReturn>,\n ): Promise<TRunReturn> => {\n return await invocation.run(taskPartialFn);\n },\n getPassword: async (): Promise<string | undefined> => {\n return await invocation.getPassword();\n },\n getSecret: async (name: string): Promise<string | undefined> => {\n return await invocation.getSecret(name);\n },\n exit: (exitCode: number, message?: string): void => {\n invocation.exit(exitCode, message);\n },\n inventory: (tags: string[]): Host[] => {\n return invocation.inventory(tags);\n },\n file: invocation.file,\n };\n }\n\n setSelectedTags(selectedTags: string[]) {\n this.selectedTags = new Set(selectedTags);\n }\n\n setOutputStyle(outputStyle: 'plain' | 'json') {\n this.outputStyle = outputStyle;\n }\n\n setVerbosity(level: number) {\n this.verbosity = level;\n }\n\n outputJson() {\n return this.outputStyle == 'json';\n }\n\n outputPlain() {\n return this.outputStyle == 'plain';\n }\n\n querySelectedInventory(tags: string[] = []): Host[] {\n return this.selectInventory(this.selectedInventory(), new Set(tags));\n }\n\n selectedInventory(): Host[] {\n return this.queryInventory(this.selectedTags);\n }\n\n // returns hosts that have *all* of the given tags\n // each tag is a string of the form:\n // - foo\n // - bar+baz\n // the tags are interpreted to be in disjunctive-normal-form: a disjunction of conjunctions\n queryInventory(tags: Set<string> = new Set()): Host[] {\n if (!this._config) {\n this.warn('Warning: Configuration not loaded, cannot query inventory.');\n return [];\n }\n const allHosts = this._config.hosts(); // Changed from inventory() to hosts()\n if (tags.size === 0) {\n return allHosts;\n }\n return this.selectInventory(allHosts, new Set(tags));\n }\n\n selectInventory(hosts: Host[], tags: Set<string> = new Set()): Host[] {\n if (S(tags).isEmpty()) {\n return hosts;\n }\n\n return A(hosts).select((host: Host) => host.hasAnyTag(tags));\n }\n\n // entrypoint for the cli: AGE_IDS=~/.secrets/age/test-jill.priv tsx bin/hostctl.ts inventory -t ubuntu\n printInventoryReport() {\n const configFromGetter = this.config;\n const config: Config = configFromGetter; // Explicitly type 'config'\n const allHosts = config.hosts(); // Gets all hosts if no tags are specified\n const allSecrets = config.secrets(); // Map<string, Secret>\n const allIds = config.ids(); // Map<string, RecipientGroup>\n\n if (this.outputPlain()) {\n let output = 'Config file: ' + this.configRef + '\\n\\nHosts:\\n';\n if (allHosts.length > 0) {\n allHosts.forEach((host) => {\n output += ` - ${host.uri}:\\n`;\n output += ` alias: ${host.alias || ''}\\n`;\n output += ` user: ${host.user || ''}\\n`;\n output += ` port: ${host.port || ''}\\n`;\n output += ` tags: ${host.tags.join(', ')}\\n`;\n });\n } else {\n output += ' {}\\n';\n }\n\n output += '\\nSecrets:\\n';\n if (allSecrets.size > 0) {\n allSecrets.forEach((secret: Secret, name: string) => {\n output += ` - ${name}:\\n`;\n output += ` encrypted: ${secret.value.isEncrypted()}\\n`;\n });\n } else {\n output += ' {}\\n';\n }\n\n output += '\\nIdentities (Public Keys):\\n';\n if (allIds.size > 0) {\n allIds.forEach((idGroup: RecipientGroup, name: string) => {\n output += ` - ${name}:\\n`;\n output += ` publicKeys: ${idGroup.publicKeys.join(', ')}\\n`;\n });\n } else {\n output += ' {}\\n';\n }\n console.log(output.trim());\n } else if (this.outputJson()) {\n const jsonData: any = {\n hosts: allHosts.map((h) => h.toObject()),\n secrets: {},\n identities: {},\n };\n allSecrets.forEach((secret: Secret, name: string) => {\n jsonData.secrets[name] = {\n name: secret.name,\n encrypted: secret.value.isEncrypted(),\n // Consider if ids/recipients should be exposed here\n };\n });\n allIds.forEach((idGroup: RecipientGroup, name: string) => {\n jsonData.identities[name] = {\n name: (idGroup as any).name || name, // Assuming NamedRecipientGroup has a name property\n publicKeys: idGroup.publicKeys,\n idRefs: idGroup.idRefs,\n };\n });\n console.log(JSON.stringify(jsonData, null, 2));\n }\n }\n\n // entrypoint for the cli: AGE_IDS=~/.secrets/age/test-david.priv tsx bin/hostctl.ts inventory encrypt\n async encryptInventoryFile() {\n if (!this.configRef) {\n throw new Error('Cannot encrypt inventory: Configuration file reference is not set.');\n }\n const currentConfigRef = this.configRef; // this.configRef is now guaranteed to be a string\n this.warn(`Encrypting inventory file: ${currentConfigRef}`);\n const configFile = new ConfigFile(currentConfigRef);\n await configFile.load();\n await configFile.encryptAll();\n await configFile.save(currentConfigRef);\n }\n\n // entrypoint for the cli: AGE_IDS=~/.secrets/age/david.priv tsx bin/hostctl.ts inventory decrypt\n async decryptInventoryFile() {\n if (!this.configRef) {\n throw new Error('Cannot decrypt inventory: Configuration file reference is not set.');\n }\n const currentConfigRef = this.configRef;\n const configFile = new ConfigFile(currentConfigRef);\n await configFile.load();\n\n let hasEncryptedSecrets = false;\n for (const secret of configFile._secrets.values()) {\n if (secret.value.isEncrypted()) {\n hasEncryptedSecrets = true;\n break;\n }\n }\n\n if (!hasEncryptedSecrets) {\n this.info('No encrypted secrets found to decrypt. Inventory is already decrypted.');\n return;\n }\n\n // Only warn if we are actually proceeding with decryption\n this.warn(`Decrypting inventory file: ${currentConfigRef}`);\n\n try {\n await configFile.decryptAllIfPossible();\n\n // Log successfully used keys. This part might need refinement if loadPrivateKeys doesn't accurately reflect *used* keys.\n const successfullyUsedIdentityPaths = configFile\n .loadPrivateKeys() // This loads all keys specified by AGE_IDS\n .filter((identity) => {\n // A more robust check would be to see if AgeEncryption.decrypt reported success with this key.\n // For now, just checking existence, assuming if it was bad, decryptAllIfPossible would have failed.\n try {\n return fs.existsSync(identity.identityFilePath);\n } catch (e) {\n return false;\n }\n })\n .map((i) => i.identityFilePath)\n .join('\\n');\n\n if (this.verbosity >= Verbosity.INFO && successfullyUsedIdentityPaths.length > 0) {\n this.info(`Decrypted with one or more of the following private keys:\\n${successfullyUsedIdentityPaths}`);\n } else if (\n this.verbosity >= Verbosity.INFO &&\n hasEncryptedSecrets &&\n successfullyUsedIdentityPaths.length === 0\n ) {\n // This case implies decryption was attempted but no specified keys worked or were found,\n // though decryptAllIfPossible should ideally throw if it can't decrypt anything it needs to.\n this.warn('Encrypted secrets found, but no specified AGE identities were successfully used or found.');\n }\n\n await configFile.save(currentConfigRef);\n } catch (error: any) {\n if (error.message?.includes('Unable to read identity file')) {\n // Match the test's expected error message pattern for unreadable/missing keys\n throw new Error('Decryption failed: no identity matched or failed to decrypt due to key issue.');\n }\n // Handle cases where decryption fails for other reasons e.g. no matching identity for a secret\n if (error.message?.includes('No identity matched secret')) {\n // Assuming AgeEncryption.decrypt might throw this\n throw new Error('Decryption failed: no identity matched the encrypted secrets.');\n }\n throw error; // Re-throw other errors\n }\n }\n\n // entrypoint for the cli: AGE_IDS=~/.secrets/age/david.priv tsx bin/hostctl.ts -t ubuntu -- script.ts\n // e.g. AGE_IDS=~/.secrets/age/david.priv tsx bin/hostctl.ts -c david.yaml -t synology blog 4gb web1 -- script.ts\n async runScript(scriptRef: string, params: TaskParams) {\n const selectedHosts = this.selectedInventory();\n this.info(`Selected hosts: ${selectedHosts.length}`);\n\n const absoluteScriptRef = Path.new(scriptRef).absolute();\n this.debug(`absoluteScriptRef=${absoluteScriptRef}`);\n this.debug(`params=${util.inspect(params)}`);\n const mod = await this.loadScriptAsModule(absoluteScriptRef.toString());\n\n this.debug(`mod=${util.inspect(mod)}`);\n\n const packageFileDir = this.pathOfPackageJsonFile(absoluteScriptRef.toString());\n if (!packageFileDir) {\n console.error(\n chalk.red(`Bundle failure. \"${absoluteScriptRef}\" nor any ancestor directory contains a package.json file.`),\n );\n return;\n }\n\n const taskFn: TaskFn = mod.default;\n\n const interactionHandler = new InteractionHandler();\n const localRuntime = new LocalRuntime(this, absoluteScriptRef, interactionHandler);\n\n if (this.outputPlain()) {\n this.info(`run: ${chalk.yellow(absoluteScriptRef.toString())} ${chalk.cyan(util.inspect(params))}`);\n }\n\n let invocation: LocalInvocation<any, any> | undefined;\n let scriptResult: RunFnReturnValue | Error;\n try {\n invocation = await (localRuntime as LocalRuntime).invokeRootTask(taskFn, params, `Running ${scriptRef}`);\n if (!invocation) {\n this.error(`Failed to invoke task for script: ${scriptRef}`);\n scriptResult = new Error(`Failed to invoke task for script: ${scriptRef}`);\n } else {\n scriptResult = await invocation.result;\n this.reportScriptResult(invocation, scriptResult);\n }\n } catch (e) {\n scriptResult = e as Error;\n if (this.outputPlain()) {\n this.error(`Error running script ${scriptRef}: ${scriptResult.message}`);\n if (this.verbosity >= Verbosity.DEBUG && scriptResult.stack) {\n this.error(scriptResult.stack);\n }\n }\n if (invocation) {\n this.reportScriptResult(invocation, scriptResult);\n }\n }\n\n if (scriptResult instanceof Error) {\n process.exit(1);\n }\n }\n\n // entrypoint for the cli: AGE_IDS=~/.secrets/age/david.priv tsx bin/hostctl.ts -t ubuntu -- script.ts\n // e.g. AGE_IDS=~/.secrets/age/david.priv tsx bin/hostctl.ts -c david.yaml -t synology blog 4gb web1 -- script.ts\n async runScriptRemote(scriptRef: string, params: TaskParams) {\n const selectedHosts = this.selectedInventory();\n this.info(`Selected hosts: ${selectedHosts.length}`);\n\n const absoluteScriptRef = Path.new(scriptRef).absolute();\n this.debug(`absoluteScriptRef=${absoluteScriptRef}`);\n this.debug(`params=${util.inspect(params)}`);\n const mod = await this.loadScriptAsModule(absoluteScriptRef.toString());\n\n this.debug(`mod=${util.inspect(mod)}`);\n\n const packageFileDir = this.pathOfPackageJsonFile(absoluteScriptRef.toString());\n if (!packageFileDir) {\n console.error(\n chalk.red(`Bundle failure. \"${absoluteScriptRef}\" nor any ancestor directory contains a package.json file.`),\n );\n return;\n }\n\n const taskFn: TaskFn = mod.default;\n\n const interactionHandler = new InteractionHandler();\n const localRuntime = new LocalRuntime(this, absoluteScriptRef, interactionHandler);\n\n this.info(`run: ${chalk.yellow(absoluteScriptRef.toString())} ${chalk.cyan(util.inspect(params))}`);\n\n let invocation: LocalInvocation<any, any> | undefined;\n let scriptResult: RunFnReturnValue | Error;\n try {\n const runAllRemoteParams = { taskFn, params };\n invocation = await (localRuntime as LocalRuntime).invokeRootTask(\n runAllRemote,\n runAllRemoteParams,\n `Running ${scriptRef} on selected hosts`,\n );\n if (!invocation) {\n this.error(`Failed to invoke task for script: ${scriptRef}`);\n scriptResult = new Error(`Failed to invoke task for script: ${scriptRef}`);\n } else {\n scriptResult = await invocation.result;\n this.reportScriptResult(invocation, scriptResult);\n }\n } catch (e) {\n scriptResult = e as Error;\n if (this.outputPlain()) {\n this.error(`Error running script ${scriptRef}: ${scriptResult.message}`);\n if (this.verbosity >= Verbosity.DEBUG && scriptResult.stack) {\n this.error(scriptResult.stack);\n }\n }\n if (invocation) {\n this.reportScriptResult(invocation, scriptResult);\n }\n }\n\n if (scriptResult instanceof Error) {\n process.exit(1);\n }\n }\n\n async walkInvocationTreePreorder(\n invocation: IInvocation<any>,\n visitFn: (invocation: IInvocation<any>, depth: number) => Promise<void>,\n visited: Set<IInvocation<any>> = new Set(),\n depth = 0,\n ) {\n if (visited.has(invocation)) return;\n\n visited.add(invocation);\n await visitFn(invocation, depth);\n\n for (const childInvocation of invocation.getChildren() as IInvocation<any>[]) {\n await this.walkInvocationTreePreorder(childInvocation, visitFn, visited, depth + 1);\n }\n }\n\n async reportScriptResult(invocation: LocalInvocation<any, any>, scriptResult: RunFnReturnValue | Error) {\n if (this.outputPlain()) {\n this.warn('=== Evaluation ===');\n await this.walkInvocationTreePreorder(invocation, async (invocation, depth) => {\n const indent = ' '.repeat(depth);\n if (invocation.getDescription() || invocation.id) {\n const err = await invocation.resultError();\n if (err) {\n if (this.verbosity >= Verbosity.WARN) {\n this.warn(\n `${indent}${chalk.red(XMARK)} ${invocation.getDescription() || invocation.id} ${chalk.red(util.inspect(err))}`,\n );\n if (this.verbosity >= Verbosity.INFO) {\n this.info(`${indent} ${chalk.red(err.message)}`);\n if (this.verbosity >= Verbosity.DEBUG) {\n invocation.stdout && this.debug(`${indent} ${chalk.bgGreen(invocation.stdout.trimEnd())}`);\n invocation.stderr && this.debug(`${indent} ${chalk.bgRed(invocation.stderr.trimEnd())}`);\n }\n }\n }\n } else {\n if (this.verbosity >= Verbosity.WARN) {\n this.warn(`${indent}${chalk.green(CHECKMARK)} ${invocation.getDescription() || invocation.id}`);\n if (this.verbosity >= Verbosity.INFO) {\n this.info(`${indent} ${chalk.green(util.inspect(await invocation.getResultPromise()))}`);\n if (this.verbosity >= Verbosity.DEBUG) {\n invocation.stdout && this.debug(`${indent} ${chalk.bgGreen(invocation.stdout.trimEnd())}`);\n invocation.stderr && this.debug(`${indent} ${chalk.bgRed(invocation.stderr.trimEnd())}`);\n }\n }\n }\n }\n }\n });\n\n this.warn('=== Result ===');\n if (isError(scriptResult)) {\n this.warn(chalk.red(`${invocation.getDescription() || invocation.id} failed:`));\n this.warn(chalk.red(scriptResult.message));\n if (scriptResult.stack) {\n this.warn(chalk.red(scriptResult.stack));\n }\n } else if (\n scriptResult &&\n typeof scriptResult === 'object' &&\n 'exitCode' in scriptResult &&\n typeof scriptResult.exitCode === 'number'\n ) {\n // This case handles an intentional exit requested by the script returning an object like { exitCode: number, message?: string }\n const exitCode = scriptResult.exitCode;\n const message = (scriptResult as any).message || '';\n this.warn(\n chalk.yellow(\n `${invocation.getDescription() || invocation.id} requested exit with code ${exitCode}: ${message}`,\n ),\n );\n } else if (scriptResult === undefined) {\n this.warn(chalk.green(`${invocation.getDescription() || invocation.id} completed successfully.`));\n } else {\n this.warn(\n chalk.green(\n `${invocation.getDescription() || invocation.id} completed with result: ${util.inspect(scriptResult, { depth: 3 })}`,\n ),\n );\n }\n } else if (this.outputJson()) {\n // When JSON output is requested, print the stringified result directly,\n // bypassing the general verbosity-controlled logging system.\n if (!(scriptResult instanceof Error)) {\n console.log(JSON.stringify(scriptResult, null, 2));\n } else {\n // For errors in JSON mode, output a JSON error object to stdout\n const errorJson = {\n error: scriptResult.message,\n stack: scriptResult.stack,\n };\n console.log(JSON.stringify(errorJson, null, 2));\n }\n }\n }\n\n async loadScriptAsModule(scriptRef: string) {\n const mod = await import(scriptRef);\n return mod;\n }\n\n parseParams(scriptArgs: string[]): Object {\n return ParamMap.parse(scriptArgs).toObject();\n }\n\n // this function creates a bundle of a given directory\n async bundleProject(entrypointPath: string) {\n const nodeRuntime = new NodeRuntime(this.tmpDir);\n\n const entrypointDir = this.pathOfPackageJsonFile(entrypointPath);\n\n if (!entrypointDir) {\n console.error(\n chalk.red(`Bundle failure. \"${entrypointPath}\" nor any ancestor directory contains a package.json file.`),\n );\n return;\n }\n // this.info(`Bundle: ${chalk.yellow(directory)}`);\n\n const tasks = new Listr([], {\n exitOnError: false,\n concurrent: true,\n });\n tasks.add([\n {\n title: `Bundling ${entrypointDir.toString()}`,\n task: async (ctx): Promise<void> => {\n await this.generateBundle(nodeRuntime, entrypointDir);\n // await nodeRuntime.installIfNeeded();\n\n // // run npm install on the specified package directory\n // const result = await nodeRuntime.npmInstall(true, entrypointDir.toString());\n // if (result.failure) throw new Error(result.err);\n\n // // zip the package directory\n // const absoluteDirPath = entrypointDir.toString();\n // const dirNameHash = sha256(absoluteDirPath).slice(0, 10);\n // const bundleZipFile = File.join(this.tmpDir, `bundle${dirNameHash}.zip`);\n // await zipDirectory(entrypointDir.toString(), bundleZipFile);\n },\n },\n ]);\n try {\n await tasks.run();\n } catch (e) {\n console.error(e);\n }\n }\n\n async generateBundle(nodeRuntime: NodeRuntime, packageFileDir: Path): Promise<Path> {\n await nodeRuntime.installIfNeeded();\n\n // run npm install on the specified package directory\n const result = await nodeRuntime.npmInstall(true, packageFileDir.toString());\n if (result.failure) throw new Error(result.err);\n\n // zip the package directory\n const absoluteDirPath = packageFileDir.toString();\n const dirNameHash = sha256(absoluteDirPath).slice(0, 10);\n const bundleZipFile = this.tmpDir.join(`bundle${dirNameHash}.zip`);\n const zipPath = await zipDirectory(packageFileDir.toString(), bundleZipFile.toString());\n\n return Path.new(zipPath);\n }\n\n // walks the directory tree that contains the given path from leaf to root searching for the deepest directory\n // containing a package.json file and returns the absolute path of that directory\n pathOfPackageJsonFile(path: string): Path | null {\n let p = Path.new(path);\n while (true) {\n if (p.dirContains('package.json')) {\n return p.absolute();\n }\n if (p.isRoot()) {\n return null;\n }\n\n p = p.parent();\n }\n }\n\n async printRuntimeReport() {\n const nodeRuntime = new NodeRuntime(this.tmpDir);\n\n const reportObj = {\n nodePath: await nodeRuntime.nodePath(),\n npmPath: await nodeRuntime.npmPath(),\n // summary: report?.getReport(),\n };\n this.info(reportObj);\n }\n\n async promptPassword(message = 'Enter your password') {\n return await promptPassword({ message });\n }\n\n async installRuntime() {\n this.info(`creating node runtime with ${this.tmpDir.toString()}`);\n const nodeRuntime = new NodeRuntime(this.tmpDir);\n await nodeRuntime.installIfNeeded();\n }\n\n async bootstrap() {}\n}\n","import Handlebars from 'handlebars';\n\n// per https://github.com/handlebars-lang/handlebars.js/issues/133#issuecomment-2585143\nHandlebars.registerHelper('join', function (items, block) {\n var delimiter = block.hash.delimiter || ',',\n start = block.hash.start || 0,\n len = items ? items.length : 0,\n end = block.hash.end || len,\n out = '';\n\n if (end > len) end = len;\n\n if ('function' === typeof block) {\n for (let i = start; i < end; i++) {\n if (i > start) out += delimiter;\n if ('string' === typeof items[i]) out += items[i];\n else out += block(items[i]);\n }\n return out;\n } else {\n return [].concat(items).slice(start, end).join(delimiter);\n }\n});\nexport default Handlebars;\n","import * as fs from 'node:fs';\nimport { ConfigFile } from './config-file';\nimport { Host } from './host';\nimport { ConfigUrl } from './config-url';\nimport type { Secret, RecipientGroup } from './config-file';\n\nexport interface ISecret {\n name: string;\n recipients(): string[]; // array of strings representing public keys of the identities that may decrypt the secret\n ciphertext(): Promise<string>;\n plaintext(): Promise<string | undefined>;\n}\n\nexport interface IRecipientGroup {\n recipients(): string[]; // returns an array of public keys associated with all immediate and transitive recipients\n}\n\nexport interface Config {\n hosts(): Host[]; // Renamed from inventory()\n secrets(): Map<string, Secret>; // Changed from property to method\n ids(): Map<string, RecipientGroup>; // Changed from property to method\n getSecret(name: string): ISecret | undefined; // Unchanged\n getRecipientGroups(idRefs: string[]): IRecipientGroup[]; // Unchanged\n}\n\nexport async function load(configRef: string | undefined): Promise<Config> {\n if (configRef && fs.existsSync(configRef)) {\n const configFile = new ConfigFile(configRef);\n await configFile.load();\n return configFile;\n } else if (configRef) {\n return new ConfigUrl(configRef);\n } else {\n throw new Error('No config specified.');\n }\n}\n","import fsa from 'node:fs/promises';\nimport fs from 'node:fs';\nimport { glob, globSync, globStream, globStreamSync, Glob } from 'glob';\nimport { base16, base32, base64, base58, bech32 } from '@scure/base';\nimport * as R from 'rambda';\nimport yaml from 'js-yaml';\n// import * as yaml from \"yaml\";\nimport { Host } from './host';\nimport { AgeEncryption, Identity } from './age-encryption';\nimport { A } from './flex/array';\nimport { File } from './flex/file';\nimport { S } from './flex/set';\nimport { VP } from './flex/pipe';\nimport type { Config, IRecipientGroup, ISecret } from './config';\nimport { Undefined, V } from './flex/type';\nimport { M } from './flex/map';\n\ntype YamlHost = {\n alias?: string;\n user?: string;\n password?: SecretRef | string;\n 'ssh-key'?: SecretRef | string;\n tags?: string[];\n};\n\ntype YamlHostsMapping = { [key: string]: YamlHost };\n\ntype YamlSecret = {\n ids: string | string[];\n value: string;\n};\n\ntype YamlSecretsMapping = { [key: string]: YamlSecret };\n\ntype YamlIdsMapping = { [key: string]: string | string[] };\n\ntype YamlConfigFile = {\n hosts?: YamlHostsMapping;\n secrets?: YamlSecretsMapping;\n ids?: YamlIdsMapping;\n};\n\nexport class SecretRef {\n constructor(public name: string) {}\n\n toYAML() {\n return this;\n }\n}\n\nexport class SecretValue {\n constructor(private value: string) {}\n\n async encrypt(recipients: string[]): Promise<string> {\n if (!this.isEncrypted()) {\n this.value = await AgeEncryption.encrypt(this.value, recipients);\n // console.log(`encrypted: ${this.value}`)\n }\n return this.value;\n }\n\n async decrypt(identities: Identity[]): Promise<string | undefined> {\n if (this.isEncrypted()) {\n const decryptedValue = await AgeEncryption.decrypt(\n this.value,\n identities.map((i) => i.identityFilePath),\n );\n if (!decryptedValue) {\n return undefined;\n }\n this.value = decryptedValue;\n }\n return this.value;\n }\n\n isEncrypted() {\n return this.value.includes('AGE ENCRYPTED FILE');\n }\n\n toYAML() {\n return this.value;\n }\n}\n\nexport class Secret implements ISecret {\n constructor(\n public config: ConfigFile,\n public name: string,\n public ids: RecipientGroup,\n public value: SecretValue,\n ) {}\n\n recipients(): string[] {\n return this.ids.recipients();\n }\n\n async ciphertext(): Promise<string> {\n // console.log(`encrypting ${this.name} with ${this.recipients()}`);\n return await this.value.encrypt(this.recipients());\n }\n\n async plaintext(): Promise<string | undefined> {\n const identities = this.config.loadPrivateKeys();\n return await this.value.decrypt(identities);\n }\n\n async encrypt(): Promise<string> {\n return await this.ciphertext();\n }\n\n async decrypt(): Promise<string | undefined> {\n return await this.plaintext();\n }\n\n toYAML() {\n return {\n ids: this.ids.toYAML(),\n value: this.value.toYAML(),\n };\n }\n}\n\nexport class RecipientGroup implements IRecipientGroup {\n constructor(\n public config: ConfigFile,\n public publicKeys: string[],\n public idRefs: string[],\n ) {}\n\n // returns an array of public keys associated with all immediate and transitive recipients\n recipients(): string[] {\n const accumulatedPublicKeys: Set<string> = A(this.publicKeys).toSet();\n\n // console.log(\"111\")\n this.walkRecipientGroups((rg: RecipientGroup) => {\n // console.log(\"222\")\n // VP(accumulatedPublicKeys).pipe(S.addAll(rg.publicKeys));\n S(accumulatedPublicKeys).addAll(rg.publicKeys);\n });\n\n return S(accumulatedPublicKeys).toArray();\n }\n\n walkRecipientGroups(visitFn: (rg: RecipientGroup) => void, visited: Set<RecipientGroup> = new Set()) {\n if (visited.has(this)) return;\n\n visited.add(this);\n visitFn(this);\n\n this.config.getRecipientGroups(this.idRefs).forEach((rg) => rg.walkRecipientGroups(visitFn, visited));\n }\n\n toYAML() {\n return this.publicKeys.concat(this.idRefs);\n }\n}\n\nexport class NamedRecipientGroup extends RecipientGroup {\n constructor(\n public config: ConfigFile,\n public name: string,\n public publicKeys: string[],\n public idRefs: string[],\n ) {\n super(config, publicKeys, idRefs);\n }\n}\n\nconst SecretRefYamlType = new yaml.Type('!secret', {\n kind: 'scalar', // 'scalar' means string\n\n // Loader must check if the input object is suitable for this type.\n resolve(data): boolean {\n return !!data && typeof data === 'string' && data.trim().length > 0;\n },\n\n // If a node is resolved, use it to create a SecretRef instance.\n construct(yamlObj) {\n return new SecretRef(yamlObj); // yamlObj should be a string\n },\n\n // Dumper must process instances of Point by rules of this YAML type.\n instanceOf: SecretRef,\n\n // Dumper must represent SecretRef objects as string in YAML.\n represent(secretRef) {\n return (secretRef as SecretRef).name;\n },\n});\n\nconst HOSTCTL_CONFIG_SCHEMA = yaml.DEFAULT_SCHEMA.extend([SecretRefYamlType]);\n\nexport class ConfigFile implements Config {\n public _hosts: Map<string, Host>;\n public _ids: Map<string, RecipientGroup>;\n public _secrets: Map<string, Secret>;\n\n constructor(public path: string) {\n this._hosts = new Map();\n this._ids = new Map();\n this._secrets = new Map();\n }\n\n // serialization and deserialization\n\n async load() {\n if (!File.exists(this.path)) {\n throw new Error(`Config file ${this.path} doesn't exist. Unable to load.`);\n }\n\n const yamlFileContents = await fsa.readFile(this.path, {\n encoding: 'utf8',\n });\n\n const yamlDocument: YamlConfigFile = yaml.load(yamlFileContents, {\n schema: HOSTCTL_CONFIG_SCHEMA,\n }) as YamlConfigFile;\n\n this.parse(yamlDocument);\n }\n\n parse(yamlDocument: YamlConfigFile) {\n this._hosts = this.parseHosts(yamlDocument.hosts || {});\n this._ids = this.parseIdsMap(yamlDocument.ids || {});\n this._secrets = this.parseSecrets(yamlDocument.secrets || {});\n }\n\n parseSecretValue(yamlSecretValue: SecretRef | string | undefined): SecretRef | string | undefined {\n switch (V(yamlSecretValue).kind()) {\n case Undefined:\n return yamlSecretValue as undefined;\n case SecretRef:\n return yamlSecretValue as SecretRef;\n case String:\n return yamlSecretValue as string;\n // return new SecretValue(yamlSecretValue as string);\n default:\n throw new Error(`unknown secret type: ${V.inspect(yamlSecretValue)}`);\n }\n }\n\n // yamlHosts is an object\n parseHosts(yamlHosts: YamlHostsMapping): Map<string, Host> {\n const hosts = Object.entries(yamlHosts).reduce((hostMap: Map<string, Host>, [hostUri, hostObj]) => {\n hostObj ||= {};\n const password = this.parseSecretValue(hostObj.password);\n const sshKey = this.parseSecretValue(hostObj['ssh-key']);\n // console.log(\n // `parse host: ${JSON.stringify(hostObj)}; ${hostObj[\"ssh-key\"]}; password ${V(password).inspect()} ; sshkey ${V(sshKey).inspect()}`\n // );\n hostMap.set(\n hostUri,\n new Host(this, {\n ...(hostObj as any), // Use 'as any' to allow spread of hostObj properties\n hostname: hostUri, // The YAML map key is always the hostname\n password,\n sshKey,\n }),\n );\n return hostMap;\n }, new Map());\n return hosts;\n }\n\n parseIdsMap(yamlIds: YamlIdsMapping): Map<string, RecipientGroup> {\n const ids = Object.entries(yamlIds).reduce((secretsMap: Map<string, RecipientGroup>, [name, value]) => {\n value ||= [];\n const rg = this.parseRecipients(value as string[]);\n secretsMap.set(name, new NamedRecipientGroup(this, name, rg.publicKeys, rg.idRefs));\n return secretsMap;\n }, new Map());\n return ids;\n }\n\n parseRecipients(ids: string | string[] | (string | string[])[]): RecipientGroup {\n let idStrings: string[];\n if (V(ids).isA(String)) {\n idStrings = [ids as string];\n } else if (Array.isArray(ids) && ids.every((item: any) => V(item).isA(String))) {\n idStrings = ids as string[]; // ids is string[]\n } else if (Array.isArray(ids)) {\n // Handles (string | string[])[]\n idStrings = (ids as (string | string[])[]).flat(1) as string[];\n } else {\n // ids is not a string and not an array (e.g. undefined, null from YAML parsing)\n // This situation should ideally be handled based on how YAML treats missing/null recipient lists.\n // For now, default to an empty array to prevent further errors, with a warning.\n // console.warn(`[ConfigFile.parseRecipients] 'ids' field has unexpected type: ${typeof ids}. Expected string or array. Defaulting to empty recipient list.`);\n idStrings = [];\n }\n const publicKeysAndIdRefs = idStrings.flatMap((str) => str.split(',')).map((str) => str.trim());\n const [publicKeys, idRefs] = A(publicKeysAndIdRefs).partition(this.isValidPublicKey);\n return new RecipientGroup(this, publicKeys, idRefs);\n }\n\n // returns true if the key is an Age encryption public key (i.e. a bech32 key with a prefix of 'age')\n isValidPublicKey(str: string): boolean {\n try {\n const { prefix, words } = bech32.decode(str as any);\n return prefix === 'age';\n } catch (e) {\n return false;\n }\n }\n\n // yamlSecrets is an object\n parseSecrets(yamlSecrets: YamlSecretsMapping): Map<string, Secret> {\n const secrets = Object.entries(yamlSecrets).reduce((secretsMap: Map<string, Secret>, [name, yamlSecret]) => {\n // yamlSecret ||= {};\n\n const recipients = this.parseRecipients(yamlSecret.ids);\n\n secretsMap.set(name, new Secret(this, name, recipients, new SecretValue(yamlSecret.value)));\n return secretsMap;\n }, new Map());\n return secrets;\n }\n\n async save(destinationPath: string = this.path) {\n const hosts = this.serializeHosts();\n const secrets = this.serializeSecrets();\n const ids = this.serializeIds();\n const yamlFileObj = {\n hosts,\n secrets,\n ids,\n };\n const yamlFileContents = yaml.dump(yamlFileObj, {\n schema: HOSTCTL_CONFIG_SCHEMA,\n noRefs: true,\n });\n await fsa.writeFile(destinationPath, yamlFileContents);\n }\n\n serializeHosts() {\n // return M.toObject(M.map(([name, host]) => [name, host.toYAML()])(this.hosts));\n return VP(this._hosts)\n .map(([name, host]: [string, Host]) => [name, host.toYAML()])\n .m.toObject().value;\n }\n\n serializeSecrets() {\n // return M.toObject(\n // M.map(([name, secret]) => [name, secret.toYAML()])(this.secrets)\n // );\n return VP(this._secrets)\n .map(([name, secret]) => [name, secret.toYAML()])\n .m.toObject().value;\n }\n\n serializeIds() {\n // return M.toObject(M.map(([name, id]) => [name, id.toYAML()])(this.ids));\n return VP(this._ids)\n .map(([name, id]) => [name, id.toYAML()])\n .m.toObject().value;\n }\n\n // domain logic\n\n // loads private keys from the AGE_IDS environment variable\n loadPrivateKeys(): Identity[] {\n const ageIds = process.env.AGE_IDS;\n // console.log(`AGE_IDS=${ageIds}`);\n if (ageIds) {\n const paths = globSync(ageIds);\n // console.log(`Loading private keys from ${ageIds}: ${paths}`);\n const ids = paths.map((path) => new Identity({ path }));\n // console.log(`Loaded ${V(ids).inspect()}`);\n return ids;\n }\n return [];\n }\n\n getSecret(name: string): Secret | undefined {\n return this._secrets.get(name);\n }\n\n getRecipientGroups(idRefs: string[]): RecipientGroup[] {\n // return pipe(idRefs, A.map(this.ids.get), A.compact());\n return VP(idRefs)\n .map((idRef: string) => this._ids.get(idRef))\n .compact().value;\n }\n\n async decryptAllIfPossible(): Promise<void> {\n await VP(this._secrets)\n .m.values()\n .map((secret: Secret) => secret.decrypt())\n .waitAll().value;\n }\n\n async encryptAll(): Promise<void> {\n await VP(this._secrets)\n .m.values()\n .map((secret: Secret) => secret.encrypt())\n .waitAll().value;\n }\n\n // Config interface\n\n hosts(): Host[] {\n return M(this._hosts).values();\n }\n\n secrets(): Map<string, Secret> {\n return this._secrets;\n }\n\n ids(): Map<string, RecipientGroup> {\n return this._ids;\n }\n}\n","export const GeneratorFunction = function* () {}.constructor;\n\nexport interface BaseWrapperProxy {\n <T>(wrappedValue: T): any; // Generic call signature for the proxy itself\n registerUncurriedFns: (fns: FunctionBag) => void;\n registerCurriedFns: (fns: FunctionBag) => void;\n registerStatic: (fns: FunctionBag) => void;\n}\n\ninterface InternalFunctionWithRegMethods extends Function {\n registerUncurriedFns: (fns: FunctionBag) => void;\n registerCurriedFns: (fns: FunctionBag) => void;\n registerStatic: (fns: FunctionBag) => void;\n}\n\n// export function buildPipeThroughFunction() {\n// function func(wrappedValue) {\n// // wrappedValue is the value passed to the object wrapper function. e.g. A([1,2,3]) the wrappedValue is [1,2,3] and A is the wrapper function called func in this context\n// return new Proxy(wrappedValue, {\n// get(target, property, receiver) {\n// // function objects, like O, don't have any properties, so the only properties present will be the function objects we assign to the 'O' function object\n// const fn = Reflect.get(func, property, receiver);\n// if (fn === undefined) {\n// return Reflect.get(target, property, receiver); // target === wrappedValue\n// }\n// const fnParams = parameters(fn);\n// const noParameters = fnParams.length === 0;\n// return function (...args: any) {\n// if (noParameters || args.length === 0) {\n// // then we are going to treat fn as a function expecting the obj to be supplied as an argument\n// return fn.call(receiver, target);\n// } else {\n// // otherwise, we are going to treat fn as a function expecting the args to be supplied as the argument, which will return a second function that expects the obj to be supplied as its argument\n// return fn.apply(receiver, args)(target);\n// }\n// };\n// },\n// });\n// }\n// return func;\n// }\n\nexport type FunctionBag = { [key: string]: Function };\nexport class MethodBag {\n public methods: Map<string, [Function, number]>;\n public staticMethods: Map<string, Function>;\n constructor() {\n this.methods = new Map();\n this.staticMethods = new Map();\n }\n registerUncurriedFns(fnBag: FunctionBag) {\n Object.entries(fnBag).forEach(([functionName, functionObj]) => {\n this.methods.set(functionName, [functionObj, 1]);\n });\n }\n registerCurriedFns(fnBag: FunctionBag) {\n Object.entries(fnBag).forEach(([functionName, functionObj]) => {\n this.methods.set(functionName, [functionObj, 2]);\n });\n }\n registerStatic(fnBag: FunctionBag) {\n Object.entries(fnBag).forEach(([functionName, functionObj]) => {\n this.staticMethods.set(functionName, functionObj);\n });\n }\n lookup(fnName: string): [Function, number] | undefined {\n const pair = this.methods.get(fnName);\n if (!pair) {\n return undefined;\n }\n return pair;\n }\n lookupStatic(fnName: string): Function | undefined {\n const fn = this.staticMethods.get(fnName);\n if (!fn) {\n return undefined;\n }\n return fn;\n }\n}\n\nexport function buildWrapperProxy(): BaseWrapperProxy {\n const methods = new MethodBag();\n function func(wrappedValue: any): any {\n // wrappedValue is the value passed to the object wrapper function. e.g. A([1,2,3]) the wrappedValue is [1,2,3] and A is the wrapper function called func in this context\n return new Proxy(wrappedValue, {\n get(target: any, property: string | symbol, receiver: any) {\n // function objects, like O, don't have any properties, so the only properties present will be the function objects we assign to the 'O' function object\n const fnArityPair = methods.lookup(property.toString());\n if (fnArityPair === undefined) {\n return Reflect.get(target, property, receiver); // target === wrappedValue\n }\n const [fn, arity] = fnArityPair;\n return function (...args: any) {\n if (arity === 1) {\n // then we are going to treat fn as a function expecting the obj to be supplied as an argument\n return fn.call(receiver, target);\n } else {\n // otherwise, we are going to treat fn as a function expecting the args to be supplied as the argument, which will return a second function that expects the obj to be supplied as its argument\n return fn.apply(receiver, args)(target);\n }\n };\n },\n });\n }\n Object.assign(func, {\n registerUncurriedFns: (fnBag: FunctionBag): void => {\n methods.registerUncurriedFns(fnBag);\n },\n registerCurriedFns: (fnBag: FunctionBag): void => {\n methods.registerCurriedFns(fnBag);\n },\n registerStatic: (fnBag: FunctionBag): void => {\n methods.registerStatic(fnBag);\n },\n });\n const funcWithMethods = func as unknown as InternalFunctionWithRegMethods;\n return new Proxy(funcWithMethods, {\n get(target: any, property: string | symbol, receiver: any) {\n const fn = methods.lookupStatic(property.toString());\n if (fn === undefined) {\n return Reflect.get(target, property, receiver); // target === func\n }\n return fn;\n },\n }) as BaseWrapperProxy;\n}\n\n// taken from https://javascript.info/currying-partials\nexport function curry(func: (...args: any[]) => any) {\n return function curried(this: any, ...args: any[]): any {\n if (args.length >= func.length) {\n return func.apply(this, args);\n } else {\n return function (this: any, ...args2: any[]): any {\n return curried.apply(this, args.concat(args2));\n };\n }\n };\n}\n\nexport function identity(val: any): any {\n return val;\n}\n\n// taken from https://stackoverflow.com/questions/1007981/how-to-get-function-parameter-names-values-dynamically\nexport function parameters(func: any): string[] {\n const ARROW = true;\n const FUNC_ARGS = ARROW ? /^(function)?\\s*[^\\(]*\\(\\s*([^\\)]*)\\)/m : /^(function)\\s*[^\\(]*\\(\\s*([^\\)]*)\\)/m;\n const FUNC_ARG_SPLIT = /,/;\n const FUNC_ARG = /^\\s*(_?)(.+?)\\1\\s*$/;\n const STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/gm;\n\n return ((func || '').toString().replace(STRIP_COMMENTS, '').match(FUNC_ARGS) || ['', '', ''])[2]\n .split(FUNC_ARG_SPLIT)\n .map(function (arg: string) {\n return arg.replace(FUNC_ARG, function (all: string, underscore: string, name: string) {\n return name.split('=')[0].trim();\n });\n })\n .filter(String);\n}\n\nexport function thread(...args: ((arg: any) => any)[]) {\n return function (firstArg: any | undefined = undefined) {\n let pipeline = args;\n if (firstArg !== undefined) {\n pipeline.unshift(firstArg);\n }\n return pipeline.reduce((arg: any, fn: (arg: any) => any) => fn(arg));\n };\n}\n\nexport function threadR(...fns: ((arg: any) => any)[]) {\n return function (firstArg: any = undefined) {\n let pipeline = fns;\n if (firstArg !== undefined) {\n pipeline.push(firstArg);\n }\n return pipeline.reduceRight((arg: any, fn: (arg: any) => any) => fn(arg));\n };\n}\n\nexport interface FunctionUtilWrapperProxy extends BaseWrapperProxy {\n curry: (func: (...args: any[]) => any) => (...args: any[]) => any;\n identity: (val: any) => any;\n parameters: (func: any) => string[];\n thread: (...args: any[]) => (firstArg?: any) => any;\n threadR: (...fns: any[]) => (firstArg?: any) => any;\n}\n\n// export const F = {\n// curry,\n// identity,\n// thread,\n// };\n\nexport const F = buildWrapperProxy() as FunctionUtilWrapperProxy;\nF.registerUncurriedFns({ parameters });\n// F.registerCurriedFns({ });\nF.registerStatic({\n curry,\n identity,\n parameters,\n thread,\n threadR,\n});\n","import { Mutex } from 'async-mutex';\n\nimport { V, kind } from './type';\n\nexport type AnyConstructor = new (...args: any[]) => any;\n\n// This represents a set of implementations of the same protocol for the same type.\n// The implementations are named for disambuation purposes.\nclass NamedImplementations<StoredItemType> {\n constructor(\n public impls: Map<string, StoredItemType> = new Map(),\n public defaultImpl: string = '',\n ) {}\n\n register<SpecificItemType extends StoredItemType>(\n name: string,\n implClass: SpecificItemType,\n makeDefault: boolean = false,\n ) {\n if (this.impls.size === 0 || makeDefault) {\n this.setDefaultImpl(name);\n }\n this.impls.set(name, implClass);\n }\n\n get(name?: string): StoredItemType | undefined {\n return this.impls.get(name || this.defaultImpl);\n }\n\n setDefaultImpl(name: string) {\n this.defaultImpl = name;\n }\n}\n\n// This class captures all the named implementations of a particular typeclass/protocol associated with a given type.\n// There will be one of these ImplementationRegistry objects for every typeclass/protocol.\n// This class is responsible for associating types with their corresponding implementations of the typeclass/protocol that this\n// instance represents.\n// For example:\n// const mappableImplementations = new ImplementationRegistry(\"Mappable\");\n// In this example, mappableImplementations would represent all of the named implementations of the Mappable typeclass/protocol\n// for any type. The implementations private member would store all of the per-type named implementations of the Mappable typeclass/protocol\n// as (type => named implementations) pairs.\nclass ImplementationRegistry {\n // implementations is a Map of (type constructor function => ProtocolImplGroup) pairs\n // It stores all the named implementations of the typeclass/protocol associated with the type stored in the key of the map\n private implementations: Map<AnyConstructor, NamedImplementations<AnyConstructor>> = new Map();\n\n constructor(public name: string) {}\n\n register(classConstructor: AnyConstructor, implClass: AnyConstructor, makeDefault: boolean = false) {\n let protocolImplGroup = this.implementations.get(classConstructor);\n if (!protocolImplGroup) {\n protocolImplGroup = new NamedImplementations<AnyConstructor>();\n this.implementations.set(classConstructor, protocolImplGroup);\n }\n\n protocolImplGroup.register(implClass.name, implClass, makeDefault);\n }\n\n use(classConstructor: AnyConstructor, implClass: AnyConstructor) {\n this.register(classConstructor, implClass, true);\n }\n\n public clear() {\n this.implementations.clear();\n }\n\n // returns a class object that implements the typeclass/protocol - this is an implementation of the typeclass/protocol for a given type\n get(classConstructor: AnyConstructor, name?: string) {\n const protocolImplGroup = this.implementations.get(classConstructor);\n if (!protocolImplGroup) {\n throw new Error(`Protocol ${this.name} not implemented by ${classConstructor}`);\n }\n const impl = protocolImplGroup.get(name);\n if (!impl) {\n throw new Error(\n `Named implementation '${\n name || protocolImplGroup.defaultImpl\n }' of protocol ${this.name} not implemented by ${classConstructor}`,\n );\n }\n return impl;\n }\n}\n\n// declare global {\n// var protocolRegistry: Map<string, ImplementationRegistry>;\n// var protocolRegistryLock: Mutex;\n// }\n// global.protocolRegistryLock = global.protocolRegistryLock || new Mutex();\n// await global.protocolRegistryLock.runExclusive(async () => {\n// global.protocolRegistry = global.protocolRegistry || new Map();\n// });\n\n// Every implementation of the protocol must conform to the same interface.\n// The interface defines which methods a user of the protocol implementation may invoke.\nexport class Protocol {\n static protocolRegistryLock: Mutex;\n static registry: Map<string, ImplementationRegistry>;\n\n static {\n Protocol.protocolRegistryLock = Protocol.protocolRegistryLock || new Mutex();\n Protocol.registry = Protocol.registry || new Map();\n }\n\n static getTypeclass(): ImplementationRegistry {\n if (this.registry.has(this.name)) {\n return this.registry.get(this.name) as ImplementationRegistry;\n } else {\n const newTypeclass = new ImplementationRegistry(this.name);\n this.registry.set(this.name, newTypeclass);\n return newTypeclass;\n }\n }\n\n // static getTypeclass(): ImplementationRegistry {\n // if (global.protocolRegistry.has(this.name)) {\n // return global.protocolRegistry.get(this.name) as ImplementationRegistry;\n // } else {\n // const newTypeclass = new ImplementationRegistry(this.name);\n // global.protocolRegistry.set(this.name, newTypeclass);\n // return newTypeclass;\n // }\n // }\n\n static async register(classConstructor: AnyConstructor, implClass: AnyConstructor, makeDefault: boolean = false) {\n await Protocol.protocolRegistryLock.runExclusive(async () => {\n let typeclass = this.getTypeclass();\n typeclass.register(classConstructor, implClass, makeDefault);\n });\n }\n\n static async use(classConstructor: AnyConstructor, implClass: AnyConstructor) {\n await Protocol.protocolRegistryLock.runExclusive(async () => {\n let typeclass = this.getTypeclass();\n typeclass.use(classConstructor, implClass);\n });\n }\n\n // returns a class object that implements the typeclass - this is an implementation of the typeclass for a given type\n static get(classConstructor: AnyConstructor, name?: string) {\n const typeclass = this.getTypeclass();\n // console.log(`looking up typeclass ${typeclass.name} implementation for ${classConstructor.name} named ${name}`)\n return typeclass.get(classConstructor, name);\n }\n\n // returns an instance of the class that implements the typeclass\n // For example, Enumerable.for([1,2,3]) returns a new instance of the EnumerableArray implementation of the\n // Enumerable typeclass on the Array type, initialized with [1,2,3] in the constructor\n static for<S extends Protocol>(\n instance: any,\n // Allow passing the implementation class constructor directly.\n // The 'implClass' parameter from the original signature was used for named lookup,\n // which is handled by this.get() when explicitImplClass is not provided.\n explicitImplClass?: new (self: any) => S,\n ) {\n let finalImplConstructor: new (self: any) => S;\n\n if (explicitImplClass) {\n finalImplConstructor = explicitImplClass;\n } else {\n // Lookup in registry if no explicit class is provided.\n // this.get will retrieve the default implementation for kind(instance).\n finalImplConstructor = this.get(\n kind(instance),\n // No name needed here for the default lookup via this.get(typeConstructor)\n ) as new (self: any) => S;\n }\n return new finalImplConstructor(instance);\n }\n}\n\n// // TC is the class that represents the typeclass, e.g. Mappable\n// class NamedImplementations<TC extends Protocol> {\n// constructor(\n// // new () => TypeclassClass means the constructor function for the TypeclassClass\n// public impls: Map<string, ImplCtor<any, TC>> = new Map(), // this map stores named references to implementations of typeclass classes, e.g. 'MappableArray' -> MappableArray class that extends Mappable, etc.\n// public defaultImpl: string = \"\"\n// ) {}\n\n// register<Impl extends TC>(\n// name: string,\n// implClass: ImplCtor<TC, Impl>,\n// makeDefault: boolean = false\n// ) {\n// if (this.impls.size === 0 || makeDefault) {\n// this.setDefaultImpl(name);\n// }\n// this.impls.set(name, implClass);\n// }\n\n// get<Impl extends TC>(name?: string): Impl | undefined {\n// return this.impls.get(name || this.defaultImpl) as Impl | undefined;\n// }\n\n// setDefaultImpl(name: string) {\n// this.defaultImpl = name;\n// }\n// }\n\n// type EmptyConstructorFor<T> = {\n// new (): T;\n// }\n\n// type ImplCtor<TC extends Protocol, ImplClass extends TC> = EmptyConstructorFor<ImplClass>\n\n// type TCCtor<TC extends Protocol> = EmptyConstructorFor<TC>;\n\n// type TypeThatImplementsATypeclass = Function;\n\n// // Every implementation of the protocol must conform to the same interface.\n// // The interface defines which methods a user of the protocol implementation may invoke.\n// export abstract class Protocol {\n// // // Protocl has two parts, static and instance.\n// // // the static bits have to do with the registry at the class level, e.g. Mappable is a static registry for Mappable implementations\n// // // the instance bits are the implementation of the Mappable\n\n// // // this field is shared among all subclasses of Protocol\n// // private static registry: Map<string, Protocol> = new Map(); // this is a map of (typeclass name -> typeclass instance) pairs.\n\n// // static getTypeclass<TC extends Protocol>(): TC {\n// // if (this.registry.has(this.name)) {\n// // // in this context, this will not be `Protocol`, it will be a subclass of `Protocol`, like `Mappable`.\n// // return this.registry.get(this.name) as unknown as TC;\n// // } else {\n// // const newTypeclass = new (this as unknown as TCCtor<TC>)(); // in this context, this will not be `Protocol`, it will be a subclass of `Protocol`, like `Mappable`.\n// // this.registry.set(this.name, newTypeclass);\n// // return newTypeclass;\n// // }\n// // }\n\n// // static register(\n// // classConstructor: TypeThatImplementsATypeclass,\n// // implClass,\n// // makeDefault: boolean = false\n// // ) {\n// // let typeclass = this.getTypeclass<TC>();\n// // typeclass.register(classConstructor, implClass, makeDefault);\n// // }\n\n// // static use(classConstructor: TypeThatImplementsATypeclass, implClass) {\n// // let typeclass = this.getTypeclass();\n// // typeclass.use(classConstructor, implClass);\n// // }\n\n// // // returns a class object that implements the typeclass - this is an implementation of the typeclass for a given type\n// // static get<TC extends Protocol, ImplClass extends TC>(\n// // classConstructor: TypeThatImplementsATypeclass,\n// // name?: string\n// // ): ImplCtor<TC, ImplClass> {\n// // const typeclass = this.getTypeclass();\n// // // console.log(`looking up typeclass ${typeclass.name} implementation for ${classConstructor.name} named ${name}`)\n// // return typeclass.get(classConstructor, name);\n// // }\n\n// // returns an instance of the class that implements the typeclass\n// // For example, Enumerable.for([1,2,3]) returns a new instance of the EnumerableArray implementation of the\n// // Enumerable typeclass on the Array type, initialized with [1,2,3] in the constructor\n// static for<TC extends Protocol, ImplClass extends TC>(\n// instance,\n// implClassConstructor = undefined\n// ): ImplClass {\n// const implConstructor = ProtocolRegistry.get(this, kind(instance), implClassConstructor?.name);\n// return new implConstructor(instance);\n// }\n\n// // implementations is a Map of (type => NamedImplementations<typeclass class>) pairs\n// // e.g. 'String' -> NamedImplementations<Mappable>\n// // It stores all the named implementations of the typeclass/protocol associated with the type stored in the key of the map\n// private implementations: Map<\n// TypeThatImplementsATypeclass,\n// NamedImplementations<typeof this>\n// > = new Map();\n\n// // constructor(public name: string) {} // we don't need the name anymore because the this.constructor.name is the name of the typeclass, e.g. class Mappable extends Protocol; new Mappable().name is the name \"Mappable\"\n\n// register<ImplClass extends typeof this>(\n// classConstructor: TypeThatImplementsATypeclass,\n// implClassConstructor: EmptyConstructorFor<ImplClass>,\n// makeDefault: boolean = false\n// ) {\n// let protocolImplGroup = this.implementations.get(classConstructor);\n// if (!protocolImplGroup) {\n// protocolImplGroup = new NamedImplementations<typeof this>();\n// this.implementations.set(classConstructor, protocolImplGroup);\n// }\n\n// protocolImplGroup.register(\n// implClassConstructor.name,\n// implClassConstructor,\n// makeDefault\n// );\n// }\n\n// use<ImplClass extends typeof this>(\n// classConstructor: TypeThatImplementsATypeclass,\n// implClassConstructor: EmptyConstructorFor<ImplClass>,\n// ) {\n// this.register(classConstructor, implClassConstructor, true);\n// }\n\n// // returns a class object that implements the typeclass/protocol - this is an implementation of the typeclass/protocol for a given type\n// get(\n// classConstructor: TypeThatImplementsATypeclass,\n// name?: string\n// ): typeof this {\n// const protocolImplGroup = this.implementations.get(classConstructor);\n// if (!protocolImplGroup) {\n// throw `Protocol ${this.constructor.name} not implemented by ${classConstructor}`;\n// }\n// const impl = protocolImplGroup.get(name);\n// if (!impl) {\n// throw `Named implementation '${\n// name || protocolImplGroup.defaultImpl\n// }' of protocol ${\n// this.constructor.name\n// } not implemented by ${classConstructor}`;\n// }\n// return impl;\n// }\n// }\n\n// // Every implementation of the protocol must conform to the same interface.\n// // The interface defines which methods a user of the protocol implementation may invoke.\n// export abstract class ProtocolRegistry {\n// private static registry: Map<string, Protocol> = new Map(); // this is a map of (typeclass name -> typeclass instance) pairs.\n\n// static getTypeclassForImpl<TC extends Protocol>(implClassCtor): TC {\n// const typeclassCtor = V(implClassCtor).superclass();\n// return this.getTypeclass(typeclassCtor.name);\n// }\n\n// static getTypeclass<TC extends Protocol>(typeclassName): TC {\n// if (this.registry.has(typeclassName)) {\n// return this.registry.get(typeclassName) as unknown as TC;\n// } else {\n// const newTypeclass = new (this as unknown as TCCtor<TC>)(); // in this context, this will not be `Protocol`, it will be a subclass of `Protocol`, like `Mappable`.\n// this.registry.set(typeclassName, newTypeclass);\n// return newTypeclass;\n// }\n// }\n\n// static register(\n// classConstructor: TypeThatImplementsATypeclass,\n// implClassCtor,\n// makeDefault: boolean = false\n// ) {\n// let typeclass = this.getTypeclassForImpl<typeof implClassCtor>(implClassCtor);\n// typeclass.register(classConstructor, implClassCtor, makeDefault);\n// }\n\n// static use(classConstructor: TypeThatImplementsATypeclass, implClassCtor) {\n// let typeclass = this.getTypeclassForImpl<typeof implClassCtor>(implClassCtor);\n// typeclass.use(classConstructor, implClassCtor);\n// }\n\n// // returns a class object that implements the typeclass - this is an implementation of the typeclass for a given type\n// static get<TC extends Protocol, ImplClass extends TC>(\n// typeclassCtor,\n// classConstructor: TypeThatImplementsATypeclass,\n// name?: string\n// ) {\n// // console.log(`looking up typeclass ${typeclass.name} implementation for ${classConstructor.name} named ${name}`)\n// const typeclass = this.registry.get(typeclassCtor.name) as Protocol;\n// return typeclass.get(classConstructor, name);\n// }\n// }\n","import { inspect as nodeInspect } from 'node:util';\nimport { MethodBag, type FunctionBag } from './function';\n\nexport class End {\n private static _instance: End;\n\n private constructor() {}\n\n public static get instance(): End {\n if (!this._instance) {\n this._instance = new End();\n }\n return this._instance;\n }\n}\nexport class Undefined {}\nexport class Null {}\nexport class Class {}\n\nexport function inspect(valueToInspect: any) {\n return nodeInspect(valueToInspect, { showProxy: true });\n}\n\nexport function isA(predicateType: any) {\n return function (value: any): boolean {\n return (\n value instanceof predicateType ||\n kind(value) === predicateType ||\n (value != null &&\n (value.constructor === predicateType || (predicateType.name === 'Object' && typeof value === 'object')))\n );\n };\n}\n\nexport function isAbsent(value: any): boolean {\n return value === null || value === undefined;\n}\n\nexport function isDefined(value: any): boolean {\n return value !== undefined;\n}\n\nconst BUILT_IN_CONSTRUCTORS = [\n String,\n Number,\n Boolean,\n Array,\n Object,\n Function,\n Date,\n RegExp,\n Map,\n Set,\n Error,\n Promise,\n Symbol,\n BigInt,\n];\n\nexport function isClass(fn: any): boolean {\n if (typeof fn !== 'function') {\n return false;\n }\n // Check for class keyword syntax for user-defined classes\n if (/^class\\s/.test(Function.prototype.toString.call(fn))) {\n return true;\n }\n // Check if it's one of the built-in constructors that should be treated as a class\n if (BUILT_IN_CONSTRUCTORS.includes(fn)) {\n return true;\n }\n return false;\n}\n\n// true for arrays, functions, objects\nexport function isObject(val: any): boolean {\n return val !== null && (typeof val === 'function' || typeof val === 'object');\n}\n\nexport function isPresent(value: any): boolean {\n return !isAbsent(value);\n}\n\n// returns Null | Undefined | Boolean | Number | BigInt | String | Symbol | Function | Class | class object\n// the returned type should always have a name property\n// kind(new Set()).name -> 'Set'\n// kind(new Set()).name -> 'Set'\nexport function kind(value: any) {\n if (value === null) {\n return Null;\n }\n switch (typeof value) {\n case 'undefined':\n return Undefined;\n case 'boolean':\n return Boolean;\n case 'number':\n return Number;\n case 'bigint':\n return BigInt;\n case 'string':\n return String;\n case 'symbol':\n return Symbol;\n case 'function': // matches class constructors (class objects) and functions\n if (isClass(value)) {\n return Class;\n } else {\n return value.constructor;\n }\n break;\n case 'object': // matches instances of classes (e.g. arrays, ) and objects\n return value.constructor;\n break;\n }\n}\n\nexport function klass(objOrClass: any) {\n if (isClass(objOrClass)) {\n // Use the updated isClass\n return Function; // The 'class' of a class is Function, as per tests\n }\n // It's an instance or a non-class function/object\n const proto = Object.getPrototypeOf(objOrClass);\n if (proto === null || proto === undefined) {\n return undefined; // Or handle as appropriate if tests cover this\n }\n return proto.constructor;\n}\n\nexport function superclass(objOrClass: any) {\n if (objOrClass === Object) {\n return null; // Object has no superclass, as per tests\n }\n\n if (isClass(objOrClass)) {\n // Use the updated isClass\n const proto = Object.getPrototypeOf(objOrClass);\n // For built-ins like String, or base user classes like 'class A {}',\n // their prototype is Function.prototype. Their superclass is Object.\n if (proto === Function.prototype) {\n return Object;\n }\n // For derived classes like 'class C extends B {}', proto is B.\n return proto;\n } else {\n // It's an instance\n const instanceProto = Object.getPrototypeOf(objOrClass);\n if (instanceProto === null || instanceProto === undefined) {\n return undefined;\n }\n const superProto = Object.getPrototypeOf(instanceProto);\n if (superProto === null || superProto === undefined) {\n // This instance's class directly inherits from Object (or has no explicit superclass)\n // or it's an object created with Object.create(null)\n return superProto === null ? null : undefined; // if superProto is null, its constructor is undefined. if it's Object.prototype, constructor is Object\n }\n // If superProto is Object.prototype, then superProto.constructor is Object.\n // If instanceProto is, e.g. an Array instance, instanceProto is Array.prototype.\n // superProto is Object.prototype. superProto.constructor is Object.\n return superProto.constructor;\n }\n}\n\n// export const T = buildPipeThroughFunction();\n// Object.assign(T, {\n// kind,\n// });\n\nclass Value<T> {\n public isWrappedValue = true;\n constructor(public value: T) {}\n\n // isA(predicateType: any): boolean {\n // return isA(predicateType)(this.value);\n // }\n\n // isAbsent(value: any) {\n // return isAbsent(value);\n // }\n\n // isClass(value: unknown) {\n // isClass(value);\n // }\n\n // isPresent(value: any) {\n // return isPresent(value);\n // }\n\n // isError(value: unknown): value is Error {\n // return isError(value);\n // }\n\n // inspect() {\n // return inspect(this.value);\n // }\n\n // kind() {\n // return kind(this.value);\n // }\n\n // klass() {\n // return klass(this.value);\n // }\n\n // superclass() {\n // return superclass(this.value);\n // }\n}\n\n// export const V = function <T>(value: T): Value<T> {\n// return new Value(value);\n// };\n\n// Object.assign(V, {\n// isA,\n// isAbsent,\n// isClass,\n// isPresent,\n// inspect,\n// kind,\n// klass,\n// superclass,\n// });\n\ninterface FunctionWithRegistrationMethods {\n (wrappedValue: any): any; // Original signature of func\n registerUncurriedFns: (fns: FunctionBag) => void;\n registerCurriedFns: (fns: FunctionBag) => void;\n registerStatic: (fns: FunctionBag) => void;\n}\n\nexport interface ValueWrapperProxy extends FunctionWithRegistrationMethods {\n <T>(wrappedValue: T): any; // Represents the function signature of V itself\n registerUncurriedFns: (fns: FunctionBag) => void;\n registerCurriedFns: (fns: FunctionBag) => void;\n registerStatic: (fns: FunctionBag) => void;\n // Add other static methods if V is supposed to have them directly, e.g., isA, inspect, etc.\n // For now, focusing on the registration methods as per the errors.\n // Static methods registered via V.registerStatic\n isA: (predicateType: any) => (value: any) => boolean;\n isAbsent: (value: any) => boolean;\n isClass: (fn: any) => boolean;\n isDefined: (value: any) => boolean;\n isObject: (val: any) => boolean;\n isPresent: (value: any) => boolean;\n inspect: (valueToInspect: any) => string;\n kind: (value: any) => any; // Adjust 'any' to the actual return type of kind if more specific\n klass: (objOrClass: any) => any; // Adjust 'any' if more specific\n superclass: (objOrClass: any) => any; // Adjust 'any' if more specific\n}\n\nexport function buildValueWrapperProxy(): ValueWrapperProxy {\n const methods = new MethodBag();\n function func(wrappedValue: any): any {\n // wrappedValue is the value passed to the object wrapper function. e.g. A([1,2,3]) the wrappedValue is [1,2,3] and A is the wrapper function called func in this context\n if (!isObject(wrappedValue)) {\n wrappedValue = new Value(wrappedValue);\n }\n return new Proxy(wrappedValue, {\n get(target, property, receiver) {\n // function objects, like O, don't have any properties, so the only properties present will be the function objects we assign to the 'O' function object\n const fnArityPair = methods.lookup(property.toString());\n if (fnArityPair === undefined) {\n if (target.isWrappedValue) {\n return Reflect.get(target.value, property, receiver); // target === Value(wrappedValue)\n } else {\n return Reflect.get(target, property, receiver); // target === wrappedValue\n }\n }\n const [fn, arity] = fnArityPair;\n return function (...args: any) {\n if (arity === 1) {\n // then we are going to treat fn as a function expecting the obj to be supplied as an argument\n if (target.isWrappedValue) {\n // console.log(`111. ${fn}.call(${inspect(receiver)}, ${inspect(target.value)})`);\n\n // target === Value(wrappedValue)\n return fn.call(receiver, target.value);\n } else {\n // console.log(`222. ${fn}.call(${inspect(receiver)}, ${inspect(target)})`);\n return fn.call(receiver, target);\n }\n } else {\n // otherwise, we are going to treat fn as a function expecting the args to be supplied as the argument, which will return a second function that expects the obj to be supplied as its argument\n if (target.isWrappedValue) {\n // console.log(`333. ${fn}.apply(${inspect(receiver)}, ${inspect(args)})(${inspect(target.value)})`);\n return fn.apply(receiver, args)(target.value);\n } else {\n // console.log(`444. ${fn}.apply(${inspect(receiver)}, ${inspect(args)})(${inspect(target)})`);\n return fn.apply(receiver, args)(target);\n }\n }\n };\n },\n });\n }\n Object.assign(func, {\n registerUncurriedFns(fnBag: FunctionBag) {\n return methods.registerUncurriedFns(fnBag);\n },\n registerCurriedFns(fnBag: FunctionBag) {\n return methods.registerCurriedFns(fnBag);\n },\n registerStatic(fnBag: FunctionBag) {\n return methods.registerStatic(fnBag);\n },\n });\n const funcWithMethods = func as FunctionWithRegistrationMethods;\n return new Proxy(funcWithMethods, {\n get(target: any, property: string | symbol, receiver: any) {\n const fn = methods.lookupStatic(property.toString());\n if (fn === undefined) {\n // If the property is not a registered static method,\n // delegate to the target (funcWithMethods), which has registerUncurriedFns etc.\n return Reflect.get(target, property, receiver);\n }\n return fn;\n },\n }) as ValueWrapperProxy;\n}\n\nexport const V = buildValueWrapperProxy() as ValueWrapperProxy;\nV.registerUncurriedFns({\n isAbsent,\n isClass,\n isDefined,\n isObject,\n isPresent,\n inspect,\n kind,\n klass,\n superclass,\n});\nV.registerCurriedFns({ isA });\nV.registerStatic({\n isA,\n isAbsent,\n isClass,\n isDefined,\n isObject,\n isPresent,\n inspect,\n kind,\n klass,\n superclass,\n});\n","import { Protocol } from './protocol';\n\nexport class Compactable<S> extends Protocol {\n constructor(public self: S) {\n super();\n }\n\n compact(omit?: any[]): any {\n throw new Error('not implemented');\n }\n}\n\nexport function compact(omit?: any[]) {\n return function <V>(compactableVal: V | V[]): V | V[] | undefined {\n return Compactable.for<Compactable<V | V[]>>(compactableVal).compact(omit);\n };\n}\n","import { identity } from './function';\nimport { End } from './type';\n\nexport class Enumerator<T> implements IterableIterator<T> {\n static for<U>(iterator: Iterator<U>): Enumerator<U> {\n return new Enumerator(iterator);\n }\n\n constructor(private iterator: Iterator<T>) {}\n\n all(predFn: (v: T) => boolean): boolean {\n for (const elem of this) {\n if (!predFn(elem)) {\n return false;\n }\n }\n return true;\n }\n\n any(predFn: (v: T) => boolean): boolean {\n for (const elem of this) {\n if (predFn(elem)) {\n return true;\n }\n }\n return false;\n }\n\n each(visitorFn: (v: T) => any) {\n for (const e of this) {\n visitorFn(e);\n }\n }\n\n first<U>(predFn: (v: T) => any = identity, defaultIfAbsesnt: U | undefined = undefined): T | U | undefined {\n for (const e of this) {\n if (predFn(e)) return e;\n }\n return defaultIfAbsesnt;\n }\n\n map<U>(mapFn: (v: T) => U): Enumerator<U> {\n function* gen(iterator: Enumerator<T>) {\n for (const e of iterator) {\n yield mapFn(e);\n }\n }\n return Enumerator.for(gen(this));\n }\n\n // per https://typescript.tv/hands-on/all-you-need-to-know-about-iterators-and-generators/#the-iterator-protocol\n // implement the IterableIterator interface by implementing [Symbol.iterator]() and next()\n [Symbol.iterator](): IterableIterator<T> {\n return this;\n }\n // per https://typescript.tv/hands-on/all-you-need-to-know-about-iterators-and-generators/#the-iterator-protocol\n // implement the IterableIterator interface by implementing [Symbol.iterator]() and next()\n next(): IteratorResult<T> {\n const val = this.produce();\n if (val instanceof End) {\n return { done: true, value: End.instance };\n }\n return { done: false, value: val };\n }\n\n // this produces either the next value in the Enumerator, or it returns End\n produce(): T | End {\n const val: IteratorResult<T> = this.iterator.next();\n if (val.done) {\n return End.instance;\n }\n return val.value;\n }\n\n select(predFn: (v: T) => boolean): Enumerator<T> {\n function* gen(iterator: Enumerator<T>) {\n for (const e of iterator) {\n if (predFn(e)) yield e;\n }\n }\n return Enumerator.for(gen(this));\n }\n\n toArray(): T[] {\n return Array.from(this);\n }\n\n toMap<K, V>(kvMapFn: (v: T) => [K, V]): Map<K, V> {\n return new Map(this.map(kvMapFn));\n }\n\n toSet(): Set<T> {\n return new Set(this);\n }\n}\n","import { Protocol } from './protocol';\nimport type { AnyConstructor } from './protocol';\nimport { Enumerator } from './enumerator';\n\nexport type ImplementsEnumerable = {};\n\nexport class Enumerable<S, T> extends Protocol {\n static each = each;\n\n constructor(public self: S) {\n super();\n }\n\n each(visitorFn: (v: T) => any) {\n return this.toEnumerator().each(visitorFn);\n }\n\n *emit(): Generator<T> {\n throw new Error('emit not implemented');\n }\n\n toArray(): T[] {\n return this.toEnumerator().toArray();\n }\n\n toEnumerator(): Enumerator<T> {\n return Enumerator.for(this.emit());\n }\n\n toSet(): Set<T> {\n return this.toEnumerator().toSet();\n }\n}\n\nexport function each<T>(visitorFn: (v: T) => any) {\n return function (enumerableVal: Iterable<T>, implClass?: AnyConstructor) {\n return Enumerable.for(enumerableVal, implClass).each(visitorFn);\n };\n}\n","import { Protocol, type AnyConstructor } from './protocol';\n\n/**\n * The interpretation of the generic type parameters is:\n * S is the self type. For example: T[]\n *\n * T is the element type that is being iterated over from the self type, S.\n * For example, when S is T[], then the element type is likely going to be T.\n *\n * U is the type that we are transforming T into.\n * For example, when S is T[], then the element type is likely going to be T,\n * and the mapping function from T -> U means that the transformation type is U.\n */\nexport class Mappable<S, T, U> extends Protocol {\n constructor(public self: S) {\n super();\n }\n\n map(mapFn: (v: T) => U): any {\n throw new Error('not implemented');\n }\n}\n\nexport function map<T, U>(mapFn: (v: T) => U) {\n return function (mappableVal: any, explicitImplClass?: new (self: any) => Mappable<any, T, U>) {\n return Mappable.for(mappableVal, explicitImplClass).map(mapFn);\n };\n}\n\nexport class AsyncMappable<S, T, U> extends Protocol {\n constructor(public self: S) {\n super();\n }\n\n async map(mapFn: (v: T) => Promise<U>): Promise<any> {\n throw new Error('not implemented');\n }\n}\n\nexport function asyncMap<T, U>(mapFn: (v: T) => Promise<U>) {\n return async function (mappableVal: any, explicitImplClass?: new (self: any) => AsyncMappable<any, T, U>) {\n return await AsyncMappable.for(mappableVal, explicitImplClass).map(mapFn);\n };\n}\n","import { Protocol, type AnyConstructor } from './protocol';\n\nexport class Selectable<S, T> extends Protocol {\n constructor(public self: S) {\n super();\n }\n\n select(predFn: (e: T) => boolean): any {\n throw new Error('not implemented');\n }\n}\n\nexport function select<T>(predFn: (e: T) => boolean) {\n return function <S>(selectableVal: S, implClass?: AnyConstructor) {\n return Selectable.for(selectableVal, implClass).select(predFn);\n };\n}\n","import { toSet } from './array';\nimport { Compactable } from './compactable';\nimport { Enumerable } from './enumerable';\nimport { Mappable, AsyncMappable } from './mappable';\nimport { Selectable } from './selectable';\n\nclass CompactableArray<T> extends Compactable<T[]> {\n compact(omit?: any[]) {\n omit ||= [null, undefined];\n\n const omitSet = toSet(omit);\n const newArr: any[] = [];\n for (const val of this.self) {\n if (!omitSet.has(val)) {\n newArr.push(val);\n }\n }\n return newArr;\n }\n}\nawait Compactable.register(Array, CompactableArray, true);\n\nclass MappableArray<T, U> extends Mappable<T[], T, U> {\n map(mapFn: (v: T) => U): any {\n return this.self.map(mapFn);\n }\n}\nawait Mappable.register(Array, MappableArray, true);\n\nexport class AsyncMappableArray<T, U> extends AsyncMappable<T[], T, U> {\n async map(mapFn: (v: T) => Promise<U>) {\n const arr: U[] = [];\n for await (const v of this.self) {\n const mappedValue = await mapFn(v);\n arr.push(mappedValue);\n }\n return arr;\n }\n}\nawait AsyncMappable.register(Array, AsyncMappableArray, true);\n\nclass EnumerableArray<T> extends Enumerable<T[], T> {\n *emit() {\n for (const e of this.self) yield e;\n }\n}\nawait Enumerable.register(Array, EnumerableArray, true);\n\nclass SelectableArray<T> extends Selectable<T[], T> {\n select(predFn: (v: T) => boolean): T[] {\n return this.self.filter(predFn);\n }\n}\nawait Selectable.register(Array, SelectableArray, true);\n","import { buildWrapperProxy } from './function';\n\nexport function each<K, V>(eachFn: (pair: [K, V]) => void) {\n return function (map: Map<K, V>): void {\n map.forEach((value, key) => {\n eachFn([key, value]);\n });\n };\n}\n\nexport function isEmpty<K, V>(map: Map<K, V>): boolean {\n return map.size === 0;\n}\n\n/**\n * @returns An array of the map's keys.\n *\n * ```ts\n * keys(\n * new Map([\n * [\"foo\", [1, 2, 3]],\n * [\"bar\", [4, 6, 7]],\n * ])\n * )\n * // [ 'foo', 'bar' ]\n * ```\n */\nexport function keys<K, V>(map: Map<K, V>): K[] {\n return Array.from(map.keys());\n}\n\nexport function map<K, V, T>(mapFn: (pair: [K, V]) => [K, T]) {\n return function (map: Map<K, V>): Map<K, T> {\n const m = new Map<K, T>();\n map.forEach((value, key) => {\n const [newKey, newValue] = mapFn([key, value]);\n m.set(newKey, newValue);\n });\n return m;\n };\n}\n\nexport function select<K, V>(predFn: (pair: [K, V]) => boolean) {\n return function (map: Map<K, V>): Map<K, V> {\n const newMap = new Map<K, V>();\n map.forEach((value, key) => {\n if (predFn([key, value])) {\n newMap.set(key, value);\n }\n });\n return newMap;\n };\n}\n\nexport function toObject<K, V>(map: Map<K, V>): object {\n return Object.fromEntries(map.entries());\n}\n\nexport function values<K, V>(map: Map<K, V>): V[] {\n return Array.from(map.values());\n}\n\n// export const M = buildPipeThroughFunction();\n\n// Object.assign(M, {\n// each,\n// isEmpty,\n// keys,\n// map,\n// select,\n// toObject,\n// values,\n// });\n\nexport const M = buildWrapperProxy();\nM.registerUncurriedFns({ isEmpty, keys, toObject, values });\nM.registerCurriedFns({ each, map, select });\nM.registerStatic({\n each,\n isEmpty,\n keys,\n map,\n select,\n toObject,\n values,\n});\n\nimport './all-protocols';\n","import { Enumerable } from './enumerable';\nimport { M } from './map';\nimport { Mappable, AsyncMappable } from './mappable';\nimport { Selectable } from './selectable';\n\nexport class MapToMap<K, V, T, U> extends Mappable<Map<K, V>, [K, V], [T, U]> {\n map(mapFn: (pair: [K, V]) => [T, U]) {\n const m = new Map<T, U>();\n this.self.forEach((value, key) => {\n const [newKey, newValue] = mapFn([key, value]);\n m.set(newKey, newValue);\n });\n return m;\n }\n}\n\nexport class MapToArray<K, V, T> extends Mappable<Map<K, V>, [K, V], T> {\n map(mapFn: (pair: [K, V]) => T) {\n const arr: T[] = [];\n this.self.forEach((value, key) => {\n const mappedValue = mapFn([key, value]);\n arr.push(mappedValue);\n });\n return arr;\n }\n}\n\nawait Mappable.register(Map, MapToMap, true);\nawait Mappable.register(Map, MapToArray);\n\nexport class AsyncMapToMap<K, V, T, U> extends AsyncMappable<Map<K, V>, [K, V], [T, U]> {\n async map(mapFn: (pair: [K, V]) => Promise<[T, U]>) {\n const m = new Map<T, U>();\n for await (const [key, value] of this.self) {\n const [newKey, newValue] = await mapFn([key, value]);\n m.set(newKey, newValue);\n }\n return m;\n }\n}\n\nexport class AsyncMapToArray<K, V, T> extends AsyncMappable<Map<K, V>, [K, V], T> {\n async map(mapFn: (pair: [K, V]) => Promise<T>) {\n const arr: T[] = [];\n for await (const [key, value] of this.self) {\n const mappedValue = await mapFn([key, value]);\n arr.push(mappedValue);\n }\n return arr;\n }\n}\n\nawait AsyncMappable.register(Map, AsyncMapToMap, true);\nawait AsyncMappable.register(Map, AsyncMapToArray);\n\nexport class EnumerablePair<K, V> extends Enumerable<Map<K, V>, [K, V]> {\n *emit(): Generator<[K, V]> {\n for (const [k, v] of this.self.entries()) {\n yield [k, v];\n }\n }\n}\n\nexport class EnumerableKey<K, V> extends Enumerable<Map<K, V>, K> {\n *emit() {\n for (const k of this.self.keys()) {\n yield k;\n }\n }\n}\n\nexport class EnumerableValue<K, V> extends Enumerable<Map<K, V>, V> {\n *emit() {\n for (const v of this.self.values()) {\n yield v;\n }\n }\n}\n\nawait Enumerable.register(Map, EnumerablePair, true);\nawait Enumerable.register(Map, EnumerableKey);\nawait Enumerable.register(Map, EnumerableValue);\n\nexport class SelectableMap<K, V> extends Selectable<Map<K, V>, [K, V]> {\n select(predFn: (v: [K, V]) => boolean): Map<K, V> {\n return M(this.self).select(predFn);\n }\n}\nawait Selectable.register(Map, SelectableMap, true);\n","import { buildWrapperProxy, type FunctionBag, type BaseWrapperProxy } from './function';\n\n// Interface for the wrapped object O(obj)\nexport interface WrappedObject<V> {\n each: (eachFn: (pair: [string, V]) => void) => void;\n keys: () => string[];\n map: <T>(mapFn: (pair: [string, V]) => [string, T]) => { [s: string]: T };\n pick: (keysToPick: Set<string>) => { [s: string]: V };\n select: (predFn: (pair: [string, V]) => boolean) => { [s: string]: V };\n toMap: () => Map<string, V>;\n values: () => V[];\n}\n\n// Interface for the O proxy object\nexport interface ObjectWrapperProxy extends BaseWrapperProxy {\n <V>(wrappedValue: { [s: string]: V }): WrappedObject<V>;\n\n // Static methods on O - these match the exported function signatures\n each: <V>(eachFn: (pair: [string, V]) => void) => (object: { [s: string]: V }) => void;\n keys: <V>(object: { [s: string]: V }) => string[];\n map: <V, T>(mapFn: (pair: [string, V]) => [string, T]) => (object: { [s: string]: V }) => { [s: string]: T };\n pick: (keys: Set<string>) => <V>(object: { [s: string]: V }) => { [s: string]: V };\n select: <V>(predFn: (pair: [string, V]) => boolean) => (object: { [s: string]: V }) => { [s: string]: V };\n toMap: <V>(object: { [s: string]: V }) => Map<string, V>;\n values: <V>(object: { [s: string]: V }) => V[];\n\n // Note: registerUncurriedFns, registerCurriedFns, registerStatic are inherited from BaseWrapperProxy\n}\n\nexport function each<V>(eachFn: (pair: [string, V]) => void) {\n return function (object: { [s: string]: V }): void {\n Object.entries<V>(object).forEach((kvPair) => {\n eachFn(kvPair);\n });\n };\n}\n\nexport function keys<V>(object: { [s: string]: V }): string[] {\n return Object.keys(object);\n}\n\nexport function map<V, T>(mapFn: (pair: [string, V]) => [string, T]) {\n return function (object: { [s: string]: V }): { [s: string]: T } {\n const obj: { [s: string]: T } = {};\n Object.entries<V>(object).forEach((kvPair) => {\n const [newKey, newValue] = mapFn(kvPair);\n obj[newKey] = newValue;\n });\n return obj;\n };\n}\n\nexport function pick(keysToPick: Set<string>) {\n // Renamed 'keys' to 'keysToPick' for clarity with WrappedObject.pick\n return select<any>(([key, _]) => keysToPick.has(key)); // Use 'any' as placeholder, select's V will be the actual type\n}\n\nexport function select<V>(predFn: (pair: [string, V]) => boolean) {\n return function (object: { [s: string]: V }): { [s: string]: V } {\n const obj: { [s: string]: V } = {};\n Object.entries<V>(object).forEach((kvPair) => {\n if (predFn(kvPair)) {\n const [k, v] = kvPair;\n obj[k] = v;\n }\n });\n return obj;\n };\n}\n\nexport function toMap<V>(object: { [s: string]: V }): Map<string, V> {\n return new Map(Object.entries<V>(object));\n}\n\nexport function values<V>(object: { [s: string]: V }): V[] {\n return Object.values<V>(object);\n}\n\n// const _O = buildPipeThroughFunction();\n\n// Object.assign(_O, {\n// each, // (eachFn)(obj) => ...\n// keys, // (obj) => ...\n// map,\n// pick,\n// select,\n// toMap,\n// values,\n// });\n\n// export const O = _O;\n\nexport const O = buildWrapperProxy() as ObjectWrapperProxy;\nO.registerUncurriedFns({ keys, toMap, values });\nO.registerCurriedFns({ each, map, pick, select });\nO.registerStatic({\n each, // (eachFn)(obj) => ...\n keys, // (obj) => ...\n map,\n pick,\n select,\n toMap,\n values,\n});\n\nimport './all-protocols';\n","import { O } from './object';\nimport { Selectable } from './selectable';\n\nclass SelectableObject<V> extends Selectable<object, [string, V]> {\n select(predFn: (v: [string, V]) => boolean): object {\n return O(this.self).select(predFn);\n }\n}\nawait Selectable.register(Object, SelectableObject, true);\n","import { copyFile, cp, readFile } from 'node:fs/promises';\nimport { existsSync, readFileSync, lstatSync } from 'node:fs';\nimport { win32, posix } from 'node:path';\nimport type { ParsedPath } from 'node:path';\nimport { homedir } from 'node:os';\nimport { glob, globSync, globStream, globStreamSync, Glob } from 'glob';\nimport { isWindows } from './platform';\nimport { A } from './array';\nimport { Str } from './string';\nimport { Range } from './range';\nimport { Equal } from './equal';\n\nexport class Path {\n static new(path: Path | string, isWindowsPath: boolean = isWindows()): Path {\n if (path instanceof Path) {\n return path;\n }\n return new Path(path, isWindowsPath);\n }\n\n static cwd(): Path {\n return Path.new(process.cwd());\n }\n\n static homeDir(): Path {\n return Path.new(homedir());\n }\n\n static sep(isWindowsPath: boolean = isWindows()) {\n if (isWindowsPath) {\n return win32.sep;\n } else {\n return posix.sep;\n }\n }\n\n constructor(\n public path: string,\n public isWindowsPath: boolean = isWindows(),\n ) {}\n\n absolute(): Path {\n return this.resolve();\n }\n\n ancestors(): Path[] {\n if (this.isRoot()) {\n return [];\n }\n\n const ancestors: Path[] = [];\n let current: Path = this.directory();\n\n while (true) {\n ancestors.push(current);\n\n if (current.isRoot()) {\n break;\n }\n\n current = current.parent();\n }\n return ancestors;\n }\n\n basename(suffix?: string): Path {\n if (this.isWindowsPath) {\n return this.build(win32.basename(this.path, suffix));\n } else {\n return this.build(posix.basename(this.path, suffix));\n }\n }\n\n build(path: string): Path {\n return new Path(path, this.isWindowsPath);\n }\n\n // returns the path to the destination on success; null otherwise\n async copy(destPath: Path | string, mode?: number): Promise<Path | null> {\n destPath = Path.new(destPath).normalize();\n try {\n if (this.isDirectory()) {\n await cp(this.toString(), destPath.toString(), { mode, recursive: true });\n } else {\n await copyFile(this.toString(), destPath.toString(), mode);\n }\n return destPath;\n } catch (e) {\n return null;\n }\n }\n\n dirContains(filename: string): boolean {\n return this.isDirectory() && this.glob(filename).length > 0;\n }\n\n directory(): Path {\n return this.absolute().dirname();\n }\n\n // given a path like \"bar/bas\", this method converts the path to an absolute path (e.g. \"/foo/bar/bas\"),\n // and then returns the directory tree as an array of the form [\"foo\", \"bar\", \"bas\"]\n directorySegments(): string[] {\n return this.absolute().dirname().split();\n }\n\n dirname(): Path {\n if (this.isWindowsPath) {\n return this.build(win32.dirname(this.path));\n } else {\n return this.build(posix.dirname(this.path));\n }\n }\n\n equals(other: any): boolean {\n if (!(other instanceof Path)) {\n return false;\n }\n return this.path === other.path && this.isWindowsPath === other.isWindowsPath;\n }\n\n exists(): boolean {\n return existsSync(this.path);\n }\n\n ext(): string {\n return this.parse().ext;\n }\n\n glob(pattern: string) {\n const cwd = this.absolute().toString();\n return globSync(pattern, { cwd }).map((path) => this.build(path));\n }\n\n isAbsolute(): boolean {\n if (this.isWindowsPath) {\n return win32.isAbsolute(this.path);\n } else {\n return posix.isAbsolute(this.path);\n }\n }\n\n isDirectory(): boolean {\n return this.exists() && lstatSync(this.path).isDirectory();\n }\n\n isFile(): boolean {\n return this.exists() && lstatSync(this.path).isFile();\n }\n\n isPosix(): boolean {\n return !this.isWindowsPath;\n }\n\n isRoot(): boolean {\n return this.parse().root === this.normalize().toString();\n }\n\n isWindows(): boolean {\n return this.isWindowsPath;\n }\n\n join(...paths: string[]): Path {\n if (this.isWindowsPath) {\n return this.build(win32.join(this.path, ...paths));\n } else {\n return this.build(posix.join(this.path, ...paths));\n }\n }\n\n normalize(): Path {\n if (this.isWindowsPath) {\n return this.build(win32.normalize(this.path));\n } else {\n return this.build(posix.normalize(this.path));\n }\n }\n\n parent(count: number = 1) {\n let path = this.absolute();\n Range.new(1, count).each((i) => {\n path = path.resolve('..');\n });\n return path;\n }\n\n // returns an object of the form: { root, dir, base, ext, name }\n //\n // Posix:\n // >>> path.parse('/home/user/dir/file.txt')\n // { root: '/',\n // dir: '/home/user/dir',\n // base: 'file.txt',\n // ext: '.txt',\n // name: 'file' }\n // ┌─────────────────────┬────────────┐\n // │ dir │ base │\n // ├──────┬ ├──────┬─────┤\n // │ root │ │ name │ ext │\n // \" / home/user/dir / file .txt \"\n // └──────┴──────────────┴──────┴─────┘\n // (All spaces in the \"\" line should be ignored. They are purely for formatting.)\n //\n // Windows:\n // >>> path.parse('C:\\\\path\\\\dir\\\\file.txt');\n // { root: 'C:\\\\',\n // dir: 'C:\\\\path\\\\dir',\n // base: 'file.txt',\n // ext: '.txt',\n // name: 'file' }\n // ┌─────────────────────┬────────────┐\n // │ dir │ base │\n // ├──────┬ ├──────┬─────┤\n // │ root │ │ name │ ext │\n // \" C:\\ path\\dir \\ file .txt \"\n // └──────┴──────────────┴──────┴─────┘\n // (All spaces in the \"\" line should be ignored. They are purely for formatting.)\n parse(): ParsedPath {\n if (this.isWindowsPath) {\n return win32.parse(this.path);\n } else {\n return posix.parse(this.path);\n }\n }\n\n pop(count: number = 1): Path {\n return this.parent(count);\n }\n\n relative(to: string): Path {\n if (this.isWindowsPath) {\n return this.build(win32.relative(this.path, to));\n } else {\n return this.build(posix.relative(this.path, to));\n }\n }\n\n resolve(...paths: string[]): Path {\n if (this.isWindowsPath) {\n return this.build(win32.resolve(this.path, ...paths));\n } else {\n return this.build(posix.resolve(this.path, ...paths));\n }\n }\n\n root(): Path {\n const { root } = this.parse();\n return this.build(root);\n }\n\n selfAndAncestors(): Path[] {\n const ancestors: Path[] = [];\n let current: Path = this.absolute();\n\n while (true) {\n ancestors.push(current);\n\n if (current.isRoot()) {\n break;\n }\n\n current = current.parent();\n }\n return ancestors;\n }\n\n // returns the parts of the path, excluding the root if applicable\n // /home/user/dir/file.txt -> [\"home\", \"user\", \"dir\", \"file.txt\"]\n // C:\\home\\user\\dir\\file.txt -> [\"home\", \"user\", \"dir\", \"file.txt\"]\n // user/dir/file.txt -> [\"user\", \"dir\", \"file.txt\"]\n // user\\dir\\file.txt -> [\"user\", \"dir\", \"file.txt\"]\n split(): string[] {\n const normalized = this.normalize();\n if (normalized.isAbsolute()) {\n const { root } = normalized.parse();\n const relPath = Str(normalized.toString()).trimPrefix(root);\n return relPath.split(Path.sep(this.isWindowsPath));\n } else {\n return normalized.toString().split(Path.sep(this.isWindowsPath));\n }\n }\n\n toString(): string {\n return this.path;\n }\n}\n\nclass PathEqualImpl extends Equal<Path> {\n equal(val: Path): boolean {\n return this.self.equals(val);\n }\n}\n\nawait Equal.register(Path, PathEqualImpl, true);\n","import { platform as nodePlatform } from 'node:process';\n\nexport function isPosix(): boolean {\n const posixPlatforms: NodeJS.Platform[] = ['darwin', 'freebsd', 'linux', 'netbsd', 'openbsd', 'sunos'];\n return posixPlatforms.includes(platform());\n}\n\nexport function isWindows(): boolean {\n return platform() == 'win32';\n}\n\nexport function platform(): NodeJS.Platform {\n return nodePlatform;\n}\n","import { V } from './type';\n\n// Define an interface for the Str object/function\ninterface StringWrapper {\n (str: string): StringProxy; // Callable signature\n isEmpty: typeof isEmpty;\n isNumeric: typeof isNumeric;\n matches: typeof matches;\n}\n\nexport function isEmpty(str: string): boolean {\n return str.length == 0;\n}\n\nexport function isNumeric(str: string): boolean {\n if (typeof str !== 'string') return false;\n const trimmedStr = str.trim();\n if (trimmedStr === '') return false; // Empty or whitespace-only string is not numeric\n const num = Number(trimmedStr);\n // Check if it's a number, finite, and if the string version of the number matches the trimmed original string\n return !isNaN(num) && isFinite(num) && String(num) === trimmedStr;\n}\n\n/**\n * @param regexp must be a global regexp, e.g. /foo/g, and not just /foo/\n * @returns array of matches, or null if no matches present\n * Example:\n * const regexp = /t(e)(st(\\d?))/g;\n * const str = 'test1test2';\n *\n * const array = matches(regexp)(str)\n *\n * > matches(regexp)(str)\n * [\n * [\n * 'test1',\n * 'e',\n * 'st1',\n * '1',\n * index: 0,\n * input: 'test1test2',\n * groups: undefined\n * ],\n * [\n * 'test2',\n * 'e',\n * 'st2',\n * '2',\n * index: 5,\n * input: 'test1test2',\n * groups: undefined\n * ]\n * ]\n *\n * > matches(/foo/g)(\"blah\")\n * null\n */\nexport function matches(regexp: RegExp) {\n const globalRegex = regexp.global ? regexp : new RegExp(regexp.source, regexp.flags + 'g');\n return function (str: string) {\n const matches = [...str.matchAll(globalRegex)];\n if (matches.length == 0) return null;\n return matches;\n };\n}\n\nexport class StringProxy {\n // Add common string properties/methods for TypeScript\n public get length(): number {\n return this.str.length;\n }\n\n public toUpperCase(): string {\n return this.str.toUpperCase();\n }\n\n constructor(public str: string) {}\n\n isEmpty() {\n return isEmpty(this.str);\n }\n\n isNumeric() {\n return isNumeric(this.str);\n }\n\n matches(regexp: RegExp) {\n return matches(regexp)(this.str);\n }\n\n trimPrefix(prefix: string): string {\n if (this.str.startsWith(prefix)) {\n return this.str.slice(prefix.length);\n }\n return this.str;\n }\n\n trimSuffix(suffix: string): string {\n if (this.str.endsWith(suffix)) {\n return this.str.slice(0, this.str.length - suffix.length);\n }\n return this.str;\n }\n}\n\n// Cast Str to the StringWrapper interface\nexport const Str = function (str: string): StringProxy {\n const handler = {\n get(target: StringProxy, property: string | symbol, receiver: any) {\n // target is instance of StringProxy\n // Check if property exists on StringProxy instance itself (e.g. isEmpty, isNumeric)\n // or on its prototype chain.\n const propOnTarget = Reflect.get(target, property, receiver);\n\n if (V.isPresent(propOnTarget)) {\n // V.isPresent checks for null or undefined\n // If propOnTarget is a function (method of StringProxy), it's already correctly bound or doesn't need special binding.\n return propOnTarget;\n }\n\n // Property not found on StringProxy instance. Try the underlying string.\n const underlyingString = target.str;\n // Access the property directly from the string primitive.\n // Using `as any` to allow indexing with symbol, though typical string properties are strings.\n const valueFromPrimitive = (underlyingString as any)[property];\n\n if (typeof valueFromPrimitive === 'function') {\n // If it's a method from the string (e.g., toUpperCase, charAt), bind it to the underlying string.\n return valueFromPrimitive.bind(underlyingString);\n }\n\n // For non-function properties (e.g., 'length'), or if the property doesn't exist on a string (valueFromPrimitive will be undefined).\n return valueFromPrimitive;\n },\n };\n\n return new Proxy(new StringProxy(str), handler);\n} as StringWrapper;\n\nObject.assign(Str, {\n isEmpty,\n isNumeric,\n matches,\n});\n","import { Enumerable } from './enumerable';\n\nexport class Range {\n static new(start: number, end: number, inclusive: boolean = true): Range {\n return new Range(start, end, inclusive);\n }\n\n constructor(\n public start: number,\n public end: number,\n public inclusive: boolean = true,\n ) {}\n\n each(visitorFn: (num: number) => any) {\n const exclusiveEnd = this.inclusive ? this.end + 1 : this.end;\n for (let i = this.start; i < exclusiveEnd; i++) {\n visitorFn(i);\n }\n }\n\n equals(other: any): boolean {\n if (!(other instanceof Range)) {\n return false;\n }\n return this.start === other.start && this.end === other.end && this.inclusive === other.inclusive;\n }\n\n map<T>(mapFn: (num: number) => T): T[] {\n const arr: T[] = [];\n this.each((num) => {\n arr.push(mapFn(num));\n });\n return arr;\n }\n\n toArray(): number[] {\n return Enumerable.for<Enumerable<Range, number>>(this).toArray();\n }\n}\n","import { Protocol } from './protocol';\n\nexport class Equal<S> extends Protocol {\n constructor(public self: S) {\n super();\n }\n\n equal(val: S): boolean {\n throw new Error('equal not implemented');\n }\n\n notEqual(val: S): boolean {\n return !this.equal(val);\n }\n\n eq(val: S): boolean {\n return this.equal(val);\n }\n\n neq(val: S): boolean {\n return this.notEqual(val);\n }\n}\n\nexport function equal<T>(self: T, other: T, implClass?: new (self: T) => Equal<T>) {\n return Equal.for(self, implClass).equal(other);\n}\n\nexport function notEqual<T>(self: T, other: T, implClass?: new (self: T) => Equal<T>) {\n return Equal.for(self, implClass).notEqual(other);\n}\n\nexport function eq<T>(self: T, other: T, implClass?: new (self: T) => Equal<T>) {\n return Equal.for(self, implClass).equal(other);\n}\n\nexport function neq<T>(self: T, other: T, implClass?: new (self: T) => Equal<T>) {\n return Equal.for(self, implClass).neq(other);\n}\n","import { Range } from './range';\nimport { Enumerable } from './enumerable';\nimport { Mappable, AsyncMappable } from './mappable';\nimport { Selectable } from './selectable';\nimport { Equal } from './equal';\n\nclass MappableRange<T> extends Mappable<Range, number, T> {\n map(mapFn: (v: number) => T): T[] {\n return this.self.map(mapFn);\n }\n}\nawait Mappable.register(Range, MappableRange, true);\n\n// export class AsyncMappableRange<T, U> extends AsyncMappable<T[], T, U> {\n// async map(mapFn: (v: T) => Promise<U>) {\n// const arr: U[] = [];\n// for await (const v of this.self) {\n// const mappedValue = await mapFn(v);\n// arr.push(mappedValue);\n// }\n// return arr;\n// }\n// }\n// await AsyncMappable.register(Range, AsyncMappableRange, true);\n\nclass EnumerableRange extends Enumerable<Range, number> {\n *emit() {\n const exclusiveEnd = this.self.inclusive ? this.self.end + 1 : this.self.end;\n for (let i = this.self.start; i < exclusiveEnd; i++) {\n yield i;\n }\n }\n}\nawait Enumerable.register(Range, EnumerableRange, true);\n\nclass EqualRange extends Equal<Range> {\n equal(other: Range): boolean {\n return this.self.equals(other);\n }\n}\nawait Equal.register(Range, EqualRange, true);\n\nclass SelectableRange extends Selectable<Range, number> {\n select(predFn: (v: number) => boolean): number[] {\n let arr: number[] = [];\n this.self.each((num) => {\n if (predFn(num)) {\n arr.push(num);\n }\n });\n return arr;\n }\n}\nawait Selectable.register(Range, SelectableRange, true);\n","import { Enumerable } from './enumerable';\nimport { Mappable } from './mappable';\n\nclass MappableSet<T, U> extends Mappable<Set<T>, T, U> {\n map(mapFn: (v: T) => U) {\n const s = new Set<U>();\n this.self.forEach((value) => {\n const newValue = mapFn(value);\n s.add(newValue);\n });\n return s;\n }\n}\nawait Mappable.register(Set, MappableSet, true);\n\nclass EnumerableSet<T> extends Enumerable<Set<T>, T> {\n // each(visitorFn: (v: T) => any): any {\n // return this.self.forEach((v) => visitorFn(v));\n // }\n *emit() {\n for (const e of this.self) {\n yield e;\n }\n }\n}\nawait Enumerable.register(Set, EnumerableSet, true);\n","import { buildWrapperProxy, identity, type BaseWrapperProxy } from './function';\n\nexport function compact(omit: any[] = [null, undefined]) {\n return function (arr: any[]): any[] {\n const omitSet = toSet(omit);\n const newArr: any[] = [];\n for (const val of arr) {\n if (!omitSet.has(val)) {\n newArr.push(val);\n }\n }\n return newArr;\n };\n}\n\nexport function concat<T>(tail: T[]) {\n return function (arr: T[]): T[] {\n return arr.concat(tail);\n };\n}\n\nexport function each<T>(eachFn: (value: T) => void) {\n return function (arr: Array<T>): void {\n arr.forEach((value) => {\n eachFn(value);\n });\n };\n}\n\nexport function find<T>(predicateFn: (v: T) => any) {\n return function (arr: Array<T>): T | undefined {\n for (const val of arr) {\n if (predicateFn(val)) {\n return val;\n }\n }\n return undefined;\n };\n}\n\n// returns the first n elements\nexport function first<T>(n: number) {\n return function (arr: T[]): T[] {\n return arr.slice(0, n);\n };\n}\n\nexport function head<T>(arr: T[]): T | undefined {\n return arr[0];\n}\n\nexport function isEmpty<T>(arr: Array<T>): boolean {\n return arr.length === 0;\n}\n\nexport function join(separator?: string) {\n return function <T>(arr: T[]): string {\n return arr.join(separator);\n };\n}\n\n// returns the last n elements\nexport function last<T>(n: number) {\n return function (arr: T[]): T[] {\n return arr.slice(arr.length - n, arr.length);\n };\n}\n\nexport function map<T, U>(mapFn: (value: T) => U) {\n return function (arr: Array<T>): Array<U> {\n return arr.map(mapFn);\n };\n}\n\nexport function nth(n: number) {\n return function <T>(arr: T[]): T | undefined {\n return arr[n];\n };\n}\n\nexport function partition<T>(predFn: (e: T) => boolean) {\n return function (arr: T[]): [T[], T[]] {\n const trueArr: T[] = [];\n const falseArr: T[] = [];\n for (const val of arr) {\n if (predFn(val)) {\n trueArr.push(val);\n } else {\n falseArr.push(val);\n }\n }\n return [trueArr, falseArr];\n };\n}\n\nexport function prepend<T>(...values: T[]) {\n return function (arr: T[]): T[] {\n arr.splice(0, 0, ...values);\n return arr;\n };\n}\n\nexport function select<T>(predFn: (e: T) => boolean) {\n return function (arr: T[]): T[] {\n return arr.filter(predFn);\n };\n}\n\n// returns the trailing elements of the array except for the leading n elements\nexport function skipFirst<T>(n: number) {\n return function (arr: T[]): T[] {\n if (n > arr.length) {\n n = arr.length;\n }\n return arr.slice(n, arr.length);\n };\n}\n\n// returns the leading elements of the array except for the trailing n elements\nexport function skipLast<T>(n: number) {\n return function (arr: T[]): T[] {\n if (n > arr.length) {\n n = arr.length;\n }\n return arr.slice(0, arr.length - n);\n };\n}\n\nexport function toSet(arr: Array<any>) {\n return new Set(arr);\n}\n\nexport function uniq(arr: Array<any>) {\n return uniqBy(identity)(arr);\n}\n\nexport function uniqBy<T, U>(comparisonValueFn: (value: T) => U) {\n return function (arr: Array<T>): Array<T> {\n const map = new Map<U, T>();\n for (const val of arr) {\n const key = comparisonValueFn(val);\n if (!map.has(key)) {\n map.set(key, val);\n }\n }\n return Array.from(map.values());\n };\n}\n\nexport function zip<T, U>(other: Array<U>) {\n return function (arr: Array<T>): Array<[T, U]> {\n var len = Math.min(arr.length, other.length);\n var result = Array(len);\n var idx = 0;\n while (idx < len) {\n result[idx] = [arr[idx], other[idx]];\n idx += 1;\n }\n return result;\n };\n}\n\n// export const A = {\n// compact,\n// concat,\n// each,\n// first,\n// map,\n// nth,\n// toSet,\n// uniq,\n// uniqBy,\n// };\n\nexport interface ArrayWrapperProxy extends BaseWrapperProxy {\n // Static methods registered via A.registerStatic\n compact: (omit?: any[]) => (arr: any[]) => any[];\n concat: <T>(tail: T[]) => (arr: T[]) => T[];\n each: <T>(eachFn: (value: T) => void) => (arr: Array<T>) => void;\n filter: <T>(predFn: (e: T) => boolean) => (arr: T[]) => T[]; // alias for select\n find: <T>(predicateFn: (v: T) => any) => (arr: Array<T>) => T | undefined;\n first: <T>(n: number) => (arr: T[]) => T[];\n head: <T>(arr: T[]) => T | undefined;\n isEmpty: <T>(arr: Array<T>) => boolean;\n join: (separator?: string) => <T>(arr: T[]) => string;\n last: <T>(n: number) => (arr: T[]) => T[];\n map: <T, U>(mapFn: (value: T) => U) => (arr: Array<T>) => Array<U>;\n nth: (n: number) => <T>(arr: T[]) => T | undefined;\n partition: <T>(predFn: (e: T) => boolean) => (arr: T[]) => [T[], T[]];\n prepend: <T>(...values: T[]) => (arr: T[]) => T[];\n select: <T>(predFn: (e: T) => boolean) => (arr: T[]) => T[];\n skipFirst: <T>(n: number) => (arr: T[]) => T[];\n skipLast: <T>(n: number) => (arr: T[]) => T[];\n toSet: <T>(arr: Array<T>) => Set<T>;\n uniq: <T>(arr: Array<T>) => T[];\n uniqBy: <T, U>(comparisonValueFn: (value: T) => U) => (arr: Array<T>) => Array<T>;\n zip: <T, U>(other: Array<U>) => (arr: Array<T>) => Array<[T, U]>;\n}\n\nexport const A = buildWrapperProxy() as ArrayWrapperProxy;\n\nA.registerUncurriedFns({ head, isEmpty, toSet, uniq });\nA.registerCurriedFns({\n compact,\n concat,\n each,\n filter: select,\n find,\n first,\n join,\n last,\n map,\n nth,\n partition,\n prepend,\n select,\n skipFirst,\n skipLast,\n uniqBy,\n zip,\n});\nA.registerStatic({\n compact,\n concat,\n each,\n filter: select,\n find,\n first,\n head,\n isEmpty,\n join,\n last,\n map,\n nth,\n partition,\n prepend,\n select,\n skipFirst,\n skipLast,\n toSet,\n uniq,\n uniqBy,\n zip,\n});\n\nimport './all-protocols';\n","import { Enumerable } from './enumerable';\nimport { buildWrapperProxy, type FunctionBag } from './function';\n\nexport interface SetWrapperProxy {\n <T>(wrappedValue: Set<T>): any; // Represents the function signature of S itself\n registerUncurriedFns: (fns: FunctionBag) => void;\n registerCurriedFns: (fns: FunctionBag) => void;\n registerStatic: (fns: FunctionBag) => void;\n\n // Static methods registered via S.registerStatic\n addAll: (enumerableVal: any) => <T>(set: Set<T>) => Set<T>;\n each: <V>(eachFn: (value: V) => void) => (set: Set<V>) => void;\n intersection: (enumerableVal: any) => <T>(set: Set<T>) => Set<T>;\n isEmpty: <V>(set: Set<V>) => boolean;\n isSubsetOf: (enumerableSuperset: any) => <T>(set: Set<T>) => boolean;\n isSupersetOf: (enumerableSubset: any) => <T>(set: Set<T>) => boolean;\n map: <V, T>(mapFn: (value: V) => T) => (set: Set<V>) => Set<T>;\n toArray: <V>(set: Set<V>) => V[];\n union: (enumerableVal: any) => <T>(set: Set<T>) => Set<T>;\n}\n\nexport function addAll(enumerableVal: any) {\n // console.log(`------------- addAll: ${V(enumerableVal).inspect()}`)\n const enumerable = Enumerable.for<Enumerable<any, any>>(enumerableVal);\n return function <T>(set: Set<T>): Set<T> {\n enumerable.each((item: T) => set.add(item));\n return set;\n };\n}\n\nexport function each<V>(eachFn: (value: V) => void) {\n return function (set: Set<V>): void {\n set.forEach((value) => {\n eachFn(value);\n });\n };\n}\n\nexport function intersection(enumerableVal: any) {\n const enumerable = Enumerable.for<Enumerable<any, any>>(enumerableVal);\n return function <T>(set: Set<T>): Set<T> {\n return set.intersection(enumerable.toSet());\n };\n}\n\nexport function isEmpty<V>(set: Set<V>): boolean {\n return set.size === 0;\n}\n\nexport function isSubsetOf(enumerableSuperset: any) {\n const enumerable = Enumerable.for<Enumerable<any, any>>(enumerableSuperset);\n return function <T>(set: Set<T>): boolean {\n return set.isSubsetOf(enumerable.toSet());\n };\n}\n\nexport function isSupersetOf(enumerableSubset: any) {\n const enumerable = Enumerable.for<Enumerable<any, any>>(enumerableSubset);\n return function <T>(set: Set<T>): boolean {\n return set.isSupersetOf(enumerable.toSet());\n };\n}\n\nexport function map<V, T>(mapFn: (value: V) => T) {\n return function (set: Set<V>): Set<T> {\n const s = new Set<T>();\n set.forEach((value) => {\n const newValue = mapFn(value);\n s.add(newValue);\n });\n return s;\n };\n}\n\nexport function toArray<V>(set: Set<V>): V[] {\n return Array.from(set.values());\n}\n\nexport function union(enumerableVal: any) {\n const enumerable = Enumerable.for<Enumerable<any, any>>(enumerableVal);\n return function <T>(set: Set<T>): Set<T> {\n return set.union(enumerable.toSet());\n };\n}\n\n// export const S = buildPipeThroughFunction();\n\n// Object.assign(S, {\n// addAll,\n// each,\n// intersection,\n// isEmpty,\n// isSubsetOf,\n// isSupersetOf,\n// map,\n// toArray,\n// union,\n// });\n\nexport const S = buildWrapperProxy() as SetWrapperProxy;\nS.registerUncurriedFns({ isEmpty, toArray });\nS.registerCurriedFns({ addAll, each, intersection, map, union, isSubsetOf, isSupersetOf });\nS.registerStatic({\n addAll,\n each,\n intersection,\n isEmpty,\n isSubsetOf,\n isSupersetOf,\n map,\n toArray,\n union,\n});\n\nimport './all-protocols';\n","import { A } from './array';\nimport { compact } from './compactable';\nimport { Enumerable, each } from './enumerable';\nimport { F } from './function';\nimport { M } from './map';\nimport { asyncMap, map } from './mappable';\nimport { O } from './object';\nimport { select } from './selectable';\nimport { S } from './set';\nimport { Str } from './string';\nimport { V } from './type';\nimport type { AnyConstructor } from './protocol';\n\nclass Pipe {\n constructor(public value: any) {}\n\n // e.g. convertMethodsToPipeline(A([1,2,3]))\n // returns a function that proxies method invocations through to the A([1,2,3]) object but assigns their return value\n // to this.value in the pipeline, and then returns the pipe object, enabling stuff like this:\n // P([1,2,3]).A.compact().A.first().value\n _convertMethodsToPipeline(wrappedValue: any, nameOfMethodBag: string) {\n const self = this;\n\n return new Proxy(wrappedValue, {\n get(target, property, receiver) {\n // function objects, like those returned from `A([1,2,3])`, have function properties attached to them that when invoked\n // will operate on the value supplied to the A function (e.g. [1,2,3]),\n // so we want to return a function that invokes the requested function property specified by the get handler\n // and assigns the result of the evaluation of that function property to the `this.value` member of the Pipe object\n const fn = Reflect.get(target, property, receiver);\n if (fn === undefined) {\n throw Error(`${nameOfMethodBag} does not have a method named ${String(property)}`);\n }\n // we return a function that wraps the function property that is being accessed, such that when invoked, the return value is\n // assigned to self.value and then the pipe object is returned\n return function (...args: any) {\n self.value = fn.apply(receiver, args);\n return self;\n };\n },\n });\n }\n\n get A() {\n return A(this.value);\n }\n\n get a() {\n return this._convertMethodsToPipeline(A(this.value), 'A');\n }\n\n compact(...args: any[]) {\n this.value = compact(...args)(this.value);\n return this;\n }\n\n each(visitorFn: (v: any) => any) {\n this.value = each(visitorFn)(this.value);\n return this;\n }\n\n get F() {\n return F(this.value);\n }\n\n get f() {\n return this._convertMethodsToPipeline(F(this.value), 'F');\n }\n\n // enumerable() {\n // this.value = Enumerable.for(this.value);\n // return this;\n // }\n\n // enumerator() {\n // this.value = Enumerator.for(this.value);\n // return this;\n // }\n\n log() {\n console.log(V.inspect(this.value));\n return this;\n }\n\n get M() {\n return M(this.value);\n }\n\n get m() {\n return this._convertMethodsToPipeline(M(this.value), 'M');\n }\n\n map(mapFn: (v: any) => any, implClass?: AnyConstructor) {\n this.value = map(mapFn)(this.value, implClass);\n return this;\n }\n\n asyncMap(mapFn: (v: any) => Promise<any> | any, implClass?: AnyConstructor) {\n this.value = asyncMap(mapFn)(this.value, implClass);\n return this;\n }\n\n get O() {\n return O(this.value);\n }\n\n get o() {\n return this._convertMethodsToPipeline(O(this.value), 'O');\n }\n\n pipe(fn: (value: any) => any) {\n this.value = fn(this.value);\n return this;\n }\n\n get S() {\n return S(this.value);\n }\n\n get s() {\n return this._convertMethodsToPipeline(S(this.value), 'S');\n }\n\n get Str() {\n return Str(this.value);\n }\n\n get str() {\n return this._convertMethodsToPipeline(Str(this.value), 'Str');\n }\n\n select(predFn: (v: any) => boolean, implClass?: AnyConstructor) {\n this.value = select(predFn)(this.value, implClass);\n return this;\n }\n\n toArray() {\n this.value = Enumerable.for<Enumerable<any, any>>(this.value).toArray();\n return this;\n }\n\n waitAll() {\n this.value = Promise.allSettled(this.value).then((results) => {\n return results.map((result) => {\n if (result.status === 'fulfilled') {\n return result.value;\n } else {\n return new Error(result.reason);\n }\n });\n });\n // .finally(() => {\n // console.log(\"Experiment completed\");\n // });\n return this;\n }\n}\n\nexport const VP = function (initial: any) {\n return new Pipe(initial);\n};\n\n// P([1,2,3,4]).map(v => v * 2).compact().value\n// P([1,2,3,4]).map(v => v * 2).A.compact()\n// P([1,2,3,4]).map(v => v * 2).a.compact().value\n// P([1,2,3,4]).map(v => v * 2).pipe(A.compact).value\n","import { homedir } from 'node:os';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport process from 'node:process';\nimport { File } from './flex/file';\nimport { Path } from './flex/path';\n\nexport class TmpFileRegistry {\n private static _instance?: TmpFileRegistry;\n static get instance() {\n const path = File.join(osHomeDir(), '.hostctl', 'tmpstatic');\n this._instance ??= new TmpFileRegistry(path);\n return this._instance;\n }\n\n private rootPath: Path;\n private tempFilePaths: string[];\n\n constructor(rootPath: string | Path) {\n // console.log(`TmpFileRegistry: ${rootPath}`);\n this.rootPath = Path.new(rootPath);\n this.tempFilePaths = [];\n process.on('exit', (code) => this.exitCallback());\n }\n\n randName(): string {\n return Math.random().toString(36).slice(-5) + Math.random().toString(36).slice(-5);\n }\n\n tmpPath(tmpName?: string) {\n tmpName ??= this.randName();\n return this.rootPath.join(tmpName);\n }\n\n // this directory will be automatically cleaned up at program exit\n createNamedTmpDir(subDirName?: string): Path {\n const path = this.tmpPath(subDirName);\n fs.mkdirSync(path.toString(), { recursive: true });\n this.registerTempFileOrDir(path.toString());\n return path;\n }\n\n // this file will be automatically cleaned up at program exit\n writeTmpFile(fileContent: string): Path {\n const path = this.tmpPath();\n fs.writeFileSync(path.toString(), fileContent);\n this.registerTempFileOrDir(path.toString());\n return path;\n }\n\n exitCallback() {\n this.cleanupTempFiles();\n }\n\n registerTempFileOrDir(path: string) {\n this.tempFilePaths.push(path);\n }\n\n cleanupTempFiles() {\n this.tempFilePaths.forEach((path) => {\n this.rmFile(path);\n });\n this.tempFilePaths = [];\n }\n\n rmFile(path: string) {\n try {\n // console.log(`rm tmp file: ${path}`)\n fs.rmSync(path, { force: true, recursive: true });\n } catch (e) {\n // no-op\n }\n }\n}\n\n/**\n * Returns the currently configured tmp dir from os.tmpdir().\n */\nexport function osTmpDir() {\n return path.resolve(os.tmpdir());\n}\n\nexport function osHomeDir() {\n return path.resolve(os.homedir());\n}\n\n// export function createHostCtlDir(): string {\n// const path = File.join(osHomeDir(), \".hostctl\");\n// fs.mkdirSync(path, { recursive: true });\n// return path;\n// }\n\n// export function createNamedTmpDir(subDirName: string = \"tmp\"): string {\n// // const path = File.join(osTmpDir(), subDirName);\n// const path = File.join(osHomeDir(), \".hostctl\", subDirName);\n// fs.mkdirSync(path, { recursive: true });\n// return path;\n// }\n\n// returns the full path to the temp file on disk\nexport function writeTmpFile(fileContents: string): Path {\n return TmpFileRegistry.instance.writeTmpFile(fileContents);\n // return temporaryWriteSync(fileContents);\n}\n\n// export function rmTmpFile(path: string) {\n// try {\n// fs.rmSync(path, { force: true, recursive: true });\n// } catch (e) {\n// // no-op\n// }\n// }\n\n// export function createTmpFile(): string {\n// tmp.setGracefulCleanup();\n\n// return tmp.tmpNameSync();\n// }\n\n// export function createTmpDir(): string {\n// tmp.setGracefulCleanup();\n\n// const tmpDir = tmp.dirSync();\n// return tmpDir.name;\n// }\n","import type { PathLike } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { win32, posix } from 'node:path';\nimport { isWindows } from './platform';\n\nexport function exists(path: PathLike): boolean {\n return existsSync(path);\n}\n\nexport class File {\n static absolutePath(...paths: string[]): string {\n if (isWindows()) {\n return win32.resolve(...paths);\n } else {\n return posix.resolve(...paths);\n }\n }\n\n // basename(\"c:\\\\foo\\\\bar\\\\baz.txt\") => \"baz.txt\"\n // basename(\"/tmp/myfile.html\") => \"myfile.html\"\n static basename(path: string, suffix?: string): string {\n if (isWindows()) {\n return win32.basename(path, suffix);\n } else {\n return posix.basename(path, suffix);\n }\n }\n\n static exists(path: PathLike): boolean {\n return exists(path);\n }\n\n static join(...paths: string[]): string {\n if (isWindows()) {\n return win32.join(...paths);\n } else {\n return posix.join(...paths);\n }\n }\n\n static readSync(path: PathLike): string {\n return readFileSync(path, {\n encoding: 'utf8',\n });\n }\n\n static async readAsync(path: PathLike): Promise<string> {\n return await readFile(path, {\n encoding: 'utf8',\n });\n }\n}\n","import { Perc } from './flex';\nimport { A } from './flex/array';\nimport { O } from './flex/object';\nimport { VP } from './flex/pipe';\nimport { Undefined, V, kind } from './flex/type';\nimport { S } from './flex/set';\nimport { ConfigFile, Secret, SecretRef, SecretValue } from './config-file';\nimport { writeTmpFile } from './tempfile';\n\nexport class Host {\n public hostname: string; // The network hostname or IP address, from the YAML hosts map key\n public alias?: string;\n public port: number;\n public user?: string;\n public password?: SecretRef | string;\n public sshKey?: SecretRef | string;\n public tags: string[];\n public tagSet: Set<string>;\n\n constructor(\n public config: ConfigFile,\n opts: {\n hostname: string; // The network hostname or IP from the YAML hosts map key\n alias?: string;\n port?: number;\n user?: string;\n password?: SecretRef | string;\n sshKey?: SecretRef | string;\n tags?: string[];\n },\n ) {\n this.hostname = opts.hostname;\n this.alias = opts.alias;\n this.port = opts.port || 22;\n this.user = opts.user;\n this.password = opts.password;\n this.sshKey = opts.sshKey;\n this.tags = opts.tags ?? [];\n this.tagSet = new Set(this.tags);\n }\n\n async decryptedPassword(): Promise<string | undefined> {\n switch (kind(this.password)) {\n case String:\n return this.password as string;\n case SecretRef:\n const secretRef = this.password as SecretRef;\n const secret = this.config.getSecret(secretRef.name);\n return await secret?.plaintext();\n }\n // otherwise, it's undefined, so implicitly return undefined\n }\n\n async decryptedSshKey(): Promise<string | undefined> {\n if (V(this.sshKey).isA(SecretRef)) {\n const secretRef = this.sshKey as SecretRef;\n const secret = this.config.getSecret(secretRef.name);\n return await secret?.plaintext();\n }\n // otherwise, it's either undefined or a string path to a key that is already on the filesystem, so implicitly return undefined\n }\n\n toYAML() {\n let passwordForYaml: string | ReturnType<SecretRef['toYAML']> | undefined = this.password;\n if (this.password && V(this.password).isA(SecretRef)) {\n passwordForYaml = (this.password as SecretRef).toYAML();\n }\n\n let sshKeyForYaml: string | ReturnType<SecretRef['toYAML']> | undefined = this.sshKey;\n if (this.sshKey && V(this.sshKey).isA(SecretRef)) {\n sshKeyForYaml = (this.sshKey as SecretRef).toYAML();\n }\n\n return {\n alias: this.alias,\n user: this.user,\n port: this.port === 22 ? undefined : this.port, // Only include port if not default\n password: passwordForYaml,\n 'ssh-key': sshKeyForYaml,\n tags: this.tags,\n };\n }\n\n // domain logic\n\n get shortName(): string {\n return this.alias || this.hostname;\n }\n\n isLocal(): boolean {\n // A host is local if its hostname is 'localhost' or '127.0.0.1'.\n // More robust checks could involve os.hostname(), but this is a common simple check.\n return this.hostname === 'localhost' || this.hostname === '127.0.0.1';\n }\n\n get uri(): string {\n return this.hostname;\n }\n\n // returns the temporary path to the decrypted ssh key\n async writeTmpDecryptedSshKey(): Promise<string | undefined> {\n const content = await this.decryptedSshKey();\n if (content) {\n return writeTmpFile(content).toString();\n }\n }\n\n private _plaintextSshKeyPath: string | undefined = undefined;\n async plaintextSshKeyPath(): Promise<string | undefined> {\n if (this._plaintextSshKeyPath) {\n return this._plaintextSshKeyPath;\n }\n\n switch (kind(this.sshKey)) {\n case String:\n this._plaintextSshKeyPath = this.sshKey as string;\n break;\n case SecretRef:\n this._plaintextSshKeyPath = await this.writeTmpDecryptedSshKey();\n break;\n }\n return this._plaintextSshKeyPath;\n }\n\n toObject() {\n return {\n hostname: this.hostname,\n port: this.port,\n alias: this.alias,\n user: this.user,\n tags: this.tags,\n };\n }\n\n hasTag(tag: string): boolean {\n return this.tagSet.has(tag);\n }\n\n // each tag is a string of the form:\n // - foo\n // - bar,baz\n // the interpretation of a 'bar,baz' tag is that the host must have either the 'bar' tag or the 'baz' tag in order to consider the 'bar,baz' tag present\n hasAllTags(tags: Set<string>): boolean {\n for (const tag of tags) {\n const tagParts = tag.split(',');\n const anyTagPartPresent = S(this.tagSet).intersection(tagParts).size > 0;\n if (!anyTagPartPresent) return false;\n }\n return true;\n }\n\n // each tag is a string of the form:\n // - foo\n // - bar+baz\n // the interpretation of a 'bar+baz' tag is that the host must have both the 'bar' tag and the 'baz' tag in order to consider the 'bar+baz' tag present\n hasAnyTag(tags: Set<string>): boolean {\n const effectiveTagsForMatching = S(new Set(this.tagSet)).addAll(A([this.hostname, this.alias]).compact());\n for (const tag of tags) {\n const tagParts = tag.split('+');\n const allTagPartsPresent = S(effectiveTagsForMatching).isSupersetOf(tagParts);\n if (allTagPartsPresent) return true;\n }\n return false;\n }\n}\n","// import { encrypt_with_x25519, decrypt_with_x25519 } from \"@kanru/rage-wasm\";\nimport fs from 'node:fs';\nimport * as age from 'age-encryption';\n\nimport { Process } from './process';\nimport { writeTmpFile } from './tempfile';\n\nconst AGE_ENCRYPTED_FILE_HEADER = '-----BEGIN AGE ENCRYPTED FILE-----';\n\n// Define a common interface for encryption drivers\ninterface IAgeDriver {\n encrypt(valueToEncrypt: string, publicKeys: string[]): Promise<string>;\n decrypt(valueToDecrypt: string, privateKeyFilePaths: string[]): Promise<string | null>;\n}\n\n// Helper function to read identity string from a file (used by LibraryDriver)\nfunction readIdentityStringFromFile(path: string): string {\n const contents = fs.readFileSync(path, {\n encoding: 'utf8',\n });\n const identityString = contents\n .split(/\\r?\\n|\\r|\\n/g)\n .map((line) => line.trim())\n .find((line) => line.startsWith('AGE-SECRET-KEY-1'));\n if (!identityString) throw new Error(`Unable to read identity from file: ${path}`);\n return identityString;\n}\n\nexport class CliDriver implements IAgeDriver {\n async encrypt(valueToEncrypt: string, publicKeys: string[]): Promise<string> {\n const recipientArgs = publicKeys.flatMap((key) => ['-r', key]);\n // Capture stderr for better error reporting\n const { stdout, success, stderr } = await Process.spawn('age', ['-e', '-a'].concat(recipientArgs), valueToEncrypt);\n\n if (!success) {\n // Use new Error and include stderr if available\n throw new Error(`Failed to encrypt with age CLI: ${stderr || stdout}`);\n }\n return stdout;\n }\n\n async decrypt(valueToDecrypt: string, privateKeyFilePaths: string[]): Promise<string | null> {\n if (privateKeyFilePaths.length === 0) {\n // Use new Error for consistency\n throw new Error('Unable to decrypt: No age encryption identity (private key) specified.');\n }\n const identityArgs = privateKeyFilePaths.flatMap((path) => ['-i', path]);\n // Capture stderr for better error reporting\n const { stdout, success, stderr } = await Process.spawn('age', ['-d'].concat(identityArgs), valueToDecrypt);\n\n if (!success) {\n // console.error(`Failed to decrypt with age CLI: ${stderr || stdout}`); // Optional for debugging\n return null; // Return null on failure\n }\n return stdout;\n }\n}\n\n// New LibraryDriver using age-encryption package, implementing IAgeDriver\nexport class LibraryDriver implements IAgeDriver {\n async encrypt(valueToEncrypt: string, publicKeys: string[]): Promise<string> {\n const e = new age.Encrypter();\n publicKeys.forEach((key) => e.addRecipient(key));\n const ciphertextBytes = await e.encrypt(valueToEncrypt); // Returns Uint8Array\n return age.armor.encode(ciphertextBytes); // Armor the Uint8Array to string\n }\n\n async decrypt(valueToDecryptArmored: string, privateKeyFilePaths: string[]): Promise<string | null> {\n if (privateKeyFilePaths.length === 0) {\n throw new Error('Unable to decrypt: No age encryption identity (private key) specified.');\n }\n\n const d = new age.Decrypter();\n let identitiesAdded = 0;\n for (const path of privateKeyFilePaths) {\n try {\n const identityString = readIdentityStringFromFile(path);\n d.addIdentity(identityString);\n identitiesAdded++;\n } catch (err) {\n // Log and continue: an invalid key path shouldn't prevent other valid keys from being tried.\n console.warn(`Failed to read or parse identity file ${path}, skipping: ${(err as Error).message}`);\n }\n }\n\n if (identitiesAdded === 0) {\n // console.error(\"Decryption failed: No valid identities could be loaded.\");\n return null; // No valid keys were loaded to attempt decryption.\n }\n\n try {\n const ciphertextBytes = age.armor.decode(valueToDecryptArmored); // De-armor string to Uint8Array\n const decryptedText = await d.decrypt(ciphertextBytes, 'text'); // Decrypts to string\n return decryptedText;\n } catch (error) {\n // Handles errors from age.armor.decode or d.decrypt (e.g., bad armor, no matching identity, corrupted data)\n // console.error(\"Library decryption failed:\", error); // Optional: for debugging\n return null; // Return null on any decryption failure\n }\n }\n}\n\nexport class Identity {\n public identityFilePath: string;\n private identity: string;\n\n // either the path to an identity file or an identity string must be supplied\n constructor({ path, identity }: { path?: string; identity?: string }) {\n if (identity) {\n this.identity = identity;\n this.identityFilePath = this.writeTmpIdentityFile(identity);\n } else if (path) {\n this.identity = this.readIdentityFromFile(path);\n this.identityFilePath = path;\n } else {\n throw 'Either an identity string or an identity file path must be supplied to create an Age Encryption identity';\n }\n }\n\n public get recipient(): Promise<string> {\n return age.identityToRecipient(this.identity);\n }\n\n // returns the path to the temp file\n private writeTmpIdentityFile(identity: string) {\n return writeTmpFile(identity).toString();\n }\n\n private readIdentityFromFile(path: string): string {\n const contents = fs.readFileSync(path, {\n encoding: 'utf8',\n });\n\n const identityString = contents\n .split(/\\r?\\n|\\r|\\n/g)\n .map((line) => line.trim())\n .find((line) => line.startsWith('AGE-SECRET-KEY-1'));\n\n if (!identityString) throw new Error(`Unable to read identity file: ${path}`);\n\n return identityString;\n }\n\n get privateKey(): string {\n return this.identity;\n }\n\n get publicKey(): Promise<string> {\n return this.recipient;\n }\n\n decrypt(encryptedString: string): Promise<string | null> {\n return AgeEncryption.decrypt(encryptedString, [this.identityFilePath]);\n\n ///////////////////////////////////\n\n // const encryptedBytes = new TextEncoder().encode(encryptedString);\n // const plaintextBytes = await decrypt_with_x25519(this.identity, encryptedBytes);\n // return new TextDecoder().decode(plaintextBytes);\n\n ///////////////////////////////////\n\n // const d = new Decrypter();\n // d.addIdentity(this.identity);\n\n // const encryptedBytes = new TextEncoder().encode(encryptedString);\n // return d.decrypt(encryptedBytes, \"text\");\n }\n\n async encrypt(plaintext: string): Promise<string> {\n return AgeEncryption.encrypt(plaintext, [await this.recipient]);\n\n ///////////////////////////////////\n\n // const plaintextBytes = new TextEncoder().encode(plaintext);\n // const encryptedBytes = await encrypt_with_x25519(\n // this.recipient,\n // plaintextBytes,\n // true\n // );\n // return new TextDecoder().decode(encryptedBytes);\n\n ///////////////////////////////////\n\n // const e = new Encrypter();\n // e.addRecipient(this.recipient);\n\n // const encryptedBytes = e.encrypt(plaintext);\n // return new TextDecoder().decode(encryptedBytes);\n }\n}\n\nexport class AgeEncryption {\n static instance: IAgeDriver = new LibraryDriver(); // Use LibraryDriver by default\n\n static async encrypt(valueToEncrypt: string, publicKeys: string[]): Promise<string> {\n const encrypted = await this.instance.encrypt(valueToEncrypt, publicKeys);\n // console.log(`encrypting ${valueToEncrypt} with keys ${publicKeys}: ${encrypted}`)\n return encrypted;\n }\n\n static async decrypt(valueToDecrypt: string, privateKeyFilePaths: string[]): Promise<string | null> {\n return await this.instance.decrypt(valueToDecrypt, privateKeyFilePaths);\n }\n}\n\n// const id = new Identity({ path: \"/home/david/.secrets/age/david.priv\" });\n// console.log(\"identity\", id.privateKey);\n// console.log(\"recipient\", id.publicKey);\n// const encrypted = await id.encrypt(\"food\");\n// console.log(\"encrypt 'food' =>\", encrypted);\n// const plain = await id.decrypt(encrypted);\n// console.log(`decrypt '${encrypted}' =>`, plain);\n","import spawnAsync, { type SpawnResult } from '@expo/spawn-async';\n\nexport type ProcessResult = SpawnResult & { success: boolean };\nexport class Process {\n static spawn(cmd: string, args: string[], stdin?: string): Promise<ProcessResult> {\n return new Process(cmd, args, stdin).spawn();\n }\n\n constructor(\n public cmd: string,\n public args: string[],\n public stdin?: string,\n ) {}\n\n async spawn(): Promise<ProcessResult> {\n try {\n const spawnOptions = {\n ignoreStdio: false,\n // detached: true, // if we wanted to keep child alive after parent exits\n };\n const promise = spawnAsync(this.cmd, this.args, spawnOptions);\n\n if (this.stdin && promise.child) {\n promise.child.stdin?.write(this.stdin);\n promise.child.stdin?.end();\n }\n const result: SpawnResult = await promise;\n\n // const child = procp.child;\n // const stdout = new StringBuilder();\n // const stderr = new StringBuilder();\n\n // child.stdout?.on('data', (data) => {\n // stdout.append(data);\n // });\n\n // child.stderr?.on('data', (data) => {\n // stderr.append(data);\n // });\n\n // child.on('exit', (code, signal) => {\n // console.log(`child process exited with code ${code} and signal ${signal}`);\n // });\n\n return { ...result, success: result.status === 0 };\n } catch (e) {\n // The error object also has the same properties as the result object\n // console.error(e.stack);\n const errorResult = e as SpawnResult;\n return { ...errorResult, success: errorResult.status === 0 };\n }\n }\n}\n","import { Host } from './host';\nimport type { Config, IRecipientGroup, ISecret } from './config';\nimport type { Secret, RecipientGroup } from './config-file'; // Import concrete types for Map values\n\nexport class ConfigUrl implements Config {\n public _hosts: Map<string, Host>;\n public _secrets: Map<string, Secret>;\n public _ids: Map<string, RecipientGroup>;\n\n constructor(public url: string) {\n this._hosts = new Map();\n this._secrets = new Map();\n this._ids = new Map();\n }\n\n // Config interface\n\n hosts(): Host[] {\n return [];\n }\n\n getSecret(name: string): ISecret | undefined {\n return undefined; // ConfigUrl does not manage individual secrets\n }\n\n getRecipientGroups(idRefs: string[]): IRecipientGroup[] {\n return []; // ConfigUrl does not manage recipient groups\n }\n\n secrets(): Map<string, Secret> {\n return this._secrets;\n }\n\n ids(): Map<string, RecipientGroup> {\n return this._ids;\n }\n}\n","import { Readable } from 'node:stream';\nimport { StreamRegex } from 'stream-regex';\nimport { M } from './flex/map';\nimport { VP } from './flex/pipe';\nimport { A } from './flex/array';\nimport type { InputMap } from './util/input-helpers';\n\nexport class InteractionHandler {\n static with(inputs: InputMap): InteractionHandler {\n return new InteractionHandler(new Map(Object.entries(inputs)));\n }\n\n private patternInputMappings: Map<string, string>; // pairs of pattern -> response\n private inputStreamForRegexMatcher: Readable | undefined;\n // private streamRegex: StreamRegex;\n // private matches: Readable;\n private writeFn: ((str: string) => void) | undefined;\n constructor(patternInputMappings: Map<string | RegExp, string> = new Map()) {\n this.patternInputMappings = M(patternInputMappings).map(([pattern, v]: [string | RegExp, string]) => [\n pattern instanceof RegExp ? pattern.source : pattern,\n v,\n ]);\n }\n clone(): InteractionHandler {\n return new InteractionHandler(this.patternInputMappings);\n }\n with(inputs: InputMap): InteractionHandler {\n const clone = this.clone();\n clone.mapInput(inputs);\n return clone;\n }\n mapInput(inputMap: InputMap): InteractionHandler {\n Object.entries(inputMap).forEach(([pattern, response]) => {\n this.map(pattern, response);\n });\n return this;\n }\n map(pattern: RegExp | string, response: string) {\n if (pattern instanceof RegExp) {\n this.patternInputMappings.set(pattern.source, response);\n } else {\n this.patternInputMappings.set(pattern, response);\n }\n return this;\n }\n // builds a regex of the form /(alternative 1)|(alternative 2)|...|(alternative N)/\n compositeRegex(): RegExp | undefined {\n if (M(this.patternInputMappings).isEmpty()) return undefined;\n const compositePattern: string = VP(this.patternInputMappings)\n .m.keys()\n .map((pattern: string) => `(${pattern})`)\n .a.join('|').value;\n return new RegExp(compositePattern, 'g');\n }\n // returns the first pattern that matches\n // the matching pattern will be a key in ioMappings\n firstMatchingPattern(matchStr: string): string | undefined {\n // we know this will not return undefined because the pattern has already been observed, we just need to figure out which regex matched it\n return Array.from(this.patternInputMappings.keys()).find((pattern) => matchStr.match(pattern));\n }\n findReplacementForMatch(matchStr: string): string | undefined {\n const matchingPattern = this.firstMatchingPattern(matchStr);\n if (!matchingPattern) return undefined; // we know this will not return undefined because the pattern has already been observed, we just need to figure out which regex matched it\n const replacementValue = this.patternInputMappings.get(matchingPattern);\n return replacementValue;\n }\n begin() {\n this.inputStreamForRegexMatcher = new Readable();\n this.inputStreamForRegexMatcher._read = () => {};\n const compositeRegex = this.compositeRegex();\n if (compositeRegex) {\n // this.streamRegex = new StreamRegex(compositeRegex);\n // this.matches = this.streamRegex.match(this.inputStreamForRegexMatcher);\n // this.matches.on(\"data\", (matchStr) => {\n const streamRegex = new StreamRegex(compositeRegex);\n const matches: Readable = streamRegex.match(this.inputStreamForRegexMatcher);\n matches.on('data', (matchStr) => {\n // console.log(\"interaction handler match\", matchStr);\n const inputToWrite: string | undefined = this.findReplacementForMatch(matchStr);\n if (inputToWrite !== undefined) {\n this.emitInput(inputToWrite);\n }\n });\n }\n }\n handleInput(inputChunk: string) {\n // console.log(\"interaction handler handle input\", inputChunk);\n if (this.inputStreamForRegexMatcher) {\n this.inputStreamForRegexMatcher.push(inputChunk);\n }\n }\n // either use setOutputToNewReadable XOR setOutputWriter; not both\n setOutputToNewReadable(): Readable {\n const stdinReadable = new Readable();\n this.setOutputWriter((str) => stdinReadable.push(str));\n stdinReadable._read = () => {};\n return stdinReadable;\n }\n // either use setOutputToNewReadable XOR setOutputWriter; not both\n setOutputWriter(writeFn: (str: string) => void) {\n this.writeFn = writeFn;\n }\n private emitInput(input: string): void {\n if (this.writeFn) {\n this.writeFn(input);\n }\n }\n end() {\n if (this.inputStreamForRegexMatcher) {\n this.inputStreamForRegexMatcher.push(null);\n }\n }\n}\n","// src/task.model.ts\nimport type { TaskContext } from './runtime-base'; // Type-only import for RunFn definition\n\n/**\n * Generic object type for parameters and return values.\n */\nexport type ObjectType = { [key: string]: any };\n\n/**\n * Base type for task-specific parameters.\n */\nexport type TaskParams = ObjectType;\n\n/**\n * Represents the possible return values of a task's run function.\n */\nexport type RunFnReturnValue = ObjectType | void | undefined | null | Error;\n\n/**\n * Defines the signature of a task's main execution function.\n * It receives a TaskContext and returns a Promise of a RunFnReturnValue.\n */\nexport interface RunFn<TParams extends TaskParams = TaskParams, TReturn extends RunFnReturnValue = RunFnReturnValue> {\n (context: TaskContext<TParams>): Promise<TReturn>;\n}\n\n/**\n * Represents a task definition, including its run function and metadata.\n * This class is instantiated by the `task` factory function.\n */\nexport class Task<TParams extends TaskParams = TaskParams, TReturn extends RunFnReturnValue = RunFnReturnValue> {\n constructor(\n public runFn: RunFn<TParams, TReturn>,\n public taskModuleAbsolutePath?: string,\n public description?: string,\n public name?: string,\n ) {}\n}\n","import StackTracey from 'stacktracey';\n\n// StackTracey {\n// items: [\n// {\n// beforeParse: 'at REPL36:1:1',\n// callee: '',\n// index: false,\n// native: false,\n// file: 'REPL36',\n// line: 1,\n// column: 1,\n// calleeShort: '',\n// fileRelative: 'REPL36',\n// fileShort: 'REPL36',\n// fileName: 'REPL36',\n// thirdParty: false,\n// externalDomain: undefined\n// },\n// {\n// beforeParse: 'at ContextifyScript.runInThisContext (node:vm:136:12)',\n// callee: 'ContextifyScript.runInThisContext',\n// index: false,\n// native: false,\n// file: 'node:vm',\n// line: 136,\n// column: 12,\n// calleeShort: 'runInThisContext',\n// fileRelative: 'node:vm',\n// fileShort: 'node:vm',\n// fileName: 'node:vm',\n// thirdParty: false,\n// externalDomain: undefined\n// },\n// {\n// beforeParse: 'at REPLServer.defaultEval (node:repl:598:22)',\n// callee: 'REPLServer.defaultEval',\n// index: false,\n// native: false,\n// file: 'node:repl',\n// line: 598,\n// column: 22,\n// calleeShort: 'defaultEval',\n// fileRelative: 'node:repl',\n// fileShort: 'node:repl',\n// fileName: 'node:repl',\n// thirdParty: false,\n// externalDomain: undefined\n// },\n// {\n// beforeParse: 'at bound (node:domain:432:15)',\n// callee: 'bound',\n// index: false,\n// native: false,\n// file: 'node:domain',\n// line: 432,\n// column: 15,\n// calleeShort: 'bound',\n// fileRelative: 'node:domain',\n// fileShort: 'node:domain',\n// fileName: 'node:domain',\n// thirdParty: false,\n// externalDomain: undefined\n// },\n// {\n// beforeParse: 'at REPLServer.runBound (node:domain:443:12)',\n// callee: 'REPLServer.runBound',\n// index: false,\n// native: false,\n// file: 'node:domain',\n// line: 443,\n// column: 12,\n// calleeShort: 'runBound',\n// fileRelative: 'node:domain',\n// fileShort: 'node:domain',\n// fileName: 'node:domain',\n// thirdParty: false,\n// externalDomain: undefined\n// },\n// {\n// beforeParse: 'at REPLServer.preEval [as eval] (/home/david/.local/share/mise/installs/node/22.7.0/lib/node_modules/tsx/dist/patch-repl.cjs:1:366)',\n// callee: 'REPLServer.preEval [as eval]',\n// index: false,\n// native: false,\n// file: '/home/david/.local/share/mise/installs/node/22.7.0/lib/node_modules/tsx/dist/patch-repl.cjs',\n// line: 1,\n// column: 366,\n// calleeShort: 'preEval [as eval]',\n// fileRelative: '../../../../.local/share/mise/installs/node/22.7.0/lib/node_modules/tsx/dist/patch-repl.cjs',\n// fileShort: '../../../../.local/share/mise/installs/node/22.7.0/lib/node_modules/tsx/dist/patch-repl.cjs',\n// fileName: 'patch-repl.cjs',\n// thirdParty: false,\n// externalDomain: undefined\n// },\n// {\n// beforeParse: 'at process.processTicksAndRejections (node:internal/process/task_queues:105:5)',\n// callee: 'process.processTicksAndRejections',\n// index: false,\n// native: false,\n// file: 'node:internal/process/task_queues',\n// line: 105,\n// column: 5,\n// calleeShort: 'processTicksAndRejections',\n// fileRelative: 'node:internal/process/task_queues',\n// fileShort: 'node:internal/process/task_queues',\n// fileName: 'task_queues',\n// thirdParty: false,\n// externalDomain: undefined\n// }\n// ]\n// }\nexport function callstack() {\n return new StackTracey();\n}\n","import { callstack } from './stacktrace';\nimport { Path } from './flex/path';\nimport { Host } from './host'; // For TaskContext and IInvocation\nimport { Mutex } from 'async-mutex'; // For Invocation\nimport { type CommandResult, type EnvVarObj } from './command'; // For IInvocation & TaskContext\nimport { StringBuilder } from 'typescript-string-operations'; // For Invocation\nimport { Verbosity, type App, type AppConfig } from './app'; // For IRuntime and TaskContext\nimport type { ConfigFile } from './config-file'; // For IRuntime\nimport type { InteractionHandler } from './interaction-handler'; // For IRuntime\nimport type { SSHSession } from './ssh-session'; // For IRuntime\nimport chalk from 'chalk'; // For Invocation.exit logging\nimport {\n Task, // Value import\n type ObjectType, // Type import for use within this module\n type TaskParams, // Type import for use within this module\n type RunFnReturnValue, // Type import for use within this module\n type RunFn, // Type import for use within this module\n} from './task.model';\n\nexport type LogLevel = number; // Numerical log levels, compatible with Verbosity in app.ts\n// ObjectType, TaskParams, RunFnReturnValue, RunFn are now imported from task.model.ts\n\nexport interface FileSystemOperations {\n read: (path: string) => Promise<string>;\n write: (\n path: string,\n content: string,\n options?: { mode?: string | number; user?: string; group?: string },\n ) => Promise<void>;\n exists: (path: string) => Promise<boolean>;\n mkdir: (path: string, options?: { recursive?: boolean; mode?: string | number }) => Promise<void>;\n rm: (path: string, options?: { recursive?: boolean; force?: boolean }) => Promise<void>;\n // Consider adding stat, ls, etc. later\n}\n\nexport interface TaskContext<TParams extends TaskParams = TaskParams> {\n params: TParams;\n readonly id: string;\n readonly host?: Host;\n readonly config: AppConfig; // Access to resolved application configuration\n log: (level: LogLevel, ...message: any[]) => void; // Unified logging with level\n info: (...message: any[]) => void;\n debug: (...message: any[]) => void;\n warn: (...message: any[]) => void;\n error: (...message: any[]) => void;\n\n // exec is for running shell commands on the host\n exec: (\n command: string | string[],\n options?: {\n input?: Record<string, string>;\n sudo?: boolean;\n stdin?: string | Buffer;\n env?: EnvVarObj;\n cwd?: string;\n user?: string;\n pty?: boolean;\n },\n ) => Promise<CommandResult>; // Renamed from sh\n\n // ssh will ssh into a set of hosts and evaluate the given function for each host\n ssh: <TRemoteParams extends TaskParams = {}, TRemoteReturn extends RunFnReturnValue = RunFnReturnValue>(\n tags: string[],\n remoteTaskFn: (remoteContext: TaskContext<TRemoteParams>) => Promise<TRemoteReturn>,\n ) => Promise<Record<string, TRemoteReturn | Error>>;\n\n // run will run a given task script\n run: <TRunReturn extends RunFnReturnValue>(taskPartialFn: TaskPartialFn<TRunReturn>) => Promise<TRunReturn>;\n\n // getPassword will prompt the user for a password\n getPassword: () => Promise<string | undefined>;\n\n // getSecret will retrieve a secret from the application configuration\n getSecret: (name: string) => Promise<string | undefined>;\n\n // exit will exit the application\n exit: (exitCode: number, message?: string) => void;\n\n // inventory will return a list of hosts that match the given tags\n inventory: (tags: string[]) => Host[];\n file: FileSystemOperations; // File system operations contextualized to host\n}\n\n// RunFn and Task class are now imported from task.model.ts\n\nexport type TaskPartialFn<TReturn extends RunFnReturnValue = RunFnReturnValue> = (\n parentInvocation: IInvocation,\n) => Promise<TReturn>;\n\n// Task class is imported from task.model.ts\n\nexport interface TaskFn<TParams extends TaskParams = TaskParams, TReturn extends RunFnReturnValue = RunFnReturnValue> {\n (params?: TParams): TaskPartialFn<TReturn>;\n task: Task<TParams, TReturn>;\n}\n\nexport function task<TParams extends TaskParams, TReturn extends RunFnReturnValue>(\n runFn: RunFn<TParams, TReturn>,\n options?: { description?: string; name?: string },\n): TaskFn<TParams, TReturn> {\n const moduleThatTaskIsDefinedIn = Path.new(callstack().items[2].file).absolute().toString();\n const taskName = options?.name || 'anonymous_task';\n const taskInstance = new Task<TParams, TReturn>(runFn, moduleThatTaskIsDefinedIn, options?.description, taskName);\n\n const taskFnObject: TaskFn<TParams, TReturn> = function (params?: TParams) {\n return function (parentInvocation: IInvocation): Promise<TReturn> {\n return parentInvocation.invokeChildTask(taskFnObject, params ?? ({} as TParams)) as Promise<TReturn>;\n };\n } as TaskFn<TParams, TReturn>;\n Object.assign(taskFnObject, { task: taskInstance });\n\n return taskFnObject;\n}\n\nexport interface IInvocation<TParams extends TaskParams = any> {\n id: string;\n runtime: IRuntime;\n host?: Host;\n readonly config: AppConfig;\n log(level: LogLevel, ...message: any[]): void;\n info(...message: any[]): void;\n debug(...message: any[]): void;\n warn(...message: any[]): void;\n error(...message: any[]): void;\n exec(\n command: string | string[],\n options?: {\n input?: Record<string, string>;\n sudo?: boolean;\n stdin?: string | Buffer;\n env?: EnvVarObj;\n cwd?: string;\n user?: string;\n pty?: boolean;\n },\n ): Promise<CommandResult>;\n readonly file: FileSystemOperations;\n ssh<TRemoteParams extends TaskParams = {}, TRemoteReturn extends RunFnReturnValue = RunFnReturnValue>(\n tags: string[],\n remoteTaskFn: (remoteContext: TaskContext<TRemoteParams>) => Promise<TRemoteReturn>,\n ): Promise<Record<string, TRemoteReturn | Error>>;\n run<TRunReturn extends RunFnReturnValue>(taskPartialFn: TaskPartialFn<TRunReturn>): Promise<TRunReturn>;\n invokeChildTask<TTaskParams extends TaskParams, TTaskReturn extends RunFnReturnValue>(\n childTaskFn: TaskFn<TTaskParams, TTaskReturn>,\n params: TTaskParams,\n ): Promise<TTaskReturn>;\n getPassword(): Promise<string | undefined>;\n getSecret(name: string): Promise<string | undefined>;\n exit(exitCode: number, message?: string): void;\n inventory(tags: string[]): Host[];\n setDescription(description: string): void;\n setFutureResult(resultPromise: Promise<RunFnReturnValue>): void;\n appendChildInvocation(childInvocation: IInvocation<any>): Promise<void>;\n readonly stderr: string;\n readonly stdout: string;\n resultError(): Promise<Error | undefined>;\n getDescription(): string | undefined;\n getChildren(): ReadonlyArray<IInvocation<any>>;\n getResultPromise(): Promise<RunFnReturnValue>;\n}\n\nexport abstract class Invocation<TParams extends TaskParams = any> implements IInvocation<TParams> {\n public id: string;\n public children: Array<IInvocation<any>>; // Children can have any params\n private childrenMutex: Mutex;\n public description?: string;\n public stderrSB: StringBuilder;\n public stdoutSB: StringBuilder;\n public host?: Host;\n public result: Promise<RunFnReturnValue>;\n public resolveResult: (value: RunFnReturnValue | PromiseLike<RunFnReturnValue>) => void;\n public rejectResult: (reason?: any) => void;\n\n constructor(\n public runtime: IRuntime,\n public taskFnDefinition: TaskFn<TParams, any>,\n public parent?: IInvocation<any>,\n ) {\n this.id = crypto.randomUUID();\n this.children = [];\n this.childrenMutex = new Mutex();\n const { promise, resolve, reject } = Promise.withResolvers<RunFnReturnValue>();\n this.result = promise;\n this.resolveResult = resolve;\n this.rejectResult = reject;\n this.stdoutSB = new StringBuilder();\n this.stderrSB = new StringBuilder();\n }\n\n // Constructor and fields are above\n\n // Concrete method implementations\n getPassword(): Promise<string | undefined> {\n return this.runtime.getPassword();\n }\n\n async getSecret(name: string): Promise<string | undefined> {\n // Ensure config is available, typically via this.runtime.app.config\n // This might need adjustment if 'this.config' is the direct source.\n const secret = this.runtime.app.config.getSecret(name);\n if (!secret) {\n return undefined;\n }\n return secret.plaintext();\n }\n\n get stderr(): string {\n return this.stderrSB.toString();\n }\n\n get stdout(): string {\n return this.stdoutSB.toString();\n }\n\n info(...message: any[]) {\n this.log(Verbosity.INFO, ...message);\n }\n\n debug(...message: any[]) {\n this.log(Verbosity.DEBUG, ...message);\n }\n\n warn(...message: any[]) {\n this.log(Verbosity.WARN, ...message);\n }\n\n error(...message: any[]) {\n this.log(Verbosity.ERROR, ...message);\n }\n\n async resultError(): Promise<Error | undefined> {\n try {\n await this.result;\n return undefined;\n } catch (e) {\n return e as Error;\n }\n }\n\n setDescription(description: string) {\n this.description = description;\n }\n\n setFutureResult(resultPromise: Promise<RunFnReturnValue>) {\n resultPromise.then(this.resolveResult, this.rejectResult);\n }\n\n public getDescription(): string | undefined {\n return this.description;\n }\n public getChildren(): ReadonlyArray<IInvocation<any>> {\n return this.children;\n }\n public getResultPromise(): Promise<RunFnReturnValue> {\n return this.result;\n }\n\n public exit(exitCode: number, message?: string): void {\n if (message) {\n this.runtime.app.warn(\n chalk.yellow(`Task ${this.description || this.id} requested exit with code ${exitCode}: ${message}`),\n );\n }\n process.exit(exitCode);\n }\n\n inventory(tags: string[]): Host[] {\n return this.runtime.inventory(tags);\n }\n\n async appendChildInvocation(childInvocation: IInvocation<any>) {\n // Ensure IInvocation<any>\n await this.childrenMutex.runExclusive(async () => {\n this.children.push(childInvocation);\n });\n }\n\n // Abstract method declarations (must be implemented by subclasses)\n public abstract readonly config: AppConfig;\n public abstract log(level: LogLevel, ...message: any[]): void;\n public abstract exec(\n command: string | string[],\n options?: {\n input?: Record<string, string>;\n sudo: boolean;\n stdin?: string | Buffer;\n env?: EnvVarObj;\n cwd?: string;\n user?: string;\n pty?: boolean;\n },\n ): Promise<CommandResult>;\n public abstract readonly file: FileSystemOperations;\n public abstract ssh<TRemoteParams extends TaskParams = {}, TRemoteReturn extends RunFnReturnValue = RunFnReturnValue>(\n tags: string[],\n remoteTaskFn: (remoteContext: TaskContext<TRemoteParams>) => Promise<TRemoteReturn>,\n ): Promise<Record<string, TRemoteReturn | Error>>;\n public abstract run<TRunReturn extends RunFnReturnValue>(\n taskPartialFn: TaskPartialFn<TRunReturn>,\n ): Promise<TRunReturn>;\n public abstract invokeChildTask<TTaskParams extends TaskParams, TTaskReturn extends RunFnReturnValue>(\n childTaskFn: TaskFn<TTaskParams, TTaskReturn>,\n params: TTaskParams,\n ): Promise<TTaskReturn>;\n // Note: 'exit' has a concrete implementation above, so it's not abstract here.\n // Note: 'inventory' has a concrete implementation above, so it's not abstract here.\n}\n\nexport interface IRuntime {\n app: App;\n config?: { cwd?: string; configFile?: ConfigFile };\n interactionHandler: InteractionHandler;\n tmpDirRootPath: Path;\n\n getPassword(): Promise<string | undefined>;\n getSecret(name: string): Promise<string | undefined>;\n getTmpDir(): Path;\n getTmpFile(prefix?: string, postfix?: string, dir?: Path): Path;\n inventory(tags: string[]): Host[];\n invokeRootTask<TParams extends TaskParams, TReturn extends RunFnReturnValue>(\n taskFnDefinition: TaskFn<TParams, TReturn>,\n params: TParams,\n description?: string,\n ): Promise<IInvocation<TParams>>;\n}\n","import type { Signal } from 'human-signals';\nexport type { Signal };\nimport { A } from './flex/array';\nimport { V } from './flex/type';\nimport { parse, quote } from 'shell-quote';\nimport Shellwords from 'shellwords-ts';\n\nexport type EnvVarObj = Record<string, string>;\n\nexport class CommandResult {\n constructor(\n public stdout: string,\n public stderr: string,\n public exitCode: number,\n public signal?: Signal,\n ) {}\n\n toJSON() {\n return {\n stdout: this.stdout,\n stderr: this.stderr,\n exitCode: this.exitCode,\n signal: this.signal,\n success: this.success,\n failure: this.failure,\n };\n }\n get out() {\n return this.stdout;\n }\n get err() {\n return this.stderr;\n }\n get exit() {\n return this.exitCode;\n }\n get sig() {\n return this.signal;\n }\n get success() {\n return this.exitCode === 0;\n }\n get failure() {\n return !this.success;\n }\n}\n\nexport class Command {\n static parse(\n commandString: string,\n env?: EnvVarObj,\n ): {\n cmd: string;\n args: string[];\n env?: EnvVarObj;\n } {\n if (!commandString || commandString.trim() === '') {\n throw new Error('Command string cannot be empty.');\n }\n // const quotedCmd = quote([commandString]);\n // console.log(`parse: ${commandString} -> ${quotedCmd}`);\n // const parts = parse(quotedCmd);\n // console.log(`parts: ${parts}`);\n\n const parts = Shellwords.split(commandString);\n // console.log(`parts: ${JSON.stringify(parts)}`);\n\n const cmd_unsafe = A.head(parts);\n if (cmd_unsafe === undefined) {\n // This case should be prevented by the check for empty commandString earlier\n throw new Error(`Failed to parse command from string: \"${commandString}\". Resulted in no command part.`);\n }\n const cmd: string = cmd_unsafe;\n // console.log(cmd);\n const parsedArgs = A(parts).skipFirst(1);\n // console.log(parsedArgs);\n\n const args: string[] = A(parsedArgs).compact();\n // console.log(args);\n\n return {\n cmd,\n args,\n env,\n };\n }\n\n public cmd;\n public args?;\n public cwd?: string;\n public env?: Record<string, string>;\n public result?: CommandResult;\n\n constructor(opts: {\n cmd: string;\n args?: string[];\n cwd?: string;\n env?: Record<string, string>;\n result?: CommandResult;\n }) {\n const { cmd, args, cwd, env, result } = opts;\n this.cmd = cmd;\n this.args = args;\n this.cwd = cwd;\n this.env = env;\n this.result = result;\n }\n\n isRunning(): boolean {\n return !!this.result;\n }\n\n toJSON() {\n return {\n cmd: this.cmd,\n args: this.args,\n cwd: this.cwd,\n env: this.env,\n result: this.result?.toJSON(),\n };\n }\n}\n","import Handlebars from 'handlebars';\nimport {\n type IInvocation,\n Invocation,\n type IRuntime,\n type TaskContext,\n type TaskFn,\n type TaskParams,\n type RunFnReturnValue,\n type TaskPartialFn,\n type LogLevel,\n RemoteRuntime,\n RemoteInvocation,\n task,\n type RunFn, // Consolidate LogLevel import here\n} from './runtime'; // Source all from ./runtime\nimport { Host } from './host';\nimport { Path } from './flex/path';\nimport { type App, type AppConfig, Verbosity } from './app';\n// LogLevel is now imported from ./runtime\nimport * as fs from 'node:fs';\nimport { ConfigFile } from './config-file';\n// CommandResult is now a value import, Command class is also imported directly\nimport { Command, CommandResult, type EnvVarObj } from './command';\nimport { InteractionHandler } from './interaction-handler';\n// import { PtyCommand } from \"./pty-command\";\nimport { RusPtyCommand } from './ruspty-command';\nimport { O } from './flex/object';\nimport { VP } from './flex/pipe';\nimport { A } from './flex/array';\nimport chalk from 'chalk';\nimport { V } from './flex/type';\nimport { withSudo } from './util/input-helpers';\n\nexport interface FileSystemOperations {\n read: (path: string) => Promise<string>;\n write: (\n path: string,\n content: string,\n options?: { mode?: string | number | undefined; user?: string | undefined; group?: string | undefined },\n ) => Promise<void>;\n exists: (path: string) => Promise<boolean>;\n mkdir: (\n path: string,\n options?: { recursive?: boolean | undefined; mode?: string | number | undefined },\n ) => Promise<void>;\n rm: (path: string, options?: { recursive?: boolean | undefined; force?: boolean | undefined }) => Promise<void>;\n}\n\nexport class LocalInvocation<TParams extends TaskParams, TReturn extends RunFnReturnValue> extends Invocation<TParams> {\n public readonly config: AppConfig;\n public readonly file: FileSystemOperations;\n constructor(\n public runtime: LocalRuntime,\n public taskFnDefinition: TaskFn<TParams, TReturn>,\n params: TParams,\n parent?: IInvocation<any>,\n ) {\n super(runtime, taskFnDefinition, parent);\n this.description = Handlebars.compile(\n taskFnDefinition.task.description || taskFnDefinition.task.name || 'anonymous_local_task',\n )(params);\n this.config = this.runtime.app.config; // Access getter, not method\n // this.host is undefined for LocalInvocation, which is fine as TaskContext.host is optional.\n\n this.file = {\n read: async (path: string): Promise<string> => fs.promises.readFile(path, 'utf-8'),\n write: async (\n path: string,\n content: string,\n options?: { mode?: string | number | undefined; user?: string | undefined; group?: string | undefined },\n ): Promise<void> => fs.promises.writeFile(path, content, { mode: options?.mode as fs.Mode | undefined }),\n exists: async (path: string): Promise<boolean> => {\n try {\n await fs.promises.access(path);\n return true;\n } catch {\n return false;\n }\n },\n mkdir: async (\n path: string,\n options?: { recursive?: boolean | undefined; mode?: string | number | undefined },\n ): Promise<void> => {\n await fs.promises.mkdir(path, options as fs.MakeDirectoryOptions | undefined);\n },\n rm: async (\n path: string,\n options?: { recursive?: boolean | undefined; force?: boolean | undefined },\n ): Promise<void> => fs.promises.rm(path, options as fs.RmOptions | undefined),\n };\n }\n\n public log(level: LogLevel, ...message: any[]): void {\n this.runtime.app.log(level, ...message);\n }\n\n override async exec(\n command: string | string[],\n options: {\n input?: Record<string, string>;\n sudo?: boolean;\n stdin?: string | Buffer;\n env?: EnvVarObj;\n cwd?: string;\n user?: string;\n pty?: boolean;\n } = {},\n ): Promise<CommandResult> {\n options = options || {};\n\n const interactionHandler = this.runtime.interactionHandler.clone();\n const stdinForCommand: string | Buffer | undefined = options.stdin;\n\n if (options.input && typeof options.input === 'object') {\n // Input is for interaction handler patterns\n O(options.input).each(([pattern, value]: [string, string]) => {\n interactionHandler.map(pattern, value);\n });\n }\n\n if (options.sudo) {\n const hostPassword = await this.runtime.getPassword();\n interactionHandler.mapInput(withSudo(hostPassword));\n }\n\n // InteractionHandler is for responding to prompts, not for initial stdin.\n\n // TODO: Handle options.user if specified (e.g., via sudo -u)\n // TODO: options.pty is implicitly true due to PtyCommand. If false, would need a non-PTY command runner.\n\n const cwd = options.cwd ?? process.cwd();\n let finalEnv: EnvVarObj = {};\n\n if (options.env) {\n finalEnv = options.env;\n } else {\n // Ensure process.env values are filtered for undefined\n Object.keys(process.env).forEach((key) => {\n const value = process.env[key];\n if (value !== undefined) {\n finalEnv[key] = value;\n }\n });\n }\n\n let commandInstance: RusPtyCommand;\n if (command instanceof Array) {\n // command = PtyCommand.fromArray(cmd, finalEnv, cwd);\n commandInstance = RusPtyCommand.fromArray(command, finalEnv, cwd);\n } else {\n // command = PtyCommand.fromString(cmd, finalEnv, cwd);\n commandInstance = RusPtyCommand.fromString(command, finalEnv, cwd);\n }\n\n this.log(\n Verbosity.DEBUG as LogLevel,\n `Executing command: ${Array.isArray(command) ? command.join(' ') : command}${options.stdin ? ' with stdin' : ''}${options.input ? ' with interaction patterns' : ''}`,\n );\n await commandInstance.run(interactionHandler, stdinForCommand);\n\n const cmdResult = commandInstance.result;\n if (!cmdResult) {\n this.log(Verbosity.ERROR as LogLevel, 'Command execution resulted in undefined result.');\n // Return a new CommandResult instance for the error case\n return new CommandResult('', 'Command execution resulted in undefined result.', -1, undefined);\n }\n // Output is already captured by PtyCommand and available in cmdResult.stdout/stderr\n // Task authors can log it if they wish using this.log(LogLevel.INFO, cmdResult.stdout)\n // For now, we don't auto-log stdout/stderr here to avoid duplication if task also logs.\n\n return cmdResult;\n }\n\n override async ssh<TRemoteParams extends TaskParams = {}, TRemoteReturn extends RunFnReturnValue = RunFnReturnValue>(\n tags: string[],\n remoteTaskFn: (remoteContext: TaskContext<TRemoteParams>) => Promise<TRemoteReturn>,\n ): Promise<Record<string, TRemoteReturn | Error>> {\n const targetHosts: Host[] = this.runtime.app.querySelectedInventory(tags);\n\n if (targetHosts.length === 0) {\n this.runtime.app.warn(`No hosts found for tags: ${tags.join(', ')} in ssh call from ${this.id}`);\n return {};\n }\n\n const entryPromises = VP(targetHosts).map(async (host: Host): Promise<[string, TRemoteReturn | Error]> => {\n const result = await this.runRemoteTaskOnHost<TRemoteParams, TRemoteReturn>(host, remoteTaskFn);\n return [host.hostname, result];\n }).value;\n\n const entries = await Promise.all(entryPromises);\n const record: Record<string, TRemoteReturn | Error> = Object.fromEntries(entries);\n return record;\n }\n\n async runRemoteTaskOnHost<TRemoteParams extends TaskParams, TRemoteReturn extends RunFnReturnValue>(\n host: Host,\n remoteTaskFn: RunFn<TRemoteParams, TRemoteReturn>,\n ): Promise<TRemoteReturn | Error> {\n this.debug(`Run function on: ${chalk.yellow(V.inspect(host.toObject()))}`);\n\n const interactionHandler = new InteractionHandler(this.runtime.app.getSecretsForHost(host.hostname));\n\n const remoteRuntime = new RemoteRuntime(\n this.runtime.app,\n host,\n this.runtime, // The LocalRuntime instance of this LocalInvocation\n interactionHandler,\n );\n\n try {\n const connected = await remoteRuntime.connect();\n if (!connected) {\n throw new Error(`Unable to connect to ${host.uri}`);\n }\n\n const adHocRemoteInvocationTaskFn = task<TRemoteParams, TRemoteReturn>(\n async function (context: TaskContext<TRemoteParams>): Promise<TRemoteReturn> {\n return remoteTaskFn(context);\n },\n { description: `Ad-hoc task on ${host.uri} via ssh from ${this.taskFnDefinition.task.name} (${this.id})` },\n );\n\n const rootRemoteInvocation = new RemoteInvocation(\n remoteRuntime,\n adHocRemoteInvocationTaskFn, // This TaskFn is for the container of the ad-hoc operation on this host\n {} as TRemoteParams,\n this, // Parent is the current LocalInvocation\n host,\n );\n await this.appendChildInvocation(rootRemoteInvocation);\n\n const rootRemoteContext = this.runtime.app.taskContextForRunFn(\n rootRemoteInvocation,\n {} as TRemoteParams,\n host,\n ) as TaskContext<TRemoteParams>;\n const resultPromise = remoteTaskFn(rootRemoteContext);\n rootRemoteInvocation.setFutureResult(resultPromise);\n rootRemoteInvocation.setDescription(`SSH to ${host.uri}`);\n\n return await resultPromise;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n this.runtime.app.error(\n `Error during SSH operation to ${host.uri}: ${errorMessage}`,\n error instanceof Error ? error.stack : undefined,\n );\n return error instanceof Error ? error : new Error(errorMessage);\n } finally {\n await remoteRuntime.disconnect();\n }\n }\n\n public exit(exitCode: number, message?: string): void {\n if (message) {\n this.log(exitCode === 0 ? (Verbosity.INFO as LogLevel) : (Verbosity.ERROR as LogLevel), message);\n }\n // In a library context, actually calling process.exit() is often undesirable.\n // Throwing a specific error might be better for the app to handle.\n // For now, keeping it simple, but this could be a point of future refinement.\n this.runtime.app.warn(`Task ${this.id} requested exit with code ${exitCode}. Forcing process exit.`);\n process.exit(exitCode);\n }\n\n public inventory(tags: string[]): Host[] {\n return this.runtime.app.queryInventory(new Set(tags));\n }\n\n override async run<TRunReturn extends RunFnReturnValue>(\n taskPartialFn: TaskPartialFn<TRunReturn>,\n ): Promise<TRunReturn> {\n return taskPartialFn(this);\n }\n\n override async invokeChildTask<TTaskParams extends TaskParams, TTaskReturn extends RunFnReturnValue>(\n childTaskFnDefinition: TaskFn<TTaskParams, TTaskReturn>,\n params: TTaskParams,\n ): Promise<TTaskReturn> {\n const childInvocation = new LocalInvocation(this.runtime, childTaskFnDefinition, params, this);\n await this.appendChildInvocation(childInvocation);\n\n const loggedChildResultPromise = childInvocation.result\n .then((value) => {\n if (value instanceof Error) return value;\n if (value === undefined || value === null) return undefined;\n return String(value);\n })\n .catch((error) => error);\n this.runtime.app.taskTree.add(\n childInvocation.id,\n this.id,\n childTaskFnDefinition.task.name || 'anonymous_child_task',\n loggedChildResultPromise,\n );\n\n const taskContext = this.runtime.app.taskContextForRunFn(\n childInvocation,\n params,\n undefined /* host is undefined for local */,\n ) as TaskContext<TTaskParams>;\n\n try {\n const result = await childTaskFnDefinition.task.runFn.call(childInvocation, taskContext);\n childInvocation.resolveResult(result);\n return result as TTaskReturn;\n } catch (error) {\n childInvocation.rejectResult(error as Error);\n throw error;\n }\n }\n}\n\nexport class LocalRuntime implements IRuntime {\n public config?: { cwd?: string; configFile?: ConfigFile };\n public host: Host; // Represents the local machine\n private memoizedPassword?: string;\n\n constructor(\n public app: App,\n public localBundlePath: Path,\n public interactionHandler: InteractionHandler = new InteractionHandler(),\n ) {\n const appConfigInstance = this.app.config;\n if (appConfigInstance instanceof ConfigFile) {\n this.host = new Host(appConfigInstance, { hostname: 'localhost' });\n } else {\n const configType = appConfigInstance?.constructor?.name || typeof appConfigInstance;\n this.app.error(\n `CRITICAL ERROR: LocalRuntime could not initialize its 'localhost' Host object. The application's configuration (type: ${configType}) is not a file-based configuration (expected ConfigFile).`,\n );\n throw new Error(\n `LocalRuntime init failed: Expected app.config to be an instance of ConfigFile for 'localhost' Host, but got ${configType}.`,\n );\n }\n this.config = {\n cwd: process.cwd(),\n configFile: appConfigInstance instanceof ConfigFile ? appConfigInstance : undefined,\n };\n }\n\n get tmpDirRootPath(): Path {\n return this.app.hostctlTmpDir();\n }\n\n async getPassword(): Promise<string | undefined> {\n if (this.memoizedPassword) {\n return this.memoizedPassword;\n }\n this.memoizedPassword = await this.app.promptPassword('Enter local sudo password:');\n return this.memoizedPassword;\n }\n\n async getSecret(name: string): Promise<string | undefined> {\n const secret = this.app.config.getSecret(name);\n if (!secret) {\n this.app.warn(`Secret ${name} not found in config.`);\n return undefined;\n }\n return secret.plaintext();\n }\n\n getTmpDir(): Path {\n return this.app.createNamedTmpDir();\n }\n\n getTmpFile(prefix?: string | undefined, postfix?: string | undefined, dir?: Path | undefined): Path {\n const tmpDir = dir || this.getTmpDir();\n // Use crypto.randomUUID() for a unique filename component\n const randomName = prefix ? `${prefix}-${crypto.randomUUID()}` : crypto.randomUUID();\n const finalName = postfix ? `${randomName}-${postfix}` : randomName;\n return tmpDir.join(finalName);\n }\n\n inventory(tags: string[]): Host[] {\n return this.app.queryInventory(new Set(tags));\n }\n\n async invokeRootTask<TParams extends TaskParams, TReturn extends RunFnReturnValue>(\n taskFnDefinition: TaskFn<TParams, TReturn>,\n params: TParams,\n description?: string,\n ): Promise<LocalInvocation<TParams, TReturn>> {\n const rootInvocation = new LocalInvocation<TParams, TReturn>(\n this,\n taskFnDefinition,\n params,\n undefined /* no parent */,\n );\n if (description) {\n rootInvocation.description = description;\n }\n const loggedRootResultPromise = rootInvocation.result\n .then((value) => {\n if (value instanceof Error) return value;\n if (value === undefined || value === null) return undefined;\n return String(value);\n })\n .catch((error) => error);\n this.app.taskTree.add(\n rootInvocation.id,\n null,\n taskFnDefinition.task.name || 'anonymous_root_task',\n loggedRootResultPromise,\n );\n\n // Corrected to call taskContextForRunFn on this.app instead of this.app.taskTree\n const taskContext = this.app.taskContextForRunFn(\n rootInvocation,\n params,\n undefined /* host is undefined */,\n ) as TaskContext<TParams>;\n\n taskFnDefinition.task.runFn\n .call(rootInvocation, taskContext)\n .then(rootInvocation.resolveResult)\n .catch(rootInvocation.rejectResult);\n\n return rootInvocation;\n }\n}\n","import { Pty } from '@replit/ruspty';\nimport { StringBuilder } from 'typescript-string-operations';\n\nimport { Command, CommandResult, type EnvVarObj } from './command';\nimport { InteractionHandler } from './interaction-handler';\nimport { signalsByNumber } from 'human-signals';\nimport { O } from './flex/object';\nimport { A } from './flex/array';\n\nexport class RusPtyCommand extends Command {\n static fromArray(commandWithArgs: string[], env?: EnvVarObj, cwd?: string): RusPtyCommand {\n const envObj: EnvVarObj = O(env || {}).map(([key, value]: [string, string | undefined]) => [key, String(value)]);\n const cmd: string = commandWithArgs[0] || ''; // Use direct access and provide a fallback\n const parsedArgs = commandWithArgs.slice(1);\n const args: string[] = parsedArgs.filter((arg) => arg !== null && arg !== undefined && arg !== ''); // Simplified compact\n\n return new RusPtyCommand({ cmd, args, cwd, env: envObj });\n }\n\n static fromString(command: string, env?: EnvVarObj, cwd?: string): RusPtyCommand {\n const envObj: EnvVarObj = O(env || {}).map(([key, value]: [string, string | undefined]) => [key, String(value)]);\n const { cmd, args } = this.parse(command, envObj);\n return new RusPtyCommand({ cmd, args, cwd, env: envObj });\n }\n\n public process!: Pty; // Definite assignment assertion\n\n async run(interactionHandler = new InteractionHandler(), stdin?: string | Buffer): Promise<CommandResult> {\n const self = this;\n return new Promise<CommandResult>(function (resolve, reject) {\n const stdout = new StringBuilder();\n // console.log(`Pty> ${self.cmd} ${self.args}`);\n self.process = new Pty({\n command: self.cmd,\n args: self.args,\n dir: self.cwd,\n envs: self.env as Record<string, string>,\n interactive: true,\n size: { rows: 30, cols: 80 },\n onExit: (err: null | Error, exitCode: number) => {\n interactionHandler.end();\n // console.log(`exit code: ${exitCode}`);\n // console.log(`exit signal: ${signal}`);\n // const signalObj = signalsByNumber[signal || 10000];\n const signalObj = undefined;\n const commandResult = new CommandResult(stdout.toString(), '', exitCode, signalObj);\n self.result = commandResult;\n resolve(commandResult);\n },\n });\n\n const read = self.process.read;\n const write = self.process.write;\n\n if (stdin) {\n // console.log(`Pty> stdin: ${stdin}`);\n write.write(stdin);\n // Consider self.process.end() or write.write('\\x04') if EOF is needed.\n }\n\n interactionHandler.begin();\n interactionHandler.setOutputWriter((str) => write.write(str));\n\n read.on('data', (chunk) => {\n stdout.append(chunk);\n interactionHandler.handleInput(chunk);\n });\n });\n }\n}\n","/**\n * An object representing the mapping of expected output (as a regex string)\n * to the input that should be provided in response.\n */\nexport type InputMap = Record<string, string>;\n\nexport const CHECKMARK = '\\u2713';\nexport const XMARK = '\\u2717';\n\n/**\n * A collection of regular expressions to detect various sudo/doas password prompts\n * across different operating systems.\n */\nexport const SUDO_PROMPT_REGEX = {\n /**\n * Matches the default sudo prompt on most Linux distributions.\n * Example: `[sudo] password for <username>:`\n */\n LINUX: '\\\\[sudo\\\\] password',\n\n /**\n * Matches the default sudo prompt on macOS and some BSD systems.\n * Example: `Password:`\n */\n MAC_BSD: '^Password:',\n\n /**\n * Matches the default prompt for `doas` on OpenBSD.\n * Example: `doas (username@hostname) password:`\n */\n DOAS: 'doas \\\\(.*\\\\) password:',\n};\n\n/**\n * A helper function that builds an input map to handle various sudo/doas password prompts.\n * This is useful for building up interaction handlers for commands that require privilege escalation\n * across different operating systems.\n *\n * @param password The sudo/doas password to provide.\n * @param existingInputMap An optional existing map of interactions.\n * @returns A new input map containing the sudo/doas prompt interactions and any existing interactions.\n */\nexport function withSudo(password: string | undefined, existingInputMap: InputMap = {}): InputMap {\n if (!password) {\n return existingInputMap;\n }\n const passwordResponse = `${password}\\n`;\n return {\n ...existingInputMap,\n [SUDO_PROMPT_REGEX.LINUX]: passwordResponse,\n [SUDO_PROMPT_REGEX.MAC_BSD]: passwordResponse,\n [SUDO_PROMPT_REGEX.DOAS]: passwordResponse,\n };\n}\n","import Handlebars from 'handlebars';\nimport {\n type IInvocation,\n Invocation,\n type IRuntime,\n type TaskFn,\n type TaskContext,\n type TaskParams,\n type RunFnReturnValue,\n type ObjectType,\n type TaskPartialFn,\n Task, // Use Task directly\n type FileSystemOperations,\n type LogLevel, // Consolidate LogLevel import here\n} from './runtime'; // Source all from ./runtime\nimport * as path from 'node:path';\nimport type { LocalRuntime } from './local-runtime'; // For config inheritance\nimport { Host } from './host';\nimport type { Config as NodeSSHConfig } from 'node-ssh'; // For SSH connection options\nimport { Path } from './flex/path';\nimport { Verbosity, type App, type AppConfig } from './app';\n// LogLevel is now imported from ./runtime\nimport { CommandResult, type EnvVarObj, Command, type Signal } from './command';\nimport { InteractionHandler } from './interaction-handler';\nimport { SSHSession } from './ssh-session';\nimport { isError } from './error';\nimport chalk from 'chalk';\nimport * as util from 'node:util';\nimport { StringBuilder } from 'typescript-string-operations';\nimport { ConfigFile } from './config-file';\nimport { O } from './flex/object';\nimport { match, P } from 'ts-pattern';\nimport { V } from './flex/type';\nimport { withSudo, type InputMap } from './util/input-helpers';\n\nexport class RemoteInvocation<\n TParams extends TaskParams = any,\n TReturn extends RunFnReturnValue = any,\n> extends Invocation<TParams> {\n public readonly config: AppConfig;\n public readonly file: FileSystemOperations;\n // sshSession is removed from RemoteInvocation, it will be managed by RemoteRuntime\n\n constructor(\n runtime: IRuntime,\n public taskFnDefinition: TaskFn<TParams, TReturn>,\n params: TParams,\n public parent: IInvocation<any>,\n public hostInstance?: Host,\n ) {\n super(runtime, taskFnDefinition, parent);\n this.description = Handlebars.compile(\n taskFnDefinition.task.description || taskFnDefinition.task.name || 'anonymous_remote_task',\n )(params);\n this.host = hostInstance || parent.host; // Inherit host from parent if not provided\n if (!this.host) {\n throw new Error('RemoteInvocation must have a host.');\n }\n this.config = this.runtime.app.config;\n\n this.file = {\n read: async (filePath: string): Promise<string> => {\n const sftp = await this.ensureSftp();\n const remotePath = this.resolveRemotePath(filePath);\n return new Promise<string>((resolve, reject) => {\n sftp.readFile(remotePath, (err: Error | null, data: Buffer | undefined) => {\n if (err) {\n return reject(err);\n }\n if (!data) {\n // Should not happen if err is null, but good practice\n return reject(new Error(`SFTP readFile returned no data for ${remotePath}`));\n }\n resolve(data.toString('utf-8'));\n });\n });\n },\n write: async (filePath: string, content: string, options?: { mode?: string | number }): Promise<void> => {\n const sftp = await this.ensureSftp();\n const remotePath = this.resolveRemotePath(filePath);\n await sftp.writeFile(remotePath, content, { mode: options?.mode as number | undefined });\n },\n exists: async (filePath: string): Promise<boolean> => {\n const sftp = await this.ensureSftp();\n const remotePath = this.resolveRemotePath(filePath);\n return new Promise((resolve, reject) => {\n sftp.stat(remotePath, (err: Error | null, stats: any) => {\n // stats type might need refinement from ssh2 types\n if (err) {\n // Common SFTP error codes for 'No such file' are 2 (SSH_FX_NO_SUCH_FILE from ssh2-streams constants)\n // node-ssh might wrap this, check error object structure\n const sftpError = err as any;\n if (\n sftpError.code === 2 ||\n sftpError.code === 'ENOENT' ||\n (typeof err.message === 'string' &&\n (err.message.includes('No such file') || err.message.includes('No such entity')))\n ) {\n resolve(false);\n } else {\n reject(err);\n }\n } else {\n resolve(true);\n }\n });\n });\n },\n mkdir: async (dirPath: string, options?: { recursive?: boolean; mode?: string | number }): Promise<void> => {\n const remoteDir = this.resolveRemotePath(dirPath);\n let command = `mkdir ${options?.recursive ? '-p ' : ''}${this.quoteRemoteArg(remoteDir)}`;\n await this.exec(command); // Use this.exec for consistency\n if (options?.mode) {\n await this.exec(`chmod ${this.quoteRemoteArg(String(options.mode))} ${this.quoteRemoteArg(remoteDir)}`);\n }\n },\n rm: async (itemPath: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> => {\n const remoteItem = this.resolveRemotePath(itemPath);\n const command = `rm ${options?.recursive ? '-r ' : ''}${options?.force ? '-f ' : ''}${this.quoteRemoteArg(remoteItem)}`;\n await this.exec(command); // Use this.exec for consistency\n },\n };\n }\n\n private async ensureSftp(): Promise<any> {\n // Return type should be the actual SFTP client type from node-ssh\n if (!(this.runtime instanceof RemoteRuntime)) {\n throw new Error('Runtime is not a RemoteRuntime instance, cannot ensure SFTP.');\n }\n // Delegate to RemoteRuntime to get the SFTP client\n return this.runtime.getSftpClient();\n }\n\n private resolveRemotePath(p: string): string {\n // Assuming paths are either absolute or relative to the user's home directory on the remote host\n // node-ssh's SFTP methods generally treat non-absolute paths as relative to home.\n // For exec, CWD handling is separate.\n return p; // Keep it simple for now, let node-ssh handle path resolution relative to home for SFTP.\n }\n\n private quoteRemoteArg(arg: string): string {\n return \"'\" + arg.replace(/'/g, \"'\\\\''\") + \"'\";\n }\n\n public log(level: LogLevel, ...message: any[]): void {\n const hostUri = this.host ? `${this.host.user || ''}@${this.host.hostname}` : 'unknown-host'; // Changed host to hostname\n this.runtime.app.log(level, `[${hostUri}|${this.id}|${this.description || 'task'}]`, ...message);\n }\n\n uri(): string {\n if (!this.host) throw new Error('Host is not defined for this remote invocation.');\n return `${this.host.user || this.runtime.app.defaultSshUser()}@${this.host.hostname}`; // Changed host to hostname\n }\n\n override async exec(\n command: string | string[],\n options?: {\n input?: InputMap;\n sudo?: boolean;\n stdin?: string | Buffer;\n env?: Record<string, string>;\n cwd?: string;\n user?: string;\n pty?: boolean;\n },\n ): Promise<CommandResult> {\n if (!this.host) throw new Error('Host is not defined for exec command in RemoteInvocation.');\n\n if (!(this.runtime instanceof RemoteRuntime)) {\n throw new Error('Runtime is not a RemoteRuntime instance, cannot execute remote command.');\n }\n\n const stdinForRemoteCommand: string | Buffer | undefined = options?.stdin;\n // Start with a clone of the runtime's default handler.\n // This handler can be augmented with exec-specific patterns.\n const execSpecificInteractionHandler = this.runtime.interactionHandler.clone();\n\n if (options?.input) {\n execSpecificInteractionHandler.mapInput(options.input);\n }\n\n if (options?.sudo) {\n const hostPassword = await this.runtime.getPassword();\n execSpecificInteractionHandler.mapInput(withSudo(hostPassword));\n }\n\n // TODO: Add support to run command as another user\n // let commandToRun = Array.isArray(command) ? command.join(\" \") : command;\n // if (options?.user) {\n // commandToRun = `sudo -u ${this.quoteRemoteArg(options.user)} -- /bin/sh -c ${this.quoteRemoteArg(commandToRun)}`;\n // }\n\n this.debug(`Executing remote command on ${this.host.hostname}: ${command}`); // Changed host to hostname\n\n const cmdOrErr = await this.runtime.executeCommand(command, {\n cwd: options?.cwd,\n stdin: stdinForRemoteCommand,\n pty: options?.pty,\n env: options?.env,\n interactionHandler: execSpecificInteractionHandler, // Pass the potentially augmented handler\n });\n\n return match(cmdOrErr)\n .with(P.instanceOf(Error), (err: Error) => {\n throw err;\n })\n .with(P.instanceOf(Command), (command: Command) => {\n return command.result!;\n })\n .exhaustive();\n }\n\n public exit(exitCode: number, message?: string): void {\n const hostUri = this.host ? `${this.host.user || ''}@${this.host.hostname}` : 'unknown-host'; // Changed host to hostname\n const msg = `Remote task ${this.id} on ${hostUri} requested exit with code ${exitCode}${message ? ': ' + message : ''}`;\n this.log(Verbosity.WARN as LogLevel, msg);\n // Throwing an error is more appropriate than trying to force a remote process.exit()\n throw new Error(msg);\n }\n\n public inventory(tags: string[]): Host[] {\n return this.runtime.app.queryInventory(new Set(tags));\n }\n\n override async run<TRunReturn extends RunFnReturnValue>(\n taskPartialFn: TaskPartialFn<TRunReturn>,\n ): Promise<TRunReturn> {\n return taskPartialFn(this);\n }\n\n override async invokeChildTask<TTaskParams extends TaskParams, TTaskReturn extends RunFnReturnValue>(\n childTaskFnDefinition: TaskFn<TTaskParams, TTaskReturn>,\n params: TTaskParams,\n ): Promise<TTaskReturn> {\n if (!this.host) throw new Error('Host is not defined for invokeChildTask in RemoteInvocation.');\n\n const childInvocation = new RemoteInvocation(this.runtime, childTaskFnDefinition, params, this, this.host);\n await this.appendChildInvocation(childInvocation);\n\n this.runtime.app.taskTree.add(\n childInvocation.id,\n this.id,\n childTaskFnDefinition.task.name || 'anonymous_remote_child_task',\n childInvocation.result.then((r) => (r === null ? undefined : r)) as Promise<string | Error | undefined>,\n );\n\n const taskContext = this.runtime.app.taskContextForRunFn(\n childInvocation,\n params,\n this.host,\n ) as TaskContext<TTaskParams>;\n\n try {\n const result = await childTaskFnDefinition.task.runFn.call(childInvocation, taskContext);\n childInvocation.resolveResult(result);\n return result as TTaskReturn;\n } catch (error) {\n childInvocation.rejectResult(error as Error);\n throw error;\n } // End of catch block for invokeChildTask\n } // End of invokeChildTask method\n\n override ssh<TRemoteParams extends TaskParams = {}, TRemoteReturn extends RunFnReturnValue = RunFnReturnValue>(\n tags: string[],\n remoteTaskFn: (remoteContext: TaskContext<TRemoteParams>) => Promise<TRemoteReturn>,\n ): Promise<Record<string, TRemoteReturn | Error>> {\n throw new Error('ssh from a remote host is not currently supported.');\n }\n} // End of RemoteInvocation class\n\nexport class RemoteRuntime implements IRuntime {\n private sftpClientInstance?: any; // Type should be SFTPWrapper from 'node-ssh'\n public readonly app: App;\n public readonly host: Host;\n public readonly interactionHandler: InteractionHandler;\n private sshSession: SSHSession;\n\n constructor(\n app: App,\n host: Host,\n _localRuntime: LocalRuntime,\n interactionHandler: InteractionHandler = new InteractionHandler(),\n ) {\n this.app = app;\n this.host = host;\n this.interactionHandler = interactionHandler;\n this.sshSession = new SSHSession(); // Initialize SSH session for this host for context\n }\n\n get tmpDirRootPath(): Path {\n return new Path('/tmp');\n }\n\n async getPassword(): Promise<string | undefined> {\n return await this.host.decryptedPassword();\n }\n\n async getSecret(name: string): Promise<string | undefined> {\n const secret = this.app.config.getSecret(name);\n if (!secret) {\n this.app.warn(`Secret ${name} not found in config.`);\n return undefined;\n }\n return secret.plaintext();\n }\n\n getTmpDir(): Path {\n return this.tmpDirRootPath.join(this.app.randName());\n }\n\n getTmpFile(prefix?: string | undefined, postfix?: string | undefined, dir?: Path | undefined): Path {\n const tmpDir = dir || this.getTmpDir();\n return tmpDir.join(this.app.randName());\n }\n\n inventory(tags: string[]): Host[] {\n return this.app.queryInventory(new Set(tags));\n }\n\n async connect(): Promise<boolean> {\n if (this.sshSession.isConnected() && this.sftpClientInstance) {\n this.app.debug(`RemoteRuntime: SSH session and SFTP already connected to ${this.host.uri}`);\n return true;\n }\n\n this.app.debug(`RemoteRuntime: Connecting SSH to ${this.host.uri}...`);\n\n const sshConnectOpts: NodeSSHConfig = {\n host: this.host.hostname, // Changed from this.host.host\n username: this.host.user || this.app.defaultSshUser(), // Assuming defaultSshUser on App\n port: this.host.port, // node-ssh parses port from host string if present\n privateKey: await this.host.plaintextSshKeyPath(),\n password: await this.host.decryptedPassword(),\n };\n\n try {\n if (!this.sshSession.isConnected()) {\n await this.sshSession.connect(sshConnectOpts);\n this.app.debug(`RemoteRuntime: SSH connected to ${this.host.uri}`);\n }\n\n this.app.debug(`RemoteRuntime: Requesting SFTP client for ${this.host.uri}`);\n this.sftpClientInstance = await this.sshSession.sftp();\n this.app.debug(`RemoteRuntime: SFTP client ready for ${this.host.uri}`);\n } catch (e: any) {\n this.app.error(`RemoteRuntime: SSH connection or SFTP setup to ${this.host.uri} failed: ${e.message}`);\n if (this.sshSession.isConnected()) {\n await this.sshSession.disconnect().catch((err: Error) => {\n this.app.error(`RemoteRuntime: Error during disconnect after failed connect/sftp: ${err.message}`);\n });\n }\n this.sftpClientInstance = undefined; // Clear sftp client on error\n throw e;\n }\n\n return this.sshSession.isConnected();\n }\n\n async getSftpClient(): Promise<any> {\n // Replace 'any' with actual SFTP client type (e.g., from 'node-ssh')\n await this.connect(); // Ensures connection and SFTP client are active and ready\n if (!this.sftpClientInstance) {\n // This should ideally be caught by connect(), but as a safeguard\n throw new Error(`SFTP client not available on SSHSession for ${this.host.uri} after connect call.`);\n }\n return this.sftpClientInstance;\n }\n\n async executeCommand(\n command: string | string[],\n options?: {\n cwd?: string;\n stdin?: string | Buffer;\n pty?: boolean;\n env?: Record<string, string>;\n interactionHandler?: InteractionHandler;\n },\n ): Promise<Command | Error> {\n this.app.debug(`RemoteRuntime: Executing on ${this.host.uri}: ${command}`);\n\n const handlerToUse = options?.interactionHandler || this.interactionHandler;\n let cmdOrErr: Command | Error;\n\n try {\n if (options?.pty || handlerToUse !== this.interactionHandler) {\n this.app.debug(`RemoteRuntime: Executing command on ${this.host.uri} via sshSession.run (PTY/custom handler)`);\n const commandObj: Command = await this.sshSession.run(command, handlerToUse, {\n cwd: options?.cwd,\n stdin: options?.stdin,\n pty: options?.pty,\n env: options?.env,\n });\n cmdOrErr = commandObj;\n } else {\n this.app.debug(\n `RemoteRuntime: Executing command on ${this.host.uri} via sshSession.execCommand (no PTY/default handler)`,\n );\n const actualCommand = Array.isArray(command) ? command.join(' ') : command;\n const commandObj: Command = await this.sshSession.execCommand(actualCommand, {\n cwd: options?.cwd,\n stdin: options?.stdin,\n env: options?.env,\n });\n cmdOrErr = commandObj;\n }\n this.app.logHostCommandResult(this.host, command, cmdOrErr);\n } catch (e: any) {\n this.app.error(`RemoteRuntime: executeCommand failed for '${command}': ${e.message}`);\n this.app.error(e.stack);\n cmdOrErr = e;\n this.app.logHostCommandResult(this.host, command, cmdOrErr);\n }\n\n return cmdOrErr;\n }\n\n async disconnect(): Promise<void> {\n if (this.sshSession.isConnected()) {\n this.app.debug(`RemoteRuntime: Disconnecting SSH from ${this.host.uri}`);\n this.sftpClientInstance = undefined; // Clear SFTP client instance\n await this.sshSession.disconnect();\n }\n }\n\n async invokeRootTask<TParams extends TaskParams, TReturn extends RunFnReturnValue>(\n taskFnDefinition: TaskFn<TParams, TReturn>,\n params: TParams,\n ): Promise<IInvocation> {\n await this.connect();\n if (!this.sshSession) throw new Error('SSH session not established for invokeRootTask.');\n\n // RemoteInvocation will use this RemoteRuntime instance for SSH operations\n const rootInvocation = new RemoteInvocation(\n this,\n taskFnDefinition,\n params,\n { runtime: this, host: this.host } as any,\n this.host,\n );\n\n this.app.taskTree.add(\n rootInvocation.id,\n null,\n taskFnDefinition.task.name || `remote_root_task_on_${this.host.hostname}`, // Changed host to hostname\n rootInvocation.result.then((r) => (r === null ? undefined : r)) as Promise<string | Error | undefined>,\n );\n\n const taskContext = this.app.taskContextForRunFn(rootInvocation, params, this.host) as TaskContext<TParams>;\n\n taskFnDefinition.task.runFn\n .call(rootInvocation, taskContext)\n .then(rootInvocation.resolveResult)\n .catch(rootInvocation.rejectResult);\n\n return rootInvocation;\n }\n}\n","import { signalsByName } from 'human-signals';\nimport { NodeSSH, type Config } from 'node-ssh';\nimport { InteractionHandler } from './interaction-handler';\nimport { PassThrough } from 'stream'; // Added for combining stdin\nimport { Command, CommandResult, type Signal } from './command';\n\nexport class SSHSession {\n public ssh: NodeSSH;\n\n constructor() {\n this.ssh = new NodeSSH();\n }\n\n connect(sshConnectOpts: Config): Promise<NodeSSH> {\n return this.ssh.connect(sshConnectOpts);\n }\n\n async deleteFile(remotePath: string) {\n const self = this;\n return new Promise(function (resolve, reject) {\n self.ssh.withSFTP(async (sftp) => {\n sftp.unlink(remotePath, (err: Error | null | undefined) => {\n if (err) {\n // err is Error | null | undefined; if non-null/undefined, it's an Error\n // ENOENT (No such file or directory) often has errno 2 or code 'ENOENT'.\n const errnoError = err as NodeJS.ErrnoException;\n if (errnoError.errno === 2 || errnoError.code === 'ENOENT') {\n resolve(true); // Consider \"file not found\" as success for delete\n } else {\n const errnoError = err as NodeJS.ErrnoException;\n const errorCodeDisplay =\n errnoError.code !== undefined\n ? errnoError.code\n : errnoError.errno !== undefined\n ? errnoError.errno\n : 'N/A';\n reject(`${errnoError.message} (code ${errorCodeDisplay}) ${remotePath}`);\n }\n } else {\n // No error means unlink was successful\n resolve(true);\n }\n });\n });\n });\n }\n\n async sftp() {\n return this.ssh.requestSFTP();\n }\n\n async execCommand(\n command: string,\n options?: { cwd?: string; stdin?: string | Buffer; pty?: boolean | object; env?: Record<string, string> },\n ) {\n // The existing 'run' method is more complex due to InteractionHandler.\n // For execCommand, we'll use a simpler ssh.execCommand which directly returns stdout/stderr.\n // Note: node-ssh's execCommand doesn't directly support 'env' in the same way as exec.\n // We might need to prepend env vars to the command string if 'env' is critical here.\n\n const nodeSshCmdOptions: any = {\n // Using 'any' temporarily to build up, then will cast or ensure type compatibility\n cwd: options?.cwd,\n stdin:\n typeof options?.stdin === 'string'\n ? options.stdin\n : Buffer.isBuffer(options?.stdin)\n ? options.stdin.toString()\n : undefined,\n };\n\n if (options?.pty !== undefined) {\n // pty and other ssh2-specific options go into a nested 'options' object\n nodeSshCmdOptions.options = {\n ...(nodeSshCmdOptions.options || {}), // Preserve other potential ssh2 options if they were there\n pty: options.pty,\n };\n }\n\n const result = await this.ssh.execCommand(command, nodeSshCmdOptions as import('node-ssh').SSHExecCommandOptions);\n const exitCode = result.code === null ? -1 : result.code; // Handle null exit code\n const signalString = result.signal; // string | null\n const signalObject = signalString ? (signalsByName as Record<string, Signal>)[signalString] : undefined;\n\n const commandResult = new CommandResult(result.stdout, result.stderr, exitCode, signalObject);\n\n return new Command({ cmd: command, args: [], cwd: options?.cwd, env: options?.env, result: commandResult });\n }\n\n async getFile(remotePath: string, localPath: string) {\n await this.ssh.getFile(localPath, remotePath);\n }\n\n /**\n * Executes a command on the remote host.\n * @param command The command to execute. Can be a string or an array of strings. If an array, the first element is\n * the command and the rest are arguments. Otherwise, the string is parsed as a command.\n * @param interactionHandler The interaction handler to use.\n * @param execOptions The options for the execution.\n * @returns A promise that resolves to the result of the command.\n */\n async run(\n command: string | string[],\n interactionHandler = new InteractionHandler(),\n execOptions: {\n cwd?: string;\n stdin?: string | Buffer;\n pty?: boolean | object; // pty option from caller\n env?: Record<string, string>;\n } = {},\n ): Promise<Command> {\n // Return type reflects node-ssh's ExecResult extended with cmd and args\n const self = this;\n\n const combinedStdin = new PassThrough();\n if (execOptions.stdin) {\n combinedStdin.write(execOptions.stdin);\n // If it's a one-off stdin, we might want to end this part of the stream,\n // but PassThrough will stay open for interactionHandler's pipe.\n // For simplicity, let interactionHandler control the end of its piped content.\n }\n interactionHandler.setOutputToNewReadable().pipe(combinedStdin);\n\n interactionHandler.begin();\n\n let cmd: string, args: string[];\n if (command instanceof Array) {\n cmd = command[0] || '';\n args = command.slice(1).filter((arg) => !!arg);\n } else {\n // Assuming Command.parse is a static method from hostctl's Command class\n // This might need adjustment if Command is from node-ssh or has a different API\n const parsedCommand = Command.parse(command); // Ensure this Command.parse is what's intended\n cmd = parsedCommand.cmd;\n args = parsedCommand.args;\n }\n\n const ptyOption = execOptions.pty ?? true; // Default to PTY if run is called, as it implies interaction\n\n const { stdout, stderr, code, signal } = await self.ssh.exec(cmd, args, {\n cwd: execOptions.cwd,\n execOptions: { pty: ptyOption, env: execOptions.env },\n stream: 'both',\n stdin: combinedStdin,\n onStdout: (chunk: Buffer) => {\n const output = chunk.toString('utf8');\n interactionHandler.handleInput(output);\n },\n onStderr: (chunk: Buffer) => {\n const errorOutput = chunk.toString('utf8');\n interactionHandler.handleInput(errorOutput); // Send stderr to handler too\n // node-ssh's `exec` still collects stderr for the final result.stderr string\n // so we don't need to explicitly return it from here for collection purposes.\n },\n });\n\n interactionHandler.end();\n\n const signalName = signal as keyof typeof signalsByName | null;\n const signalObj = signalName ? signalsByName[signalName] : undefined;\n const result = new CommandResult(stdout, stderr, code || 0, signalObj);\n\n return new Command({ cmd, args, cwd: execOptions.cwd, env: execOptions.env, result });\n }\n\n async sendFile(localPath: string, remotePath: string): Promise<boolean> {\n try {\n await this.ssh.putFile(localPath, remotePath);\n return true;\n } catch (e) {\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n this.ssh.dispose();\n }\n\n isConnected() {\n return this.ssh.isConnected();\n }\n}\n","import os from 'node:os';\nimport axios, { type AxiosInstance } from 'axios';\nimport * as cheerio from 'cheerio';\nimport { File } from './flex/file';\nimport { A } from './flex/array';\nimport { O } from './flex/object';\nimport { V } from './flex/type';\nimport { match } from 'ts-pattern';\nimport which from 'which';\nimport { downloadFile } from './http';\nimport { ShellCommand } from './shell-command';\nimport { unarchive } from './unarchive';\nimport type { CommandResult } from './command';\nimport type { Path } from './flex/path';\n\nexport class NodeRuntime {\n static Name = 'nodejs';\n\n private client: AxiosInstance;\n private alreadyInstalled: boolean;\n private localNode: Path;\n private localNpm: Path;\n\n constructor(public tmpDir: Path) {\n this.client = axios.create({\n baseURL: 'https://nodejs.org/',\n });\n this.alreadyInstalled = false;\n this.localNode = this.tmpDir.join(NodeRuntime.Name, 'bin', 'node');\n this.localNpm = this.tmpDir.join(NodeRuntime.Name, 'bin', 'npm');\n }\n\n async isNodeInstalledGlobally() {\n const result = await ShellCommand.fromString(`node --version`).run();\n // console.log(`isNodeInstalledGlobally result: ${V.inspect(result.toJSON())}`);\n return result.success;\n }\n\n async isNodeInstalledLocally() {\n const result = await ShellCommand.fromString(`${this.localNode} --version`).run();\n // console.log(`isNodeInstalledLocally result: ${V.inspect(result.toJSON())}`);\n return result.success;\n }\n\n async isNpmInstalledGlobally() {\n const result = await ShellCommand.fromString(`npm --version`).run();\n // console.log(`isNpmInstalledGlobally result: ${V.inspect(result.toJSON())}`);\n return result.success;\n }\n\n async isNpmInstalledLocally() {\n const result = await ShellCommand.fromString(`${this.localNpm} --version`).run();\n // console.log(`isNpmInstalledLocally result: ${V.inspect(result.toJSON())}`);\n // console.log(result.err);\n return result.success;\n }\n\n async nodeCmd() {\n if (await this.isNodeInstalledGlobally()) return 'node';\n\n if (await this.isNodeInstalledLocally()) return this.localNode.toString();\n\n throw new Error('node not installed');\n }\n\n async nodePath(): Promise<string | null> {\n if (await this.isNodeInstalledGlobally()) {\n return await which('node', { nothrow: true });\n }\n\n if (await this.isNodeInstalledLocally()) return this.localNode.toString();\n\n return null;\n }\n\n async npmCmd() {\n if (await this.isNpmInstalledGlobally()) return 'npm';\n\n if (await this.isNpmInstalledLocally()) return this.localNpm.toString();\n\n throw new Error('npm not installed');\n }\n\n async npmPath(): Promise<string | null> {\n if (await this.isNpmInstalledGlobally()) {\n return await which('npm', { nothrow: true });\n }\n\n if (await this.isNpmInstalledLocally()) return this.localNpm.toString();\n\n return null;\n }\n\n async installIfNeeded() {\n if (this.alreadyInstalled || (await this.isNodeInstalledGlobally()) || (await this.isNodeInstalledLocally())) {\n this.alreadyInstalled = true;\n return;\n }\n\n return this.install();\n }\n\n async install() {\n const platform = os.platform();\n const arch = os.arch();\n const packagePath = await this.downloadNodePackage(platform, arch);\n const unzipDir = await this.unzipPackage(packagePath);\n\n this.alreadyInstalled = true;\n\n return unzipDir;\n }\n\n async listPackages(): Promise<string[]> {\n const response = await this.client.get(`/dist/latest/`);\n const doc = await cheerio.load(response.data);\n const allFileLinks = doc('a')\n .map((i, el) => doc(el).attr('href'))\n .toArray();\n const archiveFiles = A(allFileLinks).select((filename: string) => filename.match(/.*\\.(gz|zip|xz)/));\n const urls = A(archiveFiles).map((filename: string) => `https://nodejs.org/dist/latest/${filename}`);\n return urls;\n }\n\n // returns the path to the downloaded zip file\n async downloadNodePackage(platform: string, arch: string): Promise<string> {\n // const url = match([platform, arch])\n // .with([\"linux\", \"x64\"], () => \"https://nodejs.org/dist/v22.4.1/node-v22.4.1-linux-x64.tar.xz\")\n // .with([\"linux\", \"arm\"], () => \"https://nodejs.org/dist/v22.4.1/node-v22.4.1-linux-armv7l.tar.xz\")\n // .with([\"linux\", \"arm64\"], () => \"https://nodejs.org/dist/v22.4.1/node-v22.4.1-linux-arm64.tar.xz\")\n // .with([\"win32\", \"x64\"], () => \"https://nodejs.org/dist/v22.4.1/node-v22.4.1-win-x64.zip\")\n // .with([\"win32\", \"arm64\"], () => \"https://nodejs.org/dist/v22.4.1/node-v22.4.1-win-arm64.zip\")\n // .with([\"darwin\", \"x64\"], () => \"https://nodejs.org/dist/v22.4.1/node-v22.4.1-darwin-x64.tar.gz\")\n // .with([\"darwin\", \"arm64\"], () => \"https://nodejs.org/dist/v22.4.1/node-v22.4.1-darwin-arm64.tar.gz\")\n // .otherwise(() => {\n // throw new Error(`Unable to download node for OS/architecture: ${os}/${arch}`);\n // });\n\n const platformInFilename = match(platform)\n .with('linux', () => 'linux')\n .with('win32', () => 'win')\n .with('darwin', () => 'darwin')\n .otherwise(() => 'unknown-platform');\n\n const archInFilename = match(arch)\n .with('x64', () => 'x64')\n .with('x86', () => 'x86')\n .with('arm', () => 'armv7l')\n .with('arm64', () => 'arm64')\n .otherwise(() => 'unknown-arch');\n\n const packages = await this.listPackages();\n const url = A(packages).find((url: string) => url.match(`node-v.*-${platformInFilename}-${archInFilename}`));\n if (V.isAbsent(url)) {\n throw new Error(`Unable to download node for ${os}/${arch} OS/architecture`);\n }\n\n const filename = File.basename(url);\n const path = this.tmpDir.join(filename);\n\n if (path.exists()) return path.toString();\n\n // console.log(`downloading ${url} to ${path}`);\n return await downloadFile(url, path.toString());\n }\n\n // returns the path to the unzipped package directory\n async unzipPackage(packagePath: string): Promise<string> {\n const dir = this.tmpDir.join(NodeRuntime.Name);\n\n if (dir.exists()) return dir.toString();\n\n // console.log(`unzipping ${packagePath} to ${dir}`);\n await unarchive(packagePath, dir.toString());\n return dir.toString();\n }\n\n async npmInstall(omitDev = true, cwd?: string): Promise<CommandResult> {\n // const result = await ShellCommand.fromString(`bun install --no-save --production`, {}, directory).run();\n // const result = await ShellCommand.fromString(`npm install --omit=dev`, {}, directory).run();\n\n if (omitDev) {\n return this.npm('install --omit=dev', cwd);\n } else {\n return this.npm('install', cwd);\n }\n }\n\n async npm(npmArgs: string, cwd?: string): Promise<CommandResult> {\n const npmCmd = await this.npmCmd();\n\n const env: Record<string, string> = O(process.env).select(([_, v]) => !!v) as Record<string, string>;\n return ShellCommand.fromString(`${npmCmd} ${npmArgs}`.trim(), env, cwd).run();\n }\n\n async node(nodeArgs: string, cwd?: string): Promise<CommandResult> {\n const nodeCmd = await this.nodeCmd();\n\n const env: Record<string, string> = O(process.env).select(([_, v]) => !!v) as Record<string, string>;\n return ShellCommand.fromString(`${nodeCmd} ${nodeArgs}`.trim(), env, cwd).run();\n }\n}\n","import type { PathLike } from 'node:fs';\nimport { createWriteStream, unlink } from 'node:fs';\nimport { get } from 'node:https';\n\nexport async function downloadFile(url: string, dest: PathLike): Promise<string> {\n return new Promise((resolve, reject) => {\n const file = createWriteStream(dest, { flags: 'wx' });\n\n const request = get(url, (response) => {\n if (response.statusCode === 200) {\n response.pipe(file);\n } else {\n file.close();\n unlink(dest, () => {}); // Delete temp file\n reject(`Server responded with ${response.statusCode}: ${response.statusMessage}`);\n }\n });\n\n request.on('error', (err) => {\n file.close();\n unlink(dest, () => {}); // Delete temp file\n reject(err.message);\n });\n\n file.on('finish', () => {\n resolve(dest.toString());\n });\n\n file.on('error', (err: NodeJS.ErrnoException) => {\n file.close();\n\n if (err.code === 'EEXIST') {\n reject(new Error('File already exists'));\n } else {\n unlink(dest, () => {}); // Delete temp file\n reject(err.message);\n }\n });\n });\n}\n","import spawnAsync from '@expo/spawn-async';\n// import { execa, ExecaError, type Result, type ResultPromise } from \"execa\";\nimport { Command, CommandResult } from './command';\nimport { signalsByName, type SignalName } from 'human-signals';\nimport { V } from './flex/type';\n\ninterface SpawnAsyncError extends Error {\n pid?: number;\n stdout?: string;\n stderr?: string;\n status?: number | null;\n signal?: string | null;\n // message and stack are inherited from Error\n}\n\nexport class ShellCommand extends Command {\n static fromString(command: string, env?: Record<string, string>, cwd?: string): ShellCommand {\n const { cmd, args } = this.parse(command, env);\n return new ShellCommand({ cmd, args, cwd, env });\n }\n\n async run(): Promise<CommandResult> {\n try {\n // console.log(V.inspect(this.args));\n // console.log(`(${this.cwd})> ${this.cmd} ${this.args}`);\n const resultPromise = spawnAsync(this.cmd, this.args, {\n cwd: this.cwd,\n env: this.env,\n // shell: true\n });\n\n let { pid, stdout, stderr, status, signal } = await resultPromise;\n\n const signalObj = (signal && signalsByName[signal as SignalName]) || undefined;\n const commandResult = new CommandResult(stdout || '', stderr || '', status || 0, signalObj);\n this.result = commandResult;\n } catch (e: unknown) {\n const error = e as SpawnAsyncError;\n // The error object also has the same properties as the result object (see https://github.com/expo/spawn-async/blob/main/src/spawnAsync.ts#L84)\n // console.log(`---------------------------------`);\n // console.log(`(${this.cwd})> ${this.cmd} ${this.args}`);\n if (error.message) console.error(error.message);\n if (error.stack) console.error(error.stack);\n let { pid, stdout, stderr, status, signal } = error;\n\n const signalObj = (signal && signalsByName[signal as SignalName]) || undefined;\n const commandResult = new CommandResult(stdout || '', stderr || '', status || 1, signalObj);\n this.result = commandResult;\n }\n return this.result;\n }\n}\n","import { File } from './flex/file';\nimport decompress from 'decompress';\nimport decompressTarGzPlugin from 'decompress-targz';\nimport decompressZipPlugin from 'decompress-unzip';\nimport { match, P } from 'ts-pattern';\n\n// these are for the tar.xz decompress functionality\nimport decompressTarPlugin from 'decompress-tar';\nimport { fileTypeFromBuffer } from 'file-type';\nimport { getStreamAsBuffer } from 'get-stream';\nimport xzdecompress from 'xz-decompress';\n\nexport async function unarchive(inputPath: string, outputPath: string): Promise<void> {\n const filename = File.basename(inputPath);\n return await match(filename)\n .with(P.string.regex(/.tar.xz$/), () => decompressTarXz(inputPath, outputPath))\n .with(P.string.regex(/.tar.gz$/), () => decompressTarGz(inputPath, outputPath))\n .with(P.string.regex(/.zip$/), () => decompressZip(inputPath, outputPath))\n .otherwise(() => {\n throw new Error(`unable to decompress unknown file type: ${inputPath}`);\n });\n}\n\nexport async function decompressTarGz(inputPath: string, outputPath: string, dropRootDir = 1) {\n await decompress(inputPath, outputPath, {\n plugins: [decompressTarGzPlugin()],\n strip: dropRootDir,\n });\n}\n\nasync function decompressTarXzPlugin(input: Buffer): Promise<decompress.File[]> {\n const type = await fileTypeFromBuffer(input);\n\n if (!type || type.ext !== 'xz') {\n // Not an XZ file, or unknown type; plugin should return an empty array.\n return [];\n }\n\n // Input is a Buffer and is an XZ file.\n const blob = new Blob([input]);\n const webReadableStream = blob.stream(); // blob.stream() is ReadableStream<Uint8Array>\n const xzStream = new xzdecompress.XzReadableStream(webReadableStream);\n\n // decompressTarPlugin() returns a function that expects a Buffer.\n // getStreamAsBuffer(xzStream) converts the decompressed stream back to a Buffer.\n const decompressedBuffer = await getStreamAsBuffer(xzStream);\n return decompressTarPlugin()(decompressedBuffer);\n}\n\nexport async function decompressTarXz(inputPath: string, outputPath: string, dropRootDir = 1) {\n await decompress(inputPath, outputPath, {\n plugins: [decompressTarXzPlugin],\n strip: dropRootDir,\n });\n}\n\nexport async function decompressZip(inputPath: string, outputPath: string, dropRootDir = 1) {\n await decompress(inputPath, outputPath, {\n plugins: [decompressZipPlugin()],\n strip: dropRootDir,\n });\n}\n","import AdmZip from 'adm-zip';\n\nexport async function zipDirectory(sourceDir: string, outputFilePath: string): Promise<string> {\n const zip = new AdmZip();\n zip.addLocalFolder(sourceDir);\n await zip.writeZipPromise(outputFilePath);\n // console.log(`Zip file created: ${outputFilePath}`);\n return outputFilePath;\n}\n\nexport async function unzipDirectory(inputFilePath: string, outputDirectory: string): Promise<string> {\n const zip = new AdmZip(inputFilePath);\n return new Promise((resolve, reject) => {\n zip.extractAllToAsync(outputDirectory, true, false, (error?: Error) => {\n if (error) {\n // console.log(error);\n reject(error);\n } else {\n // console.log(`Extracted to \"${outputDirectory}\" successfully`);\n resolve(outputDirectory);\n }\n });\n });\n}\n","import { createHash } from 'node:crypto';\n\n/**\n * Returns a SHA256 hash using SHA-2 for the given `content`.\n */\nexport function sha256(str: string): string {\n return createHash('sha256').update(str).digest('hex');\n}\n","import { A } from './flex/array';\nimport { M } from './flex/map';\nimport { VP } from './flex/pipe';\nimport { Str, isNumeric, matches } from './flex/string';\nimport { V } from './flex/type';\nimport { match } from 'ts-pattern';\n\nexport class ParamMap {\n static parse(cliArguments: string[]): ParamMap {\n const root = new ParamMap();\n\n A(cliArguments).each((arg: string) => {\n // Expect tokens like \"key:value\" – only split on the FIRST colon so that\n // values may themselves contain colons (or additional comma-separated data).\n const idx = arg.indexOf(':');\n if (idx === -1) {\n // No colon – treat entire token as key with boolean true (or empty string)\n root.set(arg, 'true');\n return;\n }\n\n const key = arg.slice(0, idx);\n const value = arg.slice(idx + 1);\n root.set(key, value);\n });\n\n return root;\n }\n\n public map: Map<string, string | ParamMap>;\n\n constructor() {\n this.map = new Map();\n }\n\n get(keyPath: string): string | ParamMap | undefined {\n try {\n return A(keyPath.split(':')).reduce(\n (node: Map<string, string | ParamMap> | ParamMap, key: string) => node.get(key),\n this.map,\n );\n } catch (e) {\n return undefined;\n }\n }\n\n set(keyPath: string, value: string | ParamMap) {\n const keyParts = keyPath.split(':');\n const paramMap: ParamMap = A(keyParts)\n .skipLast(1)\n .reduce((node: Map<string, string | ParamMap> | ParamMap, key: string) => {\n let nextNode = node.get(key);\n if (nextNode) return nextNode;\n const newParamMap = new ParamMap();\n node.set(key, newParamMap);\n return newParamMap;\n }, this.map);\n const key = A(keyParts).last(1)[0];\n paramMap.set(key, value);\n }\n\n toObject(): Object {\n let obj: any = {};\n M(this.map).each(([k, v]: [string, string | ParamMap]) => {\n obj[k] = match(v)\n .when(V.isA(String), (str) => this.stringToJsonObj(str))\n .otherwise(() => {\n return (v as ParamMap).toObject();\n });\n });\n return obj;\n }\n\n private stringToJsonObj(str: string) {\n return match(str)\n .when(matches(/(.*,)+/g), (str: string) => {\n return VP(str.split(','))\n .map((s: string) => s.trim())\n .compact([''])\n .map((s: string) => this.stringToJsonObj(s)).value;\n })\n .when(isNumeric, (str: string) => parseFloat(str))\n .otherwise(() => str);\n }\n}\n","export const version = '0.1.34';\n","import { task, type TaskContext, type TaskFn } from '../../runtime';\n\ninterface RunParams {\n taskFn: TaskFn;\n params: any;\n}\n\ntype RunResult = Record<string, any>;\n\nasync function run(context: TaskContext<RunParams>): Promise<RunResult> {\n const { params, ssh } = context;\n const { taskFn, params: taskParams } = params;\n\n // The callback to context.ssh runs on the remote host, receiving its own TaskContext.\n return await ssh([], async (remoteContext: TaskContext<RunParams>) => {\n const hostIdentifier = remoteContext.host?.alias || remoteContext.host?.shortName || 'unknown_remote_host';\n remoteContext.debug(`[${hostIdentifier}] Connected via SSH.`);\n\n try {\n const result = await remoteContext.run(taskFn(taskParams));\n remoteContext.debug(`[${hostIdentifier}] Remote task result:`, JSON.stringify(result));\n return result;\n } catch (e: any) {\n remoteContext.debug(`[${hostIdentifier}] Failed to run remote task:`, e.message);\n return e;\n }\n });\n}\n\nexport default task(run, {\n description: 'run a task on all selected hosts',\n});\n","import { simpleGit, type SimpleGit } from 'simple-git';\nimport filenamify from 'filenamify';\nimport { match } from 'ts-pattern';\nimport { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { unzipDirectory } from '../zip';\nimport { Path } from '../flex/path';\nimport { A } from '../flex/array';\nimport { App } from '../app';\n\n/**\n * Resolves the script reference provided to the `hostctl run` command.\n *\n * This helper centralises the previously in–line logic that lived in\n * `Cli.handleRun`. In addition it adds support for invoking built-in\n * core tasks using dot-notation, e.g. `core.pkg.install` will resolve\n * to `src/core/pkg/install.ts`.\n *\n * @param app The current App instance (for tmpDir access).\n * @param packageOrBundle The first positional arg (package / bundle path or URL).\n * @param scriptRef The second positional arg (script ref) – may be undefined.\n * @param scriptArgs Any additional positional args intended for the script.\n *\n * @returns The resolved absolute script path together with the (possibly\n * mutated) scriptArgs array.\n */\nexport async function resolveScriptPath(\n app: App,\n packageOrBundle: string | null,\n scriptRef: string | undefined,\n scriptArgs: string[],\n): Promise<{ scriptRef: string; scriptArgs: string[] }> {\n // 1. Support built-in core task names like `core.pkg.install`\n if (\n (packageOrBundle && packageOrBundle.startsWith('core.')) ||\n (!packageOrBundle && scriptRef && scriptRef.startsWith('core.'))\n ) {\n const name = packageOrBundle?.startsWith('core.') ? packageOrBundle : (scriptRef as string);\n const relPath = name\n .replace(/^core\\./, '')\n .split('.')\n .join(Path.sep());\n\n // Resolve path relative to current module directory (works under ESM)\n const moduleDir = Path.new(dirname(fileURLToPath(import.meta.url)));\n const coreRoot = moduleDir.parent().join('core');\n const candidate = coreRoot.join(`${relPath}.ts`);\n\n if (!candidate.isFile()) {\n throw new Error(`Core task script not found: ${candidate}`);\n }\n\n // If the core task name came via packageOrBundle, then any token that commander\n // placed into the `scriptRef` positional argument is actually the first script\n // argument. Prepend it back onto the list so that downstream param parsing\n // sees it.\n if (packageOrBundle?.startsWith('core.') && scriptRef) {\n scriptArgs = [scriptRef, ...scriptArgs];\n }\n\n return { scriptRef: candidate.toString(), scriptArgs };\n }\n\n // Existing resolution logic from previous implementation\n if (!packageOrBundle) {\n throw new Error('No bundle or package specified.');\n }\n const currentPackageOrBundle = packageOrBundle; // freeze value for pattern matching\n let resolvedScriptRef = scriptRef ?? '';\n\n await match(currentPackageOrBundle)\n .when(\n (path) => Path.new(path).isFile() && Path.new(path).ext() === '.zip',\n async () => {\n const tmpName = filenamify(currentPackageOrBundle);\n const destPath = app.tmpDir.join(tmpName);\n await unzipDirectory(currentPackageOrBundle, destPath.toString());\n resolvedScriptRef = destPath.resolve(resolvedScriptRef).toString();\n },\n )\n .when(\n (path) => Path.new(path).isDirectory(),\n async () => {\n const tmpName = filenamify(currentPackageOrBundle);\n const destPath = app.tmpDir.join(tmpName);\n const pkgPath = Path.new(currentPackageOrBundle);\n await pkgPath.copy(destPath.toString());\n resolvedScriptRef = destPath.resolve(resolvedScriptRef).toString();\n },\n )\n .when(isValidUrl, async () => {\n const tmpName = filenamify(currentPackageOrBundle);\n const destPath = app.tmpDir.join(tmpName);\n const git: SimpleGit = simpleGit();\n await git.clone(currentPackageOrBundle, destPath.toString());\n resolvedScriptRef = destPath.resolve(resolvedScriptRef).toString();\n })\n .otherwise(async () => {\n if (resolvedScriptRef) {\n // previous behaviour – treat <script> as first arg and push back into args list\n A(scriptArgs).prepend(resolvedScriptRef);\n }\n resolvedScriptRef = currentPackageOrBundle;\n });\n\n return { scriptRef: resolvedScriptRef, scriptArgs };\n}\n\nfunction isValidUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n}\n","#!/usr/bin/env -S npx tsx\n\n// #!/usr/bin/env node\n// #!/usr/bin/env -S npx tsx\n// #!/usr/bin/env -S node --import=tsx/esm\n\nimport { Cli } from '../cli';\n\nconst cli = new Cli();\ncli.program.parseAsync(process.argv).catch((error) => {\n // Minimal top-level error handling for the binary,\n // more detailed errors should be handled within Cli/App.\n console.error('Unhandled error in hostctl binary:', error);\n process.exit(1);\n});\n"],"mappings":";;;AAAA,OAAOA,cAAa;AACpB,YAAY,UAAU;;;ACDtB,OAAOC,cAAa;AACpB,YAAYC,SAAQ;AACpB,SAAS,WAAAC,gBAAe;;;ACFxB,OAAO,gBAAgB;AAGvB,WAAW,eAAe,QAAQ,SAAU,OAAO,OAAO;AACxD,MAAI,YAAY,MAAM,KAAK,aAAa,KACtC,QAAQ,MAAM,KAAK,SAAS,GAC5B,MAAM,QAAQ,MAAM,SAAS,GAC7B,MAAM,MAAM,KAAK,OAAO,KACxB,MAAM;AAER,MAAI,MAAM,IAAK,OAAM;AAErB,MAAI,eAAe,OAAO,OAAO;AAC/B,aAAS,IAAI,OAAO,IAAI,KAAK,KAAK;AAChC,UAAI,IAAI,MAAO,QAAO;AACtB,UAAI,aAAa,OAAO,MAAM,CAAC,EAAG,QAAO,MAAM,CAAC;AAAA,UAC3C,QAAO,MAAM,MAAM,CAAC,CAAC;AAAA,IAC5B;AACA,WAAO;AAAA,EACT,OAAO;AACL,WAAO,CAAC,EAAE,OAAO,KAAK,EAAE,MAAM,OAAO,GAAG,EAAE,KAAK,SAAS;AAAA,EAC1D;AACF,CAAC;;;ACtBD,YAAYC,SAAQ;;;ACApB,OAAO,SAAS;AAChB,OAAe;AACf,SAAe,YAAAC,iBAAkD;AACjE,SAAyC,cAAc;AACvD,OAAmB;AACnB,OAAO,UAAU;;;ACLV,IAAM,oBAAoB,aAAa;AAAC,EAAE;AA2C1C,IAAM,YAAN,MAAgB;AAAA,EAC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M;AACzD,UAAM,KAAK,IAAI,WAAW,gBAAgB;AAE1C,UAAM,YAAY,KAAK,QAAQ,KAAK;AACpC,SAAK,IAAI,aAAa,SAAS;AAC/B,QAAI,KAAK,MAAM;AACb,WAAK,IAAI,eAAe,MAAM;AAAA,IAChC,OAAO;AACL,WAAK,IAAI,eAAe,OAAO;AAAA,IACjC;AACA,QAAI,YAAsB,CAAC;AAC3B,QAAI,OAAO,KAAK,QAAQ,UAAU;AAChC,kBAAY,CAAC,KAAK,GAAG;AAAA,IACvB,WAAW,MAAM,QAAQ,KAAK,GAAG,GAAG;AAClC,kBAAY,KAAK;AAAA,IACnB;AACA,SAAK,IAAI,gBAAgB,SAAS;AAAA,EACpC;AAAA,EAEA,MAAM,MAAM;AACV,QAAI;AACF,YAAM,KAAK,QAAQ,WAAWE,SAAQ,IAAI;AAAA,IAC5C,SAAS,GAAG;AACV,eAAS,kBAAkB,CAAC;AAAA,IAC9B;AAAA,EACF;AAAA,EAEA,MAAM,cAAc,SAA8B,KAAmB;AACnE,UAAM,OAAO,IAAI,gBAAgB;AACjC,UAAM,KAAK,QAAQ,IAAI;AAEvB,UAAM,KAAK,IAAI,mBAAmB;AAAA,EACpC;AAAA,EAEA,MAAM,qBAAqB,SAA8B,KAAmB;AAC1E,UAAM,OAAO,IAAI,gBAAgB;AACjC,UAAM,KAAK,QAAQ,IAAI;AAEvB,UAAM,KAAK,IAAI,eAAe;AAAA,EAChC;AACF;;;AsD9WA,IAAM,MAAM,IAAI,IAAI;AACpB,IAAI,QAAQ,WAAW,QAAQ,IAAI,EAAE,MAAM,CAAC,UAAU;AAGpD,UAAQ,MAAM,sCAAsC,KAAK;AACzD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["process","process","fs","homedir","fs","globSync","each","map","select","each","keys","map","select","values","isEmpty","matches","path","compact","each","isEmpty","map","values","select","A","each","isEmpty","map","A","process","readFile","existsSync","readFileSync","win32","posix","path","existsSync","win32","posix","readFileSync","readFile","path","process","A","fs","path","fs","path","identity","fs","SecretValue","Secret","A","ConfigFile","path","globSync","ConfigFile","matches","util","chalk","Mutex","A","Mutex","Handlebars","fs","StringBuilder","StringBuilder","chalk","Handlebars","path","chalk","ConfigFile","Handlebars","errnoError","Handlebars","command","os","match","spawnAsync","signalsByName","spawnAsync","signalsByName","match","P","platform","os","A","match","url","path","zip","match","A","key","str","Mutex","match","Mutex","task","process","homedir","chalk","A","cmd","match","isError","ConfigFile","identity","invocation","path","match","match","path","A","isError","isValidUrl","path","process"]}
|