@spotpatch/vite 1.4.3 → 1.5.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/README.md +50 -2
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/runtime-client.js +34 -27
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -119,7 +119,31 @@ spotPatch({
|
|
|
119
119
|
});
|
|
120
120
|
```
|
|
121
121
|
|
|
122
|
-
The default Agent path is review-gated:
|
|
122
|
+
The default Agent path is review-gated: **Check environment** provides an optional source-free capability diagnostic, while Run starts the real isolated tool session directly and proves tool continuation inline. The Agent supplies bounded nearby project conventions, exposes file tools rather than an arbitrary shell, reuses current host-run checks, and shows the complete Diff before Apply.
|
|
123
|
+
|
|
124
|
+
For a trusted local project, `trusted-auto` replaces the provider and dirty-worktree confirmations with one session-scoped consent and directly applies changes after required checks:
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
spotPatch({
|
|
128
|
+
ai: {
|
|
129
|
+
baseURL: "https://relay.example.com/v1",
|
|
130
|
+
model: "provider-model-name",
|
|
131
|
+
execution: {
|
|
132
|
+
applyMode: "trusted-auto",
|
|
133
|
+
checks: {
|
|
134
|
+
typecheck: {
|
|
135
|
+
label: "Typecheck",
|
|
136
|
+
command: "pnpm",
|
|
137
|
+
args: ["typecheck"],
|
|
138
|
+
required: true,
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
This mode can directly apply validated file deletions and restart-sensitive configuration changes. It does not allow credentials, environment files, Git metadata, external paths, arbitrary shell, failed checks, or baseline conflicts. SpotPatch does not commit, push, publish, or deploy application code.
|
|
123
147
|
|
|
124
148
|
### Security and production behavior
|
|
125
149
|
|
|
@@ -255,7 +279,31 @@ spotPatch({
|
|
|
255
279
|
});
|
|
256
280
|
```
|
|
257
281
|
|
|
258
|
-
默认 Agent
|
|
282
|
+
默认 Agent 路径必须经过审阅:“检查运行环境”提供不含源码的可选能力诊断;点击运行会直接进入真实隔离工具会话,并在会话内证明工具续接能力。Agent 会提供有界的就近项目规范,只暴露文件工具而不是任意 Shell,复用当前变更版本中由宿主实际执行的检查,并在 Apply 前展示完整 Diff。
|
|
283
|
+
|
|
284
|
+
可信的本地项目可以配置 `trusted-auto`:面板将 Provider 与脏工作区确认合并成一次会话级授权,必需检查通过后直接应用变更。
|
|
285
|
+
|
|
286
|
+
```ts
|
|
287
|
+
spotPatch({
|
|
288
|
+
ai: {
|
|
289
|
+
baseURL: "https://relay.example.com/v1",
|
|
290
|
+
model: "provider-model-name",
|
|
291
|
+
execution: {
|
|
292
|
+
applyMode: "trusted-auto",
|
|
293
|
+
checks: {
|
|
294
|
+
typecheck: {
|
|
295
|
+
label: "Typecheck",
|
|
296
|
+
command: "pnpm",
|
|
297
|
+
args: ["typecheck"],
|
|
298
|
+
required: true,
|
|
299
|
+
},
|
|
300
|
+
},
|
|
301
|
+
},
|
|
302
|
+
},
|
|
303
|
+
});
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
该模式可以直接应用验证通过的文件删除与需要重启开发服务的配置变更,但不会开放凭据、环境文件、Git 元数据、项目外路径、任意 Shell,也不会绕过失败检查或基线冲突。SpotPatch 不会替业务代码执行 commit、push、发包或部署。
|
|
259
307
|
|
|
260
308
|
### 安全与生产行为
|
|
261
309
|
|
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.
|
|
54
|
+
version: "1.5.0",
|
|
55
55
|
description: "Vite development plugin for SpotPatch.",
|
|
56
56
|
license: "MIT",
|
|
57
57
|
repository: {
|
package/dist/index.cjs.map
CHANGED
|
@@ -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 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} 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 = (config: UserConfig, environment: ConfigEnv): 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 = resolveOptions(userOptions, environmentAi);\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 { createRuntimeAiConfig, type SpotPatchSession } 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}`;\n\ninterface RuntimeInjectionPluginInput {\n readonly clientBundle?: string;\n readonly context: SpotPatchPluginContext;\n readonly reactAdapterBundle?: string;\n readonly session: SpotPatchSession;\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 debug: options.debug,\n editor: options.editor,\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 `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 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 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 return null;\n },\n\n transformIndexHtml() {\n return [\n {\n tag: \"script\",\n attrs: {\n type: \"module\",\n src: `/@id/${SPOTPATCH_CLIENT_MODULE_ID}`,\n },\n injectTo: \"head\",\n },\n ];\n },\n };\n}\n","{\n \"name\": \"@spotpatch/vite\",\n \"version\": \"1.4.3\",\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 \"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.runtime-client.config.ts && tsup --config tsup.runtime-react-adapter.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/compiler\": \"workspace:^\",\n \"@spotpatch/dev-server\": \"workspace:^\",\n \"@spotpatch/react-adapter\": \"workspace:^\",\n \"@spotpatch/runtime\": \"workspace:^\",\n \"@spotpatch/shared\": \"workspace:^\"\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 createSpotPatchMiddleware,\n type AgentJobManager,\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 config: ResolvedConfig | undefined;\n\n const closeResources = async (): Promise<void> => {\n input.registry.clear();\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 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\n server.middlewares.use(\n createSpotPatchMiddleware({\n ...(agentManager === undefined ? {} : { agentManager }),\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 { createTransformFilter, stripViteQuery } from \"./transform-filter.js\";\n\ninterface TransformPluginInput {\n readonly configure?: (config: UserConfig, environment: ConfigEnv) => 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 cache = new Map<string, ViteTransformOutput | null>();\n\n return {\n name: \"spotpatch:transform\",\n apply: \"serve\",\n enforce: \"pre\",\n\n config(config, environment) {\n 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 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 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 { 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\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 return sourceFilter.shouldTransform(path.resolve(cleanId), code);\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 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,qBAMO;AACP,IAAAC,eAAsE;;;ACTtE,yBAA8B;AAC9B,qBAA6B;AAC7B,uBAAiB;AAEjB,wBAA6D;;;ACJ7D;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,MA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AAO,QAAQ,GAAG;AAC3D,UAAM,oBACJ,OAAO,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,kBAAU,mCAAe,aAAa,aAAa;AAEnD,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;;;AOrDA,IAAAC,qBAKO;;;ARKP,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 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} 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 = (config: UserConfig, environment: ConfigEnv): 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 = resolveOptions(userOptions, environmentAi);\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 { createRuntimeAiConfig, type SpotPatchSession } 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}`;\n\ninterface RuntimeInjectionPluginInput {\n readonly clientBundle?: string;\n readonly context: SpotPatchPluginContext;\n readonly reactAdapterBundle?: string;\n readonly session: SpotPatchSession;\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 debug: options.debug,\n editor: options.editor,\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 `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 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 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 return null;\n },\n\n transformIndexHtml() {\n return [\n {\n tag: \"script\",\n attrs: {\n type: \"module\",\n src: `/@id/${SPOTPATCH_CLIENT_MODULE_ID}`,\n },\n injectTo: \"head\",\n },\n ];\n },\n };\n}\n","{\n \"name\": \"@spotpatch/vite\",\n \"version\": \"1.5.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 \"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.runtime-client.config.ts && tsup --config tsup.runtime-react-adapter.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/compiler\": \"workspace:^\",\n \"@spotpatch/dev-server\": \"workspace:^\",\n \"@spotpatch/react-adapter\": \"workspace:^\",\n \"@spotpatch/runtime\": \"workspace:^\",\n \"@spotpatch/shared\": \"workspace:^\"\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 createSpotPatchMiddleware,\n type AgentJobManager,\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 config: ResolvedConfig | undefined;\n\n const closeResources = async (): Promise<void> => {\n input.registry.clear();\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 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\n server.middlewares.use(\n createSpotPatchMiddleware({\n ...(agentManager === undefined ? {} : { agentManager }),\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 { createTransformFilter, stripViteQuery } from \"./transform-filter.js\";\n\ninterface TransformPluginInput {\n readonly configure?: (config: UserConfig, environment: ConfigEnv) => 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 cache = new Map<string, ViteTransformOutput | null>();\n\n return {\n name: \"spotpatch:transform\",\n apply: \"serve\",\n enforce: \"pre\",\n\n config(config, environment) {\n 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 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 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 { 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\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 return sourceFilter.shouldTransform(path.resolve(cleanId), code);\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 SpotPatchOptions,\n} from \"@spotpatch/dev-server\";\n\nexport type ViteSpotPatchOptions = SharedSpotPatchOptions;\nimport type { SpotPatchOptions as SharedSpotPatchOptions } from \"@spotpatch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AAQ,KAAK,MAAM,OAAO,KAAK;AACnE,kBAAQ;AAAA,YACN,6CAA6C,eAAe,MAAM,EAAE,CAAC,0BAA0B,MAAM;AAAA,UACvG;AAAA,QACF;AAEA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;;;AL/FO,SAAS,UAAU,cAAoC,CAAC,GAAa;AAC1E,MAAI,cAAU,mCAAe,WAAW;AACxC,MAAI,wBACF,OAAO,OAAO,CAAC,CAAC;AAElB,MAAI,CAAC,QAAQ,SAAS;AACpB,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,eAAW,yCAAqB;AACtC,QAAM,cAAU,kCAAc;AAC9B,QAAM,UAAU,OAAO,OAAO;AAAA,IAC5B,0BAA0B,MAAM;AAAA,IAChC,YAAY,MAAM;AAAA,EACpB,CAAkC;AAClC,QAAM,YAAY,CAAC,QAAoB,gBAAiC;AACtE,UAAM,OAAO,kBAAAC,QAAK,QAAQ,QAAQ,IAAI,GAAG,OAAO,QAAQ,GAAG;AAC3D,UAAM,oBACJ,OAAO,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,kBAAU,mCAAe,aAAa,aAAa;AAEnD,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;;;AOrDA,IAAAC,qBAKO;;;ARKP,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
|
@@ -18,7 +18,7 @@ import { createRuntimeAiConfig } from "@spotpatch/dev-server";
|
|
|
18
18
|
// package.json
|
|
19
19
|
var package_default = {
|
|
20
20
|
name: "@spotpatch/vite",
|
|
21
|
-
version: "1.
|
|
21
|
+
version: "1.5.0",
|
|
22
22
|
description: "Vite development plugin for SpotPatch.",
|
|
23
23
|
license: "MIT",
|
|
24
24
|
repository: {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../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","../src/index.ts"],"sourcesContent":["import path from \"node:path\";\n\nimport {\n createSession,\n createSourceRegistry,\n resolveCredentialEnvironment,\n resolveEnvironmentAiConfiguration,\n resolveOptions,\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 = (config: UserConfig, environment: ConfigEnv): 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 = resolveOptions(userOptions, environmentAi);\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 { createRuntimeAiConfig, type SpotPatchSession } 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}`;\n\ninterface RuntimeInjectionPluginInput {\n readonly clientBundle?: string;\n readonly context: SpotPatchPluginContext;\n readonly reactAdapterBundle?: string;\n readonly session: SpotPatchSession;\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 debug: options.debug,\n editor: options.editor,\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 `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 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 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 return null;\n },\n\n transformIndexHtml() {\n return [\n {\n tag: \"script\",\n attrs: {\n type: \"module\",\n src: `/@id/${SPOTPATCH_CLIENT_MODULE_ID}`,\n },\n injectTo: \"head\",\n },\n ];\n },\n };\n}\n","{\n \"name\": \"@spotpatch/vite\",\n \"version\": \"1.4.3\",\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 \"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.runtime-client.config.ts && tsup --config tsup.runtime-react-adapter.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/compiler\": \"workspace:^\",\n \"@spotpatch/dev-server\": \"workspace:^\",\n \"@spotpatch/react-adapter\": \"workspace:^\",\n \"@spotpatch/runtime\": \"workspace:^\",\n \"@spotpatch/shared\": \"workspace:^\"\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 createSpotPatchMiddleware,\n type AgentJobManager,\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 config: ResolvedConfig | undefined;\n\n const closeResources = async (): Promise<void> => {\n input.registry.clear();\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 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\n server.middlewares.use(\n createSpotPatchMiddleware({\n ...(agentManager === undefined ? {} : { agentManager }),\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 { createTransformFilter, stripViteQuery } from \"./transform-filter.js\";\n\ninterface TransformPluginInput {\n readonly configure?: (config: UserConfig, environment: ConfigEnv) => 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 cache = new Map<string, ViteTransformOutput | null>();\n\n return {\n name: \"spotpatch:transform\",\n apply: \"serve\",\n enforce: \"pre\",\n\n config(config, environment) {\n 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 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 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 { 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\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 return sourceFilter.shouldTransform(path.resolve(cleanId), code);\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 SpotPatchOptions,\n} from \"@spotpatch/dev-server\";\n\nexport type ViteSpotPatchOptions = SharedSpotPatchOptions;\nimport type { SpotPatchOptions as SharedSpotPatchOptions } from \"@spotpatch/dev-server\";\n","export { spotPatch } from \"./plugin.js\";\nexport {\n DEFAULT_OPTIONS,\n resolveOptions,\n type ResolvedSpotPatchOptions,\n type SimpleAiOptions,\n type SpotPatchAiOptions,\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"],"mappings":";AAAA,OAAOA,WAAU;AAEjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAA6D;;;ACTtE,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,OAAO,UAAU;AAEjB,SAAS,6BAAoD;;;ACJ7D;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,SAAW;AAAA,EACX,YAAc;AAAA,I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M,UAAU,OAAO,OAAO;AAAA,IAC5B,0BAA0B,MAAM;AAAA,IAChC,YAAY,MAAM;AAAA,EACpB,CAAkC;AAClC,QAAM,YAAY,CAAC,QAAoB,gBAAiC;AACtE,UAAM,OAAOC,MAAK,QAAQ,QAAQ,IAAI,GAAG,OAAO,QAAQ,GAAG;AAC3D,UAAM,oBACJ,OAAO,WAAW,QACd,QAAQ,MACR,QAAQ,YAAY,MAAMA,MAAK,QAAQ,MAAM,OAAO,UAAU,GAAG,GAAG,EAAE;AAC5E,UAAM,gBACJ,YAAY,OAAO,SACf,kCAAkC,iBAAiB,EAAE,KACrD;AAEN,cAAU,eAAe,aAAa,aAAa;AAEnD,4BAAwB,6BAA6B,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;;;AOrDA;AAAA,EACE,yBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,kBAAAC;AAAA,OACK;;;ACKP;AAAA,EACE;AAAA,OAYK;","names":["path","path","path","path","path","path","createRuntimeAiConfig","resolveOptions"]}
|
|
1
|
+
{"version":3,"sources":["../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","../src/index.ts"],"sourcesContent":["import path from \"node:path\";\n\nimport {\n createSession,\n createSourceRegistry,\n resolveCredentialEnvironment,\n resolveEnvironmentAiConfiguration,\n resolveOptions,\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 = (config: UserConfig, environment: ConfigEnv): 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 = resolveOptions(userOptions, environmentAi);\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 { createRuntimeAiConfig, type SpotPatchSession } 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}`;\n\ninterface RuntimeInjectionPluginInput {\n readonly clientBundle?: string;\n readonly context: SpotPatchPluginContext;\n readonly reactAdapterBundle?: string;\n readonly session: SpotPatchSession;\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 debug: options.debug,\n editor: options.editor,\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 `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 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 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 return null;\n },\n\n transformIndexHtml() {\n return [\n {\n tag: \"script\",\n attrs: {\n type: \"module\",\n src: `/@id/${SPOTPATCH_CLIENT_MODULE_ID}`,\n },\n injectTo: \"head\",\n },\n ];\n },\n };\n}\n","{\n \"name\": \"@spotpatch/vite\",\n \"version\": \"1.5.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 \"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.runtime-client.config.ts && tsup --config tsup.runtime-react-adapter.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/compiler\": \"workspace:^\",\n \"@spotpatch/dev-server\": \"workspace:^\",\n \"@spotpatch/react-adapter\": \"workspace:^\",\n \"@spotpatch/runtime\": \"workspace:^\",\n \"@spotpatch/shared\": \"workspace:^\"\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 createSpotPatchMiddleware,\n type AgentJobManager,\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 config: ResolvedConfig | undefined;\n\n const closeResources = async (): Promise<void> => {\n input.registry.clear();\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 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\n server.middlewares.use(\n createSpotPatchMiddleware({\n ...(agentManager === undefined ? {} : { agentManager }),\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 { createTransformFilter, stripViteQuery } from \"./transform-filter.js\";\n\ninterface TransformPluginInput {\n readonly configure?: (config: UserConfig, environment: ConfigEnv) => 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 cache = new Map<string, ViteTransformOutput | null>();\n\n return {\n name: \"spotpatch:transform\",\n apply: \"serve\",\n enforce: \"pre\",\n\n config(config, environment) {\n 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 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 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 { 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\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 return sourceFilter.shouldTransform(path.resolve(cleanId), code);\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 SpotPatchOptions,\n} from \"@spotpatch/dev-server\";\n\nexport type ViteSpotPatchOptions = SharedSpotPatchOptions;\nimport type { SpotPatchOptions as SharedSpotPatchOptions } from \"@spotpatch/dev-server\";\n","export { spotPatch } from \"./plugin.js\";\nexport {\n DEFAULT_OPTIONS,\n resolveOptions,\n type ResolvedSpotPatchOptions,\n type SimpleAiOptions,\n type SpotPatchAiOptions,\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"],"mappings":";AAAA,OAAOA,WAAU;AAEjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAA6D;;;ACTtE,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,OAAO,UAAU;AAEjB,SAAS,6BAAoD;;;ACJ7D;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,EACT,SAAW;AAAA,IACT,KAAK;AAAA,MACH,QAAU;AAAA,QACR,OAAS;AAAA,QACT,SAAW;AAAA,MACb;AAAA,MACA,SAAW;AAAA,QACT,OAAS;AAAA,QACT,SAAW;AAAA,MACb;AAAA,IACF;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,OAAS;AAAA,IACT,OAAS;AAAA,IACT,WAAa;AAAA,EACf;AAAA,EACA,cAAgB;AAAA,IACd,uBAAuB;AAAA,IACvB,yBAAyB;AAAA,IACzB,4BAA4B;AAAA,IAC5B,sBAAs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ACKP;AAAA,EACE;AAAA,OAYK;","names":["path","path","path","path","path","path","createRuntimeAiConfig","resolveOptions"]}
|
package/dist/runtime-client.js
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
|
-
import{createReact18Adapter as ca}from"@spotpatch/react-adapter";var f={INVALID_REQUEST:"INVALID_REQUEST",INVALID_TOKEN:"INVALID_TOKEN",ORIGIN_NOT_ALLOWED:"ORIGIN_NOT_ALLOWED",SOURCE_NOT_FOUND:"SOURCE_NOT_FOUND",SOURCE_OUTSIDE_ROOT:"SOURCE_OUTSIDE_ROOT",SOURCE_TOO_LARGE:"SOURCE_TOO_LARGE",EDITOR_OPEN_FAILED:"EDITOR_OPEN_FAILED",AI_DISABLED:"AI_DISABLED",PROVIDER_NOT_CONFIGURED:"PROVIDER_NOT_CONFIGURED",PROVIDER_AUTH_FAILED:"PROVIDER_AUTH_FAILED",PROVIDER_PROTOCOL_UNSUPPORTED:"PROVIDER_PROTOCOL_UNSUPPORTED",MODEL_NOT_ALLOWED:"MODEL_NOT_ALLOWED",MODEL_TOOL_CALL_UNSUPPORTED:"MODEL_TOOL_CALL_UNSUPPORTED",PROVIDER_RATE_LIMITED:"PROVIDER_RATE_LIMITED",AGENT_BUSY:"AGENT_BUSY",AGENT_LIMIT_EXCEEDED:"AGENT_LIMIT_EXCEEDED",AGENT_CANCELLED:"AGENT_CANCELLED",WORKTREE_DIRTY:"WORKTREE_DIRTY",WORKTREE_NOT_REPOSITORY:"WORKTREE_NOT_REPOSITORY",WORKTREE_OPERATION_IN_PROGRESS:"WORKTREE_OPERATION_IN_PROGRESS",WORKTREE_CONFLICTED:"WORKTREE_CONFLICTED",WORKTREE_LOCAL_CHANGES_TOO_LARGE:"WORKTREE_LOCAL_CHANGES_TOO_LARGE",WORKTREE_UNTRACKED_UNSUPPORTED:"WORKTREE_UNTRACKED_UNSUPPORTED",WORKTREE_LOCAL_CHANGES_UNSUPPORTED:"WORKTREE_LOCAL_CHANGES_UNSUPPORTED",TOOL_DENIED:"TOOL_DENIED",TOOL_INPUT_INVALID:"TOOL_INPUT_INVALID",TOOL_ARGUMENTS_INVALID:"TOOL_ARGUMENTS_INVALID",TOOL_CALL_ID_CONFLICT:"TOOL_CALL_ID_CONFLICT",TOOL_PATH_DENIED:"TOOL_PATH_DENIED",PATCH_REJECTED:"PATCH_REJECTED",VALIDATION_FAILED:"VALIDATION_FAILED",APPLY_CONFLICT:"APPLY_CONFLICT",INTERNAL_ERROR:"INTERNAL_ERROR"};var fo=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,ho=/blob:[^\s"'<>]+/giu,mo=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,bo=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,yo=/\b(authorization|cookie|set-cookie|api[-_]?key|(?:access[-_]?|refresh[-_]?|auth[-_]?)?token|secret|password|default[-_]?value|value)\b(\s*[:=]\s*)("(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|`(?:\\.|[^`\\\r\n])*`|[^\s,;"'<>]+)/giu,So=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),xo=500;function Eo(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function Ao(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function St(e){let t=Eo(e);return So.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function G(e){return e.replace(fo,"[redacted inline data]").replace(ho,"[redacted blob URL]").replace(mo,"Bearer [redacted]").replace(bo,"$1[redacted]@").replace(yo,(t,o,n,s)=>{let r=s.at(0),a=r==='"'||r==="'"||r==="`";return`${o}${n}${a?r:""}[redacted]${a?r:""}`})}function Co(e){e.username="",e.password="";for(let[t,o]of e.searchParams)St(t)?e.searchParams.set(t,"[redacted]"):e.searchParams.set(t,G(o));return/token|secret|authorization|api[-_]?key/iu.test(e.hash)&&(e.hash="#[redacted]"),e.toString()}function Xe(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=G(o);try{let s=new URL(n,t),r=Co(s),a=new URL(t);return!/^[a-z][a-z\d+.-]*:/iu.test(n)&&s.origin===a.origin?`${s.pathname}${s.search}${s.hash}`:r}catch{return Ao(n,xo)}}var Je="/__spotpatch/v1",xt="X-SpotPatch-Token",Ze=Object.freeze({bootstrap:`${Je}/bootstrap`,sourceContext:`${Je}/source-context`,openEditor:`${Je}/open-editor`,agentCapability:`${Je}/agent/capability`,agentWorkspaceHealth:`${Je}/agent/workspace-health`,agentJobs:`${Je}/agent/jobs`});function at(e,t){return`${Ze.agentJobs}/${encodeURIComponent(e)}/${t}`}var Ro=Object.freeze({maxTurns:20,maxToolCalls:80,maxChangedFiles:20,maxDiffBytes:512e3,maxReadBytesPerFile:256e3,maxToolOutputCharacters:4e4,maxProviderResponseBytes:2e6,providerConnectTimeoutMs:15e3,providerFirstByteTimeoutMs:3e4,providerIdleTimeoutMs:6e4,checkTimeoutMs:12e4,jobTimeoutMs:6e5}),Mt=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),Dt=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),vo=Object.freeze(["ready","consent-required","blocked"]),To=Object.freeze({maxUntrackedFiles:1e3,maxUntrackedBytes:20*1024*1024}),$t=Object.freeze(["added","modified","deleted"]),zt=Object.freeze(["passed","failed","cancelled","timed-out"]);var jt="data-spotpatch-source",wo=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function Ht(e){if(e===null)return;let t=wo.exec(e);if(t===null)return;let o=t[1],n=Number(t[2]),s=Number(t[3]);if(!(o===void 0||!Number.isSafeInteger(n)||!Number.isSafeInteger(s)))return Object.freeze({fileId:o,line:n,column:s})}var Bt="https://github.com/huanglvjing/spotpatch";function tn(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function _o(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:tn(e.source)}})}function Po(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function Lo(e){return Object.freeze({...e,classNames:Object.freeze([...e.classNames]),matchedRules:Object.freeze(e.matchedRules.map(t=>Object.freeze({...t}))),computed:Object.freeze({...e.computed}),warnings:Object.freeze([...e.warnings])})}function Io(e){return Object.freeze({instruction:e.instruction.trim(),...e.page===void 0?{}:{page:Object.freeze({...e.page})},source:tn(e.source,e.code),react:_o(e.react),element:Po(e.element),styles:Lo(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function nn(e){if(e.targets.length<1||e.targets.length>20)throw new RangeError(`SpotPatch annotations require between 1 and ${String(20)} targets.`);let t=e.targets.map(o=>o.instruction.trim());if(t.some(o=>o.length===0||o.length>2e3)||t.reduce((o,n)=>o+n.length,0)>4e3)throw new RangeError("SpotPatch target instructions exceed the allowed bounds.");return Object.freeze({schemaVersion:3,id:e.id,locale:e.locale,page:Object.freeze({...e.page}),targets:Object.freeze(e.targets.map(Io)),createdAt:e.createdAt})}var ko=new Set(Object.values(f)),No=new Set(Dt),Mo=new Set(zt),Do=new Set($t),rn=new Set(Mt),$o=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,zo=/^[A-Za-z0-9_-]+$/,jo=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function Ue(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fe(e,t){return Object.keys(e).every(o=>t.includes(o))}function re(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function gt(e){return re(e,64,1)&&typeof e=="string"&&$o.test(e)}function Ut(e){return re(e,128,22)&&typeof e=="string"&&zo.test(e)}function ft(e){return typeof e=="string"&&jo.test(e)&&Number.isFinite(Date.parse(e))}function Qe(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function an(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function on(e,t){return e===void 0||re(e,t)}function st(e){return typeof e=="string"&&ko.has(e)}function sn(e){return!Ue(e)||!fe(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:gt(e.providerProfileId)&&re(e.providerLabel,100)&>(e.modelProfileId)&&re(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&No.has(e.state)&&typeof e.authenticated=="boolean"&&typeof e.modelAvailable=="boolean"&&typeof e.toolCalling=="boolean"&&typeof e.toolResultContinuation=="boolean"&&typeof e.streaming=="boolean"&&(e.checkedAt===void 0||ft(e.checkedAt))&&(e.errorCode===void 0||st(e.errorCode))}function cn(e){if(!Ue(e)||!fe(e,["state","checkedAt","changes","canIncludeLocalChanges","errorCode"])||e.state!=="ready"&&e.state!=="consent-required"&&e.state!=="blocked"||!ft(e.checkedAt)||typeof e.canIncludeLocalChanges!="boolean"||e.errorCode!==void 0&&!st(e.errorCode)||!Ue(e.changes)||!fe(e.changes,["staged","unstaged","untracked","conflicted","total"]))return!1;let t=e.changes,{staged:o,unstaged:n,untracked:s,conflicted:r,total:a}=t;return!Qe(o)||!Qe(n)||!Qe(s)||!Qe(r)||!Qe(a)||a<o||a<n||a<s||a<r||a>o+n+s?!1:e.state==="ready"?a===0&&!e.canIncludeLocalChanges&&e.errorCode===void 0:e.state==="consent-required"?a>0&&r===0&&e.canIncludeLocalChanges&&e.errorCode===void 0:!e.canIncludeLocalChanges&&e.errorCode!==void 0}function At(e){return!Ue(e)||!fe(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:Ut(e.jobId)&&typeof e.status=="string"&&rn.has(e.status)&>(e.providerProfileId)&&re(e.providerLabel,100)&>(e.modelProfileId)&&re(e.modelLabel,100)&&re(e.phaseMessage,1024)&&ft(e.createdAt)&&ft(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||st(e.errorCode))}function Ho(e){return Ue(e)&&fe(e,["relativePath","kind","additions","deletions"])&&re(e.relativePath,1024)&&typeof e.kind=="string"&&Do.has(e.kind)&&Qe(e.additions)&&Qe(e.deletions)}function dn(e){return Ue(e)&&fe(e,["checkId","label","status","durationMs","output"])&>(e.checkId)&&re(e.label,100)&&typeof e.status=="string"&&Mo.has(e.status)&&Qe(e.durationMs)&&re(e.output,8e4)}function Bo(e){return Ue(e)&&fe(e,["jobId","summary","diff","files","checks"])&&Ut(e.jobId)&&re(e.summary,8e4)&&re(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(Ho)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(dn)}function ln(e){return Ue(e)&&fe(e,["snapshot","result"])&&At(e.snapshot)&&(e.result===void 0||Bo(e.result)&&e.result.jobId===e.snapshot.jobId)}function Uo(e){return Ue(e)&&fe(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===2&&an(e.sequence)&&Ut(e.jobId)&&typeof e.status=="string"&&rn.has(e.status)&&ft(e.timestamp)&&typeof e.type=="string"&&Ue(e.data)}function pn(e){if(!Uo(e))return!1;let t=e.data;switch(e.type){case"snapshot":return fe(t,["snapshot"])&&At(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return fe(t,["message"])&&re(t.message,1024);case"tool":return fe(t,["turn","toolCallId","toolName","state","relativePath","checkLabel"])&&an(t.turn)&&re(t.toolCallId,256)&&re(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&on(t.relativePath,1024)&&on(t.checkLabel,100);case"check":return fe(t,["result"])&&dn(t.result);case"result-ready":return fe(t,["hasResult"])&&t.hasResult===!0;case"error":return fe(t,["code","message"])&&st(t.code)&&re(t.message,1024);default:return!1}}var Go=2e6,un=1e5,Vo=4e6,M=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wo(e){if(!(!ct(e)||e.ok!==!1||!ct(e.error)))return st(e.error.code)?e.error.code:void 0}function Jo(e){if(!ct(e)||e.ok!==!0||!("data"in e))throw new M;return e.data}function qo(e){return ct(e)&&typeof e.relativePath=="string"&&(e.language==="tsx"||e.language==="jsx")&&typeof e.startLine=="number"&&typeof e.endLine=="number"&&typeof e.excerpt=="string"&&(e.boundary==="component"||e.boundary==="nearby-lines")}function fn(e){if(!(!ct(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))fn(t);Object.freeze(e)}}function ht(e){return fn(e),e}async function Fo(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new M;if(e.body===null)throw new M;let n=e.body.getReader(),s=new TextDecoder("utf-8",{fatal:!0}),r=0,a="";try{for(;;){let l=await n.read();if(l.done)return a+=s.decode(),a;if(r+=l.value.byteLength,r>t)throw await n.cancel(),new M;a+=s.decode(l.value,{stream:!0})}}catch(l){throw l instanceof M?l:new M}finally{n.releaseLock()}}function hn(e){try{return JSON.parse(e)}catch{throw new M}}async function gn(e){let t=hn(await Fo(e,Go));if(!e.ok)throw new M(Wo(t));return Jo(t)}function Ko(e,t){if(!sn(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new M;return ht(e)}function Ct(e,t){if(!At(e)||t?.jobId!==void 0&&e.jobId!==t.jobId||t?.providerProfileId!==void 0&&e.providerProfileId!==t.providerProfileId||t?.modelProfileId!==void 0&&e.modelProfileId!==t.modelProfileId)throw new M;return ht(e)}function Yo(e,t){if(!ln(e)||e.snapshot.jobId!==t)throw new M;return ht(e)}function Xo(e){if(!pn(e))throw new M;return ht(e)}function Zo(e){return{...e,annotation:{...e.annotation,targets:e.annotation.targets.map(t=>({instruction:t.instruction,source:t.source,react:t.react,element:t.element,styles:t.styles,warnings:t.warnings}))}}}function mn(e){return e instanceof M?e.code:void 0}function bn(e){let t=new Set;function o(){for(let a of t)a.abort();t.clear()}async function n(a,l,E){let A=new AbortController;t.add(A);try{let R=await e.fetch(a,{method:l,headers:{...E===void 0?{}:{"Content-Type":"application/json"},[xt]:e.sessionToken},...E===void 0?{}:{body:JSON.stringify(E)},signal:A.signal});return await gn(R)}finally{t.delete(A)}}async function s(a,l){let E=new AbortController;t.add(E);try{let A=await e.fetch(at(a,"events"),{method:"POST",headers:{"Content-Type":"application/json",[xt]:e.sessionToken},body:JSON.stringify({}),signal:E.signal});if(!A.ok){await gn(A);return}if(A.body===null)throw new M;let R=A.body.getReader(),j=new TextDecoder("utf-8",{fatal:!0}),u="",L=0,V=0,P=b=>{if(b.trim().length===0)return;if(new TextEncoder().encode(b).byteLength>un)throw new M;let x=Xo(hn(b));if(x.jobId!==a||x.sequence<=V)throw new M;V=x.sequence,l(x)};try{for(;;){let b=await R.read();if(b.done){u+=j.decode(),P(u);return}if(L+=b.value.byteLength,L>Vo)throw await R.cancel(),new M;u+=j.decode(b.value,{stream:!0});let x=u.split(`
|
|
2
|
-
`);if(
|
|
3
|
-
`).length}function
|
|
4
|
-
`),e.maxCharacters),...
|
|
1
|
+
import{createReact18Adapter as da}from"@spotpatch/react-adapter";var f={INVALID_REQUEST:"INVALID_REQUEST",INVALID_TOKEN:"INVALID_TOKEN",ORIGIN_NOT_ALLOWED:"ORIGIN_NOT_ALLOWED",SOURCE_NOT_FOUND:"SOURCE_NOT_FOUND",SOURCE_OUTSIDE_ROOT:"SOURCE_OUTSIDE_ROOT",SOURCE_TOO_LARGE:"SOURCE_TOO_LARGE",EDITOR_OPEN_FAILED:"EDITOR_OPEN_FAILED",AI_DISABLED:"AI_DISABLED",PROVIDER_NOT_CONFIGURED:"PROVIDER_NOT_CONFIGURED",PROVIDER_AUTH_FAILED:"PROVIDER_AUTH_FAILED",PROVIDER_PROTOCOL_UNSUPPORTED:"PROVIDER_PROTOCOL_UNSUPPORTED",MODEL_NOT_ALLOWED:"MODEL_NOT_ALLOWED",MODEL_TOOL_CALL_UNSUPPORTED:"MODEL_TOOL_CALL_UNSUPPORTED",PROVIDER_RATE_LIMITED:"PROVIDER_RATE_LIMITED",AGENT_BUSY:"AGENT_BUSY",AGENT_LIMIT_EXCEEDED:"AGENT_LIMIT_EXCEEDED",AGENT_CANCELLED:"AGENT_CANCELLED",WORKTREE_DIRTY:"WORKTREE_DIRTY",WORKTREE_NOT_REPOSITORY:"WORKTREE_NOT_REPOSITORY",WORKTREE_OPERATION_IN_PROGRESS:"WORKTREE_OPERATION_IN_PROGRESS",WORKTREE_CONFLICTED:"WORKTREE_CONFLICTED",WORKTREE_LOCAL_CHANGES_TOO_LARGE:"WORKTREE_LOCAL_CHANGES_TOO_LARGE",WORKTREE_UNTRACKED_UNSUPPORTED:"WORKTREE_UNTRACKED_UNSUPPORTED",WORKTREE_LOCAL_CHANGES_UNSUPPORTED:"WORKTREE_LOCAL_CHANGES_UNSUPPORTED",TOOL_DENIED:"TOOL_DENIED",TOOL_INPUT_INVALID:"TOOL_INPUT_INVALID",TOOL_ARGUMENTS_INVALID:"TOOL_ARGUMENTS_INVALID",TOOL_CALL_ID_CONFLICT:"TOOL_CALL_ID_CONFLICT",TOOL_PATH_DENIED:"TOOL_PATH_DENIED",PATCH_REJECTED:"PATCH_REJECTED",VALIDATION_FAILED:"VALIDATION_FAILED",APPLY_CONFLICT:"APPLY_CONFLICT",INTERNAL_ERROR:"INTERNAL_ERROR"};var fo=/data:[^\s"'<>]*;base64,[a-z0-9+/_=-]+/giu,ho=/blob:[^\s"'<>]+/giu,mo=/\bbearer\s+[a-z0-9._~+/-]+=*/giu,bo=/\b(https?:\/\/)[^/\s:@]+:[^/\s@]+@/giu,yo=/\b(authorization|cookie|set-cookie|api[-_]?key|(?:access[-_]?|refresh[-_]?|auth[-_]?)?token|secret|password|default[-_]?value|value)\b(\s*[:=]\s*)("(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|`(?:\\.|[^`\\\r\n])*`|[^\s,;"'<>]+)/giu,xo=new Set(["authorization","cookie","defaultvalue","password","setcookie","value"]),So=500;function Eo(e){return e.toLowerCase().replaceAll(/[-_:]/gu,"")}function Ao(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Et(e){let t=Eo(e);return xo.has(t)||t.includes("apikey")||t.includes("authorization")||t.includes("secret")||t.includes("token")}function G(e){return e.replace(fo,"[redacted inline data]").replace(ho,"[redacted blob URL]").replace(mo,"Bearer [redacted]").replace(bo,"$1[redacted]@").replace(yo,(t,o,n,i)=>{let r=i.at(0),a=r==='"'||r==="'"||r==="`";return`${o}${n}${a?r:""}[redacted]${a?r:""}`})}function Co(e){e.username="",e.password="";for(let[t,o]of e.searchParams)Et(t)?e.searchParams.set(t,"[redacted]"):e.searchParams.set(t,G(o));return/token|secret|authorization|api[-_]?key/iu.test(e.hash)&&(e.hash="#[redacted]"),e.toString()}function Ze(e,t){let o=e.trim();if(/^(?:blob|data|javascript):/iu.test(o))return"[redacted URL]";let n=G(o);try{let i=new URL(n,t),r=Co(i),a=new URL(t);return!/^[a-z][a-z\d+.-]*:/iu.test(n)&&i.origin===a.origin?`${i.pathname}${i.search}${i.hash}`:r}catch{return Ao(n,So)}}var Je="/__spotpatch/v1",At="X-SpotPatch-Token",Qe=Object.freeze({bootstrap:`${Je}/bootstrap`,sourceContext:`${Je}/source-context`,openEditor:`${Je}/open-editor`,agentCapability:`${Je}/agent/capability`,agentWorkspaceHealth:`${Je}/agent/workspace-health`,agentJobs:`${Je}/agent/jobs`});function rt(e,t){return`${Qe.agentJobs}/${encodeURIComponent(e)}/${t}`}var Ro=Object.freeze(["review","auto","trusted-auto"]),vo=Object.freeze({maxTurns:20,maxToolCalls:80,maxChangedFiles:20,maxDiffBytes:512e3,maxReadBytesPerFile:256e3,maxToolOutputCharacters:4e4,maxProviderResponseBytes:2e6,providerConnectTimeoutMs:15e3,providerFirstByteTimeoutMs:3e4,providerIdleTimeoutMs:6e4,checkTimeoutMs:12e4,jobTimeoutMs:6e5}),$t=Object.freeze(["queued","preparing","running","validating","awaiting-review","applying","applied","completed","cancelling","cancelled","reverting","reverted","failed"]),zt=Object.freeze(["unknown","probing","agent-ready","prompt-only","unavailable"]),To=Object.freeze(["ready","consent-required","blocked"]),wo=Object.freeze({maxUntrackedFiles:1e3,maxUntrackedBytes:20*1024*1024}),jt=Object.freeze(["added","modified","deleted"]),Ht=Object.freeze(["passed","failed","cancelled","timed-out"]);var Bt="data-spotpatch-source",Oo=/^([A-Za-z0-9_-]+):([1-9]\d*):([1-9]\d*)$/;function Ut(e){if(e===null)return;let t=Oo.exec(e);if(t===null)return;let o=t[1],n=Number(t[2]),i=Number(t[3]);if(!(o===void 0||!Number.isSafeInteger(n)||!Number.isSafeInteger(i)))return Object.freeze({fileId:o,line:n,column:i})}var Gt="https://github.com/huanglvjing/spotpatch";function tn(e,t){return Object.freeze({...e,...e.relativePath===void 0&&t!==void 0?{relativePath:t.relativePath}:{}})}function Po(e){return Object.freeze({...e,componentStack:Object.freeze([...e.componentStack]),...e.source===void 0?{}:{source:tn(e.source)}})}function Lo(e){return Object.freeze({...e,rect:Object.freeze({...e.rect})})}function Io(e){return Object.freeze({...e,classNames:Object.freeze([...e.classNames]),matchedRules:Object.freeze(e.matchedRules.map(t=>Object.freeze({...t}))),computed:Object.freeze({...e.computed}),warnings:Object.freeze([...e.warnings])})}function ko(e){return Object.freeze({instruction:e.instruction.trim(),...e.page===void 0?{}:{page:Object.freeze({...e.page})},source:tn(e.source,e.code),react:Po(e.react),element:Lo(e.element),styles:Io(e.styles),...e.code===void 0?{}:{code:Object.freeze({...e.code})},warnings:Object.freeze([...e.warnings])})}function nn(e){if(e.targets.length<1||e.targets.length>20)throw new RangeError(`SpotPatch annotations require between 1 and ${String(20)} targets.`);let t=e.targets.map(o=>o.instruction.trim());if(t.some(o=>o.length===0||o.length>2e3)||t.reduce((o,n)=>o+n.length,0)>4e3)throw new RangeError("SpotPatch target instructions exceed the allowed bounds.");return Object.freeze({schemaVersion:3,id:e.id,locale:e.locale,page:Object.freeze({...e.page}),targets:Object.freeze(e.targets.map(ko)),createdAt:e.createdAt})}var No=new Set(Object.values(f)),Mo=new Set(zt),Do=new Set(Ht),$o=new Set(jt),rn=new Set($t),zo=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,jo=/^[A-Za-z0-9_-]+$/,Ho=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;function Ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fe(e,t){return Object.keys(e).every(o=>t.includes(o))}function re(e,t,o=0){return typeof e=="string"&&e.length>=o&&e.length<=t}function ht(e){return re(e,64,1)&&typeof e=="string"&&zo.test(e)}function Vt(e){return re(e,128,22)&&typeof e=="string"&&jo.test(e)}function mt(e){return typeof e=="string"&&Ho.test(e)&&Number.isFinite(Date.parse(e))}function et(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function an(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function on(e,t){return e===void 0||re(e,t)}function st(e){return typeof e=="string"&&No.has(e)}function sn(e){return!Ge(e)||!fe(e,["providerProfileId","providerLabel","modelProfileId","modelLabel","protocol","state","authenticated","modelAvailable","toolCalling","toolResultContinuation","streaming","checkedAt","errorCode"])?!1:ht(e.providerProfileId)&&re(e.providerLabel,100)&&ht(e.modelProfileId)&&re(e.modelLabel,100)&&(e.protocol==="responses"||e.protocol==="chat-completions")&&typeof e.state=="string"&&Mo.has(e.state)&&typeof e.authenticated=="boolean"&&typeof e.modelAvailable=="boolean"&&typeof e.toolCalling=="boolean"&&typeof e.toolResultContinuation=="boolean"&&typeof e.streaming=="boolean"&&(e.checkedAt===void 0||mt(e.checkedAt))&&(e.errorCode===void 0||st(e.errorCode))}function cn(e){if(!Ge(e)||!fe(e,["state","checkedAt","changes","canIncludeLocalChanges","errorCode"])||e.state!=="ready"&&e.state!=="consent-required"&&e.state!=="blocked"||!mt(e.checkedAt)||typeof e.canIncludeLocalChanges!="boolean"||e.errorCode!==void 0&&!st(e.errorCode)||!Ge(e.changes)||!fe(e.changes,["staged","unstaged","untracked","conflicted","total"]))return!1;let t=e.changes,{staged:o,unstaged:n,untracked:i,conflicted:r,total:a}=t;return!et(o)||!et(n)||!et(i)||!et(r)||!et(a)||a<o||a<n||a<i||a<r||a>o+n+i?!1:e.state==="ready"?a===0&&!e.canIncludeLocalChanges&&e.errorCode===void 0:e.state==="consent-required"?a>0&&r===0&&e.canIncludeLocalChanges&&e.errorCode===void 0:!e.canIncludeLocalChanges&&e.errorCode!==void 0}function Rt(e){return!Ge(e)||!fe(e,["jobId","status","providerProfileId","providerLabel","modelProfileId","modelLabel","phaseMessage","createdAt","updatedAt","canCancel","canApply","canRevert","errorCode"])?!1:Vt(e.jobId)&&typeof e.status=="string"&&rn.has(e.status)&&ht(e.providerProfileId)&&re(e.providerLabel,100)&&ht(e.modelProfileId)&&re(e.modelLabel,100)&&re(e.phaseMessage,1024)&&mt(e.createdAt)&&mt(e.updatedAt)&&typeof e.canCancel=="boolean"&&typeof e.canApply=="boolean"&&typeof e.canRevert=="boolean"&&(e.errorCode===void 0||st(e.errorCode))}function Bo(e){return Ge(e)&&fe(e,["relativePath","kind","additions","deletions"])&&re(e.relativePath,1024)&&typeof e.kind=="string"&&$o.has(e.kind)&&et(e.additions)&&et(e.deletions)}function dn(e){return Ge(e)&&fe(e,["checkId","label","status","durationMs","output"])&&ht(e.checkId)&&re(e.label,100)&&typeof e.status=="string"&&Do.has(e.status)&&et(e.durationMs)&&re(e.output,8e4)}function Uo(e){return Ge(e)&&fe(e,["jobId","summary","diff","files","checks"])&&Vt(e.jobId)&&re(e.summary,8e4)&&re(e.diff,1e6)&&Array.isArray(e.files)&&e.files.length<=100&&e.files.every(Bo)&&Array.isArray(e.checks)&&e.checks.length<=100&&e.checks.every(dn)}function ln(e){return Ge(e)&&fe(e,["snapshot","result"])&&Rt(e.snapshot)&&(e.result===void 0||Uo(e.result)&&e.result.jobId===e.snapshot.jobId)}function Go(e){return Ge(e)&&fe(e,["schemaVersion","sequence","jobId","status","timestamp","type","data"])&&e.schemaVersion===2&&an(e.sequence)&&Vt(e.jobId)&&typeof e.status=="string"&&rn.has(e.status)&&mt(e.timestamp)&&typeof e.type=="string"&&Ge(e.data)}function pn(e){if(!Go(e))return!1;let t=e.data;switch(e.type){case"snapshot":return fe(t,["snapshot"])&&Rt(t.snapshot)&&t.snapshot.jobId===e.jobId&&t.snapshot.status===e.status;case"phase":return fe(t,["message"])&&re(t.message,1024);case"tool":return fe(t,["turn","toolCallId","toolName","state","relativePath","checkLabel"])&&an(t.turn)&&re(t.toolCallId,256)&&re(t.toolName,100)&&(t.state==="started"||t.state==="succeeded"||t.state==="failed")&&on(t.relativePath,1024)&&on(t.checkLabel,100);case"check":return fe(t,["result"])&&dn(t.result);case"result-ready":return fe(t,["hasResult"])&&t.hasResult===!0;case"error":return fe(t,["code","message"])&&st(t.code)&&re(t.message,1024);default:return!1}}var Vo=2e6,un=1e5,Wo=4e6,D=class extends Error{code;constructor(t){super("SpotPatch local API request failed."),this.name="RuntimeApiError",this.code=t}};function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jo(e){if(!(!ct(e)||e.ok!==!1||!ct(e.error)))return st(e.error.code)?e.error.code:void 0}function Fo(e){if(!ct(e)||e.ok!==!0||!("data"in e))throw new D;return e.data}function qo(e){return ct(e)&&typeof e.relativePath=="string"&&(e.language==="tsx"||e.language==="jsx")&&typeof e.startLine=="number"&&typeof e.endLine=="number"&&typeof e.excerpt=="string"&&(e.boundary==="component"||e.boundary==="nearby-lines")}function fn(e){if(!(!ct(e)&&!Array.isArray(e))&&!Object.isFrozen(e)){for(let t of Object.values(e))fn(t);Object.freeze(e)}}function bt(e){return fn(e),e}async function Ko(e,t){let o=Number(e.headers.get("content-length"));if(Number.isFinite(o)&&o>t)throw new D;if(e.body===null)throw new D;let n=e.body.getReader(),i=new TextDecoder("utf-8",{fatal:!0}),r=0,a="";try{for(;;){let l=await n.read();if(l.done)return a+=i.decode(),a;if(r+=l.value.byteLength,r>t)throw await n.cancel(),new D;a+=i.decode(l.value,{stream:!0})}}catch(l){throw l instanceof D?l:new D}finally{n.releaseLock()}}function hn(e){try{return JSON.parse(e)}catch{throw new D}}async function gn(e){let t=hn(await Ko(e,Vo));if(!e.ok)throw new D(Jo(t));return Fo(t)}function Yo(e,t){if(!sn(e)||e.providerProfileId!==t.providerProfileId||e.modelProfileId!==t.modelProfileId)throw new D;return bt(e)}function vt(e,t){if(!Rt(e)||t?.jobId!==void 0&&e.jobId!==t.jobId||t?.providerProfileId!==void 0&&e.providerProfileId!==t.providerProfileId||t?.modelProfileId!==void 0&&e.modelProfileId!==t.modelProfileId)throw new D;return bt(e)}function Xo(e,t){if(!ln(e)||e.snapshot.jobId!==t)throw new D;return bt(e)}function Zo(e){if(!pn(e))throw new D;return bt(e)}function Qo(e){return{...e,annotation:{...e.annotation,targets:e.annotation.targets.map(t=>({instruction:t.instruction,source:t.source,react:t.react,element:t.element,styles:t.styles,warnings:t.warnings}))}}}function mn(e){return e instanceof D?e.code:void 0}function bn(e){let t=new Set;function o(){for(let a of t)a.abort();t.clear()}async function n(a,l,E){let A=new AbortController;t.add(A);try{let R=await e.fetch(a,{method:l,headers:{...E===void 0?{}:{"Content-Type":"application/json"},[At]:e.sessionToken},...E===void 0?{}:{body:JSON.stringify(E)},signal:A.signal});return await gn(R)}finally{t.delete(A)}}async function i(a,l){let E=new AbortController;t.add(E);try{let A=await e.fetch(rt(a,"events"),{method:"POST",headers:{"Content-Type":"application/json",[At]:e.sessionToken},body:JSON.stringify({}),signal:E.signal});if(!A.ok){await gn(A);return}if(A.body===null)throw new D;let R=A.body.getReader(),j=new TextDecoder("utf-8",{fatal:!0}),g="",k=0,V=0,L=m=>{if(m.trim().length===0)return;if(new TextEncoder().encode(m).byteLength>un)throw new D;let S=Zo(hn(m));if(S.jobId!==a||S.sequence<=V)throw new D;V=S.sequence,l(S)};try{for(;;){let m=await R.read();if(m.done){g+=j.decode(),L(g);return}if(k+=m.value.byteLength,k>Wo)throw await R.cancel(),new D;g+=j.decode(m.value,{stream:!0});let S=g.split(`
|
|
2
|
+
`);if(g=S.pop()??"",new TextEncoder().encode(g).byteLength>un)throw await R.cancel(),new D;for(let ee of S)L(ee)}}catch(m){throw m instanceof D||m instanceof DOMException&&m.name==="AbortError"?m:new D}finally{R.releaseLock()}}finally{t.delete(E)}}let r=Object.freeze({});return Object.freeze({cancelPending:o,async sourceContext(a){let l=await n(Qe.sourceContext,"POST",a);if(!qo(l))throw new D;return Object.freeze({...l})},async openEditor(a){let l=await n(Qe.openEditor,"POST",a);if(!ct(l)||l.editor!=="auto"&&l.editor!=="vscode"&&l.editor!=="cursor")throw new D;return Object.freeze({editor:l.editor})},async agentCapability(a){return Yo(await n(Qe.agentCapability,"POST",a),a)},async agentWorkspaceHealth(){let a=await n(Qe.agentWorkspaceHealth,"POST",r);if(!cn(a))throw new D;return bt(a)},async createAgentJob(a){let l=Qo(a);return vt(await n(Qe.agentJobs,"POST",l),a)},agentEvents:i,async agentResult(a){return Xo(await n(rt(a,"result"),"POST",r),a)},async cancelAgentJob(a){return vt(await n(rt(a,"cancel"),"POST",r),{jobId:a})},async applyAgentJob(a){return vt(await n(rt(a,"apply"),"POST",r),{jobId:a})},async revertAgentJob(a){return vt(await n(rt(a,"revert"),"POST",r),{jobId:a})},dispose(){o()}})}var er=500,yn=256;function tr(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function nr(e){return Et(e)}function xn(e,t,o){if(!nr(e))return e==="href"||e==="src"?Ze(t,o):e==="d"&&t.length>yn?`${t.slice(0,yn)}…`:tr(G(t),er)}function Ae(e){return G(e)}var Sn=Object.freeze(["display","position","inset","top","right","bottom","left","width","height","min-width","min-height","max-width","max-height","margin","padding","box-sizing","overflow","overflow-x","overflow-y","flex","flex-direction","flex-wrap","align-items","align-content","justify-content","gap","grid-template-columns","grid-template-rows","font-family","font-size","font-weight","line-height","text-align","white-space","color","background-color","border","border-radius","opacity","visibility","z-index","transform"]);var yt=Object.freeze({cascade:"CSS shorthand and longhand cascade resolution is not available in v1.",cssInJs:"Runtime CSS-in-JS rules may not include original TypeScript source locations.",inaccessibleStylesheet:"A stylesheet could not be inspected because browser security denied access.",selector:"A stylesheet selector could not be evaluated and was skipped.",state:"Dynamic pseudo-class and pseudo-element rules may be unavailable in the current state."});function or(e){return"selectorText"in e&&"style"in e}function rr(e){return"cssRules"in e}function ar(e){if(typeof e.conditionText=="string"&&e.conditionText.length>0)return e.conditionText;let t=e.cssText.indexOf("{"),o=t<0?"":e.cssText.slice(0,t).trim();return o.length===0?void 0:o}function ir(e,t,o,n,i){return e.join(" ").length+(t?.length??0)+o.reduce((r,a)=>r+a.selector.length+a.declarations.length+(a.source?.length??0)+(a.media?.length??0),0)+Object.entries(n).reduce((r,[a,l])=>r+a.length+l.length,0)+i.join(`
|
|
3
|
+
`).length}function sr(e,t){return e.href===null?void 0:Ze(e.href,t)}function En(e,t,o,n,i,r){for(let a of t){if(or(a)){let l=!1;try{l=e.matches(a.selectorText)}catch{r.add(yt.selector);continue}l&&i.push(Object.freeze({selector:Ae(a.selectorText),declarations:Ae(a.style.cssText),...o===void 0?{}:{source:o},...n.length===0?{}:{media:n.join(" and ")}}));continue}if(rr(a)){let l=ar(a);En(e,a.cssRules,o,l===void 0?n:[...n,l],i,r)}}}function cr(e,t){if(t===void 0)return{};let o=t(e),n={};for(let i of Sn){let r=Ae(o.getPropertyValue(i).trim());r.length>0&&(n[i]=r)}return n}function An(e){let t=new Set([yt.state,yt.cssInJs,yt.cascade]),o=[],n=e.readCssRules??(R=>R.cssRules);for(let R of e.document.styleSheets){let j;try{j=n(R)}catch{t.add(yt.inaccessibleStylesheet);continue}En(e.element,j,sr(R,e.document.baseURI),[],o,t)}let i=Array.from(e.element.classList),r=e.element.getAttribute("style"),a=r===null?void 0:Ae(r),l=e.getComputedStyle??e.document.defaultView?.getComputedStyle.bind(e.document.defaultView),E=Object.entries(cr(e.element,l)),A=Array.from(t);for(;ir(i,a,o,Object.fromEntries(E),A)>e.maxCharacters;){if(E.length>0){E.pop();continue}if(o.length>1){o.shift();continue}break}return Object.freeze({classNames:Object.freeze(i),...a===void 0?{}:{inlineStyle:a},matchedRules:Object.freeze(o),computed:Object.freeze(Object.fromEntries(E)),warnings:Object.freeze(A)})}var tt=Object.freeze({maxDepth:3,maxNodes:30,maxParentDepth:2,maxTextCharacters:200}),dr=new Set(["alt","autocomplete","checked","class","colspan","contenteditable","d","disabled","download","draggable","for","height","hidden","href","id","max","maxlength","min","minlength","multiple","name","open","pattern","placeholder","readonly","rel","required","role","rowspan","selected","src","step","style","tabindex","target","title","type","width"]),lr=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function Rn(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}function pr(e){return dr.has(e)||e.startsWith("aria-")||e==="data-testid"}function vn(e){let t=e.tagName.toLowerCase(),o=[],n=e.ownerDocument.baseURI;for(let i of e.attributes){let r=i.name.toLowerCase();if(!pr(r))continue;let a=xn(r,i.value,n);a!==void 0&&o.push(`${r}="${Rn(a)}"`)}return`<${t}${o.length===0?"":` ${o.join(" ")}`}>`}function Tn(e){return G(e).replaceAll(/\s+/gu," ").trim()}function wn(e,t,o,n){if(o.nodeCount>=tt.maxNodes){o.truncated=!0;return}o.nodeCount+=1;let i=" ".repeat(t),r=e.tagName.toLowerCase();if(n.push(`${i}${vn(e)}`),!lr.has(r)){for(let a of e.childNodes){if(o.nodeCount>=tt.maxNodes){o.truncated=!0;break}if(a.nodeType===3){let l=Tn(a.textContent??"");if(l.length>0){o.nodeCount+=1;let E=l.length<=tt.maxTextCharacters?l:`${l.slice(0,tt.maxTextCharacters)}…`;n.push(`${" ".repeat(t+1)}${Rn(E)}`)}continue}if(a.nodeType===1){if(t>=tt.maxDepth){o.truncated=!0;continue}wn(a,t+1,o,n)}}o.truncated&&t===0&&n.push(" …"),n.push(`${i}</${r}>`)}}function ur(e){let t=[],o=e.parentElement;for(;o!==null&&t.length<tt.maxParentDepth;)t.push(vn(o)),o=o.parentElement;return t}function gr(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}…`}function Cn(e){return Array.from(e).map(t=>/[a-z\d_-]/iu.test(t)?t:`\\${t.charCodeAt(0).toString(16)} `).join("")}function fr(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function hr(e){let t=e.tagName.toLowerCase();if(e.id.length>0)return`${t}#${Cn(e.id)}`;let o=e.getAttribute("data-testid");if(o!==null&&o.length>0)return`${t}[data-testid="${fr(o)}"]`;let n=Array.from(e.classList).slice(0,2).map(l=>`.${Cn(l)}`).join(""),i=e.parentElement===null?[]:Array.from(e.parentElement.children).filter(l=>l.tagName===e.tagName),r=i.indexOf(e),a=i.length>1&&r>=0?`:nth-of-type(${String(r+1)})`:"";return`${t}${n}${a}`}function mr(e){let t=[],o=e;for(;o!==null&&t.length<5;){let n=hr(o);if(t.unshift(n),o.id.length>0||o.hasAttribute("data-testid"))break;o=o.parentElement}return t.join(" > ")}function On(e){let t=["<!-- Selected element -->"],o={nodeCount:0,truncated:!1};wn(e.element,0,o,t);let n=ur(e.element);n.length>0&&t.push("<!-- Parent context: nearest first -->",...n);let i=Tn(e.element.textContent),r=e.element.getBoundingClientRect(),a=e.element.getAttribute("role");return Object.freeze({tagName:e.element.tagName.toLowerCase(),selector:mr(e.element),sanitizedHtml:gr(t.join(`
|
|
4
|
+
`),e.maxCharacters),...i.length===0?{}:{textPreview:i.length<=tt.maxTextCharacters?i:`${i.slice(0,tt.maxTextCharacters)}…`},...a===null?{}:{role:a},rect:Object.freeze({x:r.x,y:r.y,width:r.width,height:r.height})})}function _n(e){return/Mac|iPhone|iPad|iPod/i.test(e)}function br(e){return e.toLowerCase()}function Pn(e){return e instanceof Element?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e.closest("[contenteditable]:not([contenteditable='false'])")!==null:!1}function Ln(e,t,o){let n=t.split("+").map(R=>R.trim().toLowerCase()).filter(R=>R.length>0),i=n.find(R=>R!=="mod"&&R!=="meta"&&R!=="ctrl"&&R!=="control"&&R!=="alt"&&R!=="option"&&R!=="shift");if(i===void 0||br(e.key)!==i)return!1;let r=n.includes("mod"),a=n.includes("meta")||r&&_n(o),l=n.includes("ctrl")||n.includes("control")||r&&!_n(o),E=n.includes("alt")||n.includes("option"),A=n.includes("shift");return e.metaKey===a&&e.ctrlKey===l&&e.altKey===E&&e.shiftKey===A}function yr(e){return Object.freeze({x:e.x,y:e.y,width:e.width,height:e.height})}function xr(e){let t=e.filter(l=>l.width>0&&l.height>0),o=t[0];if(o===void 0)return;let n=o.left,i=o.top,r=o.right,a=o.bottom;for(let l of t.slice(1))n=Math.min(n,l.left),i=Math.min(i,l.top),r=Math.max(r,l.right),a=Math.max(a,l.bottom);return Object.freeze({x:n,y:i,width:r-n,height:a-i})}function In(e,t){if(t.startsWith("inline")){let o=xr(Array.from(e.getClientRects()));if(o!==void 0)return o}return yr(e.getBoundingClientRect())}function kn(e,t){return In(e,t.getComputedStyle(e).display)}function Tt(e,t){let o=t.getComputedStyle(e);if(o.display==="none"||o.visibility==="hidden")return;let n=In(e,o.display);return n.width>0&&n.height>0?n:void 0}var at="data-spotpatch-ui",xt=Object.freeze({highlight:2147483646,controls:2147483647});function Nn(e){if(e.closest(`[${at}]`)!==null)return!0;let t=e.getRootNode();return t instanceof ShadowRoot&&t.host.hasAttribute(at)}function Sr(e,t){return Tt(e,t)!==void 0}function Er(e){return e.tagName==="HTML"||e.tagName==="BODY"}function Wt(e,t,o,n){let i=e.elementsFromPoint(o,n).filter(r=>!Nn(r)&&Sr(r,t));return i.find(r=>!Er(r))??i[0]}function Mn(e){return e instanceof Element&&Nn(e)}var Jt=Object.freeze({"en-US":Object.freeze({adapter:"Adapter",boundary:"Boundary",code:"Nearby code",component:"Component",computedStyles:"Key computed styles",confidence:"Confidence",devicePixelRatio:"Device pixel ratio",element:"Selected element",file:"File",modificationConstraint:"Determine the root cause first, then implement every target instruction as one consistent, minimum-scope change. Do not modify unrelated components. If context is insufficient, state exactly what additional information is required.",modificationRequirements:"Change requirements",origin:"Origin",pageEnvironment:"Page environment",pathname:"Pathname",reactContext:"React context",reactVersion:"React",requestedChange:"Requested change",selectedTargets:e=>`Selected targets (${String(e)})`,source:"Source",stack:"Stack",styles:"Relevant styles",supported:"supported",target:e=>`Target ${String(e)}`,title:"Title",unavailable:"Unavailable",unsupported:"unsupported",url:"URL",viewport:"Viewport",warnings:"Collection warnings",none:"None"}),"zh-CN":Object.freeze({adapter:"适配器",boundary:"代码边界",code:"附近代码",component:"组件",computedStyles:"关键计算样式",confidence:"置信度",devicePixelRatio:"设备像素比",element:"选中元素",file:"文件",modificationConstraint:"请先判断根因,再把每个目标各自的修改说明作为一个原子任务,完成一致且最小范围的修改。不要合并、忽略或扩大目标说明,不要改动无关组件;如果上下文不足,请明确说明需要哪些信息。",modificationRequirements:"修改要求",origin:"定位来源",pageEnvironment:"页面环境",pathname:"路径",reactContext:"React 上下文",reactVersion:"React",requestedChange:"修改说明",selectedTargets:e=>`已选目标(${String(e)})`,source:"源码定位",stack:"组件栈",styles:"相关样式",supported:"支持",target:e=>`目标 ${String(e)}`,title:"标题",unavailable:"不可用",unsupported:"不支持",url:"URL",viewport:"视口",warnings:"采集警告",none:"无"})});function Ar(e){return Math.max(0,...Array.from(e.matchAll(/`+/gu),t=>t[0].length))}function wt(e,t){let o="`".repeat(Math.max(3,Ar(t)+1));return`${o}${e}
|
|
5
5
|
${t}
|
|
6
|
-
${o}`}function $n(e,t){let o=e.code?.relativePath??e.source.relativePath,n=e.source.line,
|
|
7
|
-
`).find(o=>/^\s*<[a-z][^>]*>/iu.test(o))?.trim()??t}function
|
|
6
|
+
${o}`}function $n(e,t){let o=e.code?.relativePath??e.source.relativePath,n=e.source.line,i=e.source.column;return o===void 0?t.unavailable:`${G(o)}${n===void 0?"":`:${String(n)}`}${i===void 0?"":`:${String(i)}`}`}function zn(e,t){return e.split(`
|
|
7
|
+
`).find(o=>/^\s*<[a-z][^>]*>/iu.test(o))?.trim()??t}function Cr(e){let t=[e.source===void 0?void 0:`/* source: ${Ae(e.source)} */`,e.media===void 0?void 0:`/* condition: ${Ae(e.media)} */`].filter(n=>n!==void 0),o=`${Ae(e.selector)} {
|
|
8
8
|
${Ae(e.declarations)}
|
|
9
9
|
}`;return[...t,o].join(`
|
|
10
|
-
`)}function
|
|
10
|
+
`)}function Rr(e,t,o){let i=[...[e.styles.classNames.length===0?void 0:`/* classes: ${e.styles.classNames.map(Ae).join(" ")} */`,e.styles.inlineStyle===void 0?void 0:`/* inline: ${Ae(e.styles.inlineStyle)} */`].filter(r=>r!==void 0),...t.map(Cr)];return i.length===0?o.unavailable:wt("css",i.join(`
|
|
11
11
|
|
|
12
|
-
`))}function
|
|
13
|
-
`))}function
|
|
12
|
+
`))}function vr(e,t){return e.length===0?t.unavailable:wt("css",e.map(([o,n])=>`${Ae(o)}: ${Ae(n)};`).join(`
|
|
13
|
+
`))}function Tr(e,t,o,n){let i=[`- ${n.adapter}: ${e.react.supported?n.supported:n.unsupported}`,...e.react.version===void 0?[]:[`- ${n.reactVersion}: ${G(e.react.version)}`],...e.react.componentName===void 0?[]:[`- ${n.component}: ${G(e.react.componentName)}`],...t.reactStack.length===0?[]:[`- ${n.stack}: ${t.reactStack.map(G).join(" > ")}`]],r=e.code===void 0||t.codeLines.length===0?n.unavailable:`- ${n.boundary}: ${e.code.boundary}
|
|
14
14
|
|
|
15
|
-
${
|
|
16
|
-
`)))}`;return[`### ${n.target(o+1)}`,`#### ${n.requestedChange}`,t.instruction,...e.page===void 0?[]:[`#### ${n.pageEnvironment}`,`- ${n.url}: <${
|
|
15
|
+
${wt(e.code.language,G(t.codeLines.join(`
|
|
16
|
+
`)))}`;return[`### ${n.target(o+1)}`,`#### ${n.requestedChange}`,t.instruction,...e.page===void 0?[]:[`#### ${n.pageEnvironment}`,`- ${n.url}: <${Ze(e.page.url,e.page.url)}>
|
|
17
17
|
- ${n.pathname}: ${G(e.page.pathname)}
|
|
18
|
-
- ${n.title}: ${G(e.page.title)||n.unavailable}`],`#### ${n.reactContext}`,
|
|
18
|
+
- ${n.title}: ${G(e.page.title)||n.unavailable}`],`#### ${n.reactContext}`,i.join(`
|
|
19
19
|
`),`#### ${n.source}`,`- ${n.file}: ${$n(e,n)}
|
|
20
20
|
- ${n.origin}: ${e.source.origin}
|
|
21
|
-
- ${n.confidence}: ${e.source.confidence}`,`#### ${n.element}`,
|
|
21
|
+
- ${n.confidence}: ${e.source.confidence}`,`#### ${n.element}`,wt("html",G(t.dom)),`#### ${n.styles}`,Rr(e,t.matchedRules,n),`#### ${n.computedStyles}`,vr(t.computedEntries,n),`#### ${n.code}`,r,`#### ${n.warnings}`,t.warnings.length===0?`- ${n.none}`:t.warnings.map(a=>`- ${G(a)}`).join(`
|
|
22
22
|
`)].join(`
|
|
23
23
|
|
|
24
|
-
`)}function Dn(e,t){let o=
|
|
24
|
+
`)}function Dn(e,t){let o=Ze(e.page.url,e.page.url),n=Jt[e.locale];return[`## ${n.pageEnvironment}`,`- ${n.url}: <${o}>
|
|
25
25
|
- ${n.pathname}: ${G(e.page.pathname)}
|
|
26
26
|
- ${n.title}: ${t.pageTitle.length===0?n.unavailable:t.pageTitle}
|
|
27
27
|
- ${n.viewport}: ${String(e.page.viewportWidth)} × ${String(e.page.viewportHeight)}
|
|
28
|
-
- ${n.devicePixelRatio}: ${String(e.page.devicePixelRatio)}`,`## ${n.selectedTargets(e.targets.length)}`,e.targets.map((
|
|
28
|
+
- ${n.devicePixelRatio}: ${String(e.page.devicePixelRatio)}`,`## ${n.selectedTargets(e.targets.length)}`,e.targets.map((i,r)=>{let a=t.targets[r];if(a===void 0)throw new RangeError("Prompt target draft is missing.");return Tr(i,a,r,n)}).join(`
|
|
29
29
|
|
|
30
30
|
`),`## ${n.modificationRequirements}`,n.modificationConstraint].join(`
|
|
31
31
|
|
|
32
|
-
`)}function
|
|
32
|
+
`)}function wr(e,t){if(t.codeLines.length===0||e.code===void 0)return!1;if(t.codeLines.length===1){let a=t.codeLines[0]??"";return a.length<=120?t.codeLines=[]:t.codeLines=[`${a.slice(0,119)}…`],!0}let o=e.source.line??e.code.startLine,n=Math.abs(e.code.startLine-o),i=e.code.startLine+t.codeLines.length-1;return Math.abs(i-o)>=n?t.codeLines.pop():t.codeLines.shift(),!0}function Or(e){return{instruction:G(e.instruction.trim()),reactStack:[...e.react.componentStack],dom:e.element.sanitizedHtml,matchedRules:[...e.styles.matchedRules],computedEntries:Object.entries(e.styles.computed),codeLines:e.code?.excerpt.split(/\r?\n/u)??[],warnings:Array.from(new Set([...e.styles.warnings,...e.warnings]))}}function _r(e){return{pageTitle:G(e.page.title),targets:e.targets.map(Or)}}function Pr(e,t,o){let n=Jt[e.locale],i=[(r,a)=>a.computedEntries.pop()!==void 0,(r,a)=>a.reactStack.pop()!==void 0,(r,a)=>{let l=zn(a.dom,n.unavailable);return a.dom===l?!1:(a.dom=l,!0)},(r,a)=>a.matchedRules.shift()!==void 0,wr,(r,a)=>a.warnings.pop()!==void 0];for(let r of i)for(let a=0;a<e.targets.length;a+=1){let l=(o+a)%e.targets.length,E=e.targets[l],A=t.targets[l];if(E!==void 0&&A!==void 0&&r(E,A))return(l+1)%e.targets.length}}function Lr(e,t){let o=Jt[e.locale],n=e.targets.map((i,r)=>{let a=t.targets[r],l=i.react.componentName;return[`### ${o.target(r+1)}`,`- ${o.requestedChange}: ${a?.instruction??G(i.instruction)}`,`- ${o.file}: ${$n(i,o)}`,...l===void 0?[]:[`- ${o.component}: ${G(l)}`],`- ${o.element}: ${G(zn(a?.dom??i.element.sanitizedHtml,o.unavailable))}`].join(`
|
|
33
33
|
`)});return[`## ${o.selectedTargets(e.targets.length)}`,n.join(`
|
|
34
34
|
|
|
35
35
|
`),`## ${o.modificationRequirements}`,o.modificationConstraint].join(`
|
|
36
36
|
|
|
37
|
-
`)}function
|
|
37
|
+
`)}function Ir(e,t){let o=_r(e),n=Dn(e,o),i=0;for(;n.length>t;){let a=Pr(e,o,i);if(a===void 0)if(o.pageTitle.length>0)o.pageTitle="";else break;else i=a;n=Dn(e,o)}if(n.length<=t)return n;let r=Lr(e,o);if(r.length>t)throw new RangeError("Prompt budget cannot preserve every target instruction and source location.");return r}function jn(e){if(!Number.isSafeInteger(e.maxCharacters)||e.maxCharacters<=0)throw new RangeError("Prompt character budget must be a positive integer.");return Object.freeze({compose(t){return Ir(t,e.maxCharacters)}})}var de=Object.freeze({idle:Object.freeze({status:"idle"}),inspecting:Object.freeze({status:"inspecting"}),selected:Object.freeze({status:"selected"}),previewing:Object.freeze({status:"previewing"})}),Ft=de.idle;function kr(e){return e.type==="ACTIVATE"?de.inspecting:e.type==="RESTORE"?de.selected:de.idle}function Nr(e){switch(e.type){case"HOVER":return de.inspecting;case"SELECT":return de.selected;case"CANCEL":return de.idle;default:return de.inspecting}}function Mr(e){switch(e.type){case"RESELECT":return de.inspecting;case"CLOSE":return de.idle;case"PREVIEW":return de.previewing;case"OPEN_EDITOR":return de.selected;default:return de.selected}}function Dr(e){switch(e.type){case"COPY_SUCCESS":case"BACK":return de.selected;case"COPY_FAILURE":return de.previewing;default:return de.previewing}}function Hn(e,t){switch(e.status){case"idle":return kr(t);case"inspecting":return Nr(t);case"selected":return Mr(t);case"previewing":return Dr(t)}}var $r="spotpatch:selection:";function Me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Q(e){return typeof e=="string"}function qe(e){return e===void 0||Q(e)}function qt(e){return Array.isArray(e)&&e.length<=256&&e.every(Q)}function Ve(e){return typeof e=="number"&&Number.isFinite(e)}function Bn(e){return e===void 0||Ve(e)}function Un(e){let t=Me(e);return t!==void 0&&Q(t.origin)&&Q(t.confidence)&&qe(t.fileId)&&qe(t.relativePath)&&Bn(t.line)&&Bn(t.column)}function zr(e){let t=Me(e);return t!==void 0&&typeof t.supported=="boolean"&&qe(t.version)&&qe(t.componentName)&&qt(t.componentStack)&&(t.source===void 0||Un(t.source))}function jr(e){let t=Me(e);return t!==void 0&&Q(t.url)&&Q(t.pathname)&&Q(t.title)&&Ve(t.viewportWidth)&&Ve(t.viewportHeight)&&Ve(t.devicePixelRatio)}function Hr(e){let t=Me(e),o=Me(t?.rect);return t!==void 0&&Q(t.tagName)&&Q(t.selector)&&Q(t.sanitizedHtml)&&qe(t.textPreview)&&qe(t.role)&&o!==void 0&&Ve(o.x)&&Ve(o.y)&&Ve(o.width)&&Ve(o.height)}function Br(e){let t=Me(e),o=Me(t?.computed);return t!==void 0&&qt(t.classNames)&&qe(t.inlineStyle)&&Array.isArray(t.matchedRules)&&t.matchedRules.length<=256&&t.matchedRules.every(n=>{let i=Me(n);return i!==void 0&&Q(i.selector)&&Q(i.declarations)&&qe(i.source)&&qe(i.media)})&&o!==void 0&&Object.values(o).every(Q)&&qt(t.warnings)}function Ur(e){let t=Me(e);return t!==void 0&&Q(t.relativePath)&&Q(t.language)&&Ve(t.startLine)&&Ve(t.endLine)&&Q(t.excerpt)&&Q(t.boundary)}function Gr(e){let t=Me(e);return t!==void 0&&Q(t.id)&&Q(t.instruction)&&jr(t.page)&&Un(t.source)&&zr(t.react)&&Hr(t.element)&&Br(t.styles)&&(t.code===void 0||Ur(t.code))}function Vr(e,t){let o=Me(e);if(o?.version!==1||typeof o.open!="boolean"||!Number.isSafeInteger(o.sequence)||Number(o.sequence)<0||o.activeTargetId!==void 0&&typeof o.activeTargetId!="string"||!Array.isArray(o.targets)||o.targets.length===0||o.targets.length>t||!o.targets.every(Gr))return;let n=o.targets,i=n.map(({id:r})=>r);if(!(new Set(i).size!==i.length||o.activeTargetId!==void 0&&!i.includes(o.activeTargetId)))return{...o.activeTargetId===void 0?{}:{activeTargetId:o.activeTargetId},open:o.open,sequence:Number(o.sequence),targets:n}}function Gn(e,t,o){let n=`${$r}${t}`,i;try{i=e.sessionStorage}catch{i=void 0}return Object.freeze({clear(){try{i?.removeItem(n)}catch{}},load(){let r;try{r=i?.getItem(n)??null}catch{return}if(!(r===null||r.length>1e6))try{return Vr(JSON.parse(r),o)}catch{return}},save(r){try{i?.setItem(n,JSON.stringify({version:1,...r}))}catch{}}})}var Vn=Object.freeze({supported:!1,componentStack:Object.freeze([])});function Jn(e){return Ut(e.getAttribute(Bt))}function Wr(e){let t=e.parentElement;for(;t!==null;){let o=Jn(t);if(o!==void 0)return o;t=t.parentElement}}function Wn(e,t,o){return Object.freeze({fileId:e.fileId,line:e.line,column:e.column,origin:t,confidence:o})}function Jr(){return Object.freeze({origin:"none",confidence:"unknown"})}function Kt(e){return e.fileId===void 0||e.line===void 0||e.column===void 0?void 0:Object.freeze({fileId:e.fileId,line:e.line,column:e.column})}function Fn(e){let t=!0;function o(n){if(!t)return Vn;try{return e.adapter.inspect(n)}catch{return t=!1,e.onAdapterError?.(),Vn}}return Object.freeze({resolve(n){let i=Jn(n),r=o(n);if(i!==void 0)return Object.freeze({react:r,source:Wn(i,"jsx-host","exact")});if(r.source!==void 0)return Object.freeze({react:r,source:r.source});let a=Wr(n);return Object.freeze(a!==void 0?{react:r,source:Wn(a,"dom-ancestor","approximate")}:{react:r,source:Jr()})},dispose(){t=!1,e.adapter.dispose()}})}function d(e,t){let o=e.createElement(t);return o.setAttribute(at,""),o}function q(e,t,o=""){let n=d(e,"button");return n.type="button",n.className=o,n.textContent=t,n}var Kn=`
|
|
38
38
|
.spotpatch-agent {
|
|
39
39
|
margin-top: 10px;
|
|
40
40
|
overflow: hidden;
|
|
@@ -142,6 +142,13 @@ ${vt(e.code.language,G(t.codeLines.join(`
|
|
|
142
142
|
line-height: 1.5;
|
|
143
143
|
}
|
|
144
144
|
.spotpatch-consent input { width: 14px; height: 14px; flex: none; margin: 2px 0 0; accent-color: var(--spotpatch-accent); }
|
|
145
|
+
.spotpatch-trusted-consent {
|
|
146
|
+
border: 1px solid rgb(251 191 36 / 20%);
|
|
147
|
+
border-radius: 10px;
|
|
148
|
+
padding: 9px 10px;
|
|
149
|
+
color: #e5e7eb;
|
|
150
|
+
background: rgb(120 53 15 / 10%);
|
|
151
|
+
}
|
|
145
152
|
.spotpatch-workspace-consent {
|
|
146
153
|
margin-top: 9px;
|
|
147
154
|
border: 1px solid rgb(251 191 36 / 18%);
|
|
@@ -239,7 +246,7 @@ ${vt(e.code.language,G(t.codeLines.join(`
|
|
|
239
246
|
white-space: pre;
|
|
240
247
|
user-select: text;
|
|
241
248
|
}
|
|
242
|
-
`;function Fn(e,t,o,n){let s=e.createElement("option");s.value=o,s.textContent=n,t.append(s)}function Yn(e,t,o){let n=o.messages(),s=d(e,"section");s.className="spotpatch-agent",s.hidden=!t.enabled;let r=d(e,"div");r.className="spotpatch-agent-head";let a=d(e,"span");a.className="spotpatch-agent-title";let l=d(e,"span");l.className="spotpatch-agent-badge",r.append(a,l);let E=d(e,"div");E.className="spotpatch-agent-setup";let A=d(e,"div");A.className="spotpatch-agent-selectors";let R=d(e,"label"),j=d(e,"span"),u=d(e,"select");R.append(j,u);let L=d(e,"label"),V=d(e,"span"),P=d(e,"select");L.append(V,P),A.append(R,L);let b=d(e,"label");b.className="spotpatch-consent";let x=d(e,"input");x.type="checkbox";let Q=d(e,"span");b.append(x,Q);let Y=d(e,"label");Y.className="spotpatch-consent spotpatch-workspace-consent",Y.hidden=!0;let h=d(e,"input");h.type="checkbox";let S=d(e,"span"),C=d(e,"strong"),T=d(e,"small");S.append(C,T),Y.append(h,S);let D=d(e,"div");D.className="spotpatch-agent-health-list";let F=d(e,"p");F.className="spotpatch-agent-workspace",F.dataset.state="idle";let $=d(e,"p");$.className="spotpatch-agent-capability",$.dataset.state="idle",D.append(F,$),E.append(A,b,Y,D);let ae=d(e,"div");ae.className="spotpatch-agent-job",ae.hidden=!0;let ie=d(e,"div");ie.className="spotpatch-agent-job-meta";let B=d(e,"span");B.className="spotpatch-agent-model";let k=d(e,"span");k.className="spotpatch-agent-status",ie.append(B,k);let Le=d(e,"p");Le.className="spotpatch-agent-phase";let he=d(e,"p");he.className="spotpatch-agent-error",he.hidden=!0;let X=d(e,"ul");X.className="spotpatch-agent-activity";let Re=d(e,"div");Re.className="spotpatch-agent-result",Re.hidden=!0;let ve=d(e,"p");ve.className="spotpatch-agent-summary";let me=d(e,"ul");me.className="spotpatch-agent-files";let ee=d(e,"div");ee.className="spotpatch-agent-checks";let N=d(e,"pre");N.className="spotpatch-agent-diff",N.tabIndex=0,N.setAttribute("aria-label",n.agent.diffAriaLabel),Re.append(ve,me,ee,N),ae.append(ie,Le,he,X,Re),s.append(r,E,ae);let be=K(e,n.agent.testConnection),Te=K(e,n.agent.verifyAndRun,"spotpatch-run"),te=K(e,n.agent.cancel),le=K(e,n.agent.apply,"spotpatch-primary"),De=K(e,n.agent.revert),ye=K(e,n.agent.revise),we=t.enabled?t.providers:[],$e=new Map(we.map(m=>[m.id,m])),w=!1,Oe=!0,ne=!1,_=!1,se=!1,oe=!1,Ce,Se,pe=[],Ie,xe="idle",_e=n.agent.connectionNotTested,ke,W="idle",Pe,Ne;for(let m of we)Fn(e,u,m.id,m.label);t.enabled&&(u.value=t.defaultProvider);let Ee=()=>$e.get(u.value),Ve=()=>{let m=Ee();if(P.replaceChildren(),m===void 0){Q.textContent=n.agent.providerUnavailable;return}for(let i of m.models)Fn(e,P,i.id,i.label);P.value=m.defaultModel,Q.textContent=n.agent.consent(m.label)},J=()=>{let m=t.enabled&&ne&&!_;Te.textContent=se?n.agent.verifying:oe?n.agent.run:n.agent.verifyAndRun,Te.classList.toggle("spotpatch-primary",oe),be.hidden=!m,Te.hidden=!m,be.disabled=!Oe||se||Ee()===void 0,Te.disabled=!Oe||se||!w||!x.checked||W==="idle"||W==="checking"||W==="blocked"||W==="consent-required"&&!h.checked||Ee()===void 0||P.value.length===0,(!_||!ne)&&(te.hidden=!0,le.hidden=!0,De.hidden=!0,ye.hidden=!0)},ze=()=>{if(W==="idle")F.textContent=n.agent.workspaceNotChecked;else if(W==="checking")F.textContent=n.agent.checkingWorkspace;else if(W==="ready")F.textContent=n.agent.workspaceReady;else if(W==="consent-required"){let m=Pe?.changes;F.textContent=n.agent.workspaceDirty(m?.staged??0,m?.unstaged??0,m?.untracked??0)}else F.textContent=Ne===void 0?n.errors.INTERNAL_ERROR:n.errors[Ne]};function je(){Ve(),x.checked=!1,$.dataset.state="idle",$.textContent=n.agent.connectionNotTested,xe="idle",_e=n.agent.connectionNotTested,ke=void 0,oe=!1,J()}function ue(){$.dataset.state="idle",$.textContent=n.agent.connectionNotTested,xe="idle",_e=n.agent.connectionNotTested,ke=void 0,oe=!1,J()}Ve(),u.addEventListener("change",je),P.addEventListener("change",ue),x.addEventListener("change",J),h.addEventListener("change",J);function He(){if(Ce===void 0)return;let m=Ce,i=Se;B.textContent=`${m.providerLabel} · ${m.modelLabel}`,k.textContent=n.agent.status(m.status),Le.textContent=m.phaseMessage;let c=Ie??m.errorCode;he.hidden=c===void 0,he.textContent=c===void 0?"":n.errors[c],X.replaceChildren();for(let g of pe.slice(-8)){let O=d(e,"li");O.dataset.state=g.state,O.textContent=g.label,X.append(O)}Re.hidden=i===void 0,ve.textContent=i?.summary??"",me.replaceChildren(),ee.replaceChildren(),N.textContent=i?.diff??"";for(let g of i?.files??[]){let O=d(e,"li");O.textContent=`${g.kind} ${g.relativePath} (+${String(g.additions)} / -${String(g.deletions)})`,me.append(O)}for(let g of i?.checks??[]){let O=d(e,"details"),z=d(e,"summary");z.textContent=`${g.label}: ${g.status} · ${String(g.durationMs)} ms`;let I=d(e,"pre");I.textContent=g.output.length===0?n.agent.noOutput:g.output,O.append(z,I),ee.append(O)}be.hidden=!0,Te.hidden=!0,te.hidden=!ne||!m.canCancel,te.textContent=m.status==="awaiting-review"?n.agent.discard:n.agent.cancel,le.hidden=!ne||!m.canApply,De.hidden=!ne||!m.canRevert,ye.hidden=!ne||!["completed","cancelled","reverted","failed"].includes(m.status)}function Ke(){n=o.messages(),a.textContent=n.agent.title,l.textContent=t.enabled&&t.applyMode==="auto"?n.agent.autoGated:n.agent.review,j.textContent=n.agent.provider,V.textContent=n.agent.model,u.setAttribute("aria-label",n.agent.providerAriaLabel),P.setAttribute("aria-label",n.agent.modelAriaLabel),C.textContent=n.agent.includeLocalChanges,T.textContent=n.agent.includeLocalChangesHelp,N.setAttribute("aria-label",n.agent.diffAriaLabel),be.textContent=n.agent.testConnection,le.textContent=n.agent.apply,De.textContent=n.agent.revert,ye.textContent=n.agent.revise;let m=Ee();Q.textContent=m===void 0?n.agent.providerUnavailable:n.agent.consent(m.label),xe==="idle"?$.textContent=n.agent.connectionNotTested:xe==="probing"?$.textContent=n.agent.testingCapability:xe==="ready"?$.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:ke!==void 0?$.textContent=n.errors[ke]:Ee()===void 0?$.textContent=n.agent.providerUnavailable:$.textContent=_e,ze(),J(),He()}let nt=o.subscribe(Ke);return Ke(),Object.freeze({root:s,providerSelect:u,modelSelect:P,consentCheckbox:x,workspaceConsentCheckbox:h,testButton:be,runButton:Te,cancelButton:te,applyButton:le,revertButton:De,resetButton:ye,consentGranted(){return x.checked},workspaceConsentGranted(){return h.checked},readSelection(){let m=Ee(),i=m?.models.find(c=>c.id===P.value);return m===void 0||i===void 0?void 0:Object.freeze({providerProfileId:m.id,modelProfileId:i.id})},renderCapability(m,i,c,g){xe=m,_e=i,ke=g,se=m==="probing",oe=m==="ready"&&c?.state==="agent-ready",$.dataset.state=m,$.textContent=c?.state==="agent-ready"?`${i} · ${n.agent.toolsReady}`:i,J()},renderWorkspaceHealth(m,i,c){W=m,Pe=i,Ne=c??i?.errorCode,F.dataset.state=m,m!=="checking"&&(Y.hidden=m!=="consent-required"),(m==="idle"||m==="ready"||m==="blocked")&&(h.checked=!1),ze(),J()},renderJob(m,i,c,g){_=!0,E.hidden=!0,ae.hidden=!1,u.disabled=!0,P.disabled=!0,x.disabled=!0,h.disabled=!0,Ce=m,Se=i,pe=c,Ie=g,He()},resetJob(){_=!1,Ce=void 0,Se=void 0,pe=[],Ie=void 0,E.hidden=!1,ae.hidden=!0,u.disabled=!1,P.disabled=!1,x.disabled=!1,h.disabled=!1,X.replaceChildren(),me.replaceChildren(),ee.replaceChildren(),N.textContent="",he.textContent="",he.hidden=!0,J()},setContextReady(m){w=m,J()},setEditingEnabled(m){Oe=m,u.disabled=!m||_,P.disabled=!m||_,x.disabled=!m||_,h.disabled=!m||_,J()},setProviderConsent(m){x.checked=m,J()},setSelectionVisible(m){ne=m,J(),m||(te.hidden=!0,le.hidden=!0,De.hidden=!0,ye.hidden=!0)},dispose(){nt(),u.removeEventListener("change",je),P.removeEventListener("change",ue),x.removeEventListener("change",J),h.removeEventListener("change",J)}})}var Xn="http://www.w3.org/2000/svg",Jr="";function qr(e){if(e!==void 0)return{content:e,viewBox:"0 0 512 512"};let t=typeof __SPOTPATCH_BRAND_MARK_CONTENT__=="string"?__SPOTPATCH_BRAND_MARK_CONTENT__:void 0;return typeof t=="string"?{content:t,viewBox:"0 0 512 512"}:{content:Jr,viewBox:"0 0 1 1"}}function Fr(e,t,o){let n=e.createElementNS(Xn,t);for(let[s,r]of Object.entries(o))n.setAttribute(s,r);return n}function Zn(e,t){let o=qr(t),n=Fr(e,"svg",{xmlns:Xn,class:"spotpatch-brand-mark",viewBox:o.viewBox,"aria-hidden":"true",focusable:"false"});return n.innerHTML=o.content,n}function tt(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function Qn({dialogHeight:e,dialogWidth:t,target:o,viewportHeight:n,viewportWidth:s}){let r=s-t-16,a=n-e-16,l=tt((s-t)/2,16,r),E=tt((n-e)/2,16,a);if(o===void 0)return Object.freeze({anchorX:tt(t/2,22,t-22),anchorY:tt(e/2,22,e-22),left:l,mode:"viewport",top:E});let A=o.x+o.width/2,R=o.y+o.height/2,j=tt(A-t/2,16,r),u=tt(R-e/2,16,a),L=j,V=u,P="viewport";return o.width>=t+48&&o.height>=e+48?P="center":o.y-e-14>=16?(V=o.y-e-14,P="above"):o.y+o.height+14+e<=n-16?(V=o.y+o.height+14,P="below"):o.x+o.width+14+t<=s-16?(L=o.x+o.width+14,P="right"):o.x-t-14>=16&&(L=o.x-t-14,P="left"),Object.freeze({anchorX:tt(A-L,22,t-22),anchorY:tt(R-V,22,e-22),left:L,mode:P,top:V})}var Kr=Object.freeze({queued:"Queued",preparing:"Preparing",running:"Running",validating:"Validating","awaiting-review":"Awaiting review",applying:"Applying",applied:"Applied",completed:"Completed",cancelling:"Cancelling",cancelled:"Cancelled",reverting:"Reverting",reverted:"Reverted",failed:"Failed"}),Yr=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),Xr=Object.freeze({[f.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[f.INVALID_TOKEN]:"The local SpotPatch session expired.",[f.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[f.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[f.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[f.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[f.EDITOR_OPEN_FAILED]:"The editor request failed.",[f.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[f.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[f.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[f.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[f.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[f.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not complete the required tool-call probe.",[f.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[f.AGENT_BUSY]:"Another write Agent job is still active.",[f.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[f.AGENT_CANCELLED]:"The Agent job was cancelled.",[f.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[f.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[f.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[f.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[f.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[f.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[f.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[f.TOOL_DENIED]:"A tool request violated local safety policy.",[f.TOOL_INPUT_INVALID]:"Invalid tool request.",[f.TOOL_ARGUMENTS_INVALID]:"Tool arguments are invalid.",[f.TOOL_CALL_ID_CONFLICT]:"Tool ID conflicts in this turn.",[f.TOOL_PATH_DENIED]:"The model requested a protected or external path.",[f.PATCH_REJECTED]:"The patch violated local policy.",[f.VALIDATION_FAILED]:"Required checks failed; changes cannot be applied.",[f.APPLY_CONFLICT]:"Agent-touched files changed; nothing was overwritten.",[f.INTERNAL_ERROR]:"The Agent failed without exposing private details."}),Zr=Object.freeze({[f.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[f.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[f.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[f.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[f.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[f.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[f.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[f.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[f.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[f.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[f.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[f.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[f.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未通过必要的工具调用能力探测。",[f.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[f.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[f.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[f.AGENT_CANCELLED]:"Agent 任务已取消。",[f.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[f.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[f.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[f.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[f.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[f.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[f.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[f.TOOL_DENIED]:"工具请求违反本地安全策略。",[f.TOOL_INPUT_INVALID]:"工具请求无效。",[f.TOOL_ARGUMENTS_INVALID]:"工具参数无效。",[f.TOOL_CALL_ID_CONFLICT]:"本轮工具 ID 冲突。",[f.TOOL_PATH_DENIED]:"模型请求了受保护或项目外路径。",[f.PATCH_REJECTED]:"补丁违反本地策略。",[f.VALIDATION_FAILED]:"必需检查失败,无法应用变更。",[f.APPLY_CONFLICT]:"Agent 触及文件已变化,未覆盖。",[f.INTERNAL_ERROR]:"Agent 失败,未暴露私有细节。"}),Qr=Object.freeze({adapter:"React adapter",api:"API",apiStatuses:Object.freeze({connected:"connected",failed:"failed",loading:"loading","not-required":"not required"}),available:"available",boundary:"Boundary",boundaries:Object.freeze({component:"component","nearby-lines":"nearby lines"}),browserContext:"Browser context",collectionStatuses:Object.freeze({failed:"failed",loading:"loading",ready:"ready"}),component:"Component",confidence:"Confidence",confidenceLabels:Object.freeze({exact:"exact element source",probable:"probable owning component",approximate:"nearest business container",unknown:"source not found"}),cssWarnings:"CSS warnings",lineLocation:(e,t)=>`line ${String(e)}${t===void 0?"":`, column ${String(t)}`}`,origin:"Origin",source:"Source",sourceContext:"Source context",stack:"Stack",target:(e,t)=>`Target ${String(e)}${t?" (active)":""}`,unavailable:"unavailable",unsupported:"unsupported",warning:"Warning"}),ea=Object.freeze({adapter:"React 适配器",api:"API",apiStatuses:Object.freeze({connected:"已连接",failed:"失败",loading:"加载中","not-required":"无需请求"}),available:"可用",boundary:"代码边界",boundaries:Object.freeze({component:"完整组件","nearby-lines":"附近代码"}),browserContext:"浏览器上下文",collectionStatuses:Object.freeze({failed:"失败",loading:"采集中",ready:"已就绪"}),component:"组件",confidence:"置信度",confidenceLabels:Object.freeze({exact:"精确元素源码",probable:"可能的所属组件",approximate:"最近业务容器",unknown:"未找到源码"}),cssWarnings:"CSS 警告",lineLocation:(e,t)=>`第 ${String(e)} 行${t===void 0?"":`,第 ${String(t)} 列`}`,origin:"定位来源",source:"源码",sourceContext:"源码上下文",stack:"组件栈",target:(e,t)=>`目标 ${String(e)}${t?"(当前)":""}`,unavailable:"不可用",unsupported:"不支持",warning:"警告"}),ta=Object.freeze({"en-US":Object.freeze({localeName:"EN",alternateLocaleName:"中",switchLocale:"Switch interface language to Chinese",brand:Object.freeze({name:"SpotPatch",context:"Live context",repository:"GitHub ↗",repositoryTitle:"Star SpotPatch on GitHub"}),trigger:Object.freeze({select:"Select element",stop:"Stop selecting",title:e=>`Toggle SpotPatch (${e})`}),dialog:Object.freeze({close:"Close SpotPatch",editTitle:"Plan the change",editSubtitle:"Give each selected target its own precise instruction.",previewTitle:"Review the request",previewSubtitle:"Verify the complete context before it leaves the browser."}),context:Object.freeze({collecting:"Collecting context",ready:"Context ready",partial:"Partial context",sourceUnavailable:"Source unavailable",selectedElement:"Selected element",selectedCount:e=>`${String(e)} elements selected`}),targets:Object.freeze({title:"Selected targets",ariaLabel:"Selected targets and change instructions",count:(e,t)=>`${String(e)} of ${String(t)}`,complete:(e,t)=>`${String(e)} of ${String(t)} described`,instructionBudget:(e,t)=>`${String(e)} / ${String(t)} characters`,instructionBudgetExceeded:(e,t)=>`${String(e)} / ${String(t)} characters — reduce the request`,statusReady:"Ready",statusPartial:"Partial",statusCollecting:"Collecting",instructionReady:"Instruction added",instructionMissing:"Needs instruction",instructionLabel:e=>`Change for ${e}`,instructionPlaceholder:"Describe the desired result for this target, including constraints…",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`Edit target ${String(e)}`,remove:e=>`Remove target ${String(e)}`,removeTitle:"Remove target",addTitle:"Add another element to this request",limitTitle:e=>`Selection limit reached (${String(e)})`}),diagnostics:Object.freeze({title:"Captured context",resolving:"Resolving source…",noExactSource:"No exact source marker",promptAriaLabel:"Generated prompt"}),summary:Qr,actions:Object.freeze({addElement:"Add element",reselect:"Start over",openEditor:"Open source",openTarget:e=>`Open source for target ${String(e)}`,preview:"Preview prompt",copy:"Copy prompt",back:"Back to edit"}),agent:Object.freeze({title:"AI code agent",review:"Review",autoGated:"Auto gated",provider:"Provider",model:"Model",providerAriaLabel:"AI provider",modelAriaLabel:"AI model",providerUnavailable:"Provider configuration is unavailable.",consent:e=>`I understand selected context and allowed source may be sent to ${e}; its data policy is my responsibility.`,connectionNotTested:"Connection not tested",workspaceNotChecked:"Local workspace not checked",checkingWorkspace:"Checking Git workspace and isolated execution…",workspaceReady:"Local workspace is ready for isolated execution",workspaceDirty:(e,t,o)=>`Local changes found · ${String(e)} staged · ${String(t)} unstaged · ${String(o)} untracked`,includeLocalChanges:"Allow the Agent to continue from my current local changes",includeLocalChangesHelp:"The Agent may edit these files. SpotPatch preserves the baseline and applies or reverts only the Agent delta.",localChangesConsentRequired:"Confirm inclusion of current local changes before running AI.",capabilityVerified:"Agent capability verified",capabilityVerifiedAnnouncement:"AI provider capability verified.",testingCapability:"Testing authentication, tools, continuation, and streaming…",applying:"Applying validated changes to the project.",cancelling:"Cancelling Agent job.",reverting:"Reverting the applied Agent change.",consentRequired:"Confirm remote provider data transmission before running AI.",toolsReady:"tools and streaming ready",testConnection:"Check environment",verifyAndRun:"Verify & run",verifying:"Verifying…",run:"Run AI",cancel:"Cancel agent",discard:"Discard changes",apply:"Apply changes",revert:"Revert changes",revise:"Revise request",diffAriaLabel:"Proposed source diff",noOutput:"No output.",status:e=>Kr[e]}),announcements:Object.freeze({adapterDisabled:"React inspection was disabled after an adapter failure.",selectionEnabled:"Element selection enabled.",chooseAnother:"Choose another element.",reselectAfterChange:"Choose the current elements again after the file change.",sourceLoaded:"Source context loaded.",sourceFailed:"Source context could not be loaded.",addCancelled:"Additional selection cancelled.",selectionLimit:e=>`The selection limit of ${String(e)} elements has been reached.`,chooseAdditional:(e,t)=>`Choose another element. ${String(e)} of ${String(t)} selected.`,duplicate:"That source target is already selected.",sourceProbable:"A probable React component was found without an authorized file token.",sourceMissing:"No authorized source marker was found for the selected element.",noSelectable:"No selectable element was found.",allTargetsRemoved:"All targets were removed. Choose an element to continue.",targetRemoved:"Selected target removed.",detachedTargetPreserved:"The page element was unloaded; its collected context remains selected.",contextWarning:"Browser context collection completed with a warning.",contextCollected:"Browser context collected.",editorOpening:"Opening source…",editorOpened:"Source opened in the editor.",editorFailed:"Could not open the editor. Start it or configure editor.",completeInstructions:"Add an instruction for every target and wait for context collection to finish.",promptCopied:"Prompt copied to the clipboard.",clipboardUnavailable:"Clipboard access is unavailable. Select the prompt manually.",copyFailed:"Copy failed. Select the prompt manually.",appliedTargetsDetached:"Changes applied. Reselect page elements after HMR before creating another request."}),errors:Xr}),"zh-CN":Object.freeze({localeName:"中",alternateLocaleName:"EN",switchLocale:"将界面语言切换为英文",brand:Object.freeze({name:"SpotPatch",context:"实时上下文",repository:"GitHub ↗",repositoryTitle:"在 GitHub 上 Star SpotPatch"}),trigger:Object.freeze({select:"选择元素",stop:"停止选择",title:e=>`切换 SpotPatch(${e})`}),dialog:Object.freeze({close:"关闭 SpotPatch",editTitle:"规划本次修改",editSubtitle:"为每个选中目标分别写清楚修改要求。",previewTitle:"审阅修改请求",previewSubtitle:"发送给 AI 前,请核对完整上下文与每项目标说明。"}),context:Object.freeze({collecting:"正在采集上下文",ready:"上下文已就绪",partial:"部分上下文可用",sourceUnavailable:"源码位置不可用",selectedElement:"已选元素",selectedCount:e=>`已选择 ${String(e)} 个元素`}),targets:Object.freeze({title:"修改目标",ariaLabel:"已选目标与逐项目标说明",count:(e,t)=>`${String(e)} / ${String(t)}`,complete:(e,t)=>`已描述 ${String(e)} / ${String(t)}`,instructionBudget:(e,t)=>`说明字符 ${String(e)} / ${String(t)}`,instructionBudgetExceeded:(e,t)=>`说明字符 ${String(e)} / ${String(t)},请精简后继续`,statusReady:"已就绪",statusPartial:"部分可用",statusCollecting:"采集中",instructionReady:"已填写修改说明",instructionMissing:"待填写修改说明",instructionLabel:e=>`${e} 的修改说明`,instructionPlaceholder:"描述这个目标期望达到的结果,以及不能破坏的约束……",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`编辑目标 ${String(e)}`,remove:e=>`移除目标 ${String(e)}`,removeTitle:"移除目标",addTitle:"继续为本次请求选择元素",limitTitle:e=>`已达到 ${String(e)} 个目标的上限`}),diagnostics:Object.freeze({title:"已采集上下文",resolving:"正在解析源码……",noExactSource:"没有精确源码标记",promptAriaLabel:"生成的 Prompt"}),summary:ea,actions:Object.freeze({addElement:"添加元素",reselect:"重新开始",openEditor:"打开源码",openTarget:e=>`打开目标 ${String(e)} 的源码`,preview:"预览 Prompt",copy:"复制 Prompt",back:"返回编辑"}),agent:Object.freeze({title:"AI 代码 Agent",review:"审阅模式",autoGated:"受控自动模式",provider:"模型服务",model:"模型",providerAriaLabel:"AI 模型服务",modelAriaLabel:"AI 模型",providerUnavailable:"模型服务配置不可用。",consent:e=>`我了解选中上下文与获准源码可能发送到 ${e},并自行负责其数据策略。`,connectionNotTested:"尚未测试连接",workspaceNotChecked:"尚未检查本地工作区",checkingWorkspace:"正在检查 Git 工作区与隔离执行环境……",workspaceReady:"本地工作区已满足隔离执行条件",workspaceDirty:(e,t,o)=>`发现本地修改 · 暂存 ${String(e)} · 未暂存 ${String(t)} · 未跟踪 ${String(o)}`,includeLocalChanges:"允许 Agent 基于我当前的本地修改继续",includeLocalChangesHelp:"Agent 可能继续修改这些文件;SpotPatch 会保留原基线,仅应用或撤销 Agent 自己的增量。",localChangesConsentRequired:"运行 AI 前,请确认允许纳入当前本地修改。",capabilityVerified:"Agent 能力验证通过",capabilityVerifiedAnnouncement:"AI 模型服务能力验证通过。",testingCapability:"正在验证鉴权、工具调用、连续调用与流式响应……",applying:"正在将已验证变更应用到项目。",cancelling:"正在取消 Agent 任务。",reverting:"正在撤销已应用的 Agent 变更。",consentRequired:"运行 AI 前,请先确认允许向远程模型服务传输数据。",toolsReady:"工具调用与流式响应已就绪",testConnection:"检查运行环境",verifyAndRun:"验证并运行",verifying:"验证中……",run:"运行 AI",cancel:"取消 Agent",discard:"放弃变更",apply:"应用变更",revert:"撤销变更",revise:"修改请求",diffAriaLabel:"建议的源码差异",noOutput:"没有输出。",status:e=>Yr[e]}),announcements:Object.freeze({adapterDisabled:"React 适配器异常,本次会话已停用 React 检查。",selectionEnabled:"元素选择已启用。",chooseAnother:"请选择另一个元素。",reselectAfterChange:"文件变更后,请重新选择当前页面元素。",sourceLoaded:"源码上下文已加载。",sourceFailed:"源码上下文加载失败。",addCancelled:"已取消追加选择。",selectionLimit:e=>`已达到 ${String(e)} 个元素的选择上限。`,chooseAdditional:(e,t)=>`请选择另一个元素,当前已选 ${String(e)} / ${String(t)}。`,duplicate:"该源码目标已经在当前选择中。",sourceProbable:"找到可能的 React 组件,但没有获授权的源码标记。",sourceMissing:"选中元素没有获授权的源码标记。",noSelectable:"当前位置没有可选择的元素。",allTargetsRemoved:"已移除全部目标,请重新选择元素。",targetRemoved:"已移除选中目标。",detachedTargetPreserved:"页面元素已卸载,已采集的上下文仍保留在选择中。",contextWarning:"浏览器上下文采集完成,但存在警告。",contextCollected:"浏览器上下文采集完成。",editorOpening:"正在打开源码……",editorOpened:"源码已在编辑器中打开。",editorFailed:"无法打开编辑器。请先启动编辑器或检查 editor 配置。",completeInstructions:"请为每个目标填写修改说明,并等待上下文采集完成。",promptCopied:"Prompt 已复制到剪贴板。",clipboardUnavailable:"无法访问剪贴板,请手动选择并复制 Prompt。",copyFailed:"复制失败,请手动选择并复制 Prompt。",appliedTargetsDetached:"变更已应用;HMR 后请重新选择页面元素再发起新请求。"}),errors:Zr})});function eo(e){if(e===void 0||e.trim().length===0)return;let t=e.trim().toLowerCase();return t==="zh"||t.startsWith("zh-")?"zh-CN":t==="en"||t.startsWith("en-")?"en-US":void 0}function na(e,t){if(e!=="auto")return e;let o=eo(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(eo).find(s=>s!==void 0)??"en-US"}function to(e,t="auto"){let o=na(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>ta[o],subscribe(s){return n.add(s),()=>{n.delete(s)}},toggle(){o=o==="en-US"?"zh-CN":"en-US";for(let s of n)s()}})}var no=460,oo=620,oa=Object.freeze({previewing:560,selected:oo});function ra(e){let t=e.createElement("style");return t.textContent=`
|
|
249
|
+
`;function qn(e,t,o,n){let i=e.createElement("option");i.value=o,i.textContent=n,t.append(i)}function Yn(e,t,o){let n=o.messages(),i=d(e,"section");i.className="spotpatch-agent",i.hidden=!t.enabled;let r=d(e,"div");r.className="spotpatch-agent-head";let a=d(e,"span");a.className="spotpatch-agent-title";let l=d(e,"span");l.className="spotpatch-agent-badge",r.append(a,l);let E=d(e,"div");E.className="spotpatch-agent-setup";let A=d(e,"div");A.className="spotpatch-agent-selectors";let R=d(e,"label"),j=d(e,"span"),g=d(e,"select");R.append(j,g);let k=d(e,"label"),V=d(e,"span"),L=d(e,"select");k.append(V,L),A.append(R,k);let m=d(e,"label");m.className="spotpatch-consent";let S=d(e,"input");S.type="checkbox";let ee=d(e,"span");m.append(S,ee);let K=d(e,"label");K.className="spotpatch-consent spotpatch-workspace-consent",K.hidden=!0;let h=d(e,"input");h.type="checkbox";let y=d(e,"span"),T=d(e,"strong"),O=d(e,"small");y.append(T,O),K.append(h,y);let I=d(e,"div");I.className="spotpatch-agent-health-list";let W=d(e,"p");W.className="spotpatch-agent-workspace",W.dataset.state="idle";let $=d(e,"p");$.className="spotpatch-agent-capability",$.dataset.state="idle",I.append(W,$),E.append(A,m,K,I);let ae=d(e,"div");ae.className="spotpatch-agent-job",ae.hidden=!0;let ie=d(e,"div");ie.className="spotpatch-agent-job-meta";let B=d(e,"span");B.className="spotpatch-agent-model";let N=d(e,"span");N.className="spotpatch-agent-status",ie.append(B,N);let _e=d(e,"p");_e.className="spotpatch-agent-phase";let he=d(e,"p");he.className="spotpatch-agent-error",he.hidden=!0;let Y=d(e,"ul");Y.className="spotpatch-agent-activity";let ve=d(e,"div");ve.className="spotpatch-agent-result",ve.hidden=!0;let Te=d(e,"p");Te.className="spotpatch-agent-summary";let me=d(e,"ul");me.className="spotpatch-agent-files";let te=d(e,"div");te.className="spotpatch-agent-checks";let M=d(e,"pre");M.className="spotpatch-agent-diff",M.tabIndex=0,M.setAttribute("aria-label",n.agent.diffAriaLabel),ve.append(Te,me,te,M),ae.append(ie,_e,he,Y,ve),i.append(r,E,ae);let be=q(e,n.agent.testConnection),we=q(e,n.agent.run,"spotpatch-run"),ne=q(e,n.agent.cancel),le=q(e,n.agent.apply,"spotpatch-primary"),De=q(e,n.agent.revert),ye=q(e,n.agent.revise),Oe=t.enabled?t.providers:[],xe=t.enabled&&t.applyMode==="trusted-auto";m.classList.toggle("spotpatch-trusted-consent",xe);let w=new Map(Oe.map(c=>[c.id,c])),Pe=!1,Se=!0,_=!1,F=!1,se=!1,Ce=!1,pe,ue,Le=[],Ie,Ee="idle",$e=n.agent.connectionNotTested,X,Z="idle",ze,ke;for(let c of Oe)qn(e,g,c.id,c.label);t.enabled&&(g.value=t.defaultProvider);let Re=()=>w.get(g.value),Ne=c=>c===void 0?n.agent.providerUnavailable:xe?n.agent.trustedFastConsent(c.label):n.agent.consent(c.label),je=()=>xe?S.checked:h.checked,He=()=>{let c=Re();if(L.replaceChildren(),c===void 0){ee.textContent=Ne(c);return}for(let x of c.models)qn(e,L,x.id,x.label);L.value=c.defaultModel,ee.textContent=Ne(c)},z=()=>{let c=t.enabled&&_&&!F;we.textContent=se?n.agent.verifying:n.agent.run,we.classList.toggle("spotpatch-primary",Ce),be.hidden=!c,we.hidden=!c,be.disabled=!Se||se||Re()===void 0,we.disabled=!Se||se||!Pe||!S.checked||Z==="idle"||Z==="checking"||Z==="blocked"||Z==="consent-required"&&!je()||Re()===void 0||L.value.length===0,(!F||!_)&&(ne.hidden=!0,le.hidden=!0,De.hidden=!0,ye.hidden=!0)},Be=()=>{if(Z==="idle")W.textContent=n.agent.workspaceNotChecked;else if(Z==="checking")W.textContent=n.agent.checkingWorkspace;else if(Z==="ready")W.textContent=n.agent.workspaceReady;else if(Z==="consent-required"){let c=ze?.changes;W.textContent=n.agent.workspaceDirty(c?.staged??0,c?.unstaged??0,c?.untracked??0)}else W.textContent=ke===void 0?n.errors.INTERNAL_ERROR:n.errors[ke]};function Ke(){He(),S.checked=!1,$.dataset.state="idle",$.textContent=n.agent.connectionNotTested,Ee="idle",$e=n.agent.connectionNotTested,X=void 0,Ce=!1,z()}function Ye(){$.dataset.state="idle",$.textContent=n.agent.connectionNotTested,Ee="idle",$e=n.agent.connectionNotTested,X=void 0,Ce=!1,z()}He(),g.addEventListener("change",Ke),L.addEventListener("change",Ye),S.addEventListener("change",z),h.addEventListener("change",z);function it(){if(pe===void 0)return;let c=pe,x=ue;B.textContent=`${c.providerLabel} · ${c.modelLabel}`,N.textContent=n.agent.status(c.status),_e.textContent=c.phaseMessage;let P=Ie??c.errorCode;he.hidden=P===void 0,he.textContent=P===void 0?"":n.errors[P],Y.replaceChildren();for(let C of Le.slice(-8)){let oe=d(e,"li");oe.dataset.state=C.state,oe.textContent=C.label,Y.append(oe)}ve.hidden=x===void 0,Te.textContent=x?.summary??"",me.replaceChildren(),te.replaceChildren(),M.textContent=x?.diff??"";for(let C of x?.files??[]){let oe=d(e,"li");oe.textContent=`${C.kind} ${C.relativePath} (+${String(C.additions)} / -${String(C.deletions)})`,me.append(oe)}for(let C of x?.checks??[]){let oe=d(e,"details"),dt=d(e,"summary");dt.textContent=`${C.label}: ${C.status} · ${String(C.durationMs)} ms`;let lt=d(e,"pre");lt.textContent=C.output.length===0?n.agent.noOutput:C.output,oe.append(dt,lt),te.append(oe)}be.hidden=!0,we.hidden=!0,ne.hidden=!_||!c.canCancel,ne.textContent=c.status==="awaiting-review"?n.agent.discard:n.agent.cancel,le.hidden=!_||!c.canApply,De.hidden=!_||!c.canRevert,ye.hidden=!_||!["completed","cancelled","reverted","failed"].includes(c.status)}function s(){n=o.messages(),a.textContent=n.agent.title,l.textContent=xe?n.agent.trustedFast:t.enabled&&t.applyMode==="auto"?n.agent.autoGated:n.agent.review,j.textContent=n.agent.provider,V.textContent=n.agent.model,g.setAttribute("aria-label",n.agent.providerAriaLabel),L.setAttribute("aria-label",n.agent.modelAriaLabel),T.textContent=n.agent.includeLocalChanges,O.textContent=n.agent.includeLocalChangesHelp,M.setAttribute("aria-label",n.agent.diffAriaLabel),be.textContent=n.agent.testConnection,le.textContent=n.agent.apply,De.textContent=n.agent.revert,ye.textContent=n.agent.revise;let c=Re();ee.textContent=Ne(c),Ee==="idle"?$.textContent=n.agent.connectionNotTested:Ee==="probing"?$.textContent=n.agent.testingCapability:Ee==="ready"?$.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:X!==void 0?$.textContent=n.errors[X]:Re()===void 0?$.textContent=n.agent.providerUnavailable:$.textContent=$e,Be(),z(),it()}let p=o.subscribe(s);return s(),Object.freeze({root:i,providerSelect:g,modelSelect:L,consentCheckbox:S,workspaceConsentCheckbox:h,testButton:be,runButton:we,cancelButton:ne,applyButton:le,revertButton:De,resetButton:ye,consentGranted(){return S.checked},workspaceConsentGranted(){return je()},readSelection(){let c=Re(),x=c?.models.find(P=>P.id===L.value);return c===void 0||x===void 0?void 0:Object.freeze({providerProfileId:c.id,modelProfileId:x.id})},renderCapability(c,x,P,C){Ee=c,$e=x,X=C,se=c==="probing",Ce=c==="ready"&&P?.state==="agent-ready",$.dataset.state=c,$.textContent=P?.state==="agent-ready"?`${x} · ${n.agent.toolsReady}`:x,z()},renderWorkspaceHealth(c,x,P){Z=c,ze=x,ke=P??x?.errorCode,W.dataset.state=c,c!=="checking"&&(K.hidden=xe||c!=="consent-required"),(c==="idle"||c==="ready"||c==="blocked")&&(h.checked=!1),Be(),z()},renderJob(c,x,P,C){F=!0,E.hidden=!0,ae.hidden=!1,g.disabled=!0,L.disabled=!0,S.disabled=!0,h.disabled=!0,pe=c,ue=x,Le=P,Ie=C,it()},resetJob(){F=!1,pe=void 0,ue=void 0,Le=[],Ie=void 0,E.hidden=!1,ae.hidden=!0,g.disabled=!1,L.disabled=!1,S.disabled=!1,h.disabled=!1,Y.replaceChildren(),me.replaceChildren(),te.replaceChildren(),M.textContent="",he.textContent="",he.hidden=!0,z()},setContextReady(c){Pe=c,z()},setEditingEnabled(c){Se=c,g.disabled=!c||F,L.disabled=!c||F,S.disabled=!c||F,h.disabled=!c||F,z()},setProviderConsent(c){S.checked=c,z()},setSelectionVisible(c){_=c,z(),c||(ne.hidden=!0,le.hidden=!0,De.hidden=!0,ye.hidden=!0)},dispose(){p(),g.removeEventListener("change",Ke),L.removeEventListener("change",Ye),S.removeEventListener("change",z),h.removeEventListener("change",z)}})}var Xn="http://www.w3.org/2000/svg",Fr="";function qr(e){if(e!==void 0)return{content:e,viewBox:"0 0 512 512"};let t=typeof __SPOTPATCH_BRAND_MARK_CONTENT__=="string"?__SPOTPATCH_BRAND_MARK_CONTENT__:void 0;return typeof t=="string"?{content:t,viewBox:"0 0 512 512"}:{content:Fr,viewBox:"0 0 1 1"}}function Kr(e,t,o){let n=e.createElementNS(Xn,t);for(let[i,r]of Object.entries(o))n.setAttribute(i,r);return n}function Zn(e,t){let o=qr(t),n=Kr(e,"svg",{xmlns:Xn,class:"spotpatch-brand-mark",viewBox:o.viewBox,"aria-hidden":"true",focusable:"false"});return n.innerHTML=o.content,n}function nt(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function Qn({dialogHeight:e,dialogWidth:t,target:o,viewportHeight:n,viewportWidth:i}){let r=i-t-16,a=n-e-16,l=nt((i-t)/2,16,r),E=nt((n-e)/2,16,a);if(o===void 0)return Object.freeze({anchorX:nt(t/2,22,t-22),anchorY:nt(e/2,22,e-22),left:l,mode:"viewport",top:E});let A=o.x+o.width/2,R=o.y+o.height/2,j=nt(A-t/2,16,r),g=nt(R-e/2,16,a),k=j,V=g,L="viewport";return o.width>=t+48&&o.height>=e+48?L="center":o.y-e-14>=16?(V=o.y-e-14,L="above"):o.y+o.height+14+e<=n-16?(V=o.y+o.height+14,L="below"):o.x+o.width+14+t<=i-16?(k=o.x+o.width+14,L="right"):o.x-t-14>=16&&(k=o.x-t-14,L="left"),Object.freeze({anchorX:nt(A-k,22,t-22),anchorY:nt(R-V,22,e-22),left:k,mode:L,top:V})}var Yr=Object.freeze({queued:"Queued",preparing:"Preparing",running:"Running",validating:"Validating","awaiting-review":"Awaiting review",applying:"Applying",applied:"Applied",completed:"Completed",cancelling:"Cancelling",cancelled:"Cancelled",reverting:"Reverting",reverted:"Reverted",failed:"Failed"}),Xr=Object.freeze({queued:"已排队",preparing:"准备中",running:"执行中",validating:"验证中","awaiting-review":"等待审阅",applying:"应用中",applied:"已应用",completed:"已完成",cancelling:"取消中",cancelled:"已取消",reverting:"撤销中",reverted:"已撤销",failed:"失败"}),Zr=Object.freeze({[f.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[f.INVALID_TOKEN]:"The local SpotPatch session expired.",[f.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[f.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[f.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[f.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[f.EDITOR_OPEN_FAILED]:"The editor request failed.",[f.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[f.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[f.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[f.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[f.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[f.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not start or continue the required tool call.",[f.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[f.AGENT_BUSY]:"Another write Agent job is still active.",[f.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[f.AGENT_CANCELLED]:"The Agent job was cancelled.",[f.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[f.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[f.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[f.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[f.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[f.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[f.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[f.TOOL_DENIED]:"A tool request violated local safety policy.",[f.TOOL_INPUT_INVALID]:"Invalid tool request.",[f.TOOL_ARGUMENTS_INVALID]:"Tool arguments are invalid.",[f.TOOL_CALL_ID_CONFLICT]:"Tool ID conflicts in this turn.",[f.TOOL_PATH_DENIED]:"The model requested a protected or external path.",[f.PATCH_REJECTED]:"The patch violated local policy.",[f.VALIDATION_FAILED]:"Required checks failed; changes cannot be applied.",[f.APPLY_CONFLICT]:"Agent-touched files changed; nothing was overwritten.",[f.INTERNAL_ERROR]:"The Agent failed without exposing private details."}),Qr=Object.freeze({[f.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[f.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[f.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[f.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[f.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[f.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[f.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[f.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[f.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[f.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[f.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[f.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[f.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未完成必要的工具调用或结果续接。",[f.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[f.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[f.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[f.AGENT_CANCELLED]:"Agent 任务已取消。",[f.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[f.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[f.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[f.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[f.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[f.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[f.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[f.TOOL_DENIED]:"工具请求违反本地安全策略。",[f.TOOL_INPUT_INVALID]:"工具请求无效。",[f.TOOL_ARGUMENTS_INVALID]:"工具参数无效。",[f.TOOL_CALL_ID_CONFLICT]:"本轮工具 ID 冲突。",[f.TOOL_PATH_DENIED]:"模型请求了受保护或项目外路径。",[f.PATCH_REJECTED]:"补丁违反本地策略。",[f.VALIDATION_FAILED]:"必需检查失败,无法应用变更。",[f.APPLY_CONFLICT]:"Agent 触及文件已变化,未覆盖。",[f.INTERNAL_ERROR]:"Agent 失败,未暴露私有细节。"}),ea=Object.freeze({adapter:"React adapter",api:"API",apiStatuses:Object.freeze({connected:"connected",failed:"failed",loading:"loading","not-required":"not required"}),available:"available",boundary:"Boundary",boundaries:Object.freeze({component:"component","nearby-lines":"nearby lines"}),browserContext:"Browser context",collectionStatuses:Object.freeze({failed:"failed",loading:"loading",ready:"ready"}),component:"Component",confidence:"Confidence",confidenceLabels:Object.freeze({exact:"exact element source",probable:"probable owning component",approximate:"nearest business container",unknown:"source not found"}),cssWarnings:"CSS warnings",lineLocation:(e,t)=>`line ${String(e)}${t===void 0?"":`, column ${String(t)}`}`,origin:"Origin",source:"Source",sourceContext:"Source context",stack:"Stack",target:(e,t)=>`Target ${String(e)}${t?" (active)":""}`,unavailable:"unavailable",unsupported:"unsupported",warning:"Warning"}),ta=Object.freeze({adapter:"React 适配器",api:"API",apiStatuses:Object.freeze({connected:"已连接",failed:"失败",loading:"加载中","not-required":"无需请求"}),available:"可用",boundary:"代码边界",boundaries:Object.freeze({component:"完整组件","nearby-lines":"附近代码"}),browserContext:"浏览器上下文",collectionStatuses:Object.freeze({failed:"失败",loading:"采集中",ready:"已就绪"}),component:"组件",confidence:"置信度",confidenceLabels:Object.freeze({exact:"精确元素源码",probable:"可能的所属组件",approximate:"最近业务容器",unknown:"未找到源码"}),cssWarnings:"CSS 警告",lineLocation:(e,t)=>`第 ${String(e)} 行${t===void 0?"":`,第 ${String(t)} 列`}`,origin:"定位来源",source:"源码",sourceContext:"源码上下文",stack:"组件栈",target:(e,t)=>`目标 ${String(e)}${t?"(当前)":""}`,unavailable:"不可用",unsupported:"不支持",warning:"警告"}),na=Object.freeze({"en-US":Object.freeze({localeName:"EN",alternateLocaleName:"中",switchLocale:"Switch interface language to Chinese",brand:Object.freeze({name:"SpotPatch",context:"Live context",repository:"GitHub ↗",repositoryTitle:"Star SpotPatch on GitHub"}),trigger:Object.freeze({select:"Select element",stop:"Stop selecting",title:e=>`Toggle SpotPatch (${e})`}),dialog:Object.freeze({close:"Close SpotPatch",editTitle:"Plan the change",editSubtitle:"Give each selected target its own precise instruction.",previewTitle:"Review the request",previewSubtitle:"Verify the complete context before it leaves the browser."}),context:Object.freeze({collecting:"Collecting context",ready:"Context ready",partial:"Partial context",sourceUnavailable:"Source unavailable",selectedElement:"Selected element",selectedCount:e=>`${String(e)} elements selected`}),targets:Object.freeze({title:"Selected targets",ariaLabel:"Selected targets and change instructions",count:(e,t)=>`${String(e)} of ${String(t)}`,complete:(e,t)=>`${String(e)} of ${String(t)} described`,instructionBudget:(e,t)=>`${String(e)} / ${String(t)} characters`,instructionBudgetExceeded:(e,t)=>`${String(e)} / ${String(t)} characters — reduce the request`,statusReady:"Ready",statusPartial:"Partial",statusCollecting:"Collecting",instructionReady:"Instruction added",instructionMissing:"Needs instruction",instructionLabel:e=>`Change for ${e}`,instructionPlaceholder:"Describe the desired result for this target, including constraints…",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`Edit target ${String(e)}`,remove:e=>`Remove target ${String(e)}`,removeTitle:"Remove target",addTitle:"Add another element to this request",limitTitle:e=>`Selection limit reached (${String(e)})`}),diagnostics:Object.freeze({title:"Captured context",resolving:"Resolving source…",noExactSource:"No exact source marker",promptAriaLabel:"Generated prompt"}),summary:ea,actions:Object.freeze({addElement:"Add element",reselect:"Start over",openEditor:"Open source",openTarget:e=>`Open source for target ${String(e)}`,preview:"Preview prompt",copy:"Copy prompt",back:"Back to edit"}),agent:Object.freeze({title:"AI code agent",review:"Review",autoGated:"Auto gated",trustedFast:"Trusted fast",provider:"Provider",model:"Model",providerAriaLabel:"AI provider",modelAriaLabel:"AI model",providerUnavailable:"Provider configuration is unavailable.",consent:e=>`I understand selected context and allowed source may be sent to ${e}; its data policy is my responsibility.`,trustedFastConsent:e=>`Enable trusted fast mode for ${e}: send allowed project context, include current local changes, and directly apply AI changes after required checks, including file deletions and configuration changes.`,connectionNotTested:"Optional connection check not run",workspaceNotChecked:"Local workspace not checked",checkingWorkspace:"Checking Git workspace and isolated execution…",workspaceReady:"Local workspace is ready for isolated execution",workspaceDirty:(e,t,o)=>`Local changes found · ${String(e)} staged · ${String(t)} unstaged · ${String(o)} untracked`,includeLocalChanges:"Allow the Agent to continue from my current local changes",includeLocalChangesHelp:"The Agent may edit these files. SpotPatch preserves the baseline and applies or reverts only the Agent delta.",localChangesConsentRequired:"Confirm inclusion of current local changes before running AI.",capabilityVerified:"Agent capability verified",capabilityVerifiedAnnouncement:"AI provider capability verified.",testingCapability:"Testing authentication, tools, continuation, and streaming…",applying:"Applying validated changes to the project.",cancelling:"Cancelling Agent job.",reverting:"Reverting the applied Agent change.",consentRequired:"Confirm remote provider data transmission before running AI.",toolsReady:"tools and streaming ready",testConnection:"Check environment",verifying:"Verifying…",run:"Run AI",cancel:"Cancel agent",discard:"Discard changes",apply:"Apply changes",revert:"Revert changes",revise:"Revise request",diffAriaLabel:"Proposed source diff",noOutput:"No output.",status:e=>Yr[e]}),announcements:Object.freeze({adapterDisabled:"React inspection was disabled after an adapter failure.",selectionEnabled:"Element selection enabled.",chooseAnother:"Choose another element.",reselectAfterChange:"Choose the current elements again after the file change.",sourceLoaded:"Source context loaded.",sourceFailed:"Source context could not be loaded.",addCancelled:"Additional selection cancelled.",selectionLimit:e=>`The selection limit of ${String(e)} elements has been reached.`,chooseAdditional:(e,t)=>`Choose another element. ${String(e)} of ${String(t)} selected.`,duplicate:"That source target is already selected.",sourceProbable:"A probable React component was found without an authorized file token.",sourceMissing:"No authorized source marker was found for the selected element.",noSelectable:"No selectable element was found.",allTargetsRemoved:"All targets were removed. Choose an element to continue.",targetRemoved:"Selected target removed.",detachedTargetPreserved:"The page element was unloaded; its collected context remains selected.",contextWarning:"Browser context collection completed with a warning.",contextCollected:"Browser context collected.",editorOpening:"Opening source…",editorOpened:"Source opened in the editor.",editorFailed:"Could not open the editor. Start it or configure editor.",completeInstructions:"Add an instruction for every target and wait for context collection to finish.",promptCopied:"Prompt copied to the clipboard.",clipboardUnavailable:"Clipboard access is unavailable. Select the prompt manually.",copyFailed:"Copy failed. Select the prompt manually.",appliedTargetsDetached:"Changes applied. Reselect page elements after HMR before creating another request."}),errors:Zr}),"zh-CN":Object.freeze({localeName:"中",alternateLocaleName:"EN",switchLocale:"将界面语言切换为英文",brand:Object.freeze({name:"SpotPatch",context:"实时上下文",repository:"GitHub ↗",repositoryTitle:"在 GitHub 上 Star SpotPatch"}),trigger:Object.freeze({select:"选择元素",stop:"停止选择",title:e=>`切换 SpotPatch(${e})`}),dialog:Object.freeze({close:"关闭 SpotPatch",editTitle:"规划本次修改",editSubtitle:"为每个选中目标分别写清楚修改要求。",previewTitle:"审阅修改请求",previewSubtitle:"发送给 AI 前,请核对完整上下文与每项目标说明。"}),context:Object.freeze({collecting:"正在采集上下文",ready:"上下文已就绪",partial:"部分上下文可用",sourceUnavailable:"源码位置不可用",selectedElement:"已选元素",selectedCount:e=>`已选择 ${String(e)} 个元素`}),targets:Object.freeze({title:"修改目标",ariaLabel:"已选目标与逐项目标说明",count:(e,t)=>`${String(e)} / ${String(t)}`,complete:(e,t)=>`已描述 ${String(e)} / ${String(t)}`,instructionBudget:(e,t)=>`说明字符 ${String(e)} / ${String(t)}`,instructionBudgetExceeded:(e,t)=>`说明字符 ${String(e)} / ${String(t)},请精简后继续`,statusReady:"已就绪",statusPartial:"部分可用",statusCollecting:"采集中",instructionReady:"已填写修改说明",instructionMissing:"待填写修改说明",instructionLabel:e=>`${e} 的修改说明`,instructionPlaceholder:"描述这个目标期望达到的结果,以及不能破坏的约束……",instructionCount:(e,t)=>`${String(e)} / ${String(t)}`,activate:e=>`编辑目标 ${String(e)}`,remove:e=>`移除目标 ${String(e)}`,removeTitle:"移除目标",addTitle:"继续为本次请求选择元素",limitTitle:e=>`已达到 ${String(e)} 个目标的上限`}),diagnostics:Object.freeze({title:"已采集上下文",resolving:"正在解析源码……",noExactSource:"没有精确源码标记",promptAriaLabel:"生成的 Prompt"}),summary:ta,actions:Object.freeze({addElement:"添加元素",reselect:"重新开始",openEditor:"打开源码",openTarget:e=>`打开目标 ${String(e)} 的源码`,preview:"预览 Prompt",copy:"复制 Prompt",back:"返回编辑"}),agent:Object.freeze({title:"AI 代码 Agent",review:"审阅模式",autoGated:"受控自动模式",trustedFast:"可信快速模式",provider:"模型服务",model:"模型",providerAriaLabel:"AI 模型服务",modelAriaLabel:"AI 模型",providerUnavailable:"模型服务配置不可用。",consent:e=>`我了解选中上下文与获准源码可能发送到 ${e},并自行负责其数据策略。`,trustedFastConsent:e=>`为 ${e} 启用可信快速模式:发送获准的项目上下文、纳入当前本地修改,并在必需检查通过后直接应用 AI 变更,包括删除文件与配置变更。`,connectionNotTested:"尚未执行可选连接检查",workspaceNotChecked:"尚未检查本地工作区",checkingWorkspace:"正在检查 Git 工作区与隔离执行环境……",workspaceReady:"本地工作区已满足隔离执行条件",workspaceDirty:(e,t,o)=>`发现本地修改 · 暂存 ${String(e)} · 未暂存 ${String(t)} · 未跟踪 ${String(o)}`,includeLocalChanges:"允许 Agent 基于我当前的本地修改继续",includeLocalChangesHelp:"Agent 可能继续修改这些文件;SpotPatch 会保留原基线,仅应用或撤销 Agent 自己的增量。",localChangesConsentRequired:"运行 AI 前,请确认允许纳入当前本地修改。",capabilityVerified:"Agent 能力验证通过",capabilityVerifiedAnnouncement:"AI 模型服务能力验证通过。",testingCapability:"正在验证鉴权、工具调用、连续调用与流式响应……",applying:"正在将已验证变更应用到项目。",cancelling:"正在取消 Agent 任务。",reverting:"正在撤销已应用的 Agent 变更。",consentRequired:"运行 AI 前,请先确认允许向远程模型服务传输数据。",toolsReady:"工具调用与流式响应已就绪",testConnection:"检查运行环境",verifying:"验证中……",run:"运行 AI",cancel:"取消 Agent",discard:"放弃变更",apply:"应用变更",revert:"撤销变更",revise:"修改请求",diffAriaLabel:"建议的源码差异",noOutput:"没有输出。",status:e=>Xr[e]}),announcements:Object.freeze({adapterDisabled:"React 适配器异常,本次会话已停用 React 检查。",selectionEnabled:"元素选择已启用。",chooseAnother:"请选择另一个元素。",reselectAfterChange:"文件变更后,请重新选择当前页面元素。",sourceLoaded:"源码上下文已加载。",sourceFailed:"源码上下文加载失败。",addCancelled:"已取消追加选择。",selectionLimit:e=>`已达到 ${String(e)} 个元素的选择上限。`,chooseAdditional:(e,t)=>`请选择另一个元素,当前已选 ${String(e)} / ${String(t)}。`,duplicate:"该源码目标已经在当前选择中。",sourceProbable:"找到可能的 React 组件,但没有获授权的源码标记。",sourceMissing:"选中元素没有获授权的源码标记。",noSelectable:"当前位置没有可选择的元素。",allTargetsRemoved:"已移除全部目标,请重新选择元素。",targetRemoved:"已移除选中目标。",detachedTargetPreserved:"页面元素已卸载,已采集的上下文仍保留在选择中。",contextWarning:"浏览器上下文采集完成,但存在警告。",contextCollected:"浏览器上下文采集完成。",editorOpening:"正在打开源码……",editorOpened:"源码已在编辑器中打开。",editorFailed:"无法打开编辑器。请先启动编辑器或检查 editor 配置。",completeInstructions:"请为每个目标填写修改说明,并等待上下文采集完成。",promptCopied:"Prompt 已复制到剪贴板。",clipboardUnavailable:"无法访问剪贴板,请手动选择并复制 Prompt。",copyFailed:"复制失败,请手动选择并复制 Prompt。",appliedTargetsDetached:"变更已应用;HMR 后请重新选择页面元素再发起新请求。"}),errors:Qr})});function eo(e){if(e===void 0||e.trim().length===0)return;let t=e.trim().toLowerCase();return t==="zh"||t.startsWith("zh-")?"zh-CN":t==="en"||t.startsWith("en-")?"en-US":void 0}function oa(e,t){if(e!=="auto")return e;let o=eo(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(eo).find(i=>i!==void 0)??"en-US"}function to(e,t="auto"){let o=oa(t,e),n=new Set;return Object.freeze({locale:()=>o,messages:()=>na[o],subscribe(i){return n.add(i),()=>{n.delete(i)}},toggle(){o=o==="en-US"?"zh-CN":"en-US";for(let i of n)i()}})}var no=460,oo=620,ra=Object.freeze({previewing:560,selected:oo});function aa(e){let t=e.createElement("style");return t.textContent=`
|
|
243
250
|
:host {
|
|
244
251
|
all: initial;
|
|
245
252
|
--spotpatch-bg: #0e0e12;
|
|
@@ -276,7 +283,7 @@ ${vt(e.code.language,G(t.codeLines.join(`
|
|
|
276
283
|
position: fixed;
|
|
277
284
|
right: 24px;
|
|
278
285
|
bottom: 24px;
|
|
279
|
-
z-index: ${String(
|
|
286
|
+
z-index: ${String(xt.controls)};
|
|
280
287
|
display: inline-flex;
|
|
281
288
|
align-items: center;
|
|
282
289
|
gap: 10px;
|
|
@@ -310,7 +317,7 @@ ${vt(e.code.language,G(t.codeLines.join(`
|
|
|
310
317
|
position: fixed;
|
|
311
318
|
top: 0;
|
|
312
319
|
left: 0;
|
|
313
|
-
z-index: ${String(
|
|
320
|
+
z-index: ${String(xt.highlight)};
|
|
314
321
|
box-sizing: border-box;
|
|
315
322
|
border: 2px solid var(--spotpatch-accent);
|
|
316
323
|
border-radius: 6px;
|
|
@@ -337,7 +344,7 @@ ${vt(e.code.language,G(t.codeLines.join(`
|
|
|
337
344
|
.spotpatch-selection-highlights {
|
|
338
345
|
position: fixed;
|
|
339
346
|
inset: 0;
|
|
340
|
-
z-index: ${String(
|
|
347
|
+
z-index: ${String(xt.highlight)};
|
|
341
348
|
pointer-events: none;
|
|
342
349
|
}
|
|
343
350
|
.spotpatch-selection-highlight {
|
|
@@ -378,7 +385,7 @@ ${vt(e.code.language,G(t.codeLines.join(`
|
|
|
378
385
|
position: fixed;
|
|
379
386
|
top: 16px;
|
|
380
387
|
left: 16px;
|
|
381
|
-
z-index: ${String(
|
|
388
|
+
z-index: ${String(xt.controls)};
|
|
382
389
|
box-sizing: border-box;
|
|
383
390
|
width: min(${String(no)}px, calc(100vw - 32px));
|
|
384
391
|
color: #edf0f7;
|
|
@@ -940,9 +947,9 @@ ${vt(e.code.language,G(t.codeLines.join(`
|
|
|
940
947
|
.spotpatch-repository { display: none; }
|
|
941
948
|
}
|
|
942
949
|
${Kn}
|
|
943
|
-
`,t}function
|
|
944
|
-
`).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function ro(e,t,o=Object.freeze({enabled:!1}),n="auto"){let s=to(e,n),r=s.messages(),a=e.createElement("spotpatch-root");a.setAttribute(it,"");let l=a.attachShadow({mode:"open"}),E=K(e,r.trigger.select,"spotpatch-trigger");E.title=r.trigger.title(t),E.setAttribute("aria-pressed","false");let A=d(e,"div");A.className="spotpatch-highlight",A.hidden=!0;let R=d(e,"span");R.className="spotpatch-highlight-label",A.append(R);let j=d(e,"div");j.className="spotpatch-selection-highlights",j.setAttribute("aria-hidden","true");let u=d(e,"section");u.className="spotpatch-dialog",u.hidden=!0,u.tabIndex=-1,u.dataset.placement="viewport",u.setAttribute("role","dialog"),u.setAttribute("aria-labelledby","spotpatch-selection-title");let L=d(e,"span");L.className="spotpatch-anchor",L.setAttribute("aria-hidden","true");let V=d(e,"div");V.className="spotpatch-shell";let P=d(e,"header");P.className="spotpatch-header";let b=d(e,"div");b.className="spotpatch-brand-row";let x=d(e,"div");x.className="spotpatch-brand";let Q=d(e,"span");Q.className="spotpatch-brand-copy";let Y=d(e,"span");Y.className="spotpatch-brand-name";let h=d(e,"span");h.className="spotpatch-brand-context",Q.append(Y,h),x.append(Zn(e),Q);let S=d(e,"span");S.className="spotpatch-header-controls";let C=d(e,"a");C.className="spotpatch-repository",C.href=Bt,C.target="_blank",C.rel="noopener noreferrer";let T=K(e,"","spotpatch-locale"),D=K(e,"×","spotpatch-close");S.append(C,T,D),b.append(x,S);let F=d(e,"h2");F.id="spotpatch-selection-title",F.className="spotpatch-title";let $=d(e,"p");$.className="spotpatch-subtitle";let ae=d(e,"div");ae.className="spotpatch-target-row";let ie=d(e,"span");ie.className="spotpatch-target-label";let B=d(e,"span");B.className="spotpatch-context-state",B.dataset.state="loading",B.textContent=r.context.collecting,ae.append(ie,B),P.append(b,F,$,ae);let k=d(e,"div");k.className="spotpatch-body";let Le=d(e,"div");Le.className="spotpatch-selection-panel";let he=d(e,"section");he.className="spotpatch-targets";let X=d(e,"div");X.className="spotpatch-targets-heading";let Re=d(e,"span"),ve=d(e,"span");ve.className="spotpatch-targets-meta";let me=d(e,"span");me.className="spotpatch-target-complete";let ee=d(e,"span");ee.className="spotpatch-target-budget",ee.setAttribute("aria-live","polite");let N=d(e,"span");N.className="spotpatch-target-count",ve.append(me,ee),ae.append(N),X.append(Re,ve);let be=d(e,"div");be.className="spotpatch-target-progress",be.setAttribute("aria-hidden","true");let Te=d(e,"div");Te.className="spotpatch-target-progress-fill",be.append(Te);let te=d(e,"div");te.className="spotpatch-target-list",he.append(X,be,te);let le=d(e,"details");le.className="spotpatch-diagnostics";let De=d(e,"summary"),ye=d(e,"span"),we=d(e,"span");we.className="spotpatch-source-peek",we.textContent=r.diagnostics.resolving,De.append(ye,we);let $e=d(e,"pre");$e.className="spotpatch-summary",le.append(De,$e);let w=Yn(e,o,s);Le.append(he,le,w.root);let Oe=d(e,"div");Oe.className="spotpatch-preview-panel",Oe.hidden=!0;let ne=d(e,"pre");ne.className="spotpatch-prompt",ne.tabIndex=0,ne.setAttribute("aria-label",r.diagnostics.promptAriaLabel),Oe.append(ne),k.append(Le,Oe);let _=d(e,"footer");_.className="spotpatch-actions";let se=d(e,"div");se.className="spotpatch-context-state spotpatch-editor-feedback",se.dataset.state="idle",se.setAttribute("role","status"),se.setAttribute("aria-live","polite"),se.hidden=!0;let oe=K(e,r.actions.addElement),Ce=K(e,r.actions.reselect),Se=K(e,r.actions.openEditor),pe=K(e,r.actions.preview,"spotpatch-primary"),Ie=K(e,r.actions.copy,"spotpatch-primary"),xe=K(e,r.actions.back),_e=d(e,"div");_e.className="spotpatch-secondary-actions";let ke=d(e,"div");ke.className="spotpatch-primary-actions",oe.classList.add("spotpatch-icon-action"),oe.dataset.compactIcon="+",w.testButton.classList.add("spotpatch-icon-action"),w.testButton.dataset.compactIcon="✓",Se.classList.add("spotpatch-secondary-action"),Ce.classList.add("spotpatch-secondary-action"),_e.append(Se,Ce),ke.append(w.testButton,oe,w.runButton,pe,w.cancelButton,w.applyButton,w.revertButton,w.resetButton,Ie,xe),_.append(se,_e,ke),V.append(P,k,_),u.append(L,V);let W=d(e,"div");W.className="spotpatch-live",W.setAttribute("aria-live","polite"),W.setAttribute("aria-atomic","true"),l.append(ra(e),j,A,u,E,W),e.documentElement.append(a);let Pe,Ne,Ee="idle",Ve=!1,J=!1,ze="",je=!0,ue=[],He=0,Ke="idle";function nt(p){Ke=p,se.dataset.state=p,se.hidden=p==="idle",se.textContent=p==="opening"?r.announcements.editorOpening:p==="success"?r.announcements.editorOpened:p==="error"?r.announcements.editorFailed:"",I()}function m(p){return p.status==="ready"?r.targets.statusReady:p.status==="warning"?r.targets.statusPartial:r.targets.statusCollecting}function i(p,y){let v=y===0?0:p/y;Te.style.width=`${String(v*100)}%`}function c(p){let y=te.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(y).find(v=>p===void 0||v.dataset.targetInstructionId===p)}function g(p,y){let v=l.activeElement?.closest("textarea[data-target-instruction-id]"),H=v?.dataset.targetInstructionId,ge=v?.selectionStart,Be=v?.selectionEnd;ue=p.map(U=>Object.freeze({...U})),He=y,te.replaceChildren();let We=p.filter(U=>U.instruction.trim().length>0).length,ce=p.reduce((U,q)=>U+q.instruction.trim().length,0);i(We,p.length),N.textContent=r.targets.count(p.length,y),me.textContent=r.targets.complete(We,p.length);let dt=ce>4e3;ee.dataset.state=dt?"over":"ready",ee.textContent=dt?r.targets.instructionBudgetExceeded(ce,4e3):r.targets.instructionBudget(ce,4e3),oe.disabled=!je||p.length>=y,oe.title=p.length>=y?r.targets.limitTitle(y):r.targets.addTitle,ie.textContent=p.length===1?p[0]?.label??r.context.selectedElement:r.context.selectedCount(p.length);for(let[U,q]of p.entries()){let rt=d(e,"div");rt.className="spotpatch-target-item",rt.dataset.active=String(q.active),rt.dataset.status=q.status,rt.dataset.targetId=q.id;let Tt=d(e,"div");Tt.className="spotpatch-target-summary";let lt=K(e,"","spotpatch-target-select");lt.dataset.activateTargetId=q.id,lt.setAttribute("aria-label",r.targets.activate(U+1)),lt.setAttribute("aria-expanded",String(q.active));let wt=d(e,"span");wt.className="spotpatch-target-index",wt.textContent=String(U+1);let Ot=d(e,"span");Ot.className="spotpatch-target-copy";let _t=d(e,"span");_t.className="spotpatch-target-name",_t.textContent=q.label;let Pt=d(e,"span");Pt.className="spotpatch-target-source",Pt.textContent=`${m(q)} · ${q.source}`,Ot.append(_t,Pt);let en=q.instruction.trim().length>0,yt=d(e,"span");yt.className="spotpatch-target-state",yt.dataset.complete=String(en),yt.textContent=en?r.targets.instructionReady:r.targets.instructionMissing,lt.append(wt,Ot,yt);let pt=K(e,"↗","spotpatch-target-open");pt.dataset.openTargetId=q.id,pt.disabled=!q.canOpenEditor,pt.setAttribute("aria-label",r.actions.openTarget(U+1)),pt.title=r.actions.openTarget(U+1);let ut=K(e,"×","spotpatch-target-remove");if(ut.dataset.removeTargetId=q.id,ut.disabled=!je,ut.setAttribute("aria-label",r.targets.remove(U+1)),ut.title=r.targets.removeTitle,Tt.append(lt,pt,ut),rt.append(Tt),q.active){let Lt=d(e,"label");Lt.className="spotpatch-target-editor";let It=d(e,"span");It.className="spotpatch-target-editor-head";let kt=d(e,"span");kt.className="spotpatch-target-editor-label",kt.textContent=r.targets.instructionLabel(q.label);let Nt=d(e,"span");Nt.className="spotpatch-target-editor-count",Nt.textContent=r.targets.instructionCount(q.instruction.length,2e3),It.append(kt,Nt);let Ye=d(e,"textarea");Ye.rows=4,Ye.maxLength=2e3,Ye.value=q.instruction,Ye.placeholder=r.targets.instructionPlaceholder,Ye.disabled=!je,Ye.dataset.targetInstructionId=q.id,Ye.setAttribute("aria-label",r.targets.instructionLabel(q.label)),Lt.append(It,Ye),rt.append(Lt)}te.append(rt)}if(H!==void 0){let U=c(H);U?.focus({preventScroll:!0}),ge!==void 0&&Be!==void 0&&U?.setSelectionRange(ge,Be)}}function O(p,y){ue=ue.map(U=>U.id===p?Object.freeze({...U,instruction:y}):U);let v=Array.from(te.querySelectorAll(".spotpatch-target-item")).find(U=>U.dataset.targetId===p);if(v===void 0)return;let H=y.trim().length>0,ge=v.querySelector(".spotpatch-target-state"),Be=v.querySelector(".spotpatch-target-editor-count");ge!==null&&(ge.dataset.complete=String(H),ge.textContent=H?r.targets.instructionReady:r.targets.instructionMissing),Be!==null&&(Be.textContent=r.targets.instructionCount(y.length,2e3));let We=ue.filter(U=>U.instruction.trim().length>0).length;me.textContent=r.targets.complete(We,ue.length),i(We,ue.length);let ce=ue.reduce((U,q)=>U+q.instruction.trim().length,0),dt=ce>4e3;ee.dataset.state=dt?"over":"ready",ee.textContent=dt?r.targets.instructionBudgetExceeded(ce,4e3):r.targets.instructionBudget(ce,4e3)}function z(p){j.replaceChildren(),Ne=p.find(y=>y.active)?.rect,Pe=Ne;for(let[y,v]of p.entries()){let H=d(e,"div");H.className="spotpatch-selection-highlight",H.dataset.targetId=v.id,H.dataset.active=String(v.active),H.style.transform=`translate(${String(v.rect.x)}px, ${String(v.rect.y)}px)`,H.style.width=`${String(v.rect.width)}px`,H.style.height=`${String(v.rect.height)}px`;let ge=d(e,"span");ge.textContent=`${String(y+1)} · ${v.label}`,H.append(ge),j.append(H)}I()}function I(){if(u.hidden)return;let p=e.defaultView,y=p?.innerWidth??e.documentElement.clientWidth,v=p?.innerHeight??e.documentElement.clientHeight,H=u.getBoundingClientRect(),ge=Ee==="previewing"?"previewing":"selected",Be=H.width>0?H.width:Math.min(no,y-32),We=H.height>0?H.height:Math.min(oa[ge],v-32),ce=Qn({dialogWidth:Be,dialogHeight:We,viewportWidth:y,viewportHeight:v,...Pe===void 0?{}:{target:Pe}});u.style.left=`${String(ce.left)}px`,u.style.top=`${String(ce.top)}px`,u.style.setProperty("--spotpatch-anchor-x",`${String(ce.anchorX)}px`),u.style.setProperty("--spotpatch-anchor-y",`${String(ce.anchorY)}px`),u.dataset.placement=ce.mode}function ot(p){let y=r.summary,v=aa(p,y.source);we.textContent=v??r.diagnostics.noExactSource;let H=`${y.browserContext}: ${y.collectionStatuses.ready}`,ge=`${y.browserContext}: ${y.collectionStatuses.loading}`,Be=`${y.browserContext}: ${y.collectionStatuses.failed}`,We=`${y.api}: ${y.apiStatuses.loading}`,ce=`${y.api}: ${y.apiStatuses.failed}`;p.includes(H)&&!p.includes(ge)&&!p.includes(We)&&!p.includes(Be)&&!p.includes(ce)?(B.dataset.state="ready",B.textContent=r.context.ready):p.includes(Be)||p.includes(ce)?(B.dataset.state="warning",B.textContent=r.context.partial):(B.dataset.state="loading",B.textContent=r.context.collecting)}function Xt(p,y,v){Ve=y,J=v,ze=p,$e.textContent=p,Se.disabled=!y,pe.disabled=!v,w.setContextReady(v),ot(p),I()}function Zt(p){Ee=p;let y=p==="selected",v=p==="previewing";E.hidden=y||v,Le.hidden=!y,Oe.hidden=!v,Ce.hidden=!y,oe.hidden=!y,Se.hidden=!y,pe.hidden=!y,_e.hidden=!y,w.setSelectionVisible(y),Ie.hidden=!v,xe.hidden=!v,F.textContent=v?r.dialog.previewTitle:r.dialog.editTitle,$.textContent=v?r.dialog.previewSubtitle:r.dialog.editSubtitle,I()}function Qt(){r=s.messages(),Y.textContent=r.brand.name,h.textContent=r.brand.context,C.textContent=r.brand.repository,C.title=r.brand.repositoryTitle,C.setAttribute("aria-label",r.brand.repositoryTitle),T.textContent=r.alternateLocaleName,T.title=r.switchLocale,T.setAttribute("aria-label",r.switchLocale),D.setAttribute("aria-label",r.dialog.close),D.title=r.dialog.close,he.setAttribute("aria-label",r.targets.ariaLabel),Re.textContent=r.targets.title,ye.textContent=r.diagnostics.title,ne.setAttribute("aria-label",r.diagnostics.promptAriaLabel),oe.textContent=r.actions.addElement,Ce.textContent=r.actions.reselect,Se.textContent=r.actions.openEditor,pe.textContent=r.actions.preview,Ie.textContent=r.actions.copy,xe.textContent=r.actions.back,E.title=r.trigger.title(t),E.textContent=Ee==="inspecting"?r.trigger.stop:r.trigger.select,Zt(Ee),nt(Ke),ue.length>0?g(ue,He):(N.textContent=r.targets.count(0,He),me.textContent=r.targets.complete(0,0),i(0,0),ee.dataset.state="ready",ee.textContent=r.targets.instructionBudget(0,4e3),ie.textContent=r.context.selectedElement),ze.length>0?ot(ze):(we.textContent=r.diagnostics.resolving,B.textContent=r.context.collecting)}le.addEventListener("toggle",I),T.addEventListener("click",s.toggle);let go=s.subscribe(Qt);return Qt(),Object.freeze({host:a,triggerButton:E,addTargetButton:oe,targetList:te,reselectButton:Ce,openEditorButton:Se,repositoryLink:C,previewButton:pe,copyButton:Ie,backButton:xe,closeButton:D,agentProviderSelect:w.providerSelect,agentModelSelect:w.modelSelect,agentConsentCheckbox:w.consentCheckbox,agentWorkspaceConsentCheckbox:w.workspaceConsentCheckbox,agentTestButton:w.testButton,agentRunButton:w.runButton,agentCancelButton:w.cancelButton,agentApplyButton:w.applyButton,agentRevertButton:w.revertButton,agentResetButton:w.resetButton,renderStatus(p){let y=p==="inspecting";E.setAttribute("aria-pressed",String(y)),E.textContent=y?r.trigger.stop:r.trigger.select,Zt(p)},renderEditorStatus:nt,showHighlight(p,y){Pe=p,A.hidden=!1,A.style.transform=`translate(${String(p.x)}px, ${String(p.y)}px)`,A.style.width=`${String(p.width)}px`,A.style.height=`${String(p.height)}px`,R.textContent=y,ie.textContent=y,I()},hideHighlight(){Pe=Ne,A.hidden=!0,R.textContent="",I()},showSelectionHighlights:z,hideSelectionHighlights(){j.replaceChildren(),Ne=void 0,Pe=void 0,I()},showSelection(p,y,v){Xt(p,y,v),E.hidden=!0,u.hidden=!1,I()},updateSelection:Xt,renderTargets:g,updateTargetInstruction:O,setPreviewEnabled(p){J=p,pe.disabled=!p,w.setContextReady(p)},hideSelection(){u.hidden=!0,E.hidden=!1,te.replaceChildren(),ue=[],He=0,ze="",nt("idle"),N.textContent=r.targets.count(0,0),me.textContent=r.targets.complete(0,0),i(0,0),ie.textContent=r.context.selectedElement,$e.textContent="",ne.textContent="",we.textContent=r.diagnostics.resolving,B.dataset.state="loading",B.textContent=r.context.collecting,Se.disabled=!0,pe.disabled=!0,Ve=!1,J=!1,w.setContextReady(!1),w.setSelectionVisible(!1),w.setEditingEnabled(!0),w.resetJob()},hideSelectionTemporarily(){u.hidden=!0,E.hidden=!1},showPreview(p){ne.textContent=p,I()},readAgentSelection(){return w.readSelection()},agentConsentGranted(){return w.consentGranted()},setAgentProviderConsent(p){w.setProviderConsent(p)},setAgentEditingEnabled(p){je=p,oe.disabled=!p,Ce.disabled=!p,te.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(y=>{y.disabled=!p}),Se.disabled=!Ve,pe.disabled=!p||!J,w.setEditingEnabled(p),I()},renderAgentCapability(p,y,v,H){w.renderCapability(p,y,v,H);let ge=p==="ready"&&v?.state==="agent-ready";pe.classList.toggle("spotpatch-primary",!ge),I()},renderAgentWorkspaceHealth(p,y,v){w.renderWorkspaceHealth(p,y,v),I()},renderAgentJob(p,y,v,H){w.renderJob(p,y,v,H),I()},resetAgentJob(){w.resetJob(),I()},focusTargetInstruction(p){c(p)?.focus({preventScroll:!0})},focusPrompt(){ne.focus({preventScroll:!0})},announce(p){W.textContent="",W.textContent=p},locale:s.locale,messages:s.messages,agentWorkspaceConsentGranted:w.workspaceConsentGranted,subscribeLocale:s.subscribe,dispose(){le.removeEventListener("toggle",I),T.removeEventListener("click",s.toggle),go(),w.dispose(),a.remove()}})}function ia(e,t,o){let n=t?.relativePath??e.source.relativePath,s=e.source.line,r=e.source.column;return n!==void 0&&s!==void 0?`${n}:${String(s)}${r===void 0?"":`:${String(r)}`}`:n!==void 0?n:s!==void 0?o.lineLocation(s,r):o.unavailable}function ao(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`${e.framework==="next"?"Next.js":"Vite"}: ${e.frameworkVersion}`,`${t.source}: ${ia(e.resolution,e.code,t)}`,`${t.confidence}: ${e.resolution.source.confidence} (${t.confidenceLabels[e.resolution.source.confidence]})`,`${t.origin}: ${e.resolution.source.origin}`];return e.resolution.react.componentName!==void 0&&o.push(`${t.component}: ${e.resolution.react.componentName}`),e.resolution.react.componentStack.length>0&&o.push(`${t.stack}: ${e.resolution.react.componentStack.join(" > ")}`),!e.resolution.react.supported&&e.resolution.react.version!==void 0&&o.push(`React ${e.resolution.react.version}: ${t.unsupported}`),o.push(`${t.adapter}: ${e.resolution.react.supported?t.available:t.unavailable}`,`${t.api}: ${t.apiStatuses[e.apiStatus]}`,`${t.browserContext}: ${t.collectionStatuses[e.collectionStatus]}`),e.code!==void 0?o.push(`${t.boundary}: ${t.boundaries[e.code.boundary]}`):e.apiStatus==="loading"?o.push(`${t.sourceContext}: ${t.apiStatuses.loading}`):e.apiStatus==="failed"&&o.push(`${t.sourceContext}: ${t.unavailable}`),e.styles!==void 0&&(o.push(`${t.cssWarnings}: ${String(e.styles.warnings.length)}`),o.push(...e.styles.warnings.map(n=>`${t.warning}: ${n}`))),o.join(`
|
|
945
|
-
`)}function io(e,t){return`${e}:${t}`}function
|
|
946
|
-
${
|
|
950
|
+
`,t}function ia(e,t){return e.split(`
|
|
951
|
+
`).find(n=>n.startsWith(`${t}: `))?.slice(t.length+2).trim()}function ro(e,t,o=Object.freeze({enabled:!1}),n="auto"){let i=to(e,n),r=i.messages(),a=e.createElement("spotpatch-root");a.setAttribute(at,"");let l=a.attachShadow({mode:"open"}),E=q(e,r.trigger.select,"spotpatch-trigger");E.title=r.trigger.title(t),E.setAttribute("aria-pressed","false");let A=d(e,"div");A.className="spotpatch-highlight",A.hidden=!0;let R=d(e,"span");R.className="spotpatch-highlight-label",A.append(R);let j=d(e,"div");j.className="spotpatch-selection-highlights",j.setAttribute("aria-hidden","true");let g=d(e,"section");g.className="spotpatch-dialog",g.hidden=!0,g.tabIndex=-1,g.dataset.placement="viewport",g.setAttribute("role","dialog"),g.setAttribute("aria-labelledby","spotpatch-selection-title");let k=d(e,"span");k.className="spotpatch-anchor",k.setAttribute("aria-hidden","true");let V=d(e,"div");V.className="spotpatch-shell";let L=d(e,"header");L.className="spotpatch-header";let m=d(e,"div");m.className="spotpatch-brand-row";let S=d(e,"div");S.className="spotpatch-brand";let ee=d(e,"span");ee.className="spotpatch-brand-copy";let K=d(e,"span");K.className="spotpatch-brand-name";let h=d(e,"span");h.className="spotpatch-brand-context",ee.append(K,h),S.append(Zn(e),ee);let y=d(e,"span");y.className="spotpatch-header-controls";let T=d(e,"a");T.className="spotpatch-repository",T.href=Gt,T.target="_blank",T.rel="noopener noreferrer";let O=q(e,"","spotpatch-locale"),I=q(e,"×","spotpatch-close");y.append(T,O,I),m.append(S,y);let W=d(e,"h2");W.id="spotpatch-selection-title",W.className="spotpatch-title";let $=d(e,"p");$.className="spotpatch-subtitle";let ae=d(e,"div");ae.className="spotpatch-target-row";let ie=d(e,"span");ie.className="spotpatch-target-label";let B=d(e,"span");B.className="spotpatch-context-state",B.dataset.state="loading",B.textContent=r.context.collecting,ae.append(ie,B),L.append(m,W,$,ae);let N=d(e,"div");N.className="spotpatch-body";let _e=d(e,"div");_e.className="spotpatch-selection-panel";let he=d(e,"section");he.className="spotpatch-targets";let Y=d(e,"div");Y.className="spotpatch-targets-heading";let ve=d(e,"span"),Te=d(e,"span");Te.className="spotpatch-targets-meta";let me=d(e,"span");me.className="spotpatch-target-complete";let te=d(e,"span");te.className="spotpatch-target-budget",te.setAttribute("aria-live","polite");let M=d(e,"span");M.className="spotpatch-target-count",Te.append(me,te),ae.append(M),Y.append(ve,Te);let be=d(e,"div");be.className="spotpatch-target-progress",be.setAttribute("aria-hidden","true");let we=d(e,"div");we.className="spotpatch-target-progress-fill",be.append(we);let ne=d(e,"div");ne.className="spotpatch-target-list",he.append(Y,be,ne);let le=d(e,"details");le.className="spotpatch-diagnostics";let De=d(e,"summary"),ye=d(e,"span"),Oe=d(e,"span");Oe.className="spotpatch-source-peek",Oe.textContent=r.diagnostics.resolving,De.append(ye,Oe);let xe=d(e,"pre");xe.className="spotpatch-summary",le.append(De,xe);let w=Yn(e,o,i);_e.append(he,le,w.root);let Pe=d(e,"div");Pe.className="spotpatch-preview-panel",Pe.hidden=!0;let Se=d(e,"pre");Se.className="spotpatch-prompt",Se.tabIndex=0,Se.setAttribute("aria-label",r.diagnostics.promptAriaLabel),Pe.append(Se),N.append(_e,Pe);let _=d(e,"footer");_.className="spotpatch-actions";let F=d(e,"div");F.className="spotpatch-context-state spotpatch-editor-feedback",F.dataset.state="idle",F.setAttribute("role","status"),F.setAttribute("aria-live","polite"),F.hidden=!0;let se=q(e,r.actions.addElement),Ce=q(e,r.actions.reselect),pe=q(e,r.actions.openEditor),ue=q(e,r.actions.preview,"spotpatch-primary"),Le=q(e,r.actions.copy,"spotpatch-primary"),Ie=q(e,r.actions.back),Ee=d(e,"div");Ee.className="spotpatch-secondary-actions";let $e=d(e,"div");$e.className="spotpatch-primary-actions",se.classList.add("spotpatch-icon-action"),se.dataset.compactIcon="+",w.testButton.classList.add("spotpatch-icon-action"),w.testButton.dataset.compactIcon="✓",pe.classList.add("spotpatch-secondary-action"),Ce.classList.add("spotpatch-secondary-action"),Ee.append(pe,Ce),$e.append(w.testButton,se,w.runButton,ue,w.cancelButton,w.applyButton,w.revertButton,w.resetButton,Le,Ie),_.append(F,Ee,$e),V.append(L,N,_),g.append(k,V);let X=d(e,"div");X.className="spotpatch-live",X.setAttribute("aria-live","polite"),X.setAttribute("aria-atomic","true"),l.append(aa(e),j,A,g,E,X),e.documentElement.append(a);let Z,ze,ke="idle",Re=!1,Ne=!1,je="",He=!0,z=[],Be=0,Ke="idle";function Ye(u){Ke=u,F.dataset.state=u,F.hidden=u==="idle",F.textContent=u==="opening"?r.announcements.editorOpening:u==="success"?r.announcements.editorOpened:u==="error"?r.announcements.editorFailed:"",C()}function it(u){return u.status==="ready"?r.targets.statusReady:u.status==="warning"?r.targets.statusPartial:r.targets.statusCollecting}function s(u,b){let v=b===0?0:u/b;we.style.width=`${String(v*100)}%`}function p(u){let b=ne.querySelectorAll("textarea[data-target-instruction-id]");return Array.from(b).find(v=>u===void 0||v.dataset.targetInstructionId===u)}function c(u,b){let v=l.activeElement?.closest("textarea[data-target-instruction-id]"),H=v?.dataset.targetInstructionId,ge=v?.selectionStart,Ue=v?.selectionEnd;z=u.map(U=>Object.freeze({...U})),Be=b,ne.replaceChildren();let We=u.filter(U=>U.instruction.trim().length>0).length,ce=u.reduce((U,J)=>U+J.instruction.trim().length,0);s(We,u.length),M.textContent=r.targets.count(u.length,b),me.textContent=r.targets.complete(We,u.length);let pt=ce>4e3;te.dataset.state=pt?"over":"ready",te.textContent=pt?r.targets.instructionBudgetExceeded(ce,4e3):r.targets.instructionBudget(ce,4e3),se.disabled=!He||u.length>=b,se.title=u.length>=b?r.targets.limitTitle(b):r.targets.addTitle,ie.textContent=u.length===1?u[0]?.label??r.context.selectedElement:r.context.selectedCount(u.length);for(let[U,J]of u.entries()){let ot=d(e,"div");ot.className="spotpatch-target-item",ot.dataset.active=String(J.active),ot.dataset.status=J.status,ot.dataset.targetId=J.id;let Ot=d(e,"div");Ot.className="spotpatch-target-summary";let ut=q(e,"","spotpatch-target-select");ut.dataset.activateTargetId=J.id,ut.setAttribute("aria-label",r.targets.activate(U+1)),ut.setAttribute("aria-expanded",String(J.active));let _t=d(e,"span");_t.className="spotpatch-target-index",_t.textContent=String(U+1);let Pt=d(e,"span");Pt.className="spotpatch-target-copy";let Lt=d(e,"span");Lt.className="spotpatch-target-name",Lt.textContent=J.label;let It=d(e,"span");It.className="spotpatch-target-source",It.textContent=`${it(J)} · ${J.source}`,Pt.append(Lt,It);let en=J.instruction.trim().length>0,St=d(e,"span");St.className="spotpatch-target-state",St.dataset.complete=String(en),St.textContent=en?r.targets.instructionReady:r.targets.instructionMissing,ut.append(_t,Pt,St);let gt=q(e,"↗","spotpatch-target-open");gt.dataset.openTargetId=J.id,gt.disabled=!J.canOpenEditor,gt.setAttribute("aria-label",r.actions.openTarget(U+1)),gt.title=r.actions.openTarget(U+1);let ft=q(e,"×","spotpatch-target-remove");if(ft.dataset.removeTargetId=J.id,ft.disabled=!He,ft.setAttribute("aria-label",r.targets.remove(U+1)),ft.title=r.targets.removeTitle,Ot.append(ut,gt,ft),ot.append(Ot),J.active){let kt=d(e,"label");kt.className="spotpatch-target-editor";let Nt=d(e,"span");Nt.className="spotpatch-target-editor-head";let Mt=d(e,"span");Mt.className="spotpatch-target-editor-label",Mt.textContent=r.targets.instructionLabel(J.label);let Dt=d(e,"span");Dt.className="spotpatch-target-editor-count",Dt.textContent=r.targets.instructionCount(J.instruction.length,2e3),Nt.append(Mt,Dt);let Xe=d(e,"textarea");Xe.rows=4,Xe.maxLength=2e3,Xe.value=J.instruction,Xe.placeholder=r.targets.instructionPlaceholder,Xe.disabled=!He,Xe.dataset.targetInstructionId=J.id,Xe.setAttribute("aria-label",r.targets.instructionLabel(J.label)),kt.append(Nt,Xe),ot.append(kt)}ne.append(ot)}if(H!==void 0){let U=p(H);U?.focus({preventScroll:!0}),ge!==void 0&&Ue!==void 0&&U?.setSelectionRange(ge,Ue)}}function x(u,b){z=z.map(U=>U.id===u?Object.freeze({...U,instruction:b}):U);let v=Array.from(ne.querySelectorAll(".spotpatch-target-item")).find(U=>U.dataset.targetId===u);if(v===void 0)return;let H=b.trim().length>0,ge=v.querySelector(".spotpatch-target-state"),Ue=v.querySelector(".spotpatch-target-editor-count");ge!==null&&(ge.dataset.complete=String(H),ge.textContent=H?r.targets.instructionReady:r.targets.instructionMissing),Ue!==null&&(Ue.textContent=r.targets.instructionCount(b.length,2e3));let We=z.filter(U=>U.instruction.trim().length>0).length;me.textContent=r.targets.complete(We,z.length),s(We,z.length);let ce=z.reduce((U,J)=>U+J.instruction.trim().length,0),pt=ce>4e3;te.dataset.state=pt?"over":"ready",te.textContent=pt?r.targets.instructionBudgetExceeded(ce,4e3):r.targets.instructionBudget(ce,4e3)}function P(u){j.replaceChildren(),ze=u.find(b=>b.active)?.rect,Z=ze;for(let[b,v]of u.entries()){let H=d(e,"div");H.className="spotpatch-selection-highlight",H.dataset.targetId=v.id,H.dataset.active=String(v.active),H.style.transform=`translate(${String(v.rect.x)}px, ${String(v.rect.y)}px)`,H.style.width=`${String(v.rect.width)}px`,H.style.height=`${String(v.rect.height)}px`;let ge=d(e,"span");ge.textContent=`${String(b+1)} · ${v.label}`,H.append(ge),j.append(H)}C()}function C(){if(g.hidden)return;let u=e.defaultView,b=u?.innerWidth??e.documentElement.clientWidth,v=u?.innerHeight??e.documentElement.clientHeight,H=g.getBoundingClientRect(),ge=ke==="previewing"?"previewing":"selected",Ue=H.width>0?H.width:Math.min(no,b-32),We=H.height>0?H.height:Math.min(ra[ge],v-32),ce=Qn({dialogWidth:Ue,dialogHeight:We,viewportWidth:b,viewportHeight:v,...Z===void 0?{}:{target:Z}});g.style.left=`${String(ce.left)}px`,g.style.top=`${String(ce.top)}px`,g.style.setProperty("--spotpatch-anchor-x",`${String(ce.anchorX)}px`),g.style.setProperty("--spotpatch-anchor-y",`${String(ce.anchorY)}px`),g.dataset.placement=ce.mode}function oe(u){let b=r.summary,v=ia(u,b.source);Oe.textContent=v??r.diagnostics.noExactSource;let H=`${b.browserContext}: ${b.collectionStatuses.ready}`,ge=`${b.browserContext}: ${b.collectionStatuses.loading}`,Ue=`${b.browserContext}: ${b.collectionStatuses.failed}`,We=`${b.api}: ${b.apiStatuses.loading}`,ce=`${b.api}: ${b.apiStatuses.failed}`;u.includes(H)&&!u.includes(ge)&&!u.includes(We)&&!u.includes(Ue)&&!u.includes(ce)?(B.dataset.state="ready",B.textContent=r.context.ready):u.includes(Ue)||u.includes(ce)?(B.dataset.state="warning",B.textContent=r.context.partial):(B.dataset.state="loading",B.textContent=r.context.collecting)}function dt(u,b,v){Re=b,Ne=v,je=u,xe.textContent=u,pe.disabled=!b,ue.disabled=!v,w.setContextReady(v),oe(u),C()}function lt(u){ke=u;let b=u==="selected",v=u==="previewing";E.hidden=b||v,_e.hidden=!b,Pe.hidden=!v,Ce.hidden=!b,se.hidden=!b,pe.hidden=!b,ue.hidden=!b,Ee.hidden=!b,w.setSelectionVisible(b),Le.hidden=!v,Ie.hidden=!v,W.textContent=v?r.dialog.previewTitle:r.dialog.editTitle,$.textContent=v?r.dialog.previewSubtitle:r.dialog.editSubtitle,C()}function Qt(){r=i.messages(),K.textContent=r.brand.name,h.textContent=r.brand.context,T.textContent=r.brand.repository,T.title=r.brand.repositoryTitle,T.setAttribute("aria-label",r.brand.repositoryTitle),O.textContent=r.alternateLocaleName,O.title=r.switchLocale,O.setAttribute("aria-label",r.switchLocale),I.setAttribute("aria-label",r.dialog.close),I.title=r.dialog.close,he.setAttribute("aria-label",r.targets.ariaLabel),ve.textContent=r.targets.title,ye.textContent=r.diagnostics.title,Se.setAttribute("aria-label",r.diagnostics.promptAriaLabel),se.textContent=r.actions.addElement,Ce.textContent=r.actions.reselect,pe.textContent=r.actions.openEditor,ue.textContent=r.actions.preview,Le.textContent=r.actions.copy,Ie.textContent=r.actions.back,E.title=r.trigger.title(t),E.textContent=ke==="inspecting"?r.trigger.stop:r.trigger.select,lt(ke),Ye(Ke),z.length>0?c(z,Be):(M.textContent=r.targets.count(0,Be),me.textContent=r.targets.complete(0,0),s(0,0),te.dataset.state="ready",te.textContent=r.targets.instructionBudget(0,4e3),ie.textContent=r.context.selectedElement),je.length>0?oe(je):(Oe.textContent=r.diagnostics.resolving,B.textContent=r.context.collecting)}le.addEventListener("toggle",C),O.addEventListener("click",i.toggle);let go=i.subscribe(Qt);return Qt(),Object.freeze({host:a,triggerButton:E,addTargetButton:se,targetList:ne,reselectButton:Ce,openEditorButton:pe,repositoryLink:T,previewButton:ue,copyButton:Le,backButton:Ie,closeButton:I,agentProviderSelect:w.providerSelect,agentModelSelect:w.modelSelect,agentConsentCheckbox:w.consentCheckbox,agentWorkspaceConsentCheckbox:w.workspaceConsentCheckbox,agentTestButton:w.testButton,agentRunButton:w.runButton,agentCancelButton:w.cancelButton,agentApplyButton:w.applyButton,agentRevertButton:w.revertButton,agentResetButton:w.resetButton,renderStatus(u){let b=u==="inspecting";E.setAttribute("aria-pressed",String(b)),E.textContent=b?r.trigger.stop:r.trigger.select,lt(u)},renderEditorStatus:Ye,showHighlight(u,b){Z=u,A.hidden=!1,A.style.transform=`translate(${String(u.x)}px, ${String(u.y)}px)`,A.style.width=`${String(u.width)}px`,A.style.height=`${String(u.height)}px`,R.textContent=b,ie.textContent=b,C()},hideHighlight(){Z=ze,A.hidden=!0,R.textContent="",C()},showSelectionHighlights:P,hideSelectionHighlights(){j.replaceChildren(),ze=void 0,Z=void 0,C()},showSelection(u,b,v){dt(u,b,v),E.hidden=!0,g.hidden=!1,C()},updateSelection:dt,renderTargets:c,updateTargetInstruction:x,setPreviewEnabled(u){Ne=u,ue.disabled=!u,w.setContextReady(u)},hideSelection(){g.hidden=!0,E.hidden=!1,ne.replaceChildren(),z=[],Be=0,je="",Ye("idle"),M.textContent=r.targets.count(0,0),me.textContent=r.targets.complete(0,0),s(0,0),ie.textContent=r.context.selectedElement,xe.textContent="",Se.textContent="",Oe.textContent=r.diagnostics.resolving,B.dataset.state="loading",B.textContent=r.context.collecting,pe.disabled=!0,ue.disabled=!0,Re=!1,Ne=!1,w.setContextReady(!1),w.setSelectionVisible(!1),w.setEditingEnabled(!0),w.resetJob()},hideSelectionTemporarily(){g.hidden=!0,E.hidden=!1},showPreview(u){Se.textContent=u,C()},readAgentSelection(){return w.readSelection()},agentConsentGranted(){return w.consentGranted()},setAgentProviderConsent(u){w.setProviderConsent(u)},setAgentEditingEnabled(u){He=u,se.disabled=!u,Ce.disabled=!u,ne.querySelectorAll(".spotpatch-target-remove, .spotpatch-target-select, textarea[data-target-instruction-id]").forEach(b=>{b.disabled=!u}),pe.disabled=!Re,ue.disabled=!u||!Ne,w.setEditingEnabled(u),C()},renderAgentCapability(u,b,v,H){w.renderCapability(u,b,v,H);let ge=u==="ready"&&v?.state==="agent-ready";ue.classList.toggle("spotpatch-primary",!ge),C()},renderAgentWorkspaceHealth(u,b,v){w.renderWorkspaceHealth(u,b,v),C()},renderAgentJob(u,b,v,H){w.renderJob(u,b,v,H),C()},resetAgentJob(){w.resetJob(),C()},focusTargetInstruction(u){p(u)?.focus({preventScroll:!0})},focusPrompt(){Se.focus({preventScroll:!0})},announce(u){X.textContent="",X.textContent=u},locale:i.locale,messages:i.messages,agentWorkspaceConsentGranted:w.workspaceConsentGranted,subscribeLocale:i.subscribe,dispose(){le.removeEventListener("toggle",C),O.removeEventListener("click",i.toggle),go(),w.dispose(),a.remove()}})}function sa(e,t,o){let n=t?.relativePath??e.source.relativePath,i=e.source.line,r=e.source.column;return n!==void 0&&i!==void 0?`${n}:${String(i)}${r===void 0?"":`:${String(r)}`}`:n!==void 0?n:i!==void 0?o.lineLocation(i,r):o.unavailable}function ao(e,t){let o=[`SpotPatch: ${e.spotPatchVersion}`,`${e.framework==="next"?"Next.js":"Vite"}: ${e.frameworkVersion}`,`${t.source}: ${sa(e.resolution,e.code,t)}`,`${t.confidence}: ${e.resolution.source.confidence} (${t.confidenceLabels[e.resolution.source.confidence]})`,`${t.origin}: ${e.resolution.source.origin}`];return e.resolution.react.componentName!==void 0&&o.push(`${t.component}: ${e.resolution.react.componentName}`),e.resolution.react.componentStack.length>0&&o.push(`${t.stack}: ${e.resolution.react.componentStack.join(" > ")}`),!e.resolution.react.supported&&e.resolution.react.version!==void 0&&o.push(`React ${e.resolution.react.version}: ${t.unsupported}`),o.push(`${t.adapter}: ${e.resolution.react.supported?t.available:t.unavailable}`,`${t.api}: ${t.apiStatuses[e.apiStatus]}`,`${t.browserContext}: ${t.collectionStatuses[e.collectionStatus]}`),e.code!==void 0?o.push(`${t.boundary}: ${t.boundaries[e.code.boundary]}`):e.apiStatus==="loading"?o.push(`${t.sourceContext}: ${t.apiStatuses.loading}`):e.apiStatus==="failed"&&o.push(`${t.sourceContext}: ${t.unavailable}`),e.styles!==void 0&&(o.push(`${t.cssWarnings}: ${String(e.styles.warnings.length)}`),o.push(...e.styles.warnings.map(n=>`${t.warning}: ${n}`))),o.join(`
|
|
952
|
+
`)}function io(e,t){return`${e}:${t}`}function ca(e){if(e.type==="tool")return Object.freeze({key:`tool:${String(e.data.turn)}:${e.data.toolCallId}`,label:`${e.data.toolName} · ${e.data.state}`,state:e.data.state==="started"?"active":e.data.state==="succeeded"?"success":"failure"});if(e.type==="check")return Object.freeze({key:`check:${e.data.result.checkId}:${String(e.sequence)}`,label:`${e.data.result.label} · ${e.data.result.status}`,state:e.data.result.status==="passed"?"success":e.data.result.status==="failed"||e.data.result.status==="timed-out"?"failure":"info"})}function so(e){let t=h=>mn(h)??f.INTERNAL_ERROR,o=h=>e.view.messages().errors[t(h)],n=new Map,i=new Set,r=new Map,a=0,l,E,A=!1,R=!1,j=()=>e.view.readAgentSelection(),g=async h=>{e.view.renderAgentWorkspaceHealth("checking");try{let y=await e.api.agentWorkspaceHealth();return h!==a||e.view.renderAgentWorkspaceHealth(y.state,y,y.errorCode),y}catch(y){throw h===a&&e.view.renderAgentWorkspaceHealth("blocked",void 0,t(y)),y}},k=h=>{l!==void 0&&e.view.renderAgentJob(l,E,Object.freeze([...r.values()]),h??l.errorCode)},V=()=>{let h=j();if(h===void 0){e.view.setAgentProviderConsent(!1),e.view.renderAgentCapability("error",e.view.messages().agent.providerUnavailable);return}e.view.setAgentProviderConsent(i.has(h.providerProfileId));let y=n.get(io(h.providerProfileId,h.modelProfileId));y===void 0?e.view.renderAgentCapability("idle",e.view.messages().agent.connectionNotTested):e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,y)},L=async h=>{let y=j();if(y===void 0)throw new Error("Agent provider selection is unavailable.");let T=io(y.providerProfileId,y.modelProfileId),O=n.get(T);if(O!==void 0)return O;e.view.renderAgentCapability("probing",e.view.messages().agent.testingCapability);let I=await e.api.agentCapability(y);if(h!==a)return I;if(I.state!=="agent-ready")throw new D(I.errorCode??f.MODEL_TOOL_CALL_UNSUPPORTED);return n.set(T,I),e.view.renderAgentCapability("ready",e.view.messages().agent.capabilityVerified,I),e.view.announce(e.view.messages().agent.capabilityVerifiedAnnouncement),I},m=async(h,y)=>{try{let T=await e.api.agentResult(h);if(y!==a||T.snapshot.jobId!==h)return;l=T.snapshot,E=T.result,k()}catch(T){y===a&&k(t(T))}},S=async(h,y)=>{try{await e.api.agentEvents(h,T=>{if(y!==a||T.jobId!==h)return;T.type==="snapshot"&&(l=T.data.snapshot,l.status==="applied"&&!A&&(A=!0,e.onApplied()));let O=ca(T);O!==void 0&&r.set(O.key,O),k()}),y===a&&await m(h,y)}catch(T){y===a&&!(T instanceof DOMException&&T.name==="AbortError")&&k(t(T))}},ee=async h=>{let y=l;if(y===void 0||R)return;R=!0;let T=a;l=Object.freeze({...y,status:h==="apply"?"applying":h==="cancel"?"cancelling":"reverting",phaseMessage:h==="apply"?e.view.messages().agent.applying:h==="cancel"?e.view.messages().agent.cancelling:e.view.messages().agent.reverting,canCancel:!1,canApply:!1,canRevert:!1}),k();try{let O=h==="apply"?await e.api.applyAgentJob(y.jobId):h==="cancel"?await e.api.cancelAgentJob(y.jobId):await e.api.revertAgentJob(y.jobId);if(T!==a)return;l=O,O.status==="applied"&&!A&&(A=!0,e.onApplied()),await m(O.jobId,T)}catch(O){if(T!==a)return;l=y,await m(y.jobId,T),k(t(O)),e.view.announce(o(O))}finally{T===a&&(R=!1)}},K=()=>{a+=1,l=void 0,E=void 0,r.clear(),A=!1,R=!1,e.view.resetAgentJob(),e.view.setAgentEditingEnabled(!0),V()};return Object.freeze({apply(){l?.canApply===!0&&ee("apply")},beginSelection(){K();let h=a;e.ai.enabled&&g(h).catch(()=>{})},cancel(){l?.canCancel===!0&&ee("cancel")},consentChanged(){let h=j();h!==void 0&&(e.view.agentConsentGranted()?i.add(h.providerProfileId):i.delete(h.providerProfileId))},disposeSelection(){let h=l?.canCancel===!0||l?.status==="cancelling"?l.jobId:void 0;a+=1,l=void 0,E=void 0,r.clear(),A=!1,R=!1,h!==void 0&&e.api.cancelAgentJob(h).catch(()=>{})},providerOrModelChanged(){a+=1,V(),g(a).catch(()=>{})},reset(){let h=A;K(),h?e.onReselectRequired():e.ai.enabled&&g(a).catch(()=>{})},revert(){l?.canRevert===!0&&ee("revert")},run(){if(!e.ai.enabled||l!==void 0)return;let h=e.ai.applyMode==="trusted-auto",y=j(),T=e.getAnnotation();if(y===void 0||T===void 0){e.view.announce(e.view.messages().announcements.completeInstructions);return}if(!e.view.agentConsentGranted()){e.view.announce(e.view.messages().agent.consentRequired);return}i.add(y.providerProfileId);let O=++a;e.view.setAgentEditingEnabled(!1),g(O).then(async I=>{if(O!==a)return;if(I.state==="blocked")throw new D(I.errorCode??f.WORKTREE_LOCAL_CHANGES_UNSUPPORTED);if(I.state==="consent-required"&&!e.view.agentWorkspaceConsentGranted())throw new D(f.WORKTREE_DIRTY);let W=await e.api.createAgentJob({annotation:T,providerProfileId:y.providerProfileId,modelProfileId:y.modelProfileId,providerDataConsent:!0,...h?{trustedFastModeConsent:!0}:{},workingTreeMode:I.state==="consent-required"?"include-local-changes":"require-clean"});O===a&&(l=W,E=void 0,r.clear(),k(),S(W.jobId,O))}).catch(I=>{O===a&&(e.view.setAgentEditingEnabled(!0),e.view.renderAgentCapability("error",o(I),void 0,t(I)),e.view.announce(o(I)))})},testCapability(){if(!e.ai.enabled||l!==void 0)return;let h=++a;Promise.all([L(h),g(h)]).catch(y=>{h===a&&(e.view.renderAgentCapability("error",o(y),void 0,t(y)),e.view.announce(o(y)))})}})}function co(e){if(typeof e.crypto.randomUUID=="function")return e.crypto.randomUUID();let t=e.crypto.getRandomValues(new Uint8Array(16));return Array.from(t,o=>o.toString(16).padStart(2,"0")).join("")}function Yt(e,t){return Object.freeze({url:t.location.href,pathname:t.location.pathname,title:e.title,viewportWidth:t.innerWidth,viewportHeight:t.innerHeight,devicePixelRatio:t.devicePixelRatio})}function lo(e){let t=Reflect.get(e,"clipboard");return typeof t=="object"&&t!==null&&"writeText"in t&&typeof t.writeText=="function"?t:void 0}var la=Object.freeze({classNames:Object.freeze([]),matchedRules:Object.freeze([]),computed:Object.freeze({}),warnings:Object.freeze(["CSS context collection failed."])});function Xt(e){let t=e.id.length>0?`#${e.id}`:"",o=Array.from(e.classList).slice(0,2).map(n=>`.${n}`).join("");return`<${e.tagName.toLowerCase()}${t}${o}>`}function pa(e,t){let o=e.code?.relativePath??e.resolution.source.relativePath,n=e.resolution.source.line,i=e.resolution.source.column;return o===void 0?t:`${o}${n===void 0?"":`:${String(n)}`}${i===void 0?"":`:${String(i)}`}`}function ua(e){return e.apiStatus==="failed"||e.collectionStatus==="failed"?"warning":e.apiStatus==="loading"||e.collectionStatus==="loading"?"loading":"ready"}function ga(e){let t=e.document??globalThis.document,o=e.window??globalThis.window;return{document:t,window:o,mutationObserver:e.mutationObserver??globalThis.MutationObserver,resizeObserver:e.resizeObserver??globalThis.ResizeObserver}}function po(e,t={}){let o=ga(t),n=t.view??ro(o.document,e.shortcut,e.ai,e.locale),i=t.api??bn({apiBase:e.apiBase,fetch:o.window.fetch.bind(o.window),sessionToken:e.sessionToken}),r=t.promptComposer??jn({maxCharacters:e.budget.totalCharacters}),a=t.clipboard??lo(o.window.navigator),l=t.createId??(()=>co(o.window)),E=t.now??(()=>new Date().toISOString()),A=t.selectionSession??Gn(o.window,e.sessionId,e.maxTargets),R=A.load(),j=Fn({adapter:t.reactAdapter??da({maxComponentDepth:e.budget.maxComponentDepth}),onAdapterError(){n.announce(n.messages().announcements.adapterDisabled),e.debug&&console.warn("[spotpatch:react] Adapter failed and was disabled for this session.")}}),g=Ft,k=!1,V,L,m=R?.targets.map(s=>{let p=Kt(s.source);return{id:s.id,resolution:Object.freeze({source:s.source,react:s.react}),apiStatus:p===void 0?"not-required":s.code===void 0?"failed":"connected",code:s.code,collectionStatus:"ready",element:void 0,elementContext:s.element,instruction:s.instruction,marker:p,page:s.page,styles:s.styles}})??[],S=R?.activeTargetId,ee=R?.sequence??0,K=R?.open??!1,h=!1,y=0,T=0,O=!1,I="",W,$,ae,ie,B=new Map;function N(s){g=Hn(g,s),n.renderStatus(g.status)}function _e(){return m.find(s=>s.id===S)??m.at(-1)}function he(s){if(!(s.elementContext===void 0||s.styles===void 0))return{id:s.id,instruction:s.instruction,page:s.page,source:s.resolution.source,react:s.resolution.react,element:s.elementContext,styles:s.styles,...s.code===void 0?{}:{code:s.code}}}function Y(){let s=m.flatMap(c=>{let x=he(c);return x===void 0?[]:[x]});if(s.length===0){A.clear();return}let p=new Set(s.map(({id:c})=>c));A.save({...S!==void 0&&p.has(S)?{activeTargetId:S}:{},open:K,sequence:ee,targets:s})}function ve(s,p){return k&&p===y&&g.status!=="idle"&&m.includes(s)}function Te(){let s=m.reduce((p,c)=>p+c.instruction.trim().length,0);return m.length>0&&s<=4e3&&m.every(p=>p.instruction.trim().length>0&&p.elementContext!==void 0&&p.styles!==void 0&&p.apiStatus!=="loading")}function me(){let s=n.messages().summary;return m.map((p,c)=>{let x=ao({resolution:p.resolution,...p.code===void 0?{}:{code:p.code},...p.styles===void 0?{}:{styles:p.styles},apiStatus:p.apiStatus,collectionStatus:p.collectionStatus,framework:e.framework,frameworkVersion:e.frameworkVersion,spotPatchVersion:e.spotPatchVersion},s);return`${s.target(c+1,p.id===S)}
|
|
953
|
+
${x}`}).join(`
|
|
947
954
|
|
|
948
|
-
`)}function ee(){let i=b.flatMap(c=>{if(!c.element?.isConnected)return[];let g=Rt(c.element,o.window);return g===void 0?[]:[{id:c.id,label:Kt(c.element),rect:g,active:c.id===x}]});i.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(i)}function N(i=!1){if(b.length===0)return;n.renderTargets(b.map(z=>({id:z.id,label:z.resolution.react.componentName??(z.element===void 0?z.elementContext?.tagName??"Element":Kt(z.element)),source:la(z,n.messages().context.sourceUnavailable),canOpenEditor:z.marker!==void 0,status:pa(z),active:z.id===x,instruction:z.instruction})),e.maxTargets),ee();let c=Le(),g=me(),O=c?.marker!==void 0;i?n.showSelection(g,O,ve()):n.updateSelection(g,O,ve())}function be(){if(!ve())return;let i=b.map(c=>{if(c.elementContext===void 0||c.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let g=[...c.apiStatus==="failed"?["Source context could not be loaded."]:[],...c.collectionStatus==="failed"?["Part of the browser context could not be collected."]:[]];return{instruction:c.instruction.trim(),page:c.page,source:c.resolution.source,react:c.resolution.react,element:c.elementContext,styles:c.styles,...c.code===void 0?{}:{code:c.code},warnings:g}});return nn({id:l(),locale:n.locale(),createdAt:E(),page:Ft(o.document,o.window),targets:i})}function Te(i){n.showHighlight(kn(i,o.window),Kt(i))}function te(){F?.isConnected===!0&&F.focus({preventScroll:!0}),F=void 0}function le(){for(let i of B.values())o.window.clearTimeout(i);B.clear()}function De(){S+=1,s.cancelPending(),_.disposeSelection(),le(),$?.disconnect(),b=[],x=void 0,Y=!1,h=!1,T=!1,D="",n.hideSelection(),n.hideSelectionHighlights(),A.clear(),te()}function ye(){u.status==="inspecting"?k({type:"CANCEL"}):u.status==="selected"?k({type:"CLOSE"}):u.status==="previewing"&&(k({type:"BACK"}),k({type:"CLOSE"})),Y=!1,X(),n.hideSelection(),n.hideSelectionHighlights(),te(),n.hideHighlight()}function we(){if(u.status!=="inspecting"||!T||b.length===0){ye();return}T=!1,k({type:"SELECT"}),n.hideHighlight(),N(!0),n.focusTargetInstruction(x),n.announce(n.messages().announcements.addCancelled)}function $e(){if(u.status==="inspecting"&&T){we();return}if(u.status!=="idle"){ye();return}if(b.length>0){Y=!0,k({type:"RESTORE"}),h||(_.beginSelection(),h=!0),N(!0),n.focusTargetInstruction(x),X();return}k({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function w(i=n.messages().announcements.chooseAnother){u.status==="selected"&&(k({type:"RESELECT"}),De(),n.hideHighlight(),n.announce(i))}function Oe(){if(u.status==="selected"){if(b.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}T=!0,k({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(b.length,e.maxTargets))}}function ne(){S+=1,le(),$?.disconnect();for(let i of b)i.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),N(),A.clear(),n.announce(n.messages().announcements.appliedTargetsDetached)}let _=so({ai:e.ai,api:s,getAnnotation:be,onApplied:ne,onReselectRequired(){w(n.messages().announcements.reselectAfterChange)},view:n});async function se(i,c){let g=i.marker;if(g!==void 0)try{let O=await s.sourceContext({fileId:g.fileId,line:g.line,column:g.column,maxLines:e.budget.maxCodeLines});Re(i,c)&&(i.code=O,i.apiStatus="connected",X(),N(),n.announce(n.messages().announcements.sourceLoaded))}catch(O){Re(i,c)&&(i.code=void 0,i.apiStatus="failed",X(),N(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(O instanceof DOMException&&O.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function oe(i,c){let g=i.element;if(g===void 0)return;let O=o.window.setTimeout(()=>{if(B.delete(i.id),!Re(i,c))return;let z=!1;try{i.elementContext=On({element:g,maxCharacters:e.budget.domCharacters})}catch{i.elementContext=void 0,z=!0}try{i.styles=An({document:o.document,element:g,maxCharacters:e.budget.cssCharacters})}catch{i.styles=da,z=!0}i.collectionStatus=z?"failed":"ready",X(),N(),n.announce(z?n.messages().announcements.contextWarning:n.messages().announcements.contextCollected),e.debug&&i.styles.warnings.length>0&&console.warn(`[spotpatch:runtime] CSS collection completed with ${String(i.styles.warnings.length)} warning(s).`)},0);B.set(i.id,O)}function Ce(i,c){return c!==void 0?b.find(g=>g.marker?.fileId===c.fileId&&g.marker.line===c.line&&g.marker.column===c.column):b.find(g=>g.element===i)}function Se(i){let c=j.resolve(i),g=qt(c.source),O=Ce(i,g);if(O!==void 0){x=O.id,T=!1,k({type:"SELECT"}),n.hideHighlight(),N(!0),n.focusTargetInstruction(O.id),n.announce(n.messages().announcements.duplicate);return}if(b.length>=e.maxTargets){T=!1,k({type:"SELECT"}),n.hideHighlight(),N(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}b.length===0&&(F=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,D="",_.beginSelection(),h=!0),Q+=1;let I={id:`target-${String(Q)}`,element:i,resolution:c,marker:g,page:Ft(o.document,o.window),code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:g===void 0?"not-required":"loading",collectionStatus:"loading"};b.push(I),x=I.id,T=!1;let ot=S;k({type:"SELECT"}),n.hideHighlight(),$?.observe(i),N(!0),Y=!0,n.focusTargetInstruction(I.id),oe(I,ot),g!==void 0?se(I,ot):n.announce(c.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function pe(){if(V=void 0,u.status!=="inspecting"||P===void 0)return;let i=Gt(o.document,o.window,P.x,P.y);if(k({type:"HOVER"}),i===void 0){n.hideHighlight();return}Te(i)}function Ie(i){u.status==="inspecting"&&(P={x:i.clientX,y:i.clientY},V??=o.window.requestAnimationFrame(pe))}function xe(i){if(u.status!=="inspecting"||Mn(i.target))return;i.preventDefault(),i.stopPropagation(),i.stopImmediatePropagation();let c=Gt(o.document,o.window,i.clientX,i.clientY);if(c===void 0){n.announce(n.messages().announcements.noSelectable);return}Se(c)}function _e(i){if(i.key==="Escape"&&u.status!=="idle"){i.preventDefault(),u.status==="inspecting"&&T?we():u.status==="inspecting"||u.status==="selected"?ye():(k({type:"BACK"}),n.focusTargetInstruction(x));return}Pn(i.target)||!Ln(i,e.shortcut,o.window.navigator.userAgent)||(i.preventDefault(),$e())}function ke(i){if(u.status!=="selected"&&u.status!=="inspecting")return;let c=b.findIndex(z=>z.id===i);if(c<0)return;let[g]=b.splice(c,1);if(g===void 0)return;let O=B.get(g.id);if(O!==void 0&&(o.window.clearTimeout(O),B.delete(g.id)),g.element!==void 0&&$?.unobserve(g.element),x===g.id&&(x=b.at(-1)?.id),b.length===0){T=!0,u.status==="selected"&&k({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),A.clear(),n.announce(n.messages().announcements.allTargetsRemoved);return}N(),X(),n.announce(n.messages().announcements.targetRemoved)}function W(){if(u.status==="idle"||b.length===0)return;let i=b.filter(c=>c.element!==void 0&&!c.element.isConnected);if(i.length>0){for(let c of i)c.element!==void 0&&($?.unobserve(c.element),c.element=void 0);N(),X(),n.announce(n.messages().announcements.detachedTargetPreserved);return}ee()}function Pe(i){let c=i===void 0?Le():b.find(I=>I.id===i);if(u.status!=="selected"||c?.marker===void 0)return;x!==c.id&&(x=c.id,N());let g=c.marker,O=S,z=++C;k({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),s.openEditor({fileId:g.fileId,line:g.line,column:g.column}).then(()=>{L&&u.status==="selected"&&O===S&&z===C&&x===c.id&&b.includes(c)&&n.renderEditorStatus("success")}).catch(()=>{L&&u.status==="selected"&&O===S&&z===C&&x===c.id&&b.includes(c)&&n.renderEditorStatus("error")})}function Ne(i){if(u.status!=="selected"||!(i.target instanceof HTMLTextAreaElement))return;let c=i.target.dataset.targetInstructionId,g=b.find(O=>O.id===c);g!==void 0&&(g.instruction=i.target.value,n.updateTargetInstruction(g.id,g.instruction),n.setPreviewEnabled(ve()),X())}function Ee(){Pe()}function Ve(i){e.ai.enabled&&u.status==="selected"&&i.key==="Enter"&&(i.metaKey||i.ctrlKey)&&(i.preventDefault(),_.run())}function J(){if(u.status!=="selected")return;let i=be();if(i===void 0){n.announce(n.messages().announcements.completeInstructions);return}D=r.compose(i),k({type:"PREVIEW"}),n.showPreview(D),n.focusPrompt()}function ze(){if(u.status!=="previewing"||D.length===0)return;if(a===void 0){k({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let i=S;a.writeText(D).then(()=>{L&&i===S&&u.status==="previewing"&&(k({type:"COPY_SUCCESS"}),n.focusTargetInstruction(x),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{L&&i===S&&u.status==="previewing"&&(k({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function je(){u.status==="previewing"&&(k({type:"BACK"}),n.focusTargetInstruction(x))}function ue(){if(!(!L||b.length===0)&&(N(),u.status==="previewing")){let i=be();i!==void 0&&(D=r.compose(i),n.showPreview(D))}}function He(i){let c=i.target;if(!(c instanceof Element))return;let g=c.closest("button[data-remove-target-id]");if(g?.dataset.removeTargetId!==void 0){ke(g.dataset.removeTargetId);return}let O=c.closest("button[data-open-target-id]");if(O?.dataset.openTargetId!==void 0){Pe(O.dataset.openTargetId);return}let I=c.closest("button[data-activate-target-id]")?.dataset.activateTargetId;u.status!=="selected"||I===void 0||!b.some(ot=>ot.id===I)||(x=I,N(),n.focusTargetInstruction(I))}function Ke(){w()}function nt(){L||(L=!0,n.renderStatus(u.status),o.document.addEventListener("pointermove",Ie,!0),o.document.addEventListener("click",xe,!0),o.document.addEventListener("keydown",_e,!0),o.window.addEventListener("scroll",W,!0),o.window.addEventListener("resize",W),n.triggerButton.addEventListener("click",$e),n.addTargetButton.addEventListener("click",Oe),n.reselectButton.addEventListener("click",Ke),n.targetList.addEventListener("click",He),n.targetList.addEventListener("input",Ne),n.targetList.addEventListener("keydown",Ve),n.openEditorButton.addEventListener("click",Ee),n.previewButton.addEventListener("click",J),n.copyButton.addEventListener("click",ze),n.backButton.addEventListener("click",je),n.closeButton.addEventListener("click",ye),n.agentProviderSelect.addEventListener("change",_.providerOrModelChanged),n.agentModelSelect.addEventListener("change",_.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",_.consentChanged),n.agentTestButton.addEventListener("click",_.testCapability),n.agentRunButton.addEventListener("click",_.run),n.agentCancelButton.addEventListener("click",_.cancel),n.agentApplyButton.addEventListener("click",_.apply),n.agentRevertButton.addEventListener("click",_.revert),n.agentResetButton.addEventListener("click",_.reset),ie=n.subscribeLocale(ue),o.resizeObserver!==void 0&&($=new o.resizeObserver(W)),o.mutationObserver!==void 0&&(ae=new o.mutationObserver(W),ae.observe(o.document.documentElement,{childList:!0,subtree:!0})),Y&&b.length>0&&(k({type:"RESTORE"}),_.beginSelection(),h=!0,N(!0)),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function m(){if(!L){ie?.(),ie=void 0,n.dispose(),s.cancelPending(),s.dispose(),_.disposeSelection(),j.dispose();return}L=!1,ie?.(),ie=void 0,o.document.removeEventListener("pointermove",Ie,!0),o.document.removeEventListener("click",xe,!0),o.document.removeEventListener("keydown",_e,!0),o.window.removeEventListener("scroll",W,!0),o.window.removeEventListener("resize",W),n.triggerButton.removeEventListener("click",$e),n.addTargetButton.removeEventListener("click",Oe),n.reselectButton.removeEventListener("click",Ke),n.targetList.removeEventListener("click",He),n.targetList.removeEventListener("input",Ne),n.targetList.removeEventListener("keydown",Ve),n.openEditorButton.removeEventListener("click",Ee),n.previewButton.removeEventListener("click",J),n.copyButton.removeEventListener("click",ze),n.backButton.removeEventListener("click",je),n.closeButton.removeEventListener("click",ye),n.agentProviderSelect.removeEventListener("change",_.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",_.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",_.consentChanged),n.agentTestButton.removeEventListener("click",_.testCapability),n.agentRunButton.removeEventListener("click",_.run),n.agentCancelButton.removeEventListener("click",_.cancel),n.agentApplyButton.removeEventListener("click",_.apply),n.agentRevertButton.removeEventListener("click",_.revert),n.agentResetButton.removeEventListener("click",_.reset),V!==void 0&&(o.window.cancelAnimationFrame(V),V=void 0),le(),X(),$?.disconnect(),ae?.disconnect(),$=void 0,ae=void 0,b=[],x=void 0,D="",P=void 0,F=void 0,s.cancelPending(),s.dispose(),_.disposeSelection(),j.dispose(),n.dispose(),u=Wt}return Object.freeze({mount:nt,dispose:m,getState:()=>u})}var uo="__spotpatchRuntime__";function Yt(e){let t=globalThis;t[uo]?.dispose();let o=po(e);t[uo]=o,o.mount()}Yt({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:Je});
|
|
955
|
+
`)}function te(){let s=m.flatMap(p=>{if(!p.element?.isConnected)return[];let c=Tt(p.element,o.window);return c===void 0?[]:[{id:p.id,label:Xt(p.element),rect:c,active:p.id===S}]});s.length===0?n.hideSelectionHighlights():n.showSelectionHighlights(s)}function M(s=!1){if(m.length===0)return;n.renderTargets(m.map(P=>({id:P.id,label:P.resolution.react.componentName??(P.element===void 0?P.elementContext?.tagName??"Element":Xt(P.element)),source:pa(P,n.messages().context.sourceUnavailable),canOpenEditor:P.marker!==void 0,status:ua(P),active:P.id===S,instruction:P.instruction})),e.maxTargets),te();let p=_e(),c=me(),x=p?.marker!==void 0;s?n.showSelection(c,x,Te()):n.updateSelection(c,x,Te())}function be(){if(!Te())return;let s=m.map(p=>{if(p.elementContext===void 0||p.styles===void 0)throw new Error("SpotPatch attempted to compose an incomplete target.");let c=[...p.apiStatus==="failed"?["Source context could not be loaded."]:[],...p.collectionStatus==="failed"?["Part of the browser context could not be collected."]:[]];return{instruction:p.instruction.trim(),page:p.page,source:p.resolution.source,react:p.resolution.react,element:p.elementContext,styles:p.styles,...p.code===void 0?{}:{code:p.code},warnings:c}});return nn({id:l(),locale:n.locale(),createdAt:E(),page:Yt(o.document,o.window),targets:s})}function we(s){n.showHighlight(kn(s,o.window),Xt(s))}function ne(){W?.isConnected===!0&&W.focus({preventScroll:!0}),W=void 0}function le(){for(let s of B.values())o.window.clearTimeout(s);B.clear()}function De(){y+=1,i.cancelPending(),_.disposeSelection(),le(),$?.disconnect(),m=[],S=void 0,K=!1,h=!1,O=!1,I="",n.hideSelection(),n.hideSelectionHighlights(),A.clear(),ne()}function ye(){g.status==="inspecting"?N({type:"CANCEL"}):g.status==="selected"?N({type:"CLOSE"}):g.status==="previewing"&&(N({type:"BACK"}),N({type:"CLOSE"})),K=!1,Y(),n.hideSelection(),n.hideSelectionHighlights(),ne(),n.hideHighlight()}function Oe(){if(g.status!=="inspecting"||!O||m.length===0){ye();return}O=!1,N({type:"SELECT"}),n.hideHighlight(),M(!0),n.focusTargetInstruction(S),n.announce(n.messages().announcements.addCancelled)}function xe(){if(g.status==="inspecting"&&O){Oe();return}if(g.status!=="idle"){ye();return}if(m.length>0){K=!0,N({type:"RESTORE"}),h||(_.beginSelection(),h=!0),M(!0),n.focusTargetInstruction(S),Y();return}N({type:"ACTIVATE"}),n.hideSelection(),n.announce(n.messages().announcements.selectionEnabled)}function w(s=n.messages().announcements.chooseAnother){g.status==="selected"&&(N({type:"RESELECT"}),De(),n.hideHighlight(),n.announce(s))}function Pe(){if(g.status==="selected"){if(m.length>=e.maxTargets){n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}O=!0,N({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideHighlight(),n.announce(n.messages().announcements.chooseAdditional(m.length,e.maxTargets))}}function Se(){y+=1,le(),$?.disconnect();for(let s of m)s.element=void 0;n.hideHighlight(),n.hideSelectionHighlights(),M(),A.clear(),n.announce(n.messages().announcements.appliedTargetsDetached)}let _=so({ai:e.ai,api:i,getAnnotation:be,onApplied:Se,onReselectRequired(){w(n.messages().announcements.reselectAfterChange)},view:n});async function F(s,p){let c=s.marker;if(c!==void 0)try{let x=await i.sourceContext({fileId:c.fileId,line:c.line,column:c.column,maxLines:e.budget.maxCodeLines});ve(s,p)&&(s.code=x,s.apiStatus="connected",Y(),M(),n.announce(n.messages().announcements.sourceLoaded))}catch(x){ve(s,p)&&(s.code=void 0,s.apiStatus="failed",Y(),M(),n.announce(n.messages().announcements.sourceFailed),e.debug&&!(x instanceof DOMException&&x.name==="AbortError")&&console.warn("[spotpatch:runtime] Source context request failed."))}}function se(s,p){let c=s.element;if(c===void 0)return;let x=o.window.setTimeout(()=>{if(B.delete(s.id),!ve(s,p))return;let P=!1;try{s.elementContext=On({element:c,maxCharacters:e.budget.domCharacters})}catch{s.elementContext=void 0,P=!0}try{s.styles=An({document:o.document,element:c,maxCharacters:e.budget.cssCharacters})}catch{s.styles=la,P=!0}s.collectionStatus=P?"failed":"ready",Y(),M(),n.announce(P?n.messages().announcements.contextWarning:n.messages().announcements.contextCollected),e.debug&&s.styles.warnings.length>0&&console.warn(`[spotpatch:runtime] CSS collection completed with ${String(s.styles.warnings.length)} warning(s).`)},0);B.set(s.id,x)}function Ce(s,p){return p!==void 0?m.find(c=>c.marker?.fileId===p.fileId&&c.marker.line===p.line&&c.marker.column===p.column):m.find(c=>c.element===s)}function pe(s){let p=j.resolve(s),c=Kt(p.source),x=Ce(s,c);if(x!==void 0){S=x.id,O=!1,N({type:"SELECT"}),n.hideHighlight(),M(!0),n.focusTargetInstruction(x.id),n.announce(n.messages().announcements.duplicate);return}if(m.length>=e.maxTargets){O=!1,N({type:"SELECT"}),n.hideHighlight(),M(!0),n.announce(n.messages().announcements.selectionLimit(e.maxTargets));return}m.length===0&&(W=o.document.activeElement instanceof HTMLElement?o.document.activeElement:void 0,I="",_.beginSelection(),h=!0),ee+=1;let C={id:`target-${String(ee)}`,element:s,resolution:p,marker:c,page:Yt(o.document,o.window),code:void 0,elementContext:void 0,styles:void 0,instruction:"",apiStatus:c===void 0?"not-required":"loading",collectionStatus:"loading"};m.push(C),S=C.id,O=!1;let oe=y;N({type:"SELECT"}),n.hideHighlight(),$?.observe(s),M(!0),K=!0,n.focusTargetInstruction(C.id),se(C,oe),c!==void 0?F(C,oe):n.announce(p.source.confidence==="probable"?n.messages().announcements.sourceProbable:n.messages().announcements.sourceMissing)}function ue(){if(V=void 0,g.status!=="inspecting"||L===void 0)return;let s=Wt(o.document,o.window,L.x,L.y);if(N({type:"HOVER"}),s===void 0){n.hideHighlight();return}we(s)}function Le(s){g.status==="inspecting"&&(L={x:s.clientX,y:s.clientY},V??=o.window.requestAnimationFrame(ue))}function Ie(s){if(g.status!=="inspecting"||Mn(s.target))return;s.preventDefault(),s.stopPropagation(),s.stopImmediatePropagation();let p=Wt(o.document,o.window,s.clientX,s.clientY);if(p===void 0){n.announce(n.messages().announcements.noSelectable);return}pe(p)}function Ee(s){if(s.key==="Escape"&&g.status!=="idle"){s.preventDefault(),g.status==="inspecting"&&O?Oe():g.status==="inspecting"||g.status==="selected"?ye():(N({type:"BACK"}),n.focusTargetInstruction(S));return}Pn(s.target)||!Ln(s,e.shortcut,o.window.navigator.userAgent)||(s.preventDefault(),xe())}function $e(s){if(g.status!=="selected"&&g.status!=="inspecting")return;let p=m.findIndex(P=>P.id===s);if(p<0)return;let[c]=m.splice(p,1);if(c===void 0)return;let x=B.get(c.id);if(x!==void 0&&(o.window.clearTimeout(x),B.delete(c.id)),c.element!==void 0&&$?.unobserve(c.element),S===c.id&&(S=m.at(-1)?.id),m.length===0){O=!0,g.status==="selected"&&N({type:"RESELECT"}),n.hideSelectionTemporarily(),n.hideSelectionHighlights(),A.clear(),n.announce(n.messages().announcements.allTargetsRemoved);return}M(),Y(),n.announce(n.messages().announcements.targetRemoved)}function X(){if(g.status==="idle"||m.length===0)return;let s=m.filter(p=>p.element!==void 0&&!p.element.isConnected);if(s.length>0){for(let p of s)p.element!==void 0&&($?.unobserve(p.element),p.element=void 0);M(),Y(),n.announce(n.messages().announcements.detachedTargetPreserved);return}te()}function Z(s){let p=s===void 0?_e():m.find(C=>C.id===s);if(g.status!=="selected"||p?.marker===void 0)return;S!==p.id&&(S=p.id,M());let c=p.marker,x=y,P=++T;N({type:"OPEN_EDITOR"}),n.renderEditorStatus("opening"),i.openEditor({fileId:c.fileId,line:c.line,column:c.column}).then(()=>{k&&g.status==="selected"&&x===y&&P===T&&S===p.id&&m.includes(p)&&n.renderEditorStatus("success")}).catch(()=>{k&&g.status==="selected"&&x===y&&P===T&&S===p.id&&m.includes(p)&&n.renderEditorStatus("error")})}function ze(s){if(g.status!=="selected"||!(s.target instanceof HTMLTextAreaElement))return;let p=s.target.dataset.targetInstructionId,c=m.find(x=>x.id===p);c!==void 0&&(c.instruction=s.target.value,n.updateTargetInstruction(c.id,c.instruction),n.setPreviewEnabled(Te()),Y())}function ke(){Z()}function Re(s){e.ai.enabled&&g.status==="selected"&&s.key==="Enter"&&(s.metaKey||s.ctrlKey)&&(s.preventDefault(),_.run())}function Ne(){if(g.status!=="selected")return;let s=be();if(s===void 0){n.announce(n.messages().announcements.completeInstructions);return}I=r.compose(s),N({type:"PREVIEW"}),n.showPreview(I),n.focusPrompt()}function je(){if(g.status!=="previewing"||I.length===0)return;if(a===void 0){N({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.clipboardUnavailable);return}let s=y;a.writeText(I).then(()=>{k&&s===y&&g.status==="previewing"&&(N({type:"COPY_SUCCESS"}),n.focusTargetInstruction(S),n.announce(n.messages().announcements.promptCopied))}).catch(()=>{k&&s===y&&g.status==="previewing"&&(N({type:"COPY_FAILURE"}),n.focusPrompt(),n.announce(n.messages().announcements.copyFailed))})}function He(){g.status==="previewing"&&(N({type:"BACK"}),n.focusTargetInstruction(S))}function z(){if(!(!k||m.length===0)&&(M(),g.status==="previewing")){let s=be();s!==void 0&&(I=r.compose(s),n.showPreview(I))}}function Be(s){let p=s.target;if(!(p instanceof Element))return;let c=p.closest("button[data-remove-target-id]");if(c?.dataset.removeTargetId!==void 0){$e(c.dataset.removeTargetId);return}let x=p.closest("button[data-open-target-id]");if(x?.dataset.openTargetId!==void 0){Z(x.dataset.openTargetId);return}let C=p.closest("button[data-activate-target-id]")?.dataset.activateTargetId;g.status!=="selected"||C===void 0||!m.some(oe=>oe.id===C)||(S=C,M(),n.focusTargetInstruction(C))}function Ke(){w()}function Ye(){k||(k=!0,n.renderStatus(g.status),o.document.addEventListener("pointermove",Le,!0),o.document.addEventListener("click",Ie,!0),o.document.addEventListener("keydown",Ee,!0),o.window.addEventListener("scroll",X,!0),o.window.addEventListener("resize",X),n.triggerButton.addEventListener("click",xe),n.addTargetButton.addEventListener("click",Pe),n.reselectButton.addEventListener("click",Ke),n.targetList.addEventListener("click",Be),n.targetList.addEventListener("input",ze),n.targetList.addEventListener("keydown",Re),n.openEditorButton.addEventListener("click",ke),n.previewButton.addEventListener("click",Ne),n.copyButton.addEventListener("click",je),n.backButton.addEventListener("click",He),n.closeButton.addEventListener("click",ye),n.agentProviderSelect.addEventListener("change",_.providerOrModelChanged),n.agentModelSelect.addEventListener("change",_.providerOrModelChanged),n.agentConsentCheckbox.addEventListener("change",_.consentChanged),n.agentTestButton.addEventListener("click",_.testCapability),n.agentRunButton.addEventListener("click",_.run),n.agentCancelButton.addEventListener("click",_.cancel),n.agentApplyButton.addEventListener("click",_.apply),n.agentRevertButton.addEventListener("click",_.revert),n.agentResetButton.addEventListener("click",_.reset),ie=n.subscribeLocale(z),o.resizeObserver!==void 0&&($=new o.resizeObserver(X)),o.mutationObserver!==void 0&&(ae=new o.mutationObserver(X),ae.observe(o.document.documentElement,{childList:!0,subtree:!0})),K&&m.length>0&&(N({type:"RESTORE"}),_.beginSelection(),h=!0,M(!0)),e.debug&&console.info(`[spotpatch:runtime] Mounted. Shortcut: ${e.shortcut}.`))}function it(){if(!k){ie?.(),ie=void 0,n.dispose(),i.cancelPending(),i.dispose(),_.disposeSelection(),j.dispose();return}k=!1,ie?.(),ie=void 0,o.document.removeEventListener("pointermove",Le,!0),o.document.removeEventListener("click",Ie,!0),o.document.removeEventListener("keydown",Ee,!0),o.window.removeEventListener("scroll",X,!0),o.window.removeEventListener("resize",X),n.triggerButton.removeEventListener("click",xe),n.addTargetButton.removeEventListener("click",Pe),n.reselectButton.removeEventListener("click",Ke),n.targetList.removeEventListener("click",Be),n.targetList.removeEventListener("input",ze),n.targetList.removeEventListener("keydown",Re),n.openEditorButton.removeEventListener("click",ke),n.previewButton.removeEventListener("click",Ne),n.copyButton.removeEventListener("click",je),n.backButton.removeEventListener("click",He),n.closeButton.removeEventListener("click",ye),n.agentProviderSelect.removeEventListener("change",_.providerOrModelChanged),n.agentModelSelect.removeEventListener("change",_.providerOrModelChanged),n.agentConsentCheckbox.removeEventListener("change",_.consentChanged),n.agentTestButton.removeEventListener("click",_.testCapability),n.agentRunButton.removeEventListener("click",_.run),n.agentCancelButton.removeEventListener("click",_.cancel),n.agentApplyButton.removeEventListener("click",_.apply),n.agentRevertButton.removeEventListener("click",_.revert),n.agentResetButton.removeEventListener("click",_.reset),V!==void 0&&(o.window.cancelAnimationFrame(V),V=void 0),le(),Y(),$?.disconnect(),ae?.disconnect(),$=void 0,ae=void 0,m=[],S=void 0,I="",L=void 0,W=void 0,i.cancelPending(),i.dispose(),_.disposeSelection(),j.dispose(),n.dispose(),g=Ft}return Object.freeze({mount:Ye,dispose:it,getState:()=>g})}var uo="__spotpatchRuntime__";function Zt(e){let t=globalThis;t[uo]?.dispose();let o=po(e);t[uo]=o,o.mount()}Zt({...__SPOTPATCH_RUNTIME_CONFIG__,apiBase:Je});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spotpatch/vite",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "Vite development plugin for SpotPatch.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -44,10 +44,10 @@
|
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"@spotpatch/compiler": "^0.1.1",
|
|
47
|
-
"@spotpatch/dev-server": "^0.
|
|
47
|
+
"@spotpatch/dev-server": "^0.2.0",
|
|
48
48
|
"@spotpatch/react-adapter": "^1.0.1",
|
|
49
|
-
"@spotpatch/runtime": "^1.
|
|
50
|
-
"@spotpatch/shared": "^1.
|
|
49
|
+
"@spotpatch/runtime": "^1.6.0",
|
|
50
|
+
"@spotpatch/shared": "^1.7.0"
|
|
51
51
|
},
|
|
52
52
|
"peerDependencies": {
|
|
53
53
|
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0"
|