@nextclaw/service 0.4.1 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app/nextclaw-service-runtime.d.ts +1 -1
- package/dist/app/nextclaw-service-runtime.d.ts.map +1 -1
- package/dist/app/nextclaw-service-runtime.js +3 -2
- package/dist/app/nextclaw-service-runtime.js.map +1 -1
- package/dist/launcher/npm-runtime-launcher.service.d.ts +5 -1
- package/dist/launcher/npm-runtime-launcher.service.d.ts.map +1 -1
- package/dist/launcher/npm-runtime-launcher.service.js +41 -12
- package/dist/launcher/npm-runtime-launcher.service.js.map +1 -1
- package/dist/managers/runtime-update.manager.d.ts.map +1 -1
- package/dist/managers/runtime-update.manager.js +11 -8
- package/dist/managers/runtime-update.manager.js.map +1 -1
- package/dist/services/runtime/npm-runtime-bundle.service.d.ts +16 -5
- package/dist/services/runtime/npm-runtime-bundle.service.d.ts.map +1 -1
- package/dist/services/runtime/npm-runtime-bundle.service.js +87 -26
- package/dist/services/runtime/npm-runtime-bundle.service.js.map +1 -1
- package/dist/services/runtime/npm-runtime-update-command.service.js +1 -1
- package/dist/services/runtime/npm-runtime-update-command.service.js.map +1 -1
- package/dist/services/runtime/npm-runtime-update.service.d.ts.map +1 -1
- package/dist/services/runtime/npm-runtime-update.service.js +1 -0
- package/dist/services/runtime/npm-runtime-update.service.js.map +1 -1
- package/package.json +23 -23
|
@@ -37,7 +37,7 @@ declare class NextclawServiceRuntime {
|
|
|
37
37
|
agent: (opts: AgentCommandOptions) => Promise<void>;
|
|
38
38
|
update: (opts: UpdateCommandOptions) => Promise<void>;
|
|
39
39
|
}
|
|
40
|
-
declare const runNextclawNpmRuntimeLauncher: (argv?: string[]) =>
|
|
40
|
+
declare const runNextclawNpmRuntimeLauncher: (argv?: string[]) => Promise<never>;
|
|
41
41
|
//#endregion
|
|
42
42
|
export { NextclawServiceRuntime, NextclawServiceRuntimeAccount, NextclawServiceRuntimeOptions, runNextclawNpmRuntimeLauncher };
|
|
43
43
|
//# sourceMappingURL=nextclaw-service-runtime.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nextclaw-service-runtime.d.ts","names":[],"sources":["../../src/app/nextclaw-service-runtime.ts"],"mappings":";;;;;KAuBY,6BAAA;EACV,IAAA;AAAA;AAAA,KAGU,6BAAA;EACV,MAAA,GAAS,IAAA;IAAS,OAAA;IAAkB,IAAA;EAAA,MAAqB,OAAA;EACzD,WAAA,GACE,QAAA,UACA,IAAA;IAAS,OAAA;IAAkB,IAAA;EAAA,MACxB,OAAA;AAAA;AAAA,cAGM,sBAAA;EAAA,iBACM,IAAA;EAAA,iBACA,gBAAA;EAAA,iBACA,qBAAA;EAAA,iBACA,cAAA;EAAA,iBACA,cAAA;EAAA,SACR,OAAA,EAAS,6BAAA;EAAA,SACT,QAAA,EAAU,uBAAA;cAEP,OAAA,EAAS,6BAAA;EAAA,IAoCjB,OAAA,CAAA;EAIJ,OAAA,GAAiB,KAAA,EAAO,iBAAA,KAAoB,OAAA,CAAQ,kBAAA;EAmBpD,OAAA,QAAoB,OAAA;EAOpB,IAAA,GAAc,OAAA;IAAW,MAAA;IAAiB,IAAA;IAAgB,KAAA;EAAA,MAAyB,OAAA;EAkDnF,KAAA,GAAe,IAAA,GAAM,mBAAA,KAA2B,OAAA;EAKhD,KAAA,GAAe,IAAA,EAAM,mBAAA,KAAsB,OAAA;EAyB3C,MAAA,GAAgB,IAAA,EAAM,oBAAA,KAAuB,OAAA;AAAA;AAAA,cAkBlC,6BAAA,GACX,IAAA"}
|
|
1
|
+
{"version":3,"file":"nextclaw-service-runtime.d.ts","names":[],"sources":["../../src/app/nextclaw-service-runtime.ts"],"mappings":";;;;;KAuBY,6BAAA;EACV,IAAA;AAAA;AAAA,KAGU,6BAAA;EACV,MAAA,GAAS,IAAA;IAAS,OAAA;IAAkB,IAAA;EAAA,MAAqB,OAAA;EACzD,WAAA,GACE,QAAA,UACA,IAAA;IAAS,OAAA;IAAkB,IAAA;EAAA,MACxB,OAAA;AAAA;AAAA,cAGM,sBAAA;EAAA,iBACM,IAAA;EAAA,iBACA,gBAAA;EAAA,iBACA,qBAAA;EAAA,iBACA,cAAA;EAAA,iBACA,cAAA;EAAA,SACR,OAAA,EAAS,6BAAA;EAAA,SACT,QAAA,EAAU,uBAAA;cAEP,OAAA,EAAS,6BAAA;EAAA,IAoCjB,OAAA,CAAA;EAIJ,OAAA,GAAiB,KAAA,EAAO,iBAAA,KAAoB,OAAA,CAAQ,kBAAA;EAmBpD,OAAA,QAAoB,OAAA;EAOpB,IAAA,GAAc,OAAA;IAAW,MAAA;IAAiB,IAAA;IAAgB,KAAA;EAAA,MAAyB,OAAA;EAkDnF,KAAA,GAAe,IAAA,GAAM,mBAAA,KAA2B,OAAA;EAKhD,KAAA,GAAe,IAAA,EAAM,mBAAA,KAAsB,OAAA;EAyB3C,MAAA,GAAgB,IAAA,EAAM,oBAAA,KAAuB,OAAA;AAAA;AAAA,cAkBlC,6BAAA,GACX,IAAA,gBACC,OAAA"}
|
|
@@ -152,10 +152,11 @@ var NextclawServiceRuntime = class {
|
|
|
152
152
|
};
|
|
153
153
|
const runNextclawNpmRuntimeLauncher = (argv = process.argv) => {
|
|
154
154
|
const distribution = NextclawDistributionService.get();
|
|
155
|
-
new NpmRuntimeLauncher({
|
|
155
|
+
return new NpmRuntimeLauncher({
|
|
156
156
|
argv,
|
|
157
157
|
launcherVersion: distribution.version,
|
|
158
|
-
packagedAppEntrypoint: distribution.appEntrypoint
|
|
158
|
+
packagedAppEntrypoint: distribution.appEntrypoint,
|
|
159
|
+
packagedPortableRunnerPath: distribution.portableServiceRunnerPath
|
|
159
160
|
}).run();
|
|
160
161
|
};
|
|
161
162
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nextclaw-service-runtime.js","names":[],"sources":["../../src/app/nextclaw-service-runtime.ts"],"sourcesContent":["import { APP_NAME, getConfigPath, getDataDir, loadConfig, resolveWorkspacePath } from \"@nextclaw/core\";\nimport {\n NextclawKernel,\n runNextclawTask,\n type NextclawHarnessOptions,\n type NextclawTaskInput,\n type NextclawTaskResult,\n} from \"@nextclaw/kernel\";\nimport { existsSync, mkdirSync } from \"node:fs\";\nimport { ManagedServiceManager } from \"@nextclaw-service/managers/managed-service.manager.js\";\nimport { ServiceCommandManager, runCliAgentCommand, type NextclawServiceCommands } from \"@nextclaw-service/managers/service-command.manager.js\";\nimport { ServiceRestartManager } from \"@nextclaw-service/managers/service-restart.manager.js\";\nimport { ServiceWorkspaceManager } from \"@nextclaw-service/managers/service-workspace.manager.js\";\nimport { NpmRuntimeLauncher } from \"@nextclaw-service/launcher/npm-runtime-launcher.service.js\";\nimport { NpmRuntimeUpdateCommandService } from \"@nextclaw-service/services/runtime/npm-runtime-update-command.service.js\";\nimport { initializeConfigIfMissing } from \"@nextclaw-service/services/runtime/runtime-config-init.service.js\";\nimport { NextclawDistributionService } from \"@nextclaw-service/services/runtime/nextclaw-distribution.service.js\";\nimport { ProductActivityReporter } from \"@nextclaw-service/services/product-activity/product-activity-reporter.service.js\";\nimport { managedServiceStateStore } from \"@nextclaw-service/stores/managed-service-state.store.js\";\nimport type { AgentCommandOptions, LoginCommandOptions, UpdateCommandOptions } from \"@nextclaw-service/types/cli.types.js\";\nimport { isProcessRunning } from \"@nextclaw-service/utils/cli.utils.js\";\nimport { logStartupTrace } from \"@nextclaw-service/utils/startup-trace.utils.js\";\n\nexport type NextclawServiceRuntimeOptions = {\n logo?: string;\n};\n\nexport type NextclawServiceRuntimeAccount = {\n status: (opts?: { apiBase?: string; json?: boolean }) => Promise<void>;\n setUsername: (\n username: string,\n opts?: { apiBase?: string; json?: boolean },\n ) => Promise<void>;\n};\n\nexport class NextclawServiceRuntime {\n private readonly logo: string;\n private readonly workspaceManager: ServiceWorkspaceManager;\n private readonly managedServiceManager: ManagedServiceManager;\n private readonly restartManager: ServiceRestartManager;\n private readonly commandManager: ServiceCommandManager;\n readonly account: NextclawServiceRuntimeAccount;\n readonly commands: NextclawServiceCommands;\n\n constructor(options: NextclawServiceRuntimeOptions) {\n logStartupTrace(\"cli.runtime.constructor.begin\");\n this.logo = options.logo ?? \"🤖\";\n this.workspaceManager = new ServiceWorkspaceManager(NextclawDistributionService.get().templatesDir);\n this.managedServiceManager = new ManagedServiceManager({\n requestRestart: (params) => this.restartManager.requestRestart(params),\n initializeAgentHomeDirectory: (homeDirectory) => this.workspaceManager.createWorkspaceTemplates(homeDirectory)\n });\n this.restartManager = new ServiceRestartManager({\n managedService: this.managedServiceManager\n });\n this.commandManager = new ServiceCommandManager({\n logo: this.logo,\n init: (params) => this.init(params),\n managedService: this.managedServiceManager,\n restart: this.restartManager,\n workspace: this.workspaceManager\n });\n this.commands = this.commandManager.commands;\n this.account = {\n status: async (opts = {}) => {\n await this.init({ source: \"account status\", auto: true });\n await this.commandManager.platformAuth.accountStatus(opts);\n },\n setUsername: async (username, opts = {}) => {\n await this.init({ source: \"account set-username\", auto: true });\n await this.commandManager.platformAuth.accountSetUsername({\n apiBase: opts.apiBase,\n json: opts.json,\n username\n });\n },\n };\n logStartupTrace(\"cli.runtime.constructor.end\");\n }\n\n get version(): string {\n return NextclawDistributionService.get().version;\n }\n\n runTask = async (input: NextclawTaskInput): Promise<NextclawTaskResult> => {\n const configPath = getConfigPath();\n const distribution = NextclawDistributionService.get();\n const productActivityReporter = new ProductActivityReporter({\n homeDir: getDataDir(),\n productVersion: distribution.version,\n loadConfig: () => loadConfig(configPath),\n });\n const options: NextclawHarnessOptions = {\n builtInAppsDirectory: distribution.builtInAppsDirectory,\n configPath,\n homeDir: getDataDir(),\n portableServiceRunnerPath: distribution.portableServiceRunnerPath,\n productActivitySink: productActivityReporter,\n productVersion: distribution.version,\n };\n return await runNextclawTask(input, options);\n };\n\n onboard = async (): Promise<void> => {\n console.warn(\n `Warning: ${APP_NAME} onboard is deprecated. Use \"${APP_NAME} init\" instead.`,\n );\n await this.init({ source: \"onboard\" });\n };\n\n init = async (options: { source?: string; auto?: boolean; force?: boolean } = {}): Promise<void> => {\n const source = options.source ?? \"init\";\n const prefix = options.auto ? \"Auto init\" : \"Init\";\n const force = Boolean(options.force);\n\n const configPath = getConfigPath();\n const createdConfig = initializeConfigIfMissing(configPath);\n\n const config = loadConfig();\n const workspacePath = resolveWorkspacePath(config.agents.defaults.workspace);\n const workspaceExisted = existsSync(workspacePath);\n mkdirSync(workspacePath, { recursive: true });\n const templateResult = this.workspaceManager.createWorkspaceTemplates(\n workspacePath,\n { force },\n );\n\n if (createdConfig) {\n console.log(`✓ ${prefix}: created config at ${configPath}`);\n }\n if (!workspaceExisted) {\n console.log(`✓ ${prefix}: created workspace at ${workspacePath}`);\n }\n for (const file of templateResult.created) {\n console.log(`✓ ${prefix}: created ${file}`);\n }\n if (\n !createdConfig &&\n workspaceExisted &&\n templateResult.created.length === 0\n ) {\n console.log(`${prefix}: already initialized.`);\n }\n\n if (!options.auto) {\n console.log(`\\n${this.logo} ${APP_NAME} is ready! (${source})`);\n console.log(\"\\nNext steps:\");\n if (createdConfig) {\n console.log(` 1. Chat now (OpenCode Zen needs no API key): ${APP_NAME} agent -m \"Hello!\"`);\n } else {\n console.log(` 1. Chat: ${APP_NAME} agent -m \"Hello!\"`);\n }\n console.log(` 2. Optional: configure another provider in ${configPath}`);\n } else {\n console.log(\n `Tip: Run \"${APP_NAME} init${force ? \" --force\" : \"\"}\" to re-run initialization if needed.`,\n );\n }\n };\n\n login = async (opts: LoginCommandOptions = {}): Promise<void> => {\n await this.init({ source: \"login\", auto: true });\n await this.commandManager.platformAuth.login(opts);\n };\n\n agent = async (opts: AgentCommandOptions): Promise<void> => {\n const configPath = getConfigPath();\n const distribution = NextclawDistributionService.get();\n const productActivityReporter = new ProductActivityReporter({\n homeDir: getDataDir(),\n productVersion: distribution.version,\n loadConfig: () => loadConfig(configPath),\n });\n const kernel = new NextclawKernel({\n homeDir: getDataDir(),\n configPath,\n portableServiceRunnerPath: distribution.portableServiceRunnerPath,\n productVersion: distribution.version,\n productActivitySink: productActivityReporter,\n });\n const config = kernel.configManager.config;\n\n await runCliAgentCommand({\n logo: this.logo,\n opts,\n config,\n kernel,\n });\n };\n\n update = async (opts: UpdateCommandOptions): Promise<void> => {\n const versionBefore = this.version;\n if (!opts.json) {\n const installationLabel = process.env.NEXTCLAW_DESKTOP_COMMAND_SURFACE === \"1\" ? \"desktop runtime\" : \"npm launcher\";\n console.log(`Current ${installationLabel} version: ${versionBefore}`);\n }\n const snapshot = await new NpmRuntimeUpdateCommandService().run(opts);\n if (snapshot.status === \"blocked\" || snapshot.status === \"failed\") {\n process.exit(1);\n }\n\n const state = managedServiceStateStore.read();\n if (snapshot.requiresRestart && state && isProcessRunning(state.pid)) {\n console.log(`Tip: restart ${APP_NAME} to apply the update.`);\n }\n };\n}\n\nexport const runNextclawNpmRuntimeLauncher = (\n argv: string[] = process.argv,\n): void => {\n const distribution = NextclawDistributionService.get();\n new NpmRuntimeLauncher({\n argv,\n launcherVersion: distribution.version,\n packagedAppEntrypoint: distribution.appEntrypoint,\n }).run();\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAmCA,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAAwC;AAClD,kBAAgB,gCAAgC;AAChD,OAAK,OAAO,QAAQ,QAAQ;AAC5B,OAAK,mBAAmB,IAAI,wBAAwB,4BAA4B,KAAK,CAAC,aAAa;AACnG,OAAK,wBAAwB,IAAI,sBAAsB;GACrD,iBAAiB,WAAW,KAAK,eAAe,eAAe,OAAO;GACtE,+BAA+B,kBAAkB,KAAK,iBAAiB,yBAAyB,cAAc;GAC/G,CAAC;AACF,OAAK,iBAAiB,IAAI,sBAAsB,EAC9C,gBAAgB,KAAK,uBACtB,CAAC;AACF,OAAK,iBAAiB,IAAI,sBAAsB;GAC9C,MAAM,KAAK;GACX,OAAO,WAAW,KAAK,KAAK,OAAO;GACnC,gBAAgB,KAAK;GACrB,SAAS,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AM,SAAS,OAAO,cAAc;AAEpC,QAAM,mBAAmB;GACvB,MAAM,KAAK;GACX;GACA;GACA;GACD,CAAC;;CAGJ,SAAS,OAAO,SAA8C;EAC5D,MAAM,gBAAgB,KAAK;AAC3B,MAAI,CAAC,KAAK,MAAM;GACd,MAAM,oBAAoB,QAAQ,IAAI,qCAAqC,MAAM,oBAAoB;AACrG,WAAQ,IAAI,WAAW,kBAAkB,YAAY,gBAAgB;;EAEvE,MAAM,WAAW,MAAM,IAAI,gCAAgC,CAAC,IAAI,KAAK;AACrE,MAAI,SAAS,WAAW,aAAa,SAAS,WAAW,SACvD,SAAQ,KAAK,EAAE;EAGjB,MAAM,QAAQ,yBAAyB,MAAM;AAC7C,MAAI,SAAS,mBAAmB,SAAS,iBAAiB,MAAM,IAAI,CAClE,SAAQ,IAAI,gBAAgB,SAAS,uBAAuB;;;AAKlE,MAAa,iCACX,OAAiB,QAAQ,SAChB;CACT,MAAM,eAAe,4BAA4B,KAAK;AACtD,KAAI,mBAAmB;EACrB;EACA,iBAAiB,aAAa;EAC9B,uBAAuB,aAAa;EACrC,CAAC,CAAC,KAAK"}
|
|
1
|
+
{"version":3,"file":"nextclaw-service-runtime.js","names":[],"sources":["../../src/app/nextclaw-service-runtime.ts"],"sourcesContent":["import { APP_NAME, getConfigPath, getDataDir, loadConfig, resolveWorkspacePath } from \"@nextclaw/core\";\nimport {\n NextclawKernel,\n runNextclawTask,\n type NextclawHarnessOptions,\n type NextclawTaskInput,\n type NextclawTaskResult,\n} from \"@nextclaw/kernel\";\nimport { existsSync, mkdirSync } from \"node:fs\";\nimport { ManagedServiceManager } from \"@nextclaw-service/managers/managed-service.manager.js\";\nimport { ServiceCommandManager, runCliAgentCommand, type NextclawServiceCommands } from \"@nextclaw-service/managers/service-command.manager.js\";\nimport { ServiceRestartManager } from \"@nextclaw-service/managers/service-restart.manager.js\";\nimport { ServiceWorkspaceManager } from \"@nextclaw-service/managers/service-workspace.manager.js\";\nimport { NpmRuntimeLauncher } from \"@nextclaw-service/launcher/npm-runtime-launcher.service.js\";\nimport { NpmRuntimeUpdateCommandService } from \"@nextclaw-service/services/runtime/npm-runtime-update-command.service.js\";\nimport { initializeConfigIfMissing } from \"@nextclaw-service/services/runtime/runtime-config-init.service.js\";\nimport { NextclawDistributionService } from \"@nextclaw-service/services/runtime/nextclaw-distribution.service.js\";\nimport { ProductActivityReporter } from \"@nextclaw-service/services/product-activity/product-activity-reporter.service.js\";\nimport { managedServiceStateStore } from \"@nextclaw-service/stores/managed-service-state.store.js\";\nimport type { AgentCommandOptions, LoginCommandOptions, UpdateCommandOptions } from \"@nextclaw-service/types/cli.types.js\";\nimport { isProcessRunning } from \"@nextclaw-service/utils/cli.utils.js\";\nimport { logStartupTrace } from \"@nextclaw-service/utils/startup-trace.utils.js\";\n\nexport type NextclawServiceRuntimeOptions = {\n logo?: string;\n};\n\nexport type NextclawServiceRuntimeAccount = {\n status: (opts?: { apiBase?: string; json?: boolean }) => Promise<void>;\n setUsername: (\n username: string,\n opts?: { apiBase?: string; json?: boolean },\n ) => Promise<void>;\n};\n\nexport class NextclawServiceRuntime {\n private readonly logo: string;\n private readonly workspaceManager: ServiceWorkspaceManager;\n private readonly managedServiceManager: ManagedServiceManager;\n private readonly restartManager: ServiceRestartManager;\n private readonly commandManager: ServiceCommandManager;\n readonly account: NextclawServiceRuntimeAccount;\n readonly commands: NextclawServiceCommands;\n\n constructor(options: NextclawServiceRuntimeOptions) {\n logStartupTrace(\"cli.runtime.constructor.begin\");\n this.logo = options.logo ?? \"🤖\";\n this.workspaceManager = new ServiceWorkspaceManager(NextclawDistributionService.get().templatesDir);\n this.managedServiceManager = new ManagedServiceManager({\n requestRestart: (params) => this.restartManager.requestRestart(params),\n initializeAgentHomeDirectory: (homeDirectory) => this.workspaceManager.createWorkspaceTemplates(homeDirectory)\n });\n this.restartManager = new ServiceRestartManager({\n managedService: this.managedServiceManager\n });\n this.commandManager = new ServiceCommandManager({\n logo: this.logo,\n init: (params) => this.init(params),\n managedService: this.managedServiceManager,\n restart: this.restartManager,\n workspace: this.workspaceManager\n });\n this.commands = this.commandManager.commands;\n this.account = {\n status: async (opts = {}) => {\n await this.init({ source: \"account status\", auto: true });\n await this.commandManager.platformAuth.accountStatus(opts);\n },\n setUsername: async (username, opts = {}) => {\n await this.init({ source: \"account set-username\", auto: true });\n await this.commandManager.platformAuth.accountSetUsername({\n apiBase: opts.apiBase,\n json: opts.json,\n username\n });\n },\n };\n logStartupTrace(\"cli.runtime.constructor.end\");\n }\n\n get version(): string {\n return NextclawDistributionService.get().version;\n }\n\n runTask = async (input: NextclawTaskInput): Promise<NextclawTaskResult> => {\n const configPath = getConfigPath();\n const distribution = NextclawDistributionService.get();\n const productActivityReporter = new ProductActivityReporter({\n homeDir: getDataDir(),\n productVersion: distribution.version,\n loadConfig: () => loadConfig(configPath),\n });\n const options: NextclawHarnessOptions = {\n builtInAppsDirectory: distribution.builtInAppsDirectory,\n configPath,\n homeDir: getDataDir(),\n portableServiceRunnerPath: distribution.portableServiceRunnerPath,\n productActivitySink: productActivityReporter,\n productVersion: distribution.version,\n };\n return await runNextclawTask(input, options);\n };\n\n onboard = async (): Promise<void> => {\n console.warn(\n `Warning: ${APP_NAME} onboard is deprecated. Use \"${APP_NAME} init\" instead.`,\n );\n await this.init({ source: \"onboard\" });\n };\n\n init = async (options: { source?: string; auto?: boolean; force?: boolean } = {}): Promise<void> => {\n const source = options.source ?? \"init\";\n const prefix = options.auto ? \"Auto init\" : \"Init\";\n const force = Boolean(options.force);\n\n const configPath = getConfigPath();\n const createdConfig = initializeConfigIfMissing(configPath);\n\n const config = loadConfig();\n const workspacePath = resolveWorkspacePath(config.agents.defaults.workspace);\n const workspaceExisted = existsSync(workspacePath);\n mkdirSync(workspacePath, { recursive: true });\n const templateResult = this.workspaceManager.createWorkspaceTemplates(\n workspacePath,\n { force },\n );\n\n if (createdConfig) {\n console.log(`✓ ${prefix}: created config at ${configPath}`);\n }\n if (!workspaceExisted) {\n console.log(`✓ ${prefix}: created workspace at ${workspacePath}`);\n }\n for (const file of templateResult.created) {\n console.log(`✓ ${prefix}: created ${file}`);\n }\n if (\n !createdConfig &&\n workspaceExisted &&\n templateResult.created.length === 0\n ) {\n console.log(`${prefix}: already initialized.`);\n }\n\n if (!options.auto) {\n console.log(`\\n${this.logo} ${APP_NAME} is ready! (${source})`);\n console.log(\"\\nNext steps:\");\n if (createdConfig) {\n console.log(` 1. Chat now (OpenCode Zen needs no API key): ${APP_NAME} agent -m \"Hello!\"`);\n } else {\n console.log(` 1. Chat: ${APP_NAME} agent -m \"Hello!\"`);\n }\n console.log(` 2. Optional: configure another provider in ${configPath}`);\n } else {\n console.log(\n `Tip: Run \"${APP_NAME} init${force ? \" --force\" : \"\"}\" to re-run initialization if needed.`,\n );\n }\n };\n\n login = async (opts: LoginCommandOptions = {}): Promise<void> => {\n await this.init({ source: \"login\", auto: true });\n await this.commandManager.platformAuth.login(opts);\n };\n\n agent = async (opts: AgentCommandOptions): Promise<void> => {\n const configPath = getConfigPath();\n const distribution = NextclawDistributionService.get();\n const productActivityReporter = new ProductActivityReporter({\n homeDir: getDataDir(),\n productVersion: distribution.version,\n loadConfig: () => loadConfig(configPath),\n });\n const kernel = new NextclawKernel({\n homeDir: getDataDir(),\n configPath,\n portableServiceRunnerPath: distribution.portableServiceRunnerPath,\n productVersion: distribution.version,\n productActivitySink: productActivityReporter,\n });\n const config = kernel.configManager.config;\n\n await runCliAgentCommand({\n logo: this.logo,\n opts,\n config,\n kernel,\n });\n };\n\n update = async (opts: UpdateCommandOptions): Promise<void> => {\n const versionBefore = this.version;\n if (!opts.json) {\n const installationLabel = process.env.NEXTCLAW_DESKTOP_COMMAND_SURFACE === \"1\" ? \"desktop runtime\" : \"npm launcher\";\n console.log(`Current ${installationLabel} version: ${versionBefore}`);\n }\n const snapshot = await new NpmRuntimeUpdateCommandService().run(opts);\n if (snapshot.status === \"blocked\" || snapshot.status === \"failed\") {\n process.exit(1);\n }\n\n const state = managedServiceStateStore.read();\n if (snapshot.requiresRestart && state && isProcessRunning(state.pid)) {\n console.log(`Tip: restart ${APP_NAME} to apply the update.`);\n }\n };\n}\n\nexport const runNextclawNpmRuntimeLauncher = (\n argv: string[] = process.argv,\n): Promise<never> => {\n const distribution = NextclawDistributionService.get();\n return new NpmRuntimeLauncher({\n argv,\n launcherVersion: distribution.version,\n packagedAppEntrypoint: distribution.appEntrypoint,\n packagedPortableRunnerPath: distribution.portableServiceRunnerPath,\n }).run();\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAmCA,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAAwC;AAClD,kBAAgB,gCAAgC;AAChD,OAAK,OAAO,QAAQ,QAAQ;AAC5B,OAAK,mBAAmB,IAAI,wBAAwB,4BAA4B,KAAK,CAAC,aAAa;AACnG,OAAK,wBAAwB,IAAI,sBAAsB;GACrD,iBAAiB,WAAW,KAAK,eAAe,eAAe,OAAO;GACtE,+BAA+B,kBAAkB,KAAK,iBAAiB,yBAAyB,cAAc;GAC/G,CAAC;AACF,OAAK,iBAAiB,IAAI,sBAAsB,EAC9C,gBAAgB,KAAK,uBACtB,CAAC;AACF,OAAK,iBAAiB,IAAI,sBAAsB;GAC9C,MAAM,KAAK;GACX,OAAO,WAAW,KAAK,KAAK,OAAO;GACnC,gBAAgB,KAAK;GACrB,SAAS,KAAK;GACd,WAAW,KAAK;GACjB,CAAC;AACF,OAAK,WAAW,KAAK,eAAe;AACpC,OAAK,UAAU;GACb,QAAQ,OAAO,OAAO,EAAE,KAAK;AAC3B,UAAM,KAAK,KAAK;KAAE,QAAQ;KAAkB,MAAM;KAAM,CAAC;AACzD,UAAM,KAAK,eAAe,aAAa,cAAc,KAAK;;GAE5D,aAAa,OAAO,UAAU,OAAO,EAAE,KAAK;AAC1C,UAAM,KAAK,KAAK;KAAE,QAAQ;KAAwB,MAAM;KAAM,CAAC;AAC/D,UAAM,KAAK,eAAe,aAAa,mBA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AAS,WAAW,SACvD,SAAQ,KAAK,EAAE;EAGjB,MAAM,QAAQ,yBAAyB,MAAM;AAC7C,MAAI,SAAS,mBAAmB,SAAS,iBAAiB,MAAM,IAAI,CAClE,SAAQ,IAAI,gBAAgB,SAAS,uBAAuB;;;AAKlE,MAAa,iCACX,OAAiB,QAAQ,SACN;CACnB,MAAM,eAAe,4BAA4B,KAAK;AACtD,QAAO,IAAI,mBAAmB;EAC5B;EACA,iBAAiB,aAAa;EAC9B,uBAAuB,aAAa;EACpC,4BAA4B,aAAa;EAC1C,CAAC,CAAC,KAAK"}
|
|
@@ -7,14 +7,18 @@ type NpmRuntimeLauncherOptions = {
|
|
|
7
7
|
layout?: NpmRuntimeBundleLayoutStore;
|
|
8
8
|
launcherVersion?: string;
|
|
9
9
|
packagedAppEntrypoint?: string;
|
|
10
|
+
packagedPortableRunnerPath?: string;
|
|
11
|
+
bootstrapRuntimeBundle?: () => Promise<void>;
|
|
10
12
|
};
|
|
11
13
|
declare class NpmRuntimeLauncher {
|
|
12
14
|
private readonly options;
|
|
13
15
|
private readonly env;
|
|
14
16
|
private readonly layout;
|
|
15
17
|
constructor(options: NpmRuntimeLauncherOptions);
|
|
16
|
-
run: () => never
|
|
18
|
+
run: () => Promise<never>;
|
|
17
19
|
private resolveRuntimeScriptPath;
|
|
20
|
+
private bootstrapRuntimeBundle;
|
|
21
|
+
private resolveIncompletePackagedRuntime;
|
|
18
22
|
private resolveLauncherVersion;
|
|
19
23
|
private resolvePackagedAppEntrypoint;
|
|
20
24
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"npm-runtime-launcher.service.d.ts","names":[],"sources":["../../src/launcher/npm-runtime-launcher.service.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"npm-runtime-launcher.service.d.ts","names":[],"sources":["../../src/launcher/npm-runtime-launcher.service.ts"],"mappings":";;;KAiBK,yBAAA;EACH,IAAA;EACA,GAAA,GAAM,MAAA,CAAO,UAAA;EACb,MAAA,GAAS,2BAAA;EACT,eAAA;EACA,qBAAA;EACA,0BAAA;EACA,sBAAA,SAA+B,OAAA;AAAA;AAAA,cAGpB,kBAAA;EAAA,iBAIkB,OAAA;EAAA,iBAHZ,GAAA;EAAA,iBACA,MAAA;cAEY,OAAA,EAAS,yBAAA;EAKtC,GAAA,QAAgB,OAAA;EAAA,QAiBR,wBAAA;EAAA,QA8DA,sBAAA;EAAA,QAWA,gCAAA;EAAA,QAKA,sBAAA;EAAA,QAEA,4BAAA;AAAA"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { getPackageVersion as getPackageVersion$1 } from "../utils/package/package-manifest.utils.js";
|
|
2
2
|
import "../utils/cli.utils.js";
|
|
3
3
|
import { NpmRuntimeBundleLayoutStore } from "../stores/npm-runtime-bundle-layout.store.js";
|
|
4
|
-
import { NpmRuntimeBundleService, shouldPreferPackagedNpmRuntime } from "../services/runtime/npm-runtime-bundle.service.js";
|
|
4
|
+
import { NpmRuntimeBundleService, isNpmRuntimeBundleComplete, isPackagedNpmRuntimeComplete, shouldPreferPackagedNpmRuntime } from "../services/runtime/npm-runtime-bundle.service.js";
|
|
5
5
|
import { inferDefaultNpmRuntimeReleaseChannel } from "../services/runtime/npm-runtime-update-source.service.js";
|
|
6
6
|
import { NpmRuntimeUpdateStateStore } from "../stores/npm-runtime-update-state.store.js";
|
|
7
|
+
import { NpmRuntimeUpdateCommandService } from "../services/runtime/npm-runtime-update-command.service.js";
|
|
7
8
|
import { createExternalCommandEnv } from "@nextclaw/core";
|
|
8
9
|
import { spawnSync } from "node:child_process";
|
|
9
10
|
import { dirname, resolve } from "node:path";
|
|
@@ -17,8 +18,8 @@ var NpmRuntimeLauncher = class {
|
|
|
17
18
|
this.env = options.env ?? process.env;
|
|
18
19
|
this.layout = options.layout ?? new NpmRuntimeBundleLayoutStore();
|
|
19
20
|
}
|
|
20
|
-
run = () => {
|
|
21
|
-
const runtimeScriptPath = this.resolveRuntimeScriptPath();
|
|
21
|
+
run = async () => {
|
|
22
|
+
const runtimeScriptPath = await this.resolveRuntimeScriptPath();
|
|
22
23
|
const launcherVersion = this.resolveLauncherVersion();
|
|
23
24
|
const launcherEntrypoint = this.options.argv[1]?.trim();
|
|
24
25
|
const result = spawnSync(process.execPath, [runtimeScriptPath, ...this.options.argv.slice(2)], {
|
|
@@ -33,7 +34,7 @@ var NpmRuntimeLauncher = class {
|
|
|
33
34
|
});
|
|
34
35
|
process.exit(typeof result.status === "number" ? result.status : 1);
|
|
35
36
|
};
|
|
36
|
-
resolveRuntimeScriptPath = () => {
|
|
37
|
+
resolveRuntimeScriptPath = async () => {
|
|
37
38
|
const launcherVersion = this.resolveLauncherVersion();
|
|
38
39
|
if (this.env.NEXTCLAW_DISABLE_RUNTIME_BUNDLE_LAUNCHER === "1" || this.env.NEXTCLAW_RUNTIME_BUNDLE_CHILD === "1") return this.resolvePackagedAppEntrypoint();
|
|
39
40
|
const stateStore = new NpmRuntimeUpdateStateStore(this.layout.getStatePath(), { defaultChannel: inferDefaultNpmRuntimeReleaseChannel(launcherVersion) });
|
|
@@ -42,18 +43,46 @@ var NpmRuntimeLauncher = class {
|
|
|
42
43
|
stateStore,
|
|
43
44
|
launcherVersion
|
|
44
45
|
});
|
|
46
|
+
let currentBundle = null;
|
|
45
47
|
try {
|
|
46
|
-
|
|
47
|
-
if (currentBundle && shouldPreferPackagedNpmRuntime({
|
|
48
|
-
launcherVersion,
|
|
49
|
-
currentBundleVersion: currentBundle.manifest.runtimeVersion ?? currentBundle.manifest.bundleVersion
|
|
50
|
-
})) return this.resolvePackagedAppEntrypoint();
|
|
51
|
-
return currentBundle?.runtimeScriptPath ?? this.resolvePackagedAppEntrypoint();
|
|
48
|
+
currentBundle = bundleService.resolveCurrentBundle();
|
|
52
49
|
} catch (error) {
|
|
53
50
|
console.error(`Cannot start current runtime bundle: ${error instanceof Error ? error.message : String(error)}`);
|
|
54
|
-
console.error("Falling back to the packaged npm launcher runtime.");
|
|
55
|
-
return this.resolvePackagedAppEntrypoint();
|
|
56
51
|
}
|
|
52
|
+
const packagedRuntimeComplete = isPackagedNpmRuntimeComplete({ runnerPath: this.options.packagedPortableRunnerPath });
|
|
53
|
+
const currentBundleComplete = Boolean(currentBundle && isNpmRuntimeBundleComplete({ bundleDirectory: currentBundle.bundleDirectory }));
|
|
54
|
+
if (packagedRuntimeComplete && (!currentBundleComplete || currentBundle && shouldPreferPackagedNpmRuntime({
|
|
55
|
+
launcherVersion,
|
|
56
|
+
currentBundleVersion: currentBundle.manifest.runtimeVersion ?? currentBundle.manifest.bundleVersion,
|
|
57
|
+
packagedRuntimeComplete
|
|
58
|
+
}))) return this.resolvePackagedAppEntrypoint();
|
|
59
|
+
if (currentBundleComplete && currentBundle && (currentBundle.manifest.runtimeVersion ?? currentBundle.manifest.bundleVersion) === launcherVersion) return currentBundle.runtimeScriptPath;
|
|
60
|
+
if (!packagedRuntimeComplete || !currentBundleComplete) try {
|
|
61
|
+
await this.bootstrapRuntimeBundle();
|
|
62
|
+
const bootstrappedBundle = bundleService.resolveCurrentBundle();
|
|
63
|
+
if (bootstrappedBundle && isNpmRuntimeBundleComplete({ bundleDirectory: bootstrappedBundle.bundleDirectory })) return bootstrappedBundle.runtimeScriptPath;
|
|
64
|
+
return currentBundle?.runtimeScriptPath ?? this.resolveIncompletePackagedRuntime();
|
|
65
|
+
} catch (error) {
|
|
66
|
+
console.error(`Cannot bootstrap the complete runtime bundle: ${error instanceof Error ? error.message : String(error)}`);
|
|
67
|
+
if (currentBundle) {
|
|
68
|
+
console.error(`Continuing with the previously installed runtime bundle ${currentBundle.manifest.runtimeVersion}.`);
|
|
69
|
+
return currentBundle.runtimeScriptPath;
|
|
70
|
+
}
|
|
71
|
+
return this.resolveIncompletePackagedRuntime();
|
|
72
|
+
}
|
|
73
|
+
return currentBundle?.runtimeScriptPath ?? this.resolvePackagedAppEntrypoint();
|
|
74
|
+
};
|
|
75
|
+
bootstrapRuntimeBundle = async () => {
|
|
76
|
+
if (this.options.bootstrapRuntimeBundle) {
|
|
77
|
+
await this.options.bootstrapRuntimeBundle();
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const snapshot = await new NpmRuntimeUpdateCommandService(this.env).runManaged({});
|
|
81
|
+
if (snapshot.status === "blocked" || snapshot.status === "failed") throw new Error(snapshot.errorMessage ?? snapshot.blockReason ?? "runtime bundle bootstrap failed");
|
|
82
|
+
};
|
|
83
|
+
resolveIncompletePackagedRuntime = () => {
|
|
84
|
+
console.error("The packaged npm runtime is missing the current platform runner; Portable Service Apps remain unavailable until runtime bootstrap succeeds.");
|
|
85
|
+
return this.resolvePackagedAppEntrypoint();
|
|
57
86
|
};
|
|
58
87
|
resolveLauncherVersion = () => this.options.launcherVersion ?? getPackageVersion$1();
|
|
59
88
|
resolvePackagedAppEntrypoint = () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"npm-runtime-launcher.service.js","names":["getPackageVersion"],"sources":["../../src/launcher/npm-runtime-launcher.service.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, resolve } from \"node:path\";\nimport { createExternalCommandEnv } from \"@nextclaw/core\";\nimport { NpmRuntimeBundleLayoutStore } from \"@nextclaw-service/stores/npm-runtime-bundle-layout.store.js\";\nimport {
|
|
1
|
+
{"version":3,"file":"npm-runtime-launcher.service.js","names":["getPackageVersion"],"sources":["../../src/launcher/npm-runtime-launcher.service.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, resolve } from \"node:path\";\nimport { createExternalCommandEnv } from \"@nextclaw/core\";\nimport { NpmRuntimeBundleLayoutStore } from \"@nextclaw-service/stores/npm-runtime-bundle-layout.store.js\";\nimport {\n isNpmRuntimeBundleComplete,\n isPackagedNpmRuntimeComplete,\n NpmRuntimeBundleService,\n shouldPreferPackagedNpmRuntime,\n type ResolvedNpmRuntimeBundle\n} from \"@nextclaw-service/services/runtime/npm-runtime-bundle.service.js\";\nimport { NpmRuntimeUpdateCommandService } from \"@nextclaw-service/services/runtime/npm-runtime-update-command.service.js\";\nimport { inferDefaultNpmRuntimeReleaseChannel } from \"@nextclaw-service/services/runtime/npm-runtime-update-source.service.js\";\nimport { NpmRuntimeUpdateStateStore } from \"@nextclaw-service/stores/npm-runtime-update-state.store.js\";\nimport { getPackageVersion } from \"@nextclaw-service/utils/cli.utils.js\";\n\ntype NpmRuntimeLauncherOptions = {\n argv: string[];\n env?: NodeJS.ProcessEnv;\n layout?: NpmRuntimeBundleLayoutStore;\n launcherVersion?: string;\n packagedAppEntrypoint?: string;\n packagedPortableRunnerPath?: string;\n bootstrapRuntimeBundle?: () => Promise<void>;\n};\n\nexport class NpmRuntimeLauncher {\n private readonly env: NodeJS.ProcessEnv;\n private readonly layout: NpmRuntimeBundleLayoutStore;\n\n constructor(private readonly options: NpmRuntimeLauncherOptions) {\n this.env = options.env ?? process.env;\n this.layout = options.layout ?? new NpmRuntimeBundleLayoutStore();\n }\n\n run = async (): Promise<never> => {\n const runtimeScriptPath = await this.resolveRuntimeScriptPath();\n const launcherVersion = this.resolveLauncherVersion();\n const launcherEntrypoint = this.options.argv[1]?.trim();\n const result = spawnSync(process.execPath, [runtimeScriptPath, ...this.options.argv.slice(2)], {\n stdio: \"inherit\",\n env: {\n ...createExternalCommandEnv(this.env),\n NEXTCLAW_RUNTIME_BUNDLE_CHILD: \"1\",\n NEXTCLAW_NPM_LAUNCHER_VERSION: launcherVersion,\n ...(launcherEntrypoint ? { NEXTCLAW_NPM_LAUNCHER_ENTRYPOINT: launcherEntrypoint } : {})\n },\n windowsHide: true\n });\n process.exit(typeof result.status === \"number\" ? result.status : 1);\n };\n\n private resolveRuntimeScriptPath = async (): Promise<string> => {\n const launcherVersion = this.resolveLauncherVersion();\n if (this.env.NEXTCLAW_DISABLE_RUNTIME_BUNDLE_LAUNCHER === \"1\" || this.env.NEXTCLAW_RUNTIME_BUNDLE_CHILD === \"1\") {\n return this.resolvePackagedAppEntrypoint();\n }\n const stateStore = new NpmRuntimeUpdateStateStore(this.layout.getStatePath(), {\n defaultChannel: inferDefaultNpmRuntimeReleaseChannel(launcherVersion)\n });\n const bundleService = new NpmRuntimeBundleService({\n layout: this.layout,\n stateStore,\n launcherVersion\n });\n let currentBundle: ResolvedNpmRuntimeBundle | null = null;\n try {\n currentBundle = bundleService.resolveCurrentBundle();\n } catch (error) {\n console.error(`Cannot start current runtime bundle: ${error instanceof Error ? error.message : String(error)}`);\n }\n const packagedRuntimeComplete = isPackagedNpmRuntimeComplete({\n runnerPath: this.options.packagedPortableRunnerPath\n });\n const currentBundleComplete = Boolean(currentBundle && isNpmRuntimeBundleComplete({\n bundleDirectory: currentBundle.bundleDirectory\n }));\n if (\n packagedRuntimeComplete &&\n (!currentBundleComplete || (currentBundle && shouldPreferPackagedNpmRuntime({\n launcherVersion,\n currentBundleVersion: currentBundle.manifest.runtimeVersion ?? currentBundle.manifest.bundleVersion,\n packagedRuntimeComplete\n })))\n ) {\n return this.resolvePackagedAppEntrypoint();\n }\n if (\n currentBundleComplete &&\n currentBundle &&\n (currentBundle.manifest.runtimeVersion ?? currentBundle.manifest.bundleVersion) === launcherVersion\n ) {\n return currentBundle.runtimeScriptPath;\n }\n if (!packagedRuntimeComplete || !currentBundleComplete) {\n try {\n await this.bootstrapRuntimeBundle();\n const bootstrappedBundle = bundleService.resolveCurrentBundle();\n if (bootstrappedBundle && isNpmRuntimeBundleComplete({ bundleDirectory: bootstrappedBundle.bundleDirectory })) {\n return bootstrappedBundle.runtimeScriptPath;\n }\n return currentBundle?.runtimeScriptPath ?? this.resolveIncompletePackagedRuntime();\n } catch (error) {\n console.error(`Cannot bootstrap the complete runtime bundle: ${error instanceof Error ? error.message : String(error)}`);\n if (currentBundle) {\n console.error(`Continuing with the previously installed runtime bundle ${currentBundle.manifest.runtimeVersion}.`);\n return currentBundle.runtimeScriptPath;\n }\n return this.resolveIncompletePackagedRuntime();\n }\n }\n return currentBundle?.runtimeScriptPath ?? this.resolvePackagedAppEntrypoint();\n };\n\n private bootstrapRuntimeBundle = async (): Promise<void> => {\n if (this.options.bootstrapRuntimeBundle) {\n await this.options.bootstrapRuntimeBundle();\n return;\n }\n const snapshot = await new NpmRuntimeUpdateCommandService(this.env).runManaged({});\n if (snapshot.status === \"blocked\" || snapshot.status === \"failed\") {\n throw new Error(snapshot.errorMessage ?? snapshot.blockReason ?? \"runtime bundle bootstrap failed\");\n }\n };\n\n private resolveIncompletePackagedRuntime = (): string => {\n console.error(\"The packaged npm runtime is missing the current platform runner; Portable Service Apps remain unavailable until runtime bootstrap succeeds.\");\n return this.resolvePackagedAppEntrypoint();\n };\n\n private resolveLauncherVersion = (): string => this.options.launcherVersion ?? getPackageVersion();\n\n private resolvePackagedAppEntrypoint = (): string => {\n if (this.options.packagedAppEntrypoint) {\n return this.options.packagedAppEntrypoint;\n }\n return resolve(dirname(fileURLToPath(import.meta.url)), \"../app/index.js\");\n };\n}\n"],"mappings":";;;;;;;;;;;;AA2BA,IAAa,qBAAb,MAAgC;CAC9B;CACA;CAEA,YAAY,SAAqD;AAApC,OAAA,UAAA;AAC3B,OAAK,MAAM,QAAQ,OAAO,QAAQ;AAClC,OAAK,SAAS,QAAQ,UAAU,IAAI,6BAA6B;;CAGnE,MAAM,YAA4B;EAChC,MAAM,oBAAoB,MAAM,KAAK,0BAA0B;EAC/D,MAAM,kBAAkB,KAAK,wBAAwB;EACrD,MAAM,qBAAqB,KAAK,QAAQ,KAAK,IAAI,MAAM;EACvD,MAAM,SAAS,UAAU,QAAQ,UAAU,CAAC,mBAAmB,GAAG,KAAK,QAAQ,KAAK,MAAM,EAAE,CAAC,EAAE;GAC7F,OAAO;GACP,KAAK;IACH,GAAG,yBAAyB,KAAK,IAAI;IACrC,+BAA+B;IAC/B,+BAA+B;IAC/B,GAAI,qBAAqB,EAAE,kCAAkC,oBAAoB,GAAG,EAAE;IACvF;GACD,aAAa;GACd,CAAC;AACF,UAAQ,KAA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eAAe;AACjB,YAAQ,MAAM,2DAA2D,cAAc,SAAS,eAAe,GAAG;AAClH,WAAO,cAAc;;AAEvB,UAAO,KAAK,kCAAkC;;AAGlD,SAAO,eAAe,qBAAqB,KAAK,8BAA8B;;CAGhF,yBAAiC,YAA2B;AAC1D,MAAI,KAAK,QAAQ,wBAAwB;AACvC,SAAM,KAAK,QAAQ,wBAAwB;AAC3C;;EAEF,MAAM,WAAW,MAAM,IAAI,+BAA+B,KAAK,IAAI,CAAC,WAAW,EAAE,CAAC;AAClF,MAAI,SAAS,WAAW,aAAa,SAAS,WAAW,SACvD,OAAM,IAAI,MAAM,SAAS,gBAAgB,SAAS,eAAe,kCAAkC;;CAIvG,yCAAyD;AACvD,UAAQ,MAAM,8IAA8I;AAC5J,SAAO,KAAK,8BAA8B;;CAG5C,+BAA+C,KAAK,QAAQ,mBAAmBA,qBAAmB;CAElG,qCAAqD;AACnD,MAAI,KAAK,QAAQ,sBACf,QAAO,KAAK,QAAQ;AAEtB,SAAO,QAAQ,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAC,EAAE,kBAAkB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-update.manager.d.ts","names":[],"sources":["../../src/managers/runtime-update.manager.ts"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"runtime-update.manager.d.ts","names":[],"sources":["../../src/managers/runtime-update.manager.ts"],"mappings":";;;;;;;;KAYK,2BAAA;EACH,MAAA,EAAQ,2BAAA;EACR,UAAA,EAAY,0BAAA;EACZ,aAAA,EAAe,uBAAA;EACf,aAAA,EAAe,uBAAA;EACf,kBAAA,GAAqB,OAAA,EAAS,wBAAA;EAC9B,eAAA;EACA,cAAA;EACA,OAAA,EAAS,wBAAA;EACT,GAAA,SAAY,IAAA;AAAA;AAAA,KAGT,6BAAA;EACH,KAAA;EACA,kBAAA;EACA,SAAA;EACA,UAAA,IAAc,QAAA,EAAU,cAAA;AAAA;AAAA,cAGb,oBAAA;EAAA,iBAMkB,OAAA;EAAA,iBALZ,eAAA;EAAA,iBACA,cAAA;EAAA,iBACA,GAAA;EAAA,QACT,iBAAA;cAEqB,OAAA,EAAS,2BAAA;EAQtC,WAAA,QAAkB,cAAA;EAYlB,GAAA,GAAa,OAAA,GAAS,6BAAA,KAAqC,OAAA,CAAQ,cAAA;EAuBnE,cAAA,QAA2B,OAAA,CAAQ,cAAA;EA+BnC,cAAA,GAAwB,UAAA,IAAc,QAAA,EAAU,cAAA,cAA0B,OAAA,CAAQ,cAAA;EAoBlF,qBAAA,QAA4B,cAAA;EAAA,QAkBpB,uBAAA;EAAA,QAWA,oBAAA;EAAA,QAiEA,2BAAA;EAAA,QAgBA,mBAAA;EAAA,QA8BA,6BAAA;AAAA"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { getPackageVersion } from "../utils/package/package-manifest.utils.js";
|
|
2
2
|
import "../utils/cli.utils.js";
|
|
3
|
-
import {
|
|
3
|
+
import { isNpmRuntimeBundleComplete } from "../services/runtime/npm-runtime-bundle.service.js";
|
|
4
4
|
//#region src/managers/runtime-update.manager.ts
|
|
5
5
|
var RuntimeUpdateManager = class {
|
|
6
6
|
launcherVersion;
|
|
@@ -84,6 +84,7 @@ var RuntimeUpdateManager = class {
|
|
|
84
84
|
this.availableManifest = null;
|
|
85
85
|
return this.toSnapshotFromState(this.options.stateStore.read(), {
|
|
86
86
|
status: "restart-required",
|
|
87
|
+
targetVersion: downloadedVersion,
|
|
87
88
|
availableVersion: null,
|
|
88
89
|
downloadedVersion: null,
|
|
89
90
|
releaseNotesUrl: null,
|
|
@@ -161,15 +162,16 @@ var RuntimeUpdateManager = class {
|
|
|
161
162
|
});
|
|
162
163
|
};
|
|
163
164
|
syncStateFromCurrentPointer = () => {
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
}
|
|
169
|
-
|
|
165
|
+
let currentVersion = null;
|
|
166
|
+
try {
|
|
167
|
+
const currentBundle = this.options.bundleService.resolveCurrentBundle();
|
|
168
|
+
if (currentBundle && isNpmRuntimeBundleComplete({ bundleDirectory: currentBundle.bundleDirectory })) currentVersion = currentBundle.manifest.runtimeVersion ?? currentBundle.manifest.bundleVersion;
|
|
169
|
+
} catch {
|
|
170
|
+
currentVersion = null;
|
|
171
|
+
}
|
|
170
172
|
this.options.stateStore.update((state) => ({
|
|
171
173
|
...state,
|
|
172
|
-
currentVersion
|
|
174
|
+
currentVersion
|
|
173
175
|
}));
|
|
174
176
|
};
|
|
175
177
|
toSnapshotFromState = (state, patch) => {
|
|
@@ -180,6 +182,7 @@ var RuntimeUpdateManager = class {
|
|
|
180
182
|
channel: state.channel,
|
|
181
183
|
hostVersion: this.launcherVersion,
|
|
182
184
|
currentVersion: this.runningVersion,
|
|
185
|
+
targetVersion: null,
|
|
183
186
|
availableVersion: null,
|
|
184
187
|
downloadedVersion: state.downloadedVersion,
|
|
185
188
|
minimumHostVersion: null,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-update.manager.js","names":[],"sources":["../../src/managers/runtime-update.manager.ts"],"sourcesContent":["import type { UpdateManifest, UpdateProgress, UpdateSnapshot } from \"@nextclaw/kernel\";\nimport { getPackageVersion } from \"@nextclaw-service/utils/cli.utils.js\";\nimport { resolveEffectiveNpmRuntimeVersion } from \"@nextclaw-service/services/runtime/npm-runtime-bundle.service.js\";\nimport type { NpmRuntimeBundleService } from \"@nextclaw-service/services/runtime/npm-runtime-bundle.service.js\";\nimport type { NpmRuntimeBundleLayoutStore } from \"@nextclaw-service/stores/npm-runtime-bundle-layout.store.js\";\nimport type { NpmRuntimeUpdateService, NpmRuntimeAvailableUpdate } from \"@nextclaw-service/services/runtime/npm-runtime-update.service.js\";\nimport type { NpmRuntimeUpdateStateStore } from \"@nextclaw-service/stores/npm-runtime-update-state.store.js\";\nimport type { NpmRuntimeReleaseChannel } from \"@nextclaw-service/services/runtime/npm-runtime-update-source.service.js\";\nimport type { NpmRuntimeUpdateState } from \"@nextclaw-service/types/npm-runtime-bundle.types.js\";\n\ntype RuntimeUpdateManagerOptions = {\n layout: NpmRuntimeBundleLayoutStore;\n stateStore: NpmRuntimeUpdateStateStore;\n bundleService: NpmRuntimeBundleService;\n updateService: NpmRuntimeUpdateService;\n resolveManifestUrl: (channel: NpmRuntimeReleaseChannel) => string | null;\n launcherVersion?: string;\n runningVersion?: string;\n channel: NpmRuntimeReleaseChannel;\n now?: () => Date;\n};\n\ntype NpmRuntimeUpdateActionOptions = {\n apply?: boolean;\n applyAfterDownload?: boolean;\n checkOnly?: boolean;\n onProgress?: (progress: UpdateProgress) => void;\n};\n\nexport class RuntimeUpdateManager {\n private readonly launcherVersion: string;\n private readonly runningVersion: string;\n private readonly now: () => Date;\n private availableManifest: UpdateManifest | null = null;\n\n constructor(private readonly options: RuntimeUpdateManagerOptions) {\n this.launcherVersion = options.launcherVersion ?? getPackageVersion();\n this.runningVersion = options.runningVersion ?? getPackageVersion();\n this.now = options.now ?? (() => new Date());\n this.options.layout.ensureLauncherDirs();\n this.syncStateFromCurrentPointer();\n }\n\n getSnapshot = (): UpdateSnapshot => {\n const state = this.options.stateStore.read();\n return this.toSnapshotFromState(state, {\n status: state.downloadedVersion\n ? \"downloaded\"\n : this.requiresRunningVersionRestart(state)\n ? \"restart-required\"\n : \"idle\",\n requiresRestart: this.requiresRunningVersionRestart(state)\n });\n };\n\n run = async (options: NpmRuntimeUpdateActionOptions = {}): Promise<UpdateSnapshot> => {\n if (options.apply) {\n return this.applyDownloadedUpdate();\n }\n\n const applyAfterDownload = options.applyAfterDownload ?? true;\n const checkedSnapshot = await this.checkForUpdate();\n if (options.checkOnly) {\n return checkedSnapshot;\n }\n if (applyAfterDownload && checkedSnapshot.status === \"downloaded\") {\n return this.applyDownloadedUpdate();\n }\n if (checkedSnapshot.status !== \"update-available\") {\n return checkedSnapshot;\n }\n const downloadedSnapshot = await this.downloadUpdate(options.onProgress);\n if (!applyAfterDownload || downloadedSnapshot.status !== \"downloaded\") {\n return downloadedSnapshot;\n }\n return this.applyDownloadedUpdate();\n };\n\n checkForUpdate = async (): Promise<UpdateSnapshot> => {\n const manifestUrl = this.options.resolveManifestUrl(this.options.channel);\n if (!this.options.updateService.hasSignatureVerifier()) {\n return this.toSnapshotFromState(this.options.stateStore.read(), {\n status: \"blocked\",\n installationKind: \"npm-runtime-bundle\",\n blockReason: \"signature-verification-unavailable\",\n recoveryCommand: \"Set NEXTCLAW_UPDATE_BUNDLE_PUBLIC_KEY or NEXTCLAW_UPDATE_BUNDLE_PUBLIC_KEY_PATH\",\n errorMessage: \"Runtime bundle updates require a configured update public key.\"\n });\n }\n if (!manifestUrl) {\n return this.toSnapshotFromState(this.options.stateStore.read(), {\n status: \"blocked\",\n installationKind: \"npm-runtime-bundle\",\n blockReason: \"unsupported-installation\",\n recoveryCommand: \"Set NEXTCLAW_UPDATE_MANIFEST_URL or NEXTCLAW_UPDATE_MANIFEST_BASE_URL\",\n errorMessage: \"Runtime bundle update manifest URL is not configured.\"\n });\n }\n\n const checkedAt = this.now().toISOString();\n const state = this.options.stateStore.update((current) => ({\n ...current,\n channel: this.options.channel,\n lastUpdateCheckAt: checkedAt\n }));\n const availableUpdate = await this.options.updateService.checkForUpdate(manifestUrl, state.currentVersion, state.badVersions);\n return this.toSnapshotAfterCheck(availableUpdate, this.options.stateStore.read());\n };\n\n downloadUpdate = async (onProgress?: (progress: UpdateProgress) => void): Promise<UpdateSnapshot> => {\n const manifest = this.availableManifest ?? await this.ensureAvailableManifest();\n const downloaded = await this.options.updateService.downloadAndInstallUpdate(manifest, onProgress);\n const state = this.options.stateStore.update((current) => ({\n ...current,\n downloadedVersion: downloaded.downloadedVersion,\n downloadedReleaseNotesUrl: downloaded.manifest.releaseNotesUrl\n }));\n await this.options.bundleService.pruneRetainedArtifacts();\n return this.toSnapshotFromState(state, {\n status: \"downloaded\",\n availableVersion: downloaded.downloadedVersion,\n downloadedVersion: downloaded.downloadedVersion,\n minimumHostVersion: downloaded.manifest.minimumLauncherVersion,\n releaseNotesUrl: downloaded.manifest.releaseNotesUrl,\n canApplyInApp: true,\n requiresRestart: false\n });\n };\n\n applyDownloadedUpdate = (): UpdateSnapshot => {\n const downloadedVersion = this.options.stateStore.read().downloadedVersion?.trim();\n if (!downloadedVersion) {\n throw new Error(\"No downloaded npm runtime update is ready to apply.\");\n }\n this.options.bundleService.activateVersion(downloadedVersion);\n this.availableManifest = null;\n return this.toSnapshotFromState(this.options.stateStore.read(), {\n status: \"restart-required\",\n availableVersion: null,\n downloadedVersion: null,\n releaseNotesUrl: null,\n canApplyInApp: false,\n requiresRestart: true\n });\n };\n\n private ensureAvailableManifest = async (): Promise<UpdateManifest> => {\n const snapshot = await this.checkForUpdate();\n if (!this.availableManifest) {\n if (snapshot.downloadedVersion) {\n throw new Error(`Version ${snapshot.downloadedVersion} has already been downloaded and is ready to apply.`);\n }\n throw new Error(\"No npm runtime update is currently available.\");\n }\n return this.availableManifest;\n };\n\n private toSnapshotAfterCheck = (\n availableUpdate: NpmRuntimeAvailableUpdate | null,\n state: NpmRuntimeUpdateState\n ): UpdateSnapshot => {\n if (state.downloadedVersion) {\n this.availableManifest = availableUpdate?.kind === \"runtime-bundle-update\" ? availableUpdate.manifest : this.availableManifest;\n return this.toSnapshotFromState(state, {\n status: \"downloaded\",\n availableVersion: availableUpdate?.kind === \"runtime-bundle-update\" ? availableUpdate.manifest.latestVersion : state.downloadedVersion,\n minimumHostVersion: availableUpdate?.kind === \"runtime-bundle-update\" ? availableUpdate.manifest.minimumLauncherVersion : null,\n canApplyInApp: true,\n requiresRestart: false\n });\n }\n if (this.requiresRunningVersionRestart(state)) {\n this.availableManifest = availableUpdate?.kind === \"runtime-bundle-update\" ? availableUpdate.manifest : null;\n return this.toSnapshotFromState(state, {\n status: \"restart-required\",\n availableVersion: availableUpdate?.manifest.latestVersion ?? null,\n minimumHostVersion: availableUpdate?.manifest.minimumLauncherVersion ?? null,\n releaseNotesUrl: availableUpdate?.manifest.releaseNotesUrl ?? null,\n canApplyInApp: false,\n requiresRestart: true\n });\n }\n if (!availableUpdate) {\n this.availableManifest = null;\n return this.toSnapshotFromState(state, {\n status: \"up-to-date\",\n availableVersion: null,\n downloadedVersion: null,\n releaseNotesUrl: null\n });\n }\n if (availableUpdate.kind === \"host-update-required\") {\n this.availableManifest = null;\n return this.toSnapshotFromState(state, {\n status: \"blocked\",\n availableVersion: availableUpdate.manifest.latestVersion,\n minimumHostVersion: availableUpdate.manifest.minimumLauncherVersion,\n releaseNotesUrl: availableUpdate.manifest.releaseNotesUrl,\n blockReason: \"host-too-old\",\n recoveryCommand: \"npm install -g nextclaw@latest\",\n errorMessage: `NextClaw npm launcher ${this.launcherVersion} is too old for runtime bundle ${availableUpdate.manifest.latestVersion}.`\n });\n }\n if (availableUpdate.kind === \"quarantined-bad-version\") {\n this.availableManifest = null;\n return this.toSnapshotFromState(state, {\n status: \"failed\",\n availableVersion: availableUpdate.manifest.latestVersion,\n minimumHostVersion: availableUpdate.manifest.minimumLauncherVersion,\n releaseNotesUrl: availableUpdate.manifest.releaseNotesUrl,\n errorMessage: `Version ${availableUpdate.manifest.latestVersion} was quarantined after a failed launch.`\n });\n }\n this.availableManifest = availableUpdate.manifest;\n return this.toSnapshotFromState(state, {\n status: \"update-available\",\n availableVersion: availableUpdate.manifest.latestVersion,\n minimumHostVersion: availableUpdate.manifest.minimumLauncherVersion,\n releaseNotesUrl: availableUpdate.manifest.releaseNotesUrl\n });\n };\n\n private syncStateFromCurrentPointer = (): void => {\n const currentPointer = this.options.layout.readCurrentPointer();\n const effectiveCurrentVersion = resolveEffectiveNpmRuntimeVersion({\n launcherVersion: this.launcherVersion,\n currentBundleVersion: currentPointer?.version ?? null\n });\n if (!effectiveCurrentVersion) {\n return;\n }\n this.options.stateStore.update((state) => ({\n ...state,\n currentVersion: effectiveCurrentVersion\n }));\n };\n\n private toSnapshotFromState = (\n state: NpmRuntimeUpdateState,\n patch: Partial<UpdateSnapshot> & Pick<UpdateSnapshot, \"status\">\n ): UpdateSnapshot => {\n const hasDownloadedVersion = Boolean(state.downloadedVersion);\n const { status } = patch;\n return {\n installationKind: \"npm-runtime-bundle\",\n channel: state.channel,\n hostVersion: this.launcherVersion,\n currentVersion: this.runningVersion,\n availableVersion: null,\n downloadedVersion: state.downloadedVersion,\n minimumHostVersion: null,\n releaseNotesUrl: state.downloadedReleaseNotesUrl,\n lastCheckedAt: state.lastUpdateCheckAt,\n progress: null,\n canApplyInApp: hasDownloadedVersion,\n requiresRestart: false,\n blockReason: null,\n recoveryCommand: null,\n errorMessage: null,\n failureStage: null,\n diagnosticCommand: null,\n ...patch,\n status\n };\n };\n\n private requiresRunningVersionRestart = (state: NpmRuntimeUpdateState): boolean => {\n const targetVersion = state.currentVersion?.trim();\n const runningVersion = this.runningVersion.trim();\n return Boolean(targetVersion && runningVersion && targetVersion !== runningVersion);\n };\n}\n"],"mappings":";;;;AA6BA,IAAa,uBAAb,MAAkC;CAChC;CACA;CACA;CACA,oBAAmD;CAEnD,YAAY,SAAuD;AAAtC,OAAA,UAAA;AAC3B,OAAK,kBAAkB,QAAQ,mBAAmB,mBAAmB;AACrE,OAAK,iBAAiB,QAAQ,kBAAkB,mBAAmB;AACnE,OAAK,MAAM,QAAQ,8BAAc,IAAI,MAAM;AAC3C,OAAK,QAAQ,OAAO,oBAAoB;AACxC,OAAK,6BAA6B;;CAGpC,oBAAoC;EAClC,MAAM,QAAQ,KAAK,QAAQ,WAAW,MAAM;AAC5C,SAAO,KAAK,oBAAoB,OAAO;GACrC,QAAQ,MAAM,oBACV,eACA,KAAK,8BAA8B,MAAM,GACvC,qBACA;GACN,iBAAiB,KAAK,8BAA8B,MAAM;GAC3D,CAAC;;CAGJ,MAAM,OAAO,UAAyC,EAAE,KAA8B;AACpF,MAAI,QAAQ,MACV,QAAO,KAAK,uBAAuB;EAGrC,MAAM,qBAAqB,QAAQ,sBAAsB;EACzD,MAAM,kBAAkB,MAAM,KAAK,gBAAgB;AACnD,MAAI,QAAQ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,OAAK,QAAQ,WAAW,QAAQ,WAAW;GACzC,GAAG;GACH,gBAAgB;GACjB,EAAE;;CAGL,uBACE,OACA,UACmB;EACnB,MAAM,uBAAuB,QAAQ,MAAM,kBAAkB;EAC7D,MAAM,EAAE,WAAW;AACnB,SAAO;GACL,kBAAkB;GAClB,SAAS,MAAM;GACf,aAAa,KAAK;GAClB,gBAAgB,KAAK;GACrB,kBAAkB;GAClB,mBAAmB,MAAM;GACzB,oBAAoB;GACpB,iBAAiB,MAAM;GACvB,eAAe,MAAM;GACrB,UAAU;GACV,eAAe;GACf,iBAAiB;GACjB,aAAa;GACb,iBAAiB;GACjB,cAAc;GACd,cAAc;GACd,mBAAmB;GACnB,GAAG;GACH;GACD;;CAGH,iCAAyC,UAA0C;EACjF,MAAM,gBAAgB,MAAM,gBAAgB,MAAM;EAClD,MAAM,iBAAiB,KAAK,eAAe,MAAM;AACjD,SAAO,QAAQ,iBAAiB,kBAAkB,kBAAkB,eAAe"}
|
|
1
|
+
{"version":3,"file":"runtime-update.manager.js","names":[],"sources":["../../src/managers/runtime-update.manager.ts"],"sourcesContent":["import type { UpdateManifest, UpdateProgress, UpdateSnapshot } from \"@nextclaw/kernel\";\nimport { getPackageVersion } from \"@nextclaw-service/utils/cli.utils.js\";\nimport {\n isNpmRuntimeBundleComplete,\n type NpmRuntimeBundleService\n} from \"@nextclaw-service/services/runtime/npm-runtime-bundle.service.js\";\nimport type { NpmRuntimeBundleLayoutStore } from \"@nextclaw-service/stores/npm-runtime-bundle-layout.store.js\";\nimport type { NpmRuntimeUpdateService, NpmRuntimeAvailableUpdate } from \"@nextclaw-service/services/runtime/npm-runtime-update.service.js\";\nimport type { NpmRuntimeUpdateStateStore } from \"@nextclaw-service/stores/npm-runtime-update-state.store.js\";\nimport type { NpmRuntimeReleaseChannel } from \"@nextclaw-service/services/runtime/npm-runtime-update-source.service.js\";\nimport type { NpmRuntimeUpdateState } from \"@nextclaw-service/types/npm-runtime-bundle.types.js\";\n\ntype RuntimeUpdateManagerOptions = {\n layout: NpmRuntimeBundleLayoutStore;\n stateStore: NpmRuntimeUpdateStateStore;\n bundleService: NpmRuntimeBundleService;\n updateService: NpmRuntimeUpdateService;\n resolveManifestUrl: (channel: NpmRuntimeReleaseChannel) => string | null;\n launcherVersion?: string;\n runningVersion?: string;\n channel: NpmRuntimeReleaseChannel;\n now?: () => Date;\n};\n\ntype NpmRuntimeUpdateActionOptions = {\n apply?: boolean;\n applyAfterDownload?: boolean;\n checkOnly?: boolean;\n onProgress?: (progress: UpdateProgress) => void;\n};\n\nexport class RuntimeUpdateManager {\n private readonly launcherVersion: string;\n private readonly runningVersion: string;\n private readonly now: () => Date;\n private availableManifest: UpdateManifest | null = null;\n\n constructor(private readonly options: RuntimeUpdateManagerOptions) {\n this.launcherVersion = options.launcherVersion ?? getPackageVersion();\n this.runningVersion = options.runningVersion ?? getPackageVersion();\n this.now = options.now ?? (() => new Date());\n this.options.layout.ensureLauncherDirs();\n this.syncStateFromCurrentPointer();\n }\n\n getSnapshot = (): UpdateSnapshot => {\n const state = this.options.stateStore.read();\n return this.toSnapshotFromState(state, {\n status: state.downloadedVersion\n ? \"downloaded\"\n : this.requiresRunningVersionRestart(state)\n ? \"restart-required\"\n : \"idle\",\n requiresRestart: this.requiresRunningVersionRestart(state)\n });\n };\n\n run = async (options: NpmRuntimeUpdateActionOptions = {}): Promise<UpdateSnapshot> => {\n if (options.apply) {\n return this.applyDownloadedUpdate();\n }\n\n const applyAfterDownload = options.applyAfterDownload ?? true;\n const checkedSnapshot = await this.checkForUpdate();\n if (options.checkOnly) {\n return checkedSnapshot;\n }\n if (applyAfterDownload && checkedSnapshot.status === \"downloaded\") {\n return this.applyDownloadedUpdate();\n }\n if (checkedSnapshot.status !== \"update-available\") {\n return checkedSnapshot;\n }\n const downloadedSnapshot = await this.downloadUpdate(options.onProgress);\n if (!applyAfterDownload || downloadedSnapshot.status !== \"downloaded\") {\n return downloadedSnapshot;\n }\n return this.applyDownloadedUpdate();\n };\n\n checkForUpdate = async (): Promise<UpdateSnapshot> => {\n const manifestUrl = this.options.resolveManifestUrl(this.options.channel);\n if (!this.options.updateService.hasSignatureVerifier()) {\n return this.toSnapshotFromState(this.options.stateStore.read(), {\n status: \"blocked\",\n installationKind: \"npm-runtime-bundle\",\n blockReason: \"signature-verification-unavailable\",\n recoveryCommand: \"Set NEXTCLAW_UPDATE_BUNDLE_PUBLIC_KEY or NEXTCLAW_UPDATE_BUNDLE_PUBLIC_KEY_PATH\",\n errorMessage: \"Runtime bundle updates require a configured update public key.\"\n });\n }\n if (!manifestUrl) {\n return this.toSnapshotFromState(this.options.stateStore.read(), {\n status: \"blocked\",\n installationKind: \"npm-runtime-bundle\",\n blockReason: \"unsupported-installation\",\n recoveryCommand: \"Set NEXTCLAW_UPDATE_MANIFEST_URL or NEXTCLAW_UPDATE_MANIFEST_BASE_URL\",\n errorMessage: \"Runtime bundle update manifest URL is not configured.\"\n });\n }\n\n const checkedAt = this.now().toISOString();\n const state = this.options.stateStore.update((current) => ({\n ...current,\n channel: this.options.channel,\n lastUpdateCheckAt: checkedAt\n }));\n const availableUpdate = await this.options.updateService.checkForUpdate(manifestUrl, state.currentVersion, state.badVersions);\n return this.toSnapshotAfterCheck(availableUpdate, this.options.stateStore.read());\n };\n\n downloadUpdate = async (onProgress?: (progress: UpdateProgress) => void): Promise<UpdateSnapshot> => {\n const manifest = this.availableManifest ?? await this.ensureAvailableManifest();\n const downloaded = await this.options.updateService.downloadAndInstallUpdate(manifest, onProgress);\n const state = this.options.stateStore.update((current) => ({\n ...current,\n downloadedVersion: downloaded.downloadedVersion,\n downloadedReleaseNotesUrl: downloaded.manifest.releaseNotesUrl\n }));\n await this.options.bundleService.pruneRetainedArtifacts();\n return this.toSnapshotFromState(state, {\n status: \"downloaded\",\n availableVersion: downloaded.downloadedVersion,\n downloadedVersion: downloaded.downloadedVersion,\n minimumHostVersion: downloaded.manifest.minimumLauncherVersion,\n releaseNotesUrl: downloaded.manifest.releaseNotesUrl,\n canApplyInApp: true,\n requiresRestart: false\n });\n };\n\n applyDownloadedUpdate = (): UpdateSnapshot => {\n const downloadedVersion = this.options.stateStore.read().downloadedVersion?.trim();\n if (!downloadedVersion) {\n throw new Error(\"No downloaded npm runtime update is ready to apply.\");\n }\n this.options.bundleService.activateVersion(downloadedVersion);\n this.availableManifest = null;\n return this.toSnapshotFromState(this.options.stateStore.read(), {\n status: \"restart-required\",\n targetVersion: downloadedVersion,\n availableVersion: null,\n downloadedVersion: null,\n releaseNotesUrl: null,\n canApplyInApp: false,\n requiresRestart: true\n });\n };\n\n private ensureAvailableManifest = async (): Promise<UpdateManifest> => {\n const snapshot = await this.checkForUpdate();\n if (!this.availableManifest) {\n if (snapshot.downloadedVersion) {\n throw new Error(`Version ${snapshot.downloadedVersion} has already been downloaded and is ready to apply.`);\n }\n throw new Error(\"No npm runtime update is currently available.\");\n }\n return this.availableManifest;\n };\n\n private toSnapshotAfterCheck = (\n availableUpdate: NpmRuntimeAvailableUpdate | null,\n state: NpmRuntimeUpdateState\n ): UpdateSnapshot => {\n if (state.downloadedVersion) {\n this.availableManifest = availableUpdate?.kind === \"runtime-bundle-update\" ? availableUpdate.manifest : this.availableManifest;\n return this.toSnapshotFromState(state, {\n status: \"downloaded\",\n availableVersion: availableUpdate?.kind === \"runtime-bundle-update\" ? availableUpdate.manifest.latestVersion : state.downloadedVersion,\n minimumHostVersion: availableUpdate?.kind === \"runtime-bundle-update\" ? availableUpdate.manifest.minimumLauncherVersion : null,\n canApplyInApp: true,\n requiresRestart: false\n });\n }\n if (this.requiresRunningVersionRestart(state)) {\n this.availableManifest = availableUpdate?.kind === \"runtime-bundle-update\" ? availableUpdate.manifest : null;\n return this.toSnapshotFromState(state, {\n status: \"restart-required\",\n availableVersion: availableUpdate?.manifest.latestVersion ?? null,\n minimumHostVersion: availableUpdate?.manifest.minimumLauncherVersion ?? null,\n releaseNotesUrl: availableUpdate?.manifest.releaseNotesUrl ?? null,\n canApplyInApp: false,\n requiresRestart: true\n });\n }\n if (!availableUpdate) {\n this.availableManifest = null;\n return this.toSnapshotFromState(state, {\n status: \"up-to-date\",\n availableVersion: null,\n downloadedVersion: null,\n releaseNotesUrl: null\n });\n }\n if (availableUpdate.kind === \"host-update-required\") {\n this.availableManifest = null;\n return this.toSnapshotFromState(state, {\n status: \"blocked\",\n availableVersion: availableUpdate.manifest.latestVersion,\n minimumHostVersion: availableUpdate.manifest.minimumLauncherVersion,\n releaseNotesUrl: availableUpdate.manifest.releaseNotesUrl,\n blockReason: \"host-too-old\",\n recoveryCommand: \"npm install -g nextclaw@latest\",\n errorMessage: `NextClaw npm launcher ${this.launcherVersion} is too old for runtime bundle ${availableUpdate.manifest.latestVersion}.`\n });\n }\n if (availableUpdate.kind === \"quarantined-bad-version\") {\n this.availableManifest = null;\n return this.toSnapshotFromState(state, {\n status: \"failed\",\n availableVersion: availableUpdate.manifest.latestVersion,\n minimumHostVersion: availableUpdate.manifest.minimumLauncherVersion,\n releaseNotesUrl: availableUpdate.manifest.releaseNotesUrl,\n errorMessage: `Version ${availableUpdate.manifest.latestVersion} was quarantined after a failed launch.`\n });\n }\n this.availableManifest = availableUpdate.manifest;\n return this.toSnapshotFromState(state, {\n status: \"update-available\",\n availableVersion: availableUpdate.manifest.latestVersion,\n minimumHostVersion: availableUpdate.manifest.minimumLauncherVersion,\n releaseNotesUrl: availableUpdate.manifest.releaseNotesUrl\n });\n };\n\n private syncStateFromCurrentPointer = (): void => {\n let currentVersion: string | null = null;\n try {\n const currentBundle = this.options.bundleService.resolveCurrentBundle();\n if (currentBundle && isNpmRuntimeBundleComplete({ bundleDirectory: currentBundle.bundleDirectory })) {\n currentVersion = currentBundle.manifest.runtimeVersion ?? currentBundle.manifest.bundleVersion;\n }\n } catch {\n currentVersion = null;\n }\n this.options.stateStore.update((state) => ({\n ...state,\n currentVersion\n }));\n };\n\n private toSnapshotFromState = (\n state: NpmRuntimeUpdateState,\n patch: Partial<UpdateSnapshot> & Pick<UpdateSnapshot, \"status\">\n ): UpdateSnapshot => {\n const hasDownloadedVersion = Boolean(state.downloadedVersion);\n const { status } = patch;\n return {\n installationKind: \"npm-runtime-bundle\",\n channel: state.channel,\n hostVersion: this.launcherVersion,\n currentVersion: this.runningVersion,\n targetVersion: null,\n availableVersion: null,\n downloadedVersion: state.downloadedVersion,\n minimumHostVersion: null,\n releaseNotesUrl: state.downloadedReleaseNotesUrl,\n lastCheckedAt: state.lastUpdateCheckAt,\n progress: null,\n canApplyInApp: hasDownloadedVersion,\n requiresRestart: false,\n blockReason: null,\n recoveryCommand: null,\n errorMessage: null,\n failureStage: null,\n diagnosticCommand: null,\n ...patch,\n status\n };\n };\n\n private requiresRunningVersionRestart = (state: NpmRuntimeUpdateState): boolean => {\n const targetVersion = state.currentVersion?.trim();\n const runningVersion = this.runningVersion.trim();\n return Boolean(targetVersion && runningVersion && targetVersion !== runningVersion);\n };\n}\n"],"mappings":";;;;AA+BA,IAAa,uBAAb,MAAkC;CAChC;CACA;CACA;CACA,oBAAmD;CAEnD,YAAY,SAAuD;AAAtC,OAAA,UAAA;AAC3B,OAAK,kBAAkB,QAAQ,mBAAmB,mBAAmB;AACrE,OAAK,iBAAiB,QAAQ,kBAAkB,mBAAmB;AACnE,OAAK,MAAM,QAAQ,8BAAc,IAAI,MAAM;AAC3C,OAAK,QAAQ,OAAO,oBAAoB;AACxC,OAAK,6BAA6B;;CAGpC,oBAAoC;EAClC,MAAM,QAAQ,KAAK,QAAQ,WAAW,MAAM;AAC5C,SAAO,KAAK,oBAAoB,OAAO;GACrC,QAAQ,MAAM,oBACV,eACA,KAAK,8BAA8B,MAAM,GACvC,qBACA;GACN,iBAAiB,KAAK,8BAA8B,MAAM;GAC3D,CAAC;;CAGJ,MAAM,OAAO,UAAyC,EAAE,KAA8B;AACpF,MAAI,QAAQ,MACV,QAAO,KAAK,uBAAuB;EAGrC,MAAM,qBAAqB,QAAQ,sBAAsB;EACzD,MAAM,kBAAkB,MAAM,KAAK,gBAAgB;AACnD,MA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G,kBAAiB,cAAc,SAAS,kBAAkB,cAAc,SAAS;UAE7E;AACN,oBAAiB;;AAEnB,OAAK,QAAQ,WAAW,QAAQ,WAAW;GACzC,GAAG;GACH;GACD,EAAE;;CAGL,uBACE,OACA,UACmB;EACnB,MAAM,uBAAuB,QAAQ,MAAM,kBAAkB;EAC7D,MAAM,EAAE,WAAW;AACnB,SAAO;GACL,kBAAkB;GAClB,SAAS,MAAM;GACf,aAAa,KAAK;GAClB,gBAAgB,KAAK;GACrB,eAAe;GACf,kBAAkB;GAClB,mBAAmB,MAAM;GACzB,oBAAoB;GACpB,iBAAiB,MAAM;GACvB,eAAe,MAAM;GACrB,UAAU;GACV,eAAe;GACf,iBAAiB;GACjB,aAAa;GACb,iBAAiB;GACjB,cAAc;GACd,cAAc;GACd,mBAAmB;GACnB,GAAG;GACH;GACD;;CAGH,iCAAyC,UAA0C;EACjF,MAAM,gBAAgB,MAAM,gBAAgB,MAAM;EAClD,MAAM,iBAAiB,KAAK,eAAe,MAAM;AACjD,SAAO,QAAQ,iBAAiB,kBAAkB,kBAAkB,eAAe"}
|
|
@@ -32,17 +32,28 @@ declare class NpmRuntimeBundleService {
|
|
|
32
32
|
activateVersion: (version: string) => void;
|
|
33
33
|
pruneRetainedArtifacts: () => Promise<void>;
|
|
34
34
|
private clearStagingDirectory;
|
|
35
|
+
private assertBundleComplete;
|
|
36
|
+
private resolveReusableBundle;
|
|
37
|
+
private displaceExistingBundle;
|
|
38
|
+
private moveBundleIntoPlace;
|
|
39
|
+
private restoreDisplacedBundle;
|
|
35
40
|
private verifyBundle;
|
|
36
41
|
}
|
|
37
42
|
declare function compareNpmRuntimeVersions(left: string, right: string): number;
|
|
38
|
-
declare function resolveEffectiveNpmRuntimeVersion(params: {
|
|
39
|
-
launcherVersion: string | null;
|
|
40
|
-
currentBundleVersion: string | null;
|
|
41
|
-
}): string | null;
|
|
42
43
|
declare function shouldPreferPackagedNpmRuntime(params: {
|
|
43
44
|
launcherVersion: string | null;
|
|
44
45
|
currentBundleVersion: string | null;
|
|
46
|
+
packagedRuntimeComplete: boolean;
|
|
47
|
+
}): boolean;
|
|
48
|
+
declare function isPackagedNpmRuntimeComplete(params: {
|
|
49
|
+
runnerPath: string | null | undefined;
|
|
50
|
+
platform?: NodeJS.Platform;
|
|
51
|
+
}): boolean;
|
|
52
|
+
declare function isNpmRuntimeBundleComplete(params: {
|
|
53
|
+
bundleDirectory: string;
|
|
54
|
+
platform?: NodeJS.Platform;
|
|
55
|
+
arch?: string;
|
|
45
56
|
}): boolean;
|
|
46
57
|
//#endregion
|
|
47
|
-
export { NpmRuntimeBundleService, ResolvedNpmRuntimeBundle, compareNpmRuntimeVersions,
|
|
58
|
+
export { NpmRuntimeBundleService, ResolvedNpmRuntimeBundle, compareNpmRuntimeVersions, isNpmRuntimeBundleComplete, isPackagedNpmRuntimeComplete, shouldPreferPackagedNpmRuntime };
|
|
48
59
|
//# sourceMappingURL=npm-runtime-bundle.service.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"npm-runtime-bundle.service.d.ts","names":[],"sources":["../../../src/services/runtime/npm-runtime-bundle.service.ts"],"mappings":";;;;;;KAQY,wBAAA;EACV,eAAA;EACA,QAAA,EAAU,wBAAA;EACV,iBAAA;AAAA;AAAA,KAGG,8BAAA;EACH,MAAA,EAAQ,2BAAA;EACR,UAAA,EAAY,0BAAA;EACZ,cAAA,GAAiB,8BAAA;EACjB,QAAA,GAAW,MAAA,CAAO,QAAA;EAClB,IAAA;EACA,eAAA;EACA,GAAA;AAAA;AAAA,cAWW,uBAAA;EAAA,iBAOkB,OAAA;EAAA,iBANZ,cAAA;EAAA,iBACA,QAAA;EAAA,iBACA,IAAA;EAAA,iBACA,eAAA;EAAA,iBACA,GAAA;cAEY,OAAA,EAAS,8BAAA;EAQtC,oBAAA,QAA2B,wBAAA;EAQ3B,cAAA,GAAkB,OAAA,aAAkB,wBAAA;EASpC,oBAAA,GAA8B,eAAA,aAA0B,OAAA,CAAQ,wBAAA;
|
|
1
|
+
{"version":3,"file":"npm-runtime-bundle.service.d.ts","names":[],"sources":["../../../src/services/runtime/npm-runtime-bundle.service.ts"],"mappings":";;;;;;KAQY,wBAAA;EACV,eAAA;EACA,QAAA,EAAU,wBAAA;EACV,iBAAA;AAAA;AAAA,KAGG,8BAAA;EACH,MAAA,EAAQ,2BAAA;EACR,UAAA,EAAY,0BAAA;EACZ,cAAA,GAAiB,8BAAA;EACjB,QAAA,GAAW,MAAA,CAAO,QAAA;EAClB,IAAA;EACA,eAAA;EACA,GAAA;AAAA;AAAA,cAWW,uBAAA;EAAA,iBAOkB,OAAA;EAAA,iBANZ,cAAA;EAAA,iBACA,QAAA;EAAA,iBACA,IAAA;EAAA,iBACA,eAAA;EAAA,iBACA,GAAA;cAEY,OAAA,EAAS,8BAAA;EAQtC,oBAAA,QAA2B,wBAAA;EAQ3B,cAAA,GAAkB,OAAA,aAAkB,wBAAA;EASpC,oBAAA,GAA8B,eAAA,aAA0B,OAAA,CAAQ,wBAAA;EAuBhE,eAAA,GAAmB,OAAA;EAkBnB,sBAAA,QAAmC,OAAA;EAAA,QAyB3B,qBAAA;EAAA,QAKA,oBAAA;EAAA,QASA,qBAAA;EAAA,QAUA,sBAAA;EAAA,QAWA,mBAAA;EAAA,QAsBA,sBAAA;EAAA,QAQA,YAAA;AAAA;AAAA,iBAuBM,yBAAA,CAA0B,IAAA,UAAc,KAAA;AAAA,iBAkBxC,8BAAA,CAA+B,MAAA;EAC7C,eAAA;EACA,oBAAA;EACA,uBAAA;AAAA;AAAA,iBAUc,4BAAA,CAA6B,MAAA;EAC3C,UAAA;EACA,QAAA,GAAW,MAAA,CAAO,QAAA;AAAA;AAAA,iBAmBJ,0BAAA,CAA2B,MAAA;EACzC,eAAA;EACA,QAAA,GAAW,MAAA,CAAO,QAAA;EAClB,IAAA;AAAA"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { NpmRuntimeBundleManifestReader } from "./npm-runtime-bundle-manifest.service.js";
|
|
2
|
-
import { existsSync } from "node:fs";
|
|
2
|
+
import { accessSync, constants, existsSync, statSync } from "node:fs";
|
|
3
3
|
import { join, resolve } from "node:path";
|
|
4
4
|
import { cp, readdir, rename, rm } from "node:fs/promises";
|
|
5
5
|
//#region src/services/runtime/npm-runtime-bundle.service.ts
|
|
@@ -36,28 +36,21 @@ var NpmRuntimeBundleService = class {
|
|
|
36
36
|
installFromDirectory = async (sourceDirectory) => {
|
|
37
37
|
this.options.layout.ensureLauncherDirs();
|
|
38
38
|
const sourceBundle = this.verifyBundle(sourceDirectory);
|
|
39
|
+
this.assertBundleComplete(sourceBundle);
|
|
39
40
|
const targetDirectory = this.options.layout.getVersionDir(sourceBundle.manifest.bundleVersion);
|
|
40
|
-
|
|
41
|
+
const reusableBundle = this.resolveReusableBundle(targetDirectory);
|
|
42
|
+
if (reusableBundle) return reusableBundle;
|
|
43
|
+
const displacedDirectory = await this.displaceExistingBundle(targetDirectory, sourceBundle.manifest.bundleVersion);
|
|
41
44
|
try {
|
|
42
|
-
await
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
if (!shouldRetryInstallWithCopy(error)) throw error;
|
|
46
|
-
}
|
|
47
|
-
const stagingDirectory = join(this.options.layout.getStagingDir(), `${sourceBundle.manifest.bundleVersion}-${this.now()}`);
|
|
48
|
-
await rm(stagingDirectory, {
|
|
49
|
-
recursive: true,
|
|
50
|
-
force: true
|
|
51
|
-
});
|
|
52
|
-
try {
|
|
53
|
-
await cp(sourceDirectory, stagingDirectory, { recursive: true });
|
|
54
|
-
await rename(stagingDirectory, targetDirectory);
|
|
55
|
-
return this.verifyBundle(targetDirectory);
|
|
56
|
-
} catch (error) {
|
|
57
|
-
await rm(stagingDirectory, {
|
|
45
|
+
await this.moveBundleIntoPlace(sourceDirectory, targetDirectory, sourceBundle.manifest.bundleVersion);
|
|
46
|
+
const installedBundle = this.verifyBundle(targetDirectory);
|
|
47
|
+
if (displacedDirectory) await rm(displacedDirectory, {
|
|
58
48
|
recursive: true,
|
|
59
49
|
force: true
|
|
60
50
|
});
|
|
51
|
+
return installedBundle;
|
|
52
|
+
} catch (error) {
|
|
53
|
+
await this.restoreDisplacedBundle(displacedDirectory, targetDirectory);
|
|
61
54
|
throw error;
|
|
62
55
|
}
|
|
63
56
|
};
|
|
@@ -105,6 +98,60 @@ var NpmRuntimeBundleService = class {
|
|
|
105
98
|
force: true
|
|
106
99
|
})));
|
|
107
100
|
};
|
|
101
|
+
assertBundleComplete = (bundle) => {
|
|
102
|
+
if (isNpmRuntimeBundleComplete({
|
|
103
|
+
bundleDirectory: bundle.bundleDirectory,
|
|
104
|
+
platform: this.platform,
|
|
105
|
+
arch: this.arch
|
|
106
|
+
})) return;
|
|
107
|
+
throw new Error(`runtime bundle runner missing or not executable: ${bundle.manifest.bundleVersion}`);
|
|
108
|
+
};
|
|
109
|
+
resolveReusableBundle = (targetDirectory) => {
|
|
110
|
+
if (!existsSync(targetDirectory)) return null;
|
|
111
|
+
const bundle = this.verifyBundle(targetDirectory);
|
|
112
|
+
return isNpmRuntimeBundleComplete({
|
|
113
|
+
bundleDirectory: bundle.bundleDirectory,
|
|
114
|
+
platform: this.platform,
|
|
115
|
+
arch: this.arch
|
|
116
|
+
}) ? bundle : null;
|
|
117
|
+
};
|
|
118
|
+
displaceExistingBundle = async (targetDirectory, version) => {
|
|
119
|
+
if (!existsSync(targetDirectory)) return null;
|
|
120
|
+
const displacedDirectory = join(this.options.layout.getStagingDir(), `displaced-${version}-${this.now()}`);
|
|
121
|
+
await rm(displacedDirectory, {
|
|
122
|
+
recursive: true,
|
|
123
|
+
force: true
|
|
124
|
+
});
|
|
125
|
+
await rename(targetDirectory, displacedDirectory);
|
|
126
|
+
return displacedDirectory;
|
|
127
|
+
};
|
|
128
|
+
moveBundleIntoPlace = async (sourceDirectory, targetDirectory, version) => {
|
|
129
|
+
try {
|
|
130
|
+
await rename(sourceDirectory, targetDirectory);
|
|
131
|
+
return;
|
|
132
|
+
} catch (error) {
|
|
133
|
+
if (!shouldRetryInstallWithCopy(error)) throw error;
|
|
134
|
+
}
|
|
135
|
+
const stagingDirectory = join(this.options.layout.getStagingDir(), `${version}-${this.now()}`);
|
|
136
|
+
await rm(stagingDirectory, {
|
|
137
|
+
recursive: true,
|
|
138
|
+
force: true
|
|
139
|
+
});
|
|
140
|
+
try {
|
|
141
|
+
await cp(sourceDirectory, stagingDirectory, { recursive: true });
|
|
142
|
+
await rename(stagingDirectory, targetDirectory);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
await rm(stagingDirectory, {
|
|
145
|
+
recursive: true,
|
|
146
|
+
force: true
|
|
147
|
+
});
|
|
148
|
+
throw error;
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
restoreDisplacedBundle = async (displacedDirectory, targetDirectory) => {
|
|
152
|
+
if (!displacedDirectory || !existsSync(displacedDirectory) || existsSync(targetDirectory)) return;
|
|
153
|
+
await rename(displacedDirectory, targetDirectory);
|
|
154
|
+
};
|
|
108
155
|
verifyBundle = (bundleDirectory) => {
|
|
109
156
|
const manifest = this.manifestReader.readFile(resolve(bundleDirectory, "manifest.json"));
|
|
110
157
|
if (manifest.platform !== this.platform) throw new Error(`runtime bundle platform mismatch: expected ${this.platform} but got ${manifest.platform}`);
|
|
@@ -132,21 +179,35 @@ function compareNpmRuntimeVersions(left, right) {
|
|
|
132
179
|
if (!leftPrerelease || !rightPrerelease) return Number(!leftPrerelease) - Number(!rightPrerelease);
|
|
133
180
|
return leftPrerelease.localeCompare(rightPrerelease, void 0, { numeric: true });
|
|
134
181
|
}
|
|
135
|
-
function
|
|
182
|
+
function shouldPreferPackagedNpmRuntime(params) {
|
|
136
183
|
const launcherVersion = params.launcherVersion?.trim() || null;
|
|
137
184
|
const currentBundleVersion = params.currentBundleVersion?.trim() || null;
|
|
138
|
-
if (!launcherVersion) return
|
|
139
|
-
|
|
140
|
-
return compareNpmRuntimeVersions(launcherVersion, currentBundleVersion) > 0 ? launcherVersion : currentBundleVersion;
|
|
185
|
+
if (!params.packagedRuntimeComplete || !launcherVersion) return false;
|
|
186
|
+
return !currentBundleVersion || compareNpmRuntimeVersions(launcherVersion, currentBundleVersion) > 0;
|
|
141
187
|
}
|
|
142
|
-
function
|
|
143
|
-
const
|
|
144
|
-
|
|
188
|
+
function isPackagedNpmRuntimeComplete(params) {
|
|
189
|
+
const runnerPath = params.runnerPath?.trim();
|
|
190
|
+
if (!runnerPath || !existsSync(runnerPath)) return false;
|
|
191
|
+
try {
|
|
192
|
+
if (!statSync(runnerPath).isFile()) return false;
|
|
193
|
+
if ((params.platform ?? process.platform) !== "win32") accessSync(runnerPath, constants.X_OK);
|
|
194
|
+
return true;
|
|
195
|
+
} catch {
|
|
196
|
+
return false;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
function isNpmRuntimeBundleComplete(params) {
|
|
200
|
+
const platform = params.platform ?? process.platform;
|
|
201
|
+
const arch = params.arch ?? process.arch;
|
|
202
|
+
return isPackagedNpmRuntimeComplete({
|
|
203
|
+
platform,
|
|
204
|
+
runnerPath: resolve(params.bundleDirectory, "runtime", "resources", "native", `${platform}-${arch}`, platform === "win32" ? "nextclaw-wasmtime-runner.exe" : "nextclaw-wasmtime-runner")
|
|
205
|
+
});
|
|
145
206
|
}
|
|
146
207
|
function parseVersionParts(version) {
|
|
147
208
|
return version.split(".").map((part) => Number(part)).map((part) => Number.isFinite(part) ? part : 0);
|
|
148
209
|
}
|
|
149
210
|
//#endregion
|
|
150
|
-
export { NpmRuntimeBundleService, compareNpmRuntimeVersions,
|
|
211
|
+
export { NpmRuntimeBundleService, compareNpmRuntimeVersions, isNpmRuntimeBundleComplete, isPackagedNpmRuntimeComplete, shouldPreferPackagedNpmRuntime };
|
|
151
212
|
|
|
152
213
|
//# sourceMappingURL=npm-runtime-bundle.service.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"npm-runtime-bundle.service.js","names":[],"sources":["../../../src/services/runtime/npm-runtime-bundle.service.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { cp, readdir, rename, rm } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { NpmRuntimeBundleManifestReader } from \"@nextclaw-service/services/runtime/npm-runtime-bundle-manifest.service.js\";\nimport type { NpmRuntimeBundleLayoutStore } from \"@nextclaw-service/stores/npm-runtime-bundle-layout.store.js\";\nimport type { NpmRuntimeBundleManifest } from \"@nextclaw-service/types/npm-runtime-bundle.types.js\";\nimport type { NpmRuntimeUpdateStateStore } from \"@nextclaw-service/stores/npm-runtime-update-state.store.js\";\n\nexport type ResolvedNpmRuntimeBundle = {\n bundleDirectory: string;\n manifest: NpmRuntimeBundleManifest;\n runtimeScriptPath: string;\n};\n\ntype NpmRuntimeBundleServiceOptions = {\n layout: NpmRuntimeBundleLayoutStore;\n stateStore: NpmRuntimeUpdateStateStore;\n manifestReader?: NpmRuntimeBundleManifestReader;\n platform?: NodeJS.Platform;\n arch?: string;\n launcherVersion?: string;\n now?: () => number;\n};\n\nfunction shouldRetryInstallWithCopy(error: unknown): boolean {\n if (!error || typeof error !== \"object\") {\n return false;\n }\n const code = \"code\" in error ? String(error.code) : \"\";\n return code === \"EXDEV\" || code === \"EPERM\";\n}\n\nexport class NpmRuntimeBundleService {\n private readonly manifestReader: NpmRuntimeBundleManifestReader;\n private readonly platform: NodeJS.Platform;\n private readonly arch: string;\n private readonly launcherVersion: string | null;\n private readonly now: () => number;\n\n constructor(private readonly options: NpmRuntimeBundleServiceOptions) {\n this.manifestReader = options.manifestReader ?? new NpmRuntimeBundleManifestReader();\n this.platform = options.platform ?? process.platform;\n this.arch = options.arch ?? process.arch;\n this.launcherVersion = options.launcherVersion?.trim() || null;\n this.now = options.now ?? Date.now;\n }\n\n resolveCurrentBundle = (): ResolvedNpmRuntimeBundle | null => {\n const pointer = this.options.layout.readCurrentPointer();\n if (!pointer) {\n return null;\n }\n return this.resolveVersion(pointer.version);\n };\n\n resolveVersion = (version: string): ResolvedNpmRuntimeBundle => {\n const bundleDirectory = this.options.layout.getVersionDir(version);\n const bundle = this.verifyBundle(bundleDirectory);\n if (bundle.manifest.bundleVersion !== version) {\n throw new Error(`runtime bundle version mismatch: pointer expects ${version} but manifest is ${bundle.manifest.bundleVersion}`);\n }\n return bundle;\n };\n\n installFromDirectory = async (sourceDirectory: string): Promise<ResolvedNpmRuntimeBundle> => {\n this.options.layout.ensureLauncherDirs();\n const sourceBundle = this.verifyBundle(sourceDirectory);\n const targetDirectory = this.options.layout.getVersionDir(sourceBundle.manifest.bundleVersion);\n if (existsSync(targetDirectory)) {\n return this.verifyBundle(targetDirectory);\n }\n\n try {\n await rename(sourceDirectory, targetDirectory);\n return this.verifyBundle(targetDirectory);\n } catch (error) {\n if (!shouldRetryInstallWithCopy(error)) {\n throw error;\n }\n }\n\n const stagingDirectory = join(this.options.layout.getStagingDir(), `${sourceBundle.manifest.bundleVersion}-${this.now()}`);\n await rm(stagingDirectory, { recursive: true, force: true });\n try {\n await cp(sourceDirectory, stagingDirectory, { recursive: true });\n await rename(stagingDirectory, targetDirectory);\n return this.verifyBundle(targetDirectory);\n } catch (error) {\n await rm(stagingDirectory, { recursive: true, force: true });\n throw error;\n }\n };\n\n activateVersion = (version: string): void => {\n this.resolveVersion(version);\n const currentPointer = this.options.layout.readCurrentPointer();\n if (currentPointer) {\n this.options.layout.writePreviousPointer(currentPointer);\n }\n this.options.layout.writeCurrentPointer({ version });\n this.options.stateStore.update((state) => ({\n ...state,\n currentVersion: version,\n previousVersion: currentPointer?.version ?? state.previousVersion,\n candidateVersion: version,\n candidateLaunchCount: 0,\n downloadedVersion: null,\n downloadedReleaseNotesUrl: null\n }));\n };\n\n pruneRetainedArtifacts = async (): Promise<void> => {\n this.options.layout.ensureLauncherDirs();\n const state = this.options.stateStore.read();\n const retained = new Set(\n [\n state.currentVersion,\n state.previousVersion,\n state.candidateVersion,\n state.lastKnownGoodVersion,\n state.downloadedVersion,\n this.options.layout.readCurrentPointer()?.version,\n this.options.layout.readPreviousPointer()?.version\n ].filter((version): version is string => Boolean(version?.trim()))\n );\n\n const entries = await readdir(this.options.layout.getVersionsDir(), { withFileTypes: true });\n for (const entry of entries.sort((left, right) => compareNpmRuntimeVersions(left.name, right.name))) {\n if (!entry.isDirectory() || retained.has(entry.name)) {\n continue;\n }\n await rm(join(this.options.layout.getVersionsDir(), entry.name), { recursive: true, force: true });\n }\n await this.clearStagingDirectory();\n };\n\n private clearStagingDirectory = async (): Promise<void> => {\n const entries = await readdir(this.options.layout.getStagingDir(), { withFileTypes: true });\n await Promise.all(entries.map(async (entry) => await rm(join(this.options.layout.getStagingDir(), entry.name), { recursive: true, force: true })));\n };\n\n private verifyBundle = (bundleDirectory: string): ResolvedNpmRuntimeBundle => {\n const manifest = this.manifestReader.readFile(resolve(bundleDirectory, \"manifest.json\"));\n if (manifest.platform !== this.platform) {\n throw new Error(`runtime bundle platform mismatch: expected ${this.platform} but got ${manifest.platform}`);\n }\n if (manifest.arch !== this.arch) {\n throw new Error(`runtime bundle arch mismatch: expected ${this.arch} but got ${manifest.arch}`);\n }\n if (this.launcherVersion && compareNpmRuntimeVersions(this.launcherVersion, manifest.launcherCompatibility.minVersion) < 0) {\n throw new Error(`runtime bundle requires launcher >= ${manifest.launcherCompatibility.minVersion} but current launcher is ${this.launcherVersion}`);\n }\n const runtimeScriptPath = resolve(bundleDirectory, manifest.entrypoints.runtimeScript);\n if (!existsSync(runtimeScriptPath)) {\n throw new Error(`runtime bundle script missing: ${runtimeScriptPath}`);\n }\n return {\n bundleDirectory,\n manifest,\n runtimeScriptPath\n };\n };\n}\n\nexport function compareNpmRuntimeVersions(left: string, right: string): number {\n const [leftCore = \"\", leftPrerelease = \"\"] = left.split(\"+\")[0]?.split(\"-\", 2) ?? [];\n const [rightCore = \"\", rightPrerelease = \"\"] = right.split(\"+\")[0]?.split(\"-\", 2) ?? [];\n const leftParts = parseVersionParts(leftCore);\n const rightParts = parseVersionParts(rightCore);\n const length = Math.max(leftParts.length, rightParts.length);\n for (let index = 0; index < length; index += 1) {\n const compared = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);\n if (compared !== 0) {\n return compared;\n }\n }\n if (!leftPrerelease || !rightPrerelease) {\n return Number(!leftPrerelease) - Number(!rightPrerelease);\n }\n return leftPrerelease.localeCompare(rightPrerelease, undefined, { numeric: true });\n}\n\nexport function resolveEffectiveNpmRuntimeVersion(params: {\n launcherVersion: string | null;\n currentBundleVersion: string | null;\n}): string | null {\n const launcherVersion = params.launcherVersion?.trim() || null;\n const currentBundleVersion = params.currentBundleVersion?.trim() || null;\n if (!launcherVersion) {\n return currentBundleVersion;\n }\n if (!currentBundleVersion) {\n return launcherVersion;\n }\n return compareNpmRuntimeVersions(launcherVersion, currentBundleVersion) > 0\n ? launcherVersion\n : currentBundleVersion;\n}\n\nexport function shouldPreferPackagedNpmRuntime(params: {\n launcherVersion: string | null;\n currentBundleVersion: string | null;\n}): boolean {\n const launcherVersion = params.launcherVersion?.trim() || null;\n return Boolean(launcherVersion) && resolveEffectiveNpmRuntimeVersion(params) === launcherVersion;\n}\n\nfunction parseVersionParts(version: string): number[] {\n return version\n .split(\".\")\n .map((part) => Number(part))\n .map((part) => (Number.isFinite(part) ? part : 0));\n}\n"],"mappings":";;;;;AAwBA,SAAS,2BAA2B,OAAyB;AAC3D,KAAI,CAAC,SAAS,OAAO,UAAU,SAC7B,QAAO;CAET,MAAM,OAAO,UAAU,QAAQ,OAAO,MAAM,KAAK,GAAG;AACpD,QAAO,SAAS,WAAW,SAAS;;AAGtC,IAAa,0BAAb,MAAqC;CACnC;CACA;CACA;CACA;CACA;CAEA,YAAY,SAA0D;AAAzC,OAAA,UAAA;AAC3B,OAAK,iBAAiB,QAAQ,kBAAkB,IAAI,gCAAgC;AACpF,OAAK,WAAW,QAAQ,YAAY,QAAQ;AAC5C,OAAK,OAAO,QAAQ,QAAQ,QAAQ;AACpC,OAAK,kBAAkB,QAAQ,iBAAiB,MAAM,IAAI;AAC1D,OAAK,MAAM,QAAQ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AAgB;AAE3D,QAAO,eAAe,cAAc,iBAAiB,KAAA,GAAW,EAAE,SAAS,MAAM,CAAC;;AAGpF,SAAgB,kCAAkC,QAGhC;CAChB,MAAM,kBAAkB,OAAO,iBAAiB,MAAM,IAAI;CAC1D,MAAM,uBAAuB,OAAO,sBAAsB,MAAM,IAAI;AACpE,KAAI,CAAC,gBACH,QAAO;AAET,KAAI,CAAC,qBACH,QAAO;AAET,QAAO,0BAA0B,iBAAiB,qBAAqB,GAAG,IACtE,kBACA;;AAGN,SAAgB,+BAA+B,QAGnC;CACV,MAAM,kBAAkB,OAAO,iBAAiB,MAAM,IAAI;AAC1D,QAAO,QAAQ,gBAAgB,IAAI,kCAAkC,OAAO,KAAK;;AAGnF,SAAS,kBAAkB,SAA2B;AACpD,QAAO,QACJ,MAAM,IAAI,CACV,KAAK,SAAS,OAAO,KAAK,CAAC,CAC3B,KAAK,SAAU,OAAO,SAAS,KAAK,GAAG,OAAO,EAAG"}
|
|
1
|
+
{"version":3,"file":"npm-runtime-bundle.service.js","names":[],"sources":["../../../src/services/runtime/npm-runtime-bundle.service.ts"],"sourcesContent":["import { accessSync, constants, existsSync, statSync } from \"node:fs\";\nimport { cp, readdir, rename, rm } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { NpmRuntimeBundleManifestReader } from \"@nextclaw-service/services/runtime/npm-runtime-bundle-manifest.service.js\";\nimport type { NpmRuntimeBundleLayoutStore } from \"@nextclaw-service/stores/npm-runtime-bundle-layout.store.js\";\nimport type { NpmRuntimeBundleManifest } from \"@nextclaw-service/types/npm-runtime-bundle.types.js\";\nimport type { NpmRuntimeUpdateStateStore } from \"@nextclaw-service/stores/npm-runtime-update-state.store.js\";\n\nexport type ResolvedNpmRuntimeBundle = {\n bundleDirectory: string;\n manifest: NpmRuntimeBundleManifest;\n runtimeScriptPath: string;\n};\n\ntype NpmRuntimeBundleServiceOptions = {\n layout: NpmRuntimeBundleLayoutStore;\n stateStore: NpmRuntimeUpdateStateStore;\n manifestReader?: NpmRuntimeBundleManifestReader;\n platform?: NodeJS.Platform;\n arch?: string;\n launcherVersion?: string;\n now?: () => number;\n};\n\nfunction shouldRetryInstallWithCopy(error: unknown): boolean {\n if (!error || typeof error !== \"object\") {\n return false;\n }\n const code = \"code\" in error ? String(error.code) : \"\";\n return code === \"EXDEV\" || code === \"EPERM\";\n}\n\nexport class NpmRuntimeBundleService {\n private readonly manifestReader: NpmRuntimeBundleManifestReader;\n private readonly platform: NodeJS.Platform;\n private readonly arch: string;\n private readonly launcherVersion: string | null;\n private readonly now: () => number;\n\n constructor(private readonly options: NpmRuntimeBundleServiceOptions) {\n this.manifestReader = options.manifestReader ?? new NpmRuntimeBundleManifestReader();\n this.platform = options.platform ?? process.platform;\n this.arch = options.arch ?? process.arch;\n this.launcherVersion = options.launcherVersion?.trim() || null;\n this.now = options.now ?? Date.now;\n }\n\n resolveCurrentBundle = (): ResolvedNpmRuntimeBundle | null => {\n const pointer = this.options.layout.readCurrentPointer();\n if (!pointer) {\n return null;\n }\n return this.resolveVersion(pointer.version);\n };\n\n resolveVersion = (version: string): ResolvedNpmRuntimeBundle => {\n const bundleDirectory = this.options.layout.getVersionDir(version);\n const bundle = this.verifyBundle(bundleDirectory);\n if (bundle.manifest.bundleVersion !== version) {\n throw new Error(`runtime bundle version mismatch: pointer expects ${version} but manifest is ${bundle.manifest.bundleVersion}`);\n }\n return bundle;\n };\n\n installFromDirectory = async (sourceDirectory: string): Promise<ResolvedNpmRuntimeBundle> => {\n this.options.layout.ensureLauncherDirs();\n const sourceBundle = this.verifyBundle(sourceDirectory);\n this.assertBundleComplete(sourceBundle);\n const targetDirectory = this.options.layout.getVersionDir(sourceBundle.manifest.bundleVersion);\n const reusableBundle = this.resolveReusableBundle(targetDirectory);\n if (reusableBundle) return reusableBundle;\n const displacedDirectory = await this.displaceExistingBundle(\n targetDirectory,\n sourceBundle.manifest.bundleVersion,\n );\n\n try {\n await this.moveBundleIntoPlace(sourceDirectory, targetDirectory, sourceBundle.manifest.bundleVersion);\n const installedBundle = this.verifyBundle(targetDirectory);\n if (displacedDirectory) await rm(displacedDirectory, { recursive: true, force: true });\n return installedBundle;\n } catch (error) {\n await this.restoreDisplacedBundle(displacedDirectory, targetDirectory);\n throw error;\n }\n };\n\n activateVersion = (version: string): void => {\n this.resolveVersion(version);\n const currentPointer = this.options.layout.readCurrentPointer();\n if (currentPointer) {\n this.options.layout.writePreviousPointer(currentPointer);\n }\n this.options.layout.writeCurrentPointer({ version });\n this.options.stateStore.update((state) => ({\n ...state,\n currentVersion: version,\n previousVersion: currentPointer?.version ?? state.previousVersion,\n candidateVersion: version,\n candidateLaunchCount: 0,\n downloadedVersion: null,\n downloadedReleaseNotesUrl: null\n }));\n };\n\n pruneRetainedArtifacts = async (): Promise<void> => {\n this.options.layout.ensureLauncherDirs();\n const state = this.options.stateStore.read();\n const retained = new Set(\n [\n state.currentVersion,\n state.previousVersion,\n state.candidateVersion,\n state.lastKnownGoodVersion,\n state.downloadedVersion,\n this.options.layout.readCurrentPointer()?.version,\n this.options.layout.readPreviousPointer()?.version\n ].filter((version): version is string => Boolean(version?.trim()))\n );\n\n const entries = await readdir(this.options.layout.getVersionsDir(), { withFileTypes: true });\n for (const entry of entries.sort((left, right) => compareNpmRuntimeVersions(left.name, right.name))) {\n if (!entry.isDirectory() || retained.has(entry.name)) {\n continue;\n }\n await rm(join(this.options.layout.getVersionsDir(), entry.name), { recursive: true, force: true });\n }\n await this.clearStagingDirectory();\n };\n\n private clearStagingDirectory = async (): Promise<void> => {\n const entries = await readdir(this.options.layout.getStagingDir(), { withFileTypes: true });\n await Promise.all(entries.map(async (entry) => await rm(join(this.options.layout.getStagingDir(), entry.name), { recursive: true, force: true })));\n };\n\n private assertBundleComplete = (bundle: ResolvedNpmRuntimeBundle): void => {\n if (isNpmRuntimeBundleComplete({\n bundleDirectory: bundle.bundleDirectory,\n platform: this.platform,\n arch: this.arch,\n })) return;\n throw new Error(`runtime bundle runner missing or not executable: ${bundle.manifest.bundleVersion}`);\n };\n\n private resolveReusableBundle = (targetDirectory: string): ResolvedNpmRuntimeBundle | null => {\n if (!existsSync(targetDirectory)) return null;\n const bundle = this.verifyBundle(targetDirectory);\n return isNpmRuntimeBundleComplete({\n bundleDirectory: bundle.bundleDirectory,\n platform: this.platform,\n arch: this.arch,\n }) ? bundle : null;\n };\n\n private displaceExistingBundle = async (\n targetDirectory: string,\n version: string,\n ): Promise<string | null> => {\n if (!existsSync(targetDirectory)) return null;\n const displacedDirectory = join(this.options.layout.getStagingDir(), `displaced-${version}-${this.now()}`);\n await rm(displacedDirectory, { recursive: true, force: true });\n await rename(targetDirectory, displacedDirectory);\n return displacedDirectory;\n };\n\n private moveBundleIntoPlace = async (\n sourceDirectory: string,\n targetDirectory: string,\n version: string,\n ): Promise<void> => {\n try {\n await rename(sourceDirectory, targetDirectory);\n return;\n } catch (error) {\n if (!shouldRetryInstallWithCopy(error)) throw error;\n }\n const stagingDirectory = join(this.options.layout.getStagingDir(), `${version}-${this.now()}`);\n await rm(stagingDirectory, { recursive: true, force: true });\n try {\n await cp(sourceDirectory, stagingDirectory, { recursive: true });\n await rename(stagingDirectory, targetDirectory);\n } catch (error) {\n await rm(stagingDirectory, { recursive: true, force: true });\n throw error;\n }\n };\n\n private restoreDisplacedBundle = async (\n displacedDirectory: string | null,\n targetDirectory: string,\n ): Promise<void> => {\n if (!displacedDirectory || !existsSync(displacedDirectory) || existsSync(targetDirectory)) return;\n await rename(displacedDirectory, targetDirectory);\n };\n\n private verifyBundle = (bundleDirectory: string): ResolvedNpmRuntimeBundle => {\n const manifest = this.manifestReader.readFile(resolve(bundleDirectory, \"manifest.json\"));\n if (manifest.platform !== this.platform) {\n throw new Error(`runtime bundle platform mismatch: expected ${this.platform} but got ${manifest.platform}`);\n }\n if (manifest.arch !== this.arch) {\n throw new Error(`runtime bundle arch mismatch: expected ${this.arch} but got ${manifest.arch}`);\n }\n if (this.launcherVersion && compareNpmRuntimeVersions(this.launcherVersion, manifest.launcherCompatibility.minVersion) < 0) {\n throw new Error(`runtime bundle requires launcher >= ${manifest.launcherCompatibility.minVersion} but current launcher is ${this.launcherVersion}`);\n }\n const runtimeScriptPath = resolve(bundleDirectory, manifest.entrypoints.runtimeScript);\n if (!existsSync(runtimeScriptPath)) {\n throw new Error(`runtime bundle script missing: ${runtimeScriptPath}`);\n }\n return {\n bundleDirectory,\n manifest,\n runtimeScriptPath\n };\n };\n}\n\nexport function compareNpmRuntimeVersions(left: string, right: string): number {\n const [leftCore = \"\", leftPrerelease = \"\"] = left.split(\"+\")[0]?.split(\"-\", 2) ?? [];\n const [rightCore = \"\", rightPrerelease = \"\"] = right.split(\"+\")[0]?.split(\"-\", 2) ?? [];\n const leftParts = parseVersionParts(leftCore);\n const rightParts = parseVersionParts(rightCore);\n const length = Math.max(leftParts.length, rightParts.length);\n for (let index = 0; index < length; index += 1) {\n const compared = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);\n if (compared !== 0) {\n return compared;\n }\n }\n if (!leftPrerelease || !rightPrerelease) {\n return Number(!leftPrerelease) - Number(!rightPrerelease);\n }\n return leftPrerelease.localeCompare(rightPrerelease, undefined, { numeric: true });\n}\n\nexport function shouldPreferPackagedNpmRuntime(params: {\n launcherVersion: string | null;\n currentBundleVersion: string | null;\n packagedRuntimeComplete: boolean;\n}): boolean {\n const launcherVersion = params.launcherVersion?.trim() || null;\n const currentBundleVersion = params.currentBundleVersion?.trim() || null;\n if (!params.packagedRuntimeComplete || !launcherVersion) {\n return false;\n }\n return !currentBundleVersion || compareNpmRuntimeVersions(launcherVersion, currentBundleVersion) > 0;\n}\n\nexport function isPackagedNpmRuntimeComplete(params: {\n runnerPath: string | null | undefined;\n platform?: NodeJS.Platform;\n}): boolean {\n const runnerPath = params.runnerPath?.trim();\n if (!runnerPath || !existsSync(runnerPath)) {\n return false;\n }\n try {\n if (!statSync(runnerPath).isFile()) {\n return false;\n }\n if ((params.platform ?? process.platform) !== \"win32\") {\n accessSync(runnerPath, constants.X_OK);\n }\n return true;\n } catch {\n return false;\n }\n}\n\nexport function isNpmRuntimeBundleComplete(params: {\n bundleDirectory: string;\n platform?: NodeJS.Platform;\n arch?: string;\n}): boolean {\n const platform = params.platform ?? process.platform;\n const arch = params.arch ?? process.arch;\n return isPackagedNpmRuntimeComplete({\n platform,\n runnerPath: resolve(\n params.bundleDirectory,\n \"runtime\",\n \"resources\",\n \"native\",\n `${platform}-${arch}`,\n platform === \"win32\" ? \"nextclaw-wasmtime-runner.exe\" : \"nextclaw-wasmtime-runner\"\n )\n });\n}\n\nfunction parseVersionParts(version: string): number[] {\n return version\n .split(\".\")\n .map((part) => Number(part))\n .map((part) => (Number.isFinite(part) ? part : 0));\n}\n"],"mappings":";;;;;AAwBA,SAAS,2BAA2B,OAAyB;AAC3D,KAAI,CAAC,SAAS,OAAO,UAAU,SAC7B,QAAO;CAET,MAAM,OAAO,UAAU,QAAQ,OAAO,MAAM,KAAK,GAAG;AACpD,QAAO,SAAS,WAAW,SAAS;;AAGtC,IAAa,0BAAb,MAAqC;CACnC;CACA;CACA;CACA;CACA;CAEA,YAAY,SAA0D;AAAzC,OAAA,UAAA;AAC3B,OAAK,iBAAiB,QAAQ,kBAAkB,IAAI,gCAAgC;AACpF,OAAK,WAAW,QAAQ,YAAY,QAAQ;AAC5C,OAAK,OAAO,QAAQ,QAAQ,QAAQ;AACpC,OAAK,kBAAkB,QAAQ,iBAAiB,MAAM,IAAI;AAC1D,OAAK,MAAM,QAAQ,OAAO,KAAK;;CAGjC,6BAA8D;EAC5D,MAAM,UAAU,KAAK,QAAQ,OAAO,oBAAoB;AACxD,MAAI,CAAC,QACH,QAAO;AAET,SAAO,KAAK,eAAe,QAAQ,QAAQ;;CAG7C,kBAAkB,YAA8C;EAC9D,MAAM,kBAAkB,KAAK,QAAQ,OAAO,cAAc,QAAQ;EAClE,MAAM,SAAS,KAAK,aAAa,gBAAgB;AACjD,MAAI,OAAO,SAAS,kBAAkB,QACpC,OAAM,IAAI,MAAM,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AAc,CAAC,WAAW,WAAW,CACxC,QAAO;AAET,KAAI;AACF,MAAI,CAAC,SAAS,WAAW,CAAC,QAAQ,CAChC,QAAO;AAET,OAAK,OAAO,YAAY,QAAQ,cAAc,QAC5C,YAAW,YAAY,UAAU,KAAK;AAExC,SAAO;SACD;AACN,SAAO;;;AAIX,SAAgB,2BAA2B,QAI/B;CACV,MAAM,WAAW,OAAO,YAAY,QAAQ;CAC5C,MAAM,OAAO,OAAO,QAAQ,QAAQ;AACpC,QAAO,6BAA6B;EAClC;EACA,YAAY,QACV,OAAO,iBACP,WACA,aACA,UACA,GAAG,SAAS,GAAG,QACf,aAAa,UAAU,iCAAiC,2BACzD;EACF,CAAC;;AAGJ,SAAS,kBAAkB,SAA2B;AACpD,QAAO,QACJ,MAAM,IAAI,CACV,KAAK,SAAS,OAAO,KAAK,CAAC,CAC3B,KAAK,SAAU,OAAO,SAAS,KAAK,GAAG,OAAO,EAAG"}
|
|
@@ -77,7 +77,7 @@ var NpmRuntimeUpdateCommandService = class {
|
|
|
77
77
|
return;
|
|
78
78
|
}
|
|
79
79
|
if (snapshot.status === "restart-required") {
|
|
80
|
-
console.log(`Runtime update applied: ${snapshot.
|
|
80
|
+
console.log(`Runtime update applied: ${snapshot.targetVersion ?? "unknown"}`);
|
|
81
81
|
console.log("Restart the running NextClaw service or start a new CLI process to use it.");
|
|
82
82
|
return;
|
|
83
83
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"npm-runtime-update-command.service.js","names":[],"sources":["../../../src/services/runtime/npm-runtime-update-command.service.ts"],"sourcesContent":["import { NpmRuntimeBundleLayoutStore } from \"@nextclaw-service/stores/npm-runtime-bundle-layout.store.js\";\nimport { NpmRuntimeBundleService } from \"@nextclaw-service/services/runtime/npm-runtime-bundle.service.js\";\nimport { RuntimeUpdateManager } from \"@nextclaw-service/managers/runtime-update.manager.js\";\nimport { NpmRuntimeUpdateService } from \"@nextclaw-service/services/runtime/npm-runtime-update.service.js\";\nimport { NpmRuntimeUpdateSourceService } from \"@nextclaw-service/services/runtime/npm-runtime-update-source.service.js\";\nimport { NpmRuntimeUpdateStateStore } from \"@nextclaw-service/stores/npm-runtime-update-state.store.js\";\nimport { NextclawDistributionService } from \"@nextclaw-service/services/runtime/nextclaw-distribution.service.js\";\nimport type { UpdateCommandOptions } from \"@nextclaw-service/types/cli.types.js\";\nimport type { UpdateProgress, UpdateSnapshot } from \"@nextclaw/kernel\";\n\nexport class NpmRuntimeUpdateCommandService {\n constructor(private readonly env: NodeJS.ProcessEnv = process.env) {}\n\n run = async (opts: UpdateCommandOptions): Promise<UpdateSnapshot> => {\n const snapshot = await this.runManaged(opts);\n if (opts.json) {\n console.log(JSON.stringify(snapshot, null, 2));\n } else {\n this.printSnapshot(snapshot);\n }\n return snapshot;\n };\n\n runManaged = async (opts: UpdateCommandOptions): Promise<UpdateSnapshot> => {\n if (this.env.NEXTCLAW_DESKTOP_COMMAND_SURFACE === \"1\") {\n return this.createDesktopCommandSurfaceBlockedSnapshot(opts);\n }\n\n const downloadOnly = Boolean(opts.downloadOnly || opts.download);\n const distribution = NextclawDistributionService.get();\n const source = new NpmRuntimeUpdateSourceService({\n packagedPublicKeyPath: distribution.runtimeUpdatePublicKeyPath,\n });\n const launcherVersion = distribution.launcherVersion;\n const channel = source.resolveChannel(opts.channel, launcherVersion);\n const manifestUrl = source.resolveManifestUrl(channel, opts.manifestUrl);\n const layout = new NpmRuntimeBundleLayoutStore();\n const stateStore = new NpmRuntimeUpdateStateStore(layout.getStatePath(), {\n defaultChannel: channel\n });\n const bundleService = new NpmRuntimeBundleService({\n layout,\n stateStore,\n launcherVersion\n });\n const updateService = new NpmRuntimeUpdateService({\n layout,\n bundleService,\n launcherVersion,\n bundlePublicKey: source.resolveBundlePublicKey() ?? undefined\n });\n const manager = new RuntimeUpdateManager({\n layout,\n stateStore,\n bundleService,\n updateService,\n resolveManifestUrl: () => manifestUrl,\n launcherVersion,\n channel\n });\n\n return await manager.run({\n apply: Boolean(opts.apply),\n checkOnly: Boolean(opts.check),\n applyAfterDownload: !downloadOnly,\n onProgress: opts.json ? undefined : this.printProgress\n });\n };\n\n private printProgress = (progress: UpdateProgress): void => {\n const percent = progress.percent === null ? \"\" : ` ${progress.percent}%`;\n const total = progress.totalBytes === null ? \"\" : ` / ${progress.totalBytes} bytes`;\n process.stdout.write(`\\rDownloading${percent} (${progress.downloadedBytes} bytes${total})`);\n if (progress.percent === 100) {\n process.stdout.write(\"\\n\");\n }\n };\n\n private printSnapshot = (snapshot: UpdateSnapshot): void => {\n if (snapshot.status === \"blocked\") {\n console.error(`Update blocked: ${snapshot.errorMessage ?? snapshot.blockReason ?? \"unknown reason\"}`);\n if (snapshot.recoveryCommand) {\n console.error(`Recovery: ${snapshot.recoveryCommand}`);\n }\n return;\n }\n if (snapshot.status === \"failed\") {\n console.error(`Update failed: ${snapshot.errorMessage ?? \"unknown error\"}`);\n return;\n }\n if (snapshot.status === \"up-to-date\") {\n console.log(`NextClaw runtime is already up to date (${snapshot.currentVersion ?? snapshot.hostVersion ?? \"unknown\"}).`);\n return;\n }\n if (snapshot.status === \"downloaded\") {\n console.log(`Runtime update downloaded: ${snapshot.downloadedVersion ?? snapshot.availableVersion}`);\n console.log(\"Run `nextclaw update --apply` to switch to the downloaded runtime.\");\n return;\n }\n if (snapshot.status === \"restart-required\") {\n console.log(`Runtime update applied: ${snapshot.
|
|
1
|
+
{"version":3,"file":"npm-runtime-update-command.service.js","names":[],"sources":["../../../src/services/runtime/npm-runtime-update-command.service.ts"],"sourcesContent":["import { NpmRuntimeBundleLayoutStore } from \"@nextclaw-service/stores/npm-runtime-bundle-layout.store.js\";\nimport { NpmRuntimeBundleService } from \"@nextclaw-service/services/runtime/npm-runtime-bundle.service.js\";\nimport { RuntimeUpdateManager } from \"@nextclaw-service/managers/runtime-update.manager.js\";\nimport { NpmRuntimeUpdateService } from \"@nextclaw-service/services/runtime/npm-runtime-update.service.js\";\nimport { NpmRuntimeUpdateSourceService } from \"@nextclaw-service/services/runtime/npm-runtime-update-source.service.js\";\nimport { NpmRuntimeUpdateStateStore } from \"@nextclaw-service/stores/npm-runtime-update-state.store.js\";\nimport { NextclawDistributionService } from \"@nextclaw-service/services/runtime/nextclaw-distribution.service.js\";\nimport type { UpdateCommandOptions } from \"@nextclaw-service/types/cli.types.js\";\nimport type { UpdateProgress, UpdateSnapshot } from \"@nextclaw/kernel\";\n\nexport class NpmRuntimeUpdateCommandService {\n constructor(private readonly env: NodeJS.ProcessEnv = process.env) {}\n\n run = async (opts: UpdateCommandOptions): Promise<UpdateSnapshot> => {\n const snapshot = await this.runManaged(opts);\n if (opts.json) {\n console.log(JSON.stringify(snapshot, null, 2));\n } else {\n this.printSnapshot(snapshot);\n }\n return snapshot;\n };\n\n runManaged = async (opts: UpdateCommandOptions): Promise<UpdateSnapshot> => {\n if (this.env.NEXTCLAW_DESKTOP_COMMAND_SURFACE === \"1\") {\n return this.createDesktopCommandSurfaceBlockedSnapshot(opts);\n }\n\n const downloadOnly = Boolean(opts.downloadOnly || opts.download);\n const distribution = NextclawDistributionService.get();\n const source = new NpmRuntimeUpdateSourceService({\n packagedPublicKeyPath: distribution.runtimeUpdatePublicKeyPath,\n });\n const launcherVersion = distribution.launcherVersion;\n const channel = source.resolveChannel(opts.channel, launcherVersion);\n const manifestUrl = source.resolveManifestUrl(channel, opts.manifestUrl);\n const layout = new NpmRuntimeBundleLayoutStore();\n const stateStore = new NpmRuntimeUpdateStateStore(layout.getStatePath(), {\n defaultChannel: channel\n });\n const bundleService = new NpmRuntimeBundleService({\n layout,\n stateStore,\n launcherVersion\n });\n const updateService = new NpmRuntimeUpdateService({\n layout,\n bundleService,\n launcherVersion,\n bundlePublicKey: source.resolveBundlePublicKey() ?? undefined\n });\n const manager = new RuntimeUpdateManager({\n layout,\n stateStore,\n bundleService,\n updateService,\n resolveManifestUrl: () => manifestUrl,\n launcherVersion,\n channel\n });\n\n return await manager.run({\n apply: Boolean(opts.apply),\n checkOnly: Boolean(opts.check),\n applyAfterDownload: !downloadOnly,\n onProgress: opts.json ? undefined : this.printProgress\n });\n };\n\n private printProgress = (progress: UpdateProgress): void => {\n const percent = progress.percent === null ? \"\" : ` ${progress.percent}%`;\n const total = progress.totalBytes === null ? \"\" : ` / ${progress.totalBytes} bytes`;\n process.stdout.write(`\\rDownloading${percent} (${progress.downloadedBytes} bytes${total})`);\n if (progress.percent === 100) {\n process.stdout.write(\"\\n\");\n }\n };\n\n private printSnapshot = (snapshot: UpdateSnapshot): void => {\n if (snapshot.status === \"blocked\") {\n console.error(`Update blocked: ${snapshot.errorMessage ?? snapshot.blockReason ?? \"unknown reason\"}`);\n if (snapshot.recoveryCommand) {\n console.error(`Recovery: ${snapshot.recoveryCommand}`);\n }\n return;\n }\n if (snapshot.status === \"failed\") {\n console.error(`Update failed: ${snapshot.errorMessage ?? \"unknown error\"}`);\n return;\n }\n if (snapshot.status === \"up-to-date\") {\n console.log(`NextClaw runtime is already up to date (${snapshot.currentVersion ?? snapshot.hostVersion ?? \"unknown\"}).`);\n return;\n }\n if (snapshot.status === \"downloaded\") {\n console.log(`Runtime update downloaded: ${snapshot.downloadedVersion ?? snapshot.availableVersion}`);\n console.log(\"Run `nextclaw update --apply` to switch to the downloaded runtime.\");\n return;\n }\n if (snapshot.status === \"restart-required\") {\n console.log(`Runtime update applied: ${snapshot.targetVersion ?? \"unknown\"}`);\n console.log(\"Restart the running NextClaw service or start a new CLI process to use it.\");\n return;\n }\n if (snapshot.status === \"update-available\") {\n console.log(`Runtime update available: ${snapshot.currentVersion ?? \"none\"} -> ${snapshot.availableVersion}`);\n return;\n }\n console.log(`Update status: ${snapshot.status}`);\n };\n\n private createDesktopCommandSurfaceBlockedSnapshot = (opts: UpdateCommandOptions): UpdateSnapshot => {\n const distribution = NextclawDistributionService.get();\n return {\n status: \"blocked\",\n installationKind: \"desktop-bundle\",\n channel: opts.channel === \"beta\" ? \"beta\" : \"stable\",\n hostVersion: distribution.version,\n currentVersion: distribution.version,\n availableVersion: null,\n downloadedVersion: null,\n minimumHostVersion: null,\n releaseNotesUrl: null,\n lastCheckedAt: new Date().toISOString(),\n progress: null,\n canApplyInApp: false,\n requiresRestart: false,\n blockReason: \"unsupported-installation\",\n recoveryCommand: \"Use the desktop update settings or restart NextClaw Desktop to check for desktop updates.\",\n errorMessage: \"The desktop-installed nextclaw command uses the desktop update channel instead of the npm runtime updater.\"\n };\n };\n}\n"],"mappings":";;;;;;;;AAUA,IAAa,iCAAb,MAA4C;CAC1C,YAAY,MAA0C,QAAQ,KAAK;AAAtC,OAAA,MAAA;;CAE7B,MAAM,OAAO,SAAwD;EACnE,MAAM,WAAW,MAAM,KAAK,WAAW,KAAK;AAC5C,MAAI,KAAK,KACP,SAAQ,IAAI,KAAK,UAAU,UAAU,MAAM,EAAE,CAAC;MAE9C,MAAK,cAAc,SAAS;AAE9B,SAAO;;CAGT,aAAa,OAAO,SAAwD;AAC1E,MAAI,KAAK,IAAI,qCAAqC,IAChD,QAAO,KAAK,2CAA2C,KAAK;EAG9D,MAAM,eAAe,QAAQ,KAAK,gBAAgB,KAAK,SAAS;EAChE,MAAM,eAAe,4BAA4B,KAAK;EACtD,MAAM,SAAS,IAAI,8BAA8B,EAC/C,uBAAuB,aAAa,4BACrC,CAAC;EACF,MAAM,kBAAkB,aAAa;EACrC,MAAM,UAAU,OAAO,eAAe,KAAK,SAAS,gBAAgB;EACpE,MAAM,cAAc,OAAO,mBAAmB,SAAS,KAAK,YAAY;EACxE,MAAM,SAAS,IAAI,6BAA6B;EAChD,MAAM,aAAa,IAAI,2BAA2B,OAAO,cAAc,EAAE,EACvE,gBAAgB,SACjB,CAAC;EACF,MAAM,gBAAgB,IAAI,wBAAwB;GAChD;GACA;GACA;GACD,CAAC;AAiBF,SAAO,MAVS,IAAI,qBAAqB;GACvC;GACA;GACA;GACA,eAVoB,IAAI,wBAAwB;IAChD;IACA;IACA;IACA,iBAAiB,OAAO,wBAAwB,IAAI,KAAA;IACrD,CAAC;GAMA,0B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S;;CAGlD,8CAAsD,SAA+C;EACnG,MAAM,eAAe,4BAA4B,KAAK;AACtD,SAAO;GACL,QAAQ;GACR,kBAAkB;GAClB,SAAS,KAAK,YAAY,SAAS,SAAS;GAC5C,aAAa,aAAa;GAC1B,gBAAgB,aAAa;GAC7B,kBAAkB;GAClB,mBAAmB;GACnB,oBAAoB;GACpB,iBAAiB;GACjB,gCAAe,IAAI,MAAM,EAAC,aAAa;GACvC,UAAU;GACV,eAAe;GACf,iBAAiB;GACjB,aAAa;GACb,iBAAiB;GACjB,cAAc;GACf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"npm-runtime-update.service.d.ts","names":[],"sources":["../../../src/services/runtime/npm-runtime-update.service.ts"],"mappings":";;;;;;KAkBK,SAAA,UAAmB,KAAA;AAAA,KAEnB,8BAAA;EACH,MAAA,EAAQ,2BAAA;EACR,aAAA,EAAe,uBAAA;EACf,eAAA;EACA,eAAA;EACA,SAAA,GAAY,SAAA;EACZ,QAAA,GAAW,MAAA,CAAO,QAAA;EAClB,IAAA;EACA,cAAA,GAAiB,oBAAA;EACjB,GAAA;AAAA;AAAA,KAGU,yBAAA;EACN,IAAA;EAA+B,QAAA,EAAU,cAAA;AAAA;EACzC,IAAA;EAA8B,QAAA,EAAU,cAAA;AAAA;EACxC,IAAA;EAAiC,QAAA,EAAU,cAAA;AAAA;AAAA,cAEpC,uBAAA;EAAA,iBAQkB,OAAA;EAAA,iBAPZ,QAAA;EAAA,iBACA,IAAA;EAAA,iBACA,SAAA;EAAA,iBACA,cAAA;EAAA,iBACA,eAAA;EAAA,iBACA,GAAA;cAEY,OAAA,EAAS,8BAAA;EAStC,oBAAA;EAEA,cAAA,GAAwB,WAAA,UAAqB,cAAA,iBAA+B,WAAA,gBAA6B,OAAA,CAAQ,yBAAA;
|
|
1
|
+
{"version":3,"file":"npm-runtime-update.service.d.ts","names":[],"sources":["../../../src/services/runtime/npm-runtime-update.service.ts"],"mappings":";;;;;;KAkBK,SAAA,UAAmB,KAAA;AAAA,KAEnB,8BAAA;EACH,MAAA,EAAQ,2BAAA;EACR,aAAA,EAAe,uBAAA;EACf,eAAA;EACA,eAAA;EACA,SAAA,GAAY,SAAA;EACZ,QAAA,GAAW,MAAA,CAAO,QAAA;EAClB,IAAA;EACA,cAAA,GAAiB,oBAAA;EACjB,GAAA;AAAA;AAAA,KAGU,yBAAA;EACN,IAAA;EAA+B,QAAA,EAAU,cAAA;AAAA;EACzC,IAAA;EAA8B,QAAA,EAAU,cAAA;AAAA;EACxC,IAAA;EAAiC,QAAA,EAAU,cAAA;AAAA;AAAA,cAEpC,uBAAA;EAAA,iBAQkB,OAAA;EAAA,iBAPZ,QAAA;EAAA,iBACA,IAAA;EAAA,iBACA,SAAA;EAAA,iBACA,cAAA;EAAA,iBACA,eAAA;EAAA,iBACA,GAAA;cAEY,OAAA,EAAS,8BAAA;EAStC,oBAAA;EAEA,cAAA,GAAwB,WAAA,UAAqB,cAAA,iBAA+B,WAAA,gBAA6B,OAAA,CAAQ,yBAAA;EAiBjH,wBAAA,GACE,QAAA,EAAU,cAAA,EACV,cAAA,GAAiB,gCAAA,KAChB,OAAA,CAAQ,0BAAA;EAAA,QAuCH,mBAAA;EAAA,QAcA,mBAAA;EAAA,QAcA,aAAA;EAAA,QAaA,cAAA;EAAA,QAiBA,WAAA;EAAA,QAiBA,iBAAA;EAAA,QA0BA,iBAAA;EAAA,QASA,sBAAA;EAAA,QAYA,cAAA;EAAA,QAYA,oBAAA;EAAA,QAgBA,uBAAA;EAAA,QAWA,qBAAA;AAAA"}
|
|
@@ -27,6 +27,7 @@ var NpmRuntimeUpdateService = class {
|
|
|
27
27
|
checkForUpdate = async (manifestUrl, currentVersion, badVersions = []) => {
|
|
28
28
|
const manifest = await this.fetchManifest(manifestUrl);
|
|
29
29
|
if (currentVersion && compareNpmRuntimeVersions(manifest.latestVersion, currentVersion) <= 0) return null;
|
|
30
|
+
if (!currentVersion && compareNpmRuntimeVersions(manifest.latestVersion, this.options.launcherVersion) < 0) return null;
|
|
30
31
|
if (compareNpmRuntimeVersions(this.options.launcherVersion, manifest.minimumLauncherVersion) < 0) return {
|
|
31
32
|
kind: "host-update-required",
|
|
32
33
|
manifest
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"npm-runtime-update.service.js","names":[],"sources":["../../../src/services/runtime/npm-runtime-update.service.ts"],"sourcesContent":["import { createHash, createPublicKey, verify, type KeyObject } from \"node:crypto\";\nimport { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { rm } from \"node:fs/promises\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, join, resolve, sep } from \"node:path\";\nimport JSZip from \"jszip\";\nimport {\n serializeUnsignedUpdateManifest,\n UpdateManifestReader,\n type UpdateManifest\n} from \"@nextclaw/kernel\";\nimport type { NpmRuntimeBundleLayoutStore } from \"@nextclaw-service/stores/npm-runtime-bundle-layout.store.js\";\nimport { compareNpmRuntimeVersions, type NpmRuntimeBundleService } from \"@nextclaw-service/services/runtime/npm-runtime-bundle.service.js\";\nimport type {\n NpmRuntimeDownloadedUpdate,\n NpmRuntimeUpdateProgressReporter\n} from \"@nextclaw-service/types/npm-runtime-bundle.types.js\";\n\ntype FetchLike = typeof fetch;\n\ntype NpmRuntimeUpdateServiceOptions = {\n layout: NpmRuntimeBundleLayoutStore;\n bundleService: NpmRuntimeBundleService;\n launcherVersion: string;\n bundlePublicKey?: string;\n fetchImpl?: FetchLike;\n platform?: NodeJS.Platform;\n arch?: string;\n manifestReader?: UpdateManifestReader;\n now?: () => number;\n};\n\nexport type NpmRuntimeAvailableUpdate =\n | { kind: \"runtime-bundle-update\"; manifest: UpdateManifest }\n | { kind: \"host-update-required\"; manifest: UpdateManifest }\n | { kind: \"quarantined-bad-version\"; manifest: UpdateManifest };\n\nexport class NpmRuntimeUpdateService {\n private readonly platform: NodeJS.Platform;\n private readonly arch: string;\n private readonly fetchImpl: FetchLike;\n private readonly manifestReader: UpdateManifestReader;\n private readonly bundlePublicKey: KeyObject | null;\n private readonly now: () => number;\n\n constructor(private readonly options: NpmRuntimeUpdateServiceOptions) {\n this.platform = options.platform ?? process.platform;\n this.arch = options.arch ?? process.arch;\n this.fetchImpl = options.fetchImpl ?? fetch;\n this.manifestReader = options.manifestReader ?? new UpdateManifestReader();\n this.bundlePublicKey = this.parseBundlePublicKey(options.bundlePublicKey);\n this.now = options.now ?? Date.now;\n }\n\n hasSignatureVerifier = (): boolean => Boolean(this.bundlePublicKey);\n\n checkForUpdate = async (manifestUrl: string, currentVersion: string | null, badVersions: string[] = []): Promise<NpmRuntimeAvailableUpdate | null> => {\n const manifest = await this.fetchManifest(manifestUrl);\n if (currentVersion && compareNpmRuntimeVersions(manifest.latestVersion, currentVersion) <= 0) {\n return null;\n }\n if (compareNpmRuntimeVersions(this.options.launcherVersion, manifest.minimumLauncherVersion) < 0) {\n return { kind: \"host-update-required\", manifest };\n }\n if (badVersions.includes(manifest.latestVersion)) {\n return { kind: \"quarantined-bad-version\", manifest };\n }\n return { kind: \"runtime-bundle-update\", manifest };\n };\n\n downloadAndInstallUpdate = async (\n manifest: UpdateManifest,\n reportProgress?: NpmRuntimeUpdateProgressReporter\n ): Promise<NpmRuntimeDownloadedUpdate> => {\n const bytes = await this.downloadBundleBytes(manifest, reportProgress);\n const stagingRoot = join(this.options.layout.getStagingDir(), `download-${manifest.latestVersion}-${this.now()}`);\n await rm(stagingRoot, { recursive: true, force: true });\n mkdirSync(stagingRoot, { recursive: true });\n\n try {\n const zip = await JSZip.loadAsync(bytes);\n const entries = Object.values(zip.files) as JSZip.JSZipObject[];\n await Promise.all(entries.map(async (entry) => {\n const targetPath = resolve(stagingRoot, entry.name);\n const resolvedStagingRoot = resolve(stagingRoot);\n if (targetPath !== resolvedStagingRoot && !targetPath.startsWith(`${resolvedStagingRoot}${sep}`)) {\n throw new Error(`runtime bundle archive contains invalid path: ${entry.name}`);\n }\n if (entry.dir) {\n mkdirSync(targetPath, { recursive: true });\n return;\n }\n mkdirSync(dirname(targetPath), { recursive: true });\n writeFileSync(targetPath, Buffer.from(await entry.async(\"uint8array\")));\n const unixMode = this.readArchiveUnixMode(entry);\n if (unixMode !== null && this.platform !== \"win32\") {\n chmodSync(targetPath, unixMode);\n }\n }));\n const bundleRoot = this.findBundleRoot(stagingRoot);\n const installedBundle = await this.options.bundleService.installFromDirectory(bundleRoot);\n return {\n manifest,\n downloadedVersion: installedBundle.manifest.bundleVersion,\n bundleDirectory: installedBundle.bundleDirectory\n };\n } catch (error) {\n await rm(stagingRoot, { recursive: true, force: true });\n throw error;\n }\n };\n\n private readArchiveUnixMode = (entry: JSZip.JSZipObject): number | null => {\n const rawMode = entry.unixPermissions;\n const parsedMode = typeof rawMode === \"number\"\n ? rawMode\n : typeof rawMode === \"string\"\n ? Number.parseInt(rawMode, 8)\n : Number.NaN;\n if (!Number.isInteger(parsedMode)) {\n return null;\n }\n const permissionBits = parsedMode & 0o777;\n return permissionBits > 0 ? permissionBits : null;\n };\n\n private downloadBundleBytes = async (\n manifest: UpdateManifest,\n reportProgress?: NpmRuntimeUpdateProgressReporter\n ): Promise<Buffer> => {\n const response = await this.fetchBundle(manifest.bundleUrl);\n const bytes = await this.readResponseBytes(response, reportProgress);\n const sha256 = createHash(\"sha256\").update(bytes).digest(\"hex\");\n if (sha256 !== manifest.bundleSha256) {\n throw new Error(`runtime bundle sha256 mismatch: expected ${manifest.bundleSha256} but got ${sha256}`);\n }\n this.assertBundleSignature(manifest, bytes);\n return bytes;\n };\n\n private fetchManifest = async (manifestUrl: string): Promise<UpdateManifest> => {\n if (manifestUrl.startsWith(\"file://\")) {\n const manifest = this.manifestReader.parse(JSON.parse(readFileSync(fileURLToPath(manifestUrl), \"utf8\")), manifestUrl);\n return this.verifyManifest(manifest, manifestUrl);\n }\n const response = await this.fetchImpl(manifestUrl);\n if (!response.ok) {\n throw new Error(`runtime update manifest request failed with status ${response.status}`);\n }\n const manifest = this.manifestReader.parse(await response.json(), manifestUrl);\n return this.verifyManifest(manifest, manifestUrl);\n };\n\n private verifyManifest = (manifest: UpdateManifest, _manifestUrl: string): UpdateManifest => {\n if (manifest.hostKind && manifest.hostKind !== \"npm-runtime-bundle\") {\n throw new Error(`runtime update manifest hostKind mismatch: expected npm-runtime-bundle but got ${manifest.hostKind}`);\n }\n if (manifest.channel !== \"stable\" && manifest.channel !== \"beta\") {\n throw new Error(`runtime update manifest channel is unsupported: ${manifest.channel}`);\n }\n if (manifest.platform !== this.platform) {\n throw new Error(`runtime update manifest platform mismatch: expected ${this.platform} but got ${manifest.platform}`);\n }\n if (manifest.arch !== this.arch) {\n throw new Error(`runtime update manifest arch mismatch: expected ${this.arch} but got ${manifest.arch}`);\n }\n this.assertManifestSignature(manifest);\n return manifest;\n };\n\n private fetchBundle = async (bundleUrl: string): Promise<Response> => {\n if (bundleUrl.startsWith(\"file://\")) {\n const bytes = readFileSync(fileURLToPath(bundleUrl));\n return new Response(bytes, {\n status: 200,\n headers: {\n \"content-length\": String(bytes.byteLength)\n }\n });\n }\n const response = await this.fetchImpl(bundleUrl);\n if (!response.ok) {\n throw new Error(`runtime bundle download failed with status ${response.status}`);\n }\n return response;\n };\n\n private readResponseBytes = async (\n response: Response,\n reportProgress?: NpmRuntimeUpdateProgressReporter\n ): Promise<Buffer> => {\n const totalBytes = this.readContentLength(response);\n if (!response.body) {\n const bytes = Buffer.from(await response.arrayBuffer());\n this.reportDownloadProgress(reportProgress, bytes.byteLength, totalBytes ?? bytes.byteLength);\n return bytes;\n }\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let downloadedBytes = 0;\n this.reportDownloadProgress(reportProgress, downloadedBytes, totalBytes);\n while (true) {\n const next = await reader.read();\n if (next.done) {\n break;\n }\n chunks.push(next.value);\n downloadedBytes += next.value.byteLength;\n this.reportDownloadProgress(reportProgress, downloadedBytes, totalBytes);\n }\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));\n };\n\n private readContentLength = (response: Response): number | null => {\n const raw = response.headers.get(\"content-length\");\n if (!raw) {\n return null;\n }\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;\n };\n\n private reportDownloadProgress = (\n reportProgress: NpmRuntimeUpdateProgressReporter | undefined,\n downloadedBytes: number,\n totalBytes: number | null\n ): void => {\n reportProgress?.({\n downloadedBytes,\n totalBytes,\n percent: totalBytes && totalBytes > 0 ? Math.min(100, Math.round((downloadedBytes / totalBytes) * 100)) : null\n });\n };\n\n private findBundleRoot = (stagingRoot: string): string => {\n const directManifestPath = join(stagingRoot, \"manifest.json\");\n if (existsSync(directManifestPath)) {\n return stagingRoot;\n }\n const entries = readDirectoryNames(stagingRoot).filter((entry) => existsSync(join(stagingRoot, entry, \"manifest.json\")));\n if (entries.length === 1) {\n return join(stagingRoot, entries[0]);\n }\n throw new Error(`runtime bundle archive does not contain exactly one manifest root under ${stagingRoot}`);\n };\n\n private parseBundlePublicKey = (publicKey: string | undefined): KeyObject | null => {\n const normalizedKey = publicKey?.trim();\n if (!normalizedKey) {\n return null;\n }\n const pemOrEscapedPem = normalizedKey.replaceAll(\"\\\\n\", \"\\n\");\n if (pemOrEscapedPem.includes(\"BEGIN PUBLIC KEY\")) {\n return createPublicKey(pemOrEscapedPem);\n }\n return createPublicKey({\n key: Buffer.from(normalizedKey, \"base64\"),\n format: \"der\",\n type: \"spki\"\n });\n };\n\n private assertManifestSignature = (manifest: UpdateManifest): void => {\n if (!this.bundlePublicKey) {\n throw new Error(\"runtime update manifest signature verification requires bundlePublicKey\");\n }\n const signature = Buffer.from(manifest.manifestSignature, \"base64\");\n const valid = verify(null, Buffer.from(serializeUnsignedUpdateManifest(manifest)), this.bundlePublicKey, signature);\n if (!valid) {\n throw new Error(`runtime update manifest signature verification failed for ${manifest.latestVersion}`);\n }\n };\n\n private assertBundleSignature = (manifest: UpdateManifest, bytes: Buffer): void => {\n if (!this.bundlePublicKey) {\n throw new Error(\"runtime bundle signature verification requires bundlePublicKey\");\n }\n const signature = Buffer.from(manifest.bundleSignature, \"base64\");\n const valid = verify(null, bytes, this.bundlePublicKey, signature);\n if (!valid) {\n throw new Error(`runtime bundle signature verification failed for ${manifest.latestVersion}`);\n }\n };\n}\n\nfunction readDirectoryNames(directory: string): string[] {\n return readdirSync(directory, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name);\n}\n"],"mappings":";;;;;;;;;AAqCA,IAAa,0BAAb,MAAqC;CACnC;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAA0D;AAAzC,OAAA,UAAA;AAC3B,OAAK,WAAW,QAAQ,YAAY,QAAQ;AAC5C,OAAK,OAAO,QAAQ,QAAQ,QAAQ;AACpC,OAAK,YAAY,QAAQ,aAAa;AACtC,OAAK,iBAAiB,QAAQ,kBAAkB,IAAI,sBAAsB;AAC1E,OAAK,kBAAkB,KAAK,qBAAqB,QAAQ,gBAAgB;AACzE,OAAK,MAAM,QAAQ,OAAO,KAAK;;CAGjC,6BAAsC,QAAQ,KAAK,gBAAgB;CAEnE,iBAAiB,OAAO,aAAqB,gBAA+B,cAAwB,EAAE,KAAgD;EACpJ,MAAM,WAAW,MAAM,KAAK,cAAc,YAAY;AACtD,MAAI,kBAAkB,0BAA0B,SAAS,eAAe,eAAe,IAAI,EACzF,QAAO;AAET,MAAI,0BAA0B,KAAK,QAAQ,iBAAiB,SAAS,uBAAuB,GAAG,EAC7F,QAAO;GAAE,MAAM;GAAwB;GAAU;AAEnD,MAAI,YAAY,SAAS,SAAS,cAAc,CAC9C,QAAO;GAAE,MAAM;GAA2B;GAAU;AAEtD,SAAO;GAAE,MAAM;GAAyB;GAAU;;CAGpD,2BAA2B,OACzB,UACA,mBACwC;EACxC,MAAM,QAAQ,MAAM,KAAK,oBAAoB,UAAU,eAAe;EACtE,MAAM,cAAc,KAAK,KAAK,QAAQ,OAAO,eAAe,EAAE,YAAY,SAAS,cAAc,GAAG,KAAK,KAAK,GAAG;AACjH,QAAM,GAAG,aAAa;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+
{"version":3,"file":"npm-runtime-update.service.js","names":[],"sources":["../../../src/services/runtime/npm-runtime-update.service.ts"],"sourcesContent":["import { createHash, createPublicKey, verify, type KeyObject } from \"node:crypto\";\nimport { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { rm } from \"node:fs/promises\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, join, resolve, sep } from \"node:path\";\nimport JSZip from \"jszip\";\nimport {\n serializeUnsignedUpdateManifest,\n UpdateManifestReader,\n type UpdateManifest\n} from \"@nextclaw/kernel\";\nimport type { NpmRuntimeBundleLayoutStore } from \"@nextclaw-service/stores/npm-runtime-bundle-layout.store.js\";\nimport { compareNpmRuntimeVersions, type NpmRuntimeBundleService } from \"@nextclaw-service/services/runtime/npm-runtime-bundle.service.js\";\nimport type {\n NpmRuntimeDownloadedUpdate,\n NpmRuntimeUpdateProgressReporter\n} from \"@nextclaw-service/types/npm-runtime-bundle.types.js\";\n\ntype FetchLike = typeof fetch;\n\ntype NpmRuntimeUpdateServiceOptions = {\n layout: NpmRuntimeBundleLayoutStore;\n bundleService: NpmRuntimeBundleService;\n launcherVersion: string;\n bundlePublicKey?: string;\n fetchImpl?: FetchLike;\n platform?: NodeJS.Platform;\n arch?: string;\n manifestReader?: UpdateManifestReader;\n now?: () => number;\n};\n\nexport type NpmRuntimeAvailableUpdate =\n | { kind: \"runtime-bundle-update\"; manifest: UpdateManifest }\n | { kind: \"host-update-required\"; manifest: UpdateManifest }\n | { kind: \"quarantined-bad-version\"; manifest: UpdateManifest };\n\nexport class NpmRuntimeUpdateService {\n private readonly platform: NodeJS.Platform;\n private readonly arch: string;\n private readonly fetchImpl: FetchLike;\n private readonly manifestReader: UpdateManifestReader;\n private readonly bundlePublicKey: KeyObject | null;\n private readonly now: () => number;\n\n constructor(private readonly options: NpmRuntimeUpdateServiceOptions) {\n this.platform = options.platform ?? process.platform;\n this.arch = options.arch ?? process.arch;\n this.fetchImpl = options.fetchImpl ?? fetch;\n this.manifestReader = options.manifestReader ?? new UpdateManifestReader();\n this.bundlePublicKey = this.parseBundlePublicKey(options.bundlePublicKey);\n this.now = options.now ?? Date.now;\n }\n\n hasSignatureVerifier = (): boolean => Boolean(this.bundlePublicKey);\n\n checkForUpdate = async (manifestUrl: string, currentVersion: string | null, badVersions: string[] = []): Promise<NpmRuntimeAvailableUpdate | null> => {\n const manifest = await this.fetchManifest(manifestUrl);\n if (currentVersion && compareNpmRuntimeVersions(manifest.latestVersion, currentVersion) <= 0) {\n return null;\n }\n if (!currentVersion && compareNpmRuntimeVersions(manifest.latestVersion, this.options.launcherVersion) < 0) {\n return null;\n }\n if (compareNpmRuntimeVersions(this.options.launcherVersion, manifest.minimumLauncherVersion) < 0) {\n return { kind: \"host-update-required\", manifest };\n }\n if (badVersions.includes(manifest.latestVersion)) {\n return { kind: \"quarantined-bad-version\", manifest };\n }\n return { kind: \"runtime-bundle-update\", manifest };\n };\n\n downloadAndInstallUpdate = async (\n manifest: UpdateManifest,\n reportProgress?: NpmRuntimeUpdateProgressReporter\n ): Promise<NpmRuntimeDownloadedUpdate> => {\n const bytes = await this.downloadBundleBytes(manifest, reportProgress);\n const stagingRoot = join(this.options.layout.getStagingDir(), `download-${manifest.latestVersion}-${this.now()}`);\n await rm(stagingRoot, { recursive: true, force: true });\n mkdirSync(stagingRoot, { recursive: true });\n\n try {\n const zip = await JSZip.loadAsync(bytes);\n const entries = Object.values(zip.files) as JSZip.JSZipObject[];\n await Promise.all(entries.map(async (entry) => {\n const targetPath = resolve(stagingRoot, entry.name);\n const resolvedStagingRoot = resolve(stagingRoot);\n if (targetPath !== resolvedStagingRoot && !targetPath.startsWith(`${resolvedStagingRoot}${sep}`)) {\n throw new Error(`runtime bundle archive contains invalid path: ${entry.name}`);\n }\n if (entry.dir) {\n mkdirSync(targetPath, { recursive: true });\n return;\n }\n mkdirSync(dirname(targetPath), { recursive: true });\n writeFileSync(targetPath, Buffer.from(await entry.async(\"uint8array\")));\n const unixMode = this.readArchiveUnixMode(entry);\n if (unixMode !== null && this.platform !== \"win32\") {\n chmodSync(targetPath, unixMode);\n }\n }));\n const bundleRoot = this.findBundleRoot(stagingRoot);\n const installedBundle = await this.options.bundleService.installFromDirectory(bundleRoot);\n return {\n manifest,\n downloadedVersion: installedBundle.manifest.bundleVersion,\n bundleDirectory: installedBundle.bundleDirectory\n };\n } catch (error) {\n await rm(stagingRoot, { recursive: true, force: true });\n throw error;\n }\n };\n\n private readArchiveUnixMode = (entry: JSZip.JSZipObject): number | null => {\n const rawMode = entry.unixPermissions;\n const parsedMode = typeof rawMode === \"number\"\n ? rawMode\n : typeof rawMode === \"string\"\n ? Number.parseInt(rawMode, 8)\n : Number.NaN;\n if (!Number.isInteger(parsedMode)) {\n return null;\n }\n const permissionBits = parsedMode & 0o777;\n return permissionBits > 0 ? permissionBits : null;\n };\n\n private downloadBundleBytes = async (\n manifest: UpdateManifest,\n reportProgress?: NpmRuntimeUpdateProgressReporter\n ): Promise<Buffer> => {\n const response = await this.fetchBundle(manifest.bundleUrl);\n const bytes = await this.readResponseBytes(response, reportProgress);\n const sha256 = createHash(\"sha256\").update(bytes).digest(\"hex\");\n if (sha256 !== manifest.bundleSha256) {\n throw new Error(`runtime bundle sha256 mismatch: expected ${manifest.bundleSha256} but got ${sha256}`);\n }\n this.assertBundleSignature(manifest, bytes);\n return bytes;\n };\n\n private fetchManifest = async (manifestUrl: string): Promise<UpdateManifest> => {\n if (manifestUrl.startsWith(\"file://\")) {\n const manifest = this.manifestReader.parse(JSON.parse(readFileSync(fileURLToPath(manifestUrl), \"utf8\")), manifestUrl);\n return this.verifyManifest(manifest, manifestUrl);\n }\n const response = await this.fetchImpl(manifestUrl);\n if (!response.ok) {\n throw new Error(`runtime update manifest request failed with status ${response.status}`);\n }\n const manifest = this.manifestReader.parse(await response.json(), manifestUrl);\n return this.verifyManifest(manifest, manifestUrl);\n };\n\n private verifyManifest = (manifest: UpdateManifest, _manifestUrl: string): UpdateManifest => {\n if (manifest.hostKind && manifest.hostKind !== \"npm-runtime-bundle\") {\n throw new Error(`runtime update manifest hostKind mismatch: expected npm-runtime-bundle but got ${manifest.hostKind}`);\n }\n if (manifest.channel !== \"stable\" && manifest.channel !== \"beta\") {\n throw new Error(`runtime update manifest channel is unsupported: ${manifest.channel}`);\n }\n if (manifest.platform !== this.platform) {\n throw new Error(`runtime update manifest platform mismatch: expected ${this.platform} but got ${manifest.platform}`);\n }\n if (manifest.arch !== this.arch) {\n throw new Error(`runtime update manifest arch mismatch: expected ${this.arch} but got ${manifest.arch}`);\n }\n this.assertManifestSignature(manifest);\n return manifest;\n };\n\n private fetchBundle = async (bundleUrl: string): Promise<Response> => {\n if (bundleUrl.startsWith(\"file://\")) {\n const bytes = readFileSync(fileURLToPath(bundleUrl));\n return new Response(bytes, {\n status: 200,\n headers: {\n \"content-length\": String(bytes.byteLength)\n }\n });\n }\n const response = await this.fetchImpl(bundleUrl);\n if (!response.ok) {\n throw new Error(`runtime bundle download failed with status ${response.status}`);\n }\n return response;\n };\n\n private readResponseBytes = async (\n response: Response,\n reportProgress?: NpmRuntimeUpdateProgressReporter\n ): Promise<Buffer> => {\n const totalBytes = this.readContentLength(response);\n if (!response.body) {\n const bytes = Buffer.from(await response.arrayBuffer());\n this.reportDownloadProgress(reportProgress, bytes.byteLength, totalBytes ?? bytes.byteLength);\n return bytes;\n }\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let downloadedBytes = 0;\n this.reportDownloadProgress(reportProgress, downloadedBytes, totalBytes);\n while (true) {\n const next = await reader.read();\n if (next.done) {\n break;\n }\n chunks.push(next.value);\n downloadedBytes += next.value.byteLength;\n this.reportDownloadProgress(reportProgress, downloadedBytes, totalBytes);\n }\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));\n };\n\n private readContentLength = (response: Response): number | null => {\n const raw = response.headers.get(\"content-length\");\n if (!raw) {\n return null;\n }\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;\n };\n\n private reportDownloadProgress = (\n reportProgress: NpmRuntimeUpdateProgressReporter | undefined,\n downloadedBytes: number,\n totalBytes: number | null\n ): void => {\n reportProgress?.({\n downloadedBytes,\n totalBytes,\n percent: totalBytes && totalBytes > 0 ? Math.min(100, Math.round((downloadedBytes / totalBytes) * 100)) : null\n });\n };\n\n private findBundleRoot = (stagingRoot: string): string => {\n const directManifestPath = join(stagingRoot, \"manifest.json\");\n if (existsSync(directManifestPath)) {\n return stagingRoot;\n }\n const entries = readDirectoryNames(stagingRoot).filter((entry) => existsSync(join(stagingRoot, entry, \"manifest.json\")));\n if (entries.length === 1) {\n return join(stagingRoot, entries[0]);\n }\n throw new Error(`runtime bundle archive does not contain exactly one manifest root under ${stagingRoot}`);\n };\n\n private parseBundlePublicKey = (publicKey: string | undefined): KeyObject | null => {\n const normalizedKey = publicKey?.trim();\n if (!normalizedKey) {\n return null;\n }\n const pemOrEscapedPem = normalizedKey.replaceAll(\"\\\\n\", \"\\n\");\n if (pemOrEscapedPem.includes(\"BEGIN PUBLIC KEY\")) {\n return createPublicKey(pemOrEscapedPem);\n }\n return createPublicKey({\n key: Buffer.from(normalizedKey, \"base64\"),\n format: \"der\",\n type: \"spki\"\n });\n };\n\n private assertManifestSignature = (manifest: UpdateManifest): void => {\n if (!this.bundlePublicKey) {\n throw new Error(\"runtime update manifest signature verification requires bundlePublicKey\");\n }\n const signature = Buffer.from(manifest.manifestSignature, \"base64\");\n const valid = verify(null, Buffer.from(serializeUnsignedUpdateManifest(manifest)), this.bundlePublicKey, signature);\n if (!valid) {\n throw new Error(`runtime update manifest signature verification failed for ${manifest.latestVersion}`);\n }\n };\n\n private assertBundleSignature = (manifest: UpdateManifest, bytes: Buffer): void => {\n if (!this.bundlePublicKey) {\n throw new Error(\"runtime bundle signature verification requires bundlePublicKey\");\n }\n const signature = Buffer.from(manifest.bundleSignature, \"base64\");\n const valid = verify(null, bytes, this.bundlePublicKey, signature);\n if (!valid) {\n throw new Error(`runtime bundle signature verification failed for ${manifest.latestVersion}`);\n }\n };\n}\n\nfunction readDirectoryNames(directory: string): string[] {\n return readdirSync(directory, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name);\n}\n"],"mappings":";;;;;;;;;AAqCA,IAAa,0BAAb,MAAqC;CACnC;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAA0D;AAAzC,OAAA,UAAA;AAC3B,OAAK,WAAW,QAAQ,YAAY,QAAQ;AAC5C,OAAK,OAAO,QAAQ,QAAQ,QAAQ;AACpC,OAAK,YAAY,QAAQ,aAAa;AACtC,OAAK,iBAAiB,QAAQ,kBAAkB,IAAI,sBAAsB;AAC1E,OAAK,kBAAkB,KAAK,qBAAqB,QAAQ,gBAAgB;AACzE,OAAK,MAAM,QAAQ,OAAO,KAAK;;CAGjC,6BAAsC,QAAQ,KAAK,gBAAgB;CAEnE,iBAAiB,OAAO,aAAqB,gBAA+B,cAAwB,EAAE,KAAgD;EACpJ,MAAM,WAAW,MAAM,KAAK,cAAc,YAAY;AACtD,MAAI,kBAAkB,0BAA0B,SAAS,eAAe,eAAe,IAAI,EACzF,QAAO;AAET,MAAI,CAAC,kBAAkB,0BAA0B,SAAS,eAAe,KAAK,QAAQ,gBAAgB,GAAG,EACvG,QAAO;AAET,MAAI,0BAA0B,KAAK,QAAQ,iBAAiB,SAAS,uBAAuB,GAAG,EAC7F,QAAO;GAAE,MAAM;GAAwB;GAAU;AAEnD,MAAI,YAAY,SAAS,SAAS,cAAc,CAC9C,QAAO;GAAE,MAAM;GAA2B;GAAU;AAEtD,SAAO;GAAE,MAAM;GAAyB;GAAU;;CAGpD,2BAA2B,OACzB,UACA,mBACwC;EACxC,MAAM,QAAQ,MAAM,KAAK,oBAAoB,UAAU,eAAe;EACtE,MAAM,cAAc,KAAK,KAAK,QAAQ,OAAO,eAAe,EAAE,YAAY,SAAS,cAAc,GAAG,KAAK,KAAK,GAAG;AACjH,QAAM,GAAG,aAAa;GAAE,WAAW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@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nextclaw/service",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.3",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "NextClaw long-running service host and runtime lifecycle.",
|
|
6
6
|
"type": "module",
|
|
@@ -42,31 +42,31 @@
|
|
|
42
42
|
"chokidar": "^3.6.0",
|
|
43
43
|
"commander": "^12.1.0",
|
|
44
44
|
"jszip": "^3.10.1",
|
|
45
|
-
"@nextclaw/channel-extension-dingtalk": "0.2.
|
|
46
|
-
"@nextclaw/channel-extension-discord": "0.2.
|
|
47
|
-
"@nextclaw/channel-extension-email": "0.2.
|
|
48
|
-
"@nextclaw/channel-extension-feishu": "0.2.
|
|
49
|
-
"@nextclaw/channel-extension-
|
|
50
|
-
"@nextclaw/channel-extension-
|
|
51
|
-
"@nextclaw/channel-extension-telegram": "0.2.
|
|
52
|
-
"@nextclaw/channel-extension-
|
|
53
|
-
"@nextclaw/channel-extension-
|
|
54
|
-
"@nextclaw/channel-extension-whatsapp": "0.2.
|
|
55
|
-
"@nextclaw/
|
|
56
|
-
"@nextclaw/
|
|
57
|
-
"@nextclaw/kernel": "0.12.
|
|
58
|
-
"@nextclaw/mcp": "0.
|
|
59
|
-
"@nextclaw/
|
|
60
|
-
"@nextclaw/ncp-agent-runtime": "0.4.21",
|
|
61
|
-
"@nextclaw/ncp-mcp": "0.2.38",
|
|
45
|
+
"@nextclaw/channel-extension-dingtalk": "0.2.39",
|
|
46
|
+
"@nextclaw/channel-extension-discord": "0.2.39",
|
|
47
|
+
"@nextclaw/channel-extension-email": "0.2.39",
|
|
48
|
+
"@nextclaw/channel-extension-feishu": "0.2.31",
|
|
49
|
+
"@nextclaw/channel-extension-qq": "0.2.30",
|
|
50
|
+
"@nextclaw/channel-extension-slack": "0.2.39",
|
|
51
|
+
"@nextclaw/channel-extension-telegram": "0.2.39",
|
|
52
|
+
"@nextclaw/channel-extension-weixin": "0.2.31",
|
|
53
|
+
"@nextclaw/channel-extension-wecom": "0.2.39",
|
|
54
|
+
"@nextclaw/channel-extension-whatsapp": "0.2.39",
|
|
55
|
+
"@nextclaw/core": "0.17.13",
|
|
56
|
+
"@nextclaw/mcp": "0.3.40",
|
|
57
|
+
"@nextclaw/kernel": "0.12.2",
|
|
58
|
+
"@nextclaw/ncp-mcp": "0.2.40",
|
|
59
|
+
"@nextclaw/client-sdk": "0.9.2",
|
|
62
60
|
"@nextclaw/ncp-toolkit": "0.6.23",
|
|
61
|
+
"@nextclaw/ncp-agent-runtime": "0.4.21",
|
|
63
62
|
"@nextclaw/nextclaw-hermes-acp-bridge": "0.3.21",
|
|
63
|
+
"@nextclaw/ncp": "0.10.0",
|
|
64
64
|
"@nextclaw/nextclaw-ncp-runtime-http-client": "0.3.22",
|
|
65
|
-
"@nextclaw/nextclaw-ncp-runtime-stdio-client": "0.3.
|
|
66
|
-
"@nextclaw/
|
|
67
|
-
"@nextclaw/
|
|
68
|
-
"@nextclaw/
|
|
69
|
-
"@nextclaw/shared": "0.4.
|
|
65
|
+
"@nextclaw/nextclaw-ncp-runtime-stdio-client": "0.3.40",
|
|
66
|
+
"@nextclaw/runtime": "0.4.39",
|
|
67
|
+
"@nextclaw/server": "0.20.2",
|
|
68
|
+
"@nextclaw/remote": "0.3.49",
|
|
69
|
+
"@nextclaw/shared": "0.4.30"
|
|
70
70
|
},
|
|
71
71
|
"devDependencies": {
|
|
72
72
|
"@types/node": "^20.17.6",
|