@spotpatch/vite 1.10.0 → 1.11.0

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/cli.js CHANGED
@@ -263,6 +263,7 @@ function childIndent(source, object) {
263
263
  function initializedPluginCall(pluginName, trustedFastMode) {
264
264
  const options = [
265
265
  "dataFlow: {}",
266
+ "externalAgent: true",
266
267
  ...trustedFastMode ? ["trustedFastMode: true"] : []
267
268
  ];
268
269
  return `${pluginName}({ ${options.join(", ")} })`;
@@ -299,6 +300,7 @@ function enableInitializedOptions(magicString, source, call, trustedFastMode) {
299
300
  );
300
301
  }
301
302
  const dataFlowProperty = findProperty(value, "dataFlow");
303
+ const externalAgentProperty = findProperty(value, "externalAgent");
302
304
  const trustedFastModeProperty = findProperty(value, "trustedFastMode");
303
305
  const missingProperties = [];
304
306
  if (dataFlowProperty === void 0) {
@@ -313,6 +315,17 @@ function enableInitializedOptions(magicString, source, call, trustedFastMode) {
313
315
  );
314
316
  }
315
317
  }
318
+ if (externalAgentProperty === void 0) {
319
+ missingProperties.push("externalAgent: true");
320
+ } else {
321
+ const propertyValue = unwrapExpression(externalAgentProperty.value);
322
+ if (propertyValue.type !== "Literal" || typeof propertyValue.value !== "boolean") {
323
+ throw new Error("SpotPatch init requires externalAgent to be a boolean literal.");
324
+ }
325
+ if (!propertyValue.value) {
326
+ magicString.overwrite(propertyValue.start, propertyValue.end, "true");
327
+ }
328
+ }
316
329
  if (trustedFastMode && trustedFastModeProperty === void 0) {
317
330
  missingProperties.push("trustedFastMode: true");
318
331
  } else if (trustedFastModeProperty !== void 0) {
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/initializer.ts","../src/setup.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\n\nimport { runSpotPatchBridgeCli } from \"@spotpatch/bridge\";\n\nimport {\n applyViteIntegrationPlan,\n checkViteIntegration,\n planViteIntegration,\n} from \"./initializer.js\";\nimport { detectPackageManager, installCurrentAdapter } from \"./setup.js\";\n\nconst VERSION_PATTERN = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-[0-9A-Za-z.-]+)?$/u;\n\nfunction writeUsage(): void {\n process.stderr.write(\n \"Usage: spotpatch-vite <setup|init|check|connect|bridge>\\n\" +\n \" setup Install this CLI's exact @spotpatch/vite version, then initialize it.\\n\" +\n \" init Preview and apply safe Vite integration changes.\\n\" +\n \" check Verify the Vite integration without writing files.\\n\" +\n \" connect codex Start the zero-setup Codex Agent connector.\\n\" +\n \" bridge Run the local external-Agent MCP, CLI, or setup commands.\\n\",\n );\n}\n\nasync function inspectViteProject(appRoot = process.cwd()): Promise<string> {\n const resolveFromApplication = createRequire(path.join(appRoot, \"package.json\"));\n let adapterEntry: string;\n let viteManifestPath: string;\n\n try {\n adapterEntry = resolveFromApplication.resolve(\"@spotpatch/vite\");\n viteManifestPath = resolveFromApplication.resolve(\"vite/package.json\");\n } catch (error: unknown) {\n throw new Error(\n \"SpotPatch could not resolve the local @spotpatch/vite and Vite packages.\",\n { cause: error },\n );\n }\n\n if (adapterEntry.length === 0) {\n throw new Error(\"SpotPatch could not resolve the Vite adapter export.\");\n }\n\n const manifest = JSON.parse(await readFile(viteManifestPath, \"utf8\")) as unknown;\n const version =\n typeof manifest === \"object\" &&\n manifest !== null &&\n \"version\" in manifest &&\n typeof manifest.version === \"string\"\n ? manifest.version\n : undefined;\n const match = version === undefined ? null : VERSION_PATTERN.exec(version);\n const major = Number(match?.[1]);\n\n if (\n version === undefined ||\n match === null ||\n !Number.isSafeInteger(major) ||\n major < 5 ||\n major >= 8\n ) {\n throw new Error(\n `SpotPatch Vite requires Vite >=5.0.0 <8.0.0; found ${version ?? \"unknown\"}.`,\n );\n }\n\n return version;\n}\n\nfunction writeTrustedModeStatus(available: boolean): void {\n process.stdout.write(\n available\n ? \"[spotpatch:vite] trusted fast mode is available in the page selector.\\n\"\n : \"[spotpatch:vite] review mode is ready; trusted fast mode needs a local TypeScript project check.\\n\",\n );\n}\n\nasync function runInit(arguments_: readonly string[]): Promise<number> {\n if (arguments_.length !== 0) {\n throw new Error(\"SpotPatch init does not accept positional arguments.\");\n }\n\n await inspectViteProject();\n const plan = await planViteIntegration();\n\n if (plan.changes.length === 0) {\n process.stdout.write(\"[spotpatch:vite] integration is already up to date.\\n\");\n writeTrustedModeStatus(plan.trustedFastModeAvailable);\n return 0;\n }\n\n process.stdout.write(\"[spotpatch:vite] integration preview (resulting files):\\n\");\n\n for (const change of plan.changes) {\n process.stdout.write(`\\n--- ${change.relativePath}\\n${change.nextContent}`);\n\n if (!change.nextContent.endsWith(\"\\n\")) {\n process.stdout.write(\"\\n\");\n }\n }\n\n await applyViteIntegrationPlan(plan);\n process.stdout.write(\n `[spotpatch:vite] updated ${String(plan.changes.length)} integration file(s).\\n`,\n );\n writeTrustedModeStatus(plan.trustedFastModeAvailable);\n\n return 0;\n}\n\nasync function runSetup(arguments_: readonly string[]): Promise<number> {\n if (arguments_.length !== 0) {\n throw new Error(\"SpotPatch setup does not accept positional arguments.\");\n }\n\n const packageManager = await detectPackageManager();\n await installCurrentAdapter(packageManager);\n return runInit([]);\n}\n\nasync function runCheck(arguments_: readonly string[]): Promise<number> {\n if (arguments_.length !== 0) {\n throw new Error(\"SpotPatch check does not accept positional arguments.\");\n }\n\n const version = await inspectViteProject();\n const result = await checkViteIntegration();\n\n if (!result.ok) {\n for (const issue of result.issues) {\n process.stderr.write(`[spotpatch:vite] ${issue}\\n`);\n }\n\n return 1;\n }\n\n const mode = result.trustedFastModeAvailable\n ? \"trusted fast mode available\"\n : \"review mode\";\n process.stdout.write(\n `[spotpatch:vite] integration verified for Vite ${version} · ${mode}.\\n`,\n );\n return 0;\n}\n\nasync function main(arguments_: readonly string[]): Promise<number> {\n const [command, ...rest] = arguments_;\n\n if (command === \"setup\") {\n return runSetup(rest);\n }\n\n if (command === \"init\") {\n return runInit(rest);\n }\n\n if (command === \"check\") {\n return runCheck(rest);\n }\n\n if (command === \"bridge\") {\n return runSpotPatchBridgeCli(rest, { adapter: \"vite\" });\n }\n\n if (command === \"connect\") {\n return runSpotPatchBridgeCli(arguments_, { adapter: \"vite\" });\n }\n\n writeUsage();\n return 1;\n}\n\ntry {\n process.exitCode = await main(process.argv.slice(2));\n} catch (error: unknown) {\n process.stderr.write(\n `[spotpatch:vite] ${\n error instanceof Error ? error.message : \"The command failed.\"\n }\\n`,\n );\n process.exitCode = 1;\n}\n","import path from \"node:path\";\n\nimport {\n applyIntegrationPlan,\n createIntegrationFileChange,\n discoverProjectValidationCheck,\n integrationPathExists,\n readIntegrationFile,\n type IntegrationFileChange,\n} from \"@spotpatch/dev-server\";\nimport { DEFAULT_AGENT_LIMITS } from \"@spotpatch/shared\";\nimport { MagicString } from \"magic-string\";\nimport {\n parseSync,\n Visitor,\n type ArrayExpression,\n type CallExpression,\n type ExportDefaultDeclaration,\n type Expression,\n type ImportDeclaration,\n type ObjectExpression,\n type ObjectProperty,\n type Program,\n type ReturnStatement,\n} from \"oxc-parser\";\n\nconst ADAPTER_PACKAGE_NAME = \"@spotpatch/vite\";\nconst CONFIG_FILE_NAMES = Object.freeze([\n \"vite.config.ts\",\n \"vite.config.mts\",\n \"vite.config.js\",\n \"vite.config.mjs\",\n] as const);\n\nexport interface ViteIntegrationPlan {\n readonly appRoot: string;\n readonly changes: readonly IntegrationFileChange[];\n readonly trustedFastModeAvailable: boolean;\n}\n\nexport interface ViteIntegrationCheck {\n readonly appRoot: string;\n readonly issues: readonly string[];\n readonly ok: boolean;\n readonly trustedFastModeAvailable: boolean;\n}\n\ninterface ParsedModule {\n readonly program: Program;\n readonly source: string;\n}\n\nfunction isParserErrorSeverity(value: unknown): boolean {\n return value === \"Error\";\n}\n\nfunction parseModule(absolutePath: string, source: string): ParsedModule {\n const result = parseSync(absolutePath, source, {\n sourceType: \"module\",\n showSemanticErrors: true,\n });\n const error = result.errors.find((entry) => isParserErrorSeverity(entry.severity));\n\n if (error !== undefined) {\n throw new SyntaxError(\n `SpotPatch could not safely parse ${path.basename(absolutePath)} (${error.message}).`,\n );\n }\n\n return Object.freeze({ program: result.program, source });\n}\n\nfunction importsOf(program: Program): readonly ImportDeclaration[] {\n return program.body.filter(\n (statement): statement is ImportDeclaration =>\n statement.type === \"ImportDeclaration\",\n );\n}\n\nfunction importInsertionOffset(program: Program): number {\n const lastImport = importsOf(program).at(-1);\n\n if (lastImport !== undefined) {\n return lastImport.end;\n }\n\n const directives = program.body.filter(\n (statement) =>\n statement.type === \"ExpressionStatement\" &&\n typeof statement.directive === \"string\",\n );\n return directives.at(-1)?.end ?? program.hashbang?.end ?? 0;\n}\n\nfunction insertStaticImport(\n magicString: MagicString,\n program: Program,\n statement: string,\n): void {\n const offset = importInsertionOffset(program);\n\n if (offset === 0) {\n magicString.prepend(`${statement}\\n`);\n return;\n }\n\n magicString.appendRight(offset, `\\n${statement}`);\n}\n\nfunction importQuote(source: string, program: Program): '\"' | \"'\" {\n const firstImport = importsOf(program)[0];\n\n if (firstImport !== undefined) {\n const quote = source[firstImport.source.start];\n\n if (quote === '\"' || quote === \"'\") {\n return quote;\n }\n }\n\n return '\"';\n}\n\nfunction collectIdentifierNames(program: Program): ReadonlySet<string> {\n const names = new Set<string>();\n new Visitor({\n Identifier(node) {\n names.add(node.name);\n },\n }).visit(program);\n return names;\n}\n\nfunction choosePluginName(program: Program): string {\n const names = collectIdentifierNames(program);\n let suffix = 0;\n let candidate = \"spotPatch\";\n\n while (names.has(candidate)) {\n suffix += 1;\n candidate = `spotPatch${String(suffix)}`;\n }\n\n return candidate;\n}\n\nfunction importedPluginName(program: Program): string | undefined {\n const adapterImports = importsOf(program).filter(\n (statement) => statement.source.value === ADAPTER_PACKAGE_NAME,\n );\n\n if (adapterImports.length > 1) {\n throw new Error(\"SpotPatch init found duplicate @spotpatch/vite imports.\");\n }\n\n const adapterImport = adapterImports[0];\n\n if (adapterImport === undefined) {\n return undefined;\n }\n\n const plugin = adapterImport.specifiers.find(\n (specifier) =>\n specifier.type === \"ImportSpecifier\" &&\n specifier.imported.type === \"Identifier\" &&\n specifier.imported.name === \"spotPatch\" &&\n specifier.importKind !== \"type\",\n );\n\n if (plugin === undefined) {\n throw new Error(\n \"SpotPatch init cannot safely merge the existing @spotpatch/vite import.\",\n );\n }\n\n return plugin.local.name;\n}\n\nfunction unwrapExpression(expression: Expression): Expression {\n let current = expression;\n\n while (\n current.type === \"ParenthesizedExpression\" ||\n current.type === \"TSAsExpression\" ||\n current.type === \"TSSatisfiesExpression\" ||\n current.type === \"TSTypeAssertion\" ||\n current.type === \"TSNonNullExpression\"\n ) {\n current = current.expression;\n }\n\n return current;\n}\n\nfunction findDefaultExport(program: Program): ExportDefaultDeclaration {\n const exports = program.body.filter(\n (statement): statement is ExportDefaultDeclaration =>\n statement.type === \"ExportDefaultDeclaration\",\n );\n\n if (exports.length !== 1 || exports[0] === undefined) {\n throw new Error(\n \"SpotPatch init requires exactly one ESM default export in vite.config.\",\n );\n }\n\n return exports[0];\n}\n\nfunction findVariableInitializer(\n program: Program,\n name: string,\n): Expression | undefined {\n for (const statement of program.body) {\n if (statement.type !== \"VariableDeclaration\") {\n continue;\n }\n\n for (const declaration of statement.declarations) {\n if (\n declaration.id.type === \"Identifier\" &&\n declaration.id.name === name &&\n declaration.init !== null\n ) {\n return declaration.init;\n }\n }\n }\n\n return undefined;\n}\n\nfunction resolveConfigExpression(program: Program): Expression {\n const exported = findDefaultExport(program).declaration;\n\n if (\n exported.type === \"FunctionDeclaration\" ||\n exported.type === \"ClassDeclaration\" ||\n exported.type === \"TSInterfaceDeclaration\"\n ) {\n throw new Error(\n \"SpotPatch init requires vite.config to export a configuration expression.\",\n );\n }\n\n const expression = unwrapExpression(exported);\n const resolved =\n expression.type === \"Identifier\"\n ? findVariableInitializer(program, expression.name)\n : expression;\n\n if (resolved === undefined) {\n throw new Error(\"SpotPatch init could not resolve the vite.config export.\");\n }\n\n return unwrapExpression(resolved);\n}\n\nfunction resolveFactoryConfigObject(\n expression: Expression,\n): ObjectExpression | undefined {\n const factory = unwrapExpression(expression);\n\n if (\n factory.type !== \"ArrowFunctionExpression\" &&\n factory.type !== \"FunctionExpression\"\n ) {\n return undefined;\n }\n\n if (factory.body === null) {\n throw new Error(\n \"SpotPatch init cannot use a defineConfig callback without a body.\",\n );\n }\n\n if (factory.body.type !== \"BlockStatement\") {\n const returned = unwrapExpression(factory.body);\n return returned.type === \"ObjectExpression\" ? returned : undefined;\n }\n\n const returns: ReturnStatement[] = [];\n new Visitor({\n ReturnStatement(statement) {\n returns.push(statement);\n },\n }).visit({\n type: \"Program\",\n body: factory.body.body,\n sourceType: \"module\",\n hashbang: null,\n start: factory.body.start,\n end: factory.body.end,\n });\n\n const onlyReturn = returns.length === 1 ? returns[0] : undefined;\n\n if (onlyReturn?.argument == null) {\n throw new Error(\n \"SpotPatch init requires a defineConfig callback with exactly one top-level object return.\",\n );\n }\n\n const returned = unwrapExpression(onlyReturn.argument);\n\n if (returned.type !== \"ObjectExpression\") {\n throw new Error(\n \"SpotPatch init requires the defineConfig callback to return a configuration object directly.\",\n );\n }\n\n return returned;\n}\n\nfunction resolveConfigObject(program: Program): ObjectExpression {\n const expression = resolveConfigExpression(program);\n\n if (expression.type === \"ObjectExpression\") {\n return expression;\n }\n\n if (expression.type === \"CallExpression\") {\n const callee = unwrapExpression(expression.callee);\n const argument = expression.arguments[0];\n\n if (\n callee.type === \"Identifier\" &&\n callee.name === \"defineConfig\" &&\n expression.arguments.length === 1 &&\n argument !== undefined &&\n argument.type !== \"SpreadElement\"\n ) {\n const value = unwrapExpression(argument);\n\n if (value.type === \"ObjectExpression\") {\n return value;\n }\n\n const callbackObject = resolveFactoryConfigObject(value);\n\n if (callbackObject !== undefined) {\n return callbackObject;\n }\n }\n }\n\n throw new Error(\n \"SpotPatch init supports a configuration object or an object-returning callback passed to defineConfig.\",\n );\n}\n\nfunction propertyName(property: ObjectProperty): string | undefined {\n if (property.computed) {\n return undefined;\n }\n\n if (property.key.type === \"Identifier\") {\n return property.key.name;\n }\n\n if (property.key.type === \"Literal\" && typeof property.key.value === \"string\") {\n return property.key.value;\n }\n\n return undefined;\n}\n\nfunction findProperty(\n object: ObjectExpression,\n name: string,\n): ObjectProperty | undefined {\n const matches = object.properties.filter(\n (property): property is ObjectProperty =>\n property.type === \"Property\" && propertyName(property) === name,\n );\n\n if (matches.length > 1) {\n throw new Error(`SpotPatch init found duplicate ${name} properties.`);\n }\n\n return matches[0];\n}\n\nfunction lineIndentAt(source: string, offset: number): string {\n const lineStart = source.lastIndexOf(\"\\n\", Math.max(0, offset - 1)) + 1;\n return /^[\\t ]*/u.exec(source.slice(lineStart, offset))?.[0] ?? \"\";\n}\n\nfunction childIndent(source: string, object: ObjectExpression): string {\n const first = object.properties[0];\n\n if (first !== undefined) {\n return lineIndentAt(source, first.start);\n }\n\n return `${lineIndentAt(source, object.start)} `;\n}\n\nfunction initializedPluginCall(pluginName: string, trustedFastMode: boolean): string {\n const options = [\n \"dataFlow: {}\",\n ...(trustedFastMode ? [\"trustedFastMode: true\"] : []),\n ];\n return `${pluginName}({ ${options.join(\", \")} })`;\n}\n\nfunction directPluginCalls(\n plugins: ArrayExpression,\n pluginName: string,\n): readonly CallExpression[] {\n return plugins.elements.filter((element): element is CallExpression => {\n if (element?.type !== \"CallExpression\") {\n return false;\n }\n\n const callee = unwrapExpression(element.callee);\n return callee.type === \"Identifier\" && callee.name === pluginName;\n });\n}\n\nfunction enableInitializedOptions(\n magicString: MagicString,\n source: string,\n call: CallExpression,\n trustedFastMode: boolean,\n): void {\n if (call.arguments.length === 0) {\n magicString.overwrite(\n call.start,\n call.end,\n initializedPluginCall(source.slice(call.start, call.callee.end), trustedFastMode),\n );\n return;\n }\n\n const argument = call.arguments[0];\n\n if (\n call.arguments.length !== 1 ||\n argument === undefined ||\n argument.type === \"SpreadElement\"\n ) {\n throw new Error(\"SpotPatch init cannot safely update the spotPatch options.\");\n }\n\n const value = unwrapExpression(argument);\n\n if (value.type !== \"ObjectExpression\") {\n throw new Error(\"SpotPatch init requires spotPatch options to be an object.\");\n }\n\n if (value.properties.some((property) => property.type === \"SpreadElement\")) {\n throw new Error(\n \"SpotPatch init cannot prove dataFlow through spread spotPatch options.\",\n );\n }\n\n const dataFlowProperty = findProperty(value, \"dataFlow\");\n const trustedFastModeProperty = findProperty(value, \"trustedFastMode\");\n const missingProperties: string[] = [];\n\n if (dataFlowProperty === undefined) {\n missingProperties.push(\"dataFlow: {}\");\n } else {\n const dataFlowValue = unwrapExpression(dataFlowProperty.value);\n\n if (dataFlowValue.type === \"Literal\" && dataFlowValue.value === false) {\n magicString.overwrite(dataFlowValue.start, dataFlowValue.end, \"{}\");\n } else if (dataFlowValue.type !== \"ObjectExpression\") {\n throw new Error(\n \"SpotPatch init requires dataFlow to be false or an options object.\",\n );\n }\n }\n\n if (trustedFastMode && trustedFastModeProperty === undefined) {\n missingProperties.push(\"trustedFastMode: true\");\n } else if (trustedFastModeProperty !== undefined) {\n const propertyValue = unwrapExpression(trustedFastModeProperty.value);\n\n if (propertyValue.type !== \"Literal\" || typeof propertyValue.value !== \"boolean\") {\n throw new Error(\n \"SpotPatch init requires trustedFastMode to be a boolean literal.\",\n );\n }\n\n if (trustedFastMode && !propertyValue.value) {\n magicString.overwrite(propertyValue.start, propertyValue.end, \"true\");\n }\n }\n\n if (missingProperties.length === 0) return;\n\n const indent = childIndent(source, value);\n\n if (value.properties.length === 0) {\n magicString.appendLeft(value.end - 1, ` ${missingProperties.join(\", \")} `);\n } else {\n magicString.appendLeft(\n value.properties[0]?.start ?? value.end - 1,\n `${missingProperties.join(`,\\n${indent}`)},\\n${indent}`,\n );\n }\n}\n\nfunction addPluginCall(\n magicString: MagicString,\n source: string,\n config: ObjectExpression,\n pluginName: string,\n trustedFastModeAvailable: boolean,\n): void {\n const pluginsProperty = findProperty(config, \"plugins\");\n const call = initializedPluginCall(pluginName, trustedFastModeAvailable);\n\n if (pluginsProperty === undefined) {\n const indent = childIndent(source, config);\n\n if (config.properties.length === 0) {\n magicString.appendLeft(config.end - 1, `\\n${indent}plugins: [${call}],\\n`);\n } else {\n magicString.appendLeft(\n config.properties[0]?.start ?? config.end - 1,\n `plugins: [${call}],\\n${indent}`,\n );\n }\n\n return;\n }\n\n const value = unwrapExpression(pluginsProperty.value);\n\n if (value.type !== \"ArrayExpression\") {\n throw new Error(\"SpotPatch init requires vite.config plugins to be an array.\");\n }\n\n const existing = directPluginCalls(value, pluginName);\n\n if (existing.length > 1) {\n throw new Error(\"SpotPatch init found duplicate spotPatch plugins.\");\n }\n\n if (existing[0] !== undefined) {\n enableInitializedOptions(\n magicString,\n source,\n existing[0],\n trustedFastModeAvailable,\n );\n\n return;\n }\n\n const first = value.elements.find((element) => element !== null);\n\n if (first === undefined) {\n magicString.appendLeft(value.end - 1, call);\n } else if (!source.slice(value.start, first.start).includes(\"\\n\")) {\n magicString.appendLeft(first.start, `${call}, `);\n } else {\n magicString.appendLeft(\n first.start,\n `${call},\\n${lineIndentAt(source, first.start)}`,\n );\n }\n}\n\nfunction transformViteConfig(\n absolutePath: string,\n source: string,\n trustedFastModeAvailable: boolean,\n): string {\n const { program } = parseModule(absolutePath, source);\n const config = resolveConfigObject(program);\n const existingPluginName = importedPluginName(program);\n const pluginName = existingPluginName ?? choosePluginName(program);\n const magicString = new MagicString(source);\n\n if (existingPluginName === undefined) {\n const specifier =\n pluginName === \"spotPatch\" ? \"spotPatch\" : `spotPatch as ${pluginName}`;\n const quote = importQuote(source, program);\n insertStaticImport(\n magicString,\n program,\n `import { ${specifier} } from ${quote}${ADAPTER_PACKAGE_NAME}${quote};`,\n );\n }\n\n addPluginCall(magicString, source, config, pluginName, trustedFastModeAvailable);\n return magicString.toString();\n}\n\nasync function findViteConfig(appRoot: string): Promise<string> {\n const candidates = (\n await Promise.all(\n CONFIG_FILE_NAMES.map(async (name) => {\n const absolutePath = path.join(appRoot, name);\n return (await integrationPathExists(absolutePath)) ? absolutePath : undefined;\n }),\n )\n ).filter((value): value is string => value !== undefined);\n\n if (candidates.length !== 1 || candidates[0] === undefined) {\n throw new Error(\"SpotPatch init requires exactly one supported vite.config file.\");\n }\n\n return candidates[0];\n}\n\nexport async function planViteIntegration(\n directory = process.cwd(),\n): Promise<ViteIntegrationPlan> {\n const appRoot = path.resolve(directory);\n const configPath = await findViteConfig(appRoot);\n const [configSource, discoveredCheck] = await Promise.all([\n readIntegrationFile(configPath),\n discoverProjectValidationCheck({\n appRoot,\n timeoutMs: DEFAULT_AGENT_LIMITS.checkTimeoutMs,\n }),\n ]);\n const trustedFastModeAvailable = discoveredCheck !== undefined;\n const nextContent = transformViteConfig(\n configPath,\n configSource,\n trustedFastModeAvailable,\n );\n const change = createIntegrationFileChange(\n appRoot,\n configPath,\n nextContent,\n configSource,\n );\n\n return Object.freeze({\n appRoot,\n changes: Object.freeze(change === undefined ? [] : [change]),\n trustedFastModeAvailable,\n });\n}\n\nexport async function applyViteIntegrationPlan(\n plan: ViteIntegrationPlan,\n): Promise<void> {\n await applyIntegrationPlan(plan);\n}\n\nexport async function checkViteIntegration(\n directory = process.cwd(),\n): Promise<ViteIntegrationCheck> {\n try {\n const plan = await planViteIntegration(directory);\n const issues = plan.changes.map(\n (change) => `INTEGRATION_REQUIRED:${change.relativePath}`,\n );\n return Object.freeze({\n appRoot: plan.appRoot,\n issues: Object.freeze(issues),\n ok: issues.length === 0,\n trustedFastModeAvailable: plan.trustedFastModeAvailable,\n });\n } catch (error: unknown) {\n return Object.freeze({\n appRoot: path.resolve(directory),\n issues: Object.freeze([\n error instanceof Error ? error.message : \"SpotPatch integration check failed.\",\n ]),\n ok: false,\n trustedFastModeAvailable: false,\n });\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { access, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport type SupportedPackageManager = \"npm\" | \"pnpm\";\n\ninterface ApplicationManifest {\n readonly packageManager?: unknown;\n}\n\nexport interface InstallCommand {\n readonly arguments: readonly string[];\n readonly executable: string;\n}\n\nconst VERSION_PATTERN = /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u;\n\ninterface AdapterManifest {\n readonly version?: unknown;\n}\n\nasync function pathExists(absolutePath: string): Promise<boolean> {\n try {\n await access(absolutePath);\n return true;\n } catch (error: unknown) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error.code === \"ENOENT\" || error.code === \"ENOTDIR\")\n ) {\n return false;\n }\n\n throw error;\n }\n}\n\nexport async function detectPackageManager(\n appRoot = process.cwd(),\n userAgent = process.env.npm_config_user_agent ?? \"\",\n): Promise<SupportedPackageManager> {\n const manifestPath = path.join(appRoot, \"package.json\");\n const manifest = JSON.parse(\n await readFile(manifestPath, \"utf8\"),\n ) as ApplicationManifest;\n const declared = manifest.packageManager;\n\n if (typeof declared === \"string\") {\n const name = declared.split(\"@\", 1)[0];\n\n if (name === \"pnpm\" || name === \"npm\") {\n return name;\n }\n\n throw new Error(\n `SpotPatch setup supports npm and pnpm projects; package.json declares ${declared}.`,\n );\n }\n\n const [hasPnpmLock, hasNpmLock] = await Promise.all([\n pathExists(path.join(appRoot, \"pnpm-lock.yaml\")),\n pathExists(path.join(appRoot, \"package-lock.json\")),\n ]);\n\n if (hasPnpmLock !== hasNpmLock) {\n return hasPnpmLock ? \"pnpm\" : \"npm\";\n }\n\n if (hasPnpmLock && hasNpmLock) {\n throw new Error(\n \"SpotPatch setup found both pnpm-lock.yaml and package-lock.json; remove the stale lockfile or run installation and init separately.\",\n );\n }\n\n if (userAgent.startsWith(\"pnpm/\")) {\n return \"pnpm\";\n }\n\n if (userAgent.startsWith(\"npm/\")) {\n return \"npm\";\n }\n\n throw new Error(\n \"SpotPatch setup could not determine npm or pnpm; run installation and init separately.\",\n );\n}\n\nexport function createInstallCommand(\n packageManager: SupportedPackageManager,\n version: string,\n platform = process.platform,\n): InstallCommand {\n if (!VERSION_PATTERN.test(version)) {\n throw new Error(\"SpotPatch setup could not determine its package version.\");\n }\n\n const packageSpecifier = `@spotpatch/vite@${version}`;\n\n return Object.freeze({\n executable: platform === \"win32\" ? `${packageManager}.cmd` : packageManager,\n arguments: Object.freeze(\n packageManager === \"pnpm\"\n ? [\"add\", \"-D\", packageSpecifier]\n : [\"install\", \"--save-dev\", packageSpecifier],\n ),\n });\n}\n\nexport async function readCurrentAdapterVersion(): Promise<string> {\n const manifest = JSON.parse(\n await readFile(new URL(\"../package.json\", import.meta.url), \"utf8\"),\n ) as AdapterManifest;\n const version = manifest.version;\n\n if (typeof version !== \"string\" || !VERSION_PATTERN.test(version)) {\n throw new Error(\"SpotPatch setup could not determine its package version.\");\n }\n\n return version;\n}\n\nexport async function installCurrentAdapter(\n packageManager: SupportedPackageManager,\n appRoot = process.cwd(),\n): Promise<void> {\n const version = await readCurrentAdapterVersion();\n const command = createInstallCommand(packageManager, version);\n\n process.stdout.write(\n `[spotpatch:vite] installing @spotpatch/vite@${version} with ${packageManager}...\\n`,\n );\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command.executable, command.arguments, {\n cwd: appRoot,\n env: process.env,\n shell: false,\n stdio: \"inherit\",\n });\n\n child.once(\"error\", reject);\n child.once(\"exit\", (code, signal) => {\n if (code === 0) {\n resolve();\n return;\n }\n\n reject(\n new Error(\n `SpotPatch setup installation failed (${signal ?? `exit ${String(code)}`}).`,\n ),\n );\n });\n });\n}\n"],"mappings":";;;AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,qBAAqB;AAC9B,OAAOC,WAAU;AAEjB,SAAS,6BAA6B;;;ACJtC,OAAO,UAAU;AAEjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,4BAA4B;AACrC,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,OAUK;AAEP,IAAM,uBAAuB;AAC7B,IAAM,oBAAoB,OAAO,OAAO;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,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AAI;AACd,eAAW,SAAS,OAAO,QAAQ;AACjC,cAAQ,OAAO,MAAM,oBAAoB,KAAK;AAAA,CAAI;AAAA,IACpD;AAEA,WAAO;AAAA,EACT;AAEA,QAAM,OAAO,OAAO,2BAChB,gCACA;AACJ,UAAQ,OAAO;AAAA,IACb,kDAAkD,OAAO,SAAM,IAAI;AAAA;AAAA,EACrE;AACA,SAAO;AACT;AAEA,eAAe,KAAK,YAAgD;AAClE,QAAM,CAAC,SAAS,GAAG,IAAI,IAAI;AAE3B,MAAI,YAAY,SAAS;AACvB,WAAO,SAAS,IAAI;AAAA,EACtB;AAEA,MAAI,YAAY,QAAQ;AACtB,WAAO,QAAQ,IAAI;AAAA,EACrB;AAEA,MAAI,YAAY,SAAS;AACvB,WAAO,SAAS,IAAI;AAAA,EACtB;AAEA,MAAI,YAAY,UAAU;AACxB,WAAO,sBAAsB,MAAM,EAAE,SAAS,OAAO,CAAC;AAAA,EACxD;AAEA,MAAI,YAAY,WAAW;AACzB,WAAO,sBAAsB,YAAY,EAAE,SAAS,OAAO,CAAC;AAAA,EAC9D;AAEA,aAAW;AACX,SAAO;AACT;AAEA,IAAI;AACF,UAAQ,WAAW,MAAM,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC;AACrD,SAAS,OAAgB;AACvB,UAAQ,OAAO;AAAA,IACb,oBACE,iBAAiB,QAAQ,MAAM,UAAU,qBAC3C;AAAA;AAAA,EACF;AACA,UAAQ,WAAW;AACrB;","names":["readFile","path","returned","path","VERSION_PATTERN","path","readFile"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/initializer.ts","../src/setup.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\n\nimport { runSpotPatchBridgeCli } from \"@spotpatch/bridge\";\n\nimport {\n applyViteIntegrationPlan,\n checkViteIntegration,\n planViteIntegration,\n} from \"./initializer.js\";\nimport { detectPackageManager, installCurrentAdapter } from \"./setup.js\";\n\nconst VERSION_PATTERN = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-[0-9A-Za-z.-]+)?$/u;\n\nfunction writeUsage(): void {\n process.stderr.write(\n \"Usage: spotpatch-vite <setup|init|check|connect|bridge>\\n\" +\n \" setup Install this CLI's exact @spotpatch/vite version, then initialize it.\\n\" +\n \" init Preview and apply safe Vite integration changes.\\n\" +\n \" check Verify the Vite integration without writing files.\\n\" +\n \" connect codex Start the zero-setup Codex Agent connector.\\n\" +\n \" bridge Run the local external-Agent MCP, CLI, or setup commands.\\n\",\n );\n}\n\nasync function inspectViteProject(appRoot = process.cwd()): Promise<string> {\n const resolveFromApplication = createRequire(path.join(appRoot, \"package.json\"));\n let adapterEntry: string;\n let viteManifestPath: string;\n\n try {\n adapterEntry = resolveFromApplication.resolve(\"@spotpatch/vite\");\n viteManifestPath = resolveFromApplication.resolve(\"vite/package.json\");\n } catch (error: unknown) {\n throw new Error(\n \"SpotPatch could not resolve the local @spotpatch/vite and Vite packages.\",\n { cause: error },\n );\n }\n\n if (adapterEntry.length === 0) {\n throw new Error(\"SpotPatch could not resolve the Vite adapter export.\");\n }\n\n const manifest = JSON.parse(await readFile(viteManifestPath, \"utf8\")) as unknown;\n const version =\n typeof manifest === \"object\" &&\n manifest !== null &&\n \"version\" in manifest &&\n typeof manifest.version === \"string\"\n ? manifest.version\n : undefined;\n const match = version === undefined ? null : VERSION_PATTERN.exec(version);\n const major = Number(match?.[1]);\n\n if (\n version === undefined ||\n match === null ||\n !Number.isSafeInteger(major) ||\n major < 5 ||\n major >= 8\n ) {\n throw new Error(\n `SpotPatch Vite requires Vite >=5.0.0 <8.0.0; found ${version ?? \"unknown\"}.`,\n );\n }\n\n return version;\n}\n\nfunction writeTrustedModeStatus(available: boolean): void {\n process.stdout.write(\n available\n ? \"[spotpatch:vite] trusted fast mode is available in the page selector.\\n\"\n : \"[spotpatch:vite] review mode is ready; trusted fast mode needs a local TypeScript project check.\\n\",\n );\n}\n\nasync function runInit(arguments_: readonly string[]): Promise<number> {\n if (arguments_.length !== 0) {\n throw new Error(\"SpotPatch init does not accept positional arguments.\");\n }\n\n await inspectViteProject();\n const plan = await planViteIntegration();\n\n if (plan.changes.length === 0) {\n process.stdout.write(\"[spotpatch:vite] integration is already up to date.\\n\");\n writeTrustedModeStatus(plan.trustedFastModeAvailable);\n return 0;\n }\n\n process.stdout.write(\"[spotpatch:vite] integration preview (resulting files):\\n\");\n\n for (const change of plan.changes) {\n process.stdout.write(`\\n--- ${change.relativePath}\\n${change.nextContent}`);\n\n if (!change.nextContent.endsWith(\"\\n\")) {\n process.stdout.write(\"\\n\");\n }\n }\n\n await applyViteIntegrationPlan(plan);\n process.stdout.write(\n `[spotpatch:vite] updated ${String(plan.changes.length)} integration file(s).\\n`,\n );\n writeTrustedModeStatus(plan.trustedFastModeAvailable);\n\n return 0;\n}\n\nasync function runSetup(arguments_: readonly string[]): Promise<number> {\n if (arguments_.length !== 0) {\n throw new Error(\"SpotPatch setup does not accept positional arguments.\");\n }\n\n const packageManager = await detectPackageManager();\n await installCurrentAdapter(packageManager);\n return runInit([]);\n}\n\nasync function runCheck(arguments_: readonly string[]): Promise<number> {\n if (arguments_.length !== 0) {\n throw new Error(\"SpotPatch check does not accept positional arguments.\");\n }\n\n const version = await inspectViteProject();\n const result = await checkViteIntegration();\n\n if (!result.ok) {\n for (const issue of result.issues) {\n process.stderr.write(`[spotpatch:vite] ${issue}\\n`);\n }\n\n return 1;\n }\n\n const mode = result.trustedFastModeAvailable\n ? \"trusted fast mode available\"\n : \"review mode\";\n process.stdout.write(\n `[spotpatch:vite] integration verified for Vite ${version} · ${mode}.\\n`,\n );\n return 0;\n}\n\nasync function main(arguments_: readonly string[]): Promise<number> {\n const [command, ...rest] = arguments_;\n\n if (command === \"setup\") {\n return runSetup(rest);\n }\n\n if (command === \"init\") {\n return runInit(rest);\n }\n\n if (command === \"check\") {\n return runCheck(rest);\n }\n\n if (command === \"bridge\") {\n return runSpotPatchBridgeCli(rest, { adapter: \"vite\" });\n }\n\n if (command === \"connect\") {\n return runSpotPatchBridgeCli(arguments_, { adapter: \"vite\" });\n }\n\n writeUsage();\n return 1;\n}\n\ntry {\n process.exitCode = await main(process.argv.slice(2));\n} catch (error: unknown) {\n process.stderr.write(\n `[spotpatch:vite] ${\n error instanceof Error ? error.message : \"The command failed.\"\n }\\n`,\n );\n process.exitCode = 1;\n}\n","import path from \"node:path\";\n\nimport {\n applyIntegrationPlan,\n createIntegrationFileChange,\n discoverProjectValidationCheck,\n integrationPathExists,\n readIntegrationFile,\n type IntegrationFileChange,\n} from \"@spotpatch/dev-server\";\nimport { DEFAULT_AGENT_LIMITS } from \"@spotpatch/shared\";\nimport { MagicString } from \"magic-string\";\nimport {\n parseSync,\n Visitor,\n type ArrayExpression,\n type CallExpression,\n type ExportDefaultDeclaration,\n type Expression,\n type ImportDeclaration,\n type ObjectExpression,\n type ObjectProperty,\n type Program,\n type ReturnStatement,\n} from \"oxc-parser\";\n\nconst ADAPTER_PACKAGE_NAME = \"@spotpatch/vite\";\nconst CONFIG_FILE_NAMES = Object.freeze([\n \"vite.config.ts\",\n \"vite.config.mts\",\n \"vite.config.js\",\n \"vite.config.mjs\",\n] as const);\n\nexport interface ViteIntegrationPlan {\n readonly appRoot: string;\n readonly changes: readonly IntegrationFileChange[];\n readonly trustedFastModeAvailable: boolean;\n}\n\nexport interface ViteIntegrationCheck {\n readonly appRoot: string;\n readonly issues: readonly string[];\n readonly ok: boolean;\n readonly trustedFastModeAvailable: boolean;\n}\n\ninterface ParsedModule {\n readonly program: Program;\n readonly source: string;\n}\n\nfunction isParserErrorSeverity(value: unknown): boolean {\n return value === \"Error\";\n}\n\nfunction parseModule(absolutePath: string, source: string): ParsedModule {\n const result = parseSync(absolutePath, source, {\n sourceType: \"module\",\n showSemanticErrors: true,\n });\n const error = result.errors.find((entry) => isParserErrorSeverity(entry.severity));\n\n if (error !== undefined) {\n throw new SyntaxError(\n `SpotPatch could not safely parse ${path.basename(absolutePath)} (${error.message}).`,\n );\n }\n\n return Object.freeze({ program: result.program, source });\n}\n\nfunction importsOf(program: Program): readonly ImportDeclaration[] {\n return program.body.filter(\n (statement): statement is ImportDeclaration =>\n statement.type === \"ImportDeclaration\",\n );\n}\n\nfunction importInsertionOffset(program: Program): number {\n const lastImport = importsOf(program).at(-1);\n\n if (lastImport !== undefined) {\n return lastImport.end;\n }\n\n const directives = program.body.filter(\n (statement) =>\n statement.type === \"ExpressionStatement\" &&\n typeof statement.directive === \"string\",\n );\n return directives.at(-1)?.end ?? program.hashbang?.end ?? 0;\n}\n\nfunction insertStaticImport(\n magicString: MagicString,\n program: Program,\n statement: string,\n): void {\n const offset = importInsertionOffset(program);\n\n if (offset === 0) {\n magicString.prepend(`${statement}\\n`);\n return;\n }\n\n magicString.appendRight(offset, `\\n${statement}`);\n}\n\nfunction importQuote(source: string, program: Program): '\"' | \"'\" {\n const firstImport = importsOf(program)[0];\n\n if (firstImport !== undefined) {\n const quote = source[firstImport.source.start];\n\n if (quote === '\"' || quote === \"'\") {\n return quote;\n }\n }\n\n return '\"';\n}\n\nfunction collectIdentifierNames(program: Program): ReadonlySet<string> {\n const names = new Set<string>();\n new Visitor({\n Identifier(node) {\n names.add(node.name);\n },\n }).visit(program);\n return names;\n}\n\nfunction choosePluginName(program: Program): string {\n const names = collectIdentifierNames(program);\n let suffix = 0;\n let candidate = \"spotPatch\";\n\n while (names.has(candidate)) {\n suffix += 1;\n candidate = `spotPatch${String(suffix)}`;\n }\n\n return candidate;\n}\n\nfunction importedPluginName(program: Program): string | undefined {\n const adapterImports = importsOf(program).filter(\n (statement) => statement.source.value === ADAPTER_PACKAGE_NAME,\n );\n\n if (adapterImports.length > 1) {\n throw new Error(\"SpotPatch init found duplicate @spotpatch/vite imports.\");\n }\n\n const adapterImport = adapterImports[0];\n\n if (adapterImport === undefined) {\n return undefined;\n }\n\n const plugin = adapterImport.specifiers.find(\n (specifier) =>\n specifier.type === \"ImportSpecifier\" &&\n specifier.imported.type === \"Identifier\" &&\n specifier.imported.name === \"spotPatch\" &&\n specifier.importKind !== \"type\",\n );\n\n if (plugin === undefined) {\n throw new Error(\n \"SpotPatch init cannot safely merge the existing @spotpatch/vite import.\",\n );\n }\n\n return plugin.local.name;\n}\n\nfunction unwrapExpression(expression: Expression): Expression {\n let current = expression;\n\n while (\n current.type === \"ParenthesizedExpression\" ||\n current.type === \"TSAsExpression\" ||\n current.type === \"TSSatisfiesExpression\" ||\n current.type === \"TSTypeAssertion\" ||\n current.type === \"TSNonNullExpression\"\n ) {\n current = current.expression;\n }\n\n return current;\n}\n\nfunction findDefaultExport(program: Program): ExportDefaultDeclaration {\n const exports = program.body.filter(\n (statement): statement is ExportDefaultDeclaration =>\n statement.type === \"ExportDefaultDeclaration\",\n );\n\n if (exports.length !== 1 || exports[0] === undefined) {\n throw new Error(\n \"SpotPatch init requires exactly one ESM default export in vite.config.\",\n );\n }\n\n return exports[0];\n}\n\nfunction findVariableInitializer(\n program: Program,\n name: string,\n): Expression | undefined {\n for (const statement of program.body) {\n if (statement.type !== \"VariableDeclaration\") {\n continue;\n }\n\n for (const declaration of statement.declarations) {\n if (\n declaration.id.type === \"Identifier\" &&\n declaration.id.name === name &&\n declaration.init !== null\n ) {\n return declaration.init;\n }\n }\n }\n\n return undefined;\n}\n\nfunction resolveConfigExpression(program: Program): Expression {\n const exported = findDefaultExport(program).declaration;\n\n if (\n exported.type === \"FunctionDeclaration\" ||\n exported.type === \"ClassDeclaration\" ||\n exported.type === \"TSInterfaceDeclaration\"\n ) {\n throw new Error(\n \"SpotPatch init requires vite.config to export a configuration expression.\",\n );\n }\n\n const expression = unwrapExpression(exported);\n const resolved =\n expression.type === \"Identifier\"\n ? findVariableInitializer(program, expression.name)\n : expression;\n\n if (resolved === undefined) {\n throw new Error(\"SpotPatch init could not resolve the vite.config export.\");\n }\n\n return unwrapExpression(resolved);\n}\n\nfunction resolveFactoryConfigObject(\n expression: Expression,\n): ObjectExpression | undefined {\n const factory = unwrapExpression(expression);\n\n if (\n factory.type !== \"ArrowFunctionExpression\" &&\n factory.type !== \"FunctionExpression\"\n ) {\n return undefined;\n }\n\n if (factory.body === null) {\n throw new Error(\n \"SpotPatch init cannot use a defineConfig callback without a body.\",\n );\n }\n\n if (factory.body.type !== \"BlockStatement\") {\n const returned = unwrapExpression(factory.body);\n return returned.type === \"ObjectExpression\" ? returned : undefined;\n }\n\n const returns: ReturnStatement[] = [];\n new Visitor({\n ReturnStatement(statement) {\n returns.push(statement);\n },\n }).visit({\n type: \"Program\",\n body: factory.body.body,\n sourceType: \"module\",\n hashbang: null,\n start: factory.body.start,\n end: factory.body.end,\n });\n\n const onlyReturn = returns.length === 1 ? returns[0] : undefined;\n\n if (onlyReturn?.argument == null) {\n throw new Error(\n \"SpotPatch init requires a defineConfig callback with exactly one top-level object return.\",\n );\n }\n\n const returned = unwrapExpression(onlyReturn.argument);\n\n if (returned.type !== \"ObjectExpression\") {\n throw new Error(\n \"SpotPatch init requires the defineConfig callback to return a configuration object directly.\",\n );\n }\n\n return returned;\n}\n\nfunction resolveConfigObject(program: Program): ObjectExpression {\n const expression = resolveConfigExpression(program);\n\n if (expression.type === \"ObjectExpression\") {\n return expression;\n }\n\n if (expression.type === \"CallExpression\") {\n const callee = unwrapExpression(expression.callee);\n const argument = expression.arguments[0];\n\n if (\n callee.type === \"Identifier\" &&\n callee.name === \"defineConfig\" &&\n expression.arguments.length === 1 &&\n argument !== undefined &&\n argument.type !== \"SpreadElement\"\n ) {\n const value = unwrapExpression(argument);\n\n if (value.type === \"ObjectExpression\") {\n return value;\n }\n\n const callbackObject = resolveFactoryConfigObject(value);\n\n if (callbackObject !== undefined) {\n return callbackObject;\n }\n }\n }\n\n throw new Error(\n \"SpotPatch init supports a configuration object or an object-returning callback passed to defineConfig.\",\n );\n}\n\nfunction propertyName(property: ObjectProperty): string | undefined {\n if (property.computed) {\n return undefined;\n }\n\n if (property.key.type === \"Identifier\") {\n return property.key.name;\n }\n\n if (property.key.type === \"Literal\" && typeof property.key.value === \"string\") {\n return property.key.value;\n }\n\n return undefined;\n}\n\nfunction findProperty(\n object: ObjectExpression,\n name: string,\n): ObjectProperty | undefined {\n const matches = object.properties.filter(\n (property): property is ObjectProperty =>\n property.type === \"Property\" && propertyName(property) === name,\n );\n\n if (matches.length > 1) {\n throw new Error(`SpotPatch init found duplicate ${name} properties.`);\n }\n\n return matches[0];\n}\n\nfunction lineIndentAt(source: string, offset: number): string {\n const lineStart = source.lastIndexOf(\"\\n\", Math.max(0, offset - 1)) + 1;\n return /^[\\t ]*/u.exec(source.slice(lineStart, offset))?.[0] ?? \"\";\n}\n\nfunction childIndent(source: string, object: ObjectExpression): string {\n const first = object.properties[0];\n\n if (first !== undefined) {\n return lineIndentAt(source, first.start);\n }\n\n return `${lineIndentAt(source, object.start)} `;\n}\n\nfunction initializedPluginCall(pluginName: string, trustedFastMode: boolean): string {\n const options = [\n \"dataFlow: {}\",\n \"externalAgent: true\",\n ...(trustedFastMode ? [\"trustedFastMode: true\"] : []),\n ];\n return `${pluginName}({ ${options.join(\", \")} })`;\n}\n\nfunction directPluginCalls(\n plugins: ArrayExpression,\n pluginName: string,\n): readonly CallExpression[] {\n return plugins.elements.filter((element): element is CallExpression => {\n if (element?.type !== \"CallExpression\") {\n return false;\n }\n\n const callee = unwrapExpression(element.callee);\n return callee.type === \"Identifier\" && callee.name === pluginName;\n });\n}\n\nfunction enableInitializedOptions(\n magicString: MagicString,\n source: string,\n call: CallExpression,\n trustedFastMode: boolean,\n): void {\n if (call.arguments.length === 0) {\n magicString.overwrite(\n call.start,\n call.end,\n initializedPluginCall(source.slice(call.start, call.callee.end), trustedFastMode),\n );\n return;\n }\n\n const argument = call.arguments[0];\n\n if (\n call.arguments.length !== 1 ||\n argument === undefined ||\n argument.type === \"SpreadElement\"\n ) {\n throw new Error(\"SpotPatch init cannot safely update the spotPatch options.\");\n }\n\n const value = unwrapExpression(argument);\n\n if (value.type !== \"ObjectExpression\") {\n throw new Error(\"SpotPatch init requires spotPatch options to be an object.\");\n }\n\n if (value.properties.some((property) => property.type === \"SpreadElement\")) {\n throw new Error(\n \"SpotPatch init cannot prove dataFlow through spread spotPatch options.\",\n );\n }\n\n const dataFlowProperty = findProperty(value, \"dataFlow\");\n const externalAgentProperty = findProperty(value, \"externalAgent\");\n const trustedFastModeProperty = findProperty(value, \"trustedFastMode\");\n const missingProperties: string[] = [];\n\n if (dataFlowProperty === undefined) {\n missingProperties.push(\"dataFlow: {}\");\n } else {\n const dataFlowValue = unwrapExpression(dataFlowProperty.value);\n\n if (dataFlowValue.type === \"Literal\" && dataFlowValue.value === false) {\n magicString.overwrite(dataFlowValue.start, dataFlowValue.end, \"{}\");\n } else if (dataFlowValue.type !== \"ObjectExpression\") {\n throw new Error(\n \"SpotPatch init requires dataFlow to be false or an options object.\",\n );\n }\n }\n\n if (externalAgentProperty === undefined) {\n missingProperties.push(\"externalAgent: true\");\n } else {\n const propertyValue = unwrapExpression(externalAgentProperty.value);\n\n if (propertyValue.type !== \"Literal\" || typeof propertyValue.value !== \"boolean\") {\n throw new Error(\"SpotPatch init requires externalAgent to be a boolean literal.\");\n }\n\n if (!propertyValue.value) {\n magicString.overwrite(propertyValue.start, propertyValue.end, \"true\");\n }\n }\n\n if (trustedFastMode && trustedFastModeProperty === undefined) {\n missingProperties.push(\"trustedFastMode: true\");\n } else if (trustedFastModeProperty !== undefined) {\n const propertyValue = unwrapExpression(trustedFastModeProperty.value);\n\n if (propertyValue.type !== \"Literal\" || typeof propertyValue.value !== \"boolean\") {\n throw new Error(\n \"SpotPatch init requires trustedFastMode to be a boolean literal.\",\n );\n }\n\n if (trustedFastMode && !propertyValue.value) {\n magicString.overwrite(propertyValue.start, propertyValue.end, \"true\");\n }\n }\n\n if (missingProperties.length === 0) return;\n\n const indent = childIndent(source, value);\n\n if (value.properties.length === 0) {\n magicString.appendLeft(value.end - 1, ` ${missingProperties.join(\", \")} `);\n } else {\n magicString.appendLeft(\n value.properties[0]?.start ?? value.end - 1,\n `${missingProperties.join(`,\\n${indent}`)},\\n${indent}`,\n );\n }\n}\n\nfunction addPluginCall(\n magicString: MagicString,\n source: string,\n config: ObjectExpression,\n pluginName: string,\n trustedFastModeAvailable: boolean,\n): void {\n const pluginsProperty = findProperty(config, \"plugins\");\n const call = initializedPluginCall(pluginName, trustedFastModeAvailable);\n\n if (pluginsProperty === undefined) {\n const indent = childIndent(source, config);\n\n if (config.properties.length === 0) {\n magicString.appendLeft(config.end - 1, `\\n${indent}plugins: [${call}],\\n`);\n } else {\n magicString.appendLeft(\n config.properties[0]?.start ?? config.end - 1,\n `plugins: [${call}],\\n${indent}`,\n );\n }\n\n return;\n }\n\n const value = unwrapExpression(pluginsProperty.value);\n\n if (value.type !== \"ArrayExpression\") {\n throw new Error(\"SpotPatch init requires vite.config plugins to be an array.\");\n }\n\n const existing = directPluginCalls(value, pluginName);\n\n if (existing.length > 1) {\n throw new Error(\"SpotPatch init found duplicate spotPatch plugins.\");\n }\n\n if (existing[0] !== undefined) {\n enableInitializedOptions(\n magicString,\n source,\n existing[0],\n trustedFastModeAvailable,\n );\n\n return;\n }\n\n const first = value.elements.find((element) => element !== null);\n\n if (first === undefined) {\n magicString.appendLeft(value.end - 1, call);\n } else if (!source.slice(value.start, first.start).includes(\"\\n\")) {\n magicString.appendLeft(first.start, `${call}, `);\n } else {\n magicString.appendLeft(\n first.start,\n `${call},\\n${lineIndentAt(source, first.start)}`,\n );\n }\n}\n\nfunction transformViteConfig(\n absolutePath: string,\n source: string,\n trustedFastModeAvailable: boolean,\n): string {\n const { program } = parseModule(absolutePath, source);\n const config = resolveConfigObject(program);\n const existingPluginName = importedPluginName(program);\n const pluginName = existingPluginName ?? choosePluginName(program);\n const magicString = new MagicString(source);\n\n if (existingPluginName === undefined) {\n const specifier =\n pluginName === \"spotPatch\" ? \"spotPatch\" : `spotPatch as ${pluginName}`;\n const quote = importQuote(source, program);\n insertStaticImport(\n magicString,\n program,\n `import { ${specifier} } from ${quote}${ADAPTER_PACKAGE_NAME}${quote};`,\n );\n }\n\n addPluginCall(magicString, source, config, pluginName, trustedFastModeAvailable);\n return magicString.toString();\n}\n\nasync function findViteConfig(appRoot: string): Promise<string> {\n const candidates = (\n await Promise.all(\n CONFIG_FILE_NAMES.map(async (name) => {\n const absolutePath = path.join(appRoot, name);\n return (await integrationPathExists(absolutePath)) ? absolutePath : undefined;\n }),\n )\n ).filter((value): value is string => value !== undefined);\n\n if (candidates.length !== 1 || candidates[0] === undefined) {\n throw new Error(\"SpotPatch init requires exactly one supported vite.config file.\");\n }\n\n return candidates[0];\n}\n\nexport async function planViteIntegration(\n directory = process.cwd(),\n): Promise<ViteIntegrationPlan> {\n const appRoot = path.resolve(directory);\n const configPath = await findViteConfig(appRoot);\n const [configSource, discoveredCheck] = await Promise.all([\n readIntegrationFile(configPath),\n discoverProjectValidationCheck({\n appRoot,\n timeoutMs: DEFAULT_AGENT_LIMITS.checkTimeoutMs,\n }),\n ]);\n const trustedFastModeAvailable = discoveredCheck !== undefined;\n const nextContent = transformViteConfig(\n configPath,\n configSource,\n trustedFastModeAvailable,\n );\n const change = createIntegrationFileChange(\n appRoot,\n configPath,\n nextContent,\n configSource,\n );\n\n return Object.freeze({\n appRoot,\n changes: Object.freeze(change === undefined ? [] : [change]),\n trustedFastModeAvailable,\n });\n}\n\nexport async function applyViteIntegrationPlan(\n plan: ViteIntegrationPlan,\n): Promise<void> {\n await applyIntegrationPlan(plan);\n}\n\nexport async function checkViteIntegration(\n directory = process.cwd(),\n): Promise<ViteIntegrationCheck> {\n try {\n const plan = await planViteIntegration(directory);\n const issues = plan.changes.map(\n (change) => `INTEGRATION_REQUIRED:${change.relativePath}`,\n );\n return Object.freeze({\n appRoot: plan.appRoot,\n issues: Object.freeze(issues),\n ok: issues.length === 0,\n trustedFastModeAvailable: plan.trustedFastModeAvailable,\n });\n } catch (error: unknown) {\n return Object.freeze({\n appRoot: path.resolve(directory),\n issues: Object.freeze([\n error instanceof Error ? error.message : \"SpotPatch integration check failed.\",\n ]),\n ok: false,\n trustedFastModeAvailable: false,\n });\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { access, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport type SupportedPackageManager = \"npm\" | \"pnpm\";\n\ninterface ApplicationManifest {\n readonly packageManager?: unknown;\n}\n\nexport interface InstallCommand {\n readonly arguments: readonly string[];\n readonly executable: string;\n}\n\nconst VERSION_PATTERN = /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u;\n\ninterface AdapterManifest {\n readonly version?: unknown;\n}\n\nasync function pathExists(absolutePath: string): Promise<boolean> {\n try {\n await access(absolutePath);\n return true;\n } catch (error: unknown) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error.code === \"ENOENT\" || error.code === \"ENOTDIR\")\n ) {\n return false;\n }\n\n throw error;\n }\n}\n\nexport async function detectPackageManager(\n appRoot = process.cwd(),\n userAgent = process.env.npm_config_user_agent ?? \"\",\n): Promise<SupportedPackageManager> {\n const manifestPath = path.join(appRoot, \"package.json\");\n const manifest = JSON.parse(\n await readFile(manifestPath, \"utf8\"),\n ) as ApplicationManifest;\n const declared = manifest.packageManager;\n\n if (typeof declared === \"string\") {\n const name = declared.split(\"@\", 1)[0];\n\n if (name === \"pnpm\" || name === \"npm\") {\n return name;\n }\n\n throw new Error(\n `SpotPatch setup supports npm and pnpm projects; package.json declares ${declared}.`,\n );\n }\n\n const [hasPnpmLock, hasNpmLock] = await Promise.all([\n pathExists(path.join(appRoot, \"pnpm-lock.yaml\")),\n pathExists(path.join(appRoot, \"package-lock.json\")),\n ]);\n\n if (hasPnpmLock !== hasNpmLock) {\n return hasPnpmLock ? \"pnpm\" : \"npm\";\n }\n\n if (hasPnpmLock && hasNpmLock) {\n throw new Error(\n \"SpotPatch setup found both pnpm-lock.yaml and package-lock.json; remove the stale lockfile or run installation and init separately.\",\n );\n }\n\n if (userAgent.startsWith(\"pnpm/\")) {\n return \"pnpm\";\n }\n\n if (userAgent.startsWith(\"npm/\")) {\n return \"npm\";\n }\n\n throw new Error(\n \"SpotPatch setup could not determine npm or pnpm; run installation and init separately.\",\n );\n}\n\nexport function createInstallCommand(\n packageManager: SupportedPackageManager,\n version: string,\n platform = process.platform,\n): InstallCommand {\n if (!VERSION_PATTERN.test(version)) {\n throw new Error(\"SpotPatch setup could not determine its package version.\");\n }\n\n const packageSpecifier = `@spotpatch/vite@${version}`;\n\n return Object.freeze({\n executable: platform === \"win32\" ? `${packageManager}.cmd` : packageManager,\n arguments: Object.freeze(\n packageManager === \"pnpm\"\n ? [\"add\", \"-D\", packageSpecifier]\n : [\"install\", \"--save-dev\", packageSpecifier],\n ),\n });\n}\n\nexport async function readCurrentAdapterVersion(): Promise<string> {\n const manifest = JSON.parse(\n await readFile(new URL(\"../package.json\", import.meta.url), \"utf8\"),\n ) as AdapterManifest;\n const version = manifest.version;\n\n if (typeof version !== \"string\" || !VERSION_PATTERN.test(version)) {\n throw new Error(\"SpotPatch setup could not determine its package version.\");\n }\n\n return version;\n}\n\nexport async function installCurrentAdapter(\n packageManager: SupportedPackageManager,\n appRoot = process.cwd(),\n): Promise<void> {\n const version = await readCurrentAdapterVersion();\n const command = createInstallCommand(packageManager, version);\n\n process.stdout.write(\n `[spotpatch:vite] installing @spotpatch/vite@${version} with ${packageManager}...\\n`,\n );\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command.executable, command.arguments, {\n cwd: appRoot,\n env: process.env,\n shell: false,\n stdio: \"inherit\",\n });\n\n child.once(\"error\", reject);\n child.once(\"exit\", (code, signal) => {\n if (code === 0) {\n resolve();\n return;\n }\n\n reject(\n new Error(\n `SpotPatch setup installation failed (${signal ?? `exit ${String(code)}`}).`,\n ),\n );\n });\n });\n}\n"],"mappings":";;;AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,qBAAqB;AAC9B,OAAOC,WAAU;AAEjB,SAAS,6BAA6B;;;ACJtC,OAAO,UAAU;AAEjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,E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,CAAC;AAAA,EAC9D;AAEA,aAAW;AACX,SAAO;AACT;AAEA,IAAI;AACF,UAAQ,WAAW,MAAM,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC;AACrD,SAAS,OAAgB;AACvB,UAAQ,OAAO;AAAA,IACb,oBACE,iBAAiB,QAAQ,MAAM,UAAU,qBAC3C;AAAA;AAAA,EACF;AACA,UAAQ,WAAW;AACrB;","names":["readFile","path","returned","path","VERSION_PATTERN","path","readFile"]}
package/dist/index.cjs CHANGED
@@ -51,7 +51,7 @@ var import_dev_server = require("@spotpatch/dev-server");
51
51
  // package.json
52
52
  var package_default = {
53
53
  name: "@spotpatch/vite",
54
- version: "1.10.0",
54
+ version: "1.11.0",
55
55
  description: "Vite development plugin for SpotPatch.",
56
56
  license: "MIT",
57
57
  repository: {
@@ -325,12 +325,19 @@ function createRuntimeInjectionPlugin(input) {
325
325
  // src/server/server-plugin.ts
326
326
  var import_node_path2 = __toESM(require("path"), 1);
327
327
  var import_dev_server2 = require("@spotpatch/dev-server");
328
+ var import_bridge = require("@spotpatch/bridge");
328
329
  function createServerPlugin(input) {
329
330
  let agentManager;
330
331
  let externalHandoffService;
332
+ let externalAgentSupervisor;
333
+ let middleware;
331
334
  let config;
332
335
  const closeResources = async () => {
333
336
  input.registry.clear();
337
+ middleware?.dispose();
338
+ middleware = void 0;
339
+ await externalAgentSupervisor?.dispose();
340
+ externalAgentSupervisor = void 0;
334
341
  await externalHandoffService?.close();
335
342
  externalHandoffService = void 0;
336
343
  await agentManager?.close();
@@ -367,18 +374,38 @@ function createServerPlugin(input) {
367
374
  "[spotpatch:vite] External Agent handoff is unavailable; core tools remain active."
368
375
  );
369
376
  }
377
+ if (externalHandoffService.capability().brokerReady) {
378
+ try {
379
+ const validation = await (0, import_dev_server2.resolveManagedExecutionValidation)({
380
+ ai: options.ai,
381
+ appRoot: root
382
+ });
383
+ externalAgentSupervisor = await (0, import_bridge.createExternalAgentSupervisor)({
384
+ bridgeAdapter: "vite",
385
+ checks: validation.checks,
386
+ limits: validation.limits,
387
+ root,
388
+ sessionId: input.session.id,
389
+ projectLabel: import_node_path2.default.basename(root)
390
+ });
391
+ } catch {
392
+ config.logger.warn(
393
+ "[spotpatch:vite] Managed Agent control is unavailable; Inbox remains active."
394
+ );
395
+ }
396
+ }
370
397
  }
371
- server.middlewares.use(
372
- (0, import_dev_server2.createSpotPatchMiddleware)({
373
- ...agentManager === void 0 ? {} : { agentManager },
374
- ...externalHandoffService === void 0 ? {} : { externalHandoffService },
375
- options,
376
- registry: input.registry,
377
- root,
378
- session: input.session,
379
- logger: config.logger
380
- })
381
- );
398
+ middleware = (0, import_dev_server2.createSpotPatchMiddleware)({
399
+ ...agentManager === void 0 ? {} : { agentManager },
400
+ ...externalAgentSupervisor === void 0 ? {} : { externalAgentControl: externalAgentSupervisor },
401
+ ...externalHandoffService === void 0 ? {} : { externalHandoffService },
402
+ options,
403
+ registry: input.registry,
404
+ root,
405
+ session: input.session,
406
+ logger: config.logger
407
+ });
408
+ server.middlewares.use(middleware);
382
409
  server.httpServer?.once("close", () => {
383
410
  void closeResources();
384
411
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/plugin.ts","../src/runtime/runtime-injection-plugin.ts","../package.json","../../runtime/src/ui/brand-mark-content.ts","../src/server/server-plugin.ts","../src/transform/transform-plugin.ts","../src/transform/transform-filter.ts","../src/options.ts"],"sourcesContent":["export { spotPatch } from \"./plugin.js\";\nexport {\n DEFAULT_OPTIONS,\n resolveOptions,\n type ResolvedSpotPatchOptions,\n type SimpleAiOptions,\n type SpotPatchAiOptions,\n type SpotPatchDataFlowOptions,\n type SpotPatchOptions,\n type ViteSpotPatchOptions,\n} from \"./options.js\";\nexport {\n DEFAULT_AGENT_LIMITS,\n type AgentApplyMode,\n type AgentCheckDefinition,\n type AgentLimits,\n type AiExecutionOptions,\n type AiModelProfile,\n type AiOptions,\n type AiProviderAuthentication,\n type AiProviderProtocol,\n type ContextBudget,\n type OpenAICompatibleProviderOptions,\n type SpotPatchEditorPreference,\n} from \"@spotpatch/shared\";\n","import path from \"node:path\";\n\nimport {\n createSession,\n createSourceRegistry,\n resolveCredentialEnvironment,\n resolveEnvironmentAiConfiguration,\n resolveOptions,\n resolveProjectOptions,\n} from \"@spotpatch/dev-server\";\nimport { loadEnv, type ConfigEnv, type Plugin, type UserConfig } from \"vite\";\n\nimport type { ViteSpotPatchOptions } from \"./options.js\";\nimport type { SpotPatchPluginContext } from \"./plugin-context.js\";\nimport { createRuntimeInjectionPlugin } from \"./runtime/runtime-injection-plugin.js\";\nimport { createServerPlugin } from \"./server/server-plugin.js\";\nimport { createTransformPlugin } from \"./transform/transform-plugin.js\";\n\nexport function spotPatch(userOptions: ViteSpotPatchOptions = {}): Plugin[] {\n let options = resolveOptions(userOptions);\n let credentialEnvironment: Readonly<Record<string, string | undefined>> =\n Object.freeze({});\n\n if (!options.enabled) {\n return [];\n }\n\n const registry = createSourceRegistry();\n const session = createSession();\n const context = Object.freeze({\n getCredentialEnvironment: () => credentialEnvironment,\n getOptions: () => options,\n } satisfies SpotPatchPluginContext);\n const configure = async (\n config: UserConfig,\n environment: ConfigEnv,\n ): Promise<void> => {\n const root = path.resolve(process.cwd(), config.root ?? \".\");\n const loadedEnvironment =\n config.envDir === false\n ? process.env\n : loadEnv(environment.mode, path.resolve(root, config.envDir ?? \".\"), \"\");\n const environmentAi =\n userOptions.ai === undefined\n ? resolveEnvironmentAiConfiguration(loadedEnvironment).ai\n : false;\n\n options = await resolveProjectOptions({\n appRoot: root,\n environmentAi,\n options: userOptions,\n });\n\n credentialEnvironment = resolveCredentialEnvironment(options, loadedEnvironment);\n };\n\n return [\n createTransformPlugin({ configure, context, registry }),\n createRuntimeInjectionPlugin({ context, session }),\n createServerPlugin({ context, registry, session }),\n ];\n}\n","import { createRequire } from \"node:module\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport {\n createRuntimeAiConfig,\n createRuntimeDataFlowConfig,\n type SpotPatchSession,\n} from \"@spotpatch/dev-server\";\nimport packageMetadata from \"../../package.json\" with { type: \"json\" };\nimport { version as VITE_VERSION, type Plugin } from \"vite\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\nimport { BRAND_MARK_CONTENT } from \"./brand-mark-content.js\";\n\nexport const SPOTPATCH_CLIENT_MODULE_ID = \"virtual:spotpatch/client\";\nexport const RESOLVED_SPOTPATCH_CLIENT_MODULE_ID = `\\0${SPOTPATCH_CLIENT_MODULE_ID}`;\nexport const SPOTPATCH_REACT_ADAPTER_MODULE_ID = \"virtual:spotpatch/react-adapter\";\nexport const RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID = `\\0${SPOTPATCH_REACT_ADAPTER_MODULE_ID}`;\nexport const SPOTPATCH_DATA_FLOW_MODULE_ID = \"virtual:spotpatch/data-flow-runtime\";\nexport const RESOLVED_SPOTPATCH_DATA_FLOW_MODULE_ID = `\\0${SPOTPATCH_DATA_FLOW_MODULE_ID}`;\nexport const SPOTPATCH_DATA_FLOW_PANEL_MODULE_ID = \"virtual:spotpatch/data-flow-panel\";\nexport const RESOLVED_SPOTPATCH_DATA_FLOW_PANEL_MODULE_ID = `\\0${SPOTPATCH_DATA_FLOW_PANEL_MODULE_ID}`;\nexport const SPOTPATCH_EXTERNAL_HANDOFF_PANEL_MODULE_ID =\n \"virtual:spotpatch/external-handoff-panel\";\nexport const RESOLVED_SPOTPATCH_EXTERNAL_HANDOFF_PANEL_MODULE_ID = `\\0${SPOTPATCH_EXTERNAL_HANDOFF_PANEL_MODULE_ID}`;\n\ninterface RuntimeInjectionPluginInput {\n readonly clientBundle?: string;\n readonly context: SpotPatchPluginContext;\n readonly dataFlowPreludeBundle?: string;\n readonly dataFlowPanelBundle?: string;\n readonly externalHandoffPanelBundle?: string;\n readonly reactAdapterBundle?: string;\n readonly session: SpotPatchSession;\n}\n\nfunction createDataFlowPreludeModule(\n input: RuntimeInjectionPluginInput,\n bundle: string,\n): string {\n return [\n `const __SPOTPATCH_DATA_FLOW_CONFIG__ = ${JSON.stringify(input.context.getOptions().dataFlow)};`,\n bundle,\n ].join(\"\\n\");\n}\n\nfunction readRuntimeBundle(root: string, fileName: string): string {\n const resolveFromProject = createRequire(path.join(root, \"package.json\"));\n const packageEntry = resolveFromProject.resolve(\"@spotpatch/vite\");\n const bundlePath = path.join(path.dirname(packageEntry), fileName);\n return readFileSync(bundlePath, \"utf8\");\n}\n\nfunction readConsumerViteVersion(root: string): string {\n try {\n const resolveFromProject = createRequire(path.join(root, \"package.json\"));\n const manifestPath = resolveFromProject.resolve(\"vite/package.json\");\n const manifest = JSON.parse(readFileSync(manifestPath, \"utf8\")) as unknown;\n\n if (\n typeof manifest === \"object\" &&\n manifest !== null &&\n \"version\" in manifest &&\n typeof manifest.version === \"string\"\n ) {\n return manifest.version;\n }\n } catch {\n // Vite itself remains the safe fallback if package metadata is not exported.\n }\n\n return VITE_VERSION;\n}\n\nfunction createClientModule(\n input: RuntimeInjectionPluginInput,\n clientBundle: string,\n viteVersion: string,\n): string {\n const options = input.context.getOptions();\n const runtimeConfig = {\n ai: createRuntimeAiConfig(options.ai),\n budget: options.budget,\n dataFlow: createRuntimeDataFlowConfig(options.dataFlow),\n debug: options.debug,\n editor: options.editor,\n externalAgent: options.externalAgent,\n framework: \"vite\" as const,\n frameworkVersion: viteVersion,\n locale: options.locale,\n maxTargets: options.maxTargets,\n redact: options.redact,\n sessionId: input.session.id,\n sessionToken: input.session.token,\n shortcut: options.shortcut,\n spotPatchVersion: packageMetadata.version,\n };\n\n return [\n ...(options.dataFlow.enabled\n ? [`import ${JSON.stringify(SPOTPATCH_DATA_FLOW_PANEL_MODULE_ID)};`]\n : []),\n ...(options.externalAgent.enabled\n ? [`import ${JSON.stringify(SPOTPATCH_EXTERNAL_HANDOFF_PANEL_MODULE_ID)};`]\n : []),\n `const __SPOTPATCH_BRAND_MARK_CONTENT__ = ${JSON.stringify(BRAND_MARK_CONTENT)};`,\n `const __SPOTPATCH_RUNTIME_CONFIG__ = ${JSON.stringify(runtimeConfig)};`,\n clientBundle,\n ].join(\"\\n\");\n}\n\nexport function createRuntimeInjectionPlugin(\n input: RuntimeInjectionPluginInput,\n): Plugin {\n let root = process.cwd();\n let clientBundle = input.clientBundle;\n let dataFlowPreludeBundle = input.dataFlowPreludeBundle;\n let dataFlowPanelBundle = input.dataFlowPanelBundle;\n let externalHandoffPanelBundle = input.externalHandoffPanelBundle;\n let viteVersion = VITE_VERSION;\n\n return {\n name: \"spotpatch:runtime-injection\",\n apply: \"serve\",\n enforce: \"pre\",\n\n configResolved(config) {\n root = path.resolve(config.root);\n viteVersion = readConsumerViteVersion(root);\n },\n\n resolveId(id, importer) {\n if (id === SPOTPATCH_CLIENT_MODULE_ID) {\n return RESOLVED_SPOTPATCH_CLIENT_MODULE_ID;\n }\n\n if (\n id === \"@spotpatch/react-adapter\" &&\n importer === RESOLVED_SPOTPATCH_CLIENT_MODULE_ID\n ) {\n return RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID;\n }\n\n if (id === SPOTPATCH_DATA_FLOW_MODULE_ID) {\n return RESOLVED_SPOTPATCH_DATA_FLOW_MODULE_ID;\n }\n\n if (id === SPOTPATCH_DATA_FLOW_PANEL_MODULE_ID) {\n return RESOLVED_SPOTPATCH_DATA_FLOW_PANEL_MODULE_ID;\n }\n\n if (id === SPOTPATCH_EXTERNAL_HANDOFF_PANEL_MODULE_ID) {\n return RESOLVED_SPOTPATCH_EXTERNAL_HANDOFF_PANEL_MODULE_ID;\n }\n\n return null;\n },\n\n load(id) {\n if (id === RESOLVED_SPOTPATCH_CLIENT_MODULE_ID) {\n clientBundle ??= readRuntimeBundle(root, \"runtime-client.js\");\n return createClientModule(input, clientBundle, viteVersion);\n }\n\n if (id === RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID) {\n return (\n input.reactAdapterBundle ??\n readRuntimeBundle(root, \"runtime-react-adapter.js\")\n );\n }\n\n if (id === RESOLVED_SPOTPATCH_DATA_FLOW_MODULE_ID) {\n if (!input.context.getOptions().dataFlow.enabled) return null;\n dataFlowPreludeBundle ??= readRuntimeBundle(\n root,\n \"runtime-data-flow-prelude.js\",\n );\n return createDataFlowPreludeModule(input, dataFlowPreludeBundle);\n }\n\n if (id === RESOLVED_SPOTPATCH_DATA_FLOW_PANEL_MODULE_ID) {\n if (!input.context.getOptions().dataFlow.enabled) return null;\n dataFlowPanelBundle ??= readRuntimeBundle(root, \"runtime-data-flow-panel.js\");\n return dataFlowPanelBundle;\n }\n\n if (id === RESOLVED_SPOTPATCH_EXTERNAL_HANDOFF_PANEL_MODULE_ID) {\n if (!input.context.getOptions().externalAgent.enabled) return null;\n externalHandoffPanelBundle ??= readRuntimeBundle(\n root,\n \"runtime-external-handoff-panel.js\",\n );\n return externalHandoffPanelBundle;\n }\n\n return null;\n },\n\n transformIndexHtml() {\n const client = {\n tag: \"script\",\n attrs: {\n type: \"module\",\n src: `/@id/${SPOTPATCH_CLIENT_MODULE_ID}`,\n },\n injectTo: \"head\" as const,\n };\n if (!input.context.getOptions().dataFlow.enabled) {\n return [client];\n }\n\n return [\n {\n tag: \"script\",\n attrs: {\n type: \"module\",\n src: `/@id/${SPOTPATCH_DATA_FLOW_MODULE_ID}`,\n },\n injectTo: \"head-prepend\" as const,\n },\n client,\n ];\n },\n };\n}\n","{\n \"name\": \"@spotpatch/vite\",\n \"version\": \"1.10.0\",\n \"description\": \"Vite development plugin for SpotPatch.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/huanglvjing/spotpatch.git\",\n \"directory\": \"packages/vite\"\n },\n \"homepage\": \"https://github.com/huanglvjing/spotpatch#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/huanglvjing/spotpatch/issues\"\n },\n \"keywords\": [\n \"spotpatch\",\n \"vite\",\n \"react\",\n \"developer-tools\",\n \"ai-agent\"\n ],\n \"type\": \"module\",\n \"sideEffects\": false,\n \"engines\": {\n \"node\": \">=20.19.0\"\n },\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"bin\": {\n \"spotpatch-vite\": \"./dist/cli.js\"\n },\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup src/index.ts --format esm,cjs --dts --sourcemap --clean && tsup --config tsup.cli.config.ts && tsup --config tsup.runtime-client.config.ts && tsup --config tsup.runtime-react-adapter.config.ts && tsup --config tsup.runtime-data-flow-prelude.config.ts && tsup --config tsup.runtime-data-flow-panel.config.ts && tsup --config tsup.runtime-external-handoff-panel.config.ts\",\n \"clean\": \"node --input-type=module -e \\\"import { rmSync } from 'node:fs'; rmSync('dist', { recursive: true, force: true })\\\"\",\n \"typecheck\": \"tsc --noEmit -p tsconfig.json\"\n },\n \"dependencies\": {\n \"@spotpatch/bridge\": \"workspace:^\",\n \"@spotpatch/compiler\": \"workspace:^\",\n \"@spotpatch/dev-server\": \"workspace:^\",\n \"@spotpatch/react-adapter\": \"workspace:^\",\n \"@spotpatch/runtime\": \"workspace:^\",\n \"@spotpatch/shared\": \"workspace:^\",\n \"magic-string\": \"1.1.0\",\n \"oxc-parser\": \"0.143.0\"\n },\n \"peerDependencies\": {\n \"vite\": \"^5.0.0 || ^6.0.0 || ^7.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n }\n}\n","/**\n * Canonical SpotPatch mark from docs/assets/spotpatch-logo-mark.svg.\n *\n * The Vite development injector consumes this trusted asset separately from\n * the core browser bundle so the Runtime gzip budget remains enforceable.\n */\nexport const BRAND_MARK_CONTENT = `\n <defs>\n <linearGradient id=\"locator-gradient\" x1=\"76\" y1=\"92\" x2=\"436\" y2=\"374\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#B61CFF\" />\n <stop offset=\"0.38\" stop-color=\"#6D35FF\" />\n <stop offset=\"0.72\" stop-color=\"#168EFF\" />\n <stop offset=\"1\" stop-color=\"#00D9E9\" />\n </linearGradient>\n <linearGradient id=\"left-code-gradient\" x1=\"165\" y1=\"166\" x2=\"236\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#A51EFF\" />\n <stop offset=\"1\" stop-color=\"#653BFF\" />\n </linearGradient>\n <linearGradient id=\"right-code-gradient\" x1=\"276\" y1=\"166\" x2=\"347\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#158DFF\" />\n <stop offset=\"1\" stop-color=\"#00D8E9\" />\n </linearGradient>\n <linearGradient id=\"bolt-gradient\" x1=\"270\" y1=\"111\" x2=\"252\" y2=\"365\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#6840FF\" />\n <stop offset=\"0.48\" stop-color=\"#257BFF\" />\n <stop offset=\"1\" stop-color=\"#00CBEF\" />\n </linearGradient>\n </defs>\n <path\n fill=\"url(#locator-gradient)\"\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n d=\"M256 52C345.47 52 418 124.53 418 214C418 267.55 391.98 316.24 354.04 348.02L256 468L157.96 348.02C120.02 316.24 94 267.55 94 214C94 124.53 166.53 52 256 52ZM256 88C186.41 88 130 144.41 130 214C130 258.2 152.76 297.08 187.2 319.57L256 403.8L324.8 319.57C359.24 297.08 382 258.2 382 214C382 144.41 325.59 88 256 88Z\"\n />\n <rect x=\"238\" y=\"20\" width=\"36\" height=\"84\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"62\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"366\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <path\n d=\"M213.5 160L158 211.5L213.5 263L238 236.5L211 211.5L238 186.5L213.5 160Z\"\n fill=\"url(#left-code-gradient)\"\n />\n <path\n d=\"M298.5 160L354 211.5L298.5 263L274 236.5L301 211.5L274 186.5L298.5 160Z\"\n fill=\"url(#right-code-gradient)\"\n />\n <path\n d=\"M283 108L232 212L266 253L238 369L302 237L267 198L283 108Z\"\n fill=\"url(#bolt-gradient)\"\n />\n`;\n","import path from \"node:path\";\n\nimport {\n createAgentJobManager,\n createExternalHandoffService,\n createSpotPatchMiddleware,\n type AgentJobManager,\n type ExternalHandoffService,\n type SourceRegistry,\n type SpotPatchSession,\n} from \"@spotpatch/dev-server\";\nimport type { Plugin, ResolvedConfig } from \"vite\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\n\ninterface ServerPluginInput {\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n readonly session: SpotPatchSession;\n}\n\nexport function createServerPlugin(input: ServerPluginInput): Plugin {\n let agentManager: AgentJobManager | undefined;\n let externalHandoffService: ExternalHandoffService | undefined;\n let config: ResolvedConfig | undefined;\n\n const closeResources = async (): Promise<void> => {\n input.registry.clear();\n await externalHandoffService?.close();\n externalHandoffService = undefined;\n await agentManager?.close();\n agentManager = undefined;\n };\n\n return {\n name: \"spotpatch:server\",\n apply: \"serve\",\n enforce: \"pre\",\n\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n },\n\n async configureServer(server) {\n if (config === undefined) {\n throw new Error(\"SpotPatch server initialized before Vite config resolution.\");\n }\n\n const root = path.resolve(config.root);\n const options = input.context.getOptions();\n agentManager =\n options.ai === false\n ? undefined\n : createAgentJobManager({\n ai: options.ai,\n environment: input.context.getCredentialEnvironment(),\n root,\n });\n externalHandoffService = options.externalAgent.enabled\n ? createExternalHandoffService({\n framework: \"vite\",\n root,\n sessionId: input.session.id,\n })\n : undefined;\n\n if (externalHandoffService !== undefined) {\n try {\n await externalHandoffService.start();\n } catch {\n config.logger.warn(\n \"[spotpatch:vite] External Agent handoff is unavailable; core tools remain active.\",\n );\n }\n }\n\n server.middlewares.use(\n createSpotPatchMiddleware({\n ...(agentManager === undefined ? {} : { agentManager }),\n ...(externalHandoffService === undefined ? {} : { externalHandoffService }),\n options,\n registry: input.registry,\n root,\n session: input.session,\n logger: config.logger,\n }),\n );\n\n server.httpServer?.once(\"close\", () => {\n void closeResources();\n });\n\n config.logger.info(\n `[spotpatch:vite] Ready. Toggle picker with ${options.shortcut}.`,\n );\n },\n\n async closeBundle() {\n await closeResources();\n },\n };\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\n\nimport type { ConfigEnv, Plugin, ResolvedConfig, UserConfig } from \"vite\";\nimport { injectSourceMarkers } from \"@spotpatch/compiler\";\nimport type { SourceRegistry } from \"@spotpatch/dev-server\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\nimport { SPOTPATCH_DATA_FLOW_MODULE_ID } from \"../runtime/runtime-injection-plugin.js\";\nimport { createTransformFilter, stripViteQuery } from \"./transform-filter.js\";\n\ninterface TransformPluginInput {\n readonly configure?: (\n config: UserConfig,\n environment: ConfigEnv,\n ) => void | Promise<void>;\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n}\n\ninterface ViteTransformOutput {\n readonly code: string;\n readonly map: string;\n}\n\nfunction createCacheKey(id: string, code: string): string {\n const hash = createHash(\"sha256\").update(code).digest(\"base64url\");\n return `${id}\\0${hash}`;\n}\n\nfunction getDisplayPath(root: string, id: string): string {\n const relative = path.relative(root, stripViteQuery(id));\n return relative.split(path.sep).join(\"/\");\n}\n\nexport function createTransformPlugin(input: TransformPluginInput): Plugin {\n let root = process.cwd();\n let filter = createTransformFilter(root, input.context.getOptions());\n let logger: ResolvedConfig[\"logger\"] | undefined;\n const warnedFiles = new Set<string>();\n const warnedDataFlowDiagnostics = new Set<string>();\n const cache = new Map<string, ViteTransformOutput | null>();\n\n return {\n name: \"spotpatch:transform\",\n apply: \"serve\",\n enforce: \"pre\",\n\n async config(config, environment) {\n await input.configure?.(config, environment);\n },\n\n configResolved(config) {\n root = path.resolve(config.root);\n filter = createTransformFilter(root, input.context.getOptions());\n logger = config.logger;\n },\n\n transform(code, id) {\n if (!filter.shouldTransform(id, code)) {\n return null;\n }\n\n const cleanId = path.resolve(stripViteQuery(id));\n const cacheKey = createCacheKey(cleanId, code);\n\n if (cache.has(cacheKey)) {\n return cache.get(cacheKey) ?? null;\n }\n\n const startedAt = performance.now();\n const options = input.context.getOptions();\n\n try {\n const result = injectSourceMarkers({\n code,\n absolutePath: cleanId,\n root,\n fileId: input.registry.register(cleanId),\n ...(options.dataFlow.enabled\n ? { dataFlow: { helperModule: SPOTPATCH_DATA_FLOW_MODULE_ID } }\n : {}),\n onWarning(warning) {\n logger?.warn(\n `[spotpatch:transform] Existing source marker at ${getDisplayPath(root, id)}:${String(warning.line)}:${String(warning.column)}; preserving application value.`,\n );\n },\n });\n\n if (result?.dataFlow !== undefined) {\n input.registry.registerDataFlowComponents(\n cleanId,\n result.dataFlow.sourceVersion,\n result.dataFlow.anchors.flatMap((anchor) =>\n anchor.kind === \"component\"\n ? [\n {\n componentSourceId: anchor.id,\n line: anchor.line,\n column: anchor.column,\n },\n ]\n : [],\n ),\n );\n for (const diagnostic of result.dataFlow.diagnostics) {\n const warningKey = `${cleanId}:${diagnostic.code}:${String(diagnostic.line)}:${String(diagnostic.column)}`;\n if (warnedDataFlowDiagnostics.has(warningKey)) continue;\n warnedDataFlowDiagnostics.add(warningKey);\n logger?.warn(\n `[spotpatch:data-flow] ${diagnostic.code} at ${getDisplayPath(root, id)}:${String(diagnostic.line)}:${String(diagnostic.column)}; keeping this adapter evidence partial.`,\n );\n }\n }\n\n const output =\n result === undefined\n ? null\n : Object.freeze({\n code: result.code,\n map: result.map.toString(),\n });\n cache.set(cacheKey, output);\n\n if (options.debug) {\n const elapsed = performance.now() - startedAt;\n logger?.info(\n `[spotpatch:transform] ${getDisplayPath(root, id)} ${elapsed.toFixed(2)}ms`,\n );\n }\n\n return output;\n } catch (error: unknown) {\n if (!warnedFiles.has(cleanId)) {\n warnedFiles.add(cleanId);\n const detail =\n options.debug && error instanceof Error ? `: ${error.message}` : \"\";\n logger?.warn(\n `[spotpatch:transform] Failed to transform ${getDisplayPath(root, id)}; using original module${detail}`,\n );\n }\n\n return null;\n }\n },\n };\n}\n","import path from \"node:path\";\n\nimport { createDataFlowSourceFilter, createSourceFilter } from \"@spotpatch/compiler\";\nimport type { ResolvedSpotPatchOptions } from \"@spotpatch/dev-server\";\n\nexport function stripViteQuery(id: string): string {\n const queryIndex = id.indexOf(\"?\");\n return queryIndex === -1 ? id : id.slice(0, queryIndex);\n}\n\nexport { isInsideRoot } from \"@spotpatch/compiler\";\n\nexport interface TransformFilter {\n shouldTransform(id: string, code: string): boolean;\n}\n\nexport function createTransformFilter(\n root: string,\n options: ResolvedSpotPatchOptions,\n): TransformFilter {\n const sourceFilter = createSourceFilter(root, options);\n const dataFlowFilter = createDataFlowSourceFilter(root, {\n include: options.include,\n exclude: options.exclude,\n });\n\n return Object.freeze({\n shouldTransform(id: string, code: string): boolean {\n if (\n id.startsWith(\"\\0\") ||\n id.includes(\"virtual:spotpatch\") ||\n id.includes(\"/packages/vite/\") ||\n id.includes(\"\\\\packages\\\\vite\\\\\")\n ) {\n return false;\n }\n\n const cleanId = stripViteQuery(id);\n const absolutePath = path.resolve(cleanId);\n return (\n sourceFilter.shouldTransform(absolutePath, code) ||\n (options.dataFlow.enabled && dataFlowFilter.shouldTransform(absolutePath, code))\n );\n },\n });\n}\n","export {\n createRuntimeAiConfig,\n DEFAULT_EXCLUDE,\n DEFAULT_OPTIONS,\n resolveOptions,\n} from \"@spotpatch/dev-server\";\nexport type {\n FilterEntry,\n ResolvedSpotPatchOptions,\n SimpleAiOptions,\n SpotPatchAiOptions,\n SpotPatchDataFlowOptions,\n SpotPatchOptions,\n} from \"@spotpatch/dev-server\";\n\nexport type ViteSpotPatchOptions = SharedSpotPatchOptions;\nimport type { SpotPatchOptions as SharedSpotP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WAAW,QACd,QAAQ,UACR,sBAAQ,YAAY,MAAM,kBAAAA,QAAK,QAAQ,MAAM,OAAO,UAAU,GAAG,GAAG,EAAE;AAC5E,UAAM,gBACJ,YAAY,OAAO,aACf,sDAAkC,iBAAiB,EAAE,KACrD;AAEN,cAAU,UAAM,0CAAsB;AAAA,MACpC,SAAS;AAAA,MACT;AAAA,MACA,SAAS;AAAA,IACX,CAAC;AAED,gCAAwB,iDAA6B,SAAS,iBAAiB;AAAA,EACjF;AAEA,SAAO;AAAA,IACL,sBAAsB,EAAE,WAAW,SAAS,SAAS,CAAC;AAAA,IACtD,6BAA6B,EAAE,SAAS,QAAQ,CAAC;AAAA,IACjD,mBAAmB,EAAE,SAAS,UAAU,QAAQ,CAAC;AAAA,EACnD;AACF;;;AO7DA,IAAAC,qBAKO;;;ARMP,oBAaO;","names":["import_node_path","import_dev_server","import_vite","path","VITE_VERSION","import_node_path","import_dev_server","path","import_node_path","import_compiler","import_node_path","import_compiler","path","path","path","import_dev_server"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/plugin.ts","../src/runtime/runtime-injection-plugin.ts","../package.json","../../runtime/src/ui/brand-mark-content.ts","../src/server/server-plugin.ts","../src/transform/transform-plugin.ts","../src/transform/transform-filter.ts","../src/options.ts"],"sourcesContent":["export { spotPatch } from \"./plugin.js\";\nexport {\n DEFAULT_OPTIONS,\n resolveOptions,\n type ResolvedSpotPatchOptions,\n type SimpleAiOptions,\n type SpotPatchAiOptions,\n type SpotPatchDataFlowOptions,\n type SpotPatchOptions,\n type ViteSpotPatchOptions,\n} from \"./options.js\";\nexport {\n DEFAULT_AGENT_LIMITS,\n type AgentApplyMode,\n type AgentCheckDefinition,\n type AgentLimits,\n type AiExecutionOptions,\n type AiModelProfile,\n type AiOptions,\n type AiProviderAuthentication,\n type AiProviderProtocol,\n type ContextBudget,\n type OpenAICompatibleProviderOptions,\n type SpotPatchEditorPreference,\n} from \"@spotpatch/shared\";\n","import path from \"node:path\";\n\nimport {\n createSession,\n createSourceRegistry,\n resolveCredentialEnvironment,\n resolveEnvironmentAiConfiguration,\n resolveOptions,\n resolveProjectOptions,\n} from \"@spotpatch/dev-server\";\nimport { loadEnv, type ConfigEnv, type Plugin, type UserConfig } from \"vite\";\n\nimport type { ViteSpotPatchOptions } from \"./options.js\";\nimport type { SpotPatchPluginContext } from \"./plugin-context.js\";\nimport { createRuntimeInjectionPlugin } from \"./runtime/runtime-injection-plugin.js\";\nimport { createServerPlugin } from \"./server/server-plugin.js\";\nimport { createTransformPlugin } from \"./transform/transform-plugin.js\";\n\nexport function spotPatch(userOptions: ViteSpotPatchOptions = {}): Plugin[] {\n let options = resolveOptions(userOptions);\n let credentialEnvironment: Readonly<Record<string, string | undefined>> =\n Object.freeze({});\n\n if (!options.enabled) {\n return [];\n }\n\n const registry = createSourceRegistry();\n const session = createSession();\n const context = Object.freeze({\n getCredentialEnvironment: () => credentialEnvironment,\n getOptions: () => options,\n } satisfies SpotPatchPluginContext);\n const configure = async (\n config: UserConfig,\n environment: ConfigEnv,\n ): Promise<void> => {\n const root = path.resolve(process.cwd(), config.root ?? \".\");\n const loadedEnvironment =\n config.envDir === false\n ? process.env\n : loadEnv(environment.mode, path.resolve(root, config.envDir ?? \".\"), \"\");\n const environmentAi =\n userOptions.ai === undefined\n ? resolveEnvironmentAiConfiguration(loadedEnvironment).ai\n : false;\n\n options = await resolveProjectOptions({\n appRoot: root,\n environmentAi,\n options: userOptions,\n });\n\n credentialEnvironment = resolveCredentialEnvironment(options, loadedEnvironment);\n };\n\n return [\n createTransformPlugin({ configure, context, registry }),\n createRuntimeInjectionPlugin({ context, session }),\n createServerPlugin({ context, registry, session }),\n ];\n}\n","import { createRequire } from \"node:module\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport {\n createRuntimeAiConfig,\n createRuntimeDataFlowConfig,\n type SpotPatchSession,\n} from \"@spotpatch/dev-server\";\nimport packageMetadata from \"../../package.json\" with { type: \"json\" };\nimport { version as VITE_VERSION, type Plugin } from \"vite\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\nimport { BRAND_MARK_CONTENT } from \"./brand-mark-content.js\";\n\nexport const SPOTPATCH_CLIENT_MODULE_ID = \"virtual:spotpatch/client\";\nexport const RESOLVED_SPOTPATCH_CLIENT_MODULE_ID = `\\0${SPOTPATCH_CLIENT_MODULE_ID}`;\nexport const SPOTPATCH_REACT_ADAPTER_MODULE_ID = \"virtual:spotpatch/react-adapter\";\nexport const RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID = `\\0${SPOTPATCH_REACT_ADAPTER_MODULE_ID}`;\nexport const SPOTPATCH_DATA_FLOW_MODULE_ID = \"virtual:spotpatch/data-flow-runtime\";\nexport const RESOLVED_SPOTPATCH_DATA_FLOW_MODULE_ID = `\\0${SPOTPATCH_DATA_FLOW_MODULE_ID}`;\nexport const SPOTPATCH_DATA_FLOW_PANEL_MODULE_ID = \"virtual:spotpatch/data-flow-panel\";\nexport const RESOLVED_SPOTPATCH_DATA_FLOW_PANEL_MODULE_ID = `\\0${SPOTPATCH_DATA_FLOW_PANEL_MODULE_ID}`;\nexport const SPOTPATCH_EXTERNAL_HANDOFF_PANEL_MODULE_ID =\n \"virtual:spotpatch/external-handoff-panel\";\nexport const RESOLVED_SPOTPATCH_EXTERNAL_HANDOFF_PANEL_MODULE_ID = `\\0${SPOTPATCH_EXTERNAL_HANDOFF_PANEL_MODULE_ID}`;\n\ninterface RuntimeInjectionPluginInput {\n readonly clientBundle?: string;\n readonly context: SpotPatchPluginContext;\n readonly dataFlowPreludeBundle?: string;\n readonly dataFlowPanelBundle?: string;\n readonly externalHandoffPanelBundle?: string;\n readonly reactAdapterBundle?: string;\n readonly session: SpotPatchSession;\n}\n\nfunction createDataFlowPreludeModule(\n input: RuntimeInjectionPluginInput,\n bundle: string,\n): string {\n return [\n `const __SPOTPATCH_DATA_FLOW_CONFIG__ = ${JSON.stringify(input.context.getOptions().dataFlow)};`,\n bundle,\n ].join(\"\\n\");\n}\n\nfunction readRuntimeBundle(root: string, fileName: string): string {\n const resolveFromProject = createRequire(path.join(root, \"package.json\"));\n const packageEntry = resolveFromProject.resolve(\"@spotpatch/vite\");\n const bundlePath = path.join(path.dirname(packageEntry), fileName);\n return readFileSync(bundlePath, \"utf8\");\n}\n\nfunction readConsumerViteVersion(root: string): string {\n try {\n const resolveFromProject = createRequire(path.join(root, \"package.json\"));\n const manifestPath = resolveFromProject.resolve(\"vite/package.json\");\n const manifest = JSON.parse(readFileSync(manifestPath, \"utf8\")) as unknown;\n\n if (\n typeof manifest === \"object\" &&\n manifest !== null &&\n \"version\" in manifest &&\n typeof manifest.version === \"string\"\n ) {\n return manifest.version;\n }\n } catch {\n // Vite itself remains the safe fallback if package metadata is not exported.\n }\n\n return VITE_VERSION;\n}\n\nfunction createClientModule(\n input: RuntimeInjectionPluginInput,\n clientBundle: string,\n viteVersion: string,\n): string {\n const options = input.context.getOptions();\n const runtimeConfig = {\n ai: createRuntimeAiConfig(options.ai),\n budget: options.budget,\n dataFlow: createRuntimeDataFlowConfig(options.dataFlow),\n debug: options.debug,\n editor: options.editor,\n externalAgent: options.externalAgent,\n framework: \"vite\" as const,\n frameworkVersion: viteVersion,\n locale: options.locale,\n maxTargets: options.maxTargets,\n redact: options.redact,\n sessionId: input.session.id,\n sessionToken: input.session.token,\n shortcut: options.shortcut,\n spotPatchVersion: packageMetadata.version,\n };\n\n return [\n ...(options.dataFlow.enabled\n ? [`import ${JSON.stringify(SPOTPATCH_DATA_FLOW_PANEL_MODULE_ID)};`]\n : []),\n ...(options.externalAgent.enabled\n ? [`import ${JSON.stringify(SPOTPATCH_EXTERNAL_HANDOFF_PANEL_MODULE_ID)};`]\n : []),\n `const __SPOTPATCH_BRAND_MARK_CONTENT__ = ${JSON.stringify(BRAND_MARK_CONTENT)};`,\n `const __SPOTPATCH_RUNTIME_CONFIG__ = ${JSON.stringify(runtimeConfig)};`,\n clientBundle,\n ].join(\"\\n\");\n}\n\nexport function createRuntimeInjectionPlugin(\n input: RuntimeInjectionPluginInput,\n): Plugin {\n let root = process.cwd();\n let clientBundle = input.clientBundle;\n let dataFlowPreludeBundle = input.dataFlowPreludeBundle;\n let dataFlowPanelBundle = input.dataFlowPanelBundle;\n let externalHandoffPanelBundle = input.externalHandoffPanelBundle;\n let viteVersion = VITE_VERSION;\n\n return {\n name: \"spotpatch:runtime-injection\",\n apply: \"serve\",\n enforce: \"pre\",\n\n configResolved(config) {\n root = path.resolve(config.root);\n viteVersion = readConsumerViteVersion(root);\n },\n\n resolveId(id, importer) {\n if (id === SPOTPATCH_CLIENT_MODULE_ID) {\n return RESOLVED_SPOTPATCH_CLIENT_MODULE_ID;\n }\n\n if (\n id === \"@spotpatch/react-adapter\" &&\n importer === RESOLVED_SPOTPATCH_CLIENT_MODULE_ID\n ) {\n return RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID;\n }\n\n if (id === SPOTPATCH_DATA_FLOW_MODULE_ID) {\n return RESOLVED_SPOTPATCH_DATA_FLOW_MODULE_ID;\n }\n\n if (id === SPOTPATCH_DATA_FLOW_PANEL_MODULE_ID) {\n return RESOLVED_SPOTPATCH_DATA_FLOW_PANEL_MODULE_ID;\n }\n\n if (id === SPOTPATCH_EXTERNAL_HANDOFF_PANEL_MODULE_ID) {\n return RESOLVED_SPOTPATCH_EXTERNAL_HANDOFF_PANEL_MODULE_ID;\n }\n\n return null;\n },\n\n load(id) {\n if (id === RESOLVED_SPOTPATCH_CLIENT_MODULE_ID) {\n clientBundle ??= readRuntimeBundle(root, \"runtime-client.js\");\n return createClientModule(input, clientBundle, viteVersion);\n }\n\n if (id === RESOLVED_SPOTPATCH_REACT_ADAPTER_MODULE_ID) {\n return (\n input.reactAdapterBundle ??\n readRuntimeBundle(root, \"runtime-react-adapter.js\")\n );\n }\n\n if (id === RESOLVED_SPOTPATCH_DATA_FLOW_MODULE_ID) {\n if (!input.context.getOptions().dataFlow.enabled) return null;\n dataFlowPreludeBundle ??= readRuntimeBundle(\n root,\n \"runtime-data-flow-prelude.js\",\n );\n return createDataFlowPreludeModule(input, dataFlowPreludeBundle);\n }\n\n if (id === RESOLVED_SPOTPATCH_DATA_FLOW_PANEL_MODULE_ID) {\n if (!input.context.getOptions().dataFlow.enabled) return null;\n dataFlowPanelBundle ??= readRuntimeBundle(root, \"runtime-data-flow-panel.js\");\n return dataFlowPanelBundle;\n }\n\n if (id === RESOLVED_SPOTPATCH_EXTERNAL_HANDOFF_PANEL_MODULE_ID) {\n if (!input.context.getOptions().externalAgent.enabled) return null;\n externalHandoffPanelBundle ??= readRuntimeBundle(\n root,\n \"runtime-external-handoff-panel.js\",\n );\n return externalHandoffPanelBundle;\n }\n\n return null;\n },\n\n transformIndexHtml() {\n const client = {\n tag: \"script\",\n attrs: {\n type: \"module\",\n src: `/@id/${SPOTPATCH_CLIENT_MODULE_ID}`,\n },\n injectTo: \"head\" as const,\n };\n if (!input.context.getOptions().dataFlow.enabled) {\n return [client];\n }\n\n return [\n {\n tag: \"script\",\n attrs: {\n type: \"module\",\n src: `/@id/${SPOTPATCH_DATA_FLOW_MODULE_ID}`,\n },\n injectTo: \"head-prepend\" as const,\n },\n client,\n ];\n },\n };\n}\n","{\n \"name\": \"@spotpatch/vite\",\n \"version\": \"1.11.0\",\n \"description\": \"Vite development plugin for SpotPatch.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/huanglvjing/spotpatch.git\",\n \"directory\": \"packages/vite\"\n },\n \"homepage\": \"https://github.com/huanglvjing/spotpatch#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/huanglvjing/spotpatch/issues\"\n },\n \"keywords\": [\n \"spotpatch\",\n \"vite\",\n \"react\",\n \"developer-tools\",\n \"ai-agent\"\n ],\n \"type\": \"module\",\n \"sideEffects\": false,\n \"engines\": {\n \"node\": \">=20.19.0\"\n },\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"bin\": {\n \"spotpatch-vite\": \"./dist/cli.js\"\n },\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup src/index.ts --format esm,cjs --dts --sourcemap --clean && tsup --config tsup.cli.config.ts && tsup --config tsup.runtime-client.config.ts && tsup --config tsup.runtime-react-adapter.config.ts && tsup --config tsup.runtime-data-flow-prelude.config.ts && tsup --config tsup.runtime-data-flow-panel.config.ts && tsup --config tsup.runtime-external-handoff-panel.config.ts\",\n \"clean\": \"node --input-type=module -e \\\"import { rmSync } from 'node:fs'; rmSync('dist', { recursive: true, force: true })\\\"\",\n \"typecheck\": \"tsc --noEmit -p tsconfig.json\"\n },\n \"dependencies\": {\n \"@spotpatch/bridge\": \"workspace:^\",\n \"@spotpatch/compiler\": \"workspace:^\",\n \"@spotpatch/dev-server\": \"workspace:^\",\n \"@spotpatch/react-adapter\": \"workspace:^\",\n \"@spotpatch/runtime\": \"workspace:^\",\n \"@spotpatch/shared\": \"workspace:^\",\n \"magic-string\": \"1.1.0\",\n \"oxc-parser\": \"0.143.0\"\n },\n \"peerDependencies\": {\n \"vite\": \"^5.0.0 || ^6.0.0 || ^7.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n }\n}\n","/**\n * Canonical SpotPatch mark from docs/assets/spotpatch-logo-mark.svg.\n *\n * The Vite development injector consumes this trusted asset separately from\n * the core browser bundle so the Runtime gzip budget remains enforceable.\n */\nexport const BRAND_MARK_CONTENT = `\n <defs>\n <linearGradient id=\"locator-gradient\" x1=\"76\" y1=\"92\" x2=\"436\" y2=\"374\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#B61CFF\" />\n <stop offset=\"0.38\" stop-color=\"#6D35FF\" />\n <stop offset=\"0.72\" stop-color=\"#168EFF\" />\n <stop offset=\"1\" stop-color=\"#00D9E9\" />\n </linearGradient>\n <linearGradient id=\"left-code-gradient\" x1=\"165\" y1=\"166\" x2=\"236\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#A51EFF\" />\n <stop offset=\"1\" stop-color=\"#653BFF\" />\n </linearGradient>\n <linearGradient id=\"right-code-gradient\" x1=\"276\" y1=\"166\" x2=\"347\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#158DFF\" />\n <stop offset=\"1\" stop-color=\"#00D8E9\" />\n </linearGradient>\n <linearGradient id=\"bolt-gradient\" x1=\"270\" y1=\"111\" x2=\"252\" y2=\"365\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#6840FF\" />\n <stop offset=\"0.48\" stop-color=\"#257BFF\" />\n <stop offset=\"1\" stop-color=\"#00CBEF\" />\n </linearGradient>\n </defs>\n <path\n fill=\"url(#locator-gradient)\"\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n d=\"M256 52C345.47 52 418 124.53 418 214C418 267.55 391.98 316.24 354.04 348.02L256 468L157.96 348.02C120.02 316.24 94 267.55 94 214C94 124.53 166.53 52 256 52ZM256 88C186.41 88 130 144.41 130 214C130 258.2 152.76 297.08 187.2 319.57L256 403.8L324.8 319.57C359.24 297.08 382 258.2 382 214C382 144.41 325.59 88 256 88Z\"\n />\n <rect x=\"238\" y=\"20\" width=\"36\" height=\"84\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"62\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"366\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <path\n d=\"M213.5 160L158 211.5L213.5 263L238 236.5L211 211.5L238 186.5L213.5 160Z\"\n fill=\"url(#left-code-gradient)\"\n />\n <path\n d=\"M298.5 160L354 211.5L298.5 263L274 236.5L301 211.5L274 186.5L298.5 160Z\"\n fill=\"url(#right-code-gradient)\"\n />\n <path\n d=\"M283 108L232 212L266 253L238 369L302 237L267 198L283 108Z\"\n fill=\"url(#bolt-gradient)\"\n />\n`;\n","import path from \"node:path\";\n\nimport {\n createAgentJobManager,\n createExternalHandoffService,\n createSpotPatchMiddleware,\n resolveManagedExecutionValidation,\n type AgentJobManager,\n type ExternalHandoffService,\n type SourceRegistry,\n type SpotPatchSession,\n type SpotPatchMiddleware,\n} from \"@spotpatch/dev-server\";\nimport {\n createExternalAgentSupervisor,\n type ExternalAgentSupervisor,\n} from \"@spotpatch/bridge\";\nimport type { Plugin, ResolvedConfig } from \"vite\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\n\ninterface ServerPluginInput {\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n readonly session: SpotPatchSession;\n}\n\nexport function createServerPlugin(input: ServerPluginInput): Plugin {\n let agentManager: AgentJobManager | undefined;\n let externalHandoffService: ExternalHandoffService | undefined;\n let externalAgentSupervisor: ExternalAgentSupervisor | undefined;\n let middleware: SpotPatchMiddleware | undefined;\n let config: ResolvedConfig | undefined;\n\n const closeResources = async (): Promise<void> => {\n input.registry.clear();\n middleware?.dispose();\n middleware = undefined;\n await externalAgentSupervisor?.dispose();\n externalAgentSupervisor = undefined;\n await externalHandoffService?.close();\n externalHandoffService = undefined;\n await agentManager?.close();\n agentManager = undefined;\n };\n\n return {\n name: \"spotpatch:server\",\n apply: \"serve\",\n enforce: \"pre\",\n\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n },\n\n async configureServer(server) {\n if (config === undefined) {\n throw new Error(\"SpotPatch server initialized before Vite config resolution.\");\n }\n\n const root = path.resolve(config.root);\n const options = input.context.getOptions();\n agentManager =\n options.ai === false\n ? undefined\n : createAgentJobManager({\n ai: options.ai,\n environment: input.context.getCredentialEnvironment(),\n root,\n });\n externalHandoffService = options.externalAgent.enabled\n ? createExternalHandoffService({\n framework: \"vite\",\n root,\n sessionId: input.session.id,\n })\n : undefined;\n\n if (externalHandoffService !== undefined) {\n try {\n await externalHandoffService.start();\n } catch {\n config.logger.warn(\n \"[spotpatch:vite] External Agent handoff is unavailable; core tools remain active.\",\n );\n }\n\n if (externalHandoffService.capability().brokerReady) {\n try {\n const validation = await resolveManagedExecutionValidation({\n ai: options.ai,\n appRoot: root,\n });\n externalAgentSupervisor = await createExternalAgentSupervisor({\n bridgeAdapter: \"vite\",\n checks: validation.checks,\n limits: validation.limits,\n root,\n sessionId: input.session.id,\n projectLabel: path.basename(root),\n });\n } catch {\n config.logger.warn(\n \"[spotpatch:vite] Managed Agent control is unavailable; Inbox remains active.\",\n );\n }\n }\n }\n\n middleware = createSpotPatchMiddleware({\n ...(agentManager === undefined ? {} : { agentManager }),\n ...(externalAgentSupervisor === undefined\n ? {}\n : { externalAgentControl: externalAgentSupervisor }),\n ...(externalHandoffService === undefined ? {} : { externalHandoffService }),\n options,\n registry: input.registry,\n root,\n session: input.session,\n logger: config.logger,\n });\n server.middlewares.use(middleware);\n\n server.httpServer?.once(\"close\", () => {\n void closeResources();\n });\n\n config.logger.info(\n `[spotpatch:vite] Ready. Toggle picker with ${options.shortcut}.`,\n );\n },\n\n async closeBundle() {\n await closeResources();\n },\n };\n}\n","import { createHash } from \"node:crypto\";\nimport path from \"node:path\";\n\nimport type { ConfigEnv, Plugin, ResolvedConfig, UserConfig } from \"vite\";\nimport { injectSourceMarkers } from \"@spotpatch/compiler\";\nimport type { SourceRegistry } from \"@spotpatch/dev-server\";\n\nimport type { SpotPatchPluginContext } from \"../plugin-context.js\";\nimport { SPOTPATCH_DATA_FLOW_MODULE_ID } from \"../runtime/runtime-injection-plugin.js\";\nimport { createTransformFilter, stripViteQuery } from \"./transform-filter.js\";\n\ninterface TransformPluginInput {\n readonly configure?: (\n config: UserConfig,\n environment: ConfigEnv,\n ) => void | Promise<void>;\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n}\n\ninterface ViteTransformOutput {\n readonly code: string;\n readonly map: string;\n}\n\nfunction createCacheKey(id: string, code: string): string {\n const hash = createHash(\"sha256\").update(code).digest(\"base64url\");\n return `${id}\\0${hash}`;\n}\n\nfunction getDisplayPath(root: string, id: string): string {\n const relative = path.relative(root, stripViteQuery(id));\n return relative.split(path.sep).join(\"/\");\n}\n\nexport function createTransformPlugin(input: TransformPluginInput): Plugin {\n let root = process.cwd();\n let filter = createTransformFilter(root, input.context.getOptions());\n let logger: ResolvedConfig[\"logger\"] | undefined;\n const warnedFiles = new Set<string>();\n const warnedDataFlowDiagnostics = new Set<string>();\n const cache = new Map<string, ViteTransformOutput | null>();\n\n return {\n name: \"spotpatch:transform\",\n apply: \"serve\",\n enforce: \"pre\",\n\n async config(config, environment) {\n await input.configure?.(config, environment);\n },\n\n configResolved(config) {\n root = path.resolve(config.root);\n filter = createTransformFilter(root, input.context.getOptions());\n logger = config.logger;\n },\n\n transform(code, id) {\n if (!filter.shouldTransform(id, code)) {\n return null;\n }\n\n const cleanId = path.resolve(stripViteQuery(id));\n const cacheKey = createCacheKey(cleanId, code);\n\n if (cache.has(cacheKey)) {\n return cache.get(cacheKey) ?? null;\n }\n\n const startedAt = performance.now();\n const options = input.context.getOptions();\n\n try {\n const result = injectSourceMarkers({\n code,\n absolutePath: cleanId,\n root,\n fileId: input.registry.register(cleanId),\n ...(options.dataFlow.enabled\n ? { dataFlow: { helperModule: SPOTPATCH_DATA_FLOW_MODULE_ID } }\n : {}),\n onWarning(warning) {\n logger?.warn(\n `[spotpatch:transform] Existing source marker at ${getDisplayPath(root, id)}:${String(warning.line)}:${String(warning.column)}; preserving application value.`,\n );\n },\n });\n\n if (result?.dataFlow !== undefined) {\n input.registry.registerDataFlowComponents(\n cleanId,\n result.dataFlow.sourceVersion,\n result.dataFlow.anchors.flatMap((anchor) =>\n anchor.kind === \"component\"\n ? [\n {\n componentSourceId: anchor.id,\n line: anchor.line,\n column: anchor.column,\n },\n ]\n : [],\n ),\n );\n for (const diagnostic of result.dataFlow.diagnostics) {\n const warningKey = `${cleanId}:${diagnostic.code}:${String(diagnostic.line)}:${String(diagnostic.column)}`;\n if (warnedDataFlowDiagnostics.has(warningKey)) continue;\n warnedDataFlowDiagnostics.add(warningKey);\n logger?.warn(\n `[spotpatch:data-flow] ${diagnostic.code} at ${getDisplayPath(root, id)}:${String(diagnostic.line)}:${String(diagnostic.column)}; keeping this adapter evidence partial.`,\n );\n }\n }\n\n const output =\n result === undefined\n ? null\n : Object.freeze({\n code: result.code,\n map: result.map.toString(),\n });\n cache.set(cacheKey, output);\n\n if (options.debug) {\n const elapsed = performance.now() - startedAt;\n logger?.info(\n `[spotpatch:transform] ${getDisplayPath(root, id)} ${elapsed.toFixed(2)}ms`,\n );\n }\n\n return output;\n } catch (error: unknown) {\n if (!warnedFiles.has(cleanId)) {\n warnedFiles.add(cleanId);\n const detail =\n options.debug && error instanceof Error ? `: ${error.message}` : \"\";\n logger?.warn(\n `[spotpatch:transform] Failed to transform ${getDisplayPath(root, id)}; using original module${detail}`,\n );\n }\n\n return null;\n }\n },\n };\n}\n","import path from \"node:path\";\n\nimport { createDataFlowSourceFilter, createSourceFilter } from \"@spotpatch/compiler\";\nimport type { ResolvedSpotPatchOptions } from \"@spotpatch/dev-server\";\n\nexport function stripViteQuery(id: string): string {\n const queryIndex = id.indexOf(\"?\");\n return queryIndex === -1 ? id : id.slice(0, queryIndex);\n}\n\nexport { isInsideRoot } from \"@spotpatch/compiler\";\n\nexport interface TransformFilter {\n shouldTransform(id: string, code: string): boolean;\n}\n\nexport function createTransformFilter(\n root: string,\n options: ResolvedSpotPatchOptions,\n): TransformFilter {\n const sourceFilter = createSourceFilter(root, options);\n const dataFlowFilter = createDataFlowSourceFilter(root, {\n include: options.include,\n exclude: options.exclude,\n });\n\n return Object.freeze({\n shouldTransform(id: string, code: string): boolean {\n if (\n id.startsWith(\"\\0\") ||\n id.includes(\"virtual:spotpatch\") ||\n id.includes(\"/packages/vite/\") ||\n id.includes(\"\\\\packages\\\\vite\\\\\")\n ) {\n return false;\n }\n\n const cleanId = stripViteQuery(id);\n const absolutePath = path.resolve(cleanId);\n return (\n sourceFilter.shouldTransform(absolutePath, code) ||\n (options.dataFlow.enabled && dataFlowFilter.shouldTransform(absolutePath, code))\n );\n },\n });\n}\n","export {\n createRuntimeAiConfig,\n DEFAULT_EXCLUDE,\n DEFAULT_OPTIONS,\n resolveOptions,\n} from \"@spotpatch/dev-server\";\nexport type {\n FilterEntry,\n ResolvedSpotPatchOptions,\n SimpleAiOptions,\n SpotPatchAiOptions,\n SpotPatchDataFlowOptions,\n SpotPatchOptions,\n} from \"@spotpatch/dev-server\";\n\nexport type ViteSpotPatchOptions = SharedSpotPatchOptions;\nimport type { SpotPatchOptions as SharedSpotPatchOptions } from \"@spotpatch/dev-server\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,oBAAiB;AAEjB,IAAAC,qBAOO;AACP,IAAAC,eAAsE;;;ACVtE,yBAA8B;AAC9B,qBAA6B;AAC7B,uBAAiB;AAEjB,wBAIO;;;ACRP;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,SAAW;AAAA,EACX,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,IACP,WAAa;AAAA,EACf;AAAA,EACA,UAAY;AAAA,EACZ,MAAQ;AAAA,IACN,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,MAAQ;AAAA,EACR,aAAe;AAAA,EACf,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,OAAS;AAAA,IACP;AAAA,EACF;AAAA,EACA,MAAQ;AAAA,EACR,QAAU;AAAA,EACV,OAAS;AAAA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AAY,OAAO,aACf,sDAAkC,iBAAiB,EAAE,KACrD;AAEN,cAAU,UAAM,0CAAsB;AAAA,MACpC,SAAS;AAAA,MACT;AAAA,MACA,SAAS;AAAA,IACX,CAAC;AAED,gCAAwB,iDAA6B,SAAS,iBAAiB;AAAA,EACjF;AAEA,SAAO;AAAA,IACL,sBAAsB,EAAE,WAAW,SAAS,SAAS,CAAC;AAAA,IACtD,6BAA6B,EAAE,SAAS,QAAQ,CAAC;AAAA,IACjD,mBAAmB,EAAE,SAAS,UAAU,QAAQ,CAAC;AAAA,EACnD;AACF;;;AO7DA,IAAAC,qBAKO;;;ARMP,oBAaO;","names":["import_node_path","import_dev_server","import_vite","path","VITE_VERSION","import_node_path","import_dev_server","path","import_node_path","import_compiler","import_node_path","import_compiler","path","path","path","import_dev_server"]}
package/dist/index.js CHANGED
@@ -22,7 +22,7 @@ import {
22
22
  // package.json
23
23
  var package_default = {
24
24
  name: "@spotpatch/vite",
25
- version: "1.10.0",
25
+ version: "1.11.0",
26
26
  description: "Vite development plugin for SpotPatch.",
27
27
  license: "MIT",
28
28
  repository: {
@@ -298,14 +298,24 @@ import path2 from "path";
298
298
  import {
299
299
  createAgentJobManager,
300
300
  createExternalHandoffService,
301
- createSpotPatchMiddleware
301
+ createSpotPatchMiddleware,
302
+ resolveManagedExecutionValidation
302
303
  } from "@spotpatch/dev-server";
304
+ import {
305
+ createExternalAgentSupervisor
306
+ } from "@spotpatch/bridge";
303
307
  function createServerPlugin(input) {
304
308
  let agentManager;
305
309
  let externalHandoffService;
310
+ let externalAgentSupervisor;
311
+ let middleware;
306
312
  let config;
307
313
  const closeResources = async () => {
308
314
  input.registry.clear();
315
+ middleware?.dispose();
316
+ middleware = void 0;
317
+ await externalAgentSupervisor?.dispose();
318
+ externalAgentSupervisor = void 0;
309
319
  await externalHandoffService?.close();
310
320
  externalHandoffService = void 0;
311
321
  await agentManager?.close();
@@ -342,18 +352,38 @@ function createServerPlugin(input) {
342
352
  "[spotpatch:vite] External Agent handoff is unavailable; core tools remain active."
343
353
  );
344
354
  }
355
+ if (externalHandoffService.capability().brokerReady) {
356
+ try {
357
+ const validation = await resolveManagedExecutionValidation({
358
+ ai: options.ai,
359
+ appRoot: root
360
+ });
361
+ externalAgentSupervisor = await createExternalAgentSupervisor({
362
+ bridgeAdapter: "vite",
363
+ checks: validation.checks,
364
+ limits: validation.limits,
365
+ root,
366
+ sessionId: input.session.id,
367
+ projectLabel: path2.basename(root)
368
+ });
369
+ } catch {
370
+ config.logger.warn(
371
+ "[spotpatch:vite] Managed Agent control is unavailable; Inbox remains active."
372
+ );
373
+ }
374
+ }
345
375
  }
346
- server.middlewares.use(
347
- createSpotPatchMiddleware({
348
- ...agentManager === void 0 ? {} : { agentManager },
349
- ...externalHandoffService === void 0 ? {} : { externalHandoffService },
350
- options,
351
- registry: input.registry,
352
- root,
353
- session: input.session,
354
- logger: config.logger
355
- })
356
- );
376
+ middleware = createSpotPatchMiddleware({
377
+ ...agentManager === void 0 ? {} : { agentManager },
378
+ ...externalAgentSupervisor === void 0 ? {} : { externalAgentControl: externalAgentSupervisor },
379
+ ...externalHandoffService === void 0 ? {} : { externalHandoffService },
380
+ options,
381
+ registry: input.registry,
382
+ root,
383
+ session: input.session,
384
+ logger: config.logger
385
+ });
386
+ server.middlewares.use(middleware);
357
387
  server.httpServer?.once("close", () => {
358
388
  void closeResources();
359
389
  });