@sundaeswap/sprinkles 0.8.0 → 0.8.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_sdk","require","_core","_prompts","_yoctocolorsCjs","_interopRequireDefault","_typebox","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_value","fs","_interopRequireWildcard","path","_types","_schemas","_typeGuards","_wallet","_encryption","_txDialog","_index","_formatting","_index2","_utilityActions","e","__esModule","default","t","WeakMap","r","n","o","i","f","__proto__","has","set","getOwnPropertyDescriptor","_defineProperty","_toPropertyKey","value","configurable","writable","_toPrimitive","Symbol","toPrimitive","TypeError","String","Number","Sprinkle","constructor","type","storagePath","options","name","createdAt","updatedAt","actionRegistry","ActionRegistry","currentProfile","profileId","id","profileMeta","sanitizeProfileId","toLowerCase","replace","profilesDir","join","profilePath","test","includes","Error","activeProfilePath","findAvailableId","baseId","candidate","counter","existsSync","scanProfiles","dir","files","readdirSync","filter","endsWith","entries","file","content","readFileSync","parsed","JSON","parse","bigIntReviver","meta","push","loadProfile","filePath","settings","decryptSettings","defaults","addressbook","writeFileSync","saveProfile","dirname","mkdirSync","recursive","Date","toISOString","settingsToSave","encryptSettings","jsonContent","stringify","bigIntReplacer","promptProfileMeta","defaultName","defaultDescription","inputCancellable","message","validate","v","trim","length","description","undefined","createProfile","result","now","prevProfileId","prevProfileMeta","prevDefaults","prevSettings","FillInStruct","UserCancelledError","migrateIfNeeded","legacyPath","SettingsPath","profileData","renameSync","selectOrCreateProfile","profiles","pointerPath","activeId","some","p","selectProfile","available","selection","selectCancellable","choices","map","duplicateProfile","console","log","renameProfile","newId","oldId","newPath","unlinkSync","deleteProfile","others","toDelete","profileToDelete","find","confirmed","confirmCancellable","showMenu","menu","_showMenu","title","main","clearPrevious","process","stdout","write","beforeShow","items","item","index","breadcrumb","colors","dim","selectionResult","selectWithClear","utilitiesMenu","action","promptAndExecute","mintToken","success","error","code","data","policyId","tokenName","amount","blaze","GetBlaze","network","provider","wallet","tx","Core","Transaction","fromCbor","TxCBOR","txCbor","TxDialog","simpleSend","registerStakeScript","settingsMenu","jsonStr","getDisplaySettings","jsonLines","split","repeat","EditStruct","saveSettings","ms","json","hashStr","toNativeScript","hash","bold","overwrite","script","MultisigScriptSchema","selected","editName","updated","delSelected","delName","selectedItem","New","sprinkle","GetProvider","GetProviderFn","GetWallet","GetWalletFn","providerSettings","walletSettings","GetBlazeFn","generateWalletFromMnemonic","SearchSelect","opts","searchCancellable","sep","LoadSettings","fileContent","encryption","encryptSensitiveFields","decryptSensitiveFields","maskSensitiveFields","getProfileById","createProfileNonInteractive","initialSettings","nameLower","duplicate","ActionError","existingId","deleteProfileById","profile","currentTx","expanded","hasSignedThisSession","isHotWallet","HotWallet","walletVkeys","addresses","getUsedAddresses","address","txHash","getTxBodyHash","sigCount","countSignatures","requiredSigners","getRequiredSigners","formatHash","signer","toCbor","slice","beforeSign","needsStakeKey","userAddress","stakeCredential","asBase","getStakeCredential","stakeKeyHash","toString","reqSigners","body","signerArray","Array","from","values","certs","hasCertificates","size","withdrawals","hasWithdrawals","warn","signed","signTransaction","ws","witnessSet","existingVkeys","vkeys","toCore","signedKeys","newSignedKeys","existingPubKeys","Set","vkey","uniqueNewKeys","setVkeys","CborSet","fromCore","VkeyWitness","setWitnessSet","signedTx","added","mergeSignatures","clipboard","Promise","resolve","then","writeSync","cborInput","importedTx","currentHash","importedHash","proceed","sourceVkeys","sourceCount","skipped","txId","submitTransaction","current","def","_fillInStruct","defs","resolvedType","sourceChoice","abChoices","shouldSave","entryName","isOptional","pathDisplay","formatPath","shouldSet","ExtractMessage","innerType","OptionalKind","isUnion","resolved","resolveType","variant","anyOf","matchedDef","isObject","literalFields","properties","fieldSchema","isLiteral","defRecord","allLiteralsMatch","every","fieldName","const","Value","Check","isString","choice","answer","passwordWithClear","defaultString","isSensitive","inputWithClear","isBigInt","s","BigInt","isBoolean","hasDefault","getDefault","promptObject","fillField","fieldType","fieldPath","fieldDefs","fieldDef","isArray","promptArray","itemType","itemPath","itemDefs","itemDef","isTuple","concat","isRef","isThis","isImport","$defs","realType","$ref","fields","fieldNames","registerAction","register","getAction","listActions","list","listActionsByCategory","listByCategory","runAction","input","a","context","executeAction","initNonInteractive","profileName","names","run","argv","mode","detectMode","actions","generateAppHelp","actionName","args","parseCliArgs","generateActionHelp","actionArgs","runCli","serverName","basename","env","runMcp"],"sources":["../../../src/Sprinkle/index.ts"],"sourcesContent":["import { type Provider } from \"@blaze-cardano/query\";\nimport {\n Blaze,\n Core,\n HotWallet,\n type Wallet,\n} from \"@blaze-cardano/sdk\";\nimport { CborSet, VkeyWitness, TxCBOR } from \"@blaze-cardano/core\";\nimport {\n selectCancellable,\n selectWithClear,\n inputCancellable,\n inputWithClear,\n passwordCancellable,\n passwordWithClear,\n confirmCancellable,\n searchCancellable,\n select,\n} from \"./prompts.js\";\nimport colors from \"yoctocolors-cjs\";\nimport { type TSchema, Type, OptionalKind } from \"@sinclair/typebox\";\nimport { Value } from \"@sinclair/typebox/value\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nexport * from \"@sinclair/typebox\";\n\n// Re-export types from types.ts\nexport type { TExact } from \"./types.js\";\nexport type {\n IEncryptionOptions,\n ISprinkleOptions,\n IProfileMeta,\n ICurrentProfile,\n IProfileEntry,\n TxDialogResult,\n TxDialogOptions,\n FieldState,\n RequiredFieldCount,\n FieldMenuResult,\n ObjectMenuResult,\n ArrayMenuResult,\n} from \"./types.js\";\nexport { UserCancelledError } from \"./types.js\";\nimport type {\n TExact,\n IEncryptionOptions,\n ISprinkleOptions,\n IProfileMeta,\n ICurrentProfile,\n IProfileEntry,\n TxDialogResult,\n TxDialogOptions,\n} from \"./types.js\";\nimport { UserCancelledError } from \"./types.js\";\n\n// Re-export schemas from schemas.ts\nexport {\n NetworkSchema,\n MultisigScriptModule,\n MultisigScript,\n NativeScriptInputSchema,\n NativeScriptsParam,\n ProviderSettingsSchema,\n WalletSettingsSchema,\n} from \"./schemas.js\";\nexport type { TMultisigScript } from \"./schemas.js\";\nimport type { TMultisigScript } from \"./schemas.js\";\nimport { MultisigScript as MultisigScriptSchema } from \"./schemas.js\";\n\n// Import and re-export type guards\nimport {\n isOptional,\n isImport,\n isArray,\n isBigInt,\n isBoolean,\n isInteger,\n isLiteral,\n isNumber,\n isObject,\n isRef,\n isString,\n isThis,\n isTuple,\n isUnion,\n isSensitive,\n isNull,\n isNullable,\n unwrapNullable,\n hasDefault,\n getDefault,\n} from \"./type-guards.js\";\nexport {\n isOptional,\n isImport,\n isArray,\n isBigInt,\n isBoolean,\n isInteger,\n isLiteral,\n isNumber,\n isObject,\n isRef,\n isString,\n isThis,\n isTuple,\n isUnion,\n isSensitive,\n isNull,\n isNullable,\n unwrapNullable,\n hasDefault,\n getDefault,\n} from \"./type-guards.js\";\n\n// Import schemas for use in this file\nimport {\n NetworkSchema,\n ProviderSettingsSchema,\n WalletSettingsSchema,\n} from \"./schemas.js\";\n\n// Import and re-export wallet utilities\nimport {\n GetProvider as GetProviderFn,\n GetWallet as GetWalletFn,\n GetBlaze as GetBlazeFn,\n generateWalletFromMnemonic,\n} from \"./wallet.js\";\nexport { GetProvider, GetWallet, GetBlaze } from \"./wallet.js\";\n\n// Import encryption utilities\nimport {\n collectSensitivePaths,\n getNestedValue,\n setNestedValue,\n bigIntReplacer,\n bigIntReviver,\n encryptSensitiveFields,\n decryptSensitiveFields,\n maskSensitiveFields,\n} from \"./encryption.js\";\n\n// Import tx-dialog utilities\nimport {\n getWalletPaymentKeyHash,\n countSignatures,\n hasVkeySigned,\n getRequiredSigners,\n getTxBodyHash,\n formatHash,\n mergeSignatures,\n} from \"./tx-dialog.js\";\n\n// Import menu modules\nimport { promptObject, promptArray } from \"./menus/index.js\";\nimport { formatPath } from \"./utils/formatting.js\";\n\n// Import and re-export action system\nimport {\n ActionRegistry,\n ActionError,\n executeAction,\n detectMode,\n parseCliArgs,\n generateActionHelp,\n camelToKebab,\n kebabToCamel,\n coerceValue,\n parseArgvWithSchema,\n generateAppHelp,\n runCli,\n runMcp,\n promptAndExecute,\n} from \"./actions/index.js\";\nimport type { AnyAction, IActionContext, IActionResult } from \"./actions/index.js\";\nimport { toNativeScript } from \"./actions/index.js\";\nexport type { IAction, IActionContext, IActionResult, IActionSuccess, IActionFailure, AnyAction } from \"./actions/index.js\";\nexport {\n ActionRegistry,\n ActionError,\n executeAction,\n detectMode,\n parseCliArgs,\n generateActionHelp,\n camelToKebab,\n kebabToCamel,\n coerceValue,\n parseArgvWithSchema,\n generateAppHelp,\n runCli,\n typeboxToJsonSchema,\n coerceMcpInput,\n getMcpSdk,\n createMcpServer,\n runMcp,\n getBuiltinActions,\n promptAndExecute,\n} from \"./actions/index.js\";\nimport {\n mintToken,\n simpleSend,\n registerStakeScript,\n} from \"./actions/builtin/utility-actions.js\";\n\nexport interface IMenuAction<S extends TSchema> {\n title: string;\n action: (sprinkle: Sprinkle<S>) => Promise<Sprinkle<S> | void>;\n}\nexport type TMenuItem<S extends TSchema> = IMenuAction<S> | IMenu<S>;\nexport interface IMenu<S extends TSchema> {\n title: string;\n items: TMenuItem<S>[];\n beforeShow?: (sprinkle: Sprinkle<S>) => Promise<void>;\n}\n\nexport class Sprinkle<S extends TSchema> {\n storagePath: string;\n settings: TExact<S> = {} as TExact<S>;\n type: S;\n defaults: Record<string, unknown> = {};\n addressbook: Record<string, TMultisigScript> = {};\n options: ISprinkleOptions;\n profileId: string = \"\";\n profileMeta: IProfileMeta = { name: \"\", createdAt: \"\", updatedAt: \"\" };\n actionRegistry: ActionRegistry<S>;\n\n constructor(type: S, storagePath: string, options?: ISprinkleOptions) {\n this.type = type;\n this.storagePath = storagePath;\n this.options = options ?? {};\n this.actionRegistry = new ActionRegistry<S>();\n }\n\n // --- Current Profile Accessor ---\n\n get currentProfile(): ICurrentProfile | null {\n if (!this.profileId) return null;\n return {\n id: this.profileId,\n ...this.profileMeta,\n };\n }\n\n // --- Profile path helpers ---\n\n static sanitizeProfileId(name: string): string {\n return (\n name\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, \"\")\n .replace(/[\\s]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\") || \"profile\"\n );\n }\n\n private static profilesDir(storagePath: string): string {\n return path.join(storagePath, \"profiles\");\n }\n\n private static profilePath(storagePath: string, id: string): string {\n if (!id || /[\\/\\\\]/.test(id) || id.includes(\"..\")) {\n throw new Error(`Invalid profile ID: \"${id}\"`);\n }\n return path.join(storagePath, \"profiles\", `${id}.json`);\n }\n\n private static activeProfilePath(storagePath: string): string {\n return path.join(storagePath, \"active-profile\");\n }\n\n private static findAvailableId(profilesDir: string, baseId: string): string {\n let candidate = baseId;\n let counter = 2;\n while (fs.existsSync(path.join(profilesDir, `${candidate}.json`))) {\n candidate = `${baseId}-${counter}`;\n counter++;\n }\n return candidate;\n }\n\n // --- Profile I/O ---\n\n scanProfiles(): IProfileEntry[] {\n const dir = Sprinkle.profilesDir(this.storagePath);\n if (!fs.existsSync(dir)) return [];\n const files = fs.readdirSync(dir).filter((f) => f.endsWith(\".json\"));\n const entries: IProfileEntry[] = [];\n for (const file of files) {\n try {\n const content = fs.readFileSync(path.join(dir, file), \"utf-8\");\n const parsed = JSON.parse(content, Sprinkle.bigIntReviver);\n if (parsed.meta?.name) {\n entries.push({\n id: file.replace(/\\.json$/, \"\"),\n meta: parsed.meta,\n });\n }\n } catch {\n // Skip malformed profile files\n }\n }\n return entries;\n }\n\n async loadProfile(id: string): Promise<void> {\n const filePath = Sprinkle.profilePath(this.storagePath, id);\n const content = fs.readFileSync(filePath, \"utf-8\");\n const parsed = JSON.parse(content, Sprinkle.bigIntReviver);\n this.profileId = id;\n this.profileMeta = parsed.meta;\n this.settings = await this.decryptSettings(parsed.settings as TExact<S>);\n this.defaults = parsed.defaults ?? {};\n this.addressbook = parsed.addressbook ?? {};\n // Update active profile pointer\n fs.writeFileSync(Sprinkle.activeProfilePath(this.storagePath), id, \"utf-8\");\n }\n\n private saveProfile(): void {\n if (!this.profileId) {\n throw new Error(\n \"Cannot save profile: no profile is loaded. Call loadProfile() or create a profile first.\",\n );\n }\n const filePath = Sprinkle.profilePath(this.storagePath, this.profileId);\n const dir = path.dirname(filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n this.profileMeta.updatedAt = new Date().toISOString();\n const settingsToSave = this.encryptSettings(this.settings);\n const jsonContent = JSON.stringify(\n {\n meta: this.profileMeta,\n settings: settingsToSave,\n defaults: this.defaults,\n addressbook: this.addressbook,\n },\n bigIntReplacer,\n 2,\n );\n fs.writeFileSync(filePath, jsonContent, \"utf-8\");\n }\n\n private async promptProfileMeta(\n defaultName?: string,\n defaultDescription?: string,\n ): Promise<{ name: string; description?: string } | null> {\n const name = await inputCancellable({\n message: \"Profile name:\",\n default: defaultName,\n validate: (v) => (v.trim().length > 0 ? true : \"Name cannot be empty\"),\n });\n if (name === null) return null; // User cancelled\n const description = await inputCancellable({\n message: \"Profile description (optional):\",\n default: defaultDescription ?? \"\",\n });\n if (description === null) return null; // User cancelled\n return { name, description: description || undefined };\n }\n\n private async createProfile(): Promise<void> {\n const result = await this.promptProfileMeta();\n if (result === null) return; // User cancelled\n const { name, description } = result;\n const profilesDir = Sprinkle.profilesDir(this.storagePath);\n const id = Sprinkle.findAvailableId(\n profilesDir,\n Sprinkle.sanitizeProfileId(name),\n );\n const now = new Date().toISOString();\n\n // Snapshot current state in case we need to restore on cancellation\n const prevProfileId = this.profileId;\n const prevProfileMeta = this.profileMeta;\n const prevDefaults = this.defaults;\n const prevSettings = this.settings;\n\n this.profileId = id;\n this.profileMeta = { name, description, createdAt: now, updatedAt: now };\n this.defaults = {};\n try {\n this.settings = await this.FillInStruct(this.type);\n } catch (e) {\n // Restore previous state on cancellation\n if (e instanceof UserCancelledError) {\n this.profileId = prevProfileId;\n this.profileMeta = prevProfileMeta;\n this.defaults = prevDefaults;\n this.settings = prevSettings;\n return;\n }\n throw e;\n }\n this.saveProfile();\n fs.writeFileSync(Sprinkle.activeProfilePath(this.storagePath), id, \"utf-8\");\n }\n\n private async migrateIfNeeded(): Promise<void> {\n const profilesDir = Sprinkle.profilesDir(this.storagePath);\n const legacyPath = Sprinkle.SettingsPath(this.storagePath);\n\n if (!fs.existsSync(profilesDir)) {\n if (fs.existsSync(legacyPath)) {\n // Migrate legacy settings.json -> profiles/default.json\n const content = fs.readFileSync(legacyPath, \"utf-8\");\n const parsed = JSON.parse(content, Sprinkle.bigIntReviver);\n const now = new Date().toISOString();\n const profileData = {\n meta: {\n name: \"Default\",\n createdAt: now,\n updatedAt: now,\n },\n settings: parsed.settings,\n defaults: parsed.defaults ?? {},\n addressbook: parsed.addressbook ?? {},\n };\n fs.mkdirSync(profilesDir, { recursive: true });\n fs.writeFileSync(\n Sprinkle.profilePath(this.storagePath, \"default\"),\n JSON.stringify(profileData, bigIntReplacer, 2),\n \"utf-8\",\n );\n fs.writeFileSync(\n Sprinkle.activeProfilePath(this.storagePath),\n \"default\",\n \"utf-8\",\n );\n // Backup legacy file\n fs.renameSync(legacyPath, `${legacyPath}.bak`);\n } else {\n fs.mkdirSync(profilesDir, { recursive: true });\n }\n }\n }\n\n private async selectOrCreateProfile(): Promise<void> {\n const profiles = this.scanProfiles();\n\n if (profiles.length === 0) {\n await this.createProfile();\n return;\n }\n\n if (profiles.length === 1) {\n await this.loadProfile(profiles[0]!.id);\n return;\n }\n\n // Multiple profiles: check active-profile pointer\n const pointerPath = Sprinkle.activeProfilePath(this.storagePath);\n if (fs.existsSync(pointerPath)) {\n const activeId = fs.readFileSync(pointerPath, \"utf-8\").trim();\n if (profiles.some((p) => p.id === activeId)) {\n await this.loadProfile(activeId);\n return;\n }\n }\n\n // No valid pointer - show selector\n await this.selectProfile(profiles);\n }\n\n private async selectProfile(profiles?: IProfileEntry[]): Promise<void> {\n const available = profiles ?? this.scanProfiles();\n const selection = await selectCancellable({\n message: \"Select a profile:\",\n choices: available.map((p) => ({\n name: p.meta.description\n ? `${p.meta.name} - ${p.meta.description}`\n : p.meta.name,\n value: p.id,\n })),\n });\n if (selection === null) return; // User cancelled\n await this.loadProfile(selection as string);\n }\n\n // --- Profile management (CRUD) ---\n\n private async duplicateProfile(): Promise<void> {\n const result = await this.promptProfileMeta(\n `${this.profileMeta.name} (copy)`,\n this.profileMeta.description,\n );\n if (result === null) return; // User cancelled\n const { name, description } = result;\n const profilesDir = Sprinkle.profilesDir(this.storagePath);\n const id = Sprinkle.findAvailableId(\n profilesDir,\n Sprinkle.sanitizeProfileId(name),\n );\n const now = new Date().toISOString();\n // Write duplicate with current settings\n const settingsToSave = this.encryptSettings(this.settings);\n const jsonContent = JSON.stringify(\n {\n meta: { name, description, createdAt: now, updatedAt: now },\n settings: settingsToSave,\n defaults: this.defaults,\n addressbook: this.addressbook,\n },\n bigIntReplacer,\n 2,\n );\n fs.writeFileSync(\n path.join(profilesDir, `${id}.json`),\n jsonContent,\n \"utf-8\",\n );\n console.log(`Profile \"${name}\" created as a copy.`);\n }\n\n private async renameProfile(): Promise<void> {\n const result = await this.promptProfileMeta(\n this.profileMeta.name,\n this.profileMeta.description,\n );\n if (result === null) return; // User cancelled\n const { name, description } = result;\n const newId = Sprinkle.sanitizeProfileId(name);\n const oldId = this.profileId;\n\n this.profileMeta.name = name;\n this.profileMeta.description = description;\n\n if (newId !== oldId) {\n const newPath = Sprinkle.profilePath(this.storagePath, newId);\n if (fs.existsSync(newPath)) {\n console.log(\n `A profile with ID \"${newId}\" already exists. Choose a different name.`,\n );\n return;\n }\n // Save to new path, remove old file\n this.profileId = newId;\n this.saveProfile();\n fs.unlinkSync(Sprinkle.profilePath(this.storagePath, oldId));\n fs.writeFileSync(\n Sprinkle.activeProfilePath(this.storagePath),\n newId,\n \"utf-8\",\n );\n } else {\n this.saveProfile();\n }\n console.log(`Profile renamed to \"${name}\".`);\n }\n\n private async deleteProfile(): Promise<void> {\n const profiles = this.scanProfiles();\n const others = profiles.filter((p) => p.id !== this.profileId);\n\n if (others.length === 0) {\n console.log(\"Cannot delete the only profile.\");\n return;\n }\n\n const toDelete = await selectCancellable({\n message: \"Select a profile to delete:\",\n choices: others.map((p) => ({\n name: p.meta.description\n ? `${p.meta.name} - ${p.meta.description}`\n : p.meta.name,\n value: p.id,\n })),\n });\n\n if (toDelete === null) return; // User cancelled\n\n const profileId = toDelete as string;\n const profileToDelete = others.find((p) => p.id === profileId);\n const confirmed = await confirmCancellable({\n message: `Delete profile \"${profileToDelete?.meta.name ?? profileId}\"? This cannot be undone.`,\n default: false,\n });\n\n if (confirmed === null) return; // User cancelled\n\n if (confirmed) {\n fs.unlinkSync(Sprinkle.profilePath(this.storagePath, profileId));\n console.log(\n `Profile \"${profileToDelete?.meta.name ?? profileId}\" deleted.`,\n );\n }\n }\n\n // --- Menu ---\n\n async showMenu(menu: IMenu<S>): Promise<void> {\n return this._showMenu(menu, true, [menu.title]);\n }\n\n private async _showMenu(menu: IMenu<S>, main: boolean, path: string[], clearPrevious = false): Promise<void> {\n // Clear previous breadcrumb if coming back from action/submenu\n if (clearPrevious) {\n process.stdout.write(\"\\x1b[1A\\x1b[2K\\x1b[G\");\n }\n\n if (menu.beforeShow) {\n await menu.beforeShow(this);\n }\n const choices = menu.items.map((item, index) => {\n if (\"action\" in item) {\n return { name: item.title, value: index };\n } else {\n return { name: `${item.title} Submenu`, value: index };\n }\n });\n if (!main) {\n choices.push({ name: \"Back\", value: -1 });\n } else {\n choices.push({ name: \"Utilities\", value: -6 });\n choices.push({ name: \"Settings & Profiles\", value: -5 });\n choices.push({ name: \"Exit\", value: -1 });\n }\n\n // Show breadcrumb\n const breadcrumb = path.join(\" > \");\n console.log(colors.dim(\"🍞 \" + breadcrumb));\n\n const selectionResult = await selectWithClear({\n message: \"Select an option:\",\n choices: choices,\n });\n // Handle escape (null) as Back\n // Don't clear here - let the caller's clearPrevious handle it\n if (selectionResult === null) {\n return;\n }\n const selection = selectionResult as number;\n if (selection === -6) {\n const utilitiesMenu: IMenu<S> = {\n title: \"Utilities\",\n items: [\n {\n title: \"Mint Token\",\n action: async () => {\n const result = await promptAndExecute(this, mintToken);\n if (!result.success) {\n if (result.error.code === \"USER_CANCELLED\") return;\n console.error(`\\nError (${result.error.code}): ${result.error.message}\\n`);\n return;\n }\n const data = result.data as { txCbor: string; policyId: string; tokenName: string; amount: string };\n console.log(`\\nPolicy: ${data.policyId}\\nToken: ${data.tokenName}\\nAmount: ${data.amount}\\n`);\n const blaze = await Sprinkle.GetBlaze(\n (this.settings as Record<string, unknown>).network as TExact<typeof NetworkSchema>,\n (this.settings as Record<string, unknown>).provider as TExact<typeof ProviderSettingsSchema>,\n (this.settings as Record<string, unknown>).wallet as TExact<typeof WalletSettingsSchema>,\n );\n const tx = Core.Transaction.fromCbor(Core.TxCBOR(data.txCbor));\n await this.TxDialog(blaze, tx);\n },\n },\n {\n title: \"Simple Send\",\n action: async () => {\n const result = await promptAndExecute(this, simpleSend);\n if (!result.success) {\n if (result.error.code === \"USER_CANCELLED\") return;\n console.error(`\\nError (${result.error.code}): ${result.error.message}\\n`);\n return;\n }\n const data = result.data as { txCbor: string };\n const blaze = await Sprinkle.GetBlaze(\n (this.settings as Record<string, unknown>).network as TExact<typeof NetworkSchema>,\n (this.settings as Record<string, unknown>).provider as TExact<typeof ProviderSettingsSchema>,\n (this.settings as Record<string, unknown>).wallet as TExact<typeof WalletSettingsSchema>,\n );\n const tx = Core.Transaction.fromCbor(Core.TxCBOR(data.txCbor));\n await this.TxDialog(blaze, tx);\n },\n },\n {\n title: \"Register Stake Script\",\n action: async () => {\n const result = await promptAndExecute(this, registerStakeScript);\n if (!result.success) {\n if (result.error.code === \"USER_CANCELLED\") return;\n console.error(`\\nError (${result.error.code}): ${result.error.message}\\n`);\n return;\n }\n const data = result.data as { txCbor: string };\n const blaze = await Sprinkle.GetBlaze(\n (this.settings as Record<string, unknown>).network as TExact<typeof NetworkSchema>,\n (this.settings as Record<string, unknown>).provider as TExact<typeof ProviderSettingsSchema>,\n (this.settings as Record<string, unknown>).wallet as TExact<typeof WalletSettingsSchema>,\n );\n const tx = Core.Transaction.fromCbor(Core.TxCBOR(data.txCbor));\n await this.TxDialog(blaze, tx);\n },\n },\n ],\n };\n await this._showMenu(utilitiesMenu, false, [...path, \"Utilities\"], true);\n await this._showMenu(menu, main, path, true);\n return;\n }\n if (selection === -5) {\n const settingsMenu: IMenu<S> = {\n title: \"Settings & Profiles\",\n items: [\n {\n title: \"View settings\",\n action: async () => {\n const jsonStr = JSON.stringify(this.getDisplaySettings(), bigIntReplacer, 2);\n const jsonLines = jsonStr.split(\"\\n\").length;\n console.log(jsonStr);\n\n // Wait for user to press Enter\n await selectWithClear({\n message: \"Press Enter to continue...\",\n choices: [{ name: \"Continue\", value: \"continue\" }],\n });\n\n // Clear the JSON output\n process.stdout.write(\"\\x1b[1A\\x1b[2K\".repeat(jsonLines) + \"\\x1b[G\");\n },\n },\n {\n title: \"Edit settings\",\n action: async () => {\n try {\n this.settings = await this.EditStruct(this.type, this.settings);\n this.saveSettings();\n } catch (e) {\n if (e instanceof UserCancelledError) {\n return; // User cancelled, return to menu\n }\n throw e;\n }\n },\n },\n {\n title: \"Switch profile\",\n action: async () => {\n this.saveSettings();\n const profiles = this.scanProfiles();\n if (profiles.length <= 1) {\n console.log(\n \"No other profiles to switch to. Create a new one first.\",\n );\n } else {\n await this.selectProfile(profiles);\n }\n },\n },\n {\n title: \"Create new profile\",\n action: async () => {\n await this.createProfile();\n },\n },\n {\n title: \"Duplicate current profile\",\n action: async () => {\n await this.duplicateProfile();\n },\n },\n {\n title: \"Rename current profile\",\n action: async () => {\n await this.renameProfile();\n },\n },\n {\n title: \"Delete a profile\",\n action: async () => {\n await this.deleteProfile();\n },\n },\n {\n title: \"Addressbook\",\n items: [\n {\n title: \"View entries\",\n action: async () => {\n const entries = Object.entries(this.addressbook);\n if (entries.length === 0) {\n console.log(\"Addressbook is empty.\");\n } else {\n for (const [name, ms] of entries) {\n const json = JSON.stringify(ms, bigIntReplacer, 2);\n let hashStr = \"unknown\";\n try {\n hashStr = toNativeScript(ms).hash();\n } catch { /* skip */ }\n console.log(colors.bold(name) + \" \" + colors.dim(hashStr));\n console.log(json);\n console.log();\n }\n }\n await selectWithClear({\n message: \"Press Enter to continue...\",\n choices: [{ name: \"Continue\", value: \"continue\" }],\n });\n },\n },\n {\n title: \"Add entry\",\n action: async () => {\n const name = await inputCancellable({\n message: \"Entry name:\",\n validate: (v) =>\n v.trim().length > 0 ? true : \"Name cannot be empty\",\n });\n if (name === null) return;\n if (this.addressbook[name]) {\n const overwrite = await confirmCancellable({\n message: `Entry \"${name}\" already exists. Overwrite?`,\n default: false,\n });\n if (!overwrite) return;\n }\n try {\n const script = await this.FillInStruct(MultisigScriptSchema);\n this.addressbook[name] = script as TMultisigScript;\n this.saveSettings();\n console.log(`Added \"${name}\" to addressbook.`);\n } catch (e) {\n if (e instanceof UserCancelledError) return;\n throw e;\n }\n },\n },\n {\n title: \"Edit entry\",\n action: async () => {\n const entries = Object.keys(this.addressbook);\n if (entries.length === 0) {\n console.log(\"Addressbook is empty.\");\n return;\n }\n const selected = await selectCancellable({\n message: \"Select entry to edit:\",\n choices: entries.map((n) => ({ name: n, value: n })),\n });\n if (selected === null) return;\n const editName = selected as string;\n try {\n const updated = await this.EditStruct(\n MultisigScriptSchema,\n this.addressbook[editName] as any,\n );\n this.addressbook[editName] = updated as TMultisigScript;\n this.saveSettings();\n console.log(`Updated \"${editName}\".`);\n } catch (e) {\n if (e instanceof UserCancelledError) return;\n throw e;\n }\n },\n },\n {\n title: \"Delete entry\",\n action: async () => {\n const entries = Object.keys(this.addressbook);\n if (entries.length === 0) {\n console.log(\"Addressbook is empty.\");\n return;\n }\n const delSelected = await selectCancellable({\n message: \"Select entry to delete:\",\n choices: entries.map((n) => ({ name: n, value: n })),\n });\n if (delSelected === null) return;\n const delName = delSelected as string;\n const confirmed = await confirmCancellable({\n message: `Delete \"${delName}\"?`,\n default: false,\n });\n if (!confirmed) return;\n delete this.addressbook[delName];\n this.saveSettings();\n console.log(`Deleted \"${delName}\".`);\n },\n },\n ],\n } as IMenu<S>,\n ],\n };\n await this._showMenu(settingsMenu, false, [...path, \"Settings & Profiles\"], true);\n await this._showMenu(menu, main, path, true);\n return;\n }\n if (selection === -1) {\n // Don't clear here - let the caller's clearPrevious handle it\n return;\n }\n const selectedItem = menu.items[selection]!;\n if (\"action\" in selectedItem) {\n // Update breadcrumb to show current action\n process.stdout.write(\"\\x1b[1A\\x1b[2K\\x1b[G\");\n console.log(colors.dim(\"🍞 \" + [...path, selectedItem.title].join(\" > \")));\n\n const result = await selectedItem.action(this);\n if (result instanceof Sprinkle) {\n this.settings = result.settings;\n this.saveSettings();\n }\n await this._showMenu(menu, main, path, true);\n } else {\n await this._showMenu(selectedItem, false, [...path, selectedItem.title], true);\n await this._showMenu(menu, main, path, true);\n }\n return;\n }\n\n static async New<S extends TSchema>(\n type: S,\n storagePath: string,\n options?: ISprinkleOptions,\n ): Promise<Sprinkle<S>> {\n const sprinkle = new Sprinkle<S>(type, storagePath, options);\n await sprinkle.migrateIfNeeded();\n await sprinkle.selectOrCreateProfile();\n sprinkle.saveSettings();\n return sprinkle;\n }\n\n static async GetProvider(\n network: TExact<typeof NetworkSchema>,\n settings: TExact<typeof ProviderSettingsSchema>,\n ): Promise<Provider> {\n return GetProviderFn(network, settings);\n }\n\n static async GetWallet(\n settings: TExact<typeof WalletSettingsSchema>,\n provider: Provider,\n ): Promise<Wallet> {\n return GetWalletFn(settings, provider);\n }\n\n static async GetBlaze(\n network: TExact<typeof NetworkSchema>,\n providerSettings: TExact<typeof ProviderSettingsSchema>,\n walletSettings: TExact<typeof WalletSettingsSchema>,\n ): Promise<Blaze<Provider, Wallet>> {\n return GetBlazeFn(network, providerSettings, walletSettings);\n }\n\n /**\n * Generates a new wallet from a BIP39 mnemonic phrase.\n * Displays the 24-word recovery phrase and requires user confirmation.\n * @returns The Bip32PrivateKey hex string for storage\n */\n private static async generateWalletFromMnemonic(): Promise<string> {\n return generateWalletFromMnemonic();\n }\n\n static async SearchSelect<T>(opts: {\n message: string;\n source: (\n term: string | undefined,\n ) => Promise<{ name: string; value: T }[]> | { name: string; value: T }[];\n }): Promise<T | null> {\n return searchCancellable(opts) as Promise<T | null>;\n }\n\n static SettingsPath(storagePath: string): string {\n return `${storagePath}${path.sep}settings.json`;\n }\n\n async LoadSettings(type: S, storagePath: string): Promise<void> {\n try {\n // Check if the settings file exists\n if (fs.existsSync(storagePath)) {\n // Read and parse the JSON file\n const fileContent = fs.readFileSync(storagePath, \"utf-8\");\n const parsed = JSON.parse(fileContent, Sprinkle.bigIntReviver) as {\n settings: unknown;\n defaults: Record<string, unknown>;\n };\n // Convert string representations back to BigInt where needed\n this.settings = await this.decryptSettings(\n parsed.settings as TExact<S>,\n );\n this.defaults = parsed.defaults;\n } else {\n this.defaults = {};\n this.settings = await this.FillInStruct(type);\n }\n } catch (error) {\n throw new Error(`Error loading settings from ${storagePath}: ${error}`);\n }\n }\n\n static bigIntReviver(key: string, value: unknown): unknown {\n return bigIntReviver(key, value);\n }\n\n private encryptSettings(settings: TExact<S>): TExact<S> {\n if (!this.options.encryption) return settings;\n return encryptSensitiveFields(settings, this.type, this.options.encryption);\n }\n\n private async decryptSettings(settings: TExact<S>): Promise<TExact<S>> {\n if (!this.options.encryption) return settings;\n return decryptSensitiveFields(settings, this.type, this.options.encryption);\n }\n\n saveSettings(): void {\n this.saveProfile();\n }\n\n getDisplaySettings(): TExact<S> {\n return maskSensitiveFields(this.settings, this.type);\n }\n\n // --- Non-interactive profile management (for CLI/MCP actions) ---\n\n /**\n * Look up a profile entry by its ID without loading it.\n * Returns undefined if no profile with the given ID exists.\n */\n getProfileById(id: string): IProfileEntry | undefined {\n return this.scanProfiles().find((p) => p.id === id);\n }\n\n /**\n * Create a new profile file without interactive prompts.\n * Does NOT switch the active profile.\n *\n * @throws ActionError with code DUPLICATE_PROFILE if a profile with the same name already exists.\n * @returns The created IProfileEntry\n */\n async createProfileNonInteractive(\n name: string,\n description?: string,\n initialSettings?: Partial<TExact<S>>,\n ): Promise<IProfileEntry> {\n const profiles = this.scanProfiles();\n const nameLower = name.toLowerCase();\n const duplicate = profiles.find(\n (p) => p.meta.name.toLowerCase() === nameLower,\n );\n if (duplicate) {\n throw new ActionError(\n `A profile named \"${name}\" already exists.`,\n \"DUPLICATE_PROFILE\",\n { existingId: duplicate.id },\n );\n }\n\n const profilesDir = Sprinkle.profilesDir(this.storagePath);\n if (!fs.existsSync(profilesDir)) {\n fs.mkdirSync(profilesDir, { recursive: true });\n }\n\n const baseId = Sprinkle.sanitizeProfileId(name);\n const id = Sprinkle.findAvailableId(profilesDir, baseId);\n const now = new Date().toISOString();\n const meta: IProfileMeta = { name, description, createdAt: now, updatedAt: now };\n\n const profileData = {\n meta,\n settings: initialSettings ?? {},\n defaults: {},\n addressbook: {},\n };\n\n fs.writeFileSync(\n path.join(profilesDir, `${id}.json`),\n JSON.stringify(profileData, bigIntReplacer, 2),\n \"utf-8\",\n );\n\n return { id, meta };\n }\n\n /**\n * Delete a profile file by ID.\n *\n * @throws ActionError with code PROFILE_NOT_FOUND if no profile with the given ID exists.\n * @throws ActionError with code CANNOT_DELETE_ONLY_PROFILE if this is the only profile.\n * @throws ActionError with code CANNOT_DELETE_ACTIVE_PROFILE if this is the currently active profile.\n */\n deleteProfileById(id: string): void {\n const profiles = this.scanProfiles();\n const profile = profiles.find((p) => p.id === id);\n\n if (!profile) {\n throw new ActionError(\n `Profile \"${id}\" not found.`,\n \"PROFILE_NOT_FOUND\",\n { id },\n );\n }\n\n if (profiles.length === 1) {\n throw new ActionError(\n \"Cannot delete the only profile.\",\n \"CANNOT_DELETE_ONLY_PROFILE\",\n { id },\n );\n }\n\n if (id === this.profileId) {\n throw new ActionError(\n \"Cannot delete the active profile. Switch to a different profile first.\",\n \"CANNOT_DELETE_ACTIVE_PROFILE\",\n { id },\n );\n }\n\n fs.unlinkSync(Sprinkle.profilePath(this.storagePath, id));\n }\n\n async TxDialog<P extends Provider, W extends Wallet>(\n blaze: Blaze<P, W>,\n tx: Core.Transaction,\n opts?: TxDialogOptions,\n ): Promise<TxDialogResult> {\n let currentTx = tx;\n let expanded = false;\n let hasSignedThisSession = false;\n\n // Check if wallet can sign (is HotWallet)\n const isHotWallet = blaze.wallet instanceof HotWallet;\n\n // Get wallet's vkeys for detecting if already signed\n let walletVkeys: string[] = [];\n if (isHotWallet) {\n try {\n // Sign a dummy to get the wallet's public keys\n // We'll use this to check if wallet has already signed\n const wallet = blaze.wallet as unknown as HotWallet;\n const addresses = await wallet.getUsedAddresses();\n const address = addresses[0];\n if (address) {\n // We can't easily get vkeys without signing, so we'll track after first sign\n }\n } catch {\n // Ignore errors in setup\n }\n }\n\n while (true) {\n // Display transaction status\n const txHash = getTxBodyHash(currentTx);\n const sigCount = countSignatures(currentTx);\n const requiredSigners = getRequiredSigners(currentTx);\n\n console.log(\"\");\n console.log(`Transaction: ${formatHash(txHash)}`);\n if (requiredSigners.length > 0) {\n console.log(`Signatures: ${sigCount} of ${requiredSigners.length} required`);\n console.log(\"Required signers:\");\n for (const signer of requiredSigners) {\n console.log(` - ${formatHash(signer)}`);\n }\n } else {\n console.log(`Signatures: ${sigCount}`);\n }\n\n // Display CBOR\n const txCbor = currentTx.toCbor();\n if (expanded) {\n console.log(\"Transaction CBOR:\", txCbor);\n } else {\n console.log(\"Transaction CBOR:\", `${String(txCbor).slice(0, 50)}...`);\n }\n\n // Build dynamic menu choices\n const choices: { name: string; value: string }[] = [];\n\n // \"Sign with this wallet\" - only if HotWallet and hasn't signed this session\n if (isHotWallet && !hasSignedThisSession) {\n choices.push({ name: \"Sign with this wallet\", value: \"sign\" });\n }\n\n // CBOR options\n if (!expanded) {\n choices.push({ name: \"Expand CBOR\", value: \"expand\" });\n }\n choices.push({ name: \"Copy CBOR to clipboard\", value: \"copy\" });\n choices.push({ name: \"Import signatures from CBOR\", value: \"import\" });\n\n // Submit and cancel\n choices.push({ name: \"Submit transaction\", value: \"submit\" });\n choices.push({ name: \"Cancel\", value: \"cancel\" });\n\n const selection = await selectWithClear({\n message: \"Select an option:\",\n choices,\n });\n\n // Handle escape/cancel as cancel action\n if (selection === null) {\n if (hasSignedThisSession) {\n return { action: \"signed\", tx: currentTx };\n }\n return { action: \"cancelled\", tx: currentTx };\n }\n\n // Handle selection\n if (selection === \"sign\") {\n if (opts?.beforeSign) {\n await opts.beforeSign();\n }\n\n // Detect if stake key signature is required\n let needsStakeKey = false;\n try {\n const wallet = blaze.wallet as unknown as HotWallet;\n const addresses = await wallet.getUsedAddresses();\n const userAddress = addresses[0];\n if (userAddress) {\n const stakeCredential = userAddress.asBase()?.getStakeCredential();\n const stakeKeyHash = stakeCredential?.hash?.toString();\n\n if (stakeKeyHash) {\n const reqSigners = currentTx.body().requiredSigners();\n if (reqSigners) {\n const signerArray = Array.from(reqSigners.values());\n needsStakeKey = signerArray.some(\n (signer) => signer.toString() === stakeKeyHash,\n );\n }\n\n const certs = currentTx.body().certs();\n const hasCertificates = certs && certs.size() > 0;\n const withdrawals = currentTx.body().withdrawals();\n const hasWithdrawals = withdrawals && withdrawals.size > 0;\n\n if (hasCertificates || hasWithdrawals) {\n needsStakeKey = true;\n }\n }\n }\n\n if (needsStakeKey) {\n console.log(\"Transaction requires stake key signature.\");\n } else {\n console.log(\"Transaction requires payment key signature only.\");\n }\n } catch (error) {\n console.warn(\n \"Could not determine stake key requirement, signing with payment key only.\",\n );\n console.warn(`Error: ${(error as Error).message}`);\n }\n\n try {\n if (needsStakeKey) {\n const wallet = blaze.wallet as unknown as HotWallet;\n const signed = await wallet.signTransaction(currentTx, true, true);\n const ws = currentTx.witnessSet();\n const existingVkeys = ws.vkeys()?.toCore() ?? [];\n\n const signedKeys = signed.vkeys();\n if (!signedKeys) {\n throw new Error(\n \"signTransaction: no signed keys in wallet witness response\",\n );\n }\n\n // Check for duplicates before adding\n const newSignedKeys = signedKeys.toCore();\n const existingPubKeys = new Set(existingVkeys.map(([vkey]) => vkey));\n const uniqueNewKeys = newSignedKeys.filter(\n ([vkey]) => !existingPubKeys.has(vkey),\n );\n\n if (uniqueNewKeys.length === 0) {\n console.log(\"Wallet has already signed this transaction.\");\n } else {\n ws.setVkeys(\n CborSet.fromCore(\n [...existingVkeys, ...uniqueNewKeys],\n VkeyWitness.fromCore,\n ),\n );\n currentTx.setWitnessSet(ws);\n console.log(`Added ${uniqueNewKeys.length} signature(s).`);\n hasSignedThisSession = true;\n }\n } else {\n const signedTx = await blaze.signTransaction(currentTx);\n // Merge signatures from signed tx into current tx\n const added = mergeSignatures(currentTx, signedTx);\n if (added > 0) {\n console.log(`Added ${added} signature(s).`);\n hasSignedThisSession = true;\n } else {\n console.log(\"Wallet has already signed this transaction.\");\n }\n }\n } catch (error) {\n console.error(`Signing failed: ${(error as Error).message}`);\n }\n // Continue loop after signing\n continue;\n }\n\n if (selection === \"expand\") {\n expanded = true;\n continue;\n }\n\n if (selection === \"copy\") {\n try {\n const { default: clipboard } = await import(\"clipboardy\");\n clipboard.writeSync(String(currentTx.toCbor()));\n console.log(\"Transaction CBOR copied to clipboard.\");\n } catch {\n console.log(\"Failed to copy to clipboard, expanding instead.\");\n expanded = true;\n }\n continue;\n }\n\n if (selection === \"import\") {\n const cborInput = await inputCancellable({\n message: \"Paste transaction CBOR (hex):\",\n });\n\n if (cborInput === null || cborInput.trim() === \"\") {\n console.log(\"No CBOR provided.\");\n continue;\n }\n\n try {\n const importedTx = Core.Transaction.fromCbor(\n TxCBOR(cborInput.trim()),\n );\n\n // Validate body hash matches\n const currentHash = getTxBodyHash(currentTx);\n const importedHash = getTxBodyHash(importedTx);\n\n if (currentHash !== importedHash) {\n const proceed = await confirmCancellable({\n message: `Warning: Imported transaction has different body hash.\\nCurrent: ${formatHash(currentHash)}\\nImported: ${formatHash(importedHash)}\\nProceed anyway?`,\n default: false,\n });\n if (proceed === null || !proceed) {\n console.log(\"Import cancelled.\");\n continue;\n }\n }\n\n // Merge signatures\n const added = mergeSignatures(currentTx, importedTx);\n const sourceVkeys = importedTx.witnessSet().vkeys();\n const sourceCount = sourceVkeys ? sourceVkeys.size() : 0;\n const skipped = sourceCount - added;\n\n if (added > 0) {\n console.log(`Added ${added} new signature(s).`);\n }\n if (skipped > 0) {\n console.log(`Skipped ${skipped} duplicate signature(s).`);\n }\n if (added === 0 && skipped === 0) {\n console.log(\"No signatures found in imported transaction.\");\n }\n } catch (error) {\n console.error(`Failed to import CBOR: ${(error as Error).message}`);\n }\n continue;\n }\n\n if (selection === \"submit\") {\n const sigCount = countSignatures(currentTx);\n if (sigCount === 0) {\n const proceed = await confirmCancellable({\n message: \"Warning: Transaction has no signatures. Submit anyway?\",\n default: false,\n });\n if (proceed === null || !proceed) {\n continue;\n }\n }\n\n try {\n const txId = await blaze.submitTransaction(currentTx);\n console.log(`Transaction submitted: ${txId}`);\n return { action: \"submitted\", txId, tx: currentTx };\n } catch (error) {\n console.error(`Submit failed: ${(error as Error).message}`);\n // Continue loop to allow retry or other actions\n continue;\n }\n }\n\n if (selection === \"cancel\") {\n if (hasSignedThisSession) {\n return { action: \"signed\", tx: currentTx };\n }\n return { action: \"cancelled\", tx: currentTx };\n }\n }\n }\n\n /**\n * Edit an existing struct value using a menu-based interface.\n * This is now unified with FillInStruct - both use the same menu system.\n * @param type - The TypeBox schema\n * @param current - The current value to edit\n * @returns The edited value\n */\n async EditStruct<U extends TSchema>(\n type: U,\n current: TExact<U>,\n ): Promise<TExact<U>> {\n // Use FillInStruct with current values as defaults\n // The menu system will show existing values and allow editing\n return this.FillInStruct(type, current);\n }\n\n async FillInStruct<U extends TSchema>(\n type: U,\n def?: TExact<U>,\n ): Promise<TExact<U>> {\n return this._fillInStruct<U>(type, [\"root\"], {}, def);\n }\n\n async _fillInStruct<U extends TSchema>(\n type: U,\n path: string[],\n defs: Record<string, TSchema>,\n def?: TExact<U>,\n ): Promise<TExact<U>> {\n if (\"$ref\" in type) {\n defs = { ...defs, ...type[\"$defs\"] };\n const resolvedType = defs[type[\"$ref\"]];\n if (!resolvedType) {\n throw new Error(\n `Could not resolve type ${type[\"$ref\"]} at ${path.join(\".\")}`,\n );\n }\n\n // Addressbook integration for MultisigScript fields\n if (type[\"$ref\"] === \"MultisigScript\" && Object.keys(this.addressbook).length > 0) {\n const sourceChoice = await selectWithClear({\n message: \"Select source for native script:\",\n choices: [\n { name: \"Enter manually\", value: \"manual\" },\n { name: \"Select from addressbook\", value: \"addressbook\" },\n ],\n });\n if (sourceChoice === null) throw new UserCancelledError();\n if (sourceChoice === \"addressbook\") {\n const entries = Object.entries(this.addressbook);\n const abChoices = entries.map(([name, ms]) => {\n let hashStr = \"\";\n try { hashStr = \" \" + colors.dim(toNativeScript(ms).hash()); } catch { /* skip */ }\n return { name: name + hashStr, value: name };\n });\n const selected = await selectWithClear({\n message: \"Select addressbook entry:\",\n choices: abChoices,\n });\n if (selected === null) throw new UserCancelledError();\n return this.addressbook[selected as string] as TExact<U>;\n }\n }\n\n const result = await this._fillInStruct(resolvedType, path, defs, def) as TExact<U>;\n\n // Offer to save manually entered MultisigScript to addressbook\n if (type[\"$ref\"] === \"MultisigScript\" && result !== undefined) {\n const shouldSave = await selectWithClear({\n message: \"Save this script to the addressbook?\",\n choices: [\n { name: \"No\", value: false },\n { name: \"Yes\", value: true },\n ],\n });\n if (shouldSave) {\n const entryName = await inputCancellable({\n message: \"Addressbook entry name:\",\n validate: (v) => v.trim().length > 0 ? true : \"Name cannot be empty\",\n });\n if (entryName !== null) {\n this.addressbook[entryName] = result as TMultisigScript;\n this.saveSettings();\n console.log(`Saved \"${entryName}\" to addressbook.`);\n }\n }\n }\n\n return result;\n }\n if (isOptional(type)) {\n const pathDisplay = formatPath(path) || \"value\";\n const shouldSet = await selectWithClear({\n message: Sprinkle.ExtractMessage(\n type,\n `Set value for ${pathDisplay}?`,\n ),\n choices: [\n { name: \"Yes\", value: true },\n { name: \"Skip\", value: false },\n ],\n default: def !== undefined,\n });\n if (shouldSet === null) {\n throw new UserCancelledError();\n }\n if (!shouldSet) {\n return undefined as TExact<U>;\n }\n // Unwrap the optional and fill the inner type\n const innerType = { ...type };\n delete (innerType as any)[OptionalKind];\n return this._fillInStruct(innerType as U, path, defs, def);\n }\n\n if (isUnion(type)) {\n const pathDisplay = formatPath(path) || \"value\";\n const choices = [];\n const resolved = this.resolveType(type, path, defs);\n for (const variant of resolved.anyOf) {\n choices.push({\n name: Sprinkle.ExtractMessage(variant, `${variant}`),\n value: variant,\n });\n }\n const selectionResult = await selectWithClear({\n message: Sprinkle.ExtractMessage(\n resolved,\n `Enter a choice for ${pathDisplay}`,\n ),\n choices: choices,\n });\n if (selectionResult === null) {\n throw new UserCancelledError();\n }\n const selection = selectionResult as TSchema;\n // Determine if the provided default value matches the selected variant.\n // For discriminated unions (objects with literal fields like `type`), check\n // if the literal field values in the selected variant match those in `def`.\n // For non-discriminated unions, fall back to structural matching with Value.Check.\n let matchedDef: unknown = undefined;\n if (def !== undefined) {\n if (isObject(selection)) {\n // Check if all literal fields in the selected variant match def\n const literalFields = Object.entries(selection.properties ?? {}).filter(\n ([, fieldSchema]) => isLiteral(fieldSchema as TSchema),\n );\n if (literalFields.length > 0) {\n const defRecord = def as Record<string, unknown>;\n const allLiteralsMatch = literalFields.every(\n ([fieldName, fieldSchema]) =>\n defRecord[fieldName] === (fieldSchema as unknown as { const: unknown }).const,\n );\n if (allLiteralsMatch) {\n matchedDef = def;\n }\n } else {\n // No literal discriminators - use structural check\n if (Value.Check(selection, def)) {\n matchedDef = def;\n }\n }\n } else {\n // Non-object variant - use structural check\n if (Value.Check(selection, def)) {\n matchedDef = def;\n }\n }\n }\n return this._fillInStruct(selection, path, defs, matchedDef as TExact<typeof selection>) as Promise<TExact<U>>;\n }\n\n if (isString(type)) {\n // Special handling for hot wallet private key - offer generation option\n if (type.title === \"Hot Wallet Private Key\") {\n const choice = await selectWithClear({\n message: \"Hot wallet setup:\",\n choices: [\n { name: \"Enter existing private key\", value: \"existing\" },\n { name: \"Generate new wallet\", value: \"generate\" },\n ],\n });\n\n if (choice === null) {\n throw new UserCancelledError();\n }\n if (choice === \"generate\") {\n return Sprinkle.generateWalletFromMnemonic() as Promise<TExact<U>>;\n }\n // Fall through to password prompt for \"existing\" choice\n const answer = await passwordWithClear({\n message: \"Enter your private key:\",\n });\n if (answer === null) {\n throw new UserCancelledError();\n }\n return answer as TExact<U>;\n }\n\n const pathDisplay = formatPath(path) || \"value\";\n const defaultString = (def ? def : this.defaults[\"string\"]) as\n | string\n | undefined;\n const message = Sprinkle.ExtractMessage(\n type,\n `Enter a string for ${pathDisplay}`,\n );\n let answer: string | null;\n if (isSensitive(type)) {\n answer = await passwordWithClear({ message });\n } else {\n answer = await inputWithClear({ message, default: defaultString });\n if (answer !== null) {\n this.defaults[\"string\"] = answer;\n }\n }\n if (answer === null) {\n throw new UserCancelledError();\n }\n return answer as TExact<U>;\n }\n\n if (isBigInt(type)) {\n const pathDisplay = formatPath(path) || \"value\";\n const answer = await inputWithClear({\n message: Sprinkle.ExtractMessage(\n type,\n `Enter a bigint for ${pathDisplay}`,\n ),\n default: def ? (def as bigint).toString() : undefined,\n validate: (s) => {\n try {\n BigInt(s);\n return true;\n } catch {\n return \"Please enter a valid bigint.\";\n }\n },\n });\n if (answer === null) {\n throw new UserCancelledError();\n }\n return BigInt(answer) as TExact<U>;\n }\n\n if (isBoolean(type)) {\n const pathDisplay = formatPath(path) || \"value\";\n const answer = await selectWithClear({\n message: Sprinkle.ExtractMessage(type, `${pathDisplay}?`),\n choices: [\n { name: \"Yes\", value: true },\n { name: \"No\", value: false },\n ],\n default: def !== undefined ? (def as boolean) : hasDefault(type) ? getDefault(type) : undefined,\n });\n if (answer === null) {\n throw new UserCancelledError();\n }\n return answer as TExact<U>;\n }\n\n if (isLiteral(type)) {\n return type.const as TExact<U>;\n }\n\n if (isObject(type)) {\n // Use menu-based editing for objects\n const defaults = def as Record<string, unknown> | undefined;\n const sprinkle = this;\n const result = await promptObject({\n type,\n path,\n defs,\n defaults,\n fillField: async <T extends TSchema>(\n fieldType: T,\n fieldPath: string[],\n fieldDefs: Record<string, TSchema>,\n fieldDef?: unknown,\n ) => {\n return sprinkle._fillInStruct(fieldType, fieldPath, fieldDefs, fieldDef as TExact<T>);\n },\n });\n\n if (result.action === \"cancel\") {\n throw new UserCancelledError();\n }\n\n return result.value as TExact<U>;\n }\n\n if (isArray(type)) {\n // Use menu-based editing for arrays\n const defaults = def as unknown[] | undefined;\n const sprinkle = this;\n const result = await promptArray({\n type,\n path,\n defs,\n defaults,\n fillField: async <T extends TSchema>(\n itemType: T,\n itemPath: string[],\n itemDefs: Record<string, TSchema>,\n itemDef?: unknown,\n ) => {\n return sprinkle._fillInStruct(itemType, itemPath, itemDefs, itemDef as TExact<T>);\n },\n });\n\n if (result.action === \"back\") {\n throw new UserCancelledError();\n }\n\n return result.value as TExact<U>;\n }\n\n if (isTuple(type)) {\n const items = type.items ?? [];\n const result: unknown[] = [];\n for (let i = 0; i < items.length; i++) {\n const itemType = items[i] as U;\n const value = await this._fillInStruct(\n itemType,\n path.concat([`[${i}]`]),\n defs,\n def ? ((def as unknown[])[i] as TExact<U>) : undefined,\n );\n result.push(value);\n }\n return result as TExact<U>;\n }\n\n const pathDisplay = formatPath(path) || \"root\";\n throw new Error(\n `Unable to fill in struct for type at path ${pathDisplay}`,\n );\n }\n\n resolveType<T extends TSchema>(\n type: T,\n path: string[],\n defs: Record<string, TSchema>,\n ): T {\n if (isRef(type) || isThis(type) || isImport(type)) {\n defs = { ...defs, ...type.$defs };\n const realType = defs[type.$ref];\n if (!realType) {\n throw new Error(\n `Invalid type at ${path.join(\".\")}: Unrecognized reference ${type.$ref}`,\n );\n }\n return this.resolveType(realType, path, defs) as T;\n }\n return type;\n }\n\n static ExtractMessage(type: TSchema, def: string): string {\n if (\"title\" in type) {\n return type.title!;\n }\n\n if (\"description\" in type) {\n return type.description!;\n }\n\n if (isLiteral(type)) {\n return `${type.const}`;\n }\n\n if (isObject(type)) {\n const fields = type[\"properties\"] as Record<string, TSchema>;\n if (\"type\" in fields) {\n return Sprinkle.ExtractMessage(fields[\"type\"], def);\n }\n const fieldNames = Object.keys(fields);\n if (fieldNames.length === 1) {\n return fieldNames[0]!;\n }\n }\n\n return def;\n }\n\n // --- Action System ---\n\n /**\n * Register an action on this Sprinkle instance.\n * Delegates to the internal ActionRegistry with name and schema validation.\n */\n registerAction(action: AnyAction<S>): void {\n this.actionRegistry.register(action);\n }\n\n /**\n * Retrieve a registered action by name.\n * @returns The action, or undefined if not registered\n */\n getAction(name: string): AnyAction<S> | undefined {\n return this.actionRegistry.get(name);\n }\n\n /**\n * List all registered actions.\n */\n listActions(): AnyAction<S>[] {\n return this.actionRegistry.list();\n }\n\n /**\n * List all registered actions grouped by category.\n * Uncategorized actions are grouped under \"default\".\n */\n listActionsByCategory(): Map<string, AnyAction<S>[]> {\n return this.actionRegistry.listByCategory();\n }\n\n /**\n * Execute a registered action by name with raw (unvalidated) input.\n * Input is validated against the action's inputSchema before execution.\n *\n * @throws Error if the action name is not registered\n */\n async runAction(\n name: string,\n input: unknown,\n ): Promise<IActionResult<unknown>> {\n const action = this.actionRegistry.get(name);\n if (!action) {\n throw new Error(\n `Action \"${name}\" is not registered. Available actions: ${this.actionRegistry.list().map((a) => a.name).join(\", \") || \"(none)\"}`,\n );\n }\n\n const context: IActionContext<S> = {\n sprinkle: this,\n settings: this.settings,\n };\n\n return executeAction(action, input, context);\n }\n\n /**\n * Non-interactive profile initialization for CLI/MCP modes.\n * Resolves a profile without any user prompts.\n *\n * Resolution order:\n * 1. If profileName provided, load that profile directly\n * 2. If exactly one profile exists, auto-select it\n * 3. If multiple profiles exist and no name given, throw with available names\n * 4. If no profiles exist, throw instructing user to run in interactive mode\n */\n private async initNonInteractive(profileName?: string): Promise<void> {\n await this.migrateIfNeeded();\n\n if (profileName) {\n await this.loadProfile(profileName);\n return;\n }\n\n const profiles = this.scanProfiles();\n\n if (profiles.length === 0) {\n throw new Error(\n \"No profiles found. Run in interactive mode to create one.\",\n );\n }\n\n if (profiles.length === 1) {\n await this.loadProfile(profiles[0]!.id);\n return;\n }\n\n // Multiple profiles without a --profile flag\n const names = profiles.map((p) => `\"${p.id}\" (${p.meta.name})`).join(\", \");\n throw new Error(\n `Multiple profiles found. Specify one with --profile <id>. Available profiles: ${names}`,\n );\n }\n\n /**\n * Static entry point that detects mode and runs accordingly.\n *\n * Modes:\n * - \"tui\" -- Interactive TUI menu (requires menu option)\n * - \"cli\" -- CLI action execution (parses argv for action name and args)\n * - \"mcp\" -- MCP protocol mode (not yet implemented)\n * - \"help\" -- Print available actions and exit\n */\n static async run<S extends TSchema>(opts: {\n type: S;\n storagePath: string;\n menu?: IMenu<S>;\n actions?: AnyAction<S>[];\n options?: ISprinkleOptions;\n argv?: string[];\n }): Promise<void> {\n const argv = opts.argv ?? process.argv.slice(2);\n const mode = detectMode(argv);\n\n if (mode === \"tui\") {\n if (!opts.menu) {\n throw new Error(\n \"TUI mode requires a menu. Provide a menu option or pass --help to see available actions.\",\n );\n }\n const sprinkle = await Sprinkle.New(\n opts.type,\n opts.storagePath,\n opts.options,\n );\n // Register any provided actions\n for (const action of opts.actions ?? []) {\n sprinkle.registerAction(action);\n }\n await sprinkle.showMenu(opts.menu);\n return;\n }\n\n if (mode === \"help\") {\n const sprinkle = new Sprinkle(opts.type, opts.storagePath, opts.options);\n for (const action of opts.actions ?? []) {\n sprinkle.registerAction(action);\n }\n console.log(generateAppHelp(sprinkle.listActions()));\n return;\n }\n\n if (mode === \"cli\") {\n const { actionName, args } = parseCliArgs(argv);\n\n // Extract --profile flag from args if present\n const profileName =\n typeof args[\"profile\"] === \"string\" ? args[\"profile\"] : undefined;\n\n const sprinkle = new Sprinkle(opts.type, opts.storagePath, opts.options);\n for (const action of opts.actions ?? []) {\n sprinkle.registerAction(action);\n }\n\n // Handle action-specific --help BEFORE profile initialization\n // (help should work without a profile)\n if (args[\"help\"] === true) {\n const action = sprinkle.getAction(actionName);\n if (action) {\n console.log(generateActionHelp(action));\n } else {\n console.log(`Unknown action \"${actionName}\". Run --help to see available actions.`);\n }\n return;\n }\n\n await sprinkle.initNonInteractive(profileName);\n\n // Remove internal flags from args before passing to action\n const actionArgs = { ...args };\n delete actionArgs[\"profile\"];\n delete actionArgs[\"help\"];\n\n // Build context and delegate to runCli for proper error routing\n const context = {\n sprinkle,\n settings: sprinkle.settings,\n };\n await runCli(sprinkle, actionName, actionArgs, context);\n return;\n }\n\n if (mode === \"mcp\") {\n // Derive a server name from the storage path basename, falling back to a\n // sensible default.\n const serverName = path.basename(opts.storagePath) || \"sprinkle-mcp\";\n\n const sprinkle = new Sprinkle(opts.type, opts.storagePath, opts.options);\n for (const action of opts.actions ?? []) {\n sprinkle.registerAction(action);\n }\n\n // Read profile name from environment variable (MCP clients have no\n // interactive terminal to prompt for profile selection).\n const profileName = process.env[\"SPRINKLE_PROFILE\"];\n\n await sprinkle.initNonInteractive(profileName);\n await runMcp(sprinkle, serverName);\n return;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,IAAAA,IAAA,GAAAC,OAAA;AAMA,IAAAC,KAAA,GAAAD,OAAA;AACA,IAAAE,QAAA,GAAAF,OAAA;AAWA,IAAAG,eAAA,GAAAC,sBAAA,CAAAJ,OAAA;AACA,IAAAK,QAAA,GAAAL,OAAA;AAIAM,MA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G;QACdtL,QAAQ;QACRvI,QAAQ,EAAEuI,QAAQ,CAACvI;MACrB,CAAC;MACD,MAAM,IAAA6U,cAAM,EAACtM,QAAQ,EAAEiM,UAAU,EAAEI,UAAU,EAAEf,OAAO,CAAC;MACvD;IACF;IAEA,IAAIO,IAAI,KAAK,KAAK,EAAE;MAClB;MACA;MACA,MAAMU,UAAU,GAAGja,IAAI,CAACka,QAAQ,CAAC9L,IAAI,CAAC7L,WAAW,CAAC,IAAI,cAAc;MAEpE,MAAMmL,QAAQ,GAAG,IAAItL,QAAQ,CAACgM,IAAI,CAAC9L,IAAI,EAAE8L,IAAI,CAAC7L,WAAW,EAAE6L,IAAI,CAAC5L,OAAO,CAAC;MACxE,KAAK,MAAMkI,MAAM,IAAI0D,IAAI,CAACqL,OAAO,IAAI,EAAE,EAAE;QACvC/L,QAAQ,CAAC4K,cAAc,CAAC5N,MAAM,CAAC;MACjC;;MAEA;MACA;MACA,MAAMyO,WAAW,GAAGtP,OAAO,CAACsQ,GAAG,CAAC,kBAAkB,CAAC;MAEnD,MAAMzM,QAAQ,CAACwL,kBAAkB,CAACC,WAAW,CAAC;MAC9C,MAAM,IAAAiB,cAAM,EAAC1M,QAAQ,EAAEuM,UAAU,CAAC;MAClC;IACF;EACF;AACF;AAACxa,OAAA,CAAA2C,QAAA,GAAAA,QAAA","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_sdk","require","_core","_prompts","_yoctocolorsCjs","_interopRequireDefault","_typebox","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_value","fs","_interopRequireWildcard","path","_types","_schemas","_typeGuards","_wallet","_encryption","_txDialog","_index","_formatting","_index2","_utilityActions","e","__esModule","default","t","WeakMap","r","n","o","i","f","__proto__","has","set","getOwnPropertyDescriptor","_defineProperty","_toPropertyKey","value","configurable","writable","_toPrimitive","Symbol","toPrimitive","TypeError","String","Number","Sprinkle","constructor","type","storagePath","options","name","createdAt","updatedAt","actionRegistry","ActionRegistry","currentProfile","profileId","id","profileMeta","sanitizeProfileId","toLowerCase","replace","profilesDir","join","profilePath","test","includes","Error","activeProfilePath","findAvailableId","baseId","candidate","counter","existsSync","scanProfiles","dir","files","readdirSync","filter","endsWith","entries","file","content","readFileSync","parsed","JSON","parse","bigIntReviver","meta","push","loadProfile","filePath","settings","decryptSettings","defaults","addressbook","writeFileSync","saveProfile","dirname","mkdirSync","recursive","Date","toISOString","settingsToSave","encryptSettings","jsonContent","stringify","bigIntReplacer","promptProfileMeta","defaultName","defaultDescription","inputCancellable","message","validate","v","trim","length","description","undefined","createProfile","result","now","prevProfileId","prevProfileMeta","prevDefaults","prevSettings","FillInStruct","UserCancelledError","migrateIfNeeded","legacyPath","SettingsPath","profileData","renameSync","selectOrCreateProfile","profiles","pointerPath","activeId","some","p","selectProfile","available","selection","selectCancellable","choices","map","duplicateProfile","console","log","renameProfile","newId","oldId","newPath","unlinkSync","deleteProfile","others","toDelete","profileToDelete","find","confirmed","confirmCancellable","showMenu","menu","_showMenu","title","main","clearPrevious","process","stdout","write","beforeShow","items","item","index","breadcrumb","colors","dim","selectionResult","selectWithClear","utilitiesMenu","action","promptAndExecute","mintToken","success","error","code","data","policyId","tokenName","amount","blaze","GetBlaze","network","provider","wallet","tx","Core","Transaction","fromCbor","TxCBOR","txCbor","TxDialog","simpleSend","registerStakeScript","settingsMenu","jsonStr","getDisplaySettings","jsonLines","split","repeat","EditStruct","saveSettings","ms","json","hashStr","toNativeScript","hash","bold","overwrite","script","MultisigScriptSchema","selected","editName","updated","delSelected","delName","selectedItem","New","sprinkle","GetProvider","GetProviderFn","GetWallet","GetWalletFn","providerSettings","walletSettings","GetBlazeFn","generateWalletFromMnemonic","SearchSelect","opts","searchCancellable","sep","LoadSettings","fileContent","encryption","encryptSensitiveFields","decryptSensitiveFields","maskSensitiveFields","getProfileById","createProfileNonInteractive","initialSettings","nameLower","duplicate","ActionError","existingId","deleteProfileById","profile","currentTx","expanded","hasSignedThisSession","isHotWallet","HotWallet","walletVkeys","addresses","getUsedAddresses","address","txHash","getTxBodyHash","sigCount","countSignatures","requiredSigners","getRequiredSigners","formatHash","signer","toCbor","slice","beforeSign","needsStakeKey","userAddress","stakeCredential","asBase","getStakeCredential","stakeKeyHash","toString","reqSigners","body","signerArray","Array","from","values","certs","hasCertificates","size","withdrawals","hasWithdrawals","warn","signed","signTransaction","ws","witnessSet","existingVkeys","vkeys","toCore","signedKeys","newSignedKeys","existingPubKeys","Set","vkey","uniqueNewKeys","setVkeys","CborSet","fromCore","VkeyWitness","setWitnessSet","signedTx","added","mergeSignatures","clipboard","Promise","resolve","then","writeSync","cborInput","importedTx","currentHash","importedHash","proceed","sourceVkeys","sourceCount","skipped","txId","submitTransaction","current","def","_fillInStruct","defs","resolvedType","sourceChoice","abChoices","shouldSave","entryName","isOptional","pathDisplay","formatPath","shouldSet","ExtractMessage","innerType","OptionalKind","isUnion","resolved","resolveType","variant","anyOf","matchedDef","references","s","$id","isObject","literalFields","properties","fieldSchema","isLiteral","defRecord","allLiteralsMatch","every","fieldName","const","Value","Check","isString","choice","answer","passwordWithClear","defaultString","isSensitive","inputWithClear","isBigInt","BigInt","isBoolean","hasDefault","getDefault","promptObject","fillField","fieldType","fieldPath","fieldDefs","fieldDef","isArray","promptArray","itemType","itemPath","itemDefs","itemDef","isTuple","concat","isRef","isThis","isImport","$defs","realType","$ref","fields","fieldNames","registerAction","register","getAction","listActions","list","listActionsByCategory","listByCategory","runAction","input","a","context","executeAction","initNonInteractive","profileName","names","run","argv","mode","detectMode","actions","generateAppHelp","actionName","args","parseCliArgs","generateActionHelp","actionArgs","runCli","serverName","basename","env","runMcp"],"sources":["../../../src/Sprinkle/index.ts"],"sourcesContent":["import { type Provider } from \"@blaze-cardano/query\";\nimport {\n Blaze,\n Core,\n HotWallet,\n type Wallet,\n} from \"@blaze-cardano/sdk\";\nimport { CborSet, VkeyWitness, TxCBOR } from \"@blaze-cardano/core\";\nimport {\n selectCancellable,\n selectWithClear,\n inputCancellable,\n inputWithClear,\n passwordCancellable,\n passwordWithClear,\n confirmCancellable,\n searchCancellable,\n select,\n} from \"./prompts.js\";\nimport colors from \"yoctocolors-cjs\";\nimport { type TSchema, Type, OptionalKind } from \"@sinclair/typebox\";\nimport { Value } from \"@sinclair/typebox/value\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nexport * from \"@sinclair/typebox\";\n\n// Re-export types from types.ts\nexport type { TExact } from \"./types.js\";\nexport type {\n IEncryptionOptions,\n ISprinkleOptions,\n IProfileMeta,\n ICurrentProfile,\n IProfileEntry,\n TxDialogResult,\n TxDialogOptions,\n FieldState,\n RequiredFieldCount,\n FieldMenuResult,\n ObjectMenuResult,\n ArrayMenuResult,\n} from \"./types.js\";\nexport { UserCancelledError } from \"./types.js\";\nimport type {\n TExact,\n IEncryptionOptions,\n ISprinkleOptions,\n IProfileMeta,\n ICurrentProfile,\n IProfileEntry,\n TxDialogResult,\n TxDialogOptions,\n} from \"./types.js\";\nimport { UserCancelledError } from \"./types.js\";\n\n// Re-export schemas from schemas.ts\nexport {\n NetworkSchema,\n MultisigScriptModule,\n MultisigScript,\n NativeScriptInputSchema,\n NativeScriptsParam,\n ProviderSettingsSchema,\n WalletSettingsSchema,\n} from \"./schemas.js\";\nexport type { TMultisigScript } from \"./schemas.js\";\nimport type { TMultisigScript } from \"./schemas.js\";\nimport { MultisigScript as MultisigScriptSchema } from \"./schemas.js\";\n\n// Import and re-export type guards\nimport {\n isOptional,\n isImport,\n isArray,\n isBigInt,\n isBoolean,\n isInteger,\n isLiteral,\n isNumber,\n isObject,\n isRef,\n isString,\n isThis,\n isTuple,\n isUnion,\n isSensitive,\n isNull,\n isNullable,\n unwrapNullable,\n hasDefault,\n getDefault,\n} from \"./type-guards.js\";\nexport {\n isOptional,\n isImport,\n isArray,\n isBigInt,\n isBoolean,\n isInteger,\n isLiteral,\n isNumber,\n isObject,\n isRef,\n isString,\n isThis,\n isTuple,\n isUnion,\n isSensitive,\n isNull,\n isNullable,\n unwrapNullable,\n hasDefault,\n getDefault,\n} from \"./type-guards.js\";\n\n// Import schemas for use in this file\nimport {\n NetworkSchema,\n ProviderSettingsSchema,\n WalletSettingsSchema,\n} from \"./schemas.js\";\n\n// Import and re-export wallet utilities\nimport {\n GetProvider as GetProviderFn,\n GetWallet as GetWalletFn,\n GetBlaze as GetBlazeFn,\n generateWalletFromMnemonic,\n} from \"./wallet.js\";\nexport { GetProvider, GetWallet, GetBlaze } from \"./wallet.js\";\n\n// Import encryption utilities\nimport {\n collectSensitivePaths,\n getNestedValue,\n setNestedValue,\n bigIntReplacer,\n bigIntReviver,\n encryptSensitiveFields,\n decryptSensitiveFields,\n maskSensitiveFields,\n} from \"./encryption.js\";\n\n// Import tx-dialog utilities\nimport {\n getWalletPaymentKeyHash,\n countSignatures,\n hasVkeySigned,\n getRequiredSigners,\n getTxBodyHash,\n formatHash,\n mergeSignatures,\n} from \"./tx-dialog.js\";\n\n// Import menu modules\nimport { promptObject, promptArray } from \"./menus/index.js\";\nimport { formatPath } from \"./utils/formatting.js\";\n\n// Import and re-export action system\nimport {\n ActionRegistry,\n ActionError,\n executeAction,\n detectMode,\n parseCliArgs,\n generateActionHelp,\n camelToKebab,\n kebabToCamel,\n coerceValue,\n parseArgvWithSchema,\n generateAppHelp,\n runCli,\n runMcp,\n promptAndExecute,\n} from \"./actions/index.js\";\nimport type { AnyAction, IActionContext, IActionResult } from \"./actions/index.js\";\nimport { toNativeScript } from \"./actions/index.js\";\nexport type { IAction, IActionContext, IActionResult, IActionSuccess, IActionFailure, AnyAction } from \"./actions/index.js\";\nexport {\n ActionRegistry,\n ActionError,\n executeAction,\n detectMode,\n parseCliArgs,\n generateActionHelp,\n camelToKebab,\n kebabToCamel,\n coerceValue,\n parseArgvWithSchema,\n generateAppHelp,\n runCli,\n typeboxToJsonSchema,\n coerceMcpInput,\n getMcpSdk,\n createMcpServer,\n runMcp,\n getBuiltinActions,\n promptAndExecute,\n toNativeScript,\n completeWithScripts,\n} from \"./actions/index.js\";\nexport type { NativeScriptInput } from \"./actions/index.js\";\nimport {\n mintToken,\n simpleSend,\n registerStakeScript,\n} from \"./actions/builtin/utility-actions.js\";\n\nexport interface IMenuAction<S extends TSchema> {\n title: string;\n action: (sprinkle: Sprinkle<S>) => Promise<Sprinkle<S> | void>;\n}\nexport type TMenuItem<S extends TSchema> = IMenuAction<S> | IMenu<S>;\nexport interface IMenu<S extends TSchema> {\n title: string;\n items: TMenuItem<S>[];\n beforeShow?: (sprinkle: Sprinkle<S>) => Promise<void>;\n}\n\nexport class Sprinkle<S extends TSchema> {\n storagePath: string;\n settings: TExact<S> = {} as TExact<S>;\n type: S;\n defaults: Record<string, unknown> = {};\n addressbook: Record<string, TMultisigScript> = {};\n options: ISprinkleOptions;\n profileId: string = \"\";\n profileMeta: IProfileMeta = { name: \"\", createdAt: \"\", updatedAt: \"\" };\n actionRegistry: ActionRegistry<S>;\n\n constructor(type: S, storagePath: string, options?: ISprinkleOptions) {\n this.type = type;\n this.storagePath = storagePath;\n this.options = options ?? {};\n this.actionRegistry = new ActionRegistry<S>();\n }\n\n // --- Current Profile Accessor ---\n\n get currentProfile(): ICurrentProfile | null {\n if (!this.profileId) return null;\n return {\n id: this.profileId,\n ...this.profileMeta,\n };\n }\n\n // --- Profile path helpers ---\n\n static sanitizeProfileId(name: string): string {\n return (\n name\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, \"\")\n .replace(/[\\s]+/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\") || \"profile\"\n );\n }\n\n private static profilesDir(storagePath: string): string {\n return path.join(storagePath, \"profiles\");\n }\n\n private static profilePath(storagePath: string, id: string): string {\n if (!id || /[\\/\\\\]/.test(id) || id.includes(\"..\")) {\n throw new Error(`Invalid profile ID: \"${id}\"`);\n }\n return path.join(storagePath, \"profiles\", `${id}.json`);\n }\n\n private static activeProfilePath(storagePath: string): string {\n return path.join(storagePath, \"active-profile\");\n }\n\n private static findAvailableId(profilesDir: string, baseId: string): string {\n let candidate = baseId;\n let counter = 2;\n while (fs.existsSync(path.join(profilesDir, `${candidate}.json`))) {\n candidate = `${baseId}-${counter}`;\n counter++;\n }\n return candidate;\n }\n\n // --- Profile I/O ---\n\n scanProfiles(): IProfileEntry[] {\n const dir = Sprinkle.profilesDir(this.storagePath);\n if (!fs.existsSync(dir)) return [];\n const files = fs.readdirSync(dir).filter((f) => f.endsWith(\".json\"));\n const entries: IProfileEntry[] = [];\n for (const file of files) {\n try {\n const content = fs.readFileSync(path.join(dir, file), \"utf-8\");\n const parsed = JSON.parse(content, Sprinkle.bigIntReviver);\n if (parsed.meta?.name) {\n entries.push({\n id: file.replace(/\\.json$/, \"\"),\n meta: parsed.meta,\n });\n }\n } catch {\n // Skip malformed profile files\n }\n }\n return entries;\n }\n\n async loadProfile(id: string): Promise<void> {\n const filePath = Sprinkle.profilePath(this.storagePath, id);\n const content = fs.readFileSync(filePath, \"utf-8\");\n const parsed = JSON.parse(content, Sprinkle.bigIntReviver);\n this.profileId = id;\n this.profileMeta = parsed.meta;\n this.settings = await this.decryptSettings(parsed.settings as TExact<S>);\n this.defaults = parsed.defaults ?? {};\n this.addressbook = parsed.addressbook ?? {};\n // Update active profile pointer\n fs.writeFileSync(Sprinkle.activeProfilePath(this.storagePath), id, \"utf-8\");\n }\n\n private saveProfile(): void {\n if (!this.profileId) {\n throw new Error(\n \"Cannot save profile: no profile is loaded. Call loadProfile() or create a profile first.\",\n );\n }\n const filePath = Sprinkle.profilePath(this.storagePath, this.profileId);\n const dir = path.dirname(filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n this.profileMeta.updatedAt = new Date().toISOString();\n const settingsToSave = this.encryptSettings(this.settings);\n const jsonContent = JSON.stringify(\n {\n meta: this.profileMeta,\n settings: settingsToSave,\n defaults: this.defaults,\n addressbook: this.addressbook,\n },\n bigIntReplacer,\n 2,\n );\n fs.writeFileSync(filePath, jsonContent, \"utf-8\");\n }\n\n private async promptProfileMeta(\n defaultName?: string,\n defaultDescription?: string,\n ): Promise<{ name: string; description?: string } | null> {\n const name = await inputCancellable({\n message: \"Profile name:\",\n default: defaultName,\n validate: (v) => (v.trim().length > 0 ? true : \"Name cannot be empty\"),\n });\n if (name === null) return null; // User cancelled\n const description = await inputCancellable({\n message: \"Profile description (optional):\",\n default: defaultDescription ?? \"\",\n });\n if (description === null) return null; // User cancelled\n return { name, description: description || undefined };\n }\n\n private async createProfile(): Promise<void> {\n const result = await this.promptProfileMeta();\n if (result === null) return; // User cancelled\n const { name, description } = result;\n const profilesDir = Sprinkle.profilesDir(this.storagePath);\n const id = Sprinkle.findAvailableId(\n profilesDir,\n Sprinkle.sanitizeProfileId(name),\n );\n const now = new Date().toISOString();\n\n // Snapshot current state in case we need to restore on cancellation\n const prevProfileId = this.profileId;\n const prevProfileMeta = this.profileMeta;\n const prevDefaults = this.defaults;\n const prevSettings = this.settings;\n\n this.profileId = id;\n this.profileMeta = { name, description, createdAt: now, updatedAt: now };\n this.defaults = {};\n try {\n this.settings = await this.FillInStruct(this.type);\n } catch (e) {\n // Restore previous state on cancellation\n if (e instanceof UserCancelledError) {\n this.profileId = prevProfileId;\n this.profileMeta = prevProfileMeta;\n this.defaults = prevDefaults;\n this.settings = prevSettings;\n return;\n }\n throw e;\n }\n this.saveProfile();\n fs.writeFileSync(Sprinkle.activeProfilePath(this.storagePath), id, \"utf-8\");\n }\n\n private async migrateIfNeeded(): Promise<void> {\n const profilesDir = Sprinkle.profilesDir(this.storagePath);\n const legacyPath = Sprinkle.SettingsPath(this.storagePath);\n\n if (!fs.existsSync(profilesDir)) {\n if (fs.existsSync(legacyPath)) {\n // Migrate legacy settings.json -> profiles/default.json\n const content = fs.readFileSync(legacyPath, \"utf-8\");\n const parsed = JSON.parse(content, Sprinkle.bigIntReviver);\n const now = new Date().toISOString();\n const profileData = {\n meta: {\n name: \"Default\",\n createdAt: now,\n updatedAt: now,\n },\n settings: parsed.settings,\n defaults: parsed.defaults ?? {},\n addressbook: parsed.addressbook ?? {},\n };\n fs.mkdirSync(profilesDir, { recursive: true });\n fs.writeFileSync(\n Sprinkle.profilePath(this.storagePath, \"default\"),\n JSON.stringify(profileData, bigIntReplacer, 2),\n \"utf-8\",\n );\n fs.writeFileSync(\n Sprinkle.activeProfilePath(this.storagePath),\n \"default\",\n \"utf-8\",\n );\n // Backup legacy file\n fs.renameSync(legacyPath, `${legacyPath}.bak`);\n } else {\n fs.mkdirSync(profilesDir, { recursive: true });\n }\n }\n }\n\n private async selectOrCreateProfile(): Promise<void> {\n const profiles = this.scanProfiles();\n\n if (profiles.length === 0) {\n await this.createProfile();\n return;\n }\n\n if (profiles.length === 1) {\n await this.loadProfile(profiles[0]!.id);\n return;\n }\n\n // Multiple profiles: check active-profile pointer\n const pointerPath = Sprinkle.activeProfilePath(this.storagePath);\n if (fs.existsSync(pointerPath)) {\n const activeId = fs.readFileSync(pointerPath, \"utf-8\").trim();\n if (profiles.some((p) => p.id === activeId)) {\n await this.loadProfile(activeId);\n return;\n }\n }\n\n // No valid pointer - show selector\n await this.selectProfile(profiles);\n }\n\n private async selectProfile(profiles?: IProfileEntry[]): Promise<void> {\n const available = profiles ?? this.scanProfiles();\n const selection = await selectCancellable({\n message: \"Select a profile:\",\n choices: available.map((p) => ({\n name: p.meta.description\n ? `${p.meta.name} - ${p.meta.description}`\n : p.meta.name,\n value: p.id,\n })),\n });\n if (selection === null) return; // User cancelled\n await this.loadProfile(selection as string);\n }\n\n // --- Profile management (CRUD) ---\n\n private async duplicateProfile(): Promise<void> {\n const result = await this.promptProfileMeta(\n `${this.profileMeta.name} (copy)`,\n this.profileMeta.description,\n );\n if (result === null) return; // User cancelled\n const { name, description } = result;\n const profilesDir = Sprinkle.profilesDir(this.storagePath);\n const id = Sprinkle.findAvailableId(\n profilesDir,\n Sprinkle.sanitizeProfileId(name),\n );\n const now = new Date().toISOString();\n // Write duplicate with current settings\n const settingsToSave = this.encryptSettings(this.settings);\n const jsonContent = JSON.stringify(\n {\n meta: { name, description, createdAt: now, updatedAt: now },\n settings: settingsToSave,\n defaults: this.defaults,\n addressbook: this.addressbook,\n },\n bigIntReplacer,\n 2,\n );\n fs.writeFileSync(\n path.join(profilesDir, `${id}.json`),\n jsonContent,\n \"utf-8\",\n );\n await this.loadProfile(id);\n console.log(`Profile \"${name}\" created as a copy.`);\n }\n\n private async renameProfile(): Promise<void> {\n const result = await this.promptProfileMeta(\n this.profileMeta.name,\n this.profileMeta.description,\n );\n if (result === null) return; // User cancelled\n const { name, description } = result;\n const newId = Sprinkle.sanitizeProfileId(name);\n const oldId = this.profileId;\n\n this.profileMeta.name = name;\n this.profileMeta.description = description;\n\n if (newId !== oldId) {\n const newPath = Sprinkle.profilePath(this.storagePath, newId);\n if (fs.existsSync(newPath)) {\n console.log(\n `A profile with ID \"${newId}\" already exists. Choose a different name.`,\n );\n return;\n }\n // Save to new path, remove old file\n this.profileId = newId;\n this.saveProfile();\n fs.unlinkSync(Sprinkle.profilePath(this.storagePath, oldId));\n fs.writeFileSync(\n Sprinkle.activeProfilePath(this.storagePath),\n newId,\n \"utf-8\",\n );\n } else {\n this.saveProfile();\n }\n console.log(`Profile renamed to \"${name}\".`);\n }\n\n private async deleteProfile(): Promise<void> {\n const profiles = this.scanProfiles();\n const others = profiles.filter((p) => p.id !== this.profileId);\n\n if (others.length === 0) {\n console.log(\"Cannot delete the only profile.\");\n return;\n }\n\n const toDelete = await selectCancellable({\n message: \"Select a profile to delete:\",\n choices: others.map((p) => ({\n name: p.meta.description\n ? `${p.meta.name} - ${p.meta.description}`\n : p.meta.name,\n value: p.id,\n })),\n });\n\n if (toDelete === null) return; // User cancelled\n\n const profileId = toDelete as string;\n const profileToDelete = others.find((p) => p.id === profileId);\n const confirmed = await confirmCancellable({\n message: `Delete profile \"${profileToDelete?.meta.name ?? profileId}\"? This cannot be undone.`,\n default: false,\n });\n\n if (confirmed === null) return; // User cancelled\n\n if (confirmed) {\n fs.unlinkSync(Sprinkle.profilePath(this.storagePath, profileId));\n console.log(\n `Profile \"${profileToDelete?.meta.name ?? profileId}\" deleted.`,\n );\n }\n }\n\n // --- Menu ---\n\n async showMenu(menu: IMenu<S>): Promise<void> {\n return this._showMenu(menu, true, [menu.title]);\n }\n\n private async _showMenu(menu: IMenu<S>, main: boolean, path: string[], clearPrevious = false): Promise<void> {\n // Clear previous breadcrumb if coming back from action/submenu\n if (clearPrevious) {\n process.stdout.write(\"\\x1b[1A\\x1b[2K\\x1b[G\");\n }\n\n if (menu.beforeShow) {\n await menu.beforeShow(this);\n }\n const choices = menu.items.map((item, index) => {\n if (\"action\" in item) {\n return { name: item.title, value: index };\n } else {\n return { name: `${item.title} Submenu`, value: index };\n }\n });\n if (!main) {\n choices.push({ name: \"Back\", value: -1 });\n } else {\n choices.push({ name: \"Utilities\", value: -6 });\n choices.push({ name: \"Settings & Profiles\", value: -5 });\n choices.push({ name: \"Exit\", value: -1 });\n }\n\n // Show breadcrumb\n const breadcrumb = path.join(\" > \");\n console.log(colors.dim(\"🍞 \" + breadcrumb));\n\n const selectionResult = await selectWithClear({\n message: \"Select an option:\",\n choices: choices,\n });\n // Handle escape (null) as Back\n // Don't clear here - let the caller's clearPrevious handle it\n if (selectionResult === null) {\n return;\n }\n const selection = selectionResult as number;\n if (selection === -6) {\n const utilitiesMenu: IMenu<S> = {\n title: \"Utilities\",\n items: [\n {\n title: \"Mint Token\",\n action: async () => {\n const result = await promptAndExecute(this, mintToken);\n if (!result.success) {\n if (result.error.code === \"USER_CANCELLED\") return;\n console.error(`\\nError (${result.error.code}): ${result.error.message}\\n`);\n return;\n }\n const data = result.data as { txCbor: string; policyId: string; tokenName: string; amount: string };\n console.log(`\\nPolicy: ${data.policyId}\\nToken: ${data.tokenName}\\nAmount: ${data.amount}\\n`);\n const blaze = await Sprinkle.GetBlaze(\n (this.settings as Record<string, unknown>).network as TExact<typeof NetworkSchema>,\n (this.settings as Record<string, unknown>).provider as TExact<typeof ProviderSettingsSchema>,\n (this.settings as Record<string, unknown>).wallet as TExact<typeof WalletSettingsSchema>,\n );\n const tx = Core.Transaction.fromCbor(Core.TxCBOR(data.txCbor));\n await this.TxDialog(blaze, tx);\n },\n },\n {\n title: \"Simple Send\",\n action: async () => {\n const result = await promptAndExecute(this, simpleSend);\n if (!result.success) {\n if (result.error.code === \"USER_CANCELLED\") return;\n console.error(`\\nError (${result.error.code}): ${result.error.message}\\n`);\n return;\n }\n const data = result.data as { txCbor: string };\n const blaze = await Sprinkle.GetBlaze(\n (this.settings as Record<string, unknown>).network as TExact<typeof NetworkSchema>,\n (this.settings as Record<string, unknown>).provider as TExact<typeof ProviderSettingsSchema>,\n (this.settings as Record<string, unknown>).wallet as TExact<typeof WalletSettingsSchema>,\n );\n const tx = Core.Transaction.fromCbor(Core.TxCBOR(data.txCbor));\n await this.TxDialog(blaze, tx);\n },\n },\n {\n title: \"Register Stake Script\",\n action: async () => {\n const result = await promptAndExecute(this, registerStakeScript);\n if (!result.success) {\n if (result.error.code === \"USER_CANCELLED\") return;\n console.error(`\\nError (${result.error.code}): ${result.error.message}\\n`);\n return;\n }\n const data = result.data as { txCbor: string };\n const blaze = await Sprinkle.GetBlaze(\n (this.settings as Record<string, unknown>).network as TExact<typeof NetworkSchema>,\n (this.settings as Record<string, unknown>).provider as TExact<typeof ProviderSettingsSchema>,\n (this.settings as Record<string, unknown>).wallet as TExact<typeof WalletSettingsSchema>,\n );\n const tx = Core.Transaction.fromCbor(Core.TxCBOR(data.txCbor));\n await this.TxDialog(blaze, tx);\n },\n },\n ],\n };\n await this._showMenu(utilitiesMenu, false, [...path, \"Utilities\"], true);\n await this._showMenu(menu, main, path, true);\n return;\n }\n if (selection === -5) {\n const settingsMenu: IMenu<S> = {\n title: \"Settings & Profiles\",\n items: [\n {\n title: \"View settings\",\n action: async () => {\n const jsonStr = JSON.stringify(this.getDisplaySettings(), bigIntReplacer, 2);\n const jsonLines = jsonStr.split(\"\\n\").length;\n console.log(jsonStr);\n\n // Wait for user to press Enter\n await selectWithClear({\n message: \"Press Enter to continue...\",\n choices: [{ name: \"Continue\", value: \"continue\" }],\n });\n\n // Clear the JSON output\n process.stdout.write(\"\\x1b[1A\\x1b[2K\".repeat(jsonLines) + \"\\x1b[G\");\n },\n },\n {\n title: \"Edit settings\",\n action: async () => {\n try {\n this.settings = await this.EditStruct(this.type, this.settings);\n this.saveSettings();\n } catch (e) {\n if (e instanceof UserCancelledError) {\n return; // User cancelled, return to menu\n }\n throw e;\n }\n },\n },\n {\n title: \"Switch profile\",\n action: async () => {\n this.saveSettings();\n const profiles = this.scanProfiles();\n if (profiles.length <= 1) {\n console.log(\n \"No other profiles to switch to. Create a new one first.\",\n );\n } else {\n await this.selectProfile(profiles);\n }\n },\n },\n {\n title: \"Create new profile\",\n action: async () => {\n await this.createProfile();\n },\n },\n {\n title: \"Duplicate current profile\",\n action: async () => {\n await this.duplicateProfile();\n },\n },\n {\n title: \"Rename current profile\",\n action: async () => {\n await this.renameProfile();\n },\n },\n {\n title: \"Delete a profile\",\n action: async () => {\n await this.deleteProfile();\n },\n },\n {\n title: \"Addressbook\",\n items: [\n {\n title: \"View entries\",\n action: async () => {\n const entries = Object.entries(this.addressbook);\n if (entries.length === 0) {\n console.log(\"Addressbook is empty.\");\n } else {\n for (const [name, ms] of entries) {\n const json = JSON.stringify(ms, bigIntReplacer, 2);\n let hashStr = \"unknown\";\n try {\n hashStr = toNativeScript(ms).hash();\n } catch { /* skip */ }\n console.log(colors.bold(name) + \" \" + colors.dim(hashStr));\n console.log(json);\n console.log();\n }\n }\n await selectWithClear({\n message: \"Press Enter to continue...\",\n choices: [{ name: \"Continue\", value: \"continue\" }],\n });\n },\n },\n {\n title: \"Add entry\",\n action: async () => {\n const name = await inputCancellable({\n message: \"Entry name:\",\n validate: (v) =>\n v.trim().length > 0 ? true : \"Name cannot be empty\",\n });\n if (name === null) return;\n if (this.addressbook[name]) {\n const overwrite = await confirmCancellable({\n message: `Entry \"${name}\" already exists. Overwrite?`,\n default: false,\n });\n if (!overwrite) return;\n }\n try {\n const script = await this.FillInStruct(MultisigScriptSchema);\n this.addressbook[name] = script as TMultisigScript;\n this.saveSettings();\n console.log(`Added \"${name}\" to addressbook.`);\n } catch (e) {\n if (e instanceof UserCancelledError) return;\n throw e;\n }\n },\n },\n {\n title: \"Edit entry\",\n action: async () => {\n const entries = Object.keys(this.addressbook);\n if (entries.length === 0) {\n console.log(\"Addressbook is empty.\");\n return;\n }\n const selected = await selectCancellable({\n message: \"Select entry to edit:\",\n choices: entries.map((n) => ({ name: n, value: n })),\n });\n if (selected === null) return;\n const editName = selected as string;\n try {\n const updated = await this.EditStruct(\n MultisigScriptSchema,\n this.addressbook[editName] as any,\n );\n this.addressbook[editName] = updated as TMultisigScript;\n this.saveSettings();\n console.log(`Updated \"${editName}\".`);\n } catch (e) {\n if (e instanceof UserCancelledError) return;\n throw e;\n }\n },\n },\n {\n title: \"Delete entry\",\n action: async () => {\n const entries = Object.keys(this.addressbook);\n if (entries.length === 0) {\n console.log(\"Addressbook is empty.\");\n return;\n }\n const delSelected = await selectCancellable({\n message: \"Select entry to delete:\",\n choices: entries.map((n) => ({ name: n, value: n })),\n });\n if (delSelected === null) return;\n const delName = delSelected as string;\n const confirmed = await confirmCancellable({\n message: `Delete \"${delName}\"?`,\n default: false,\n });\n if (!confirmed) return;\n delete this.addressbook[delName];\n this.saveSettings();\n console.log(`Deleted \"${delName}\".`);\n },\n },\n ],\n } as IMenu<S>,\n ],\n };\n await this._showMenu(settingsMenu, false, [...path, \"Settings & Profiles\"], true);\n await this._showMenu(menu, main, path, true);\n return;\n }\n if (selection === -1) {\n // Don't clear here - let the caller's clearPrevious handle it\n return;\n }\n const selectedItem = menu.items[selection]!;\n if (\"action\" in selectedItem) {\n // Update breadcrumb to show current action\n process.stdout.write(\"\\x1b[1A\\x1b[2K\\x1b[G\");\n console.log(colors.dim(\"🍞 \" + [...path, selectedItem.title].join(\" > \")));\n\n const result = await selectedItem.action(this);\n if (result instanceof Sprinkle) {\n this.settings = result.settings;\n this.saveSettings();\n }\n await this._showMenu(menu, main, path, true);\n } else {\n await this._showMenu(selectedItem, false, [...path, selectedItem.title], true);\n await this._showMenu(menu, main, path, true);\n }\n return;\n }\n\n static async New<S extends TSchema>(\n type: S,\n storagePath: string,\n options?: ISprinkleOptions,\n ): Promise<Sprinkle<S>> {\n const sprinkle = new Sprinkle<S>(type, storagePath, options);\n await sprinkle.migrateIfNeeded();\n await sprinkle.selectOrCreateProfile();\n sprinkle.saveSettings();\n return sprinkle;\n }\n\n static async GetProvider(\n network: TExact<typeof NetworkSchema>,\n settings: TExact<typeof ProviderSettingsSchema>,\n ): Promise<Provider> {\n return GetProviderFn(network, settings);\n }\n\n static async GetWallet(\n settings: TExact<typeof WalletSettingsSchema>,\n provider: Provider,\n ): Promise<Wallet> {\n return GetWalletFn(settings, provider);\n }\n\n static async GetBlaze(\n network: TExact<typeof NetworkSchema>,\n providerSettings: TExact<typeof ProviderSettingsSchema>,\n walletSettings: TExact<typeof WalletSettingsSchema>,\n ): Promise<Blaze<Provider, Wallet>> {\n return GetBlazeFn(network, providerSettings, walletSettings);\n }\n\n /**\n * Generates a new wallet from a BIP39 mnemonic phrase.\n * Displays the 24-word recovery phrase and requires user confirmation.\n * @returns The Bip32PrivateKey hex string for storage\n */\n private static async generateWalletFromMnemonic(): Promise<string> {\n return generateWalletFromMnemonic();\n }\n\n static async SearchSelect<T>(opts: {\n message: string;\n source: (\n term: string | undefined,\n ) => Promise<{ name: string; value: T }[]> | { name: string; value: T }[];\n }): Promise<T | null> {\n return searchCancellable(opts) as Promise<T | null>;\n }\n\n static SettingsPath(storagePath: string): string {\n return `${storagePath}${path.sep}settings.json`;\n }\n\n async LoadSettings(type: S, storagePath: string): Promise<void> {\n try {\n // Check if the settings file exists\n if (fs.existsSync(storagePath)) {\n // Read and parse the JSON file\n const fileContent = fs.readFileSync(storagePath, \"utf-8\");\n const parsed = JSON.parse(fileContent, Sprinkle.bigIntReviver) as {\n settings: unknown;\n defaults: Record<string, unknown>;\n };\n // Convert string representations back to BigInt where needed\n this.settings = await this.decryptSettings(\n parsed.settings as TExact<S>,\n );\n this.defaults = parsed.defaults;\n } else {\n this.defaults = {};\n this.settings = await this.FillInStruct(type);\n }\n } catch (error) {\n throw new Error(`Error loading settings from ${storagePath}: ${error}`);\n }\n }\n\n static bigIntReviver(key: string, value: unknown): unknown {\n return bigIntReviver(key, value);\n }\n\n private encryptSettings(settings: TExact<S>): TExact<S> {\n if (!this.options.encryption) return settings;\n return encryptSensitiveFields(settings, this.type, this.options.encryption);\n }\n\n private async decryptSettings(settings: TExact<S>): Promise<TExact<S>> {\n if (!this.options.encryption) return settings;\n return decryptSensitiveFields(settings, this.type, this.options.encryption);\n }\n\n saveSettings(): void {\n this.saveProfile();\n }\n\n getDisplaySettings(): TExact<S> {\n return maskSensitiveFields(this.settings, this.type);\n }\n\n // --- Non-interactive profile management (for CLI/MCP actions) ---\n\n /**\n * Look up a profile entry by its ID without loading it.\n * Returns undefined if no profile with the given ID exists.\n */\n getProfileById(id: string): IProfileEntry | undefined {\n return this.scanProfiles().find((p) => p.id === id);\n }\n\n /**\n * Create a new profile file without interactive prompts.\n * Does NOT switch the active profile.\n *\n * @throws ActionError with code DUPLICATE_PROFILE if a profile with the same name already exists.\n * @returns The created IProfileEntry\n */\n async createProfileNonInteractive(\n name: string,\n description?: string,\n initialSettings?: Partial<TExact<S>>,\n ): Promise<IProfileEntry> {\n const profiles = this.scanProfiles();\n const nameLower = name.toLowerCase();\n const duplicate = profiles.find(\n (p) => p.meta.name.toLowerCase() === nameLower,\n );\n if (duplicate) {\n throw new ActionError(\n `A profile named \"${name}\" already exists.`,\n \"DUPLICATE_PROFILE\",\n { existingId: duplicate.id },\n );\n }\n\n const profilesDir = Sprinkle.profilesDir(this.storagePath);\n if (!fs.existsSync(profilesDir)) {\n fs.mkdirSync(profilesDir, { recursive: true });\n }\n\n const baseId = Sprinkle.sanitizeProfileId(name);\n const id = Sprinkle.findAvailableId(profilesDir, baseId);\n const now = new Date().toISOString();\n const meta: IProfileMeta = { name, description, createdAt: now, updatedAt: now };\n\n const profileData = {\n meta,\n settings: initialSettings ?? {},\n defaults: {},\n addressbook: {},\n };\n\n fs.writeFileSync(\n path.join(profilesDir, `${id}.json`),\n JSON.stringify(profileData, bigIntReplacer, 2),\n \"utf-8\",\n );\n\n return { id, meta };\n }\n\n /**\n * Delete a profile file by ID.\n *\n * @throws ActionError with code PROFILE_NOT_FOUND if no profile with the given ID exists.\n * @throws ActionError with code CANNOT_DELETE_ONLY_PROFILE if this is the only profile.\n * @throws ActionError with code CANNOT_DELETE_ACTIVE_PROFILE if this is the currently active profile.\n */\n deleteProfileById(id: string): void {\n const profiles = this.scanProfiles();\n const profile = profiles.find((p) => p.id === id);\n\n if (!profile) {\n throw new ActionError(\n `Profile \"${id}\" not found.`,\n \"PROFILE_NOT_FOUND\",\n { id },\n );\n }\n\n if (profiles.length === 1) {\n throw new ActionError(\n \"Cannot delete the only profile.\",\n \"CANNOT_DELETE_ONLY_PROFILE\",\n { id },\n );\n }\n\n if (id === this.profileId) {\n throw new ActionError(\n \"Cannot delete the active profile. Switch to a different profile first.\",\n \"CANNOT_DELETE_ACTIVE_PROFILE\",\n { id },\n );\n }\n\n fs.unlinkSync(Sprinkle.profilePath(this.storagePath, id));\n }\n\n async TxDialog<P extends Provider, W extends Wallet>(\n blaze: Blaze<P, W>,\n tx: Core.Transaction,\n opts?: TxDialogOptions,\n ): Promise<TxDialogResult> {\n let currentTx = tx;\n let expanded = false;\n let hasSignedThisSession = false;\n\n // Check if wallet can sign (is HotWallet)\n const isHotWallet = blaze.wallet instanceof HotWallet;\n\n // Get wallet's vkeys for detecting if already signed\n let walletVkeys: string[] = [];\n if (isHotWallet) {\n try {\n // Sign a dummy to get the wallet's public keys\n // We'll use this to check if wallet has already signed\n const wallet = blaze.wallet as unknown as HotWallet;\n const addresses = await wallet.getUsedAddresses();\n const address = addresses[0];\n if (address) {\n // We can't easily get vkeys without signing, so we'll track after first sign\n }\n } catch {\n // Ignore errors in setup\n }\n }\n\n while (true) {\n // Display transaction status\n const txHash = getTxBodyHash(currentTx);\n const sigCount = countSignatures(currentTx);\n const requiredSigners = getRequiredSigners(currentTx);\n\n console.log(\"\");\n console.log(`Transaction: ${formatHash(txHash)}`);\n if (requiredSigners.length > 0) {\n console.log(`Signatures: ${sigCount} of ${requiredSigners.length} required`);\n console.log(\"Required signers:\");\n for (const signer of requiredSigners) {\n console.log(` - ${formatHash(signer)}`);\n }\n } else {\n console.log(`Signatures: ${sigCount}`);\n }\n\n // Display CBOR\n const txCbor = currentTx.toCbor();\n if (expanded) {\n console.log(\"Transaction CBOR:\", txCbor);\n } else {\n console.log(\"Transaction CBOR:\", `${String(txCbor).slice(0, 50)}...`);\n }\n\n // Build dynamic menu choices\n const choices: { name: string; value: string }[] = [];\n\n // \"Sign with this wallet\" - only if HotWallet and hasn't signed this session\n if (isHotWallet && !hasSignedThisSession) {\n choices.push({ name: \"Sign with this wallet\", value: \"sign\" });\n }\n\n // CBOR options\n if (!expanded) {\n choices.push({ name: \"Expand CBOR\", value: \"expand\" });\n }\n choices.push({ name: \"Copy CBOR to clipboard\", value: \"copy\" });\n choices.push({ name: \"Import signatures from CBOR\", value: \"import\" });\n\n // Submit and cancel\n choices.push({ name: \"Submit transaction\", value: \"submit\" });\n choices.push({ name: \"Cancel\", value: \"cancel\" });\n\n const selection = await selectWithClear({\n message: \"Select an option:\",\n choices,\n });\n\n // Handle escape/cancel as cancel action\n if (selection === null) {\n if (hasSignedThisSession) {\n return { action: \"signed\", tx: currentTx };\n }\n return { action: \"cancelled\", tx: currentTx };\n }\n\n // Handle selection\n if (selection === \"sign\") {\n if (opts?.beforeSign) {\n await opts.beforeSign();\n }\n\n // Detect if stake key signature is required\n let needsStakeKey = false;\n try {\n const wallet = blaze.wallet as unknown as HotWallet;\n const addresses = await wallet.getUsedAddresses();\n const userAddress = addresses[0];\n if (userAddress) {\n const stakeCredential = userAddress.asBase()?.getStakeCredential();\n const stakeKeyHash = stakeCredential?.hash?.toString();\n\n if (stakeKeyHash) {\n const reqSigners = currentTx.body().requiredSigners();\n if (reqSigners) {\n const signerArray = Array.from(reqSigners.values());\n needsStakeKey = signerArray.some(\n (signer) => signer.toString() === stakeKeyHash,\n );\n }\n\n const certs = currentTx.body().certs();\n const hasCertificates = certs && certs.size() > 0;\n const withdrawals = currentTx.body().withdrawals();\n const hasWithdrawals = withdrawals && withdrawals.size > 0;\n\n if (hasCertificates || hasWithdrawals) {\n needsStakeKey = true;\n }\n }\n }\n\n if (needsStakeKey) {\n console.log(\"Transaction requires stake key signature.\");\n } else {\n console.log(\"Transaction requires payment key signature only.\");\n }\n } catch (error) {\n console.warn(\n \"Could not determine stake key requirement, signing with payment key only.\",\n );\n console.warn(`Error: ${(error as Error).message}`);\n }\n\n try {\n if (needsStakeKey) {\n const wallet = blaze.wallet as unknown as HotWallet;\n const signed = await wallet.signTransaction(currentTx, true, true);\n const ws = currentTx.witnessSet();\n const existingVkeys = ws.vkeys()?.toCore() ?? [];\n\n const signedKeys = signed.vkeys();\n if (!signedKeys) {\n throw new Error(\n \"signTransaction: no signed keys in wallet witness response\",\n );\n }\n\n // Check for duplicates before adding\n const newSignedKeys = signedKeys.toCore();\n const existingPubKeys = new Set(existingVkeys.map(([vkey]) => vkey));\n const uniqueNewKeys = newSignedKeys.filter(\n ([vkey]) => !existingPubKeys.has(vkey),\n );\n\n if (uniqueNewKeys.length === 0) {\n console.log(\"Wallet has already signed this transaction.\");\n } else {\n ws.setVkeys(\n CborSet.fromCore(\n [...existingVkeys, ...uniqueNewKeys],\n VkeyWitness.fromCore,\n ),\n );\n currentTx.setWitnessSet(ws);\n console.log(`Added ${uniqueNewKeys.length} signature(s).`);\n hasSignedThisSession = true;\n }\n } else {\n const signedTx = await blaze.signTransaction(currentTx);\n // Merge signatures from signed tx into current tx\n const added = mergeSignatures(currentTx, signedTx);\n if (added > 0) {\n console.log(`Added ${added} signature(s).`);\n hasSignedThisSession = true;\n } else {\n console.log(\"Wallet has already signed this transaction.\");\n }\n }\n } catch (error) {\n console.error(`Signing failed: ${(error as Error).message}`);\n }\n // Continue loop after signing\n continue;\n }\n\n if (selection === \"expand\") {\n expanded = true;\n continue;\n }\n\n if (selection === \"copy\") {\n try {\n const { default: clipboard } = await import(\"clipboardy\");\n clipboard.writeSync(String(currentTx.toCbor()));\n console.log(\"Transaction CBOR copied to clipboard.\");\n } catch {\n console.log(\"Failed to copy to clipboard, expanding instead.\");\n expanded = true;\n }\n continue;\n }\n\n if (selection === \"import\") {\n const cborInput = await inputCancellable({\n message: \"Paste transaction CBOR (hex):\",\n });\n\n if (cborInput === null || cborInput.trim() === \"\") {\n console.log(\"No CBOR provided.\");\n continue;\n }\n\n try {\n const importedTx = Core.Transaction.fromCbor(\n TxCBOR(cborInput.trim()),\n );\n\n // Validate body hash matches\n const currentHash = getTxBodyHash(currentTx);\n const importedHash = getTxBodyHash(importedTx);\n\n if (currentHash !== importedHash) {\n const proceed = await confirmCancellable({\n message: `Warning: Imported transaction has different body hash.\\nCurrent: ${formatHash(currentHash)}\\nImported: ${formatHash(importedHash)}\\nProceed anyway?`,\n default: false,\n });\n if (proceed === null || !proceed) {\n console.log(\"Import cancelled.\");\n continue;\n }\n }\n\n // Merge signatures\n const added = mergeSignatures(currentTx, importedTx);\n const sourceVkeys = importedTx.witnessSet().vkeys();\n const sourceCount = sourceVkeys ? sourceVkeys.size() : 0;\n const skipped = sourceCount - added;\n\n if (added > 0) {\n console.log(`Added ${added} new signature(s).`);\n }\n if (skipped > 0) {\n console.log(`Skipped ${skipped} duplicate signature(s).`);\n }\n if (added === 0 && skipped === 0) {\n console.log(\"No signatures found in imported transaction.\");\n }\n } catch (error) {\n console.error(`Failed to import CBOR: ${(error as Error).message}`);\n }\n continue;\n }\n\n if (selection === \"submit\") {\n const sigCount = countSignatures(currentTx);\n if (sigCount === 0) {\n const proceed = await confirmCancellable({\n message: \"Warning: Transaction has no signatures. Submit anyway?\",\n default: false,\n });\n if (proceed === null || !proceed) {\n continue;\n }\n }\n\n try {\n const txId = await blaze.submitTransaction(currentTx);\n console.log(`Transaction submitted: ${txId}`);\n return { action: \"submitted\", txId, tx: currentTx };\n } catch (error) {\n console.error(`Submit failed: ${(error as Error).message}`);\n // Continue loop to allow retry or other actions\n continue;\n }\n }\n\n if (selection === \"cancel\") {\n if (hasSignedThisSession) {\n return { action: \"signed\", tx: currentTx };\n }\n return { action: \"cancelled\", tx: currentTx };\n }\n }\n }\n\n /**\n * Edit an existing struct value using a menu-based interface.\n * This is now unified with FillInStruct - both use the same menu system.\n * @param type - The TypeBox schema\n * @param current - The current value to edit\n * @returns The edited value\n */\n async EditStruct<U extends TSchema>(\n type: U,\n current: TExact<U>,\n ): Promise<TExact<U>> {\n // Use FillInStruct with current values as defaults\n // The menu system will show existing values and allow editing\n return this.FillInStruct(type, current);\n }\n\n async FillInStruct<U extends TSchema>(\n type: U,\n def?: TExact<U>,\n ): Promise<TExact<U>> {\n return this._fillInStruct<U>(type, [\"root\"], {}, def);\n }\n\n async _fillInStruct<U extends TSchema>(\n type: U,\n path: string[],\n defs: Record<string, TSchema>,\n def?: TExact<U>,\n ): Promise<TExact<U>> {\n if (\"$ref\" in type) {\n defs = { ...defs, ...type[\"$defs\"] };\n const resolvedType = defs[type[\"$ref\"]];\n if (!resolvedType) {\n throw new Error(\n `Could not resolve type ${type[\"$ref\"]} at ${path.join(\".\")}`,\n );\n }\n\n // Addressbook integration for MultisigScript fields\n if (type[\"$ref\"] === \"MultisigScript\" && Object.keys(this.addressbook).length > 0) {\n const sourceChoice = await selectWithClear({\n message: \"Select source for native script:\",\n choices: [\n { name: \"Enter manually\", value: \"manual\" },\n { name: \"Select from addressbook\", value: \"addressbook\" },\n ],\n });\n if (sourceChoice === null) throw new UserCancelledError();\n if (sourceChoice === \"addressbook\") {\n const entries = Object.entries(this.addressbook);\n const abChoices = entries.map(([name, ms]) => {\n let hashStr = \"\";\n try { hashStr = \" \" + colors.dim(toNativeScript(ms).hash()); } catch { /* skip */ }\n return { name: name + hashStr, value: name };\n });\n const selected = await selectWithClear({\n message: \"Select addressbook entry:\",\n choices: abChoices,\n });\n if (selected === null) throw new UserCancelledError();\n return this.addressbook[selected as string] as TExact<U>;\n }\n }\n\n const result = await this._fillInStruct(resolvedType, path, defs, def) as TExact<U>;\n\n // Offer to save manually entered MultisigScript to addressbook\n if (type[\"$ref\"] === \"MultisigScript\" && result !== undefined) {\n const shouldSave = await selectWithClear({\n message: \"Save this script to the addressbook?\",\n choices: [\n { name: \"No\", value: false },\n { name: \"Yes\", value: true },\n ],\n });\n if (shouldSave) {\n const entryName = await inputCancellable({\n message: \"Addressbook entry name:\",\n validate: (v) => v.trim().length > 0 ? true : \"Name cannot be empty\",\n });\n if (entryName !== null) {\n this.addressbook[entryName] = result as TMultisigScript;\n this.saveSettings();\n console.log(`Saved \"${entryName}\" to addressbook.`);\n }\n }\n }\n\n return result;\n }\n if (isOptional(type)) {\n const pathDisplay = formatPath(path) || \"value\";\n const shouldSet = await selectWithClear({\n message: Sprinkle.ExtractMessage(\n type,\n `Set value for ${pathDisplay}?`,\n ),\n choices: [\n { name: \"Yes\", value: true },\n { name: \"Skip\", value: false },\n ],\n default: def !== undefined,\n });\n if (shouldSet === null) {\n throw new UserCancelledError();\n }\n if (!shouldSet) {\n return undefined as TExact<U>;\n }\n // Unwrap the optional and fill the inner type\n const innerType = { ...type };\n delete (innerType as any)[OptionalKind];\n return this._fillInStruct(innerType as U, path, defs, def);\n }\n\n if (isUnion(type)) {\n const pathDisplay = formatPath(path) || \"value\";\n const choices = [];\n const resolved = this.resolveType(type, path, defs);\n for (const variant of resolved.anyOf) {\n choices.push({\n name: Sprinkle.ExtractMessage(variant, `${variant}`),\n value: variant,\n });\n }\n const selectionResult = await selectWithClear({\n message: Sprinkle.ExtractMessage(\n resolved,\n `Enter a choice for ${pathDisplay}`,\n ),\n choices: choices,\n });\n if (selectionResult === null) {\n throw new UserCancelledError();\n }\n const selection = selectionResult as TSchema;\n // Determine if the provided default value matches the selected variant.\n // For discriminated unions (objects with literal fields like `type`), check\n // if the literal field values in the selected variant match those in `def`.\n // For non-discriminated unions, fall back to structural matching with Value.Check.\n let matchedDef: unknown = undefined;\n // Build references array for Value.Check — schemas with $id from defs\n // so TypeBox can resolve $ref inside variant schemas (e.g. MultisigScript).\n const references = Object.values(defs).filter((s) => s.$id) as TSchema[];\n if (def !== undefined) {\n if (isObject(selection)) {\n // Check if all literal fields in the selected variant match def\n const literalFields = Object.entries(selection.properties ?? {}).filter(\n ([, fieldSchema]) => isLiteral(fieldSchema as TSchema),\n );\n if (literalFields.length > 0) {\n const defRecord = def as Record<string, unknown>;\n const allLiteralsMatch = literalFields.every(\n ([fieldName, fieldSchema]) =>\n defRecord[fieldName] === (fieldSchema as unknown as { const: unknown }).const,\n );\n if (allLiteralsMatch) {\n matchedDef = def;\n }\n } else {\n // No literal discriminators - use structural check\n if (Value.Check(selection, references, def)) {\n matchedDef = def;\n }\n }\n } else {\n // Non-object variant - use structural check\n if (Value.Check(selection, references, def)) {\n matchedDef = def;\n }\n }\n }\n return this._fillInStruct(selection, path, defs, matchedDef as TExact<typeof selection>) as Promise<TExact<U>>;\n }\n\n if (isString(type)) {\n // Special handling for hot wallet private key - offer generation option\n if (type.title === \"Hot Wallet Private Key\") {\n const choice = await selectWithClear({\n message: \"Hot wallet setup:\",\n choices: [\n { name: \"Enter existing private key\", value: \"existing\" },\n { name: \"Generate new wallet\", value: \"generate\" },\n ],\n });\n\n if (choice === null) {\n throw new UserCancelledError();\n }\n if (choice === \"generate\") {\n return Sprinkle.generateWalletFromMnemonic() as Promise<TExact<U>>;\n }\n // Fall through to password prompt for \"existing\" choice\n const answer = await passwordWithClear({\n message: \"Enter your private key:\",\n });\n if (answer === null) {\n throw new UserCancelledError();\n }\n return answer as TExact<U>;\n }\n\n const pathDisplay = formatPath(path) || \"value\";\n const defaultString = (def ? def : this.defaults[\"string\"]) as\n | string\n | undefined;\n const message = Sprinkle.ExtractMessage(\n type,\n `Enter a string for ${pathDisplay}`,\n );\n let answer: string | null;\n if (isSensitive(type)) {\n answer = await passwordWithClear({ message });\n } else {\n answer = await inputWithClear({ message, default: defaultString });\n if (answer !== null) {\n this.defaults[\"string\"] = answer;\n }\n }\n if (answer === null) {\n throw new UserCancelledError();\n }\n return answer as TExact<U>;\n }\n\n if (isBigInt(type)) {\n const pathDisplay = formatPath(path) || \"value\";\n const answer = await inputWithClear({\n message: Sprinkle.ExtractMessage(\n type,\n `Enter a bigint for ${pathDisplay}`,\n ),\n default: def ? (def as bigint).toString() : undefined,\n validate: (s) => {\n try {\n BigInt(s);\n return true;\n } catch {\n return \"Please enter a valid bigint.\";\n }\n },\n });\n if (answer === null) {\n throw new UserCancelledError();\n }\n return BigInt(answer) as TExact<U>;\n }\n\n if (isBoolean(type)) {\n const pathDisplay = formatPath(path) || \"value\";\n const answer = await selectWithClear({\n message: Sprinkle.ExtractMessage(type, `${pathDisplay}?`),\n choices: [\n { name: \"Yes\", value: true },\n { name: \"No\", value: false },\n ],\n default: def !== undefined ? (def as boolean) : hasDefault(type) ? getDefault(type) : undefined,\n });\n if (answer === null) {\n throw new UserCancelledError();\n }\n return answer as TExact<U>;\n }\n\n if (isLiteral(type)) {\n return type.const as TExact<U>;\n }\n\n if (isObject(type)) {\n // Use menu-based editing for objects\n const defaults = def as Record<string, unknown> | undefined;\n const sprinkle = this;\n const result = await promptObject({\n type,\n path,\n defs,\n defaults,\n fillField: async <T extends TSchema>(\n fieldType: T,\n fieldPath: string[],\n fieldDefs: Record<string, TSchema>,\n fieldDef?: unknown,\n ) => {\n return sprinkle._fillInStruct(fieldType, fieldPath, fieldDefs, fieldDef as TExact<T>);\n },\n });\n\n if (result.action === \"cancel\") {\n throw new UserCancelledError();\n }\n\n return result.value as TExact<U>;\n }\n\n if (isArray(type)) {\n // Use menu-based editing for arrays\n const defaults = def as unknown[] | undefined;\n const sprinkle = this;\n const result = await promptArray({\n type,\n path,\n defs,\n defaults,\n fillField: async <T extends TSchema>(\n itemType: T,\n itemPath: string[],\n itemDefs: Record<string, TSchema>,\n itemDef?: unknown,\n ) => {\n return sprinkle._fillInStruct(itemType, itemPath, itemDefs, itemDef as TExact<T>);\n },\n });\n\n if (result.action === \"back\") {\n throw new UserCancelledError();\n }\n\n return result.value as TExact<U>;\n }\n\n if (isTuple(type)) {\n const items = type.items ?? [];\n const result: unknown[] = [];\n for (let i = 0; i < items.length; i++) {\n const itemType = items[i] as U;\n const value = await this._fillInStruct(\n itemType,\n path.concat([`[${i}]`]),\n defs,\n def ? ((def as unknown[])[i] as TExact<U>) : undefined,\n );\n result.push(value);\n }\n return result as TExact<U>;\n }\n\n const pathDisplay = formatPath(path) || \"root\";\n throw new Error(\n `Unable to fill in struct for type at path ${pathDisplay}`,\n );\n }\n\n resolveType<T extends TSchema>(\n type: T,\n path: string[],\n defs: Record<string, TSchema>,\n ): T {\n if (isRef(type) || isThis(type) || isImport(type)) {\n defs = { ...defs, ...type.$defs };\n const realType = defs[type.$ref];\n if (!realType) {\n throw new Error(\n `Invalid type at ${path.join(\".\")}: Unrecognized reference ${type.$ref}`,\n );\n }\n return this.resolveType(realType, path, defs) as T;\n }\n return type;\n }\n\n static ExtractMessage(type: TSchema, def: string): string {\n if (\"title\" in type) {\n return type.title!;\n }\n\n if (\"description\" in type) {\n return type.description!;\n }\n\n if (isLiteral(type)) {\n return `${type.const}`;\n }\n\n if (isObject(type)) {\n const fields = type[\"properties\"] as Record<string, TSchema>;\n if (\"type\" in fields) {\n return Sprinkle.ExtractMessage(fields[\"type\"], def);\n }\n const fieldNames = Object.keys(fields);\n if (fieldNames.length === 1) {\n return fieldNames[0]!;\n }\n }\n\n return def;\n }\n\n // --- Action System ---\n\n /**\n * Register an action on this Sprinkle instance.\n * Delegates to the internal ActionRegistry with name and schema validation.\n */\n registerAction(action: AnyAction<S>): void {\n this.actionRegistry.register(action);\n }\n\n /**\n * Retrieve a registered action by name.\n * @returns The action, or undefined if not registered\n */\n getAction(name: string): AnyAction<S> | undefined {\n return this.actionRegistry.get(name);\n }\n\n /**\n * List all registered actions.\n */\n listActions(): AnyAction<S>[] {\n return this.actionRegistry.list();\n }\n\n /**\n * List all registered actions grouped by category.\n * Uncategorized actions are grouped under \"default\".\n */\n listActionsByCategory(): Map<string, AnyAction<S>[]> {\n return this.actionRegistry.listByCategory();\n }\n\n /**\n * Execute a registered action by name with raw (unvalidated) input.\n * Input is validated against the action's inputSchema before execution.\n *\n * @throws Error if the action name is not registered\n */\n async runAction(\n name: string,\n input: unknown,\n ): Promise<IActionResult<unknown>> {\n const action = this.actionRegistry.get(name);\n if (!action) {\n throw new Error(\n `Action \"${name}\" is not registered. Available actions: ${this.actionRegistry.list().map((a) => a.name).join(\", \") || \"(none)\"}`,\n );\n }\n\n const context: IActionContext<S> = {\n sprinkle: this,\n settings: this.settings,\n };\n\n return executeAction(action, input, context);\n }\n\n /**\n * Non-interactive profile initialization for CLI/MCP modes.\n * Resolves a profile without any user prompts.\n *\n * Resolution order:\n * 1. If profileName provided, load that profile directly\n * 2. If exactly one profile exists, auto-select it\n * 3. If multiple profiles exist and no name given, throw with available names\n * 4. If no profiles exist, throw instructing user to run in interactive mode\n */\n private async initNonInteractive(profileName?: string): Promise<void> {\n await this.migrateIfNeeded();\n\n if (profileName) {\n await this.loadProfile(profileName);\n return;\n }\n\n const profiles = this.scanProfiles();\n\n if (profiles.length === 0) {\n throw new Error(\n \"No profiles found. Run in interactive mode to create one.\",\n );\n }\n\n if (profiles.length === 1) {\n await this.loadProfile(profiles[0]!.id);\n return;\n }\n\n // Multiple profiles without a --profile flag\n const names = profiles.map((p) => `\"${p.id}\" (${p.meta.name})`).join(\", \");\n throw new Error(\n `Multiple profiles found. Specify one with --profile <id>. Available profiles: ${names}`,\n );\n }\n\n /**\n * Static entry point that detects mode and runs accordingly.\n *\n * Modes:\n * - \"tui\" -- Interactive TUI menu (requires menu option)\n * - \"cli\" -- CLI action execution (parses argv for action name and args)\n * - \"mcp\" -- MCP protocol mode (not yet implemented)\n * - \"help\" -- Print available actions and exit\n */\n static async run<S extends TSchema>(opts: {\n type: S;\n storagePath: string;\n menu?: IMenu<S>;\n actions?: AnyAction<S>[];\n options?: ISprinkleOptions;\n argv?: string[];\n }): Promise<void> {\n const argv = opts.argv ?? process.argv.slice(2);\n const mode = detectMode(argv);\n\n if (mode === \"tui\") {\n if (!opts.menu) {\n throw new Error(\n \"TUI mode requires a menu. Provide a menu option or pass --help to see available actions.\",\n );\n }\n const sprinkle = await Sprinkle.New(\n opts.type,\n opts.storagePath,\n opts.options,\n );\n // Register any provided actions\n for (const action of opts.actions ?? []) {\n sprinkle.registerAction(action);\n }\n await sprinkle.showMenu(opts.menu);\n return;\n }\n\n if (mode === \"help\") {\n const sprinkle = new Sprinkle(opts.type, opts.storagePath, opts.options);\n for (const action of opts.actions ?? []) {\n sprinkle.registerAction(action);\n }\n console.log(generateAppHelp(sprinkle.listActions()));\n return;\n }\n\n if (mode === \"cli\") {\n const { actionName, args } = parseCliArgs(argv);\n\n // Extract --profile flag from args if present\n const profileName =\n typeof args[\"profile\"] === \"string\" ? args[\"profile\"] : undefined;\n\n const sprinkle = new Sprinkle(opts.type, opts.storagePath, opts.options);\n for (const action of opts.actions ?? []) {\n sprinkle.registerAction(action);\n }\n\n // Handle action-specific --help BEFORE profile initialization\n // (help should work without a profile)\n if (args[\"help\"] === true) {\n const action = sprinkle.getAction(actionName);\n if (action) {\n console.log(generateActionHelp(action));\n } else {\n console.log(`Unknown action \"${actionName}\". Run --help to see available actions.`);\n }\n return;\n }\n\n await sprinkle.initNonInteractive(profileName);\n\n // Remove internal flags from args before passing to action\n const actionArgs = { ...args };\n delete actionArgs[\"profile\"];\n delete actionArgs[\"help\"];\n\n // Build context and delegate to runCli for proper error routing\n const context = {\n sprinkle,\n settings: sprinkle.settings,\n };\n await runCli(sprinkle, actionName, actionArgs, context);\n return;\n }\n\n if (mode === \"mcp\") {\n // Derive a server name from the storage path basename, falling back to a\n // sensible default.\n const serverName = path.basename(opts.storagePath) || \"sprinkle-mcp\";\n\n const sprinkle = new Sprinkle(opts.type, opts.storagePath, opts.options);\n for (const action of opts.actions ?? []) {\n sprinkle.registerAction(action);\n }\n\n // Read profile name from environment variable (MCP clients have no\n // interactive terminal to prompt for profile selection).\n const profileName = process.env[\"SPRINKLE_PROFILE\"];\n\n await sprinkle.initNonInteractive(profileName);\n await runMcp(sprinkle, serverName);\n return;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,IAAAA,IAAA,GAAAC,OAAA;AAMA,IAAAC,KAAA,GAAAD,OAAA;AACA,IAAAE,QAAA,GAAAF,OAAA;AAWA,IAAAG,eAAA,GAAAC,sBAAA,CAAAJ,OAAA;AACA,IAAAK,QAAA,GAAAL,OAAA;AAIAM,MAAA,CAAAC,IAAA,CAAAF,QAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,QAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA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