hostctl 0.1.32 → 0.1.35

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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../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/cli.ts","../src/version.ts","../src/cli/run-resolver.ts","../src/zip.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/hash.ts","../src/param-map.ts","../src/core/remote/runAllRemote.ts","../src/core/echo.ts","../src/core/whoami.ts","../src/core/dir/index.ts","../src/core/dir/exists.ts","../src/core/file/chmod.ts","../src/core/file/chown.ts","../src/core/file/copy.ts","../src/core/dir/copy.ts","../src/core/dir/create.ts","../src/core/file/index.ts","../src/core/file/chgrp.ts","../src/core/file/exists.ts","../src/core/file/touch.ts","../src/core/file/delete.ts","../src/core/file/link.ts","../src/keyboard.ts","../src/core/file/edit.ts","../src/core/file/grep.ts","../src/core/git/index.ts","../src/core/git/clone.ts","../src/core/git/pull.ts","../src/core/git/checkout.ts","../src/core/group/index.ts","../src/core/group/exists.ts","../src/core/group/create.ts","../src/core/group/delete.ts","../src/core/group/list.ts","../src/core/group/modify.ts","../src/core/host/index.ts","../src/core/host/hostname.ts","../src/core/host/os.ts","../src/core/host/info.ts","../src/core/host/summary.ts","../src/core/pkg/index.ts","../src/core/pkg/install/arch.ts","../src/core/system/reboot_needed.ts","../src/core/pkg/install/debian.ts","../src/core/pkg/install/fedora.ts","../src/core/pkg/install/index.ts","../src/core/pkg/install.ts","../src/core/pkg/remove/arch.ts","../src/core/pkg/remove/debian.ts","../src/core/pkg/remove/fedora.ts","../src/core/pkg/remove/index.ts","../src/core/pkg/remove.ts","../src/core/pkg/update/arch.ts","../src/core/pkg/update/debian.ts","../src/core/pkg/update/fedora.ts","../src/core/pkg/update/index.ts","../src/core/pkg/update.ts","../src/core/pkg/info.ts","../src/core/pkg/is_installed.ts","../src/core/k3s/index.ts","../src/core/k3s/k3sup-install.ts","../src/core/ssh/index.ts","../src/core/ssh/copy_id.ts","../src/core/user/exists.ts","../src/core/user/home_dir.ts","../src/core/user/get_username.ts","../src/core/sudoers/index.ts","../src/core/sudoers/check.ts","../src/core/sudoers/grant-nopasswd.ts","../src/core/system/index.ts","../src/core/system/reboot.ts","../src/core/system/shutdown.ts","../src/core/system/reboot_if_needed.ts","../src/core/systemd/index.ts","../src/core/systemd/disable.ts","../src/core/systemd/enable.ts","../src/core/systemd/restart.ts","../src/core/systemd/start.ts","../src/core/systemd/stop.ts","../src/core/systemd/reload.ts","../src/core/systemd/status.ts","../src/core/template/index.ts","../src/core/template/write.ts","../src/core/ufw/index.ts","../src/core/ufw/deny.ts","../src/core/ufw/disable.ts","../src/core/ufw/enable.ts","../src/core/ufw/install.ts","../src/core/ufw/reload.ts","../src/core/user/index.ts","../src/core/user/add_groups.ts","../src/core/user/create.ts","../src/core/user/get_gid.ts","../src/core/user/get_groups.ts","../src/core/user/get_uid.ts","../src/core/user/set_groups.ts","../src/core/user/set_shell.ts","../src/core/user/delete.ts","../src/core/user/modify.ts","../src/core/index.ts"],"sourcesContent":["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","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","export const version = '0.1.32';\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","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","// 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 { 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","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 { task, type TaskContext, type LogLevel } from '../runtime';\nimport { Verbosity } from '../app'; // Verbosity is in app\n\nexport type EchoParams = {\n args: string[];\n};\n\nexport interface EchoResult {\n stdout: string;\n}\n\n/**\n * Echoes the provided arguments.\n * @param {EchoParams} params - Parameters for the echo operation, containing an array of strings.\n * @returns {Promise<EchoResult>} - The result of the echo operation, containing the stdout.\n */\nasync function run(context: TaskContext<EchoParams>): Promise<EchoResult> {\n const { params, exec, log } = context;\n const { args = [] } = params; // Default to empty array if args is not provided\n\n // Log the arguments being echoed for debugging purposes.\n // Note: If args can contain sensitive information, consider logging strategy.\n log(Verbosity.DEBUG as LogLevel, `Echoing arguments: ${args.join(' ')}`);\n\n // Pass arguments as an array to exec. Manual quoting is not needed here.\n const commandArray = ['echo', ...args];\n const { stdout } = await exec(commandArray);\n\n return {\n stdout,\n };\n}\n\nexport default task(run, { name: 'core.echo', description: 'Echo.' });\n","import { task, type TaskContext } from '../runtime';\n\n// Define an empty params interface as this task doesn't take direct parameters\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface WhoamiParams {}\n\nexport interface WhoamiResult {\n user: string; // The username of the current user\n}\n\n/**\n * Gets the username of the current user by executing the 'whoami' command.\n * @param {TaskContext<WhoamiParams>} context - The task context (no parameters needed for this task).\n * @returns {Promise<WhoamiResult>} - An object containing the username.\n */\nasync function run(context: TaskContext<WhoamiParams>): Promise<WhoamiResult> {\n const { exec } = context;\n // Execute 'whoami' command. Pass command and args as an array.\n const { stdout } = await exec(['whoami']);\n return {\n user: stdout.trim(), // Trim whitespace from the output\n };\n}\n\nexport default task(run, { name: 'core.whoami', description: 'Whoami.' });\n","export { default as exists } from './exists';\nexport { default as copy } from './copy';\nexport { default as create } from './create';\n","import { task, type TaskContext } from '../../runtime';\n\ninterface DirExistsParams {\n path: string;\n}\n\ninterface DirExistsResult {\n exists: boolean;\n}\n\n/**\n * @param {path: string} params\n * @returns {\n * exists: boolean\n * }\n */\nasync function run(context: TaskContext<DirExistsParams>): Promise<DirExistsResult> {\n const { params, exec } = context;\n const { path } = params;\n\n // Check if directory exists using test command\n const command = ['test', '-d', path].join(' ');\n\n const { success: exists } = await exec(command);\n\n return {\n exists,\n };\n}\n\nexport default task(run, { name: 'core.dir.exists', description: 'Dir exists.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface ChmodParams {\n path: string;\n mode: string | number;\n recursive?: boolean;\n sudo?: boolean;\n}\n\nexport interface ChmodResult {\n success: boolean;\n error?: string;\n}\n\n/**\n * Changes the permissions mode of a file or directory.\n * @param {ChmodParams} params - Parameters for the chmod operation.\n * @returns {Promise<ChmodResult>} - The result of the chmod operation.\n */\nasync function run(context: TaskContext<ChmodParams>): Promise<ChmodResult> {\n const { params, exec } = context;\n const { path, mode, recursive = false, sudo = false } = params;\n\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('chmod');\n if (recursive) {\n commandArray.push('-R');\n }\n commandArray.push(String(mode));\n commandArray.push(path);\n\n try {\n const { success, stdout, stderr } = await exec(commandArray, { sudo });\n\n if (!success) {\n return {\n success: false,\n error: `${stdout}\\n${stderr}`,\n };\n }\n\n return {\n success: true,\n };\n } catch (error: any) {\n return {\n success: false,\n error: error.message,\n };\n }\n}\n\nexport default task(run, { name: 'core.file.chmod', description: 'Chmod.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface ChownParams {\n path: string;\n owner: string;\n group?: string;\n recursive?: boolean;\n sudo?: boolean;\n}\n\nexport interface ChownResult {\n success: boolean;\n error?: string;\n}\n\n/**\n * Changes the ownership of a file or directory.\n * @param {ChownParams} params - Parameters for the chown operation.\n * @returns {Promise<ChownResult>} - The result of the chown operation.\n */\nasync function run(context: TaskContext<ChownParams>): Promise<ChownResult> {\n const { params, exec } = context;\n const { path, owner, group, recursive = false, sudo = true } = params;\n\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('chown');\n if (recursive) {\n commandArray.push('-R');\n }\n commandArray.push(owner + (group ? `:${group}` : ''));\n commandArray.push(path);\n\n try {\n const { success, stdout, stderr } = await exec(commandArray, { sudo });\n\n if (!success) {\n return {\n success: false,\n error: `${stdout}\\n${stderr}`,\n };\n }\n\n return {\n success: true,\n };\n } catch (error: any) {\n return {\n success: false,\n error: error.message,\n };\n }\n}\n\nexport default task(run, { name: 'core.file.chown', description: 'Change ownership.' });\n","import { task, type TaskContext } from '../../runtime';\nimport chmod from './chmod';\nimport chown from './chown';\n\nexport interface FileCopyParams {\n from: string;\n to: string;\n mode?: string;\n owner?: string;\n group?: string;\n recursive?: boolean;\n sudo?: boolean;\n}\n\nexport interface FileCopyResult {\n success: boolean;\n}\n\n/**\n * @param {from: string, to: string, mode?: string, owner?: string, group?: string, recursive?: boolean, sudo?: boolean} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<FileCopyParams>): Promise<FileCopyResult> {\n const { params, exec, run: runTask } = context;\n const { from, to, mode, owner, group, recursive = false } = params;\n const effectiveSudo = params.sudo ?? !!owner;\n\n const cpCommandArray: string[] = [];\n if (effectiveSudo) {\n cpCommandArray.push('sudo');\n }\n cpCommandArray.push('cp');\n if (recursive) {\n cpCommandArray.push('-r');\n }\n cpCommandArray.push(from, to);\n\n const { success: cpSuccess } = await exec(cpCommandArray, { sudo: effectiveSudo });\n\n let chmodSuccess = true;\n if (mode && cpSuccess) {\n const chmodResult = await runTask(\n chmod({\n path: to,\n mode,\n sudo: effectiveSudo, // Original logic: sudo for chmod is based on owner presence\n }),\n );\n chmodSuccess = chmodResult.success;\n }\n\n let chownSuccess = true;\n if (owner && cpSuccess) {\n // Original logic: chown task uses its internal sudo default if not specified.\n const chownResult = await runTask(\n chown({\n path: to,\n owner,\n group,\n // sudo is intentionally omitted to use chown's default sudo behavior\n }),\n );\n chownSuccess = chownResult.success;\n }\n\n return {\n success: cpSuccess && chmodSuccess && chownSuccess,\n };\n}\n\nexport default task(run, { name: 'core.file.copy', description: 'Copy a file or directory.' });\n","import { task, type TaskContext } from '../../runtime';\nimport exists from './exists';\nimport fileCopy from '../file/copy';\n\ninterface DirCopyParams {\n from: string;\n to: string;\n mode?: string;\n owner?: string;\n group?: string;\n sudo?: boolean;\n}\n\ninterface DirCopyResult {\n success: boolean;\n}\n\n/**\n * @param {from: string, to: string, mode?: string, owner?: string, group?: string, sudo?: boolean} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<DirCopyParams>): Promise<DirCopyResult> {\n const { params, run: runTask } = context;\n const { from, to, mode, owner, group, sudo = false } = params;\n\n // First check if source directory exists\n const dirExistsResult = await runTask(exists({ path: from }));\n if (!dirExistsResult.exists) {\n return { success: false };\n }\n\n // Copy directory using file copy with recursive flag\n // Assuming fileCopy will be refactored to accept TaskContext compatible params\n // and return a result object with a success property.\n const copyResult = await runTask(\n fileCopy({\n from,\n to,\n mode,\n owner,\n group,\n recursive: true,\n sudo,\n }),\n );\n\n return {\n success: copyResult?.success ?? false, // Adapt if fileCopy's result structure differs\n };\n}\n\nexport default task(run, { name: 'core.dir.copy', description: 'Dir copy.' });\n","import { task, type TaskContext } from '../../runtime';\nimport chmod from '../file/chmod';\n\ninterface DirCreateParams {\n path: string;\n mode?: string;\n owner?: string;\n}\n\ninterface DirCreateResult {\n success: boolean;\n}\n\n/**\n * @param {path: string, mode?: string, owner?: string} params\n * @returns {\n * success: boolean\n * }\n */\nasync function runFn(context: TaskContext<DirCreateParams>): Promise<DirCreateResult> {\n const { params, exec, run } = context;\n const { path, mode, owner } = params;\n\n // Create directory with mkdir\n const commandParts = [];\n if (owner) {\n commandParts.push(`sudo -u ${owner}`);\n }\n commandParts.push('mkdir', '-p', path);\n const command = commandParts.filter(Boolean).join(' ');\n\n const { success: mkdirSuccess } = await exec(command);\n\n // Set mode if specified\n let chmodSuccess = true;\n if (mode && mkdirSuccess) {\n // Assuming chmod task is refactored to accept TaskContext compatible params\n // and returns a result object with a success property.\n const chmodResult = await run(chmod({ path, mode, sudo: !!owner }));\n chmodSuccess = chmodResult?.success ?? false;\n }\n\n return {\n success: mkdirSuccess && chmodSuccess,\n };\n}\n\nexport default task(runFn, { name: 'core.dir.create', description: 'Dir create.' });\n","import chown, { type ChownParams, type ChownResult } from './chown';\nimport chgrp, { type ChgrpParams, type ChgrpResult } from './chgrp';\nimport chmod, { type ChmodParams, type ChmodResult } from './chmod';\nimport copy, { type FileCopyParams, type FileCopyResult } from './copy';\nimport exists, { type FileExistsParams, type FileExistsResult } from './exists';\nimport touch, { type FileTouchParams, type FileTouchResult } from './touch';\nimport deleteFn, { type FileDeleteParams, type FileDeleteResult } from './delete';\nimport link, { type FileLinkParams, type FileLinkResult } from './link';\nimport editFile, { type FileEditParams, type FileEditResult } from './edit';\nimport grep, { type FileGrepParams, type FileGrepResult } from './grep';\n\nexport {\n chown,\n type ChownParams,\n type ChownResult,\n chgrp,\n type ChgrpParams,\n type ChgrpResult,\n chmod,\n type ChmodParams,\n type ChmodResult,\n copy,\n type FileCopyParams,\n type FileCopyResult,\n exists,\n type FileExistsParams,\n type FileExistsResult,\n touch,\n type FileTouchParams,\n type FileTouchResult,\n editFile as edit,\n type FileEditParams,\n type FileEditResult,\n link,\n type FileLinkParams,\n type FileLinkResult,\n deleteFn as delete,\n type FileDeleteParams,\n type FileDeleteResult,\n grep,\n type FileGrepParams,\n type FileGrepResult,\n};\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface ChgrpParams {\n path: string;\n group: string;\n recursive?: boolean;\n sudo?: boolean;\n}\n\nexport interface ChgrpResult {\n success: boolean;\n error?: string;\n}\n\n/**\n * Changes the group ownership of a file or directory.\n * @param {ChgrpParams} params - Parameters for the chgrp operation.\n * @returns {Promise<ChgrpResult>} - The result of the chgrp operation.\n */\nasync function run(context: TaskContext<ChgrpParams>): Promise<ChgrpResult> {\n const { params, exec } = context;\n const { path, group, recursive = false, sudo = true } = params;\n\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('chgrp');\n if (recursive) {\n commandArray.push('-R');\n }\n commandArray.push(group);\n commandArray.push(path);\n\n try {\n const { success, stdout, stderr } = await exec(commandArray, { sudo });\n\n if (!success) {\n return {\n success: false,\n error: `${stdout}\\n${stderr}`,\n };\n }\n\n return {\n success: true,\n };\n } catch (error: any) {\n return {\n success: false,\n error: error.message,\n };\n }\n}\n\nexport default task(run, { name: 'core.file.chgrp', description: 'Chgrp.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface FileExistsParams {\n path: string;\n}\n\nexport interface FileExistsResult {\n exists: boolean;\n}\n\n/**\n * @param {path: string} params\n * @returns {\n * exists: boolean\n * }\n */\nasync function run(context: TaskContext<FileExistsParams>): Promise<FileExistsResult> {\n const { params, exec } = context;\n const { path } = params;\n\n const { success: exists } = await exec(['test', '-f', path]);\n\n return {\n exists,\n };\n}\n\nexport default task(run, { name: 'core.file.exists', description: 'File exists.' });\n","import { task, type TaskContext } from '../../runtime';\nimport chmod from './chmod';\n\nexport interface FileTouchParams {\n file: string;\n mode?: string;\n owner?: string;\n}\n\nexport interface FileTouchResult {\n success: boolean;\n}\n\n/**\n * @param {file: string, mode?: string, owner?: string} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<FileTouchParams>): Promise<FileTouchResult> {\n const { params, exec, run: runTask } = context;\n const { file, mode, owner } = params;\n\n const touchCommandArray: string[] = [];\n if (owner) {\n touchCommandArray.push('sudo', '-u', owner);\n }\n touchCommandArray.push('touch', file);\n\n const { success: touchSuccess } = await exec(touchCommandArray);\n\n let chmodSuccess = true;\n if (mode && touchSuccess) {\n const chmodResult = await runTask(\n chmod({\n path: file,\n mode,\n sudo: !!owner, // Original logic: sudo for chmod is based on owner presence\n }),\n );\n chmodSuccess = chmodResult?.success ?? false;\n }\n\n return {\n success: touchSuccess && chmodSuccess,\n };\n}\n\nexport default task(run, { name: 'core.file.touch', description: 'Touches a file on the system.' });\n","import { task, type TaskContext } from '../../runtime';\nimport { Path } from '../../flex/path';\n\nexport interface FileDeleteParams {\n path: string;\n recursive?: boolean;\n force?: boolean;\n}\n\nexport interface FileDeleteResult {\n success: boolean;\n}\n\nasync function run(context: TaskContext<FileDeleteParams>): Promise<FileDeleteResult> {\n const { params, exec } = context;\n const { path, recursive = false, force = false } = params;\n const p = Path.new(path);\n\n if (!(await p.exists())) {\n return {\n success: true,\n };\n }\n\n const args: string[] = [];\n if (recursive) {\n args.push('-r');\n }\n // The 'force' flag for rm is for ignoring nonexistent files and overriding permissions.\n // We handle non-existence above. The permission override is a useful side-effect.\n if (force) {\n args.push('-f');\n }\n args.push('--'); // End of options, ensures paths starting with '-' are not treated as options.\n args.push(path);\n\n const { success } = await exec(['rm', ...args]);\n\n return {\n success,\n };\n}\n\nexport default task(run, { name: 'core.file.delete', description: 'File delete.' });\n","import { task, type TaskContext } from '../../runtime';\nimport { dirname } from 'path';\n\nexport interface FileLinkParams {\n /** Path the symlink should point TO (target). */\n target: string;\n /** Path of the symlink itself. */\n link: string;\n /** Overwrite existing link/file if necessary (default true) */\n force?: boolean;\n /** Use sudo when creating/modifying (default false) */\n sudo?: boolean;\n}\n\nexport interface FileLinkResult {\n changed: boolean;\n success: boolean;\n}\n\n/**\n * Ensures a symbolic link exists at `link` pointing to `target`.\n * If link already exists with correct target, this is a no-op.\n */\nasync function run(context: TaskContext<FileLinkParams>): Promise<FileLinkResult> {\n const { params, exec } = context;\n const { target, link, force = true, sudo = false } = params;\n\n // Check existing symlink\n const { stdout: statOut, success: statOk } = await exec(\n ['readlink', '-f', link],\n );\n\n if (statOk && statOut.trim() === target) {\n return { changed: false, success: true };\n }\n\n // Ensure parent directory exists\n const parentDir = dirname(link);\n await exec(['mkdir', '-p', parentDir], { sudo });\n\n const cmd = [sudo ? 'sudo' : '', 'ln', '-s', force ? '-f' : '', target, link].filter(Boolean);\n const { success } = await exec(cmd);\n return { changed: true, success };\n}\n\nexport default task(run, {\n name: 'core.file.link',\n description: 'Ensures a symbolic link exists pointing to a target.'\n});\n","import os from 'os';\n\nexport const KeySequence = {\n EOL: os.EOL,\n CRLF: '\\r\\n',\n CR: '\\r',\n LF: '\\n',\n NEWLINE: '\\n',\n CTRL_C: '\\x03',\n CTRL_D: '\\x04',\n};\n","import { KeySequence } from '../../keyboard';\nimport { task, type TaskContext } from '../../runtime';\nimport { dirname } from 'path';\nimport type { FileGrepResult } from './grep';\nimport grep from './grep';\n\nexport interface FileEditParams {\n file: string;\n state?: 'present' | 'absent';\n backup?: boolean;\n sudo?: boolean;\n\n // append-mode\n append?: string;\n\n // line-mode\n line?: string;\n regex?: string;\n after?: string;\n before?: string;\n\n // block-mode\n block?: string; // use \\n for newlines\n marker_begin?: string; // default markers\n marker_end?: string;\n}\n\nexport interface FileEditResult {\n changed: boolean;\n success: boolean;\n}\n\nfunction escapeForSed(str: string): string {\n return str.replace(/[\\\\/\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n}\n\nasync function ensureFile(context: TaskContext<any>, file: string, sudo: boolean) {\n const { exec } = context;\n await exec(['mkdir', '-p', dirname(file)], { sudo });\n await exec(['touch', file], { sudo });\n}\n\n/**\n * Edits a file.\n *\n * File editing is done in one of two modes:\n *\n * 1. **Append Mode**: If `append` is defined, the task will append the given content to the end of the file.\n * 2. **Line/Block Mode**: If `line` or `block` is defined, the task will modify the file contents using the provided parameters.\n *\n * In Line/Block mode, the following rules apply:\n *\n * - If `line` is defined, the task will search for the first occurrence of the line and remove it.\n * If `regex` is defined, the task will search for the first occurrence of the line that matches the regex and remove it.\n * If `after` is defined, the task will insert the line after the first occurrence of the line that matches the regex.\n * If `before` is defined, the task will insert the line before the first occurrence of the line that matches the regex.\n * - If `block` is defined, the task will replace the first occurrence of the block marker with the new block content.\n * The block marker is defined by `marker_begin` and `marker_end` (default: `# BEGIN HOSTCTL BLOCK` and `# END HOSTCTL BLOCK`).\n *\n * The `state` parameter determines whether the file should exist or not. If `state === 'absent'`, the task will delete the file.\n * If `state === 'present'`, the task will ensure the file exists and has the correct contents.\n *\n * The `backup` parameter determines whether to create a backup of the file before modifying it.\n *\n * === Usage examples ===\n *\n * 1. Append a line (idempotent; no duplicates)\n * hostctl run core.file.edit file:/etc/profile line:\"export EDITOR=vim\"\n *\n * 2. Always append raw text to end of file\n * hostctl run core.file.edit file:/etc/profile append:\"export EDITOR=vim\"\n *\n * 3. Insert a line AFTER an anchor\n * hostctl run core.file.edit file:/etc/sshd_config \\\n * line:\"PermitRootLogin no\" after:\"# Authentication:\"\n *\n * 4. Insert a line BEFORE an anchor\n * hostctl run core.file.edit file:/etc/ssh/sshd_config \\\n * line:\"Match User root\" before:\"Subsystem sftp\"\n *\n * 5. Replace the first line matching a regex\n * hostctl run core.file.edit file:/etc/default/app \\\n * regex:\"^PORT=\" line:\"PORT=8080\"\n *\n * 6. Ensure a multi-line block is present\n * hostctl run core.file.edit file:/etc/my.conf \\\n * block:\"alpha\\\\nbeta\" marker_begin:\"# BEGIN MY\" marker_end:\"# END MY\"\n *\n * 7. Remove that block\n * hostctl run core.file.edit file:/etc/my.conf \\\n * block:\"alpha\\\\nbeta\" marker_begin:\"# BEGIN MY\" marker_end:\"# END MY\" state:absent\n */\nasync function runFn(context: TaskContext<FileEditParams>): Promise<FileEditResult> {\n const { params, exec, info, run } = context;\n const {\n file,\n state = 'present',\n backup = false,\n sudo = false,\n append,\n line,\n regex,\n after,\n before,\n block,\n marker_begin = '# BEGIN HOSTCTL BLOCK',\n marker_end = '# END HOSTCTL BLOCK',\n } = params;\n\n const backupPath = backup ? `${file}.bak` : null;\n\n if (state === 'present') {\n await ensureFile(context, file, sudo);\n }\n\n const sudoPrefix = sudo ? ['sudo'] : [];\n\n // append-mode\n if (append !== undefined) {\n const stdin = `${append}${KeySequence.NEWLINE}${KeySequence.CTRL_D}`;\n const { success } = await exec(['tee', '-a', file], { sudo, stdin });\n return { changed: true, success };\n }\n\n // block-mode if block defined\n if (block !== undefined) {\n const beginEsc = escapeForSed(marker_begin);\n const endEsc = escapeForSed(marker_end);\n const body = block.replace(/\\\\n/g, '\\n');\n\n const { success: exists } = await exec(['grep', '-Fxq', marker_begin, file]);\n\n if (state === 'absent') {\n if (!exists) return { changed: false, success: true };\n const sedExpr = `/${beginEsc}/,/${endEsc}/d`;\n const { success } = await exec([...sudoPrefix, 'sed', '-i', '-e', sedExpr, file], { sudo });\n return { changed: true, success };\n }\n\n // state === 'present'\n const fullBlock = `${marker_begin}\\n${body}\\n${marker_end}`;\n\n if (exists) {\n const sedGetBlock = `sed -n '/${beginEsc}/,/${endEsc}/p' \"${file}\"`;\n const currentBlockResult = await exec(['sh', '-c', sedGetBlock]);\n // Normalize line endings for comparison\n if (currentBlockResult.stdout.trim().replace(/\\r\\n/g, '\\n') === fullBlock) {\n return { changed: false, success: true };\n }\n // Block exists but content is different, so remove it before adding the new one\n const sedExpr = `/${beginEsc}/,/${endEsc}/d`;\n await exec([...sudoPrefix, 'sed', '-i', '-e', sedExpr, file], { sudo });\n }\n\n // To append, we use a temp file to avoid quoting issues\n const tempFile = `/tmp/hostctl-block-${Date.now()}`;\n await exec([...sudoPrefix, 'sh', '-c', `printf '%s' \"$1\" > \"$2\"`, '_', fullBlock, tempFile], { sudo });\n\n const script = `\n # Add a newline if file is not empty and does not end with a newline\n if [ -s \\\"$2\\\" ] && [ \\\"$(tail -c 1 <\\\"$2\\\")\\\" ]; then\n printf '\\\\n' >> \\\"$2\\\";\n fi;\n # Append the content of the temp file\n cat \\\"$1\\\" >> \\\"$2\\\";\n `;\n const { success } = await exec([...sudoPrefix, 'sh', '-c', script, '_', tempFile, file], { sudo });\n\n // Clean up the temp file\n await exec([...sudoPrefix, 'rm', tempFile], { sudo });\n\n return { changed: true, success };\n }\n\n const effectiveAfter = after;\n const effectiveBefore = before;\n\n // line / regex mode\n if (line !== undefined || regex !== undefined) {\n if (state === 'present') {\n if (!line) {\n info('`line` parameter is required for state: present');\n return { changed: false, success: false };\n }\n\n const grepResult: FileGrepResult = await context.run(\n grep({\n file,\n pattern: line,\n }),\n );\n\n if (regex) {\n const { found: regexExists } = await context.run(\n grep({\n file,\n pattern: regex,\n }),\n );\n if (regexExists && !grepResult.found) {\n const escapedLine = line.replace(/\\\\/g, '\\\\\\\\').replace(/[&/]/g, '\\\\$&');\n const sedCmd = `sed -i -e '/${regex}/c\\\\${escapedLine}' \"${file}\"`;\n info(`Running sed command: ${sedCmd}`);\n const result = await exec([...sudoPrefix, 'sh', '-c', sedCmd], { sudo });\n if (!result.success) {\n info(`sed command failed. stderr: ${result.stderr}`);\n }\n return { changed: true, success: result.success };\n }\n }\n\n if (grepResult.found) {\n return { changed: false, success: true };\n }\n\n const escapedLineForSed = line.replace(/\\\\/g, '\\\\\\\\').replace(/[&/]/g, '\\\\$&');\n if (effectiveBefore) {\n const beforeEsc = escapeForSed(effectiveBefore);\n const insertCmd = `sed -i -e '/${beforeEsc}/i ${escapedLineForSed}' \"${file}\"`;\n info(`Running sed command: ${insertCmd}`);\n const result = await exec([...sudoPrefix, 'sh', '-c', insertCmd], { sudo });\n if (!result.success) {\n info(`sed command failed. stderr: ${result.stderr}`);\n }\n return { changed: true, success: result.success };\n } else if (effectiveAfter) {\n const afterEsc = escapeForSed(effectiveAfter);\n const insertCmd = `sed -i -e '/${afterEsc}/a ${escapedLineForSed}' \"${file}\"`;\n info(`Running sed command: ${insertCmd}`);\n const result = await exec([...sudoPrefix, 'sh', '-c', insertCmd], { sudo });\n if (!result.success) {\n info(`sed command failed. stderr: ${result.stderr}`);\n }\n return { changed: true, success: result.success };\n } else {\n // No specific insertion point provided; append the line to the end of the file\n const stdin = `${line}${KeySequence.NEWLINE}${KeySequence.CTRL_D}`;\n info(`Appending line with tee: '${line}'`);\n const result = await exec([...sudoPrefix, 'tee', '-a', file], { sudo, stdin });\n if (!result.success) {\n info(`tee command failed. stderr: ${result.stderr}`);\n }\n return { changed: true, success: result.success };\n }\n } else {\n // state === 'absent'\n const searchPattern = regex ?? (line ? escapeForSed(line) : null);\n if (!searchPattern) return { changed: false, success: true };\n\n const { success: exists } = await exec([...sudoPrefix, 'grep', '-Eq', searchPattern, file]);\n if (!exists) return { changed: false, success: true };\n\n const sedExpr = `/${searchPattern}/d`;\n info(`Running sed command: sed -i -e '${sedExpr}' ${file}`);\n const result = await exec([...sudoPrefix, 'sed', '-i', '-e', sedExpr, file], { sudo });\n if (!result.success) {\n info(`sed command failed. stderr: ${result.stderr}`);\n }\n return { changed: true, success: result.success };\n }\n }\n\n return { changed: false, success: true };\n}\n\nexport default task(runFn, {\n name: 'core.file.edit',\n description: 'Edit files: ensure lines/blocks present or absent with optional regex matching.',\n});\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface FileGrepParams {\n /** Path to the file to search */\n file: string;\n /** Pattern to search for (POSIX extended regex passed to grep -E) */\n pattern: string;\n /** If true, perform a case-insensitive match (adds -i flag). Default: false */\n ignore_case?: boolean;\n /** If true, show only lines that do NOT match (grep -v). Default: false */\n invert_match?: boolean;\n /** Match whole words only (grep -w). Default: false */\n whole_word?: boolean;\n /** Treat pattern as a fixed string, not regex (grep -F). Default: false */\n fixed_string?: boolean;\n /** Include line numbers in output (grep -n). Default: false */\n line_numbers?: boolean;\n /** Lines of context before each match (grep -B) */\n before_context?: number;\n /** Lines of context after each match (grep -A) */\n after_context?: number;\n /** Lines of context before & after (grep -C) */\n context?: number;\n /** Stop reading after NUM matching lines (grep -m) */\n max_count?: number;\n /** Return the matching lines in the result payload. Default: false */\n return_lines?: boolean;\n}\n\nexport interface FileGrepResult {\n /** True if one or more matches were found */\n found: boolean;\n /** Number of matching lines */\n count: number;\n /** Matching lines (included only when return_lines=true) */\n lines?: string[];\n}\n\n/**\n * Searches a file for a pattern using `grep` and reports whether it was found and the number of matches.\n *\n * Equivalent shell command:\n * grep -E -c PATTERN FILE\n *\n * If no matches are found, `count` will be 0 and `found` will be false.\n */\nasync function run(context: TaskContext<FileGrepParams>): Promise<FileGrepResult> {\n const { params, exec } = context;\n const {\n file,\n pattern,\n ignore_case = false,\n invert_match = false,\n whole_word = false,\n fixed_string = false,\n line_numbers = false,\n before_context,\n after_context,\n context: contextLines,\n max_count,\n return_lines = false,\n } = params;\n\n const grepArgs: string[] = ['grep'];\n\n // Choose regex type flags\n if (fixed_string) {\n grepArgs.push('-F');\n } else {\n grepArgs.push('-E');\n }\n\n // Counting vs content output\n const needContent = return_lines || line_numbers || before_context !== undefined || after_context !== undefined || contextLines !== undefined;\n if (!needContent) {\n grepArgs.push('-c');\n }\n\n if (ignore_case) grepArgs.push('-i');\n if (invert_match) grepArgs.push('-v');\n if (whole_word) grepArgs.push('-w');\n if (line_numbers) grepArgs.push('-n');\n if (contextLines !== undefined) grepArgs.push('-C', String(contextLines));\n if (before_context !== undefined) grepArgs.push('-B', String(before_context));\n if (after_context !== undefined) grepArgs.push('-A', String(after_context));\n if (max_count !== undefined) grepArgs.push('-m', String(max_count));\n\n grepArgs.push(pattern, file);\n\n const { success, stdout } = await exec(grepArgs);\n\n if (!needContent) {\n // stdout is a count string (may be empty if no matches)\n const count = stdout ? parseInt(stdout.trim(), 10) : 0;\n return { found: success, count };\n }\n\n const lines = stdout\n ? stdout.trim().split('\\n').map((l) => l.replace(/\\r$/, '')).filter((l) => l.length > 0)\n : [];\n return {\n found: success,\n count: lines.length,\n lines: return_lines ? lines : undefined,\n };\n}\n\nexport default task<FileGrepParams, FileGrepResult>(run, {\n name: 'core.file.grep',\n description: 'Search for a pattern in a file and return presence and count.',\n});\n","import clone, { type GitCloneParams, type GitCloneResult } from './clone';\nimport pull, { type GitPullParams, type GitPullResult } from './pull';\nimport checkout, { type GitCheckoutParams, type GitCheckoutResult } from './checkout';\n\nexport {\n clone,\n type GitCloneParams,\n type GitCloneResult,\n pull,\n type GitPullParams,\n type GitPullResult,\n checkout,\n type GitCheckoutParams,\n type GitCheckoutResult,\n};\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GitCloneParams {\n repo: string;\n dir: string;\n}\n\nexport interface GitCloneResult {\n success: boolean;\n}\n\n/**\n * @param {repo: string, dir: string} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<GitCloneParams>): Promise<GitCloneResult> {\n const { params, exec } = context;\n const { repo, dir } = params;\n\n // Build the git clone command\n const commandArray = ['git', 'clone', repo, dir];\n\n const { success } = await exec(commandArray);\n\n return {\n success,\n };\n}\n\nexport default task(run, { name: 'core.git.clone', description: 'Git clone.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GitPullParams {\n /** The directory of the git repository on the host. */\n directory: string;\n /** Optional: Whether to use --rebase. Defaults to false. */\n rebase?: boolean;\n /** Optional: The remote to pull from. Defaults to 'origin'. */\n remote?: string;\n /** Optional: The branch to pull. Defaults to the current branch. */\n branch?: string;\n}\n\nexport interface GitPullResult {\n /** Indicates whether the pull operation was successful. */\n success: boolean;\n /** Error message if the pull operation failed. */\n error?: string;\n}\n\n/**\n * Pulls the latest changes for a git repository.\n */\nasync function run(context: TaskContext<GitPullParams>): Promise<GitPullResult> {\n const { params, exec } = context;\n const { directory, rebase = false, remote = 'origin', branch } = params;\n\n const command = ['git', '-C', directory, 'pull'];\n if (rebase) {\n command.push('--rebase');\n }\n command.push(remote);\n if (branch) {\n command.push(branch);\n }\n\n try {\n const { success } = await exec(command);\n return { success };\n } catch (error: any) {\n return {\n success: false,\n error: error.message,\n };\n }\n}\n\nexport default task(run, { name: 'core.git.pull', description: 'Git pull.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GitCheckoutParams {\n /** The directory of the git repository on the host. */\n directory: string;\n /** The branch, tag, or commit hash to checkout. */\n target: string;\n /** Optional: If true, creates a new branch named <target> before checking out. Defaults to false. */\n new_branch?: boolean;\n}\n\nexport interface GitCheckoutResult {\n /** Indicates whether the checkout operation was successful. */\n success: boolean;\n /** Error message if the checkout operation failed. */\n error?: string;\n}\n\n/**\n * Checks out a specific branch, tag, or commit in a git repository.\n */\nasync function run(context: TaskContext<GitCheckoutParams>): Promise<GitCheckoutResult> {\n const { params, exec } = context;\n const { directory, target, new_branch: newBranch = false } = params;\n\n const command = ['git', '-C', directory, 'checkout'];\n\n if (newBranch) {\n command.push('-b');\n }\n command.push(target);\n\n try {\n const { success } = await exec(command);\n return { success };\n } catch (error: any) {\n return {\n success: false,\n error: error.message,\n };\n }\n}\n\nexport default task(run, { name: 'core.git.checkout', description: 'Git checkout.' });\n","import create, { type GroupCreateParams, type GroupCreateResult } from './create';\nimport del, { type GroupDeleteParams, type GroupDeleteResult } from './delete';\nimport exists, { type GroupExistsParams, type GroupExistsResult } from './exists';\nimport list, { type GroupListParams, type GroupListResult, type GroupInfo } from './list';\nimport modify, { type GroupModifyParams, type GroupModifyResult } from './modify';\n\nexport {\n create,\n del as delete,\n exists,\n list,\n modify,\n type GroupCreateParams,\n type GroupCreateResult,\n type GroupDeleteParams,\n type GroupDeleteResult,\n type GroupExistsParams,\n type GroupExistsResult,\n type GroupListParams,\n type GroupListResult,\n type GroupInfo,\n type GroupModifyParams,\n type GroupModifyResult,\n};\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GroupExistsParams {\n group: string;\n}\n\nexport interface GroupExistsResult {\n exists: boolean;\n}\n\n/**\n * @param {group: string} params\n * @returns {\n * exists: boolean\n * }\n */\nasync function run(context: TaskContext<GroupExistsParams>): Promise<GroupExistsResult> {\n const { params, exec } = context;\n const { group } = params;\n\n // Check if group exists using getent\n const commandArray = ['getent', 'group', group];\n\n const { success: exists } = await exec(commandArray);\n\n return {\n exists,\n };\n}\n\nexport default task(run, { name: 'core.group.exists', description: 'Group exists.' });\n","import { task, type TaskContext } from '../../runtime';\nimport exists from './exists';\n\nexport interface GroupCreateParams {\n group: string;\n /** Whether to run the command with sudo. Defaults to true. */\n sudo?: boolean;\n}\n\nexport interface GroupCreateResult {\n success: boolean;\n}\n\n/**\n * @param {group: string} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<GroupCreateParams>): Promise<GroupCreateResult> {\n const { params, run: runTask, exec } = context;\n const { group, sudo = true } = params;\n\n // First check if group exists\n const groupExistsResult = await runTask(exists({ group }));\n\n // If group already exists, return success\n if (groupExistsResult.exists) {\n return { success: true };\n }\n\n // Create the group using groupadd\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('groupadd', group);\n\n const { success } = await exec(commandArray, { sudo });\n\n return {\n success,\n };\n}\n\nexport default task(run, { name: 'core.group.create', description: 'Creates a user group on the system.' });\n","import { type TaskContext, task } from '../../runtime';\n\nexport interface GroupDeleteParams {\n group: string;\n /** Whether to run the command with sudo. Defaults to true. */\n sudo?: boolean;\n}\n\nexport interface GroupDeleteResult {\n success: boolean;\n error?: string;\n}\n\nasync function run(context: TaskContext<GroupDeleteParams>): Promise<GroupDeleteResult> {\n const { params, exec } = context;\n const { group, sudo = true } = params;\n\n const command: string[] = [];\n if (sudo) {\n command.push('sudo');\n }\n command.push('groupdel', group);\n\n const result = await exec(command, { sudo });\n\n if (result.success) {\n return { success: true };\n }\n\n // `groupdel` returns 6 if group doesn't exist. Treat as success for idempotency.\n if (result.exitCode === 6) {\n return { success: true };\n }\n\n return { success: false, error: [result.stdout, result.stderr].join('\\n') };\n}\n\nexport default task(run, { name: 'core.group.delete', description: 'Deletes a user group from the system.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GroupInfo {\n name: string;\n gid: number;\n}\n\nexport interface GroupListParams {}\n\nexport interface GroupListResult {\n success: boolean;\n groups: GroupInfo[];\n}\n\n/**\n * Lists all user groups on the system.\n * @returns { success: boolean, groups: { name: string, gid: number }[] }\n */\nasync function run(context: TaskContext<GroupListParams>): Promise<GroupListResult> {\n const { exec } = context;\n\n const { stdout, success } = await exec('getent group');\n\n if (!success) {\n return { success: false, groups: [] };\n }\n\n const groups = stdout\n .split('\\n')\n .filter((line) => line.includes(':')) // Ensure the line has the expected format before parsing\n .map((line) => {\n const [name, , gid] = line.split(':');\n // Add a check for valid parsed data\n if (name && gid) {\n return { name, gid: parseInt(gid, 10) };\n }\n return null;\n })\n .filter((g): g is GroupInfo => g !== null && !isNaN(g.gid)); // Filter out nulls and ensure GID is a number\n\n return { success: true, groups };\n}\n\nexport default task(run, {\n name: 'core.group.list',\n description: 'Lists user groups on the system, including their GID.',\n});\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GroupModifyParams {\n /** The current name of the group. */\n group: string;\n /** The new name for the group. */\n new_name?: string;\n /** The new numerical value of the group's ID. */\n gid?: number;\n /** Whether to run the command with sudo. Defaults to true. */\n sudo?: boolean;\n}\n\nexport interface GroupModifyResult {\n success: boolean;\n changed: boolean;\n error?: string;\n}\n\nasync function run(context: TaskContext<GroupModifyParams>): Promise<GroupModifyResult> {\n const { params, exec } = context;\n const { group, new_name, gid, sudo = true } = params;\n\n if (gid) {\n const command = ['groupmod', '-g', String(gid), group];\n if (sudo) {\n command.unshift('sudo');\n }\n const { success, stdout, stderr } = await exec(command, { sudo });\n if (!success) {\n return { success: false, changed: false, error: [stdout, stderr].join('\\n') };\n }\n return { success: true, changed: true };\n }\n\n if (new_name) {\n const command = ['groupmod', '-n', new_name, group];\n if (sudo) {\n command.unshift('sudo');\n }\n const { success, stdout, stderr } = await exec(command, { sudo });\n if (!success) {\n return { success: false, changed: false, error: [stdout, stderr].join('\\n') };\n }\n return { success: true, changed: true };\n }\n\n return { success: true, changed: false };\n}\n\nexport default task(run, {\n name: 'core.group.modify',\n description: 'Modify a user group on the system.',\n});\n","export * from './types';\nexport { default as info, type HostInfoResult } from './info';\nexport { default as summary, type HostSummaryResult } from './summary';\nexport { default as os, type OsDetailsResult } from './os';\nexport { default as hostname, type HostnameResult, type HostnameParams } from './hostname';\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface HostnameParams {\n new_name?: string;\n}\n\nexport interface HostnameResult {\n hostname: string;\n updated: boolean;\n}\n\n/**\n * @param {new_name?: string} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<HostnameParams>): Promise<HostnameResult> {\n const { params, exec } = context;\n const { new_name } = params;\n\n if (!new_name) {\n // Get hostname using hostname command\n const { stdout: hostname } = await exec(['hostname']);\n return {\n hostname: hostname.trim(),\n updated: false,\n };\n } else {\n // Set hostname using hostnamectl\n const commandArray = ['sudo', 'hostnamectl', 'set-hostname', new_name];\n\n const { success } = await exec(commandArray);\n\n return {\n hostname: new_name,\n updated: success,\n };\n }\n}\n\nexport default task(run, { name: 'core.host.hostname', description: 'Gets or sets the hostname of the system.' });\n","import { match, P } from 'ts-pattern';\nimport { task, type TaskContext } from '../../runtime';\n\ninterface OsInfo {\n idLike: string;\n id: string;\n version: string;\n}\n\nexport interface OsDetailsResult {\n success: boolean;\n error?: string;\n family: 'bsd' | 'darwin' | 'linux' | 'solaris' | 'windows' | 'unknown';\n /** The general OS type, e.g., 'debian', 'fedora', 'osx'. Derived from ID_LIKE in /etc/os-release for Linux. */\n os: string;\n /** The specific OS variant, e.g., 'ubuntu', 'arch'. Derived from ID in /etc/os-release for Linux. */\n variant: string;\n /** The OS version string. */\n version: string;\n}\n\nasync function getOsReleaseInfo(exec: TaskContext['exec']): Promise<OsInfo> {\n try {\n const { stdout: osRelease } = await exec(['cat', '/etc/os-release']);\n\n const idMatch = osRelease.match(/^ID=(.*?)$/im);\n const idLikeMatch = osRelease.match(/^ID_LIKE=(.*?)$/im);\n const versionIdMatch = osRelease.match(/^VERSION_ID=(.*)$/im);\n const buildIdMatch = osRelease.match(/^BUILD_ID=(.*)$/im); // Some distros like Arch use BUILD_ID\n\n if (idMatch) {\n const id = idMatch[1].trim().replace(/\"/g, '');\n const idLike = idLikeMatch ? idLikeMatch[1].trim().replace(/\"/g, '') : id;\n const version =\n (versionIdMatch && versionIdMatch[1].trim().replace(/\"/g, '')) ||\n (buildIdMatch && buildIdMatch[1].trim().replace(/\"/g, '')) ||\n 'unknown';\n\n return {\n idLike,\n id,\n version,\n };\n }\n\n return {\n idLike: 'unknown',\n id: 'unknown',\n version: 'unknown',\n };\n } catch (error) {\n // If cat /etc/os-release fails or parsing fails, return unknowns\n return {\n idLike: 'unknown',\n id: 'unknown',\n version: 'unknown',\n };\n }\n}\n\n/**\n * Determines the operating system family, specific OS, variant, and version.\n * @returns {OsDetailsResult}\n */\nexport default task(\n async function run(context: TaskContext): Promise<OsDetailsResult> {\n try {\n const { exec } = context;\n const { success: ostypeSuccess, stdout: ostypeOutput, stderr: ostypeStderr } = await exec(['bash', '-c', 'echo $OSTYPE']);\n if (!ostypeSuccess) {\n throw new Error(`Failed to get OSTYPE: ${ostypeStderr}`);\n }\n\n const family = (await match(ostypeOutput.trim().toLowerCase())\n .with(P.string.startsWith('solaris'), () => 'solaris')\n .with(P.string.startsWith('darwin'), () => 'darwin')\n .with(P.string.startsWith('linux'), () => 'linux') // Covers linux-gnu, linux-musl etc.\n .with(P.string.startsWith('bsd'), () => 'bsd')\n .with(P.string.startsWith('freebsd'), () => 'bsd') // $OSTYPE can be 'freebsdX.Y'\n .with(P.string.startsWith('msys'), () => 'windows')\n .with(P.string.startsWith('cygwin'), () => 'windows')\n .with(P.string.startsWith('mingw'), () => 'windows')\n .otherwise(async () => {\n const { stdout: unameOutput } = await exec(['uname']);\n const unameFamily = match(unameOutput.trim().toLowerCase())\n .with(P.string.startsWith('sunos'), () => 'solaris')\n .with(P.string.startsWith('darwin'), () => 'darwin')\n .with(P.string.startsWith('linux'), () => 'linux')\n .with(P.string.startsWith('freebsd'), () => 'bsd')\n .with(P.string.startsWith('openbsd'), () => 'bsd')\n .with(P.string.startsWith('netbsd'), () => 'bsd')\n // Add other uname outputs for Windows if necessary, though $OSTYPE should cover it.\n .otherwise(() => 'unknown') as OsDetailsResult['family'];\n return unameFamily;\n })) as OsDetailsResult['family'];\n\n const [osIdLike, osId, osVersion] = await match(family)\n .with('bsd', async () => {\n // For BSD, try to get version from uname -r\n const { stdout: unameROutput } = await exec(['uname', '-r']);\n return [family, family, unameROutput.trim()];\n })\n .with('darwin', async () => {\n // For Darwin, get product version\n const { stdout: swVersOutput } = await exec(['sw_vers', '-productVersion']);\n return [family, family, swVersOutput.trim()];\n })\n .with('linux', async () => {\n const { idLike, id, version } = await getOsReleaseInfo(exec);\n return [idLike, id, version];\n })\n // Solaris and Windows might need specific commands if /etc/os-release equivalent or $OSTYPE isn't enough\n .with('solaris', async () => {\n const { stdout: unameROutput } = await exec(['uname', '-r']);\n return ['solaris', 'solaris', unameROutput.trim()];\n })\n .with('windows', () => ['windows', 'windows', 'unknown']) // Placeholder, windows version detection is complex\n .otherwise(() => ['unknown', 'unknown', 'unknown']);\n\n return {\n success: true,\n family,\n os: osIdLike.toLowerCase(),\n variant: osId.toLowerCase(),\n version: osVersion,\n };\n } catch (error: any) {\n return {\n success: false,\n error: error.message,\n family: 'unknown',\n os: 'unknown',\n variant: 'unknown',\n version: 'unknown',\n };\n }\n },\n { name: 'core.host.os' },\n);\n","import { task, type TaskContext } from '../../runtime';\nimport { type HostInfo, type LSBRelease } from './types';\nimport getHostname from './hostname';\nimport getOS from './os';\n\nexport interface HostInfoResult {\n host: HostInfo;\n}\n\n/**\n * @returns {\n * host: HostInfo\n * }\n */\nasync function run(context: TaskContext): Promise<HostInfoResult> {\n const { run: runTask, exec } = context;\n\n // Get hostname\n const hostnameResult = await runTask(getHostname({}));\n const name = hostnameResult.hostname;\n\n // Get OS info\n const os = await runTask(getOS({}));\n\n // Get LSB release info\n const { stdout: lsbOutput } = await exec(['lsb_release', '-a']);\n const lsb_release = lsbOutput\n .split('\\n')\n .filter(Boolean)\n .reduce((acc, line) => {\n const [key, ...valueParts] = line.split(':');\n const value = valueParts.join(':').trim();\n // Ensure the keys match LSBRelease interface for type safety\n acc[key.trim() as keyof LSBRelease] = value;\n return acc;\n }, {} as LSBRelease);\n\n // Get CPU info in JSON format\n const { stdout: lscpuOutput } = await exec(['lscpu', '-J']);\n const lscpu = JSON.parse(lscpuOutput).lscpu;\n\n return {\n host: {\n name,\n os: {\n family: os.family,\n base_os: os.family, // Assuming base_os is also the OS family\n os: os.os, // This is the specific OS like 'debian'\n version: os.version,\n },\n lsb_release,\n lscpu,\n },\n };\n}\n\nexport default task(run, { name: 'core.host.info', description: 'Host info.' });\n","import { task, type TaskContext } from '../../runtime';\nimport { type HostSummary } from './types';\nimport info from './info';\n\nexport interface HostSummaryResult {\n host: HostSummary;\n}\n\n/**\n * @returns {\n * host: HostSummary\n * }\n */\nasync function run(context: TaskContext): Promise<HostSummaryResult> {\n const { run: runTask } = context;\n\n // Get full host info\n const infoResult = await runTask(info({}));\n const hostInfo = infoResult.host;\n\n // Extract CPU info from lscpu data\n // Ensure lscpu array and its children are accessed safely\n const cpuModelEntry = hostInfo.lscpu?.find((entry) => entry.field === 'Model name:');\n const cpu = cpuModelEntry?.data ?? hostInfo.lscpu[2]?.children?.[0]?.data ?? 'Unknown';\n\n return {\n host: {\n name: hostInfo.name,\n os: hostInfo.os,\n cpu,\n },\n };\n}\n\nexport default task(run, { name: 'core.host.summary', description: 'Host summary.' });\n","// src/core/pkg/index.ts\nimport install from './install';\nimport remove from './remove';\nimport update from './update';\nimport info from './info';\nimport isInstalled from './is_installed';\n\n// Export types to make them available when 'pkg' module is used\nexport type { PkgInstallParams, PkgInstallResult, PkgRemoveParams, PkgRemoveResult, PkgUpdateParams, PkgUpdateResult, PkgIsInstalledParams, PkgIsInstalledResult } from './types';\nexport type { PkgInfoParams, PkgInfoResult } from './info';\n\n// Export tasks\nexport { install, remove, update, info, isInstalled };\n","import { task, type TaskContext } from '../../../runtime';\nimport type { PkgInstallParams, PkgInstallResult } from '../types';\n\n/**\n * Installs a package using pacman on Arch Linux\n * @param {package: string | string[]} params\n * @returns {PkgInstallResult}\n */\nasync function run(context: TaskContext<PkgInstallParams>): Promise<PkgInstallResult> {\n const { params: taskParams, exec } = context;\n const { package: pkg, sudo = true } = taskParams;\n const packages = Array.isArray(pkg) ? pkg : [pkg];\n const commandArray = [sudo ? 'sudo' : '', 'pacman', '-Syu', '--noconfirm', '--needed', ...packages].filter(Boolean);\n\n const { success, stdout, stderr } = await exec(commandArray, { sudo });\n if (!success) {\n return { success: false, error: `${stdout}\\n${stderr}` };\n }\n return { success };\n}\n\nexport const install = task(run);\n","import { type TaskContext, type LogLevel, task } from '../../runtime';\nimport { Verbosity } from '../../app';\nimport os from '../host/os';\n// Assuming these paths correctly resolve to the index.ts files in their respective directories\nimport { install as installPkgTask, info as pkgInfoTask } from '../pkg';\n\n// Define empty params interface as this task doesn't take direct parameters\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface RebootNeededParams {}\n\nexport interface RebootNeededResult {\n reboot_needed: boolean;\n success: boolean;\n error?: string;\n}\n\n/**\n * Checks if the system needs to be rebooted.\n * It handles Debian/Ubuntu (using needrestart) and Fedora (using dnf-utils/needs-restarting).\n * Required tools (needrestart, dnf-utils) are installed if missing.\n * @returns {Promise<RebootNeededResult>} - An object indicating if a reboot is needed and the success of the check.\n */\nasync function run(\n context: TaskContext<RebootNeededParams>, // Params can be empty\n): Promise<RebootNeededResult> {\n const { run: runTask, exec, log } = context;\n const osDetails = await runTask(os());\n\n if (!osDetails.success) {\n log(Verbosity.ERROR as LogLevel, `Failed to get OS details: ${osDetails.error}`);\n return { reboot_needed: false, success: false, error: `Failed to get OS details: ${osDetails.error}` };\n }\n\n if (typeof osDetails?.os !== 'string' || osDetails.os === 'unknown') {\n const errorMsg = 'Could not determine OS from osDetails.';\n log(Verbosity.ERROR as LogLevel, errorMsg);\n return { reboot_needed: false, success: false, error: errorMsg };\n }\n const baseOs = osDetails.os;\n\n if (baseOs.match(/debian|ubuntu/)) {\n let pkgInfoResult = await runTask(pkgInfoTask({ package: 'needrestart' }));\n if (!pkgInfoResult.success) {\n const errorMsg = `Failed to check if needrestart is installed: ${pkgInfoResult.error}`;\n log(Verbosity.ERROR as LogLevel, errorMsg);\n return { reboot_needed: false, success: false, error: errorMsg };\n }\n if (!pkgInfoResult.installed) {\n log(Verbosity.INFO as LogLevel, 'needrestart package not found, attempting to install.');\n const installResult = await runTask(installPkgTask({ package: 'needrestart' }));\n if (!installResult.success) {\n const errorMsg = `Failed to install needrestart: ${installResult.error}`;\n log(Verbosity.ERROR as LogLevel, errorMsg);\n return { reboot_needed: false, success: false, error: errorMsg };\n }\n log(Verbosity.INFO as LogLevel, 'needrestart installed successfully.');\n }\n\n const { success, stdout, stderr } = await exec(['sudo', 'needrestart', '-b']);\n if (!success) {\n return { reboot_needed: false, success: false, error: `Failed to run needrestart: ${stdout}\\n${stderr}` };\n }\n const rebootIsNeeded = stdout.includes('NEEDRESTART-KSTA: 1');\n return { reboot_needed: rebootIsNeeded, success: true };\n }\n\n if (baseOs === 'fedora') {\n let pkgInfoResult = await runTask(pkgInfoTask({ package: 'dnf-utils' }));\n if (!pkgInfoResult.success) {\n const errorMsg = `Failed to check if dnf-utils is installed: ${pkgInfoResult.error}`;\n log(Verbosity.ERROR as LogLevel, errorMsg);\n return { reboot_needed: false, success: false, error: errorMsg };\n }\n if (!pkgInfoResult.installed) {\n log(Verbosity.INFO as LogLevel, 'dnf-utils package not found, attempting to install.');\n const installResult = await runTask(installPkgTask({ package: 'dnf-utils' }));\n if (!installResult.success) {\n const errorMsg = `Failed to install dnf-utils: ${installResult.error}`;\n log(Verbosity.ERROR as LogLevel, errorMsg);\n return { reboot_needed: false, success: false, error: errorMsg };\n }\n log(Verbosity.INFO as LogLevel, 'dnf-utils installed successfully.');\n }\n\n const { success } = await exec(['needs-restarting']);\n return { reboot_needed: !success, success: true };\n }\n\n log(Verbosity.WARN as LogLevel, `Unsupported OS (${baseOs}) for reboot_needed check.`);\n return { reboot_needed: false, success: true };\n}\n\nexport default task(run, { name: 'core.system.reboot_needed', description: 'Reboot needed.' });\n","import { task, type TaskContext, type LogLevel } from '../../../runtime';\nimport { Verbosity } from '../../../app';\nimport rebootNeeded from '../../system/reboot_needed';\nimport type { PkgInstallParams, PkgInstallResult } from '../types';\n\n/**\n * Installs a package using apt on Debian/Ubuntu\n * @param {package: string | string[]} params\n * @returns {PkgInstallResult}\n */\nasync function run(context: TaskContext<PkgInstallParams>): Promise<PkgInstallResult> {\n const { params: taskParams, exec, run: runTask, debug } = context;\n const { package: pkg, sudo = true } = taskParams;\n const packages = Array.isArray(pkg) ? pkg.join(' ') : pkg;\n\n // DEBIAN_FRONTEND=noninteractive is often set for scripts\n // apt install -yq should handle most cases without interaction\n const commandArray = [\n sudo ? 'sudo' : '',\n 'DEBIAN_FRONTEND=noninteractive',\n 'apt',\n 'install',\n '-yq',\n packages,\n ].filter(Boolean);\n\n const { success, stdout, stderr } = await exec(commandArray.join(' '), { sudo });\n if (!success) {\n const errorMsg = `Failed to install package(s): ${packages}. Error: ${stdout}\\n${stderr}`;\n debug(errorMsg);\n return { success: false, error: errorMsg };\n }\n\n // Restart services that need to be restarted using needrestart\n const needrestartCmd = [sudo ? 'sudo' : '', 'needrestart', '-q', '-r', 'a'].filter(Boolean);\n const needrestartResult = await exec(needrestartCmd.join(' '));\n if (!needrestartResult.success) {\n debug(`needrestart command failed. This might be okay. Error: ${needrestartResult.stdout}\\n${needrestartResult.stderr}`);\n }\n\n // Check if reboot is needed\n const rebootNeededResult = await runTask(rebootNeeded({}));\n if (!rebootNeededResult.success) {\n debug(`Could not determine if reboot is needed: ${rebootNeededResult.error}`);\n } else if (rebootNeededResult.reboot_needed) {\n debug('The system needs to be rebooted after package installation.');\n }\n\n return { success: true };\n}\n\n// Exporting as 'install' to match usage in src/core/pkg/install/index.ts\n// If index.ts is updated to import 'default as installDebian', this can be 'export default task(run, { name: 'core.pkg.install.debian', description: 'Pkg install debian.' });'\nexport const install = task(run);\n","import { task, type TaskContext } from '../../../runtime';\nimport type { PkgInstallParams, PkgInstallResult } from '../types';\n\n/**\n * Installs a package using dnf on Fedora\n * @param {package: string | string[]} params\n * @returns {PkgInstallResult}\n */\nasync function run(context: TaskContext<PkgInstallParams>): Promise<PkgInstallResult> {\n const { params: taskParams, exec } = context;\n const { package: pkg, sudo = true } = taskParams;\n const packages = Array.isArray(pkg) ? pkg : [pkg];\n const commandArray = [sudo ? 'sudo' : '', 'dnf', '-yq', 'install', ...packages].filter(Boolean);\n\n const { success, stdout, stderr } = await exec(commandArray.join(' '), { sudo });\n if (!success) {\n return { success: false, error: `${stdout}\\n${stderr}` };\n }\n return { success };\n}\n\nexport const install = task(run);\n","import { task, type TaskContext } from '../../../runtime';\nimport os from '../../host/os';\nimport { install as installArch } from './arch';\nimport { install as installDebian } from './debian';\nimport { install as installFedora } from './fedora';\nimport type { PkgInstallParams, PkgInstallResult } from '../types';\n\n/**\n * Installs a package using the appropriate package manager by dispatching to OS-specific tasks.\n * @param {package: string | string[]} params\n * @returns {PkgInstallResult}\n */\nasync function run(context: TaskContext<PkgInstallParams>): Promise<PkgInstallResult> {\n const { params: taskParams, run: runTask, error } = context;\n\n const osDetails = await runTask(os());\n\n if (!osDetails.success) {\n const errorMsg = `Failed to determine OS details: ${osDetails.error}`;\n error(errorMsg);\n return { success: false, error: errorMsg };\n }\n if (typeof osDetails?.os !== 'string' || osDetails.os === 'unknown') {\n const errorMsg = `OS details are invalid or 'os' property is missing/not a string.`;\n error(errorMsg);\n return { success: false, error: errorMsg };\n }\n\n const baseOs = osDetails.os;\n\n let installResult: PkgInstallResult;\n\n if (baseOs.match(/arch/)) {\n installResult = await runTask(installArch(taskParams));\n } else if (baseOs.match(/debian|ubuntu/)) {\n installResult = await runTask(installDebian(taskParams));\n } else if (baseOs === 'fedora') {\n installResult = await runTask(installFedora(taskParams));\n } else {\n const errorMsg = `Unsupported OS (${baseOs}) for package installation, or OS not detected.`;\n error(errorMsg);\n return { success: false, error: errorMsg };\n }\n\n if (!installResult.success) {\n const errorMsg = `Package installation failed for OS ${baseOs}: ${installResult.error}`;\n error(errorMsg);\n return { success: false, error: errorMsg };\n }\n\n return installResult;\n}\n\nexport default task(run, {\n name: 'core.pkg.install',\n description: 'Installs a package using the appropriate OS package manager.',\n});\n","import installDispatcherTask from './install/index'; // Imports the default export from ./install/index.ts\n\nexport { type PkgInstallParams, type PkgInstallResult } from './types';\n\nexport default installDispatcherTask;\n","import { task, type TaskContext } from '../../../runtime';\nimport type { PkgRemoveParams, PkgRemoveResult } from '../types';\n\n/**\n * Removes a package using pacman on Arch Linux\n */\nasync function run(context: TaskContext<PkgRemoveParams>): Promise<PkgRemoveResult> {\n const { params: { package: pkg, sudo = true }, exec } = context;\n const packages = Array.isArray(pkg) ? pkg : [pkg];\n const commandArray = [sudo ? 'sudo' : '', 'pacman', '-Rns', '--noconfirm', ...packages].filter(Boolean);\n const { success } = await exec(commandArray.join(' '), { sudo });\n return { success };\n}\n\nexport const remove = task(run, { name: 'core.pkg.remove.arch', description: 'Remove package(s) on Arch Linux.' });\nexport default remove;\n","import { task, type TaskContext } from '../../../runtime';\nimport rebootNeeded from '../../system/reboot_needed';\nimport type { PkgRemoveParams, PkgRemoveResult } from '../types';\n\n/**\n * Removes a package (or packages) using apt on Debian/Ubuntu.\n */\nasync function run(context: TaskContext<PkgRemoveParams>): Promise<PkgRemoveResult> {\n const {\n params: { package: pkg, sudo = true },\n exec,\n run: runTask,\n } = context;\n\n const packages = Array.isArray(pkg) ? pkg.join(' ') : pkg;\n const commandArray = [sudo ? 'sudo' : '', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', '-yq', '--purge', 'remove', packages].filter(Boolean);\n const { success } = await exec(commandArray.join(' '), { sudo });\n if (!success) {\n return { success: false };\n }\n\n // attempt autoremove to clean up dependencies\n await exec([sudo ? 'sudo' : '', 'apt-get', '-yq', 'autoremove'].filter(Boolean).join(' '), { sudo });\n\n // check if reboot needed\n await runTask(rebootNeeded());\n\n return { success: true };\n}\n\nexport const remove = task(run, {\n name: 'core.pkg.remove.debian',\n description: 'Remove package(s) on Debian/Ubuntu.',\n});\n\nexport default remove;\n","import { task, type TaskContext } from '../../../runtime';\nimport type { PkgRemoveParams, PkgRemoveResult } from '../types';\n\n/**\n * Removes a package using dnf on Fedora\n */\nasync function run(context: TaskContext<PkgRemoveParams>): Promise<PkgRemoveResult> {\n const { params: { package: pkg, sudo = true }, exec } = context;\n const packages = Array.isArray(pkg) ? pkg : [pkg];\n const commandArray = [sudo ? 'sudo' : '', 'dnf', '-yq', 'remove', ...packages].filter(Boolean);\n const { success } = await exec(commandArray.join(' '), { sudo });\n return { success };\n}\n\nexport const remove = task(run, { name: 'core.pkg.remove.fedora', description: 'Remove package(s) on Fedora.' });\nexport default remove;\n","import { task, type TaskContext } from '../../../runtime';\nimport os from '../../host/os';\nimport { remove as removeArch } from './arch';\nimport { remove as removeDebian } from './debian';\nimport { remove as removeFedora } from './fedora';\nimport type { PkgRemoveParams, PkgRemoveResult } from '../types';\n\n/**\n * Removes a package using the appropriate package manager by dispatching to OS-specific tasks.\n */\nasync function run(context: TaskContext<PkgRemoveParams>): Promise<PkgRemoveResult> {\n const { params: taskParams, run: runTask, error } = context;\n\n const osDetails = await runTask(os());\n if (osDetails instanceof Error) {\n error(`Failed to determine OS details: ${osDetails.message}`);\n return { success: false };\n }\n if (typeof osDetails?.os !== 'string') {\n error(`OS details are invalid or 'os' property is missing/not a string.`);\n return { success: false };\n }\n\n const baseOs = osDetails.os;\n let removeResult: PkgRemoveResult | Error;\n\n if (baseOs.match(/arch/)) {\n removeResult = await runTask(removeArch(taskParams));\n } else if (baseOs.match(/debian|ubuntu/)) {\n removeResult = await runTask(removeDebian(taskParams));\n } else if (baseOs === 'fedora') {\n removeResult = await runTask(removeFedora(taskParams));\n } else {\n error(`Unsupported OS (${baseOs}) for package removal, or OS not detected.`);\n return { success: false };\n }\n\n if (removeResult instanceof Error) {\n error(`Package removal failed for OS ${baseOs}: ${removeResult.message}`);\n return { success: false };\n }\n\n return removeResult;\n}\n\nexport default task(run, {\n name: 'core.pkg.remove',\n description: 'Removes a package using the appropriate OS package manager.',\n});\n","import removeDispatcherTask from './remove/index';\n\nexport { type PkgRemoveParams, type PkgRemoveResult } from './types';\n\nexport default removeDispatcherTask;\n","import { task, type TaskContext } from '../../../runtime';\nimport type { PkgUpdateParams, PkgUpdateResult } from '../types';\n\n/**\n * Updates system packages on Arch Linux using pacman.\n * If specific package names are passed, only those will be upgraded.\n */\nasync function run(context: TaskContext<PkgUpdateParams>): Promise<PkgUpdateResult> {\n const { params: { package: pkg, sudo = true }, exec } = context;\n\n const commandParts = [sudo ? 'sudo' : '', 'pacman', '-Syu', '--noconfirm'];\n if (pkg && Array.isArray(pkg) && pkg.length) {\n commandParts.push(...pkg);\n }\n\n const { success } = await exec(commandParts.filter(Boolean).join(' '), { sudo });\n return { success };\n}\n\nexport const update = task(run);\n","import { task, type TaskContext } from '../../../runtime';\nimport type { PkgUpdateParams, PkgUpdateResult } from '../types';\n\n/**\n * Updates or upgrades packages on Debian/Ubuntu systems.\n * Behaviour:\n * - no package param -> apt-get update && apt-get (upgrade|dist-upgrade)\n * - package list -> apt-get install --only-upgrade <pkg...>\n */\nasync function run(context: TaskContext<PkgUpdateParams>): Promise<PkgUpdateResult> {\n const { params: { package: pkg, sudo = true, fullUpgrade = false }, exec } = context;\n\n const prefix = sudo ? 'sudo ' : '';\n if (!pkg || (Array.isArray(pkg) && pkg.length === 0)) {\n // System-wide upgrade\n const upgradeCmd = fullUpgrade ? 'apt-get dist-upgrade -y' : 'apt-get upgrade -y';\n const { success: u1 } = await exec(`${prefix}apt-get update`, { sudo });\n if (!u1) return { success: false };\n const { success } = await exec(prefix + upgradeCmd, { sudo });\n return { success };\n }\n\n const packages = Array.isArray(pkg) ? pkg : [pkg];\n const { success } = await exec(`${prefix}apt-get install -y --only-upgrade ${packages.join(' ')}`, { sudo });\n return { success };\n}\n\nexport const update = task(run);\n","import { task, type TaskContext } from '../../../runtime';\nimport type { PkgUpdateParams, PkgUpdateResult } from '../types';\n\n/**\n * Updates packages on Fedora/RHEL-like systems via dnf.\n */\nasync function run(context: TaskContext<PkgUpdateParams>): Promise<PkgUpdateResult> {\n const { params: { package: pkg, sudo = true }, exec } = context;\n\n const prefix = sudo ? 'sudo ' : '';\n\n if (!pkg || (Array.isArray(pkg) && pkg.length === 0)) {\n const { success } = await exec(`${prefix}dnf upgrade -y`, { sudo });\n return { success };\n }\n const packages = Array.isArray(pkg) ? pkg : [pkg];\n const { success } = await exec(`${prefix}dnf upgrade -y ${packages.join(' ')}`, { sudo });\n return { success };\n}\n\nexport const update = task(run);\n","import { task, type TaskContext } from '../../../runtime';\nimport os from '../../host/os';\nimport { update as updateArch } from './arch';\nimport { update as updateDebian } from './debian';\nimport { update as updateFedora } from './fedora';\nimport type { PkgUpdateParams, PkgUpdateResult } from '../types';\n\n/**\n * Dispatcher that selects the correct per-OS implementation at runtime.\n */\nasync function run(context: TaskContext<PkgUpdateParams>): Promise<PkgUpdateResult> {\n const { params: taskParams, run: runTask, error } = context;\n const osDetails = await runTask(os());\n if (osDetails instanceof Error) {\n error(`Failed to determine OS details: ${osDetails.message}`);\n return { success: false };\n }\n const baseOs = String(osDetails?.os ?? '');\n\n let result: PkgUpdateResult | Error;\n if (/arch/.test(baseOs)) {\n result = await runTask(updateArch(taskParams));\n } else if (/debian|ubuntu/.test(baseOs)) {\n result = await runTask(updateDebian(taskParams));\n } else if (baseOs === 'fedora') {\n result = await runTask(updateFedora(taskParams));\n } else {\n error(`Unsupported OS (${baseOs}) for pkg.update`);\n return { success: false };\n }\n\n if (result instanceof Error) {\n error(`pkg.update failed: ${result.message}`);\n return { success: false };\n }\n return result;\n}\n\nexport default task(run, {\n name: 'core.pkg.update',\n description: 'Updates packages using the appropriate OS package manager.',\n});\n","import updateDispatcherTask from './update/index'; // Imports the default export from ./install/index.ts\n\nexport { type PkgUpdateParams, type PkgUpdateResult } from './types';\n\nexport default updateDispatcherTask;\n","import { task, type TaskContext } from '../../runtime';\nimport os from '../host/os';\n\nexport interface PkgInfoParams {\n package: string;\n}\n\nexport interface PkgInfoResult {\n installed: boolean;\n success: boolean;\n error?: string;\n // Potentially add more fields like version, status if needed from parsed output\n}\n\n/**\n * Gets information about a package\n * @param {package: string} params\n * @returns {PkgInfoResult}\n */\nasync function run(context: TaskContext<PkgInfoParams>): Promise<PkgInfoResult> {\n const { params: taskParams, run: runTask, exec, error } = context;\n const osDetails = await runTask(os({}));\n if (!osDetails.success) {\n const errorMsg = `Failed to get OS details for pkg info: ${osDetails.error}`;\n error(errorMsg);\n return { installed: false, success: false, error: errorMsg };\n }\n if (typeof osDetails?.os !== 'string') {\n // Should not happen if not an error\n const errorMsg = `OS details 'os' field is not a string: ${typeof osDetails?.os}`;\n error(errorMsg);\n return { installed: false, success: false, error: errorMsg };\n }\n const baseOs = osDetails.os; // Using the 'os' field which is ID_LIKE (e.g., debian, fedora)\n const { package: pkg } = taskParams;\n\n let commandArray: string[];\n if (baseOs.match(/debian|ubuntu/)) {\n // dpkg returns exit code 0 only when the package is installed\n commandArray = ['dpkg', '-s', pkg];\n } else if (baseOs.match(/fedora|rhel|centos|rocky|alma/)) {\n commandArray = ['rpm', '-q', pkg];\n } else if (baseOs.match(/arch/)) {\n commandArray = ['pacman', '-Qi', pkg];\n } else if (baseOs.match(/alpine/)) {\n commandArray = ['apk', 'info', '-e', pkg];\n } else {\n const errorMsg = `Unsupported operating system for package info: ${baseOs}`;\n error(errorMsg);\n return { installed: false, success: false, error: errorMsg };\n }\n\n try {\n const { success, stdout, stderr } = await exec(commandArray);\n if (success) {\n return { installed: true, success: true };\n }\n\n const output = (stdout + stderr).toLowerCase();\n if (output.includes('not installed') || output.includes('not found')) {\n return { installed: false, success: true };\n }\n\n return { installed: false, success: false, error: `Command failed unexpectedly:\\nstdout: ${stdout}\\nstderr: ${stderr}` };\n } catch (e: any) {\n const output = (e.stdout || '' + e.stderr || '').toLowerCase();\n if (output.includes('not installed') || output.includes('not found')) {\n return { installed: false, success: true };\n }\n return { installed: false, success: false, error: e.message };\n }\n}\n\nexport default task(run, { name: 'core.pkg.info', description: 'Pkg info.' });\n","import { task, type TaskContext } from '../../runtime';\nimport type { PkgIsInstalledParams, PkgIsInstalledResult } from './types';\nimport pkgInfo from './info';\n\n/**\n * Returns true if the given package is installed (wrapper around core.pkg.info).\n */\nasync function run(context: TaskContext<PkgIsInstalledParams>): Promise<PkgIsInstalledResult> {\n const { params, run: runTask } = context;\n const info = await runTask(pkgInfo({ package: params.package }));\n if (info instanceof Error) {\n return { installed: false };\n }\n return { installed: !!info.installed };\n}\n\nexport default task(run, {\n name: 'core.pkg.is_installed',\n description: 'Checks if a package is installed on the system.',\n});\n","import k3supInstall, { type K3supInstallParams, type K3supInstallResult } from './k3sup-install';\n\nexport { k3supInstall, type K3supInstallParams, type K3supInstallResult };\n","import { task, type TaskContext, type LogLevel } from '../../runtime';\nimport { Verbosity } from '../../app';\n\nexport interface K3supInstallParams {\n cluster?: boolean;\n context?: string;\n datastore?: string;\n /** Public hostname of node on which to install k3s (k3sup --host) */\n targetHost?: string;\n /** Public IP of node (k3sup --ip) */\n ip?: string;\n ipsec?: boolean;\n k3sChannel?: string; // default \"stable\"\n k3sExtraArgs?: string;\n k3sVersion?: string;\n local?: boolean;\n localPath?: string; // default \"kubeconfig\"\n merge?: boolean;\n noExtras?: boolean;\n printCommand?: boolean;\n printConfig?: boolean;\n skipInstall?: boolean;\n sshKey?: string; // default \"~/.ssh/id_rsa\"\n sshPort?: number; // default 22\n sudo?: boolean; // default true\n tlsSan?: string;\n token?: string;\n /** Username for SSH login (k3sup --user) */\n user?: string; // default \"root\"\n}\n\nexport interface K3supInstallResult {\n stdout: string;\n stderr: string;\n /** Kubeconfig content if --print-config was used */\n kubeconfig?: string;\n /** The command that would be run if --print-command was used */\n executedCommand?: string;\n}\n\n/**\n * Installs k3s on a target host using k3sup.\n * Assumes k3sup is installed on the machine running hostctl.\n */\nasync function run(context: TaskContext<K3supInstallParams>): Promise<K3supInstallResult> {\n const { params, exec, log, error, debug } = context;\n\n const k3supCmd: string[] = ['k3sup', 'install'];\n\n // Helper to add flag if param is true\n const addFlag = (flag: string, condition?: boolean) => {\n if (condition) {\n k3supCmd.push(flag);\n }\n };\n\n // Helper to add option with value if param is defined\n const addOption = (flag: string, value?: string | number | undefined) => {\n if (value !== undefined) {\n k3supCmd.push(flag, String(value));\n }\n };\n\n addFlag('--cluster', params.cluster);\n addOption('--context', params.context);\n addOption('--datastore', params.datastore);\n addOption('--host', params.targetHost);\n addOption('--ip', params.ip);\n addFlag('--ipsec', params.ipsec);\n addOption('--k3s-channel', params.k3sChannel);\n addOption('--k3s-extra-args', params.k3sExtraArgs);\n addOption('--k3s-version', params.k3sVersion);\n addFlag('--local', params.local);\n addOption('--local-path', params.localPath);\n addFlag('--merge', params.merge);\n addFlag('--no-extras', params.noExtras);\n addFlag('--print-command', params.printCommand);\n addFlag('--print-config', params.printConfig);\n addFlag('--skip-install', params.skipInstall);\n addOption('--ssh-key', params.sshKey);\n addOption('--ssh-port', params.sshPort);\n // --sudo is true by default, only add --sudo=false if params.sudo is explicitly false\n if (params.sudo === false) {\n k3supCmd.push('--sudo=false');\n } else if (params.sudo === true) {\n // k3sup defaults to sudo, so no need to add --sudo or --sudo=true unless k3sup changes its default\n // However, to be explicit if the user sets it true:\n // k3supCmd.push(\"--sudo\"); // or k3supCmd.push(\"--sudo=true\");\n }\n addOption('--tls-san', params.tlsSan);\n addOption('--token', params.token);\n addOption('--user', params.user);\n\n debug(`Executing k3sup command: ${k3supCmd.join(' ')}`);\n\n try {\n const { stdout, stderr, exitCode } = await exec(k3supCmd);\n\n if (exitCode !== 0) {\n error(`k3sup command failed with exit code ${exitCode}. Stderr: ${stderr}`);\n }\n\n const result: K3supInstallResult = {\n stdout,\n stderr,\n executedCommand: params.printCommand ? stdout : k3supCmd.join(' '),\n };\n\n if (params.printConfig) {\n result.kubeconfig = stdout;\n }\n\n return result;\n } catch (e: any) {\n error(`Error executing k3sup command: ${e.message}`);\n throw e; // Re-throw to ensure task failure is propagated\n }\n}\n\nexport default task(run, { name: 'core.k3s.k3sup-install', description: 'K3s k3sup-install.' });\n","export { default as copy_id } from './copy_id';\n","import path from 'node:path';\nimport { task, type TaskContext, type LogLevel } from '../../runtime';\n\n// Child task imports\nimport userExistsTask from '../user/exists';\nimport userHomeDirTask from '../user/home_dir';\nimport dirCreateTask from '../dir/create';\nimport getHostnameTask from '../host/hostname';\nimport getUsernameTask from '../user/get_username';\nimport fileTouchTask from '../file/touch';\n\ninterface CopyIdParams {\n public_key: string;\n user?: string;\n}\n\ninterface CopyIdResult {\n success: boolean;\n}\n\n/**\n * Copies an SSH public key to a specified user's authorized_keys file.\n */\nasync function run(context: TaskContext<CopyIdParams>): Promise<CopyIdResult> {\n const { params, run: runTask, exec, log, info } = context;\n let { public_key, user } = params;\n const publicKeyTrimmed = public_key.trim();\n\n if (!user) {\n const usernameResult = await runTask(getUsernameTask());\n if (usernameResult instanceof Error) {\n info(`Failed to get current username: ${usernameResult.message}`); // ERROR: 3\n return { success: false };\n }\n if (typeof usernameResult?.username !== 'string') {\n info('Could not determine current username from task result.'); // ERROR: 3\n return { success: false };\n }\n user = usernameResult.username;\n }\n\n if (!user) {\n // Should be caught by above, but as a safeguard\n info('User for SSH key copy is undefined.'); // ERROR: 3\n return { success: false };\n }\n\n const userExistsResult = await runTask(userExistsTask({ user }));\n if (userExistsResult instanceof Error) {\n info(`Error checking if user '${user}' exists: ${userExistsResult.message}`); // ERROR: 3\n return { success: false };\n }\n if (!userExistsResult?.exists) {\n const hostnameResult = await runTask(getHostnameTask());\n const hostname =\n hostnameResult instanceof Error || !hostnameResult?.hostname ? 'current host' : hostnameResult.hostname;\n info(`User '${user}' does not exist on ${hostname}. Cannot copy SSH ID.`); // WARN: 2\n return { success: false };\n }\n\n const homeDirResult = await runTask(userHomeDirTask({ user }));\n if (homeDirResult instanceof Error) {\n info(`Error getting home directory for user '${user}': ${homeDirResult.message}`); // ERROR: 3\n return { success: false };\n }\n if (typeof homeDirResult?.path !== 'string') {\n info(`Could not determine home directory path for user '${user}'.`); // ERROR: 3\n return { success: false };\n }\n const userHome = homeDirResult.path;\n const sshDir = path.join(userHome, '.ssh');\n\n const dirCreateResult = await runTask(dirCreateTask({ path: sshDir, mode: '700', owner: user }));\n if (dirCreateResult instanceof Error || !dirCreateResult?.success) {\n info(\n `Failed to create or set permissions for ${sshDir}: ${dirCreateResult instanceof Error ? dirCreateResult.message : 'Task reported failure'}`,\n ); // ERROR: 3\n return { success: false };\n }\n\n const authorizedKeysFile = path.join(sshDir, 'authorized_keys');\n const touchResult = await runTask(fileTouchTask({ file: authorizedKeysFile, mode: '600', owner: user }));\n if (touchResult instanceof Error || !touchResult?.success) {\n info(\n `Failed to touch or set permissions for ${authorizedKeysFile}: ${touchResult instanceof Error ? touchResult.message : 'Task reported failure'}`,\n ); // ERROR: 3\n return { success: false };\n }\n\n const checkKeyCommandParts: string[] = [];\n // No sudo if current user matches target user and no specific user is forced for exec context\n // However, grep might need to read a file owned by another user, so sudo -u is safer.\n checkKeyCommandParts.push('sudo', '-u', user, 'grep', '-xqF', publicKeyTrimmed, authorizedKeysFile);\n\n const checkKeyCmdResult = await exec(checkKeyCommandParts);\n\n if (checkKeyCmdResult.exitCode === 0) {\n info(`SSH key already exists in ${authorizedKeysFile} for user ${user}.`); // INFO: 1\n return { success: true };\n } else if (checkKeyCmdResult.exitCode !== 1) {\n // 1 means not found (which is OK), >1 is an error\n info(`Error checking for existing SSH key: ${checkKeyCmdResult.stderr || checkKeyCmdResult.stdout}`); // ERROR: 3\n return { success: false };\n }\n\n // Key not found (exitCode === 1), proceed to add it.\n const sudoCmd = `sudo -u ${user}`;\n const escapedPublicKey = publicKeyTrimmed.replace(/\"/g, '\\\\\"').replace(/\\$/g, '\\\\\\$').replace(/`/g, '\\\\`');\n const shellCommand = `echo \"${escapedPublicKey}\" | ${sudoCmd} tee -a \"${authorizedKeysFile}\"`;\n\n info(`Attempting to add key with command: sh -c '${shellCommand}'`); // DEBUG: 0\n const addKeyResult = await exec(['sh', '-c', shellCommand]);\n\n if (!addKeyResult.success) {\n info(\n `Failed to add SSH key for user ${user}. Exit code: ${addKeyResult.exitCode}, Error: ${addKeyResult.stderr || addKeyResult.stdout}`,\n ); // ERROR: 3\n }\n\n return {\n success: addKeyResult.success,\n };\n}\n\nexport default task(run, { name: 'core.ssh.copy_id', description: 'Ssh copy id.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface UserExistsParams {\n user: string;\n}\n\nexport interface UserExistsResult {\n exists: boolean;\n}\n\n/**\n * @param {user: string} params\n * @returns {\n * exists: boolean\n * }\n */\nasync function run(context: TaskContext<UserExistsParams>): Promise<UserExistsResult> {\n const { params, exec } = context;\n const { user } = params;\n\n // Check if user exists using id command\n const command = ['id', user].join(' ');\n\n const { success: exists } = await exec(command);\n\n return {\n exists,\n };\n}\n\nexport default task(run, { name: 'core.user.exists', description: 'User exists.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface UserHomeDirParams {\n user: string;\n}\n\nexport interface UserHomeDirResult {\n path: string;\n exists: boolean;\n}\n\n/**\n * @param {user: string} params\n * @returns {\n * path: string\n * exists: boolean\n * }\n */\nasync function run(context: TaskContext<UserHomeDirParams>): Promise<UserHomeDirResult> {\n const { params, exec } = context;\n const { user } = params;\n\n // Get user's home directory using getent\n const getentCommand = ['getent', 'passwd', user].filter(Boolean).join(' ');\n const { success: getentSuccess, stdout } = await exec(getentCommand);\n\n let path = '';\n if (getentSuccess) {\n // Parse home directory from passwd entry (6th field)\n const fields = stdout.split(':');\n path = fields[5]?.trim() || '';\n }\n\n let exists = false;\n if (path) {\n // Check if directory exists\n const testCommand = `test -d ${path}`;\n const { success: dirExistsSuccess } = await exec(testCommand);\n exists = dirExistsSuccess;\n }\n\n return {\n path,\n exists,\n };\n}\n\nexport default task(run, { name: 'core.user.home_dir', description: 'User home dir.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GetUsernameResult {\n success: boolean;\n username: string;\n}\n\n/**\n * @param {} params\n * @returns {\n * success: boolean\n * username: string // Corrected from uid to username in comment\n * }\n */\nasync function run(context: TaskContext<{}>): Promise<GetUsernameResult> {\n const { exec } = context;\n const command = ['id', '-un'].filter(Boolean).join(' ');\n\n const { success, stdout: username } = await exec(command);\n\n return {\n success,\n username: username.trim(),\n };\n}\n\nexport default task(run, { name: 'core.user.get_username', description: 'User get username.' });\n","export { default as check } from './check';\nexport { default as grantNopasswd } from './grant-nopasswd';\n","import { task, type TaskContext } from '../../runtime';\n\ninterface SudoersCheckParams {\n file?: string; // Path to the sudoers file to check. Defaults to /etc/sudoers.\n}\n\nexport interface SudoersCheckResult {\n success: boolean; // True if the sudoers file syntax is valid, false otherwise.\n}\n\n/**\n * Checks the syntax of a sudoers file using 'visudo -cf'.\n * @param {SudoersCheckParams} params - Parameters for the sudoers check operation.\n * @returns {Promise<SudoersCheckResult>} - The result of the syntax check.\n */\nasync function run(context: TaskContext<SudoersCheckParams>): Promise<SudoersCheckResult> {\n const { params, exec } = context;\n const effectiveFile = params.file || '/etc/sudoers';\n\n // Execute 'visudo -cf <file>'. This command typically requires sudo privileges itself.\n const { stdout, success } = await exec(['sudo', 'visudo', '-cf', effectiveFile]);\n\n // 'visudo -cf' on success prints '<file>: parsed OK' to stdout and exits with 0.\n // On failure, it prints an error to stderr and exits non-zero.\n return {\n success: success && stdout.includes(`${effectiveFile}: parsed OK`),\n };\n}\n\nexport default task(run, { name: 'core.sudoers.check', description: 'Sudoers check.' });\n","import { task, type TaskContext, type LogLevel } from '../../runtime';\nimport { Verbosity } from '../../app';\nimport { KeySequence } from '../../keyboard';\n\nexport interface GrantNopasswdParams {\n /** The username to grant passwordless sudo privileges. */\n user: string;\n /** The name of the file to create in /etc/sudoers.d/. Defaults to the username. */\n name?: string;\n}\n\nexport interface GrantNopasswdResult {\n /** True if the operation was successful. */\n success: boolean;\n /** The path to the created sudoers file. */\n filePath: string;\n}\n\n/**\n * Grants a user passwordless sudo privileges by creating a file in /etc/sudoers.d/.\n */\nasync function run(context: TaskContext<GrantNopasswdParams>): Promise<GrantNopasswdResult> {\n const { params, exec, log, error } = context;\n const { user } = params;\n\n if (!user) {\n throw new Error(\"The 'user' parameter is required.\");\n }\n\n const sudoersFileName = params.name || user;\n const sudoersFilePath = `/etc/sudoers.d/${sudoersFileName}`;\n const sudoersContent = `${user} ALL=(ALL) NOPASSWD: ALL${KeySequence.NEWLINE}${KeySequence.CTRL_D}`;\n\n try {\n // Use 'tee' to write the file with sudo privileges.\n // The input to the exec command is piped to stdin of the shell process.\n const writeCmd = await exec(['sudo', 'tee', sudoersFilePath], { stdin: sudoersContent });\n if (!writeCmd.success) {\n error(`Failed to write to ${sudoersFilePath}: ${writeCmd.stderr}`);\n return { success: false, filePath: sudoersFilePath };\n }\n\n // Set the correct permissions for the sudoers file.\n const chmodCmd = await exec(['sudo', 'chmod', '0440', sudoersFilePath]);\n if (!chmodCmd.success) {\n error(`Failed to set permissions on ${sudoersFilePath}: ${chmodCmd.stderr}`);\n return { success: false, filePath: sudoersFilePath };\n }\n\n // Set the correct ownership for the sudoers file.\n const chownCmd = await exec(['sudo', 'chown', 'root:root', sudoersFilePath]);\n if (!chownCmd.success) {\n error(`Failed to set ownership on ${sudoersFilePath}: ${chownCmd.stderr}`);\n return { success: false, filePath: sudoersFilePath };\n }\n\n // Verify the syntax of the new sudoers file.\n const checkCmd = await exec(['sudo', 'visudo', '-cf', sudoersFilePath]);\n if (!checkCmd.success) {\n error(`Syntax check failed for ${sudoersFilePath}: ${checkCmd.stderr}`);\n // Attempt to clean up the invalid file\n await exec(['sudo', 'rm', '-f', sudoersFilePath]);\n return { success: false, filePath: sudoersFilePath };\n }\n\n log(Verbosity.INFO as LogLevel, `Successfully granted passwordless sudo to user '${user}' via ${sudoersFilePath}`);\n return { success: true, filePath: sudoersFilePath };\n } catch (e: any) {\n error(`An unexpected error occurred: ${e.message}`);\n throw e;\n }\n}\n\nexport default task(run, {\n description: 'Grants a user passwordless sudo privileges by creating a file in /etc/sudoers.d/.',\n});\n","import reboot, { type RebootParams, type RebootResult } from './reboot';\nimport shutdown, { type ShutdownParams, type ShutdownResult } from './shutdown';\nimport rebootNeeded, { type RebootNeededParams, type RebootNeededResult } from './reboot_needed';\nimport rebootIfNeeded, { type RebootIfNeededParams, type RebootIfNeededResult } from './reboot_if_needed';\n\nexport {\n reboot,\n type RebootParams,\n type RebootResult,\n shutdown,\n type ShutdownParams,\n type ShutdownResult,\n rebootNeeded,\n type RebootNeededParams,\n type RebootNeededResult,\n rebootIfNeeded,\n type RebootIfNeededParams,\n type RebootIfNeededResult,\n};\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface RebootParams {\n /**\n * A message to broadcast to all users before rebooting.\n */\n message?: string;\n\n /**\n * The time to wait before rebooting. E.g., \"+5\" for 5 minutes, \"now\" for immediately.\n * @default \"now\"\n */\n time?: string;\n\n /**\n * Whether to run the command with sudo. Defaults to true.\n */\n sudo?: boolean;\n}\n\nexport interface RebootResult {\n success: boolean;\n error?: string;\n status: string;\n}\n\n/**\n * Reboots a system.\n */\nasync function run(context: TaskContext<RebootParams>): Promise<RebootResult> {\n const { params, info, warn, exec } = context;\n const time = params.time || 'now';\n const sudo = params.sudo ?? true;\n\n info(`Sending reboot command to host. Time: ${time}`);\n\n const command = [sudo ? 'sudo' : '', 'shutdown', '-r', time, params.message ? `\"${params.message}\"` : ''].filter(\n Boolean,\n );\n\n try {\n const { success, stdout, stderr } = await exec(command, { sudo });\n\n if (success) {\n return {\n success: true,\n status: `Reboot command issued to host. The host will reboot at: ${time}`,\n };\n }\n\n // Command failed but didn't throw. Could be a graceful shutdown signal.\n warn('Reboot command failed without throwing an exception. Assuming success during shutdown.');\n\n return {\n success: true, // As per original logic, treat as success\n status: `Reboot command issued. The host is likely shutting down.`,\n error: `stdout: ${stdout}\\nstderr: ${stderr}`,\n };\n } catch (e: any) {\n // If the exec command fails, it's often because the host has already started shutting down,\n // which can be considered a success for a reboot task.\n warn('Command may have timed out or disconnected, which is expected during a reboot. Assuming success.');\n return {\n success: true,\n status: `Reboot command issued. The host is likely shutting down.`,\n error: e.message,\n };\n }\n}\n\nexport default task(run, {\n description: 'Reboots a system',\n});\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface ShutdownParams {\n /**\n * A message to broadcast to all users before shutting down.\n */\n message?: string;\n\n /**\n * The time to wait before shutting down. E.g., \"+5\" for 5 minutes, \"now\" for immediately.\n * @default \"now\"\n */\n time?: string;\n\n /**\n * Whether to run the command with sudo. Defaults to true.\n */\n sudo?: boolean;\n}\n\nexport interface ShutdownResult {\n success: boolean;\n error?: string;\n status: string;\n}\n\n/**\n * Shuts down a system.\n */\nasync function run(context: TaskContext<ShutdownParams>): Promise<ShutdownResult> {\n const { params, info, warn, exec } = context;\n const time = params.time || 'now';\n const sudo = params.sudo ?? true;\n\n info(`Sending shutdown command to host. Time: ${time}`);\n\n const command = `shutdown -h ${time} ${params.message ? `\"${params.message}\"` : ''}`.trim();\n\n try {\n const { success, stdout, stderr } = await exec(command, { pty: true, sudo });\n\n if (success) {\n info('Shutdown command successfully issued.');\n return {\n success: true,\n status: `Shutdown command issued to host. The host will shut down at: ${time}`,\n };\n }\n\n warn('Shutdown command failed without throwing an exception. Assuming success during shutdown.');\n return {\n success: true, // As per original logic, treat as success\n status: `Shutdown command issued. The host is likely shutting down.`,\n error: `stdout: ${stdout}\\nstderr: ${stderr}`,\n };\n } catch (e: any) {\n // If the exec command fails, it's often because the host has already started shutting down,\n // which can be considered a success for a shutdown task.\n warn('The shutdown command may have disconnected the session, which is expected. Assuming success.');\n return {\n success: true,\n status: `Shutdown command issued to host. The host will shut down at: ${time}`,\n error: e.message,\n };\n }\n}\n\nexport default task(run);\n","import { type TaskContext, type LogLevel, task } from '../../runtime';\nimport { Verbosity } from '../../app';\nimport rebootNeeded from './reboot_needed';\n\nexport interface RebootIfNeededParams {\n delay?: number; // Delay in seconds before rebooting\n message?: string; // Message to log before rebooting\n}\n\nexport interface RebootIfNeededResult {\n rebooting: boolean; // True if a reboot was initiated, false otherwise\n success: boolean;\n error?: string;\n}\n\n/**\n * Reboots the system if a reboot is determined to be needed by the 'reboot_needed' task.\n * @param {RebootIfNeededParams} params - Parameters for the reboot operation, including optional delay and message.\n * @returns {Promise<RebootIfNeededResult>} - An object indicating whether a reboot was initiated.\n */\nasync function run(context: TaskContext<RebootIfNeededParams>): Promise<RebootIfNeededResult> {\n const { params, run: runTask, exec, log } = context;\n const delayInSeconds = Math.max(1, params.delay ?? 1); // Ensure at least 1 second delay\n const message = params.message ?? 'Reboot is required. Initiating reboot sequence.';\n\n // Check if a reboot is needed by running the reboot_needed task\n const rebootCheckResult = await runTask(rebootNeeded());\n\n if (!rebootCheckResult.success) {\n const errorMsg = `Failed to check if reboot is needed: ${rebootCheckResult.error}`;\n log(Verbosity.ERROR as LogLevel, errorMsg);\n return { rebooting: false, success: false, error: errorMsg };\n }\n\n if (!rebootCheckResult.reboot_needed) {\n log(Verbosity.INFO as LogLevel, 'Reboot not needed.');\n return { rebooting: false, success: true };\n }\n\n log(Verbosity.WARN as LogLevel, `${message} System will reboot in ${delayInSeconds} second(s).`);\n\n // Wait for the specified delay\n await new Promise((resolve) => setTimeout(resolve, delayInSeconds * 1000));\n\n // Execute the reboot command\n try {\n const { success, stdout, stderr } = await exec(['sudo', 'reboot']);\n if (!success) {\n // This part might not be reached if reboot is fast, but it's good practice.\n const errorMsg = `Reboot command failed: ${stdout}\\n${stderr}`;\n log(Verbosity.ERROR as LogLevel, errorMsg);\n return { rebooting: false, success: false, error: errorMsg };\n }\n } catch (error: any) {\n // This catch block is for when exec itself throws, e.g., due to connection issues\n log(Verbosity.ERROR as LogLevel, `Reboot command failed to execute: ${error.message}`);\n return { rebooting: false, success: false, error: error.message };\n }\n\n // This line indicates the command was dispatched.\n return { rebooting: true, success: true };\n}\n\nexport default task(run, { name: 'core.system.reboot_if_needed', description: 'Reboot if needed.' });\n","export { default as disable } from './disable';\nexport { default as enable } from './enable';\nexport { default as restart } from './restart';\nexport { default as start } from './start';\nexport { default as stop } from './stop';\nexport { default as reload } from './reload';\nexport { default as status } from './status';\n","import { task, type TaskContext } from '../../runtime';\n\ninterface DisableServiceParams {\n service: string;\n sudo?: boolean;\n}\n\ninterface DisableServiceResult {\n success: boolean;\n}\n\n/**\n * @param {service: string, sudo?: boolean} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<DisableServiceParams>): Promise<DisableServiceResult> {\n const { params, exec } = context;\n const { service, sudo = false } = params;\n\n const command = [sudo ? 'sudo' : '', 'systemctl', 'disable', service].filter(Boolean).join(' ');\n\n const { success } = await exec(command);\n\n return {\n success: success,\n };\n}\n\nexport default task(run, { name: 'core.systemd.disable', description: 'Systemd disable.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface SystemdEnableParams {\n service: string; // The name of the systemd service to enable.\n sudo?: boolean; // Whether to use sudo. Defaults to false.\n}\n\ninterface SystemdEnableResult {\n success: boolean; // True if the service was enabled successfully, false otherwise.\n}\n\n/**\n * Enables a systemd service.\n * @param {TaskContext<SystemdEnableParams>} context - The task context containing parameters.\n * @returns {Promise<SystemdEnableResult>} - The result of the enable operation.\n */\nasync function run(context: TaskContext<SystemdEnableParams>): Promise<SystemdEnableResult> {\n const { params, exec } = context;\n const { service, sudo = false } = params;\n\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('systemctl', 'enable', service);\n\n // systemctl enable usually requires sudo if not run as root.\n const { success } = await exec(commandArray);\n\n return {\n success: success,\n };\n}\n\nexport default task(run, { name: 'core.systemd.enable', description: 'Systemd enable.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface SystemdRestartParams {\n service: string; // The name of the systemd service to restart.\n sudo?: boolean; // Whether to use sudo. Defaults to false.\n}\n\ninterface SystemdRestartResult {\n success: boolean; // True if the service was restarted successfully, false otherwise.\n}\n\n/**\n * Restarts a systemd service.\n * @param {TaskContext<SystemdRestartParams>} context - The task context containing parameters.\n * @returns {Promise<SystemdRestartResult>} - The result of the restart operation.\n */\nasync function run(context: TaskContext<SystemdRestartParams>): Promise<SystemdRestartResult> {\n const { params, exec } = context;\n const { service, sudo = false } = params;\n\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('systemctl', 'restart', service);\n\n // systemctl restart usually requires sudo if not run as root.\n const { success } = await exec(commandArray);\n\n return {\n success: success,\n };\n}\n\nexport default task(run, { name: 'core.systemd.restart', description: 'Systemd restart.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface SystemdStartParams {\n service: string; // The name of the systemd service to start.\n sudo?: boolean; // Whether to use sudo. Defaults to false.\n}\n\ninterface SystemdStartResult {\n success: boolean; // True if the service was started successfully, false otherwise.\n}\n\n/**\n * Starts a systemd service.\n * @param {TaskContext<SystemdStartParams>} context - The task context containing parameters.\n * @returns {Promise<SystemdStartResult>} - The result of the start operation.\n */\nasync function run(context: TaskContext<SystemdStartParams>): Promise<SystemdStartResult> {\n const { params, exec } = context;\n const { service, sudo = false } = params;\n\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('systemctl', 'start', service);\n\n // systemctl start usually requires sudo if not run as root.\n const { success } = await exec(commandArray);\n\n return {\n success: success,\n };\n}\n\nexport default task(run, { name: 'core.systemd.start', description: 'Systemd start.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface SystemdStopParams {\n service: string; // The name of the systemd service to stop.\n sudo?: boolean; // Whether to use sudo. Defaults to false.\n}\n\ninterface SystemdStopResult {\n success: boolean; // True if the service was stopped successfully, false otherwise.\n}\n\n/**\n * Stops a systemd service.\n * @param {TaskContext<SystemdStopParams>} context - The task context containing parameters.\n * @returns {Promise<SystemdStopResult>} - The result of the stop operation.\n */\nasync function run(context: TaskContext<SystemdStopParams>): Promise<SystemdStopResult> {\n const { params, exec } = context;\n const { service, sudo = false } = params;\n\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('systemctl', 'stop', service);\n\n // systemctl stop usually requires sudo if not run as root.\n const { success } = await exec(commandArray);\n\n return {\n success: success,\n };\n}\n\nexport default task(run, { name: 'core.systemd.stop', description: 'Systemd stop.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface SystemdReloadParams {\n service: string;\n sudo?: boolean;\n}\n\ninterface SystemdReloadResult {\n success: boolean;\n}\n\n/**\n * Reloads a systemd service (e.g., re-reads configuration without full restart).\n */\nasync function run(context: TaskContext<SystemdReloadParams>): Promise<SystemdReloadResult> {\n const { params, exec } = context;\n const { service, sudo = false } = params;\n\n const command = [sudo ? 'sudo' : '', 'systemctl', 'reload', service].filter(Boolean);\n const { success } = await exec(command, { sudo });\n return { success };\n}\n\nexport default task(run, {\n name: 'core.systemd.reload',\n description: 'Reloads a systemd service (e.g., re-reads configuration without full restart).'\n});\n","import { task, type TaskContext } from '../../runtime';\n\ninterface SystemdStatusParams {\n service: string;\n sudo?: boolean;\n}\n\ninterface SystemdStatusResult {\n active: boolean;\n}\n\n/**\n * Checks whether a systemd service is active.\n */\nasync function run(context: TaskContext<SystemdStatusParams>): Promise<SystemdStatusResult> {\n const { params, exec } = context;\n const { service, sudo = false } = params;\n\n const command = [sudo ? 'sudo' : '', 'systemctl', 'is-active', '--quiet', service].filter(Boolean);\n const { success } = await exec(command, { sudo });\n return { active: success };\n}\n\nexport default task(run, {\n name: 'core.systemd.status',\n description: 'Checks systemd service status.'\n});\n","export { default as write } from './write';\n","import { type TaskContext, type LogLevel, task } from '../../runtime';\nimport { Verbosity } from '../../app';\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\n// Assuming these tasks are default exports from their respective files\nimport chmodTask from '../file/chmod';\nimport chownTask from '../file/chown';\n\ninterface TemplateWriteParams {\n template?: string; // Template content as a string\n template_file?: string; // Path to a template file\n variables: Record<string, any>; // Key-value pairs for template substitution\n to: string; // Destination path (file or directory)\n mode?: string; // File mode (e.g., \"644\")\n owner?: string; // File owner\n group?: string; // File group\n sudo?: boolean; // Optional: If true, chmod/chown tasks will attempt to use sudo. Defaults to their internal sudo behavior (usually true).\n}\n\ninterface TemplateWriteResult {\n success: boolean;\n path: string; // Actual path where the file was written\n}\n\n/**\n * Renders a template (from string or file) with given variables and writes it to a destination path.\n * Optionally sets file mode and ownership using chmod and chown tasks.\n * @param {TaskContext<TemplateWriteParams>} context - The task context containing parameters.\n * @returns {Promise<TemplateWriteResult>} - An object indicating success and the final output path.\n */\nasync function runFn(context: TaskContext<TemplateWriteParams>): Promise<TemplateWriteResult> {\n const { params, log, warn, error, debug, run } = context;\n const { template, template_file, variables, to, mode, owner, group, sudo } = params;\n\n let templateContent: string | undefined = template;\n\n if (template && template_file) {\n warn(\"Both 'template' string and 'template_file' path provided. Using 'template' string.\");\n }\n\n if (!templateContent && template_file) {\n try {\n templateContent = await fs.readFile(template_file, 'utf-8');\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n error(`Failed to read template_file '${template_file}': ${errorMessage}`);\n throw new Error(`Failed to read template_file '${template_file}': ${errorMessage}`);\n }\n }\n\n if (typeof templateContent !== 'string') {\n error(`No template content provided for destination '${to}'. Either 'template' or 'template_file' must be specified.`);\n throw new Error(`No template content provided for destination '${to}'.`);\n }\n\n // Simple template rendering (same as original)\n const renderedContent = templateContent.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key) => variables[key]?.toString() ?? '');\n\n let outputPath = to;\n try {\n const stat = await fs.stat(to);\n if (stat.isDirectory()) {\n const baseName = template_file ? path.basename(template_file) : 'rendered_template.txt'; // Added .txt for default\n outputPath = path.join(to, baseName);\n }\n } catch (error: any) {\n if (error.code !== 'ENOENT') {\n log(2, `Error checking destination path '${to}': ${error.message}. Proceeding assuming 'to' is a file path.`); // Assuming WARN is 2\n }\n // If 'to' does not exist (ENOENT), outputPath remains 'to', which is the intended new file path.\n }\n\n debug(`Writing rendered template to: ${outputPath}`);\n\n try {\n await fs.writeFile(outputPath, renderedContent, 'utf-8');\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n log(3, `Failed to write template to '${outputPath}': ${errorMessage}`); // Assuming ERROR is 3\n return { success: false, path: outputPath };\n }\n\n let overallSuccess = true;\n\n if (mode) {\n log(0, `Setting mode ${mode} for ${outputPath}`); // Assuming DEBUG is 0\n try {\n const chmodParams = { path: outputPath, mode, sudo };\n const chmodResult = await run(chmodTask(chmodParams)); // chmodTask is from ../file/chmod\n\n if (chmodResult instanceof Error) {\n log(Verbosity.ERROR as LogLevel, `Error setting mode for ${outputPath}: ${chmodResult.message}`);\n overallSuccess = false;\n } else if (!chmodResult?.success) {\n log(Verbosity.ERROR as LogLevel, `Failed to set mode ${mode} for ${outputPath}`);\n overallSuccess = false;\n }\n } catch (error) {\n // Catch unexpected errors from run or promise chain\n const errorMessage = error instanceof Error ? error.message : String(error);\n log(3, `Unexpected error during chmod operation for ${outputPath}: ${errorMessage}`); // Assuming ERROR is 3\n overallSuccess = false;\n }\n }\n\n if (owner) {\n // chownTask requires an owner\n log(0, `Setting owner='${owner}'${group ? ` group='${group}'` : ''} for ${outputPath}`); // Assuming DEBUG is 0\n try {\n // ChownParams requires owner: string. group is optional.\n const chownTaskParams: { path: string; owner: string; group?: string; sudo?: boolean } = {\n path: outputPath,\n owner: owner, // owner is guaranteed to be a string here\n sudo,\n };\n if (group) {\n chownTaskParams.group = group;\n }\n\n const chownResult = await run(chownTask(chownTaskParams));\n if (chownResult instanceof Error) {\n error(`Error setting owner/group for ${outputPath}: ${chownResult.message}`); // Assuming ERROR is 3\n overallSuccess = false;\n } else if (!chownResult?.success) {\n error(`Failed to set owner/group for ${outputPath}. chownTask reported failure.`); // Assuming WARN is 2\n overallSuccess = false;\n }\n } catch (error) {\n // Catch unexpected errors from run or promise chain\n const errorMessage = error instanceof Error ? error.message : String(error);\n log(3, `Unexpected error during chown operation for ${outputPath}: ${errorMessage}`); // Assuming ERROR is 3\n overallSuccess = false;\n }\n } else if (group) {\n // Owner is not provided, but group is. Current chownTask cannot set only group.\n log(\n 2,\n `Owner not specified for ${outputPath}, but group '${group}' was. Cannot set only group with current chown task.`,\n ); // Assuming WARN is 2\n // overallSuccess remains unchanged as we didn't attempt an operation that could fail here.\n }\n\n return {\n success: overallSuccess,\n path: outputPath,\n };\n}\n\nexport default task(runFn, { name: 'core.template.write', description: 'Template write.' });\n","export { default as deny } from './deny';\nexport { default as disable } from './disable';\nexport { default as enable } from './enable';\nexport { default as install } from './install';\nexport { default as reload } from './reload';\n","import { task, type TaskContext } from '../../runtime';\n\ninterface UfwDenyParams {\n from_addr?: string; // Source address, defaults to 'any'\n from_port?: number; // Source port\n to_addr?: string; // Destination address\n to_port?: number; // Destination port (only if to_addr is specified)\n}\n\ninterface UfwDenyResult {\n success: boolean;\n}\n\n/**\n * Adds a deny rule to UFW (Uncomplicated Firewall).\n * Rule structure: ufw deny from <from_addr> [port <from_port>] [to <to_addr> [port <to_port>]]\n * @param {TaskContext<UfwDenyParams>} context - The task context with parameters.\n * @returns {Promise<UfwDenyResult>} - An object indicating the success of the operation.\n */\nasync function run(context: TaskContext<UfwDenyParams>): Promise<UfwDenyResult> {\n const { params, exec } = context;\n const from_addr = params.from_addr || 'any';\n const { from_port, to_addr, to_port } = params;\n\n const commandArray: string[] = ['sudo', 'ufw', 'deny'];\n\n commandArray.push('from', from_addr);\n if (from_port !== undefined) {\n commandArray.push('port', from_port.toString());\n }\n\n if (to_addr) {\n commandArray.push('to', to_addr);\n if (to_port !== undefined) {\n commandArray.push('port', to_port.toString());\n }\n }\n\n const { success } = await exec(commandArray, { sudo: true });\n return { success };\n}\n\nexport default task(run, { name: 'core.ufw.deny', description: 'Ufw deny.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface UfwDisableParams {}\n\ninterface UfwDisableResult {\n success: boolean;\n}\n\n/**\n * Disables UFW (Uncomplicated Firewall).\n * This command typically requires sudo privileges.\n * @param {TaskContext<UfwDisableParams>} context - The task context.\n * @returns {Promise<UfwDisableResult>} - An object indicating the success of the operation.\n */\nasync function run(context: TaskContext<UfwDisableParams>): Promise<UfwDisableResult> {\n const { exec } = context;\n\n const { success } = await exec(['sudo', 'ufw', 'disable'], { sudo: true });\n return { success };\n}\n\nexport default task(run, { name: 'core.ufw.disable', description: 'Ufw disable.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface UfwEnableParams {}\n\ninterface UfwEnableResult {\n success: boolean;\n}\n\n/**\n * Enables UFW (Uncomplicated Firewall).\n * This command typically requires sudo privileges and may prompt for confirmation if enabling for the first time.\n * @param {TaskContext<UfwEnableParams>} context - The task context.\n * @returns {Promise<UfwEnableResult>} - An object indicating the success of the operation.\n */\nasync function run(context: TaskContext<UfwEnableParams>): Promise<UfwEnableResult> {\n const { exec } = context;\n\n const { success } = await exec(['yes | sudo ufw enable'], { sudo: true });\n return { success };\n}\n\nexport default task(run, { name: 'core.ufw.enable', description: 'Ufw enable.' });\n","import { task, type TaskContext } from '../../runtime';\nimport pkgInstallTask from '../pkg/install';\n\ninterface UfwInstallParams {}\n\ninterface UfwInstallResult {\n success: boolean;\n}\n\n/**\n * Installs the UFW (Uncomplicated Firewall) package using the core package installation task.\n * @param {TaskContext<UfwInstallParams>} context - The task context.\n * @returns {Promise<UfwInstallResult>} - An object indicating the success of the package installation.\n */\nasync function run(context: TaskContext<UfwInstallParams>): Promise<UfwInstallResult> {\n const { run: runTask, error } = context;\n\n const installResult = await runTask(pkgInstallTask({ package: 'ufw', sudo: true }));\n\n if (installResult instanceof Error) {\n error(`Error during UFW package installation: ${installResult.message}`);\n return { success: false };\n }\n\n if (typeof installResult?.success === 'boolean') {\n if (!installResult.success) {\n error(`UFW package installation failed (reported by pkg/install).`);\n }\n return { success: installResult.success };\n }\n\n return { success: false };\n}\n\nexport default task(run, { name: 'core.ufw.install', description: 'Ufw install.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface UfwReloadParams {}\n\ninterface UfwReloadResult {\n success: boolean;\n}\n\n/**\n * Reloads UFW (Uncomplicated Firewall) rules.\n * This command typically requires sudo privileges.\n * @param {TaskContext<UfwReloadParams>} context - The task context.\n * @returns {Promise<UfwReloadResult>} - An object indicating the success of the operation.\n */\nasync function run(context: TaskContext<UfwReloadParams>): Promise<UfwReloadResult> {\n const { exec } = context;\n\n const { success } = await exec(['sudo', 'ufw', 'reload'], { sudo: true });\n return { success };\n}\n\nexport default task(run, { name: 'core.ufw.reload', description: 'Ufw reload.' });\n","import addGroups, { type AddGroupsParams, type AddGroupsResult } from './add_groups';\nimport create, { type CreateUserParams, type CreateUserResult } from './create';\nimport exists, { type UserExistsParams, type UserExistsResult } from './exists';\nimport getGid, { type GetGidParams, type GetGidResult } from './get_gid';\nimport getGroups, { type GetGroupsParams, type GetGroupsResult } from './get_groups';\nimport getUid, { type GetUidParams, type GetUidResult } from './get_uid';\nimport getUsername, { type GetUsernameResult } from './get_username';\nimport homeDir, { type UserHomeDirParams, type UserHomeDirResult } from './home_dir';\nimport setGroups, { type SetUserGroupsParams, type SetUserGroupsResult } from './set_groups';\nimport setShell, { type SetUserShellParams, type SetUserShellResult } from './set_shell';\nimport del, { type UserDeleteParams, type UserDeleteResult } from './delete';\nimport modify from './modify';\n\nexport {\n addGroups,\n type AddGroupsParams,\n type AddGroupsResult,\n create,\n type CreateUserParams,\n type CreateUserResult,\n exists,\n type UserExistsParams,\n type UserExistsResult,\n getGid,\n type GetGidParams,\n type GetGidResult,\n getGroups,\n type GetGroupsParams,\n type GetGroupsResult,\n getUid,\n type GetUidParams,\n type GetUidResult,\n getUsername,\n type GetUsernameResult,\n homeDir,\n type UserHomeDirParams,\n type UserHomeDirResult,\n setGroups,\n type SetUserGroupsParams,\n type SetUserGroupsResult,\n setShell,\n type SetUserShellParams,\n type SetUserShellResult,\n del as delete,\n type UserDeleteParams,\n type UserDeleteResult,\n modify,\n};\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface AddGroupsParams {\n user: string;\n groups: string[];\n}\n\nexport interface AddGroupsResult {\n success: boolean;\n}\n\n/**\n * @param {user: string, groups: string[]} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<AddGroupsParams>): Promise<AddGroupsResult> {\n const { params, exec } = context;\n const { user, groups } = params;\n\n // Only proceed if groups array is not empty\n if (groups.length === 0) {\n return { success: true };\n }\n\n // Add groups to user using usermod command with --append\n const groupsStr = groups.join(',');\n const command = ['sudo', 'usermod', '--append', '-G', groupsStr, user].filter(Boolean).join(' ');\n\n const { success } = await exec(command);\n\n return {\n success,\n };\n}\n\nexport default task(run, { name: 'core.user.add_groups', description: 'User add groups.' });\n","import { task, type TaskContext } from '../../runtime';\nimport exists from './exists';\nimport homeDir from './home_dir';\n\nexport interface CreateUserParams {\n user: string;\n create_home?: boolean;\n create_group?: boolean;\n system?: boolean;\n sudo?: boolean;\n}\n\nexport interface CreateUserResult {\n success: boolean;\n}\n\n/**\n * @param {user: string, create_home?: boolean, create_group?: boolean, system?: boolean} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<CreateUserParams>): Promise<CreateUserResult> {\n const { params, exec, run: runTask } = context;\n const { user, create_home = true, create_group = true, system = false, sudo = true } = params;\n\n // First check if user exists\n const { exists: userExists } = await runTask(exists({ user }));\n if (userExists) {\n return { success: true };\n }\n\n // Build useradd command with appropriate flags\n const command = [\n sudo ? 'sudo' : '',\n 'useradd',\n create_home ? '--create-home' : '--no-create-home',\n create_group ? '--user-group' : '--no-user-group',\n system ? '--system' : '',\n user,\n ]\n .filter(Boolean)\n .join(' ');\n\n const { success } = await exec(command, { sudo });\n\n // If create_home is true, verify home directory exists or create it\n let createHomeSuccess = true;\n if (create_home && success) {\n const { exists: homeDirExists } = await runTask(homeDir({ user }));\n if (!homeDirExists) {\n const { success: mkhomeSuccess } = await exec(`sudo mkhomedir_helper ${user}`);\n createHomeSuccess = mkhomeSuccess;\n }\n }\n\n return {\n success: success && createHomeSuccess,\n };\n}\n\nexport default task(run, { name: 'core.user.create', description: 'User create.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GetGidParams {\n user: string;\n}\n\nexport interface GetGidResult {\n success: boolean;\n gid: string;\n}\n\n/**\n * @param {user: string} params\n * @returns {\n * success: boolean\n * gid: string\n * }\n */\nasync function run(context: TaskContext<GetGidParams>): Promise<GetGidResult> {\n const { params, exec } = context;\n const { user } = params;\n\n // Get user's GID using id command\n const command = ['id', '-g', user].filter(Boolean).join(' ');\n\n const { success, stdout: gid } = await exec(command);\n\n return {\n success,\n gid: gid.trim(),\n };\n}\n\nexport default task(run, { name: 'core.user.get_gid', description: 'User get gid.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GetGroupsParams {\n user: string;\n}\n\nexport interface GetGroupsResult {\n success: boolean;\n groups: string[];\n}\n\n/**\n * @param {user: string} params\n * @returns {\n * success: boolean\n * groups: string[]\n * }\n */\nasync function run(context: TaskContext<GetGroupsParams>): Promise<GetGroupsResult> {\n const { params, exec } = context;\n const { user } = params;\n\n // Get user's groups using groups command\n const command = ['groups', user].filter(Boolean).join(' ');\n\n const { success, stdout } = await exec(command);\n\n // Parse groups from output\n let groups: string[] = [];\n if (success) {\n const match = stdout.match(new RegExp(`${user} : (.*)`));\n if (match) {\n groups = match[1].split(' ').filter(Boolean);\n }\n }\n\n return {\n success,\n groups,\n };\n}\n\nexport default task(run, { name: 'core.user.get_groups', description: 'User get groups.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GetUidParams {\n user: string;\n}\n\nexport interface GetUidResult {\n success: boolean;\n uid: string;\n}\n\n/**\n * @param {user: string} params\n * @returns {\n * success: boolean\n * uid: string\n * }\n */\nasync function run(context: TaskContext<GetUidParams>): Promise<GetUidResult> {\n const { params, exec } = context;\n const { user } = params;\n\n // Get user's UID using id command\n const command = ['id', '-u', user].filter(Boolean).join(' ');\n\n const { success, stdout: uid } = await exec(command);\n\n return {\n success,\n uid: uid.trim(),\n };\n}\n\nexport default task(run, { name: 'core.user.get_uid', description: 'User get uid.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface SetUserGroupsParams {\n user: string;\n groups: string[];\n}\n\nexport interface SetUserGroupsResult {\n success: boolean;\n}\n\n/**\n * @param {user: string, groups: string[]} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<SetUserGroupsParams>): Promise<SetUserGroupsResult> {\n const { params, exec } = context;\n const { user, groups } = params;\n\n // Only proceed if groups array is not empty\n if (groups.length === 0) {\n return { success: true };\n }\n\n // Set user's groups using usermod command\n const groupsStr = groups.join(',');\n const command = ['sudo', 'usermod', '-G', groupsStr, user].filter(Boolean).join(' ');\n\n const { success } = await exec(command);\n\n return {\n success,\n };\n}\n\nexport default task(run, { name: 'core.user.set_groups', description: 'User set groups.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface SetUserShellParams {\n user: string;\n shell: string;\n}\n\nexport interface SetUserShellResult {\n success: boolean;\n}\n\n/**\n * @param {user: string, shell: string} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<SetUserShellParams>): Promise<SetUserShellResult> {\n const { params, exec } = context;\n const { user, shell } = params;\n\n // Set user's shell using usermod command\n const command = ['sudo', 'usermod', '-s', shell, user].filter(Boolean).join(' ');\n\n const { success } = await exec(command);\n\n return {\n success,\n };\n}\n\nexport default task(run, { name: 'core.user.set_shell', description: 'User set shell.' });\n","import { type TaskContext, task } from '../../runtime';\nimport exists from './exists';\n\nexport interface UserDeleteParams {\n user: string;\n /** If true, remove the user's home directory and mail spool. */\n remove?: boolean;\n /** Whether to run the command with sudo. Defaults to true. */\n sudo?: boolean;\n}\n\nexport interface UserDeleteResult {\n success: boolean;\n error?: string;\n}\n\n/**\n * Deletes a user from the system idempotently (Linux only).\n * @param context params is a map of the form { user: string, remove?: boolean }.\n * remove - remove home directory and mail spool\n * @returns The result of the task.\n */\nasync function run(context: TaskContext<UserDeleteParams>): Promise<UserDeleteResult> {\n const { params, debug, exec, run } = context;\n const { user, remove = false, sudo = true } = params;\n\n // Check if user exists by calling the user.exists task.\n const { exists: userExists } = await run(exists({ user }));\n\n if (!userExists) {\n // User does not exist, so we are done (idempotency).\n debug(`User '${user}' does not exist, considering task successful (idempotent).`);\n return { success: true };\n }\n\n const args = [];\n if (remove) {\n args.push('--remove');\n }\n args.push(user);\n\n const command: string[] = [];\n if (sudo) {\n command.push('sudo');\n }\n command.push('userdel', ...args);\n\n const { failure, stdout, stderr } = await exec(command, { sudo });\n\n if (failure) {\n return { success: false, error: [stdout, stderr].join('\\n') };\n }\n\n debug(`User '${user}' deleted successfully.`);\n\n return { success: true };\n}\n\nexport default task(run, {\n description: 'Deletes a user from the system idempotently',\n});\n","import { task, type TaskContext } from '../../runtime';\nimport exists from './exists';\n\nexport interface ModifyUserParams {\n user: string;\n comment?: string;\n home?: string;\n expiredate?: string;\n gid?: string;\n groups?: string[];\n login?: string;\n lock?: boolean;\n unlock?: boolean;\n move_home?: boolean;\n shell?: string;\n uid?: string;\n sudo?: boolean;\n}\n\nexport interface ModifyUserResult {\n success: boolean;\n}\n\n/**\n * @param {user: string, comment?: string, home?: string, expiredate?: string, gid?: string, groups?: string[], login?: string, lock?: boolean, unlock?: boolean, move_home?: boolean, shell?: string, uid?: string, sudo?: boolean} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<ModifyUserParams>): Promise<ModifyUserResult> {\n const { params, exec, run: runTask } = context;\n const {\n user,\n comment,\n home,\n expiredate,\n gid,\n groups,\n login,\n lock,\n unlock,\n move_home,\n shell,\n uid,\n sudo = true,\n } = params;\n\n // First check if user exists\n const { exists: userExists } = await runTask(exists({ user }));\n if (!userExists) {\n // Depending on desired behavior, you might want to throw an error\n // or return a specific status indicating the user was not found.\n // For now, we'll return success: false.\n return { success: false };\n }\n\n // Build usermod command with appropriate flags\n const command = [\n sudo ? 'sudo' : '',\n 'usermod',\n comment ? `--comment '${comment}'` : '',\n home ? `--home ${home}` : '',\n expiredate ? `--expiredate ${expiredate}` : '',\n gid ? `--gid ${gid}` : '',\n groups ? `--groups ${groups.join(',')}` : '',\n login ? `--login ${login}` : '',\n lock ? '--lock' : '',\n unlock ? '--unlock' : '',\n move_home ? '--move-home' : '',\n shell ? `--shell ${shell}` : '',\n uid ? `--uid ${uid}` : '',\n user,\n ]\n .filter(Boolean)\n .join(' ');\n\n const { success } = await exec(command, { sudo });\n\n return {\n success,\n };\n}\n\nexport default task(run, { name: 'core.user.modify', description: 'Modify an existing user account.' });\n","// Individual task files from src/core/\nimport echo from './echo';\nimport whoami from './whoami';\n\n// Modules from subdirectories of src/core/\n// These assume each subdirectory has an index.ts exporting its contents, often as a namespace.\nimport * as dir from './dir';\nimport * as file from './file';\nimport * as git from './git';\nimport * as group from './group';\nimport * as host from './host';\nimport * as pkg from './pkg';\nimport * as k3s from './k3s';\nimport * as ssh from './ssh';\nimport * as sudoers from './sudoers';\nimport * as system from './system';\nimport * as systemd from './systemd';\nimport * as template from './template';\nimport * as ufw from './ufw';\nimport * as user from './user';\n\nexport default {\n // Individual tasks\n echo,\n whoami,\n\n // Modules from subdirectories\n dir,\n file,\n git,\n group,\n host,\n pkg,\n k3s,\n ssh,\n sudoers,\n system,\n systemd,\n template,\n ufw,\n user,\n};\n"],"mappings":";;;;;;;AAAA,OAAOA,cAAa;AACpB,YAAYC,SAAQ;AACpB,SAAS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D,SAAO;AAAA,IACL;AAAA,EACF;AACF;AAEA,IAAOC,kBAAQ,KAAKF,OAAK,EAAE,MAAM,oBAAoB,aAAa,mCAAmC,CAAC;;;AC9DtG,IAAO,eAAQ;AAAA;AAAA,EAEb;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":["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","process","zip","path","A","isValidUrl","App","path","process","runFn","Mutex","Command","A","runFn","Mutex","Handlebars","fs","StringBuilder","Command","StringBuilder","chalk","Handlebars","path","chalk","ConfigFile","Handlebars","errnoError","Command","match","Handlebars","match","Command","command","os","match","spawnAsync","signalsByName","Command","spawnAsync","signalsByName","match","P","platform","os","A","match","url","path","match","A","key","str","Mutex","match","Mutex","task","App","process","homedir","chalk","A","cmd","match","ConfigFile","identity","invocation","path","run","run","copy_default","run","path","exists","run","path","run","path","run","run","copy_default","run","path","exists_default","run","path","run","path","exists","exists_default","run","run","path","dirname","run","os","dirname","run","dirname","runFn","run","exists","success","run","run","run","create_default","delete_default","exists_default","run","exists","exists_default","run","exists_default","create_default","run","delete_default","run","run","run","match","P","version","run","match","P","run","os","run","info_default","remove_default","update_default","run","run","info_default","run","install","run","install","run","install","install_default","install_default","run","run","remove","run","remove","run","remove","remove_default","run","run","success","update","run","success","update","run","update","update_default","run","info_default","run","info_default","run","path","run","exists","exists_default","run","path","exists","run","run","exists_default","path","run","run","run","run","run","run","run","run","run","run","run","run","fs","path","runFn","run","fs","path","error","disable_default","enable_default","install_default","reload_default","run","run","disable_default","run","enable_default","run","install_default","run","reload_default","create_default","delete_default","exists_default","modify_default","run","run","exists_default","create_default","run","run","match","run","run","run","run","remove","exists_default","delete_default","run","exists_default","modify_default"]}
1
+ {"version":3,"sources":["../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/cli.ts","../src/version.ts","../src/cli/run-resolver.ts","../src/zip.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/hash.ts","../src/param-map.ts","../src/core/remote/runAllRemote.ts","../src/core/echo.ts","../src/core/whoami.ts","../src/core/dir/index.ts","../src/core/dir/exists.ts","../src/core/file/chmod.ts","../src/core/file/chown.ts","../src/core/file/copy.ts","../src/core/dir/copy.ts","../src/core/dir/create.ts","../src/core/file/index.ts","../src/core/file/chgrp.ts","../src/core/file/exists.ts","../src/core/file/touch.ts","../src/core/file/delete.ts","../src/core/file/link.ts","../src/keyboard.ts","../src/core/file/edit.ts","../src/core/file/grep.ts","../src/core/git/index.ts","../src/core/git/clone.ts","../src/core/git/pull.ts","../src/core/git/checkout.ts","../src/core/group/index.ts","../src/core/group/exists.ts","../src/core/group/create.ts","../src/core/group/delete.ts","../src/core/group/list.ts","../src/core/group/modify.ts","../src/core/host/index.ts","../src/core/host/hostname.ts","../src/core/host/os.ts","../src/core/host/info.ts","../src/core/host/summary.ts","../src/core/pkg/index.ts","../src/core/pkg/install/arch.ts","../src/core/system/reboot_needed.ts","../src/core/pkg/install/debian.ts","../src/core/pkg/install/fedora.ts","../src/core/pkg/install/index.ts","../src/core/pkg/install.ts","../src/core/pkg/remove/arch.ts","../src/core/pkg/remove/debian.ts","../src/core/pkg/remove/fedora.ts","../src/core/pkg/remove/index.ts","../src/core/pkg/remove.ts","../src/core/pkg/update/arch.ts","../src/core/pkg/update/debian.ts","../src/core/pkg/update/fedora.ts","../src/core/pkg/update/index.ts","../src/core/pkg/update.ts","../src/core/pkg/info.ts","../src/core/pkg/is_installed.ts","../src/core/k3s/index.ts","../src/core/k3s/k3sup-install.ts","../src/core/ssh/index.ts","../src/core/ssh/copy_id.ts","../src/core/user/exists.ts","../src/core/user/home_dir.ts","../src/core/user/get_username.ts","../src/core/sudoers/index.ts","../src/core/sudoers/check.ts","../src/core/sudoers/grant-nopasswd.ts","../src/core/system/index.ts","../src/core/system/reboot.ts","../src/core/system/shutdown.ts","../src/core/system/reboot_if_needed.ts","../src/core/systemd/index.ts","../src/core/systemd/disable.ts","../src/core/systemd/enable.ts","../src/core/systemd/restart.ts","../src/core/systemd/start.ts","../src/core/systemd/stop.ts","../src/core/systemd/reload.ts","../src/core/systemd/status.ts","../src/core/template/index.ts","../src/core/template/write.ts","../src/core/ufw/index.ts","../src/core/ufw/deny.ts","../src/core/ufw/disable.ts","../src/core/ufw/enable.ts","../src/core/ufw/install.ts","../src/core/ufw/reload.ts","../src/core/user/index.ts","../src/core/user/add_groups.ts","../src/core/user/create.ts","../src/core/user/get_gid.ts","../src/core/user/get_groups.ts","../src/core/user/get_uid.ts","../src/core/user/set_groups.ts","../src/core/user/set_shell.ts","../src/core/user/delete.ts","../src/core/user/modify.ts","../src/core/index.ts"],"sourcesContent":["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","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","export const version = '0.1.35';\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","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","// 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 { 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","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 { task, type TaskContext, type LogLevel } from '../runtime';\nimport { Verbosity } from '../app'; // Verbosity is in app\n\nexport type EchoParams = {\n args: string[];\n};\n\nexport interface EchoResult {\n stdout: string;\n}\n\n/**\n * Echoes the provided arguments.\n * @param {EchoParams} params - Parameters for the echo operation, containing an array of strings.\n * @returns {Promise<EchoResult>} - The result of the echo operation, containing the stdout.\n */\nasync function run(context: TaskContext<EchoParams>): Promise<EchoResult> {\n const { params, exec, log } = context;\n const { args = [] } = params; // Default to empty array if args is not provided\n\n // Log the arguments being echoed for debugging purposes.\n // Note: If args can contain sensitive information, consider logging strategy.\n log(Verbosity.DEBUG as LogLevel, `Echoing arguments: ${args.join(' ')}`);\n\n // Pass arguments as an array to exec. Manual quoting is not needed here.\n const commandArray = ['echo', ...args];\n const { stdout } = await exec(commandArray);\n\n return {\n stdout,\n };\n}\n\nexport default task(run, { name: 'core.echo', description: 'Echo.' });\n","import { task, type TaskContext } from '../runtime';\n\n// Define an empty params interface as this task doesn't take direct parameters\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface WhoamiParams {}\n\nexport interface WhoamiResult {\n user: string; // The username of the current user\n}\n\n/**\n * Gets the username of the current user by executing the 'whoami' command.\n * @param {TaskContext<WhoamiParams>} context - The task context (no parameters needed for this task).\n * @returns {Promise<WhoamiResult>} - An object containing the username.\n */\nasync function run(context: TaskContext<WhoamiParams>): Promise<WhoamiResult> {\n const { exec } = context;\n // Execute 'whoami' command. Pass command and args as an array.\n const { stdout } = await exec(['whoami']);\n return {\n user: stdout.trim(), // Trim whitespace from the output\n };\n}\n\nexport default task(run, { name: 'core.whoami', description: 'Whoami.' });\n","export { default as exists } from './exists';\nexport { default as copy } from './copy';\nexport { default as create } from './create';\n","import { task, type TaskContext } from '../../runtime';\n\ninterface DirExistsParams {\n path: string;\n}\n\ninterface DirExistsResult {\n exists: boolean;\n}\n\n/**\n * @param {path: string} params\n * @returns {\n * exists: boolean\n * }\n */\nasync function run(context: TaskContext<DirExistsParams>): Promise<DirExistsResult> {\n const { params, exec } = context;\n const { path } = params;\n\n // Check if directory exists using test command\n const command = ['test', '-d', path].join(' ');\n\n const { success: exists } = await exec(command);\n\n return {\n exists,\n };\n}\n\nexport default task(run, { name: 'core.dir.exists', description: 'Dir exists.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface ChmodParams {\n path: string;\n mode: string | number;\n recursive?: boolean;\n sudo?: boolean;\n}\n\nexport interface ChmodResult {\n success: boolean;\n error?: string;\n}\n\n/**\n * Changes the permissions mode of a file or directory.\n * @param {ChmodParams} params - Parameters for the chmod operation.\n * @returns {Promise<ChmodResult>} - The result of the chmod operation.\n */\nasync function run(context: TaskContext<ChmodParams>): Promise<ChmodResult> {\n const { params, exec } = context;\n const { path, mode, recursive = false, sudo = false } = params;\n\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('chmod');\n if (recursive) {\n commandArray.push('-R');\n }\n commandArray.push(String(mode));\n commandArray.push(path);\n\n try {\n const { success, stdout, stderr } = await exec(commandArray, { sudo });\n\n if (!success) {\n return {\n success: false,\n error: `${stdout}\\n${stderr}`,\n };\n }\n\n return {\n success: true,\n };\n } catch (error: any) {\n return {\n success: false,\n error: error.message,\n };\n }\n}\n\nexport default task(run, { name: 'core.file.chmod', description: 'Chmod.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface ChownParams {\n path: string;\n owner: string;\n group?: string;\n recursive?: boolean;\n sudo?: boolean;\n}\n\nexport interface ChownResult {\n success: boolean;\n error?: string;\n}\n\n/**\n * Changes the ownership of a file or directory.\n * @param {ChownParams} params - Parameters for the chown operation.\n * @returns {Promise<ChownResult>} - The result of the chown operation.\n */\nasync function run(context: TaskContext<ChownParams>): Promise<ChownResult> {\n const { params, exec } = context;\n const { path, owner, group, recursive = false, sudo = true } = params;\n\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('chown');\n if (recursive) {\n commandArray.push('-R');\n }\n commandArray.push(owner + (group ? `:${group}` : ''));\n commandArray.push(path);\n\n try {\n const { success, stdout, stderr } = await exec(commandArray, { sudo });\n\n if (!success) {\n return {\n success: false,\n error: `${stdout}\\n${stderr}`,\n };\n }\n\n return {\n success: true,\n };\n } catch (error: any) {\n return {\n success: false,\n error: error.message,\n };\n }\n}\n\nexport default task(run, { name: 'core.file.chown', description: 'Change ownership.' });\n","import { task, type TaskContext } from '../../runtime';\nimport chmod from './chmod';\nimport chown from './chown';\n\nexport interface FileCopyParams {\n from: string;\n to: string;\n mode?: string;\n owner?: string;\n group?: string;\n recursive?: boolean;\n sudo?: boolean;\n}\n\nexport interface FileCopyResult {\n success: boolean;\n}\n\n/**\n * @param {from: string, to: string, mode?: string, owner?: string, group?: string, recursive?: boolean, sudo?: boolean} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<FileCopyParams>): Promise<FileCopyResult> {\n const { params, exec, run: runTask } = context;\n const { from, to, mode, owner, group, recursive = false } = params;\n const effectiveSudo = params.sudo ?? !!owner;\n\n const cpCommandArray: string[] = [];\n if (effectiveSudo) {\n cpCommandArray.push('sudo');\n }\n cpCommandArray.push('cp');\n if (recursive) {\n cpCommandArray.push('-r');\n }\n cpCommandArray.push(from, to);\n\n const { success: cpSuccess } = await exec(cpCommandArray, { sudo: effectiveSudo });\n\n let chmodSuccess = true;\n if (mode && cpSuccess) {\n const chmodResult = await runTask(\n chmod({\n path: to,\n mode,\n sudo: effectiveSudo, // Original logic: sudo for chmod is based on owner presence\n }),\n );\n chmodSuccess = chmodResult.success;\n }\n\n let chownSuccess = true;\n if (owner && cpSuccess) {\n // Original logic: chown task uses its internal sudo default if not specified.\n const chownResult = await runTask(\n chown({\n path: to,\n owner,\n group,\n // sudo is intentionally omitted to use chown's default sudo behavior\n }),\n );\n chownSuccess = chownResult.success;\n }\n\n return {\n success: cpSuccess && chmodSuccess && chownSuccess,\n };\n}\n\nexport default task(run, { name: 'core.file.copy', description: 'Copy a file or directory.' });\n","import { task, type TaskContext } from '../../runtime';\nimport exists from './exists';\nimport fileCopy from '../file/copy';\n\ninterface DirCopyParams {\n from: string;\n to: string;\n mode?: string;\n owner?: string;\n group?: string;\n sudo?: boolean;\n}\n\ninterface DirCopyResult {\n success: boolean;\n}\n\n/**\n * @param {from: string, to: string, mode?: string, owner?: string, group?: string, sudo?: boolean} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<DirCopyParams>): Promise<DirCopyResult> {\n const { params, run: runTask } = context;\n const { from, to, mode, owner, group, sudo = false } = params;\n\n // First check if source directory exists\n const dirExistsResult = await runTask(exists({ path: from }));\n if (!dirExistsResult.exists) {\n return { success: false };\n }\n\n // Copy directory using file copy with recursive flag\n // Assuming fileCopy will be refactored to accept TaskContext compatible params\n // and return a result object with a success property.\n const copyResult = await runTask(\n fileCopy({\n from,\n to,\n mode,\n owner,\n group,\n recursive: true,\n sudo,\n }),\n );\n\n return {\n success: copyResult?.success ?? false, // Adapt if fileCopy's result structure differs\n };\n}\n\nexport default task(run, { name: 'core.dir.copy', description: 'Dir copy.' });\n","import { task, type TaskContext } from '../../runtime';\nimport chmod from '../file/chmod';\n\ninterface DirCreateParams {\n path: string;\n mode?: string;\n owner?: string;\n}\n\ninterface DirCreateResult {\n success: boolean;\n}\n\n/**\n * @param {path: string, mode?: string, owner?: string} params\n * @returns {\n * success: boolean\n * }\n */\nasync function runFn(context: TaskContext<DirCreateParams>): Promise<DirCreateResult> {\n const { params, exec, run } = context;\n const { path, mode, owner } = params;\n\n // Create directory with mkdir\n const commandParts = [];\n if (owner) {\n commandParts.push(`sudo -u ${owner}`);\n }\n commandParts.push('mkdir', '-p', path);\n const command = commandParts.filter(Boolean).join(' ');\n\n const { success: mkdirSuccess } = await exec(command);\n\n // Set mode if specified\n let chmodSuccess = true;\n if (mode && mkdirSuccess) {\n // Assuming chmod task is refactored to accept TaskContext compatible params\n // and returns a result object with a success property.\n const chmodResult = await run(chmod({ path, mode, sudo: !!owner }));\n chmodSuccess = chmodResult?.success ?? false;\n }\n\n return {\n success: mkdirSuccess && chmodSuccess,\n };\n}\n\nexport default task(runFn, { name: 'core.dir.create', description: 'Dir create.' });\n","import chown, { type ChownParams, type ChownResult } from './chown';\nimport chgrp, { type ChgrpParams, type ChgrpResult } from './chgrp';\nimport chmod, { type ChmodParams, type ChmodResult } from './chmod';\nimport copy, { type FileCopyParams, type FileCopyResult } from './copy';\nimport exists, { type FileExistsParams, type FileExistsResult } from './exists';\nimport touch, { type FileTouchParams, type FileTouchResult } from './touch';\nimport deleteFn, { type FileDeleteParams, type FileDeleteResult } from './delete';\nimport link, { type FileLinkParams, type FileLinkResult } from './link';\nimport editFile, { type FileEditParams, type FileEditResult } from './edit';\nimport grep, { type FileGrepParams, type FileGrepResult } from './grep';\n\nexport {\n chown,\n type ChownParams,\n type ChownResult,\n chgrp,\n type ChgrpParams,\n type ChgrpResult,\n chmod,\n type ChmodParams,\n type ChmodResult,\n copy,\n type FileCopyParams,\n type FileCopyResult,\n exists,\n type FileExistsParams,\n type FileExistsResult,\n touch,\n type FileTouchParams,\n type FileTouchResult,\n editFile as edit,\n type FileEditParams,\n type FileEditResult,\n link,\n type FileLinkParams,\n type FileLinkResult,\n deleteFn as delete,\n type FileDeleteParams,\n type FileDeleteResult,\n grep,\n type FileGrepParams,\n type FileGrepResult,\n};\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface ChgrpParams {\n path: string;\n group: string;\n recursive?: boolean;\n sudo?: boolean;\n}\n\nexport interface ChgrpResult {\n success: boolean;\n error?: string;\n}\n\n/**\n * Changes the group ownership of a file or directory.\n * @param {ChgrpParams} params - Parameters for the chgrp operation.\n * @returns {Promise<ChgrpResult>} - The result of the chgrp operation.\n */\nasync function run(context: TaskContext<ChgrpParams>): Promise<ChgrpResult> {\n const { params, exec } = context;\n const { path, group, recursive = false, sudo = true } = params;\n\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('chgrp');\n if (recursive) {\n commandArray.push('-R');\n }\n commandArray.push(group);\n commandArray.push(path);\n\n try {\n const { success, stdout, stderr } = await exec(commandArray, { sudo });\n\n if (!success) {\n return {\n success: false,\n error: `${stdout}\\n${stderr}`,\n };\n }\n\n return {\n success: true,\n };\n } catch (error: any) {\n return {\n success: false,\n error: error.message,\n };\n }\n}\n\nexport default task(run, { name: 'core.file.chgrp', description: 'Chgrp.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface FileExistsParams {\n path: string;\n}\n\nexport interface FileExistsResult {\n exists: boolean;\n}\n\n/**\n * @param {path: string} params\n * @returns {\n * exists: boolean\n * }\n */\nasync function run(context: TaskContext<FileExistsParams>): Promise<FileExistsResult> {\n const { params, exec } = context;\n const { path } = params;\n\n const { success: exists } = await exec(['test', '-f', path]);\n\n return {\n exists,\n };\n}\n\nexport default task(run, { name: 'core.file.exists', description: 'File exists.' });\n","import { task, type TaskContext } from '../../runtime';\nimport chmod from './chmod';\n\nexport interface FileTouchParams {\n file: string;\n mode?: string;\n owner?: string;\n}\n\nexport interface FileTouchResult {\n success: boolean;\n}\n\n/**\n * @param {file: string, mode?: string, owner?: string} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<FileTouchParams>): Promise<FileTouchResult> {\n const { params, exec, run: runTask } = context;\n const { file, mode, owner } = params;\n\n const touchCommandArray: string[] = [];\n if (owner) {\n touchCommandArray.push('sudo', '-u', owner);\n }\n touchCommandArray.push('touch', file);\n\n const { success: touchSuccess } = await exec(touchCommandArray);\n\n let chmodSuccess = true;\n if (mode && touchSuccess) {\n const chmodResult = await runTask(\n chmod({\n path: file,\n mode,\n sudo: !!owner, // Original logic: sudo for chmod is based on owner presence\n }),\n );\n chmodSuccess = chmodResult?.success ?? false;\n }\n\n return {\n success: touchSuccess && chmodSuccess,\n };\n}\n\nexport default task(run, { name: 'core.file.touch', description: 'Touches a file on the system.' });\n","import { task, type TaskContext } from '../../runtime';\nimport { Path } from '../../flex/path';\n\nexport interface FileDeleteParams {\n path: string;\n recursive?: boolean;\n force?: boolean;\n}\n\nexport interface FileDeleteResult {\n success: boolean;\n}\n\nasync function run(context: TaskContext<FileDeleteParams>): Promise<FileDeleteResult> {\n const { params, exec } = context;\n const { path, recursive = false, force = false } = params;\n const p = Path.new(path);\n\n if (!(await p.exists())) {\n return {\n success: true,\n };\n }\n\n const args: string[] = [];\n if (recursive) {\n args.push('-r');\n }\n // The 'force' flag for rm is for ignoring nonexistent files and overriding permissions.\n // We handle non-existence above. The permission override is a useful side-effect.\n if (force) {\n args.push('-f');\n }\n args.push('--'); // End of options, ensures paths starting with '-' are not treated as options.\n args.push(path);\n\n const { success } = await exec(['rm', ...args]);\n\n return {\n success,\n };\n}\n\nexport default task(run, { name: 'core.file.delete', description: 'File delete.' });\n","import { task, type TaskContext } from '../../runtime';\nimport { dirname } from 'path';\n\nexport interface FileLinkParams {\n /** Path the symlink should point TO (target). */\n target: string;\n /** Path of the symlink itself. */\n link: string;\n /** Overwrite existing link/file if necessary (default true) */\n force?: boolean;\n /** Use sudo when creating/modifying (default false) */\n sudo?: boolean;\n}\n\nexport interface FileLinkResult {\n changed: boolean;\n success: boolean;\n}\n\n/**\n * Ensures a symbolic link exists at `link` pointing to `target`.\n * If link already exists with correct target, this is a no-op.\n */\nasync function run(context: TaskContext<FileLinkParams>): Promise<FileLinkResult> {\n const { params, exec } = context;\n const { target, link, force = true, sudo = false } = params;\n\n // Check existing symlink\n const { stdout: statOut, success: statOk } = await exec(\n ['readlink', '-f', link],\n );\n\n if (statOk && statOut.trim() === target) {\n return { changed: false, success: true };\n }\n\n // Ensure parent directory exists\n const parentDir = dirname(link);\n await exec(['mkdir', '-p', parentDir], { sudo });\n\n const cmd = [sudo ? 'sudo' : '', 'ln', '-s', force ? '-f' : '', target, link].filter(Boolean);\n const { success } = await exec(cmd);\n return { changed: true, success };\n}\n\nexport default task(run, {\n name: 'core.file.link',\n description: 'Ensures a symbolic link exists pointing to a target.'\n});\n","import os from 'os';\n\nexport const KeySequence = {\n EOL: os.EOL,\n CRLF: '\\r\\n',\n CR: '\\r',\n LF: '\\n',\n NEWLINE: '\\n',\n CTRL_C: '\\x03',\n CTRL_D: '\\x04',\n};\n","import { KeySequence } from '../../keyboard';\nimport { task, type TaskContext } from '../../runtime';\nimport { dirname } from 'path';\nimport type { FileGrepResult } from './grep';\nimport grep from './grep';\n\nexport interface FileEditParams {\n file: string;\n state?: 'present' | 'absent';\n backup?: boolean;\n sudo?: boolean;\n\n // append-mode\n append?: string;\n\n // line-mode\n line?: string;\n regex?: string;\n after?: string;\n before?: string;\n\n // block-mode\n block?: string; // use \\n for newlines\n marker_begin?: string; // default markers\n marker_end?: string;\n}\n\nexport interface FileEditResult {\n changed: boolean;\n success: boolean;\n}\n\nfunction escapeForSed(str: string): string {\n return str.replace(/[\\\\/\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n}\n\nasync function ensureFile(context: TaskContext<any>, file: string, sudo: boolean) {\n const { exec } = context;\n await exec(['mkdir', '-p', dirname(file)], { sudo });\n await exec(['touch', file], { sudo });\n}\n\n/**\n * Edits a file.\n *\n * File editing is done in one of two modes:\n *\n * 1. **Append Mode**: If `append` is defined, the task will append the given content to the end of the file.\n * 2. **Line/Block Mode**: If `line` or `block` is defined, the task will modify the file contents using the provided parameters.\n *\n * In Line/Block mode, the following rules apply:\n *\n * - If `line` is defined, the task will search for the first occurrence of the line and remove it.\n * If `regex` is defined, the task will search for the first occurrence of the line that matches the regex and remove it.\n * If `after` is defined, the task will insert the line after the first occurrence of the line that matches the regex.\n * If `before` is defined, the task will insert the line before the first occurrence of the line that matches the regex.\n * - If `block` is defined, the task will replace the first occurrence of the block marker with the new block content.\n * The block marker is defined by `marker_begin` and `marker_end` (default: `# BEGIN HOSTCTL BLOCK` and `# END HOSTCTL BLOCK`).\n *\n * The `state` parameter determines whether the file should exist or not. If `state === 'absent'`, the task will delete the file.\n * If `state === 'present'`, the task will ensure the file exists and has the correct contents.\n *\n * The `backup` parameter determines whether to create a backup of the file before modifying it.\n *\n * === Usage examples ===\n *\n * 1. Append a line (idempotent; no duplicates)\n * hostctl run core.file.edit file:/etc/profile line:\"export EDITOR=vim\"\n *\n * 2. Always append raw text to end of file\n * hostctl run core.file.edit file:/etc/profile append:\"export EDITOR=vim\"\n *\n * 3. Insert a line AFTER an anchor\n * hostctl run core.file.edit file:/etc/sshd_config \\\n * line:\"PermitRootLogin no\" after:\"# Authentication:\"\n *\n * 4. Insert a line BEFORE an anchor\n * hostctl run core.file.edit file:/etc/ssh/sshd_config \\\n * line:\"Match User root\" before:\"Subsystem sftp\"\n *\n * 5. Replace the first line matching a regex\n * hostctl run core.file.edit file:/etc/default/app \\\n * regex:\"^PORT=\" line:\"PORT=8080\"\n *\n * 6. Ensure a multi-line block is present\n * hostctl run core.file.edit file:/etc/my.conf \\\n * block:\"alpha\\\\nbeta\" marker_begin:\"# BEGIN MY\" marker_end:\"# END MY\"\n *\n * 7. Remove that block\n * hostctl run core.file.edit file:/etc/my.conf \\\n * block:\"alpha\\\\nbeta\" marker_begin:\"# BEGIN MY\" marker_end:\"# END MY\" state:absent\n */\nasync function runFn(context: TaskContext<FileEditParams>): Promise<FileEditResult> {\n const { params, exec, info, run } = context;\n const {\n file,\n state = 'present',\n backup = false,\n sudo = false,\n append,\n line,\n regex,\n after,\n before,\n block,\n marker_begin = '# BEGIN HOSTCTL BLOCK',\n marker_end = '# END HOSTCTL BLOCK',\n } = params;\n\n const backupPath = backup ? `${file}.bak` : null;\n\n if (state === 'present') {\n await ensureFile(context, file, sudo);\n }\n\n const sudoPrefix = sudo ? ['sudo'] : [];\n\n // append-mode\n if (append !== undefined) {\n const stdin = `${append}${KeySequence.NEWLINE}${KeySequence.CTRL_D}`;\n const { success } = await exec(['tee', '-a', file], { sudo, stdin });\n return { changed: true, success };\n }\n\n // block-mode if block defined\n if (block !== undefined) {\n const beginEsc = escapeForSed(marker_begin);\n const endEsc = escapeForSed(marker_end);\n const body = block.replace(/\\\\n/g, '\\n');\n\n const { success: exists } = await exec(['grep', '-Fxq', marker_begin, file]);\n\n if (state === 'absent') {\n if (!exists) return { changed: false, success: true };\n const sedExpr = `/${beginEsc}/,/${endEsc}/d`;\n const { success } = await exec([...sudoPrefix, 'sed', '-i', '-e', sedExpr, file], { sudo });\n return { changed: true, success };\n }\n\n // state === 'present'\n const fullBlock = `${marker_begin}\\n${body}\\n${marker_end}`;\n\n if (exists) {\n const sedGetBlock = `sed -n '/${beginEsc}/,/${endEsc}/p' \"${file}\"`;\n const currentBlockResult = await exec(['sh', '-c', sedGetBlock]);\n // Normalize line endings for comparison\n if (currentBlockResult.stdout.trim().replace(/\\r\\n/g, '\\n') === fullBlock) {\n return { changed: false, success: true };\n }\n // Block exists but content is different, so remove it before adding the new one\n const sedExpr = `/${beginEsc}/,/${endEsc}/d`;\n await exec([...sudoPrefix, 'sed', '-i', '-e', sedExpr, file], { sudo });\n }\n\n // To append, we use a temp file to avoid quoting issues\n const tempFile = `/tmp/hostctl-block-${Date.now()}`;\n await exec([...sudoPrefix, 'sh', '-c', `printf '%s' \"$1\" > \"$2\"`, '_', fullBlock, tempFile], { sudo });\n\n const script = `\n # Add a newline if file is not empty and does not end with a newline\n if [ -s \\\"$2\\\" ] && [ \\\"$(tail -c 1 <\\\"$2\\\")\\\" ]; then\n printf '\\\\n' >> \\\"$2\\\";\n fi;\n # Append the content of the temp file\n cat \\\"$1\\\" >> \\\"$2\\\";\n `;\n const { success } = await exec([...sudoPrefix, 'sh', '-c', script, '_', tempFile, file], { sudo });\n\n // Clean up the temp file\n await exec([...sudoPrefix, 'rm', tempFile], { sudo });\n\n return { changed: true, success };\n }\n\n const effectiveAfter = after;\n const effectiveBefore = before;\n\n // line / regex mode\n if (line !== undefined || regex !== undefined) {\n if (state === 'present') {\n if (!line) {\n info('`line` parameter is required for state: present');\n return { changed: false, success: false };\n }\n\n const grepResult: FileGrepResult = await context.run(\n grep({\n file,\n pattern: line,\n }),\n );\n\n if (regex) {\n const { found: regexExists } = await context.run(\n grep({\n file,\n pattern: regex,\n }),\n );\n if (regexExists && !grepResult.found) {\n const escapedLine = line.replace(/\\\\/g, '\\\\\\\\').replace(/[&/]/g, '\\\\$&');\n const sedCmd = `sed -i -e '/${regex}/c\\\\${escapedLine}' \"${file}\"`;\n info(`Running sed command: ${sedCmd}`);\n const result = await exec([...sudoPrefix, 'sh', '-c', sedCmd], { sudo });\n if (!result.success) {\n info(`sed command failed. stderr: ${result.stderr}`);\n }\n return { changed: true, success: result.success };\n }\n }\n\n if (grepResult.found) {\n return { changed: false, success: true };\n }\n\n const escapedLineForSed = line.replace(/\\\\/g, '\\\\\\\\').replace(/[&/]/g, '\\\\$&');\n if (effectiveBefore) {\n const beforeEsc = escapeForSed(effectiveBefore);\n const insertCmd = `sed -i -e '/${beforeEsc}/i ${escapedLineForSed}' \"${file}\"`;\n info(`Running sed command: ${insertCmd}`);\n const result = await exec([...sudoPrefix, 'sh', '-c', insertCmd], { sudo });\n if (!result.success) {\n info(`sed command failed. stderr: ${result.stderr}`);\n }\n return { changed: true, success: result.success };\n } else if (effectiveAfter) {\n const afterEsc = escapeForSed(effectiveAfter);\n const insertCmd = `sed -i -e '/${afterEsc}/a ${escapedLineForSed}' \"${file}\"`;\n info(`Running sed command: ${insertCmd}`);\n const result = await exec([...sudoPrefix, 'sh', '-c', insertCmd], { sudo });\n if (!result.success) {\n info(`sed command failed. stderr: ${result.stderr}`);\n }\n return { changed: true, success: result.success };\n } else {\n // No specific insertion point provided; append the line to the end of the file\n const stdin = `${line}${KeySequence.NEWLINE}${KeySequence.CTRL_D}`;\n info(`Appending line with tee: '${line}'`);\n const result = await exec([...sudoPrefix, 'tee', '-a', file], { sudo, stdin });\n if (!result.success) {\n info(`tee command failed. stderr: ${result.stderr}`);\n }\n return { changed: true, success: result.success };\n }\n } else {\n // state === 'absent'\n const searchPattern = regex ?? (line ? escapeForSed(line) : null);\n if (!searchPattern) return { changed: false, success: true };\n\n const { success: exists } = await exec([...sudoPrefix, 'grep', '-Eq', searchPattern, file]);\n if (!exists) return { changed: false, success: true };\n\n const sedExpr = `/${searchPattern}/d`;\n info(`Running sed command: sed -i -e '${sedExpr}' ${file}`);\n const result = await exec([...sudoPrefix, 'sed', '-i', '-e', sedExpr, file], { sudo });\n if (!result.success) {\n info(`sed command failed. stderr: ${result.stderr}`);\n }\n return { changed: true, success: result.success };\n }\n }\n\n return { changed: false, success: true };\n}\n\nexport default task(runFn, {\n name: 'core.file.edit',\n description: 'Edit files: ensure lines/blocks present or absent with optional regex matching.',\n});\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface FileGrepParams {\n /** Path to the file to search */\n file: string;\n /** Pattern to search for (POSIX extended regex passed to grep -E) */\n pattern: string;\n /** If true, perform a case-insensitive match (adds -i flag). Default: false */\n ignore_case?: boolean;\n /** If true, show only lines that do NOT match (grep -v). Default: false */\n invert_match?: boolean;\n /** Match whole words only (grep -w). Default: false */\n whole_word?: boolean;\n /** Treat pattern as a fixed string, not regex (grep -F). Default: false */\n fixed_string?: boolean;\n /** Include line numbers in output (grep -n). Default: false */\n line_numbers?: boolean;\n /** Lines of context before each match (grep -B) */\n before_context?: number;\n /** Lines of context after each match (grep -A) */\n after_context?: number;\n /** Lines of context before & after (grep -C) */\n context?: number;\n /** Stop reading after NUM matching lines (grep -m) */\n max_count?: number;\n /** Return the matching lines in the result payload. Default: false */\n return_lines?: boolean;\n}\n\nexport interface FileGrepResult {\n /** True if one or more matches were found */\n found: boolean;\n /** Number of matching lines */\n count: number;\n /** Matching lines (included only when return_lines=true) */\n lines?: string[];\n}\n\n/**\n * Searches a file for a pattern using `grep` and reports whether it was found and the number of matches.\n *\n * Equivalent shell command:\n * grep -E -c PATTERN FILE\n *\n * If no matches are found, `count` will be 0 and `found` will be false.\n */\nasync function run(context: TaskContext<FileGrepParams>): Promise<FileGrepResult> {\n const { params, exec } = context;\n const {\n file,\n pattern,\n ignore_case = false,\n invert_match = false,\n whole_word = false,\n fixed_string = false,\n line_numbers = false,\n before_context,\n after_context,\n context: contextLines,\n max_count,\n return_lines = false,\n } = params;\n\n const grepArgs: string[] = ['grep'];\n\n // Choose regex type flags\n if (fixed_string) {\n grepArgs.push('-F');\n } else {\n grepArgs.push('-E');\n }\n\n // Counting vs content output\n const needContent = return_lines || line_numbers || before_context !== undefined || after_context !== undefined || contextLines !== undefined;\n if (!needContent) {\n grepArgs.push('-c');\n }\n\n if (ignore_case) grepArgs.push('-i');\n if (invert_match) grepArgs.push('-v');\n if (whole_word) grepArgs.push('-w');\n if (line_numbers) grepArgs.push('-n');\n if (contextLines !== undefined) grepArgs.push('-C', String(contextLines));\n if (before_context !== undefined) grepArgs.push('-B', String(before_context));\n if (after_context !== undefined) grepArgs.push('-A', String(after_context));\n if (max_count !== undefined) grepArgs.push('-m', String(max_count));\n\n grepArgs.push(pattern, file);\n\n const { success, stdout } = await exec(grepArgs);\n\n if (!needContent) {\n // stdout is a count string (may be empty if no matches)\n const count = stdout ? parseInt(stdout.trim(), 10) : 0;\n return { found: success, count };\n }\n\n const lines = stdout\n ? stdout.trim().split('\\n').map((l) => l.replace(/\\r$/, '')).filter((l) => l.length > 0)\n : [];\n return {\n found: success,\n count: lines.length,\n lines: return_lines ? lines : undefined,\n };\n}\n\nexport default task<FileGrepParams, FileGrepResult>(run, {\n name: 'core.file.grep',\n description: 'Search for a pattern in a file and return presence and count.',\n});\n","import clone, { type GitCloneParams, type GitCloneResult } from './clone';\nimport pull, { type GitPullParams, type GitPullResult } from './pull';\nimport checkout, { type GitCheckoutParams, type GitCheckoutResult } from './checkout';\n\nexport {\n clone,\n type GitCloneParams,\n type GitCloneResult,\n pull,\n type GitPullParams,\n type GitPullResult,\n checkout,\n type GitCheckoutParams,\n type GitCheckoutResult,\n};\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GitCloneParams {\n repo: string;\n dir: string;\n}\n\nexport interface GitCloneResult {\n success: boolean;\n}\n\n/**\n * @param {repo: string, dir: string} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<GitCloneParams>): Promise<GitCloneResult> {\n const { params, exec } = context;\n const { repo, dir } = params;\n\n // Build the git clone command\n const commandArray = ['git', 'clone', repo, dir];\n\n const { success } = await exec(commandArray);\n\n return {\n success,\n };\n}\n\nexport default task(run, { name: 'core.git.clone', description: 'Git clone.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GitPullParams {\n /** The directory of the git repository on the host. */\n directory: string;\n /** Optional: Whether to use --rebase. Defaults to false. */\n rebase?: boolean;\n /** Optional: The remote to pull from. Defaults to 'origin'. */\n remote?: string;\n /** Optional: The branch to pull. Defaults to the current branch. */\n branch?: string;\n}\n\nexport interface GitPullResult {\n /** Indicates whether the pull operation was successful. */\n success: boolean;\n /** Error message if the pull operation failed. */\n error?: string;\n}\n\n/**\n * Pulls the latest changes for a git repository.\n */\nasync function run(context: TaskContext<GitPullParams>): Promise<GitPullResult> {\n const { params, exec } = context;\n const { directory, rebase = false, remote = 'origin', branch } = params;\n\n const command = ['git', '-C', directory, 'pull'];\n if (rebase) {\n command.push('--rebase');\n }\n command.push(remote);\n if (branch) {\n command.push(branch);\n }\n\n try {\n const { success } = await exec(command);\n return { success };\n } catch (error: any) {\n return {\n success: false,\n error: error.message,\n };\n }\n}\n\nexport default task(run, { name: 'core.git.pull', description: 'Git pull.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GitCheckoutParams {\n /** The directory of the git repository on the host. */\n directory: string;\n /** The branch, tag, or commit hash to checkout. */\n target: string;\n /** Optional: If true, creates a new branch named <target> before checking out. Defaults to false. */\n new_branch?: boolean;\n}\n\nexport interface GitCheckoutResult {\n /** Indicates whether the checkout operation was successful. */\n success: boolean;\n /** Error message if the checkout operation failed. */\n error?: string;\n}\n\n/**\n * Checks out a specific branch, tag, or commit in a git repository.\n */\nasync function run(context: TaskContext<GitCheckoutParams>): Promise<GitCheckoutResult> {\n const { params, exec } = context;\n const { directory, target, new_branch: newBranch = false } = params;\n\n const command = ['git', '-C', directory, 'checkout'];\n\n if (newBranch) {\n command.push('-b');\n }\n command.push(target);\n\n try {\n const { success } = await exec(command);\n return { success };\n } catch (error: any) {\n return {\n success: false,\n error: error.message,\n };\n }\n}\n\nexport default task(run, { name: 'core.git.checkout', description: 'Git checkout.' });\n","import create, { type GroupCreateParams, type GroupCreateResult } from './create';\nimport del, { type GroupDeleteParams, type GroupDeleteResult } from './delete';\nimport exists, { type GroupExistsParams, type GroupExistsResult } from './exists';\nimport list, { type GroupListParams, type GroupListResult, type GroupInfo } from './list';\nimport modify, { type GroupModifyParams, type GroupModifyResult } from './modify';\n\nexport {\n create,\n del as delete,\n exists,\n list,\n modify,\n type GroupCreateParams,\n type GroupCreateResult,\n type GroupDeleteParams,\n type GroupDeleteResult,\n type GroupExistsParams,\n type GroupExistsResult,\n type GroupListParams,\n type GroupListResult,\n type GroupInfo,\n type GroupModifyParams,\n type GroupModifyResult,\n};\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GroupExistsParams {\n group: string;\n}\n\nexport interface GroupExistsResult {\n exists: boolean;\n}\n\n/**\n * @param {group: string} params\n * @returns {\n * exists: boolean\n * }\n */\nasync function run(context: TaskContext<GroupExistsParams>): Promise<GroupExistsResult> {\n const { params, exec } = context;\n const { group } = params;\n\n // Check if group exists using getent\n const commandArray = ['getent', 'group', group];\n\n const { success: exists } = await exec(commandArray);\n\n return {\n exists,\n };\n}\n\nexport default task(run, { name: 'core.group.exists', description: 'Group exists.' });\n","import { task, type TaskContext } from '../../runtime';\nimport exists from './exists';\n\nexport interface GroupCreateParams {\n group: string;\n /** Whether to run the command with sudo. Defaults to true. */\n sudo?: boolean;\n}\n\nexport interface GroupCreateResult {\n success: boolean;\n}\n\n/**\n * @param {group: string} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<GroupCreateParams>): Promise<GroupCreateResult> {\n const { params, run: runTask, exec } = context;\n const { group, sudo = true } = params;\n\n // First check if group exists\n const groupExistsResult = await runTask(exists({ group }));\n\n // If group already exists, return success\n if (groupExistsResult.exists) {\n return { success: true };\n }\n\n // Create the group using groupadd\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('groupadd', group);\n\n const { success } = await exec(commandArray, { sudo });\n\n return {\n success,\n };\n}\n\nexport default task(run, { name: 'core.group.create', description: 'Creates a user group on the system.' });\n","import { type TaskContext, task } from '../../runtime';\n\nexport interface GroupDeleteParams {\n group: string;\n /** Whether to run the command with sudo. Defaults to true. */\n sudo?: boolean;\n}\n\nexport interface GroupDeleteResult {\n success: boolean;\n error?: string;\n}\n\nasync function run(context: TaskContext<GroupDeleteParams>): Promise<GroupDeleteResult> {\n const { params, exec } = context;\n const { group, sudo = true } = params;\n\n const command: string[] = [];\n if (sudo) {\n command.push('sudo');\n }\n command.push('groupdel', group);\n\n const result = await exec(command, { sudo });\n\n if (result.success) {\n return { success: true };\n }\n\n // `groupdel` returns 6 if group doesn't exist. Treat as success for idempotency.\n if (result.exitCode === 6) {\n return { success: true };\n }\n\n return { success: false, error: [result.stdout, result.stderr].join('\\n') };\n}\n\nexport default task(run, { name: 'core.group.delete', description: 'Deletes a user group from the system.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GroupInfo {\n name: string;\n gid: number;\n}\n\nexport interface GroupListParams {}\n\nexport interface GroupListResult {\n success: boolean;\n groups: GroupInfo[];\n}\n\n/**\n * Lists all user groups on the system.\n * @returns { success: boolean, groups: { name: string, gid: number }[] }\n */\nasync function run(context: TaskContext<GroupListParams>): Promise<GroupListResult> {\n const { exec } = context;\n\n const { stdout, success } = await exec('getent group');\n\n if (!success) {\n return { success: false, groups: [] };\n }\n\n const groups = stdout\n .split('\\n')\n .filter((line) => line.includes(':')) // Ensure the line has the expected format before parsing\n .map((line) => {\n const [name, , gid] = line.split(':');\n // Add a check for valid parsed data\n if (name && gid) {\n return { name, gid: parseInt(gid, 10) };\n }\n return null;\n })\n .filter((g): g is GroupInfo => g !== null && !isNaN(g.gid)); // Filter out nulls and ensure GID is a number\n\n return { success: true, groups };\n}\n\nexport default task(run, {\n name: 'core.group.list',\n description: 'Lists user groups on the system, including their GID.',\n});\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GroupModifyParams {\n /** The current name of the group. */\n group: string;\n /** The new name for the group. */\n new_name?: string;\n /** The new numerical value of the group's ID. */\n gid?: number;\n /** Whether to run the command with sudo. Defaults to true. */\n sudo?: boolean;\n}\n\nexport interface GroupModifyResult {\n success: boolean;\n changed: boolean;\n error?: string;\n}\n\nasync function run(context: TaskContext<GroupModifyParams>): Promise<GroupModifyResult> {\n const { params, exec } = context;\n const { group, new_name, gid, sudo = true } = params;\n\n if (gid) {\n const command = ['groupmod', '-g', String(gid), group];\n if (sudo) {\n command.unshift('sudo');\n }\n const { success, stdout, stderr } = await exec(command, { sudo });\n if (!success) {\n return { success: false, changed: false, error: [stdout, stderr].join('\\n') };\n }\n return { success: true, changed: true };\n }\n\n if (new_name) {\n const command = ['groupmod', '-n', new_name, group];\n if (sudo) {\n command.unshift('sudo');\n }\n const { success, stdout, stderr } = await exec(command, { sudo });\n if (!success) {\n return { success: false, changed: false, error: [stdout, stderr].join('\\n') };\n }\n return { success: true, changed: true };\n }\n\n return { success: true, changed: false };\n}\n\nexport default task(run, {\n name: 'core.group.modify',\n description: 'Modify a user group on the system.',\n});\n","export * from './types';\nexport { default as info, type HostInfoResult } from './info';\nexport { default as summary, type HostSummaryResult } from './summary';\nexport { default as os, type OsDetailsResult } from './os';\nexport { default as hostname, type HostnameResult, type HostnameParams } from './hostname';\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface HostnameParams {\n new_name?: string;\n}\n\nexport interface HostnameResult {\n hostname: string;\n updated: boolean;\n}\n\n/**\n * @param {new_name?: string} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<HostnameParams>): Promise<HostnameResult> {\n const { params, exec } = context;\n const { new_name } = params;\n\n if (!new_name) {\n // Get hostname using hostname command\n const { stdout: hostname } = await exec(['hostname']);\n return {\n hostname: hostname.trim(),\n updated: false,\n };\n } else {\n // Set hostname using hostnamectl\n const commandArray = ['sudo', 'hostnamectl', 'set-hostname', new_name];\n\n const { success } = await exec(commandArray);\n\n return {\n hostname: new_name,\n updated: success,\n };\n }\n}\n\nexport default task(run, { name: 'core.host.hostname', description: 'Gets or sets the hostname of the system.' });\n","import { match, P } from 'ts-pattern';\nimport { task, type TaskContext } from '../../runtime';\n\ninterface OsInfo {\n idLike: string;\n id: string;\n version: string;\n}\n\nexport interface OsDetailsResult {\n success: boolean;\n error?: string;\n family: 'bsd' | 'darwin' | 'linux' | 'solaris' | 'windows' | 'unknown';\n /** The general OS type, e.g., 'debian', 'fedora', 'osx'. Derived from ID_LIKE in /etc/os-release for Linux. */\n os: string;\n /** The specific OS variant, e.g., 'ubuntu', 'arch'. Derived from ID in /etc/os-release for Linux. */\n variant: string;\n /** The OS version string. */\n version: string;\n}\n\nasync function getOsReleaseInfo(exec: TaskContext['exec']): Promise<OsInfo> {\n try {\n const { stdout: osRelease } = await exec(['cat', '/etc/os-release']);\n\n const idMatch = osRelease.match(/^ID=(.*?)$/im);\n const idLikeMatch = osRelease.match(/^ID_LIKE=(.*?)$/im);\n const versionIdMatch = osRelease.match(/^VERSION_ID=(.*)$/im);\n const buildIdMatch = osRelease.match(/^BUILD_ID=(.*)$/im); // Some distros like Arch use BUILD_ID\n\n if (idMatch) {\n const id = idMatch[1].trim().replace(/\"/g, '');\n const idLike = idLikeMatch ? idLikeMatch[1].trim().replace(/\"/g, '') : id;\n const version =\n (versionIdMatch && versionIdMatch[1].trim().replace(/\"/g, '')) ||\n (buildIdMatch && buildIdMatch[1].trim().replace(/\"/g, '')) ||\n 'unknown';\n\n return {\n idLike,\n id,\n version,\n };\n }\n\n return {\n idLike: 'unknown',\n id: 'unknown',\n version: 'unknown',\n };\n } catch (error) {\n // If cat /etc/os-release fails or parsing fails, return unknowns\n return {\n idLike: 'unknown',\n id: 'unknown',\n version: 'unknown',\n };\n }\n}\n\n/**\n * Determines the operating system family, specific OS, variant, and version.\n * @returns {OsDetailsResult}\n */\nexport default task(\n async function run(context: TaskContext): Promise<OsDetailsResult> {\n try {\n const { exec } = context;\n const { success: ostypeSuccess, stdout: ostypeOutput, stderr: ostypeStderr } = await exec(['bash', '-c', 'echo $OSTYPE']);\n if (!ostypeSuccess) {\n throw new Error(`Failed to get OSTYPE: ${ostypeStderr}`);\n }\n\n const family = (await match(ostypeOutput.trim().toLowerCase())\n .with(P.string.startsWith('solaris'), () => 'solaris')\n .with(P.string.startsWith('darwin'), () => 'darwin')\n .with(P.string.startsWith('linux'), () => 'linux') // Covers linux-gnu, linux-musl etc.\n .with(P.string.startsWith('bsd'), () => 'bsd')\n .with(P.string.startsWith('freebsd'), () => 'bsd') // $OSTYPE can be 'freebsdX.Y'\n .with(P.string.startsWith('msys'), () => 'windows')\n .with(P.string.startsWith('cygwin'), () => 'windows')\n .with(P.string.startsWith('mingw'), () => 'windows')\n .otherwise(async () => {\n const { stdout: unameOutput } = await exec(['uname']);\n const unameFamily = match(unameOutput.trim().toLowerCase())\n .with(P.string.startsWith('sunos'), () => 'solaris')\n .with(P.string.startsWith('darwin'), () => 'darwin')\n .with(P.string.startsWith('linux'), () => 'linux')\n .with(P.string.startsWith('freebsd'), () => 'bsd')\n .with(P.string.startsWith('openbsd'), () => 'bsd')\n .with(P.string.startsWith('netbsd'), () => 'bsd')\n // Add other uname outputs for Windows if necessary, though $OSTYPE should cover it.\n .otherwise(() => 'unknown') as OsDetailsResult['family'];\n return unameFamily;\n })) as OsDetailsResult['family'];\n\n const [osIdLike, osId, osVersion] = await match(family)\n .with('bsd', async () => {\n // For BSD, try to get version from uname -r\n const { stdout: unameROutput } = await exec(['uname', '-r']);\n return [family, family, unameROutput.trim()];\n })\n .with('darwin', async () => {\n // For Darwin, get product version\n const { stdout: swVersOutput } = await exec(['sw_vers', '-productVersion']);\n return [family, family, swVersOutput.trim()];\n })\n .with('linux', async () => {\n const { idLike, id, version } = await getOsReleaseInfo(exec);\n return [idLike, id, version];\n })\n // Solaris and Windows might need specific commands if /etc/os-release equivalent or $OSTYPE isn't enough\n .with('solaris', async () => {\n const { stdout: unameROutput } = await exec(['uname', '-r']);\n return ['solaris', 'solaris', unameROutput.trim()];\n })\n .with('windows', () => ['windows', 'windows', 'unknown']) // Placeholder, windows version detection is complex\n .otherwise(() => ['unknown', 'unknown', 'unknown']);\n\n return {\n success: true,\n family,\n os: osIdLike.toLowerCase(),\n variant: osId.toLowerCase(),\n version: osVersion,\n };\n } catch (error: any) {\n return {\n success: false,\n error: error.message,\n family: 'unknown',\n os: 'unknown',\n variant: 'unknown',\n version: 'unknown',\n };\n }\n },\n { name: 'core.host.os' },\n);\n","import { task, type TaskContext } from '../../runtime';\nimport { type HostInfo, type LSBRelease } from './types';\nimport getHostname from './hostname';\nimport getOS from './os';\n\nexport interface HostInfoResult {\n host: HostInfo;\n}\n\n/**\n * @returns {\n * host: HostInfo\n * }\n */\nasync function run(context: TaskContext): Promise<HostInfoResult> {\n const { run: runTask, exec } = context;\n\n // Get hostname\n const hostnameResult = await runTask(getHostname({}));\n const name = hostnameResult.hostname;\n\n // Get OS info\n const os = await runTask(getOS({}));\n\n // Get LSB release info\n const { stdout: lsbOutput } = await exec(['lsb_release', '-a']);\n const lsb_release = lsbOutput\n .split('\\n')\n .filter(Boolean)\n .reduce((acc, line) => {\n const [key, ...valueParts] = line.split(':');\n const value = valueParts.join(':').trim();\n // Ensure the keys match LSBRelease interface for type safety\n acc[key.trim() as keyof LSBRelease] = value;\n return acc;\n }, {} as LSBRelease);\n\n // Get CPU info in JSON format\n const { stdout: lscpuOutput } = await exec(['lscpu', '-J']);\n const lscpu = JSON.parse(lscpuOutput).lscpu;\n\n return {\n host: {\n name,\n os: {\n family: os.family,\n base_os: os.family, // Assuming base_os is also the OS family\n os: os.os, // This is the specific OS like 'debian'\n version: os.version,\n },\n lsb_release,\n lscpu,\n },\n };\n}\n\nexport default task(run, { name: 'core.host.info', description: 'Host info.' });\n","import { task, type TaskContext } from '../../runtime';\nimport { type HostSummary } from './types';\nimport info from './info';\n\nexport interface HostSummaryResult {\n host: HostSummary;\n}\n\n/**\n * @returns {\n * host: HostSummary\n * }\n */\nasync function run(context: TaskContext): Promise<HostSummaryResult> {\n const { run: runTask } = context;\n\n // Get full host info\n const infoResult = await runTask(info({}));\n const hostInfo = infoResult.host;\n\n // Extract CPU info from lscpu data\n // Ensure lscpu array and its children are accessed safely\n const cpuModelEntry = hostInfo.lscpu?.find((entry) => entry.field === 'Model name:');\n const cpu = cpuModelEntry?.data ?? hostInfo.lscpu[2]?.children?.[0]?.data ?? 'Unknown';\n\n return {\n host: {\n name: hostInfo.name,\n os: hostInfo.os,\n cpu,\n },\n };\n}\n\nexport default task(run, { name: 'core.host.summary', description: 'Host summary.' });\n","// src/core/pkg/index.ts\nimport install from './install';\nimport remove from './remove';\nimport update from './update';\nimport info from './info';\nimport isInstalled from './is_installed';\n\n// Export types to make them available when 'pkg' module is used\nexport type { PkgInstallParams, PkgInstallResult, PkgRemoveParams, PkgRemoveResult, PkgUpdateParams, PkgUpdateResult, PkgIsInstalledParams, PkgIsInstalledResult } from './types';\nexport type { PkgInfoParams, PkgInfoResult } from './info';\n\n// Export tasks\nexport { install, remove, update, info, isInstalled };\n","import { task, type TaskContext } from '../../../runtime';\nimport type { PkgInstallParams, PkgInstallResult } from '../types';\n\n/**\n * Installs a package using pacman on Arch Linux\n * @param {package: string | string[]} params\n * @returns {PkgInstallResult}\n */\nasync function run(context: TaskContext<PkgInstallParams>): Promise<PkgInstallResult> {\n const { params: taskParams, exec } = context;\n const { package: pkg, sudo = true } = taskParams;\n const packages = Array.isArray(pkg) ? pkg : [pkg];\n const commandArray = [sudo ? 'sudo' : '', 'pacman', '-Syu', '--noconfirm', '--needed', ...packages].filter(Boolean);\n\n const { success, stdout, stderr } = await exec(commandArray, { sudo });\n if (!success) {\n return { success: false, error: `${stdout}\\n${stderr}` };\n }\n return { success };\n}\n\nexport const install = task(run);\n","import { type TaskContext, type LogLevel, task } from '../../runtime';\nimport { Verbosity } from '../../app';\nimport os from '../host/os';\n// Assuming these paths correctly resolve to the index.ts files in their respective directories\nimport { install as installPkgTask, info as pkgInfoTask } from '../pkg';\n\n// Define empty params interface as this task doesn't take direct parameters\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface RebootNeededParams {}\n\nexport interface RebootNeededResult {\n reboot_needed: boolean;\n success: boolean;\n error?: string;\n}\n\n/**\n * Checks if the system needs to be rebooted.\n * It handles Debian/Ubuntu (using needrestart) and Fedora (using dnf-utils/needs-restarting).\n * Required tools (needrestart, dnf-utils) are installed if missing.\n * @returns {Promise<RebootNeededResult>} - An object indicating if a reboot is needed and the success of the check.\n */\nasync function run(\n context: TaskContext<RebootNeededParams>, // Params can be empty\n): Promise<RebootNeededResult> {\n const { run: runTask, exec, log } = context;\n const osDetails = await runTask(os());\n\n if (!osDetails.success) {\n log(Verbosity.ERROR as LogLevel, `Failed to get OS details: ${osDetails.error}`);\n return { reboot_needed: false, success: false, error: `Failed to get OS details: ${osDetails.error}` };\n }\n\n if (typeof osDetails?.os !== 'string' || osDetails.os === 'unknown') {\n const errorMsg = 'Could not determine OS from osDetails.';\n log(Verbosity.ERROR as LogLevel, errorMsg);\n return { reboot_needed: false, success: false, error: errorMsg };\n }\n const baseOs = osDetails.os;\n\n if (baseOs.match(/debian|ubuntu/)) {\n let pkgInfoResult = await runTask(pkgInfoTask({ package: 'needrestart' }));\n if (!pkgInfoResult.success) {\n const errorMsg = `Failed to check if needrestart is installed: ${pkgInfoResult.error}`;\n log(Verbosity.ERROR as LogLevel, errorMsg);\n return { reboot_needed: false, success: false, error: errorMsg };\n }\n if (!pkgInfoResult.installed) {\n log(Verbosity.INFO as LogLevel, 'needrestart package not found, attempting to install.');\n const installResult = await runTask(installPkgTask({ package: 'needrestart' }));\n if (!installResult.success) {\n const errorMsg = `Failed to install needrestart: ${installResult.error}`;\n log(Verbosity.ERROR as LogLevel, errorMsg);\n return { reboot_needed: false, success: false, error: errorMsg };\n }\n log(Verbosity.INFO as LogLevel, 'needrestart installed successfully.');\n }\n\n const { success, stdout, stderr } = await exec(['sudo', 'needrestart', '-b']);\n if (!success) {\n return { reboot_needed: false, success: false, error: `Failed to run needrestart: ${stdout}\\n${stderr}` };\n }\n const rebootIsNeeded = stdout.includes('NEEDRESTART-KSTA: 1');\n return { reboot_needed: rebootIsNeeded, success: true };\n }\n\n if (baseOs === 'fedora') {\n let pkgInfoResult = await runTask(pkgInfoTask({ package: 'dnf-utils' }));\n if (!pkgInfoResult.success) {\n const errorMsg = `Failed to check if dnf-utils is installed: ${pkgInfoResult.error}`;\n log(Verbosity.ERROR as LogLevel, errorMsg);\n return { reboot_needed: false, success: false, error: errorMsg };\n }\n if (!pkgInfoResult.installed) {\n log(Verbosity.INFO as LogLevel, 'dnf-utils package not found, attempting to install.');\n const installResult = await runTask(installPkgTask({ package: 'dnf-utils' }));\n if (!installResult.success) {\n const errorMsg = `Failed to install dnf-utils: ${installResult.error}`;\n log(Verbosity.ERROR as LogLevel, errorMsg);\n return { reboot_needed: false, success: false, error: errorMsg };\n }\n log(Verbosity.INFO as LogLevel, 'dnf-utils installed successfully.');\n }\n\n const { success } = await exec(['needs-restarting']);\n return { reboot_needed: !success, success: true };\n }\n\n log(Verbosity.WARN as LogLevel, `Unsupported OS (${baseOs}) for reboot_needed check.`);\n return { reboot_needed: false, success: true };\n}\n\nexport default task(run, { name: 'core.system.reboot_needed', description: 'Reboot needed.' });\n","import { task, type TaskContext, type LogLevel } from '../../../runtime';\nimport { Verbosity } from '../../../app';\nimport rebootNeeded from '../../system/reboot_needed';\nimport type { PkgInstallParams, PkgInstallResult } from '../types';\n\n/**\n * Installs a package using apt on Debian/Ubuntu\n * @param {package: string | string[]} params\n * @returns {PkgInstallResult}\n */\nasync function run(context: TaskContext<PkgInstallParams>): Promise<PkgInstallResult> {\n const { params: taskParams, exec, run: runTask, debug } = context;\n const { package: pkg, sudo = true } = taskParams;\n const packages = Array.isArray(pkg) ? pkg.join(' ') : pkg;\n\n // DEBIAN_FRONTEND=noninteractive is often set for scripts\n // apt install -yq should handle most cases without interaction\n const commandArray = [\n sudo ? 'sudo' : '',\n 'DEBIAN_FRONTEND=noninteractive',\n 'apt',\n 'install',\n '-yq',\n packages,\n ].filter(Boolean);\n\n const { success, stdout, stderr } = await exec(commandArray.join(' '), { sudo });\n if (!success) {\n const errorMsg = `Failed to install package(s): ${packages}. Error: ${stdout}\\n${stderr}`;\n debug(errorMsg);\n return { success: false, error: errorMsg };\n }\n\n // Restart services that need to be restarted using needrestart\n const needrestartCmd = [sudo ? 'sudo' : '', 'needrestart', '-q', '-r', 'a'].filter(Boolean);\n const needrestartResult = await exec(needrestartCmd.join(' '));\n if (!needrestartResult.success) {\n debug(`needrestart command failed. This might be okay. Error: ${needrestartResult.stdout}\\n${needrestartResult.stderr}`);\n }\n\n // Check if reboot is needed\n const rebootNeededResult = await runTask(rebootNeeded({}));\n if (!rebootNeededResult.success) {\n debug(`Could not determine if reboot is needed: ${rebootNeededResult.error}`);\n } else if (rebootNeededResult.reboot_needed) {\n debug('The system needs to be rebooted after package installation.');\n }\n\n return { success: true };\n}\n\n// Exporting as 'install' to match usage in src/core/pkg/install/index.ts\n// If index.ts is updated to import 'default as installDebian', this can be 'export default task(run, { name: 'core.pkg.install.debian', description: 'Pkg install debian.' });'\nexport const install = task(run);\n","import { task, type TaskContext } from '../../../runtime';\nimport type { PkgInstallParams, PkgInstallResult } from '../types';\n\n/**\n * Installs a package using dnf on Fedora\n * @param {package: string | string[]} params\n * @returns {PkgInstallResult}\n */\nasync function run(context: TaskContext<PkgInstallParams>): Promise<PkgInstallResult> {\n const { params: taskParams, exec } = context;\n const { package: pkg, sudo = true } = taskParams;\n const packages = Array.isArray(pkg) ? pkg : [pkg];\n const commandArray = [sudo ? 'sudo' : '', 'dnf', '-yq', 'install', ...packages].filter(Boolean);\n\n const { success, stdout, stderr } = await exec(commandArray.join(' '), { sudo });\n if (!success) {\n return { success: false, error: `${stdout}\\n${stderr}` };\n }\n return { success };\n}\n\nexport const install = task(run);\n","import { task, type TaskContext } from '../../../runtime';\nimport os from '../../host/os';\nimport { install as installArch } from './arch';\nimport { install as installDebian } from './debian';\nimport { install as installFedora } from './fedora';\nimport type { PkgInstallParams, PkgInstallResult } from '../types';\n\n/**\n * Installs a package using the appropriate package manager by dispatching to OS-specific tasks.\n * @param {package: string | string[]} params\n * @returns {PkgInstallResult}\n */\nasync function run(context: TaskContext<PkgInstallParams>): Promise<PkgInstallResult> {\n const { params: taskParams, run: runTask, error } = context;\n\n const osDetails = await runTask(os());\n\n if (!osDetails.success) {\n const errorMsg = `Failed to determine OS details: ${osDetails.error}`;\n error(errorMsg);\n return { success: false, error: errorMsg };\n }\n if (typeof osDetails?.os !== 'string' || osDetails.os === 'unknown') {\n const errorMsg = `OS details are invalid or 'os' property is missing/not a string.`;\n error(errorMsg);\n return { success: false, error: errorMsg };\n }\n\n const baseOs = osDetails.os;\n\n let installResult: PkgInstallResult;\n\n if (baseOs.match(/arch/)) {\n installResult = await runTask(installArch(taskParams));\n } else if (baseOs.match(/debian|ubuntu/)) {\n installResult = await runTask(installDebian(taskParams));\n } else if (baseOs === 'fedora') {\n installResult = await runTask(installFedora(taskParams));\n } else {\n const errorMsg = `Unsupported OS (${baseOs}) for package installation, or OS not detected.`;\n error(errorMsg);\n return { success: false, error: errorMsg };\n }\n\n if (!installResult.success) {\n const errorMsg = `Package installation failed for OS ${baseOs}: ${installResult.error}`;\n error(errorMsg);\n return { success: false, error: errorMsg };\n }\n\n return installResult;\n}\n\nexport default task(run, {\n name: 'core.pkg.install',\n description: 'Installs a package using the appropriate OS package manager.',\n});\n","import installDispatcherTask from './install/index'; // Imports the default export from ./install/index.ts\n\nexport { type PkgInstallParams, type PkgInstallResult } from './types';\n\nexport default installDispatcherTask;\n","import { task, type TaskContext } from '../../../runtime';\nimport type { PkgRemoveParams, PkgRemoveResult } from '../types';\n\n/**\n * Removes a package using pacman on Arch Linux\n */\nasync function run(context: TaskContext<PkgRemoveParams>): Promise<PkgRemoveResult> {\n const { params: { package: pkg, sudo = true }, exec } = context;\n const packages = Array.isArray(pkg) ? pkg : [pkg];\n const commandArray = [sudo ? 'sudo' : '', 'pacman', '-Rns', '--noconfirm', ...packages].filter(Boolean);\n const { success } = await exec(commandArray.join(' '), { sudo });\n return { success };\n}\n\nexport const remove = task(run, { name: 'core.pkg.remove.arch', description: 'Remove package(s) on Arch Linux.' });\nexport default remove;\n","import { task, type TaskContext } from '../../../runtime';\nimport rebootNeeded from '../../system/reboot_needed';\nimport type { PkgRemoveParams, PkgRemoveResult } from '../types';\n\n/**\n * Removes a package (or packages) using apt on Debian/Ubuntu.\n */\nasync function run(context: TaskContext<PkgRemoveParams>): Promise<PkgRemoveResult> {\n const {\n params: { package: pkg, sudo = true },\n exec,\n run: runTask,\n } = context;\n\n const packages = Array.isArray(pkg) ? pkg.join(' ') : pkg;\n const commandArray = [sudo ? 'sudo' : '', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', '-yq', '--purge', 'remove', packages].filter(Boolean);\n const { success } = await exec(commandArray.join(' '), { sudo });\n if (!success) {\n return { success: false };\n }\n\n // attempt autoremove to clean up dependencies\n await exec([sudo ? 'sudo' : '', 'apt-get', '-yq', 'autoremove'].filter(Boolean).join(' '), { sudo });\n\n // check if reboot needed\n await runTask(rebootNeeded());\n\n return { success: true };\n}\n\nexport const remove = task(run, {\n name: 'core.pkg.remove.debian',\n description: 'Remove package(s) on Debian/Ubuntu.',\n});\n\nexport default remove;\n","import { task, type TaskContext } from '../../../runtime';\nimport type { PkgRemoveParams, PkgRemoveResult } from '../types';\n\n/**\n * Removes a package using dnf on Fedora\n */\nasync function run(context: TaskContext<PkgRemoveParams>): Promise<PkgRemoveResult> {\n const { params: { package: pkg, sudo = true }, exec } = context;\n const packages = Array.isArray(pkg) ? pkg : [pkg];\n const commandArray = [sudo ? 'sudo' : '', 'dnf', '-yq', 'remove', ...packages].filter(Boolean);\n const { success } = await exec(commandArray.join(' '), { sudo });\n return { success };\n}\n\nexport const remove = task(run, { name: 'core.pkg.remove.fedora', description: 'Remove package(s) on Fedora.' });\nexport default remove;\n","import { task, type TaskContext } from '../../../runtime';\nimport os from '../../host/os';\nimport { remove as removeArch } from './arch';\nimport { remove as removeDebian } from './debian';\nimport { remove as removeFedora } from './fedora';\nimport type { PkgRemoveParams, PkgRemoveResult } from '../types';\n\n/**\n * Removes a package using the appropriate package manager by dispatching to OS-specific tasks.\n */\nasync function run(context: TaskContext<PkgRemoveParams>): Promise<PkgRemoveResult> {\n const { params: taskParams, run: runTask, error } = context;\n\n const osDetails = await runTask(os());\n if (osDetails instanceof Error) {\n error(`Failed to determine OS details: ${osDetails.message}`);\n return { success: false };\n }\n if (typeof osDetails?.os !== 'string') {\n error(`OS details are invalid or 'os' property is missing/not a string.`);\n return { success: false };\n }\n\n const baseOs = osDetails.os;\n let removeResult: PkgRemoveResult | Error;\n\n if (baseOs.match(/arch/)) {\n removeResult = await runTask(removeArch(taskParams));\n } else if (baseOs.match(/debian|ubuntu/)) {\n removeResult = await runTask(removeDebian(taskParams));\n } else if (baseOs === 'fedora') {\n removeResult = await runTask(removeFedora(taskParams));\n } else {\n error(`Unsupported OS (${baseOs}) for package removal, or OS not detected.`);\n return { success: false };\n }\n\n if (removeResult instanceof Error) {\n error(`Package removal failed for OS ${baseOs}: ${removeResult.message}`);\n return { success: false };\n }\n\n return removeResult;\n}\n\nexport default task(run, {\n name: 'core.pkg.remove',\n description: 'Removes a package using the appropriate OS package manager.',\n});\n","import removeDispatcherTask from './remove/index';\n\nexport { type PkgRemoveParams, type PkgRemoveResult } from './types';\n\nexport default removeDispatcherTask;\n","import { task, type TaskContext } from '../../../runtime';\nimport type { PkgUpdateParams, PkgUpdateResult } from '../types';\n\n/**\n * Updates system packages on Arch Linux using pacman.\n * If specific package names are passed, only those will be upgraded.\n */\nasync function run(context: TaskContext<PkgUpdateParams>): Promise<PkgUpdateResult> {\n const { params: { package: pkg, sudo = true }, exec } = context;\n\n const commandParts = [sudo ? 'sudo' : '', 'pacman', '-Syu', '--noconfirm'];\n if (pkg && Array.isArray(pkg) && pkg.length) {\n commandParts.push(...pkg);\n }\n\n const { success } = await exec(commandParts.filter(Boolean).join(' '), { sudo });\n return { success };\n}\n\nexport const update = task(run);\n","import { task, type TaskContext } from '../../../runtime';\nimport type { PkgUpdateParams, PkgUpdateResult } from '../types';\n\n/**\n * Updates or upgrades packages on Debian/Ubuntu systems.\n * Behaviour:\n * - no package param -> apt-get update && apt-get (upgrade|dist-upgrade)\n * - package list -> apt-get install --only-upgrade <pkg...>\n */\nasync function run(context: TaskContext<PkgUpdateParams>): Promise<PkgUpdateResult> {\n const { params: { package: pkg, sudo = true, fullUpgrade = false }, exec } = context;\n\n const prefix = sudo ? 'sudo ' : '';\n if (!pkg || (Array.isArray(pkg) && pkg.length === 0)) {\n // System-wide upgrade\n const upgradeCmd = fullUpgrade ? 'apt-get dist-upgrade -y' : 'apt-get upgrade -y';\n const { success: u1 } = await exec(`${prefix}apt-get update`, { sudo });\n if (!u1) return { success: false };\n const { success } = await exec(prefix + upgradeCmd, { sudo });\n return { success };\n }\n\n const packages = Array.isArray(pkg) ? pkg : [pkg];\n const { success } = await exec(`${prefix}apt-get install -y --only-upgrade ${packages.join(' ')}`, { sudo });\n return { success };\n}\n\nexport const update = task(run);\n","import { task, type TaskContext } from '../../../runtime';\nimport type { PkgUpdateParams, PkgUpdateResult } from '../types';\n\n/**\n * Updates packages on Fedora/RHEL-like systems via dnf.\n */\nasync function run(context: TaskContext<PkgUpdateParams>): Promise<PkgUpdateResult> {\n const { params: { package: pkg, sudo = true }, exec } = context;\n\n const prefix = sudo ? 'sudo ' : '';\n\n if (!pkg || (Array.isArray(pkg) && pkg.length === 0)) {\n const { success } = await exec(`${prefix}dnf upgrade -y`, { sudo });\n return { success };\n }\n const packages = Array.isArray(pkg) ? pkg : [pkg];\n const { success } = await exec(`${prefix}dnf upgrade -y ${packages.join(' ')}`, { sudo });\n return { success };\n}\n\nexport const update = task(run);\n","import { task, type TaskContext } from '../../../runtime';\nimport os from '../../host/os';\nimport { update as updateArch } from './arch';\nimport { update as updateDebian } from './debian';\nimport { update as updateFedora } from './fedora';\nimport type { PkgUpdateParams, PkgUpdateResult } from '../types';\n\n/**\n * Dispatcher that selects the correct per-OS implementation at runtime.\n */\nasync function run(context: TaskContext<PkgUpdateParams>): Promise<PkgUpdateResult> {\n const { params: taskParams, run: runTask, error } = context;\n const osDetails = await runTask(os());\n if (osDetails instanceof Error) {\n error(`Failed to determine OS details: ${osDetails.message}`);\n return { success: false };\n }\n const baseOs = String(osDetails?.os ?? '');\n\n let result: PkgUpdateResult | Error;\n if (/arch/.test(baseOs)) {\n result = await runTask(updateArch(taskParams));\n } else if (/debian|ubuntu/.test(baseOs)) {\n result = await runTask(updateDebian(taskParams));\n } else if (baseOs === 'fedora') {\n result = await runTask(updateFedora(taskParams));\n } else {\n error(`Unsupported OS (${baseOs}) for pkg.update`);\n return { success: false };\n }\n\n if (result instanceof Error) {\n error(`pkg.update failed: ${result.message}`);\n return { success: false };\n }\n return result;\n}\n\nexport default task(run, {\n name: 'core.pkg.update',\n description: 'Updates packages using the appropriate OS package manager.',\n});\n","import updateDispatcherTask from './update/index'; // Imports the default export from ./install/index.ts\n\nexport { type PkgUpdateParams, type PkgUpdateResult } from './types';\n\nexport default updateDispatcherTask;\n","import { task, type TaskContext } from '../../runtime';\nimport os from '../host/os';\n\nexport interface PkgInfoParams {\n package: string;\n}\n\nexport interface PkgInfoResult {\n installed: boolean;\n success: boolean;\n error?: string;\n // Potentially add more fields like version, status if needed from parsed output\n}\n\n/**\n * Gets information about a package\n * @param {package: string} params\n * @returns {PkgInfoResult}\n */\nasync function run(context: TaskContext<PkgInfoParams>): Promise<PkgInfoResult> {\n const { params: taskParams, run: runTask, exec, error } = context;\n const osDetails = await runTask(os({}));\n if (!osDetails.success) {\n const errorMsg = `Failed to get OS details for pkg info: ${osDetails.error}`;\n error(errorMsg);\n return { installed: false, success: false, error: errorMsg };\n }\n if (typeof osDetails?.os !== 'string') {\n // Should not happen if not an error\n const errorMsg = `OS details 'os' field is not a string: ${typeof osDetails?.os}`;\n error(errorMsg);\n return { installed: false, success: false, error: errorMsg };\n }\n const baseOs = osDetails.os; // Using the 'os' field which is ID_LIKE (e.g., debian, fedora)\n const { package: pkg } = taskParams;\n\n let commandArray: string[];\n if (baseOs.match(/debian|ubuntu/)) {\n // dpkg returns exit code 0 only when the package is installed\n commandArray = ['dpkg', '-s', pkg];\n } else if (baseOs.match(/fedora|rhel|centos|rocky|alma/)) {\n commandArray = ['rpm', '-q', pkg];\n } else if (baseOs.match(/arch/)) {\n commandArray = ['pacman', '-Qi', pkg];\n } else if (baseOs.match(/alpine/)) {\n commandArray = ['apk', 'info', '-e', pkg];\n } else {\n const errorMsg = `Unsupported operating system for package info: ${baseOs}`;\n error(errorMsg);\n return { installed: false, success: false, error: errorMsg };\n }\n\n try {\n const { success, stdout, stderr } = await exec(commandArray);\n if (success) {\n return { installed: true, success: true };\n }\n\n const output = (stdout + stderr).toLowerCase();\n if (output.includes('not installed') || output.includes('not found')) {\n return { installed: false, success: true };\n }\n\n return { installed: false, success: false, error: `Command failed unexpectedly:\\nstdout: ${stdout}\\nstderr: ${stderr}` };\n } catch (e: any) {\n const output = (e.stdout || '' + e.stderr || '').toLowerCase();\n if (output.includes('not installed') || output.includes('not found')) {\n return { installed: false, success: true };\n }\n return { installed: false, success: false, error: e.message };\n }\n}\n\nexport default task(run, { name: 'core.pkg.info', description: 'Pkg info.' });\n","import { task, type TaskContext } from '../../runtime';\nimport type { PkgIsInstalledParams, PkgIsInstalledResult } from './types';\nimport pkgInfo from './info';\n\n/**\n * Returns true if the given package is installed (wrapper around core.pkg.info).\n */\nasync function run(context: TaskContext<PkgIsInstalledParams>): Promise<PkgIsInstalledResult> {\n const { params, run: runTask } = context;\n const info = await runTask(pkgInfo({ package: params.package }));\n if (info instanceof Error) {\n return { installed: false };\n }\n return { installed: !!info.installed };\n}\n\nexport default task(run, {\n name: 'core.pkg.is_installed',\n description: 'Checks if a package is installed on the system.',\n});\n","import k3supInstall, { type K3supInstallParams, type K3supInstallResult } from './k3sup-install';\n\nexport { k3supInstall, type K3supInstallParams, type K3supInstallResult };\n","import { task, type TaskContext, type LogLevel } from '../../runtime';\nimport { Verbosity } from '../../app';\n\nexport interface K3supInstallParams {\n cluster?: boolean;\n context?: string;\n datastore?: string;\n /** Public hostname of node on which to install k3s (k3sup --host) */\n targetHost?: string;\n /** Public IP of node (k3sup --ip) */\n ip?: string;\n ipsec?: boolean;\n k3sChannel?: string; // default \"stable\"\n k3sExtraArgs?: string;\n k3sVersion?: string;\n local?: boolean;\n localPath?: string; // default \"kubeconfig\"\n merge?: boolean;\n noExtras?: boolean;\n printCommand?: boolean;\n printConfig?: boolean;\n skipInstall?: boolean;\n sshKey?: string; // default \"~/.ssh/id_rsa\"\n sshPort?: number; // default 22\n sudo?: boolean; // default true\n tlsSan?: string;\n token?: string;\n /** Username for SSH login (k3sup --user) */\n user?: string; // default \"root\"\n}\n\nexport interface K3supInstallResult {\n stdout: string;\n stderr: string;\n /** Kubeconfig content if --print-config was used */\n kubeconfig?: string;\n /** The command that would be run if --print-command was used */\n executedCommand?: string;\n}\n\n/**\n * Installs k3s on a target host using k3sup.\n * Assumes k3sup is installed on the machine running hostctl.\n */\nasync function run(context: TaskContext<K3supInstallParams>): Promise<K3supInstallResult> {\n const { params, exec, log, error, debug } = context;\n\n const k3supCmd: string[] = ['k3sup', 'install'];\n\n // Helper to add flag if param is true\n const addFlag = (flag: string, condition?: boolean) => {\n if (condition) {\n k3supCmd.push(flag);\n }\n };\n\n // Helper to add option with value if param is defined\n const addOption = (flag: string, value?: string | number | undefined) => {\n if (value !== undefined) {\n k3supCmd.push(flag, String(value));\n }\n };\n\n addFlag('--cluster', params.cluster);\n addOption('--context', params.context);\n addOption('--datastore', params.datastore);\n addOption('--host', params.targetHost);\n addOption('--ip', params.ip);\n addFlag('--ipsec', params.ipsec);\n addOption('--k3s-channel', params.k3sChannel);\n addOption('--k3s-extra-args', params.k3sExtraArgs);\n addOption('--k3s-version', params.k3sVersion);\n addFlag('--local', params.local);\n addOption('--local-path', params.localPath);\n addFlag('--merge', params.merge);\n addFlag('--no-extras', params.noExtras);\n addFlag('--print-command', params.printCommand);\n addFlag('--print-config', params.printConfig);\n addFlag('--skip-install', params.skipInstall);\n addOption('--ssh-key', params.sshKey);\n addOption('--ssh-port', params.sshPort);\n // --sudo is true by default, only add --sudo=false if params.sudo is explicitly false\n if (params.sudo === false) {\n k3supCmd.push('--sudo=false');\n } else if (params.sudo === true) {\n // k3sup defaults to sudo, so no need to add --sudo or --sudo=true unless k3sup changes its default\n // However, to be explicit if the user sets it true:\n // k3supCmd.push(\"--sudo\"); // or k3supCmd.push(\"--sudo=true\");\n }\n addOption('--tls-san', params.tlsSan);\n addOption('--token', params.token);\n addOption('--user', params.user);\n\n debug(`Executing k3sup command: ${k3supCmd.join(' ')}`);\n\n try {\n const { stdout, stderr, exitCode } = await exec(k3supCmd);\n\n if (exitCode !== 0) {\n error(`k3sup command failed with exit code ${exitCode}. Stderr: ${stderr}`);\n }\n\n const result: K3supInstallResult = {\n stdout,\n stderr,\n executedCommand: params.printCommand ? stdout : k3supCmd.join(' '),\n };\n\n if (params.printConfig) {\n result.kubeconfig = stdout;\n }\n\n return result;\n } catch (e: any) {\n error(`Error executing k3sup command: ${e.message}`);\n throw e; // Re-throw to ensure task failure is propagated\n }\n}\n\nexport default task(run, { name: 'core.k3s.k3sup-install', description: 'K3s k3sup-install.' });\n","export { default as copy_id } from './copy_id';\n","import path from 'node:path';\nimport { task, type TaskContext, type LogLevel } from '../../runtime';\n\n// Child task imports\nimport userExistsTask from '../user/exists';\nimport userHomeDirTask from '../user/home_dir';\nimport dirCreateTask from '../dir/create';\nimport getHostnameTask from '../host/hostname';\nimport getUsernameTask from '../user/get_username';\nimport fileTouchTask from '../file/touch';\n\ninterface CopyIdParams {\n public_key: string;\n user?: string;\n}\n\ninterface CopyIdResult {\n success: boolean;\n}\n\n/**\n * Copies an SSH public key to a specified user's authorized_keys file.\n */\nasync function run(context: TaskContext<CopyIdParams>): Promise<CopyIdResult> {\n const { params, run: runTask, exec, log, info } = context;\n let { public_key, user } = params;\n const publicKeyTrimmed = public_key.trim();\n\n if (!user) {\n const usernameResult = await runTask(getUsernameTask());\n if (usernameResult instanceof Error) {\n info(`Failed to get current username: ${usernameResult.message}`); // ERROR: 3\n return { success: false };\n }\n if (typeof usernameResult?.username !== 'string') {\n info('Could not determine current username from task result.'); // ERROR: 3\n return { success: false };\n }\n user = usernameResult.username;\n }\n\n if (!user) {\n // Should be caught by above, but as a safeguard\n info('User for SSH key copy is undefined.'); // ERROR: 3\n return { success: false };\n }\n\n const userExistsResult = await runTask(userExistsTask({ user }));\n if (userExistsResult instanceof Error) {\n info(`Error checking if user '${user}' exists: ${userExistsResult.message}`); // ERROR: 3\n return { success: false };\n }\n if (!userExistsResult?.exists) {\n const hostnameResult = await runTask(getHostnameTask());\n const hostname =\n hostnameResult instanceof Error || !hostnameResult?.hostname ? 'current host' : hostnameResult.hostname;\n info(`User '${user}' does not exist on ${hostname}. Cannot copy SSH ID.`); // WARN: 2\n return { success: false };\n }\n\n const homeDirResult = await runTask(userHomeDirTask({ user }));\n if (homeDirResult instanceof Error) {\n info(`Error getting home directory for user '${user}': ${homeDirResult.message}`); // ERROR: 3\n return { success: false };\n }\n if (typeof homeDirResult?.path !== 'string') {\n info(`Could not determine home directory path for user '${user}'.`); // ERROR: 3\n return { success: false };\n }\n const userHome = homeDirResult.path;\n const sshDir = path.join(userHome, '.ssh');\n\n const dirCreateResult = await runTask(dirCreateTask({ path: sshDir, mode: '700', owner: user }));\n if (dirCreateResult instanceof Error || !dirCreateResult?.success) {\n info(\n `Failed to create or set permissions for ${sshDir}: ${dirCreateResult instanceof Error ? dirCreateResult.message : 'Task reported failure'}`,\n ); // ERROR: 3\n return { success: false };\n }\n\n const authorizedKeysFile = path.join(sshDir, 'authorized_keys');\n const touchResult = await runTask(fileTouchTask({ file: authorizedKeysFile, mode: '600', owner: user }));\n if (touchResult instanceof Error || !touchResult?.success) {\n info(\n `Failed to touch or set permissions for ${authorizedKeysFile}: ${touchResult instanceof Error ? touchResult.message : 'Task reported failure'}`,\n ); // ERROR: 3\n return { success: false };\n }\n\n const checkKeyCommandParts: string[] = [];\n // No sudo if current user matches target user and no specific user is forced for exec context\n // However, grep might need to read a file owned by another user, so sudo -u is safer.\n checkKeyCommandParts.push('sudo', '-u', user, 'grep', '-xqF', publicKeyTrimmed, authorizedKeysFile);\n\n const checkKeyCmdResult = await exec(checkKeyCommandParts);\n\n if (checkKeyCmdResult.exitCode === 0) {\n info(`SSH key already exists in ${authorizedKeysFile} for user ${user}.`); // INFO: 1\n return { success: true };\n } else if (checkKeyCmdResult.exitCode !== 1) {\n // 1 means not found (which is OK), >1 is an error\n info(`Error checking for existing SSH key: ${checkKeyCmdResult.stderr || checkKeyCmdResult.stdout}`); // ERROR: 3\n return { success: false };\n }\n\n // Key not found (exitCode === 1), proceed to add it.\n const sudoCmd = `sudo -u ${user}`;\n const escapedPublicKey = publicKeyTrimmed.replace(/\"/g, '\\\\\"').replace(/\\$/g, '\\\\\\$').replace(/`/g, '\\\\`');\n const shellCommand = `echo \"${escapedPublicKey}\" | ${sudoCmd} tee -a \"${authorizedKeysFile}\"`;\n\n info(`Attempting to add key with command: sh -c '${shellCommand}'`); // DEBUG: 0\n const addKeyResult = await exec(['sh', '-c', shellCommand]);\n\n if (!addKeyResult.success) {\n info(\n `Failed to add SSH key for user ${user}. Exit code: ${addKeyResult.exitCode}, Error: ${addKeyResult.stderr || addKeyResult.stdout}`,\n ); // ERROR: 3\n }\n\n return {\n success: addKeyResult.success,\n };\n}\n\nexport default task(run, { name: 'core.ssh.copy_id', description: 'Ssh copy id.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface UserExistsParams {\n user: string;\n}\n\nexport interface UserExistsResult {\n exists: boolean;\n}\n\n/**\n * @param {user: string} params\n * @returns {\n * exists: boolean\n * }\n */\nasync function run(context: TaskContext<UserExistsParams>): Promise<UserExistsResult> {\n const { params, exec } = context;\n const { user } = params;\n\n // Check if user exists using id command\n const command = ['id', user].join(' ');\n\n const { success: exists } = await exec(command);\n\n return {\n exists,\n };\n}\n\nexport default task(run, { name: 'core.user.exists', description: 'User exists.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface UserHomeDirParams {\n user: string;\n}\n\nexport interface UserHomeDirResult {\n path: string;\n exists: boolean;\n}\n\n/**\n * @param {user: string} params\n * @returns {\n * path: string\n * exists: boolean\n * }\n */\nasync function run(context: TaskContext<UserHomeDirParams>): Promise<UserHomeDirResult> {\n const { params, exec } = context;\n const { user } = params;\n\n // Get user's home directory using getent\n const getentCommand = ['getent', 'passwd', user].filter(Boolean).join(' ');\n const { success: getentSuccess, stdout } = await exec(getentCommand);\n\n let path = '';\n if (getentSuccess) {\n // Parse home directory from passwd entry (6th field)\n const fields = stdout.split(':');\n path = fields[5]?.trim() || '';\n }\n\n let exists = false;\n if (path) {\n // Check if directory exists\n const testCommand = `test -d ${path}`;\n const { success: dirExistsSuccess } = await exec(testCommand);\n exists = dirExistsSuccess;\n }\n\n return {\n path,\n exists,\n };\n}\n\nexport default task(run, { name: 'core.user.home_dir', description: 'User home dir.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GetUsernameResult {\n success: boolean;\n username: string;\n}\n\n/**\n * @param {} params\n * @returns {\n * success: boolean\n * username: string // Corrected from uid to username in comment\n * }\n */\nasync function run(context: TaskContext<{}>): Promise<GetUsernameResult> {\n const { exec } = context;\n const command = ['id', '-un'].filter(Boolean).join(' ');\n\n const { success, stdout: username } = await exec(command);\n\n return {\n success,\n username: username.trim(),\n };\n}\n\nexport default task(run, { name: 'core.user.get_username', description: 'User get username.' });\n","export { default as check } from './check';\nexport { default as grantNopasswd } from './grant-nopasswd';\n","import { task, type TaskContext } from '../../runtime';\n\ninterface SudoersCheckParams {\n file?: string; // Path to the sudoers file to check. Defaults to /etc/sudoers.\n}\n\nexport interface SudoersCheckResult {\n success: boolean; // True if the sudoers file syntax is valid, false otherwise.\n}\n\n/**\n * Checks the syntax of a sudoers file using 'visudo -cf'.\n * @param {SudoersCheckParams} params - Parameters for the sudoers check operation.\n * @returns {Promise<SudoersCheckResult>} - The result of the syntax check.\n */\nasync function run(context: TaskContext<SudoersCheckParams>): Promise<SudoersCheckResult> {\n const { params, exec } = context;\n const effectiveFile = params.file || '/etc/sudoers';\n\n // Execute 'visudo -cf <file>'. This command typically requires sudo privileges itself.\n const { stdout, success } = await exec(['sudo', 'visudo', '-cf', effectiveFile]);\n\n // 'visudo -cf' on success prints '<file>: parsed OK' to stdout and exits with 0.\n // On failure, it prints an error to stderr and exits non-zero.\n return {\n success: success && stdout.includes(`${effectiveFile}: parsed OK`),\n };\n}\n\nexport default task(run, { name: 'core.sudoers.check', description: 'Sudoers check.' });\n","import { task, type TaskContext, type LogLevel } from '../../runtime';\nimport { Verbosity } from '../../app';\nimport { KeySequence } from '../../keyboard';\n\nexport interface GrantNopasswdParams {\n /** The username to grant passwordless sudo privileges. */\n user: string;\n /** The name of the file to create in /etc/sudoers.d/. Defaults to the username. */\n name?: string;\n}\n\nexport interface GrantNopasswdResult {\n /** True if the operation was successful. */\n success: boolean;\n /** The path to the created sudoers file. */\n filePath: string;\n}\n\n/**\n * Grants a user passwordless sudo privileges by creating a file in /etc/sudoers.d/.\n */\nasync function run(context: TaskContext<GrantNopasswdParams>): Promise<GrantNopasswdResult> {\n const { params, exec, log, error } = context;\n const { user } = params;\n\n if (!user) {\n throw new Error(\"The 'user' parameter is required.\");\n }\n\n const sudoersFileName = params.name || user;\n const sudoersFilePath = `/etc/sudoers.d/${sudoersFileName}`;\n const sudoersContent = `${user} ALL=(ALL) NOPASSWD: ALL${KeySequence.NEWLINE}${KeySequence.CTRL_D}`;\n\n try {\n // Use 'tee' to write the file with sudo privileges.\n // The input to the exec command is piped to stdin of the shell process.\n const writeCmd = await exec(['sudo', 'tee', sudoersFilePath], { stdin: sudoersContent });\n if (!writeCmd.success) {\n error(`Failed to write to ${sudoersFilePath}: ${writeCmd.stderr}`);\n return { success: false, filePath: sudoersFilePath };\n }\n\n // Set the correct permissions for the sudoers file.\n const chmodCmd = await exec(['sudo', 'chmod', '0440', sudoersFilePath]);\n if (!chmodCmd.success) {\n error(`Failed to set permissions on ${sudoersFilePath}: ${chmodCmd.stderr}`);\n return { success: false, filePath: sudoersFilePath };\n }\n\n // Set the correct ownership for the sudoers file.\n const chownCmd = await exec(['sudo', 'chown', 'root:root', sudoersFilePath]);\n if (!chownCmd.success) {\n error(`Failed to set ownership on ${sudoersFilePath}: ${chownCmd.stderr}`);\n return { success: false, filePath: sudoersFilePath };\n }\n\n // Verify the syntax of the new sudoers file.\n const checkCmd = await exec(['sudo', 'visudo', '-cf', sudoersFilePath]);\n if (!checkCmd.success) {\n error(`Syntax check failed for ${sudoersFilePath}: ${checkCmd.stderr}`);\n // Attempt to clean up the invalid file\n await exec(['sudo', 'rm', '-f', sudoersFilePath]);\n return { success: false, filePath: sudoersFilePath };\n }\n\n log(Verbosity.INFO as LogLevel, `Successfully granted passwordless sudo to user '${user}' via ${sudoersFilePath}`);\n return { success: true, filePath: sudoersFilePath };\n } catch (e: any) {\n error(`An unexpected error occurred: ${e.message}`);\n throw e;\n }\n}\n\nexport default task(run, {\n description: 'Grants a user passwordless sudo privileges by creating a file in /etc/sudoers.d/.',\n});\n","import reboot, { type RebootParams, type RebootResult } from './reboot';\nimport shutdown, { type ShutdownParams, type ShutdownResult } from './shutdown';\nimport rebootNeeded, { type RebootNeededParams, type RebootNeededResult } from './reboot_needed';\nimport rebootIfNeeded, { type RebootIfNeededParams, type RebootIfNeededResult } from './reboot_if_needed';\n\nexport {\n reboot,\n type RebootParams,\n type RebootResult,\n shutdown,\n type ShutdownParams,\n type ShutdownResult,\n rebootNeeded,\n type RebootNeededParams,\n type RebootNeededResult,\n rebootIfNeeded,\n type RebootIfNeededParams,\n type RebootIfNeededResult,\n};\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface RebootParams {\n /**\n * A message to broadcast to all users before rebooting.\n */\n message?: string;\n\n /**\n * The time to wait before rebooting. E.g., \"+5\" for 5 minutes, \"now\" for immediately.\n * @default \"now\"\n */\n time?: string;\n\n /**\n * Whether to run the command with sudo. Defaults to true.\n */\n sudo?: boolean;\n}\n\nexport interface RebootResult {\n success: boolean;\n error?: string;\n status: string;\n}\n\n/**\n * Reboots a system.\n */\nasync function run(context: TaskContext<RebootParams>): Promise<RebootResult> {\n const { params, info, warn, exec } = context;\n const time = params.time || 'now';\n const sudo = params.sudo ?? true;\n\n info(`Sending reboot command to host. Time: ${time}`);\n\n const command = [sudo ? 'sudo' : '', 'shutdown', '-r', time, params.message ? `\"${params.message}\"` : ''].filter(\n Boolean,\n );\n\n try {\n const { success, stdout, stderr } = await exec(command, { sudo });\n\n if (success) {\n return {\n success: true,\n status: `Reboot command issued to host. The host will reboot at: ${time}`,\n };\n }\n\n // Command failed but didn't throw. Could be a graceful shutdown signal.\n warn('Reboot command failed without throwing an exception. Assuming success during shutdown.');\n\n return {\n success: true, // As per original logic, treat as success\n status: `Reboot command issued. The host is likely shutting down.`,\n error: `stdout: ${stdout}\\nstderr: ${stderr}`,\n };\n } catch (e: any) {\n // If the exec command fails, it's often because the host has already started shutting down,\n // which can be considered a success for a reboot task.\n warn('Command may have timed out or disconnected, which is expected during a reboot. Assuming success.');\n return {\n success: true,\n status: `Reboot command issued. The host is likely shutting down.`,\n error: e.message,\n };\n }\n}\n\nexport default task(run, {\n description: 'Reboots a system',\n});\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface ShutdownParams {\n /**\n * A message to broadcast to all users before shutting down.\n */\n message?: string;\n\n /**\n * The time to wait before shutting down. E.g., \"+5\" for 5 minutes, \"now\" for immediately.\n * @default \"now\"\n */\n time?: string;\n\n /**\n * Whether to run the command with sudo. Defaults to true.\n */\n sudo?: boolean;\n}\n\nexport interface ShutdownResult {\n success: boolean;\n error?: string;\n status: string;\n}\n\n/**\n * Shuts down a system.\n */\nasync function run(context: TaskContext<ShutdownParams>): Promise<ShutdownResult> {\n const { params, info, warn, exec } = context;\n const time = params.time || 'now';\n const sudo = params.sudo ?? true;\n\n info(`Sending shutdown command to host. Time: ${time}`);\n\n const command = `shutdown -h ${time} ${params.message ? `\"${params.message}\"` : ''}`.trim();\n\n try {\n const { success, stdout, stderr } = await exec(command, { pty: true, sudo });\n\n if (success) {\n info('Shutdown command successfully issued.');\n return {\n success: true,\n status: `Shutdown command issued to host. The host will shut down at: ${time}`,\n };\n }\n\n warn('Shutdown command failed without throwing an exception. Assuming success during shutdown.');\n return {\n success: true, // As per original logic, treat as success\n status: `Shutdown command issued. The host is likely shutting down.`,\n error: `stdout: ${stdout}\\nstderr: ${stderr}`,\n };\n } catch (e: any) {\n // If the exec command fails, it's often because the host has already started shutting down,\n // which can be considered a success for a shutdown task.\n warn('The shutdown command may have disconnected the session, which is expected. Assuming success.');\n return {\n success: true,\n status: `Shutdown command issued to host. The host will shut down at: ${time}`,\n error: e.message,\n };\n }\n}\n\nexport default task(run);\n","import { type TaskContext, type LogLevel, task } from '../../runtime';\nimport { Verbosity } from '../../app';\nimport rebootNeeded from './reboot_needed';\n\nexport interface RebootIfNeededParams {\n delay?: number; // Delay in seconds before rebooting\n message?: string; // Message to log before rebooting\n}\n\nexport interface RebootIfNeededResult {\n rebooting: boolean; // True if a reboot was initiated, false otherwise\n success: boolean;\n error?: string;\n}\n\n/**\n * Reboots the system if a reboot is determined to be needed by the 'reboot_needed' task.\n * @param {RebootIfNeededParams} params - Parameters for the reboot operation, including optional delay and message.\n * @returns {Promise<RebootIfNeededResult>} - An object indicating whether a reboot was initiated.\n */\nasync function run(context: TaskContext<RebootIfNeededParams>): Promise<RebootIfNeededResult> {\n const { params, run: runTask, exec, log } = context;\n const delayInSeconds = Math.max(1, params.delay ?? 1); // Ensure at least 1 second delay\n const message = params.message ?? 'Reboot is required. Initiating reboot sequence.';\n\n // Check if a reboot is needed by running the reboot_needed task\n const rebootCheckResult = await runTask(rebootNeeded());\n\n if (!rebootCheckResult.success) {\n const errorMsg = `Failed to check if reboot is needed: ${rebootCheckResult.error}`;\n log(Verbosity.ERROR as LogLevel, errorMsg);\n return { rebooting: false, success: false, error: errorMsg };\n }\n\n if (!rebootCheckResult.reboot_needed) {\n log(Verbosity.INFO as LogLevel, 'Reboot not needed.');\n return { rebooting: false, success: true };\n }\n\n log(Verbosity.WARN as LogLevel, `${message} System will reboot in ${delayInSeconds} second(s).`);\n\n // Wait for the specified delay\n await new Promise((resolve) => setTimeout(resolve, delayInSeconds * 1000));\n\n // Execute the reboot command\n try {\n const { success, stdout, stderr } = await exec(['sudo', 'reboot']);\n if (!success) {\n // This part might not be reached if reboot is fast, but it's good practice.\n const errorMsg = `Reboot command failed: ${stdout}\\n${stderr}`;\n log(Verbosity.ERROR as LogLevel, errorMsg);\n return { rebooting: false, success: false, error: errorMsg };\n }\n } catch (error: any) {\n // This catch block is for when exec itself throws, e.g., due to connection issues\n log(Verbosity.ERROR as LogLevel, `Reboot command failed to execute: ${error.message}`);\n return { rebooting: false, success: false, error: error.message };\n }\n\n // This line indicates the command was dispatched.\n return { rebooting: true, success: true };\n}\n\nexport default task(run, { name: 'core.system.reboot_if_needed', description: 'Reboot if needed.' });\n","export { default as disable } from './disable';\nexport { default as enable } from './enable';\nexport { default as restart } from './restart';\nexport { default as start } from './start';\nexport { default as stop } from './stop';\nexport { default as reload } from './reload';\nexport { default as status } from './status';\n","import { task, type TaskContext } from '../../runtime';\n\ninterface DisableServiceParams {\n service: string;\n sudo?: boolean;\n}\n\ninterface DisableServiceResult {\n success: boolean;\n}\n\n/**\n * @param {service: string, sudo?: boolean} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<DisableServiceParams>): Promise<DisableServiceResult> {\n const { params, exec } = context;\n const { service, sudo = false } = params;\n\n const command = [sudo ? 'sudo' : '', 'systemctl', 'disable', service].filter(Boolean).join(' ');\n\n const { success } = await exec(command);\n\n return {\n success: success,\n };\n}\n\nexport default task(run, { name: 'core.systemd.disable', description: 'Systemd disable.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface SystemdEnableParams {\n service: string; // The name of the systemd service to enable.\n sudo?: boolean; // Whether to use sudo. Defaults to false.\n}\n\ninterface SystemdEnableResult {\n success: boolean; // True if the service was enabled successfully, false otherwise.\n}\n\n/**\n * Enables a systemd service.\n * @param {TaskContext<SystemdEnableParams>} context - The task context containing parameters.\n * @returns {Promise<SystemdEnableResult>} - The result of the enable operation.\n */\nasync function run(context: TaskContext<SystemdEnableParams>): Promise<SystemdEnableResult> {\n const { params, exec } = context;\n const { service, sudo = false } = params;\n\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('systemctl', 'enable', service);\n\n // systemctl enable usually requires sudo if not run as root.\n const { success } = await exec(commandArray);\n\n return {\n success: success,\n };\n}\n\nexport default task(run, { name: 'core.systemd.enable', description: 'Systemd enable.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface SystemdRestartParams {\n service: string; // The name of the systemd service to restart.\n sudo?: boolean; // Whether to use sudo. Defaults to false.\n}\n\ninterface SystemdRestartResult {\n success: boolean; // True if the service was restarted successfully, false otherwise.\n}\n\n/**\n * Restarts a systemd service.\n * @param {TaskContext<SystemdRestartParams>} context - The task context containing parameters.\n * @returns {Promise<SystemdRestartResult>} - The result of the restart operation.\n */\nasync function run(context: TaskContext<SystemdRestartParams>): Promise<SystemdRestartResult> {\n const { params, exec } = context;\n const { service, sudo = false } = params;\n\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('systemctl', 'restart', service);\n\n // systemctl restart usually requires sudo if not run as root.\n const { success } = await exec(commandArray);\n\n return {\n success: success,\n };\n}\n\nexport default task(run, { name: 'core.systemd.restart', description: 'Systemd restart.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface SystemdStartParams {\n service: string; // The name of the systemd service to start.\n sudo?: boolean; // Whether to use sudo. Defaults to false.\n}\n\ninterface SystemdStartResult {\n success: boolean; // True if the service was started successfully, false otherwise.\n}\n\n/**\n * Starts a systemd service.\n * @param {TaskContext<SystemdStartParams>} context - The task context containing parameters.\n * @returns {Promise<SystemdStartResult>} - The result of the start operation.\n */\nasync function run(context: TaskContext<SystemdStartParams>): Promise<SystemdStartResult> {\n const { params, exec } = context;\n const { service, sudo = false } = params;\n\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('systemctl', 'start', service);\n\n // systemctl start usually requires sudo if not run as root.\n const { success } = await exec(commandArray);\n\n return {\n success: success,\n };\n}\n\nexport default task(run, { name: 'core.systemd.start', description: 'Systemd start.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface SystemdStopParams {\n service: string; // The name of the systemd service to stop.\n sudo?: boolean; // Whether to use sudo. Defaults to false.\n}\n\ninterface SystemdStopResult {\n success: boolean; // True if the service was stopped successfully, false otherwise.\n}\n\n/**\n * Stops a systemd service.\n * @param {TaskContext<SystemdStopParams>} context - The task context containing parameters.\n * @returns {Promise<SystemdStopResult>} - The result of the stop operation.\n */\nasync function run(context: TaskContext<SystemdStopParams>): Promise<SystemdStopResult> {\n const { params, exec } = context;\n const { service, sudo = false } = params;\n\n const commandArray: string[] = [];\n if (sudo) {\n commandArray.push('sudo');\n }\n commandArray.push('systemctl', 'stop', service);\n\n // systemctl stop usually requires sudo if not run as root.\n const { success } = await exec(commandArray);\n\n return {\n success: success,\n };\n}\n\nexport default task(run, { name: 'core.systemd.stop', description: 'Systemd stop.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface SystemdReloadParams {\n service: string;\n sudo?: boolean;\n}\n\ninterface SystemdReloadResult {\n success: boolean;\n}\n\n/**\n * Reloads a systemd service (e.g., re-reads configuration without full restart).\n */\nasync function run(context: TaskContext<SystemdReloadParams>): Promise<SystemdReloadResult> {\n const { params, exec } = context;\n const { service, sudo = false } = params;\n\n const command = [sudo ? 'sudo' : '', 'systemctl', 'reload', service].filter(Boolean);\n const { success } = await exec(command, { sudo });\n return { success };\n}\n\nexport default task(run, {\n name: 'core.systemd.reload',\n description: 'Reloads a systemd service (e.g., re-reads configuration without full restart).'\n});\n","import { task, type TaskContext } from '../../runtime';\n\ninterface SystemdStatusParams {\n service: string;\n sudo?: boolean;\n}\n\ninterface SystemdStatusResult {\n active: boolean;\n}\n\n/**\n * Checks whether a systemd service is active.\n */\nasync function run(context: TaskContext<SystemdStatusParams>): Promise<SystemdStatusResult> {\n const { params, exec } = context;\n const { service, sudo = false } = params;\n\n const command = [sudo ? 'sudo' : '', 'systemctl', 'is-active', '--quiet', service].filter(Boolean);\n const { success } = await exec(command, { sudo });\n return { active: success };\n}\n\nexport default task(run, {\n name: 'core.systemd.status',\n description: 'Checks systemd service status.'\n});\n","export { default as write } from './write';\n","import { type TaskContext, type LogLevel, task } from '../../runtime';\nimport { Verbosity } from '../../app';\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\n// Assuming these tasks are default exports from their respective files\nimport chmodTask from '../file/chmod';\nimport chownTask from '../file/chown';\n\ninterface TemplateWriteParams {\n template?: string; // Template content as a string\n template_file?: string; // Path to a template file\n variables: Record<string, any>; // Key-value pairs for template substitution\n to: string; // Destination path (file or directory)\n mode?: string; // File mode (e.g., \"644\")\n owner?: string; // File owner\n group?: string; // File group\n sudo?: boolean; // Optional: If true, chmod/chown tasks will attempt to use sudo. Defaults to their internal sudo behavior (usually true).\n}\n\ninterface TemplateWriteResult {\n success: boolean;\n path: string; // Actual path where the file was written\n}\n\n/**\n * Renders a template (from string or file) with given variables and writes it to a destination path.\n * Optionally sets file mode and ownership using chmod and chown tasks.\n * @param {TaskContext<TemplateWriteParams>} context - The task context containing parameters.\n * @returns {Promise<TemplateWriteResult>} - An object indicating success and the final output path.\n */\nasync function runFn(context: TaskContext<TemplateWriteParams>): Promise<TemplateWriteResult> {\n const { params, log, warn, error, debug, run } = context;\n const { template, template_file, variables, to, mode, owner, group, sudo } = params;\n\n let templateContent: string | undefined = template;\n\n if (template && template_file) {\n warn(\"Both 'template' string and 'template_file' path provided. Using 'template' string.\");\n }\n\n if (!templateContent && template_file) {\n try {\n templateContent = await fs.readFile(template_file, 'utf-8');\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : String(err);\n error(`Failed to read template_file '${template_file}': ${errorMessage}`);\n throw new Error(`Failed to read template_file '${template_file}': ${errorMessage}`);\n }\n }\n\n if (typeof templateContent !== 'string') {\n error(`No template content provided for destination '${to}'. Either 'template' or 'template_file' must be specified.`);\n throw new Error(`No template content provided for destination '${to}'.`);\n }\n\n // Simple template rendering (same as original)\n const renderedContent = templateContent.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key) => variables[key]?.toString() ?? '');\n\n let outputPath = to;\n try {\n const stat = await fs.stat(to);\n if (stat.isDirectory()) {\n const baseName = template_file ? path.basename(template_file) : 'rendered_template.txt'; // Added .txt for default\n outputPath = path.join(to, baseName);\n }\n } catch (error: any) {\n if (error.code !== 'ENOENT') {\n log(2, `Error checking destination path '${to}': ${error.message}. Proceeding assuming 'to' is a file path.`); // Assuming WARN is 2\n }\n // If 'to' does not exist (ENOENT), outputPath remains 'to', which is the intended new file path.\n }\n\n debug(`Writing rendered template to: ${outputPath}`);\n\n try {\n await fs.writeFile(outputPath, renderedContent, 'utf-8');\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n log(3, `Failed to write template to '${outputPath}': ${errorMessage}`); // Assuming ERROR is 3\n return { success: false, path: outputPath };\n }\n\n let overallSuccess = true;\n\n if (mode) {\n log(0, `Setting mode ${mode} for ${outputPath}`); // Assuming DEBUG is 0\n try {\n const chmodParams = { path: outputPath, mode, sudo };\n const chmodResult = await run(chmodTask(chmodParams)); // chmodTask is from ../file/chmod\n\n if (chmodResult instanceof Error) {\n log(Verbosity.ERROR as LogLevel, `Error setting mode for ${outputPath}: ${chmodResult.message}`);\n overallSuccess = false;\n } else if (!chmodResult?.success) {\n log(Verbosity.ERROR as LogLevel, `Failed to set mode ${mode} for ${outputPath}`);\n overallSuccess = false;\n }\n } catch (error) {\n // Catch unexpected errors from run or promise chain\n const errorMessage = error instanceof Error ? error.message : String(error);\n log(3, `Unexpected error during chmod operation for ${outputPath}: ${errorMessage}`); // Assuming ERROR is 3\n overallSuccess = false;\n }\n }\n\n if (owner) {\n // chownTask requires an owner\n log(0, `Setting owner='${owner}'${group ? ` group='${group}'` : ''} for ${outputPath}`); // Assuming DEBUG is 0\n try {\n // ChownParams requires owner: string. group is optional.\n const chownTaskParams: { path: string; owner: string; group?: string; sudo?: boolean } = {\n path: outputPath,\n owner: owner, // owner is guaranteed to be a string here\n sudo,\n };\n if (group) {\n chownTaskParams.group = group;\n }\n\n const chownResult = await run(chownTask(chownTaskParams));\n if (chownResult instanceof Error) {\n error(`Error setting owner/group for ${outputPath}: ${chownResult.message}`); // Assuming ERROR is 3\n overallSuccess = false;\n } else if (!chownResult?.success) {\n error(`Failed to set owner/group for ${outputPath}. chownTask reported failure.`); // Assuming WARN is 2\n overallSuccess = false;\n }\n } catch (error) {\n // Catch unexpected errors from run or promise chain\n const errorMessage = error instanceof Error ? error.message : String(error);\n log(3, `Unexpected error during chown operation for ${outputPath}: ${errorMessage}`); // Assuming ERROR is 3\n overallSuccess = false;\n }\n } else if (group) {\n // Owner is not provided, but group is. Current chownTask cannot set only group.\n log(\n 2,\n `Owner not specified for ${outputPath}, but group '${group}' was. Cannot set only group with current chown task.`,\n ); // Assuming WARN is 2\n // overallSuccess remains unchanged as we didn't attempt an operation that could fail here.\n }\n\n return {\n success: overallSuccess,\n path: outputPath,\n };\n}\n\nexport default task(runFn, { name: 'core.template.write', description: 'Template write.' });\n","export { default as deny } from './deny';\nexport { default as disable } from './disable';\nexport { default as enable } from './enable';\nexport { default as install } from './install';\nexport { default as reload } from './reload';\n","import { task, type TaskContext } from '../../runtime';\n\ninterface UfwDenyParams {\n from_addr?: string; // Source address, defaults to 'any'\n from_port?: number; // Source port\n to_addr?: string; // Destination address\n to_port?: number; // Destination port (only if to_addr is specified)\n}\n\ninterface UfwDenyResult {\n success: boolean;\n}\n\n/**\n * Adds a deny rule to UFW (Uncomplicated Firewall).\n * Rule structure: ufw deny from <from_addr> [port <from_port>] [to <to_addr> [port <to_port>]]\n * @param {TaskContext<UfwDenyParams>} context - The task context with parameters.\n * @returns {Promise<UfwDenyResult>} - An object indicating the success of the operation.\n */\nasync function run(context: TaskContext<UfwDenyParams>): Promise<UfwDenyResult> {\n const { params, exec } = context;\n const from_addr = params.from_addr || 'any';\n const { from_port, to_addr, to_port } = params;\n\n const commandArray: string[] = ['sudo', 'ufw', 'deny'];\n\n commandArray.push('from', from_addr);\n if (from_port !== undefined) {\n commandArray.push('port', from_port.toString());\n }\n\n if (to_addr) {\n commandArray.push('to', to_addr);\n if (to_port !== undefined) {\n commandArray.push('port', to_port.toString());\n }\n }\n\n const { success } = await exec(commandArray, { sudo: true });\n return { success };\n}\n\nexport default task(run, { name: 'core.ufw.deny', description: 'Ufw deny.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface UfwDisableParams {}\n\ninterface UfwDisableResult {\n success: boolean;\n}\n\n/**\n * Disables UFW (Uncomplicated Firewall).\n * This command typically requires sudo privileges.\n * @param {TaskContext<UfwDisableParams>} context - The task context.\n * @returns {Promise<UfwDisableResult>} - An object indicating the success of the operation.\n */\nasync function run(context: TaskContext<UfwDisableParams>): Promise<UfwDisableResult> {\n const { exec } = context;\n\n const { success } = await exec(['sudo', 'ufw', 'disable'], { sudo: true });\n return { success };\n}\n\nexport default task(run, { name: 'core.ufw.disable', description: 'Ufw disable.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface UfwEnableParams {}\n\ninterface UfwEnableResult {\n success: boolean;\n}\n\n/**\n * Enables UFW (Uncomplicated Firewall).\n * This command typically requires sudo privileges and may prompt for confirmation if enabling for the first time.\n * @param {TaskContext<UfwEnableParams>} context - The task context.\n * @returns {Promise<UfwEnableResult>} - An object indicating the success of the operation.\n */\nasync function run(context: TaskContext<UfwEnableParams>): Promise<UfwEnableResult> {\n const { exec } = context;\n\n const { success } = await exec(['yes | sudo ufw enable'], { sudo: true });\n return { success };\n}\n\nexport default task(run, { name: 'core.ufw.enable', description: 'Ufw enable.' });\n","import { task, type TaskContext } from '../../runtime';\nimport pkgInstallTask from '../pkg/install';\n\ninterface UfwInstallParams {}\n\ninterface UfwInstallResult {\n success: boolean;\n}\n\n/**\n * Installs the UFW (Uncomplicated Firewall) package using the core package installation task.\n * @param {TaskContext<UfwInstallParams>} context - The task context.\n * @returns {Promise<UfwInstallResult>} - An object indicating the success of the package installation.\n */\nasync function run(context: TaskContext<UfwInstallParams>): Promise<UfwInstallResult> {\n const { run: runTask, error } = context;\n\n const installResult = await runTask(pkgInstallTask({ package: 'ufw', sudo: true }));\n\n if (installResult instanceof Error) {\n error(`Error during UFW package installation: ${installResult.message}`);\n return { success: false };\n }\n\n if (typeof installResult?.success === 'boolean') {\n if (!installResult.success) {\n error(`UFW package installation failed (reported by pkg/install).`);\n }\n return { success: installResult.success };\n }\n\n return { success: false };\n}\n\nexport default task(run, { name: 'core.ufw.install', description: 'Ufw install.' });\n","import { task, type TaskContext } from '../../runtime';\n\ninterface UfwReloadParams {}\n\ninterface UfwReloadResult {\n success: boolean;\n}\n\n/**\n * Reloads UFW (Uncomplicated Firewall) rules.\n * This command typically requires sudo privileges.\n * @param {TaskContext<UfwReloadParams>} context - The task context.\n * @returns {Promise<UfwReloadResult>} - An object indicating the success of the operation.\n */\nasync function run(context: TaskContext<UfwReloadParams>): Promise<UfwReloadResult> {\n const { exec } = context;\n\n const { success } = await exec(['sudo', 'ufw', 'reload'], { sudo: true });\n return { success };\n}\n\nexport default task(run, { name: 'core.ufw.reload', description: 'Ufw reload.' });\n","import addGroups, { type AddGroupsParams, type AddGroupsResult } from './add_groups';\nimport create, { type CreateUserParams, type CreateUserResult } from './create';\nimport exists, { type UserExistsParams, type UserExistsResult } from './exists';\nimport getGid, { type GetGidParams, type GetGidResult } from './get_gid';\nimport getGroups, { type GetGroupsParams, type GetGroupsResult } from './get_groups';\nimport getUid, { type GetUidParams, type GetUidResult } from './get_uid';\nimport getUsername, { type GetUsernameResult } from './get_username';\nimport homeDir, { type UserHomeDirParams, type UserHomeDirResult } from './home_dir';\nimport setGroups, { type SetUserGroupsParams, type SetUserGroupsResult } from './set_groups';\nimport setShell, { type SetUserShellParams, type SetUserShellResult } from './set_shell';\nimport del, { type UserDeleteParams, type UserDeleteResult } from './delete';\nimport modify from './modify';\n\nexport {\n addGroups,\n type AddGroupsParams,\n type AddGroupsResult,\n create,\n type CreateUserParams,\n type CreateUserResult,\n exists,\n type UserExistsParams,\n type UserExistsResult,\n getGid,\n type GetGidParams,\n type GetGidResult,\n getGroups,\n type GetGroupsParams,\n type GetGroupsResult,\n getUid,\n type GetUidParams,\n type GetUidResult,\n getUsername,\n type GetUsernameResult,\n homeDir,\n type UserHomeDirParams,\n type UserHomeDirResult,\n setGroups,\n type SetUserGroupsParams,\n type SetUserGroupsResult,\n setShell,\n type SetUserShellParams,\n type SetUserShellResult,\n del as delete,\n type UserDeleteParams,\n type UserDeleteResult,\n modify,\n};\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface AddGroupsParams {\n user: string;\n groups: string[];\n}\n\nexport interface AddGroupsResult {\n success: boolean;\n}\n\n/**\n * @param {user: string, groups: string[]} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<AddGroupsParams>): Promise<AddGroupsResult> {\n const { params, exec } = context;\n const { user, groups } = params;\n\n // Only proceed if groups array is not empty\n if (groups.length === 0) {\n return { success: true };\n }\n\n // Add groups to user using usermod command with --append\n const groupsStr = groups.join(',');\n const command = ['sudo', 'usermod', '--append', '-G', groupsStr, user].filter(Boolean).join(' ');\n\n const { success } = await exec(command);\n\n return {\n success,\n };\n}\n\nexport default task(run, { name: 'core.user.add_groups', description: 'User add groups.' });\n","import { task, type TaskContext } from '../../runtime';\nimport exists from './exists';\nimport homeDir from './home_dir';\n\nexport interface CreateUserParams {\n user: string;\n create_home?: boolean;\n create_group?: boolean;\n system?: boolean;\n sudo?: boolean;\n}\n\nexport interface CreateUserResult {\n success: boolean;\n}\n\n/**\n * @param {user: string, create_home?: boolean, create_group?: boolean, system?: boolean} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<CreateUserParams>): Promise<CreateUserResult> {\n const { params, exec, run: runTask } = context;\n const { user, create_home = true, create_group = true, system = false, sudo = true } = params;\n\n // First check if user exists\n const { exists: userExists } = await runTask(exists({ user }));\n if (userExists) {\n return { success: true };\n }\n\n // Build useradd command with appropriate flags\n const command = [\n sudo ? 'sudo' : '',\n 'useradd',\n create_home ? '--create-home' : '--no-create-home',\n create_group ? '--user-group' : '--no-user-group',\n system ? '--system' : '',\n user,\n ]\n .filter(Boolean)\n .join(' ');\n\n const { success } = await exec(command, { sudo });\n\n // If create_home is true, verify home directory exists or create it\n let createHomeSuccess = true;\n if (create_home && success) {\n const { exists: homeDirExists } = await runTask(homeDir({ user }));\n if (!homeDirExists) {\n const { success: mkhomeSuccess } = await exec(`sudo mkhomedir_helper ${user}`);\n createHomeSuccess = mkhomeSuccess;\n }\n }\n\n return {\n success: success && createHomeSuccess,\n };\n}\n\nexport default task(run, { name: 'core.user.create', description: 'User create.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GetGidParams {\n user: string;\n}\n\nexport interface GetGidResult {\n success: boolean;\n gid: string;\n}\n\n/**\n * @param {user: string} params\n * @returns {\n * success: boolean\n * gid: string\n * }\n */\nasync function run(context: TaskContext<GetGidParams>): Promise<GetGidResult> {\n const { params, exec } = context;\n const { user } = params;\n\n // Get user's GID using id command\n const command = ['id', '-g', user].filter(Boolean).join(' ');\n\n const { success, stdout: gid } = await exec(command);\n\n return {\n success,\n gid: gid.trim(),\n };\n}\n\nexport default task(run, { name: 'core.user.get_gid', description: 'User get gid.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GetGroupsParams {\n user: string;\n}\n\nexport interface GetGroupsResult {\n success: boolean;\n groups: string[];\n}\n\n/**\n * @param {user: string} params\n * @returns {\n * success: boolean\n * groups: string[]\n * }\n */\nasync function run(context: TaskContext<GetGroupsParams>): Promise<GetGroupsResult> {\n const { params, exec } = context;\n const { user } = params;\n\n // Get user's groups using groups command\n const command = ['groups', user].filter(Boolean).join(' ');\n\n const { success, stdout } = await exec(command);\n\n // Parse groups from output\n let groups: string[] = [];\n if (success) {\n const match = stdout.match(new RegExp(`${user} : (.*)`));\n if (match) {\n groups = match[1].split(' ').filter(Boolean);\n }\n }\n\n return {\n success,\n groups,\n };\n}\n\nexport default task(run, { name: 'core.user.get_groups', description: 'User get groups.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface GetUidParams {\n user: string;\n}\n\nexport interface GetUidResult {\n success: boolean;\n uid: string;\n}\n\n/**\n * @param {user: string} params\n * @returns {\n * success: boolean\n * uid: string\n * }\n */\nasync function run(context: TaskContext<GetUidParams>): Promise<GetUidResult> {\n const { params, exec } = context;\n const { user } = params;\n\n // Get user's UID using id command\n const command = ['id', '-u', user].filter(Boolean).join(' ');\n\n const { success, stdout: uid } = await exec(command);\n\n return {\n success,\n uid: uid.trim(),\n };\n}\n\nexport default task(run, { name: 'core.user.get_uid', description: 'User get uid.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface SetUserGroupsParams {\n user: string;\n groups: string[];\n}\n\nexport interface SetUserGroupsResult {\n success: boolean;\n}\n\n/**\n * @param {user: string, groups: string[]} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<SetUserGroupsParams>): Promise<SetUserGroupsResult> {\n const { params, exec } = context;\n const { user, groups } = params;\n\n // Only proceed if groups array is not empty\n if (groups.length === 0) {\n return { success: true };\n }\n\n // Set user's groups using usermod command\n const groupsStr = groups.join(',');\n const command = ['sudo', 'usermod', '-G', groupsStr, user].filter(Boolean).join(' ');\n\n const { success } = await exec(command);\n\n return {\n success,\n };\n}\n\nexport default task(run, { name: 'core.user.set_groups', description: 'User set groups.' });\n","import { task, type TaskContext } from '../../runtime';\n\nexport interface SetUserShellParams {\n user: string;\n shell: string;\n}\n\nexport interface SetUserShellResult {\n success: boolean;\n}\n\n/**\n * @param {user: string, shell: string} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<SetUserShellParams>): Promise<SetUserShellResult> {\n const { params, exec } = context;\n const { user, shell } = params;\n\n // Set user's shell using usermod command\n const command = ['sudo', 'usermod', '-s', shell, user].filter(Boolean).join(' ');\n\n const { success } = await exec(command);\n\n return {\n success,\n };\n}\n\nexport default task(run, { name: 'core.user.set_shell', description: 'User set shell.' });\n","import { type TaskContext, task } from '../../runtime';\nimport exists from './exists';\n\nexport interface UserDeleteParams {\n user: string;\n /** If true, remove the user's home directory and mail spool. */\n remove?: boolean;\n /** Whether to run the command with sudo. Defaults to true. */\n sudo?: boolean;\n}\n\nexport interface UserDeleteResult {\n success: boolean;\n error?: string;\n}\n\n/**\n * Deletes a user from the system idempotently (Linux only).\n * @param context params is a map of the form { user: string, remove?: boolean }.\n * remove - remove home directory and mail spool\n * @returns The result of the task.\n */\nasync function run(context: TaskContext<UserDeleteParams>): Promise<UserDeleteResult> {\n const { params, debug, exec, run } = context;\n const { user, remove = false, sudo = true } = params;\n\n // Check if user exists by calling the user.exists task.\n const { exists: userExists } = await run(exists({ user }));\n\n if (!userExists) {\n // User does not exist, so we are done (idempotency).\n debug(`User '${user}' does not exist, considering task successful (idempotent).`);\n return { success: true };\n }\n\n const args = [];\n if (remove) {\n args.push('--remove');\n }\n args.push(user);\n\n const command: string[] = [];\n if (sudo) {\n command.push('sudo');\n }\n command.push('userdel', ...args);\n\n const { failure, stdout, stderr } = await exec(command, { sudo });\n\n if (failure) {\n return { success: false, error: [stdout, stderr].join('\\n') };\n }\n\n debug(`User '${user}' deleted successfully.`);\n\n return { success: true };\n}\n\nexport default task(run, {\n description: 'Deletes a user from the system idempotently',\n});\n","import { task, type TaskContext } from '../../runtime';\nimport exists from './exists';\n\nexport interface ModifyUserParams {\n user: string;\n comment?: string;\n home?: string;\n expiredate?: string;\n gid?: string;\n groups?: string[];\n login?: string;\n lock?: boolean;\n unlock?: boolean;\n move_home?: boolean;\n shell?: string;\n uid?: string;\n sudo?: boolean;\n}\n\nexport interface ModifyUserResult {\n success: boolean;\n}\n\n/**\n * @param {user: string, comment?: string, home?: string, expiredate?: string, gid?: string, groups?: string[], login?: string, lock?: boolean, unlock?: boolean, move_home?: boolean, shell?: string, uid?: string, sudo?: boolean} params\n * @returns {\n * success: boolean\n * }\n */\nasync function run(context: TaskContext<ModifyUserParams>): Promise<ModifyUserResult> {\n const { params, exec, run: runTask } = context;\n const {\n user,\n comment,\n home,\n expiredate,\n gid,\n groups,\n login,\n lock,\n unlock,\n move_home,\n shell,\n uid,\n sudo = true,\n } = params;\n\n // First check if user exists\n const { exists: userExists } = await runTask(exists({ user }));\n if (!userExists) {\n // Depending on desired behavior, you might want to throw an error\n // or return a specific status indicating the user was not found.\n // For now, we'll return success: false.\n return { success: false };\n }\n\n // Build usermod command with appropriate flags\n const command = [\n sudo ? 'sudo' : '',\n 'usermod',\n comment ? `--comment '${comment}'` : '',\n home ? `--home ${home}` : '',\n expiredate ? `--expiredate ${expiredate}` : '',\n gid ? `--gid ${gid}` : '',\n groups ? `--groups ${groups.join(',')}` : '',\n login ? `--login ${login}` : '',\n lock ? '--lock' : '',\n unlock ? '--unlock' : '',\n move_home ? '--move-home' : '',\n shell ? `--shell ${shell}` : '',\n uid ? `--uid ${uid}` : '',\n user,\n ]\n .filter(Boolean)\n .join(' ');\n\n const { success } = await exec(command, { sudo });\n\n return {\n success,\n };\n}\n\nexport default task(run, { name: 'core.user.modify', description: 'Modify an existing user account.' });\n","// Individual task files from src/core/\nimport echo from './echo';\nimport whoami from './whoami';\n\n// Modules from subdirectories of src/core/\n// These assume each subdirectory has an index.ts exporting its contents, often as a namespace.\nimport * as dir from './dir';\nimport * as file from './file';\nimport * as git from './git';\nimport * as group from './group';\nimport * as host from './host';\nimport * as pkg from './pkg';\nimport * as k3s from './k3s';\nimport * as ssh from './ssh';\nimport * as sudoers from './sudoers';\nimport * as system from './system';\nimport * as systemd from './systemd';\nimport * as template from './template';\nimport * as ufw from './ufw';\nimport * as user from './user';\n\nexport default {\n // Individual tasks\n echo,\n whoami,\n\n // Modules from subdirectories\n dir,\n file,\n git,\n group,\n host,\n pkg,\n k3s,\n ssh,\n sudoers,\n system,\n systemd,\n template,\n ufw,\n user,\n};\n"],"mappings":";;;;;;;AAAA,OAAOA,cAAa;AACpB,YAAYC,SAAQ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,CAAC;AAEhD,SAAO;AAAA,IACL;AAAA,EACF;AACF;AAEA,IAAOC,kBAAQ,KAAKF,OAAK,EAAE,MAAM,oBAAoB,aAAa,mCAAmC,CAAC;;;AC9DtG,IAAO,eAAQ;AAAA;AAAA,EAEb;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":["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","process","zip","path","A","isValidUrl","App","path","process","runFn","Mutex","Command","A","runFn","Mutex","Handlebars","fs","StringBuilder","Command","StringBuilder","chalk","Handlebars","path","chalk","ConfigFile","Handlebars","errnoError","Command","match","Handlebars","match","Command","command","os","match","spawnAsync","signalsByName","Command","spawnAsync","signalsByName","match","P","platform","os","A","match","url","path","match","A","key","str","Mutex","match","Mutex","task","App","process","homedir","chalk","A","cmd","match","ConfigFile","identity","invocation","path","run","run","copy_default","run","path","exists","run","path","run","path","run","run","copy_default","run","path","exists_default","run","path","run","path","exists","exists_default","run","run","path","dirname","run","os","dirname","run","dirname","runFn","run","exists","success","run","run","run","create_default","delete_default","exists_default","run","exists","exists_default","run","exists_default","create_default","run","delete_default","run","run","run","match","P","version","run","match","P","run","os","run","info_default","remove_default","update_default","run","run","info_default","run","install","run","install","run","install","install_default","install_default","run","run","remove","run","remove","run","remove","remove_default","run","run","success","update","run","success","update","run","update","update_default","run","info_default","run","info_default","run","path","run","exists","exists_default","run","path","exists","run","run","exists_default","path","run","run","run","run","run","run","run","run","run","run","run","run","fs","path","runFn","run","fs","path","error","disable_default","enable_default","install_default","reload_default","run","run","disable_default","run","enable_default","run","install_default","run","reload_default","create_default","delete_default","exists_default","modify_default","run","run","exists_default","create_default","run","run","match","run","run","run","run","remove","exists_default","delete_default","run","exists_default","modify_default"]}