@spotpatch/vite 1.6.1 → 1.8.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 CHANGED
@@ -17,24 +17,30 @@ The supported Vite integration for SpotPatch: select React UI, trace it to JSX/T
17
17
 
18
18
  SpotPatch runs only with the Vite development server. Production builds contain no SpotPatch Runtime, source markers, or local API endpoints.
19
19
 
20
- ### Install
20
+ ### One-command setup (recommended)
21
21
 
22
22
  ```bash
23
- npm install --save-dev @spotpatch/vite
24
- # or
25
- pnpm add -D @spotpatch/vite
23
+ # pnpm project
24
+ pnpm dlx @spotpatch/vite@latest setup
25
+
26
+ # npm project
27
+ npx --yes @spotpatch/vite@latest setup
26
28
  ```
27
29
 
28
- ### Initialize
30
+ `setup` detects npm or pnpm, installs or upgrades the explicit npm `latest` tag, updates a supported `vite.config.*`, and verifies the result. The initializer supports configuration objects and object-returning `defineConfig` callbacks, while ambiguous dynamic configurations fail without writing the config.
29
31
 
30
- Run the safe, idempotent initializer and its read-only diagnostic:
32
+ For separate steps, use `@latest` when you intend to upgrade an existing lockfile entry:
31
33
 
32
34
  ```bash
35
+ npm install --save-dev @spotpatch/vite@latest
36
+ npx spotpatch-vite init
37
+
38
+ # or
39
+ pnpm add -D @spotpatch/vite@latest
33
40
  pnpm exec spotpatch-vite init
34
- pnpm exec spotpatch-vite check
35
41
  ```
36
42
 
37
- The initializer places SpotPatch before the React plugin. When the project has a local TypeScript installation and root `tsconfig.json`, it also exposes the in-page Review / Trusted fast selector without duplicating provider configuration:
43
+ The initializer places SpotPatch before the React plugin so source markers are injected before React transforms the module:
38
44
 
39
45
  ```ts
40
46
  // vite.config.ts
@@ -47,6 +53,8 @@ export default defineConfig({
47
53
  });
48
54
  ```
49
55
 
56
+ When no safe local TypeScript check can be discovered, it generates `spotPatch()` and keeps Review mode. Unsupported dynamic configuration can still be integrated manually using the same plugin order.
57
+
50
58
  Start the application normally:
51
59
 
52
60
  ```bash
@@ -60,11 +68,11 @@ Select **Select element** in the bottom-right corner or press `Mod+Shift+S`. Spo
60
68
  | Dependency | Supported range |
61
69
  | -------------------- | ------------------------------ |
62
70
  | Node.js | `>=20.19.0` |
63
- | Vite | `^5.0.0 | | ^6.0.0 | | ^7.0.0` |
71
+ | Vite | `>=5.0.0 <8.0.0` |
64
72
  | React public support | `18.2–18.3` |
65
73
  | Default source files | `src/**/*.jsx`, `src/**/*.tsx` |
66
74
 
67
- React 19 is not part of the Vite v1 public support promise. Next.js projects must not use this package as a substitute for a Next adapter; see the repository's [Next.js status](https://github.com/huanglvjing/spotpatch/blob/main/docs/%E6%8A%80%E6%9C%AF%E6%96%B9%E6%A1%88/Next%E9%80%82%E9%85%8D/00-%E7%B4%A2%E5%BC%95%E4%B8%8E%E6%9E%B6%E6%9E%84%E6%91%98%E8%A6%81.md).
75
+ React 19, including 19.2.x, is not part of the Vite v1 public support promise. You may try it experimentally, but verify picking, source resolution, HMR, and the AI workflow in your application before relying on it. Next.js projects must not use this package as a substitute for a Next adapter; see the repository's [Next.js status](https://github.com/huanglvjing/spotpatch/blob/main/docs/%E6%8A%80%E6%9C%AF%E6%96%B9%E6%A1%88/Next%E9%80%82%E9%85%8D/00-%E7%B4%A2%E5%BC%95%E4%B8%8E%E6%9E%B6%E6%9E%84%E6%91%98%E8%A6%81.md).
68
76
 
69
77
  ### Options
70
78
 
@@ -96,7 +104,7 @@ spotPatch({
96
104
  | `locale` | `"auto"` | Resolves `en-US` or `zh-CN`. |
97
105
  | `maxTargets` | `8` | Targets allowed in one change request by default. |
98
106
  | `ai` | disabled or a detected complete environment | Optional provider and Agent settings. |
99
- | `trustedFastMode` | `false` | Exposes the page selector and auto-discovers a local TypeScript check. |
107
+ | `trustedFastMode` | `false` | Exposes Review/Trusted direct and discovers TypeScript for Review. |
100
108
 
101
109
  The package exports the option types, AI provider types, Agent limits, and immutable defaults. See the [public API specification](https://github.com/huanglvjing/spotpatch/blob/main/docs/%E6%8A%80%E6%9C%AF%E6%96%B9%E6%A1%88/03-%E5%85%AC%E5%85%B1API%E4%B8%8E%E6%95%B0%E6%8D%AE%E6%A8%A1%E5%9E%8B.md) for the complete constraints.
102
110
 
@@ -129,13 +137,13 @@ spotPatch({
129
137
 
130
138
  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.
131
139
 
132
- `spotpatch-vite init` automatically enables the page selector when it can discover a local TypeScript check. The equivalent concise manual option is:
140
+ To expose the optional Trusted direct mode, configure it explicitly. It requires a local TypeScript project check; otherwise keep the default Review mode:
133
141
 
134
142
  ```ts
135
143
  spotPatch({ trustedFastMode: true });
136
144
  ```
137
145
 
138
- The page defaults to Review; choosing Trusted fast replaces the provider and dirty-worktree confirmations with one session-scoped consent and directly applies changes after required checks. Advanced projects can still configure explicit checks through `ai.execution`. 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.
146
+ The page defaults to Review. Choosing Trusted direct uses the exact SpotPatch source path first, removes `run_check` from the model tools, skips host project checks, and immediately applies the isolated Diff after one session-scoped consent. This is faster but does not promise that TypeScript, lint, tests, or builds pass; configured checks still protect Review and Auto modes. Project-root boundaries, protected paths, atomic patch checks, concurrent-edit hashes, Revert, and the ban on arbitrary shell remain enforced. SpotPatch does not commit, push, publish, or deploy application code.
139
147
 
140
148
  ### Security and production behavior
141
149
 
@@ -149,6 +157,8 @@ The page defaults to Review; choosing Trusted fast replaces the provider and dir
149
157
 
150
158
  ### Troubleshooting
151
159
 
160
+ - **An old version remains installed:** use `@spotpatch/vite@latest`; an untagged add may preserve an existing compatible lockfile entry.
161
+ - **Initializer rejects the config:** use a configuration object or a callback with one unambiguous object return. For conditional returns or dynamic plugin arrays, configure `spotPatch()` manually before the React plugin.
152
162
  - **No selection button:** confirm `spotPatch()` appears before the React plugin and that the app is running through `vite`/`vite dev`, not `vite preview`.
153
163
  - **No exact source location:** confirm the component is authored in an included `.jsx` or `.tsx` file under `src`, or configure `include` explicitly.
154
164
  - **AI is unavailable:** provide all three required environment values or set `ai: false`; partial environment configuration fails closed.
@@ -169,24 +179,30 @@ The page defaults to Review; choosing Trusted fast replaces the provider and dir
169
179
 
170
180
  SpotPatch 只在 Vite 开发服务器中运行。生产构建不包含 SpotPatch Runtime、源码标记或本地 API 端点。
171
181
 
172
- ### 安装
182
+ ### 一条命令接入(推荐)
173
183
 
174
184
  ```bash
175
- npm install --save-dev @spotpatch/vite
176
- #
177
- pnpm add -D @spotpatch/vite
185
+ # pnpm 项目
186
+ pnpm dlx @spotpatch/vite@latest setup
187
+
188
+ # npm 项目
189
+ npx --yes @spotpatch/vite@latest setup
178
190
  ```
179
191
 
180
- ### 初始化
192
+ `setup` 会识别 npm 或 pnpm,显式安装或升级 npm `latest` 标签,安全更新受支持的 `vite.config.*` 并验证结果。初始化器支持配置对象和返回对象的 `defineConfig` 回调;有歧义的动态配置会在不写入配置文件的情况下失败。
181
193
 
182
- 运行安全、幂等的初始化命令,再执行只读诊断:
194
+ 需要分开执行时,如果要升级锁文件里的已有版本,请显式使用 `@latest`:
183
195
 
184
196
  ```bash
197
+ npm install --save-dev @spotpatch/vite@latest
198
+ npx spotpatch-vite init
199
+
200
+ # 或
201
+ pnpm add -D @spotpatch/vite@latest
185
202
  pnpm exec spotpatch-vite init
186
- pnpm exec spotpatch-vite check
187
203
  ```
188
204
 
189
- 初始化器会把 SpotPatch 放在 React 插件之前;项目存在本地 TypeScript 与根 `tsconfig.json` 时,还会自动开放页面内的“审阅 / 可信快速”选择,不需要重复填写 Provider:
205
+ 初始化器会将 SpotPatch 放在 React 插件之前,确保源码标记在 React 转换前注入:
190
206
 
191
207
  ```ts
192
208
  // vite.config.ts
@@ -199,6 +215,8 @@ export default defineConfig({
199
215
  });
200
216
  ```
201
217
 
218
+ 无法发现安全的本地 TypeScript 检查时,初始化器会生成 `spotPatch()` 并保持审阅模式。不受支持的动态配置仍可按相同插件顺序手动接入。
219
+
202
220
  照常启动应用:
203
221
 
204
222
  ```bash
@@ -212,11 +230,11 @@ pnpm dev
212
230
  | 依赖 | 正式支持范围 |
213
231
  | -------------- | ------------------------------ |
214
232
  | Node.js | `>=20.19.0` |
215
- | Vite | `^5.0.0 | | ^6.0.0 | | ^7.0.0` |
233
+ | Vite | `>=5.0.0 <8.0.0` |
216
234
  | React 正式支持 | `18.2–18.3` |
217
235
  | 默认源码文件 | `src/**/*.jsx`、`src/**/*.tsx` |
218
236
 
219
- React 19 不在 Vite v1 正式承诺内。Next.js 项目不能把本包当作 Next 适配器使用;准确状态见仓库中的 [Next.js 适配说明](https://github.com/huanglvjing/spotpatch/blob/main/docs/%E6%8A%80%E6%9C%AF%E6%96%B9%E6%A1%88/Next%E9%80%82%E9%85%8D/00-%E7%B4%A2%E5%BC%95%E4%B8%8E%E6%9E%B6%E6%9E%84%E6%91%98%E8%A6%81.md)。
237
+ React 19(包括 19.2.x)不在 Vite v1 正式承诺内。可以作为实验性组合尝试,但在日常使用前必须在自身项目验证元素选择、源码定位、HMR 和 AI 流程。Next.js 项目不能把本包当作 Next 适配器使用;准确状态见仓库中的 [Next.js 适配说明](https://github.com/huanglvjing/spotpatch/blob/main/docs/%E6%8A%80%E6%9C%AF%E6%96%B9%E6%A1%88/Next%E9%80%82%E9%85%8D/00-%E7%B4%A2%E5%BC%95%E4%B8%8E%E6%9E%B6%E6%9E%84%E6%91%98%E8%A6%81.md)。
220
238
 
221
239
  ### 选项
222
240
 
@@ -234,21 +252,21 @@ spotPatch({
234
252
  });
235
253
  ```
236
254
 
237
- | 选项 | 默认值 | 说明 |
238
- | ----------------- | ---------------------------- | ---------------------------------------------------- |
239
- | `enabled` | `true` | 启用开发期插件。 |
240
- | `include` | `src` 下 JSX/TSX | 允许注入源码标记的文件。 |
241
- | `exclude` | 依赖、测试、Story 与生成目录 | 不进行转换的文件。 |
242
- | `editor` | `"auto"` | 自动识别 Cursor 或 VS Code,也可显式固定。 |
243
- | `redact` | `true` | 清洗采集上下文;强制保护的秘密类型不会因关闭而暴露。 |
244
- | `budget` | 有界默认值 | 限制总量、DOM、CSS 和源码上下文大小。 |
245
- | `shortcut` | `"Mod+Shift+S"` | 切换元素选择器。 |
246
- | `allowLan` | `false` | 默认只允许 loopback Host 与 Origin。 |
247
- | `debug` | `false` | 输出不包含凭据的开发诊断。 |
248
- | `locale` | `"auto"` | 自动解析 `en-US` 或 `zh-CN`。 |
249
- | `maxTargets` | `8` | 一次修改任务默认允许的目标数。 |
250
- | `ai` | 关闭或检测到完整环境配置 | 可选 Provider 和 Agent 配置。 |
251
- | `trustedFastMode` | `false` | 开放页面模式选择并自动发现本地 TypeScript 校验。 |
255
+ | 选项 | 默认值 | 说明 |
256
+ | ----------------- | ---------------------------- | ------------------------------------------------------ |
257
+ | `enabled` | `true` | 启用开发期插件。 |
258
+ | `include` | `src` 下 JSX/TSX | 允许注入源码标记的文件。 |
259
+ | `exclude` | 依赖、测试、Story 与生成目录 | 不进行转换的文件。 |
260
+ | `editor` | `"auto"` | 自动识别 Cursor 或 VS Code,也可显式固定。 |
261
+ | `redact` | `true` | 清洗采集上下文;强制保护的秘密类型不会因关闭而暴露。 |
262
+ | `budget` | 有界默认值 | 限制总量、DOM、CSS 和源码上下文大小。 |
263
+ | `shortcut` | `"Mod+Shift+S"` | 切换元素选择器。 |
264
+ | `allowLan` | `false` | 默认只允许 loopback Host 与 Origin。 |
265
+ | `debug` | `false` | 输出不包含凭据的开发诊断。 |
266
+ | `locale` | `"auto"` | 自动解析 `en-US` 或 `zh-CN`。 |
267
+ | `maxTargets` | `8` | 一次修改任务默认允许的目标数。 |
268
+ | `ai` | 关闭或检测到完整环境配置 | 可选 Provider 和 Agent 配置。 |
269
+ | `trustedFastMode` | `false` | 开放审阅/可信极速选择;TypeScript 检查供审阅模式使用。 |
252
270
 
253
271
  本包导出选项类型、AI Provider 类型、Agent 限制和不可变默认值。完整约束见[公共 API 规范](https://github.com/huanglvjing/spotpatch/blob/main/docs/%E6%8A%80%E6%9C%AF%E6%96%B9%E6%A1%88/03-%E5%85%AC%E5%85%B1API%E4%B8%8E%E6%95%B0%E6%8D%AE%E6%A8%A1%E5%9E%8B.md)。
254
272
 
@@ -281,13 +299,13 @@ spotPatch({
281
299
 
282
300
  默认 Agent 路径必须经过审阅:“检查运行环境”提供不含源码的可选能力诊断;点击运行会直接进入真实隔离工具会话,并在会话内证明工具续接能力。Agent 会提供有界的就近项目规范,只暴露文件工具而不是任意 Shell,复用当前变更版本中由宿主实际执行的检查,并在 Apply 前展示完整 Diff。
283
301
 
284
- `spotpatch-vite init` 能发现本地 TypeScript 校验时会自动开放页面选择;等价的简洁手动配置只有一行:
302
+ 需要开放可选的“可信极速”模式时,请显式配置。它要求项目能提供本地 TypeScript 检查;否则请保持默认的审阅模式:
285
303
 
286
304
  ```ts
287
305
  spotPatch({ trustedFastMode: true });
288
306
  ```
289
307
 
290
- 页面默认保持审阅模式;用户选择“可信快速”后,面板才会把 Provider 与脏工作区确认合并成一次会话级授权,并在必需检查通过后直接应用。高级项目仍可通过 `ai.execution` 配置自己的检查。该模式可以直接应用验证通过的文件删除与需要重启开发服务的配置变更,但不会开放凭据、环境文件、Git 元数据、项目外路径、任意 Shell,也不会绕过失败检查或基线冲突。SpotPatch 不会替业务代码执行 commit、push、发包或部署。
308
+ 页面默认保持审阅模式。用户选择“可信极速”后,Agent 会优先使用 SpotPatch 已定位的精确源码路径,不再获得 `run_check` 工具,也不执行宿主项目检查;隔离 Diff 形成后立即写回。它速度更快,但不承诺 TypeScript、lint、测试或构建通过;配置的检查仍用于审阅和受控自动模式。项目根、保护路径、原子 patch 校验、并发哈希冲突和 Revert 仍然保留,也不会开放任意 Shell,或替业务代码执行 commit、push、发包和部署。
291
309
 
292
310
  ### 安全与生产行为
293
311
 
@@ -301,6 +319,8 @@ spotPatch({ trustedFastMode: true });
301
319
 
302
320
  ### 常见问题
303
321
 
322
+ - **仍然安装了旧版本:**请使用 `@spotpatch/vite@latest`;不带标签的 add 可能继续复用锁文件中满足范围的旧版本。
323
+ - **初始化器拒绝配置:**请使用配置对象,或只含一个明确对象返回的回调。存在条件返回或动态插件数组时,手动将 `spotPatch()` 放到 React 插件之前。
304
324
  - **没有选择元素按钮:**确认 `spotPatch()` 位于 React 插件之前,并且应用通过 `vite`/`vite dev` 而不是 `vite preview` 启动。
305
325
  - **没有精确源码位置:**确认组件来自 include 范围内的 `.jsx` 或 `.tsx` 文件,默认范围是 `src`。
306
326
  - **AI 不可用:**提供全部三个必需环境变量,或者显式设置 `ai: false`;不完整配置会安全失败。
package/dist/cli.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli.ts
4
- import { readFile } from "fs/promises";
4
+ import { readFile as readFile2 } from "fs/promises";
5
5
  import { createRequire } from "module";
6
- import path2 from "path";
6
+ import path3 from "path";
7
7
 
8
8
  // src/initializer.ts
9
9
  import path from "path";
@@ -153,6 +153,47 @@ function resolveConfigExpression(program) {
153
153
  }
154
154
  return unwrapExpression(resolved);
155
155
  }
156
+ function resolveFactoryConfigObject(expression) {
157
+ const factory = unwrapExpression(expression);
158
+ if (factory.type !== "ArrowFunctionExpression" && factory.type !== "FunctionExpression") {
159
+ return void 0;
160
+ }
161
+ if (factory.body === null) {
162
+ throw new Error(
163
+ "SpotPatch init cannot use a defineConfig callback without a body."
164
+ );
165
+ }
166
+ if (factory.body.type !== "BlockStatement") {
167
+ const returned2 = unwrapExpression(factory.body);
168
+ return returned2.type === "ObjectExpression" ? returned2 : void 0;
169
+ }
170
+ const returns = [];
171
+ new Visitor({
172
+ ReturnStatement(statement) {
173
+ returns.push(statement);
174
+ }
175
+ }).visit({
176
+ type: "Program",
177
+ body: factory.body.body,
178
+ sourceType: "module",
179
+ hashbang: null,
180
+ start: factory.body.start,
181
+ end: factory.body.end
182
+ });
183
+ const onlyReturn = returns.length === 1 ? returns[0] : void 0;
184
+ if (onlyReturn?.argument == null) {
185
+ throw new Error(
186
+ "SpotPatch init requires a defineConfig callback with exactly one top-level object return."
187
+ );
188
+ }
189
+ const returned = unwrapExpression(onlyReturn.argument);
190
+ if (returned.type !== "ObjectExpression") {
191
+ throw new Error(
192
+ "SpotPatch init requires the defineConfig callback to return a configuration object directly."
193
+ );
194
+ }
195
+ return returned;
196
+ }
156
197
  function resolveConfigObject(program) {
157
198
  const expression = resolveConfigExpression(program);
158
199
  if (expression.type === "ObjectExpression") {
@@ -166,10 +207,14 @@ function resolveConfigObject(program) {
166
207
  if (value.type === "ObjectExpression") {
167
208
  return value;
168
209
  }
210
+ const callbackObject = resolveFactoryConfigObject(value);
211
+ if (callbackObject !== void 0) {
212
+ return callbackObject;
213
+ }
169
214
  }
170
215
  }
171
216
  throw new Error(
172
- "SpotPatch init currently supports an object passed to defineConfig in vite.config."
217
+ "SpotPatch init supports a configuration object or an object-returning callback passed to defineConfig."
173
218
  );
174
219
  }
175
220
  function propertyName(property) {
@@ -384,15 +429,103 @@ async function checkViteIntegration(directory = process.cwd()) {
384
429
  }
385
430
  }
386
431
 
432
+ // src/setup.ts
433
+ import { spawn } from "child_process";
434
+ import { access, readFile } from "fs/promises";
435
+ import path2 from "path";
436
+ async function pathExists(absolutePath) {
437
+ try {
438
+ await access(absolutePath);
439
+ return true;
440
+ } catch (error) {
441
+ if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
442
+ return false;
443
+ }
444
+ throw error;
445
+ }
446
+ }
447
+ async function detectPackageManager(appRoot = process.cwd(), userAgent = process.env.npm_config_user_agent ?? "") {
448
+ const manifestPath = path2.join(appRoot, "package.json");
449
+ const manifest = JSON.parse(
450
+ await readFile(manifestPath, "utf8")
451
+ );
452
+ const declared = manifest.packageManager;
453
+ if (typeof declared === "string") {
454
+ const name = declared.split("@", 1)[0];
455
+ if (name === "pnpm" || name === "npm") {
456
+ return name;
457
+ }
458
+ throw new Error(
459
+ `SpotPatch setup supports npm and pnpm projects; package.json declares ${declared}.`
460
+ );
461
+ }
462
+ const [hasPnpmLock, hasNpmLock] = await Promise.all([
463
+ pathExists(path2.join(appRoot, "pnpm-lock.yaml")),
464
+ pathExists(path2.join(appRoot, "package-lock.json"))
465
+ ]);
466
+ if (hasPnpmLock !== hasNpmLock) {
467
+ return hasPnpmLock ? "pnpm" : "npm";
468
+ }
469
+ if (hasPnpmLock && hasNpmLock) {
470
+ throw new Error(
471
+ "SpotPatch setup found both pnpm-lock.yaml and package-lock.json; remove the stale lockfile or run installation and init separately."
472
+ );
473
+ }
474
+ if (userAgent.startsWith("pnpm/")) {
475
+ return "pnpm";
476
+ }
477
+ if (userAgent.startsWith("npm/")) {
478
+ return "npm";
479
+ }
480
+ throw new Error(
481
+ "SpotPatch setup could not determine npm or pnpm; run installation and init separately."
482
+ );
483
+ }
484
+ function createInstallCommand(packageManager, platform = process.platform) {
485
+ return Object.freeze({
486
+ executable: platform === "win32" ? `${packageManager}.cmd` : packageManager,
487
+ arguments: Object.freeze(
488
+ packageManager === "pnpm" ? ["add", "-D", "@spotpatch/vite@latest"] : ["install", "--save-dev", "@spotpatch/vite@latest"]
489
+ )
490
+ });
491
+ }
492
+ async function installLatestAdapter(packageManager, appRoot = process.cwd()) {
493
+ const command = createInstallCommand(packageManager);
494
+ process.stdout.write(
495
+ `[spotpatch:vite] installing @spotpatch/vite@latest with ${packageManager}...
496
+ `
497
+ );
498
+ await new Promise((resolve, reject) => {
499
+ const child = spawn(command.executable, command.arguments, {
500
+ cwd: appRoot,
501
+ env: process.env,
502
+ shell: false,
503
+ stdio: "inherit"
504
+ });
505
+ child.once("error", reject);
506
+ child.once("exit", (code, signal) => {
507
+ if (code === 0) {
508
+ resolve();
509
+ return;
510
+ }
511
+ reject(
512
+ new Error(
513
+ `SpotPatch setup installation failed (${signal ?? `exit ${String(code)}`}).`
514
+ )
515
+ );
516
+ });
517
+ });
518
+ }
519
+
387
520
  // src/cli.ts
388
521
  var VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/u;
389
522
  function writeUsage() {
390
523
  process.stderr.write(
391
- "Usage: spotpatch-vite <init|check>\n init Preview and apply safe Vite integration changes.\n check Verify the Vite integration without writing files.\n"
524
+ "Usage: spotpatch-vite <setup|init|check>\n setup Install or upgrade @spotpatch/vite@latest, then initialize it.\n init Preview and apply safe Vite integration changes.\n check Verify the Vite integration without writing files.\n"
392
525
  );
393
526
  }
394
527
  async function inspectViteProject(appRoot = process.cwd()) {
395
- const resolveFromApplication = createRequire(path2.join(appRoot, "package.json"));
528
+ const resolveFromApplication = createRequire(path3.join(appRoot, "package.json"));
396
529
  let adapterEntry;
397
530
  let viteManifestPath;
398
531
  try {
@@ -407,7 +540,7 @@ async function inspectViteProject(appRoot = process.cwd()) {
407
540
  if (adapterEntry.length === 0) {
408
541
  throw new Error("SpotPatch could not resolve the Vite adapter export.");
409
542
  }
410
- const manifest = JSON.parse(await readFile(viteManifestPath, "utf8"));
543
+ const manifest = JSON.parse(await readFile2(viteManifestPath, "utf8"));
411
544
  const version = typeof manifest === "object" && manifest !== null && "version" in manifest && typeof manifest.version === "string" ? manifest.version : void 0;
412
545
  const match = version === void 0 ? null : VERSION_PATTERN.exec(version);
413
546
  const major = Number(match?.[1]);
@@ -451,6 +584,14 @@ ${change.nextContent}`);
451
584
  writeTrustedModeStatus(plan.trustedFastModeAvailable);
452
585
  return 0;
453
586
  }
587
+ async function runSetup(arguments_) {
588
+ if (arguments_.length !== 0) {
589
+ throw new Error("SpotPatch setup does not accept positional arguments.");
590
+ }
591
+ const packageManager = await detectPackageManager();
592
+ await installLatestAdapter(packageManager);
593
+ return runInit([]);
594
+ }
454
595
  async function runCheck(arguments_) {
455
596
  if (arguments_.length !== 0) {
456
597
  throw new Error("SpotPatch check does not accept positional arguments.");
@@ -473,6 +614,9 @@ async function runCheck(arguments_) {
473
614
  }
474
615
  async function main(arguments_) {
475
616
  const [command, ...rest] = arguments_;
617
+ if (command === "setup") {
618
+ return runSetup(rest);
619
+ }
476
620
  if (command === "init") {
477
621
  return runInit(rest);
478
622
  }
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/initializer.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\n\nimport {\n applyViteIntegrationPlan,\n checkViteIntegration,\n planViteIntegration,\n} from \"./initializer.js\";\n\nconst VERSION_PATTERN = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-[0-9A-Za-z.-]+)?$/u;\n\nfunction writeUsage(): void {\n process.stderr.write(\n \"Usage: spotpatch-vite <init|check>\\n\" +\n \" init Preview and apply safe Vite integration changes.\\n\" +\n \" check Verify the Vite integration without writing files.\\n\",\n );\n}\n\nasync function inspectViteProject(appRoot = process.cwd()): Promise<string> {\n const resolveFromApplication = createRequire(path.join(appRoot, \"package.json\"));\n let adapterEntry: string;\n let viteManifestPath: string;\n\n try {\n adapterEntry = resolveFromApplication.resolve(\"@spotpatch/vite\");\n viteManifestPath = resolveFromApplication.resolve(\"vite/package.json\");\n } catch (error: unknown) {\n throw new Error(\n \"SpotPatch could not resolve the local @spotpatch/vite and Vite packages.\",\n { cause: error },\n );\n }\n\n if (adapterEntry.length === 0) {\n throw new Error(\"SpotPatch could not resolve the Vite adapter export.\");\n }\n\n const manifest = JSON.parse(await readFile(viteManifestPath, \"utf8\")) as unknown;\n const version =\n typeof manifest === \"object\" &&\n manifest !== null &&\n \"version\" in manifest &&\n typeof manifest.version === \"string\"\n ? manifest.version\n : undefined;\n const match = version === undefined ? null : VERSION_PATTERN.exec(version);\n const major = Number(match?.[1]);\n\n if (\n version === undefined ||\n match === null ||\n !Number.isSafeInteger(major) ||\n major < 5 ||\n major >= 8\n ) {\n throw new Error(\n `SpotPatch Vite requires Vite >=5.0.0 <8.0.0; found ${version ?? \"unknown\"}.`,\n );\n }\n\n return version;\n}\n\nfunction writeTrustedModeStatus(available: boolean): void {\n process.stdout.write(\n available\n ? \"[spotpatch:vite] trusted fast mode is available in the page selector.\\n\"\n : \"[spotpatch:vite] review mode is ready; trusted fast mode needs a local TypeScript project check.\\n\",\n );\n}\n\nasync function runInit(arguments_: readonly string[]): Promise<number> {\n if (arguments_.length !== 0) {\n throw new Error(\"SpotPatch init does not accept positional arguments.\");\n }\n\n await inspectViteProject();\n const plan = await planViteIntegration();\n\n if (plan.changes.length === 0) {\n process.stdout.write(\"[spotpatch:vite] integration is already up to date.\\n\");\n writeTrustedModeStatus(plan.trustedFastModeAvailable);\n return 0;\n }\n\n process.stdout.write(\"[spotpatch:vite] integration preview (resulting files):\\n\");\n\n for (const change of plan.changes) {\n process.stdout.write(`\\n--- ${change.relativePath}\\n${change.nextContent}`);\n\n if (!change.nextContent.endsWith(\"\\n\")) {\n process.stdout.write(\"\\n\");\n }\n }\n\n await applyViteIntegrationPlan(plan);\n process.stdout.write(\n `[spotpatch:vite] updated ${String(plan.changes.length)} integration file(s).\\n`,\n );\n writeTrustedModeStatus(plan.trustedFastModeAvailable);\n\n return 0;\n}\n\nasync function runCheck(arguments_: readonly string[]): Promise<number> {\n if (arguments_.length !== 0) {\n throw new Error(\"SpotPatch check does not accept positional arguments.\");\n }\n\n const version = await inspectViteProject();\n const result = await checkViteIntegration();\n\n if (!result.ok) {\n for (const issue of result.issues) {\n process.stderr.write(`[spotpatch:vite] ${issue}\\n`);\n }\n\n return 1;\n }\n\n const mode = result.trustedFastModeAvailable\n ? \"trusted fast mode available\"\n : \"review mode\";\n process.stdout.write(\n `[spotpatch:vite] integration verified for Vite ${version} · ${mode}.\\n`,\n );\n return 0;\n}\n\nasync function main(arguments_: readonly string[]): Promise<number> {\n const [command, ...rest] = arguments_;\n\n if (command === \"init\") {\n return runInit(rest);\n }\n\n if (command === \"check\") {\n return runCheck(rest);\n }\n\n writeUsage();\n return 1;\n}\n\ntry {\n process.exitCode = await main(process.argv.slice(2));\n} catch (error: unknown) {\n process.stderr.write(\n `[spotpatch:vite] ${\n error instanceof Error ? error.message : \"The command failed.\"\n }\\n`,\n );\n process.exitCode = 1;\n}\n","import path from \"node:path\";\n\nimport {\n applyIntegrationPlan,\n createIntegrationFileChange,\n discoverProjectValidationCheck,\n integrationPathExists,\n readIntegrationFile,\n type IntegrationFileChange,\n} from \"@spotpatch/dev-server\";\nimport { DEFAULT_AGENT_LIMITS } from \"@spotpatch/shared\";\nimport { MagicString } from \"magic-string\";\nimport {\n parseSync,\n Visitor,\n type ArrayExpression,\n type CallExpression,\n type ExportDefaultDeclaration,\n type Expression,\n type ImportDeclaration,\n type ObjectExpression,\n type ObjectProperty,\n type Program,\n} from \"oxc-parser\";\n\nconst ADAPTER_PACKAGE_NAME = \"@spotpatch/vite\";\nconst CONFIG_FILE_NAMES = Object.freeze([\n \"vite.config.ts\",\n \"vite.config.mts\",\n \"vite.config.js\",\n \"vite.config.mjs\",\n] as const);\n\nexport interface ViteIntegrationPlan {\n readonly appRoot: string;\n readonly changes: readonly IntegrationFileChange[];\n readonly trustedFastModeAvailable: boolean;\n}\n\nexport interface ViteIntegrationCheck {\n readonly appRoot: string;\n readonly issues: readonly string[];\n readonly ok: boolean;\n readonly trustedFastModeAvailable: boolean;\n}\n\ninterface ParsedModule {\n readonly program: Program;\n readonly source: string;\n}\n\nfunction isParserErrorSeverity(value: unknown): boolean {\n return value === \"Error\";\n}\n\nfunction parseModule(absolutePath: string, source: string): ParsedModule {\n const result = parseSync(absolutePath, source, {\n sourceType: \"module\",\n showSemanticErrors: true,\n });\n const error = result.errors.find((entry) => isParserErrorSeverity(entry.severity));\n\n if (error !== undefined) {\n throw new SyntaxError(\n `SpotPatch could not safely parse ${path.basename(absolutePath)} (${error.message}).`,\n );\n }\n\n return Object.freeze({ program: result.program, source });\n}\n\nfunction importsOf(program: Program): readonly ImportDeclaration[] {\n return program.body.filter(\n (statement): statement is ImportDeclaration =>\n statement.type === \"ImportDeclaration\",\n );\n}\n\nfunction importInsertionOffset(program: Program): number {\n const lastImport = importsOf(program).at(-1);\n\n if (lastImport !== undefined) {\n return lastImport.end;\n }\n\n const directives = program.body.filter(\n (statement) =>\n statement.type === \"ExpressionStatement\" &&\n typeof statement.directive === \"string\",\n );\n return directives.at(-1)?.end ?? program.hashbang?.end ?? 0;\n}\n\nfunction insertStaticImport(\n magicString: MagicString,\n program: Program,\n statement: string,\n): void {\n const offset = importInsertionOffset(program);\n\n if (offset === 0) {\n magicString.prepend(`${statement}\\n`);\n return;\n }\n\n magicString.appendRight(offset, `\\n${statement}`);\n}\n\nfunction collectIdentifierNames(program: Program): ReadonlySet<string> {\n const names = new Set<string>();\n new Visitor({\n Identifier(node) {\n names.add(node.name);\n },\n }).visit(program);\n return names;\n}\n\nfunction choosePluginName(program: Program): string {\n const names = collectIdentifierNames(program);\n let suffix = 0;\n let candidate = \"spotPatch\";\n\n while (names.has(candidate)) {\n suffix += 1;\n candidate = `spotPatch${String(suffix)}`;\n }\n\n return candidate;\n}\n\nfunction importedPluginName(program: Program): string | undefined {\n const adapterImports = importsOf(program).filter(\n (statement) => statement.source.value === ADAPTER_PACKAGE_NAME,\n );\n\n if (adapterImports.length > 1) {\n throw new Error(\"SpotPatch init found duplicate @spotpatch/vite imports.\");\n }\n\n const adapterImport = adapterImports[0];\n\n if (adapterImport === undefined) {\n return undefined;\n }\n\n const plugin = adapterImport.specifiers.find(\n (specifier) =>\n specifier.type === \"ImportSpecifier\" &&\n specifier.imported.type === \"Identifier\" &&\n specifier.imported.name === \"spotPatch\" &&\n specifier.importKind !== \"type\",\n );\n\n if (plugin === undefined) {\n throw new Error(\n \"SpotPatch init cannot safely merge the existing @spotpatch/vite import.\",\n );\n }\n\n return plugin.local.name;\n}\n\nfunction unwrapExpression(expression: Expression): Expression {\n let current = expression;\n\n while (\n current.type === \"ParenthesizedExpression\" ||\n current.type === \"TSAsExpression\" ||\n current.type === \"TSSatisfiesExpression\" ||\n current.type === \"TSTypeAssertion\" ||\n current.type === \"TSNonNullExpression\"\n ) {\n current = current.expression;\n }\n\n return current;\n}\n\nfunction findDefaultExport(program: Program): ExportDefaultDeclaration {\n const exports = program.body.filter(\n (statement): statement is ExportDefaultDeclaration =>\n statement.type === \"ExportDefaultDeclaration\",\n );\n\n if (exports.length !== 1 || exports[0] === undefined) {\n throw new Error(\n \"SpotPatch init requires exactly one ESM default export in vite.config.\",\n );\n }\n\n return exports[0];\n}\n\nfunction findVariableInitializer(\n program: Program,\n name: string,\n): Expression | undefined {\n for (const statement of program.body) {\n if (statement.type !== \"VariableDeclaration\") {\n continue;\n }\n\n for (const declaration of statement.declarations) {\n if (\n declaration.id.type === \"Identifier\" &&\n declaration.id.name === name &&\n declaration.init !== null\n ) {\n return declaration.init;\n }\n }\n }\n\n return undefined;\n}\n\nfunction resolveConfigExpression(program: Program): Expression {\n const exported = findDefaultExport(program).declaration;\n\n if (\n exported.type === \"FunctionDeclaration\" ||\n exported.type === \"ClassDeclaration\" ||\n exported.type === \"TSInterfaceDeclaration\"\n ) {\n throw new Error(\n \"SpotPatch init requires vite.config to export a configuration expression.\",\n );\n }\n\n const expression = unwrapExpression(exported);\n const resolved =\n expression.type === \"Identifier\"\n ? findVariableInitializer(program, expression.name)\n : expression;\n\n if (resolved === undefined) {\n throw new Error(\"SpotPatch init could not resolve the vite.config export.\");\n }\n\n return unwrapExpression(resolved);\n}\n\nfunction resolveConfigObject(program: Program): ObjectExpression {\n const expression = resolveConfigExpression(program);\n\n if (expression.type === \"ObjectExpression\") {\n return expression;\n }\n\n if (expression.type === \"CallExpression\") {\n const callee = unwrapExpression(expression.callee);\n const argument = expression.arguments[0];\n\n if (\n callee.type === \"Identifier\" &&\n callee.name === \"defineConfig\" &&\n expression.arguments.length === 1 &&\n argument !== undefined &&\n argument.type !== \"SpreadElement\"\n ) {\n const value = unwrapExpression(argument);\n\n if (value.type === \"ObjectExpression\") {\n return value;\n }\n }\n }\n\n throw new Error(\n \"SpotPatch init currently supports an object passed to defineConfig in vite.config.\",\n );\n}\n\nfunction propertyName(property: ObjectProperty): string | undefined {\n if (property.computed) {\n return undefined;\n }\n\n if (property.key.type === \"Identifier\") {\n return property.key.name;\n }\n\n if (property.key.type === \"Literal\" && typeof property.key.value === \"string\") {\n return property.key.value;\n }\n\n return undefined;\n}\n\nfunction findProperty(\n object: ObjectExpression,\n name: string,\n): ObjectProperty | undefined {\n const matches = object.properties.filter(\n (property): property is ObjectProperty =>\n property.type === \"Property\" && propertyName(property) === name,\n );\n\n if (matches.length > 1) {\n throw new Error(`SpotPatch init found duplicate ${name} properties.`);\n }\n\n return matches[0];\n}\n\nfunction lineIndentAt(source: string, offset: number): string {\n const lineStart = source.lastIndexOf(\"\\n\", Math.max(0, offset - 1)) + 1;\n return /^[\\t ]*/u.exec(source.slice(lineStart, offset))?.[0] ?? \"\";\n}\n\nfunction childIndent(source: string, object: ObjectExpression): string {\n const first = object.properties[0];\n\n if (first !== undefined) {\n return lineIndentAt(source, first.start);\n }\n\n return `${lineIndentAt(source, object.start)} `;\n}\n\nfunction trustedFastCall(pluginName: string, enabled: boolean): string {\n return enabled ? `${pluginName}({ trustedFastMode: true })` : `${pluginName}()`;\n}\n\nfunction directPluginCalls(\n plugins: ArrayExpression,\n pluginName: string,\n): readonly CallExpression[] {\n return plugins.elements.filter((element): element is CallExpression => {\n if (element?.type !== \"CallExpression\") {\n return false;\n }\n\n const callee = unwrapExpression(element.callee);\n return callee.type === \"Identifier\" && callee.name === pluginName;\n });\n}\n\nfunction enableTrustedFastMode(\n magicString: MagicString,\n source: string,\n call: CallExpression,\n): void {\n if (call.arguments.length === 0) {\n magicString.overwrite(\n call.start,\n call.end,\n `${source.slice(call.start, call.end - 1)}{ trustedFastMode: true })`,\n );\n return;\n }\n\n const argument = call.arguments[0];\n\n if (\n call.arguments.length !== 1 ||\n argument === undefined ||\n argument.type === \"SpreadElement\"\n ) {\n throw new Error(\"SpotPatch init cannot safely update the spotPatch options.\");\n }\n\n const value = unwrapExpression(argument);\n\n if (value.type !== \"ObjectExpression\") {\n throw new Error(\"SpotPatch init requires spotPatch options to be an object.\");\n }\n\n const property = findProperty(value, \"trustedFastMode\");\n\n if (property !== undefined) {\n const propertyValue = unwrapExpression(property.value);\n\n if (propertyValue.type !== \"Literal\" || typeof propertyValue.value !== \"boolean\") {\n throw new Error(\n \"SpotPatch init requires trustedFastMode to be a boolean literal.\",\n );\n }\n\n if (!propertyValue.value) {\n magicString.overwrite(propertyValue.start, propertyValue.end, \"true\");\n }\n\n return;\n }\n\n const indent = childIndent(source, value);\n\n if (value.properties.length === 0) {\n magicString.appendLeft(value.end - 1, \" trustedFastMode: true \");\n } else {\n magicString.appendLeft(\n value.properties[0]?.start ?? value.end - 1,\n `trustedFastMode: true,\\n${indent}`,\n );\n }\n}\n\nfunction addPluginCall(\n magicString: MagicString,\n source: string,\n config: ObjectExpression,\n pluginName: string,\n trustedFastModeAvailable: boolean,\n): void {\n const pluginsProperty = findProperty(config, \"plugins\");\n const call = trustedFastCall(pluginName, trustedFastModeAvailable);\n\n if (pluginsProperty === undefined) {\n const indent = childIndent(source, config);\n\n if (config.properties.length === 0) {\n magicString.appendLeft(config.end - 1, `\\n${indent}plugins: [${call}],\\n`);\n } else {\n magicString.appendLeft(\n config.properties[0]?.start ?? config.end - 1,\n `plugins: [${call}],\\n${indent}`,\n );\n }\n\n return;\n }\n\n const value = unwrapExpression(pluginsProperty.value);\n\n if (value.type !== \"ArrayExpression\") {\n throw new Error(\"SpotPatch init requires vite.config plugins to be an array.\");\n }\n\n const existing = directPluginCalls(value, pluginName);\n\n if (existing.length > 1) {\n throw new Error(\"SpotPatch init found duplicate spotPatch plugins.\");\n }\n\n if (existing[0] !== undefined) {\n if (trustedFastModeAvailable) {\n enableTrustedFastMode(magicString, source, existing[0]);\n }\n\n return;\n }\n\n const first = value.elements.find((element) => element !== null);\n\n if (first === undefined) {\n magicString.appendLeft(value.end - 1, call);\n } else {\n magicString.appendLeft(\n first.start,\n `${call},\\n${lineIndentAt(source, first.start)}`,\n );\n }\n}\n\nfunction transformViteConfig(\n absolutePath: string,\n source: string,\n trustedFastModeAvailable: boolean,\n): string {\n const { program } = parseModule(absolutePath, source);\n const config = resolveConfigObject(program);\n const existingPluginName = importedPluginName(program);\n const pluginName = existingPluginName ?? choosePluginName(program);\n const magicString = new MagicString(source);\n\n if (existingPluginName === undefined) {\n const specifier =\n pluginName === \"spotPatch\" ? \"spotPatch\" : `spotPatch as ${pluginName}`;\n insertStaticImport(\n magicString,\n program,\n `import { ${specifier} } from ${JSON.stringify(ADAPTER_PACKAGE_NAME)};`,\n );\n }\n\n addPluginCall(magicString, source, config, pluginName, trustedFastModeAvailable);\n return magicString.toString();\n}\n\nasync function findViteConfig(appRoot: string): Promise<string> {\n const candidates = (\n await Promise.all(\n CONFIG_FILE_NAMES.map(async (name) => {\n const absolutePath = path.join(appRoot, name);\n return (await integrationPathExists(absolutePath)) ? absolutePath : undefined;\n }),\n )\n ).filter((value): value is string => value !== undefined);\n\n if (candidates.length !== 1 || candidates[0] === undefined) {\n throw new Error(\"SpotPatch init requires exactly one supported vite.config file.\");\n }\n\n return candidates[0];\n}\n\nexport async function planViteIntegration(\n directory = process.cwd(),\n): Promise<ViteIntegrationPlan> {\n const appRoot = path.resolve(directory);\n const configPath = await findViteConfig(appRoot);\n const [configSource, discoveredCheck] = await Promise.all([\n readIntegrationFile(configPath),\n discoverProjectValidationCheck({\n appRoot,\n timeoutMs: DEFAULT_AGENT_LIMITS.checkTimeoutMs,\n }),\n ]);\n const trustedFastModeAvailable = discoveredCheck !== undefined;\n const nextContent = transformViteConfig(\n configPath,\n configSource,\n trustedFastModeAvailable,\n );\n const change = createIntegrationFileChange(\n appRoot,\n configPath,\n nextContent,\n configSource,\n );\n\n return Object.freeze({\n appRoot,\n changes: Object.freeze(change === undefined ? [] : [change]),\n trustedFastModeAvailable,\n });\n}\n\nexport async function applyViteIntegrationPlan(\n plan: ViteIntegrationPlan,\n): Promise<void> {\n await applyIntegrationPlan(plan);\n}\n\nexport async function checkViteIntegration(\n directory = process.cwd(),\n): Promise<ViteIntegrationCheck> {\n try {\n const plan = await planViteIntegration(directory);\n const issues = plan.changes.map(\n (change) => `INTEGRATION_REQUIRED:${change.relativePath}`,\n );\n return Object.freeze({\n appRoot: plan.appRoot,\n issues: Object.freeze(issues),\n ok: issues.length === 0,\n trustedFastModeAvailable: plan.trustedFastModeAvailable,\n });\n } catch (error: unknown) {\n return Object.freeze({\n appRoot: path.resolve(directory),\n issues: Object.freeze([\n error instanceof Error ? error.message : \"SpotPatch integration check failed.\",\n ]),\n ok: false,\n trustedFastModeAvailable: false,\n });\n }\n}\n"],"mappings":";;;AAAA,SAAS,gBAAgB;AACzB,SAAS,qBAAqB;AAC9B,OAAOA,WAAU;;;ACFjB,OAAO,UAAU;AAEjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,4BAA4B;AACrC,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,OASK;AAEP,IAAM,uBAAuB;AAC7B,IAAM,oBAAoB,OAAO,OAAO;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAU;AAoBV,SAAS,sBAAsB,OAAyB;AACtD,SAAO,UAAU;AACnB;AAEA,SAAS,YAAY,cAAsB,QAA8B;AACvE,QAAM,SAAS,UAAU,cAAc,QAAQ;AAAA,IAC7C,YAAY;AAAA,IACZ,oBAAoB;AAAA,EACtB,CAAC;AACD,QAAM,QAAQ,OAAO,OAAO,KAAK,CAAC,UAAU,sBAAsB,MAAM,QAAQ,CAAC;AAEjF,MAAI,UAAU,QAAW;AACvB,UAAM,IAAI;AAAA,MACR,oCAAoC,KAAK,SAAS,YAAY,CAAC,KAAK,MAAM,OAAO;AAAA,IACnF;AAAA,EACF;AAEA,SAAO,OAAO,OAAO,EAAE,SAAS,OAAO,SAAS,OAAO,CAAC;AAC1D;AAEA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WAAW,MAAM,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC;AACrD,SAAS,OAAgB;AACvB,UAAQ,OAAO;AAAA,IACb,oBACE,iBAAiB,QAAQ,MAAM,UAAU,qBAC3C;AAAA;AAAA,EACF;AACA,UAAQ,WAAW;AACrB;","names":["path","path"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/initializer.ts","../src/setup.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\n\nimport {\n applyViteIntegrationPlan,\n checkViteIntegration,\n planViteIntegration,\n} from \"./initializer.js\";\nimport { detectPackageManager, installLatestAdapter } from \"./setup.js\";\n\nconst VERSION_PATTERN = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-[0-9A-Za-z.-]+)?$/u;\n\nfunction writeUsage(): void {\n process.stderr.write(\n \"Usage: spotpatch-vite <setup|init|check>\\n\" +\n \" setup Install or upgrade @spotpatch/vite@latest, then initialize it.\\n\" +\n \" init Preview and apply safe Vite integration changes.\\n\" +\n \" check Verify the Vite integration without writing files.\\n\",\n );\n}\n\nasync function inspectViteProject(appRoot = process.cwd()): Promise<string> {\n const resolveFromApplication = createRequire(path.join(appRoot, \"package.json\"));\n let adapterEntry: string;\n let viteManifestPath: string;\n\n try {\n adapterEntry = resolveFromApplication.resolve(\"@spotpatch/vite\");\n viteManifestPath = resolveFromApplication.resolve(\"vite/package.json\");\n } catch (error: unknown) {\n throw new Error(\n \"SpotPatch could not resolve the local @spotpatch/vite and Vite packages.\",\n { cause: error },\n );\n }\n\n if (adapterEntry.length === 0) {\n throw new Error(\"SpotPatch could not resolve the Vite adapter export.\");\n }\n\n const manifest = JSON.parse(await readFile(viteManifestPath, \"utf8\")) as unknown;\n const version =\n typeof manifest === \"object\" &&\n manifest !== null &&\n \"version\" in manifest &&\n typeof manifest.version === \"string\"\n ? manifest.version\n : undefined;\n const match = version === undefined ? null : VERSION_PATTERN.exec(version);\n const major = Number(match?.[1]);\n\n if (\n version === undefined ||\n match === null ||\n !Number.isSafeInteger(major) ||\n major < 5 ||\n major >= 8\n ) {\n throw new Error(\n `SpotPatch Vite requires Vite >=5.0.0 <8.0.0; found ${version ?? \"unknown\"}.`,\n );\n }\n\n return version;\n}\n\nfunction writeTrustedModeStatus(available: boolean): void {\n process.stdout.write(\n available\n ? \"[spotpatch:vite] trusted fast mode is available in the page selector.\\n\"\n : \"[spotpatch:vite] review mode is ready; trusted fast mode needs a local TypeScript project check.\\n\",\n );\n}\n\nasync function runInit(arguments_: readonly string[]): Promise<number> {\n if (arguments_.length !== 0) {\n throw new Error(\"SpotPatch init does not accept positional arguments.\");\n }\n\n await inspectViteProject();\n const plan = await planViteIntegration();\n\n if (plan.changes.length === 0) {\n process.stdout.write(\"[spotpatch:vite] integration is already up to date.\\n\");\n writeTrustedModeStatus(plan.trustedFastModeAvailable);\n return 0;\n }\n\n process.stdout.write(\"[spotpatch:vite] integration preview (resulting files):\\n\");\n\n for (const change of plan.changes) {\n process.stdout.write(`\\n--- ${change.relativePath}\\n${change.nextContent}`);\n\n if (!change.nextContent.endsWith(\"\\n\")) {\n process.stdout.write(\"\\n\");\n }\n }\n\n await applyViteIntegrationPlan(plan);\n process.stdout.write(\n `[spotpatch:vite] updated ${String(plan.changes.length)} integration file(s).\\n`,\n );\n writeTrustedModeStatus(plan.trustedFastModeAvailable);\n\n return 0;\n}\n\nasync function runSetup(arguments_: readonly string[]): Promise<number> {\n if (arguments_.length !== 0) {\n throw new Error(\"SpotPatch setup does not accept positional arguments.\");\n }\n\n const packageManager = await detectPackageManager();\n await installLatestAdapter(packageManager);\n return runInit([]);\n}\n\nasync function runCheck(arguments_: readonly string[]): Promise<number> {\n if (arguments_.length !== 0) {\n throw new Error(\"SpotPatch check does not accept positional arguments.\");\n }\n\n const version = await inspectViteProject();\n const result = await checkViteIntegration();\n\n if (!result.ok) {\n for (const issue of result.issues) {\n process.stderr.write(`[spotpatch:vite] ${issue}\\n`);\n }\n\n return 1;\n }\n\n const mode = result.trustedFastModeAvailable\n ? \"trusted fast mode available\"\n : \"review mode\";\n process.stdout.write(\n `[spotpatch:vite] integration verified for Vite ${version} · ${mode}.\\n`,\n );\n return 0;\n}\n\nasync function main(arguments_: readonly string[]): Promise<number> {\n const [command, ...rest] = arguments_;\n\n if (command === \"setup\") {\n return runSetup(rest);\n }\n\n if (command === \"init\") {\n return runInit(rest);\n }\n\n if (command === \"check\") {\n return runCheck(rest);\n }\n\n writeUsage();\n return 1;\n}\n\ntry {\n process.exitCode = await main(process.argv.slice(2));\n} catch (error: unknown) {\n process.stderr.write(\n `[spotpatch:vite] ${\n error instanceof Error ? error.message : \"The command failed.\"\n }\\n`,\n );\n process.exitCode = 1;\n}\n","import path from \"node:path\";\n\nimport {\n applyIntegrationPlan,\n createIntegrationFileChange,\n discoverProjectValidationCheck,\n integrationPathExists,\n readIntegrationFile,\n type IntegrationFileChange,\n} from \"@spotpatch/dev-server\";\nimport { DEFAULT_AGENT_LIMITS } from \"@spotpatch/shared\";\nimport { MagicString } from \"magic-string\";\nimport {\n parseSync,\n Visitor,\n type ArrayExpression,\n type CallExpression,\n type ExportDefaultDeclaration,\n type Expression,\n type ImportDeclaration,\n type ObjectExpression,\n type ObjectProperty,\n type Program,\n type ReturnStatement,\n} from \"oxc-parser\";\n\nconst ADAPTER_PACKAGE_NAME = \"@spotpatch/vite\";\nconst CONFIG_FILE_NAMES = Object.freeze([\n \"vite.config.ts\",\n \"vite.config.mts\",\n \"vite.config.js\",\n \"vite.config.mjs\",\n] as const);\n\nexport interface ViteIntegrationPlan {\n readonly appRoot: string;\n readonly changes: readonly IntegrationFileChange[];\n readonly trustedFastModeAvailable: boolean;\n}\n\nexport interface ViteIntegrationCheck {\n readonly appRoot: string;\n readonly issues: readonly string[];\n readonly ok: boolean;\n readonly trustedFastModeAvailable: boolean;\n}\n\ninterface ParsedModule {\n readonly program: Program;\n readonly source: string;\n}\n\nfunction isParserErrorSeverity(value: unknown): boolean {\n return value === \"Error\";\n}\n\nfunction parseModule(absolutePath: string, source: string): ParsedModule {\n const result = parseSync(absolutePath, source, {\n sourceType: \"module\",\n showSemanticErrors: true,\n });\n const error = result.errors.find((entry) => isParserErrorSeverity(entry.severity));\n\n if (error !== undefined) {\n throw new SyntaxError(\n `SpotPatch could not safely parse ${path.basename(absolutePath)} (${error.message}).`,\n );\n }\n\n return Object.freeze({ program: result.program, source });\n}\n\nfunction importsOf(program: Program): readonly ImportDeclaration[] {\n return program.body.filter(\n (statement): statement is ImportDeclaration =>\n statement.type === \"ImportDeclaration\",\n );\n}\n\nfunction importInsertionOffset(program: Program): number {\n const lastImport = importsOf(program).at(-1);\n\n if (lastImport !== undefined) {\n return lastImport.end;\n }\n\n const directives = program.body.filter(\n (statement) =>\n statement.type === \"ExpressionStatement\" &&\n typeof statement.directive === \"string\",\n );\n return directives.at(-1)?.end ?? program.hashbang?.end ?? 0;\n}\n\nfunction insertStaticImport(\n magicString: MagicString,\n program: Program,\n statement: string,\n): void {\n const offset = importInsertionOffset(program);\n\n if (offset === 0) {\n magicString.prepend(`${statement}\\n`);\n return;\n }\n\n magicString.appendRight(offset, `\\n${statement}`);\n}\n\nfunction collectIdentifierNames(program: Program): ReadonlySet<string> {\n const names = new Set<string>();\n new Visitor({\n Identifier(node) {\n names.add(node.name);\n },\n }).visit(program);\n return names;\n}\n\nfunction choosePluginName(program: Program): string {\n const names = collectIdentifierNames(program);\n let suffix = 0;\n let candidate = \"spotPatch\";\n\n while (names.has(candidate)) {\n suffix += 1;\n candidate = `spotPatch${String(suffix)}`;\n }\n\n return candidate;\n}\n\nfunction importedPluginName(program: Program): string | undefined {\n const adapterImports = importsOf(program).filter(\n (statement) => statement.source.value === ADAPTER_PACKAGE_NAME,\n );\n\n if (adapterImports.length > 1) {\n throw new Error(\"SpotPatch init found duplicate @spotpatch/vite imports.\");\n }\n\n const adapterImport = adapterImports[0];\n\n if (adapterImport === undefined) {\n return undefined;\n }\n\n const plugin = adapterImport.specifiers.find(\n (specifier) =>\n specifier.type === \"ImportSpecifier\" &&\n specifier.imported.type === \"Identifier\" &&\n specifier.imported.name === \"spotPatch\" &&\n specifier.importKind !== \"type\",\n );\n\n if (plugin === undefined) {\n throw new Error(\n \"SpotPatch init cannot safely merge the existing @spotpatch/vite import.\",\n );\n }\n\n return plugin.local.name;\n}\n\nfunction unwrapExpression(expression: Expression): Expression {\n let current = expression;\n\n while (\n current.type === \"ParenthesizedExpression\" ||\n current.type === \"TSAsExpression\" ||\n current.type === \"TSSatisfiesExpression\" ||\n current.type === \"TSTypeAssertion\" ||\n current.type === \"TSNonNullExpression\"\n ) {\n current = current.expression;\n }\n\n return current;\n}\n\nfunction findDefaultExport(program: Program): ExportDefaultDeclaration {\n const exports = program.body.filter(\n (statement): statement is ExportDefaultDeclaration =>\n statement.type === \"ExportDefaultDeclaration\",\n );\n\n if (exports.length !== 1 || exports[0] === undefined) {\n throw new Error(\n \"SpotPatch init requires exactly one ESM default export in vite.config.\",\n );\n }\n\n return exports[0];\n}\n\nfunction findVariableInitializer(\n program: Program,\n name: string,\n): Expression | undefined {\n for (const statement of program.body) {\n if (statement.type !== \"VariableDeclaration\") {\n continue;\n }\n\n for (const declaration of statement.declarations) {\n if (\n declaration.id.type === \"Identifier\" &&\n declaration.id.name === name &&\n declaration.init !== null\n ) {\n return declaration.init;\n }\n }\n }\n\n return undefined;\n}\n\nfunction resolveConfigExpression(program: Program): Expression {\n const exported = findDefaultExport(program).declaration;\n\n if (\n exported.type === \"FunctionDeclaration\" ||\n exported.type === \"ClassDeclaration\" ||\n exported.type === \"TSInterfaceDeclaration\"\n ) {\n throw new Error(\n \"SpotPatch init requires vite.config to export a configuration expression.\",\n );\n }\n\n const expression = unwrapExpression(exported);\n const resolved =\n expression.type === \"Identifier\"\n ? findVariableInitializer(program, expression.name)\n : expression;\n\n if (resolved === undefined) {\n throw new Error(\"SpotPatch init could not resolve the vite.config export.\");\n }\n\n return unwrapExpression(resolved);\n}\n\nfunction resolveFactoryConfigObject(\n expression: Expression,\n): ObjectExpression | undefined {\n const factory = unwrapExpression(expression);\n\n if (\n factory.type !== \"ArrowFunctionExpression\" &&\n factory.type !== \"FunctionExpression\"\n ) {\n return undefined;\n }\n\n if (factory.body === null) {\n throw new Error(\n \"SpotPatch init cannot use a defineConfig callback without a body.\",\n );\n }\n\n if (factory.body.type !== \"BlockStatement\") {\n const returned = unwrapExpression(factory.body);\n return returned.type === \"ObjectExpression\" ? returned : undefined;\n }\n\n const returns: ReturnStatement[] = [];\n new Visitor({\n ReturnStatement(statement) {\n returns.push(statement);\n },\n }).visit({\n type: \"Program\",\n body: factory.body.body,\n sourceType: \"module\",\n hashbang: null,\n start: factory.body.start,\n end: factory.body.end,\n });\n\n const onlyReturn = returns.length === 1 ? returns[0] : undefined;\n\n if (onlyReturn?.argument == null) {\n throw new Error(\n \"SpotPatch init requires a defineConfig callback with exactly one top-level object return.\",\n );\n }\n\n const returned = unwrapExpression(onlyReturn.argument);\n\n if (returned.type !== \"ObjectExpression\") {\n throw new Error(\n \"SpotPatch init requires the defineConfig callback to return a configuration object directly.\",\n );\n }\n\n return returned;\n}\n\nfunction resolveConfigObject(program: Program): ObjectExpression {\n const expression = resolveConfigExpression(program);\n\n if (expression.type === \"ObjectExpression\") {\n return expression;\n }\n\n if (expression.type === \"CallExpression\") {\n const callee = unwrapExpression(expression.callee);\n const argument = expression.arguments[0];\n\n if (\n callee.type === \"Identifier\" &&\n callee.name === \"defineConfig\" &&\n expression.arguments.length === 1 &&\n argument !== undefined &&\n argument.type !== \"SpreadElement\"\n ) {\n const value = unwrapExpression(argument);\n\n if (value.type === \"ObjectExpression\") {\n return value;\n }\n\n const callbackObject = resolveFactoryConfigObject(value);\n\n if (callbackObject !== undefined) {\n return callbackObject;\n }\n }\n }\n\n throw new Error(\n \"SpotPatch init supports a configuration object or an object-returning callback passed to defineConfig.\",\n );\n}\n\nfunction propertyName(property: ObjectProperty): string | undefined {\n if (property.computed) {\n return undefined;\n }\n\n if (property.key.type === \"Identifier\") {\n return property.key.name;\n }\n\n if (property.key.type === \"Literal\" && typeof property.key.value === \"string\") {\n return property.key.value;\n }\n\n return undefined;\n}\n\nfunction findProperty(\n object: ObjectExpression,\n name: string,\n): ObjectProperty | undefined {\n const matches = object.properties.filter(\n (property): property is ObjectProperty =>\n property.type === \"Property\" && propertyName(property) === name,\n );\n\n if (matches.length > 1) {\n throw new Error(`SpotPatch init found duplicate ${name} properties.`);\n }\n\n return matches[0];\n}\n\nfunction lineIndentAt(source: string, offset: number): string {\n const lineStart = source.lastIndexOf(\"\\n\", Math.max(0, offset - 1)) + 1;\n return /^[\\t ]*/u.exec(source.slice(lineStart, offset))?.[0] ?? \"\";\n}\n\nfunction childIndent(source: string, object: ObjectExpression): string {\n const first = object.properties[0];\n\n if (first !== undefined) {\n return lineIndentAt(source, first.start);\n }\n\n return `${lineIndentAt(source, object.start)} `;\n}\n\nfunction trustedFastCall(pluginName: string, enabled: boolean): string {\n return enabled ? `${pluginName}({ trustedFastMode: true })` : `${pluginName}()`;\n}\n\nfunction directPluginCalls(\n plugins: ArrayExpression,\n pluginName: string,\n): readonly CallExpression[] {\n return plugins.elements.filter((element): element is CallExpression => {\n if (element?.type !== \"CallExpression\") {\n return false;\n }\n\n const callee = unwrapExpression(element.callee);\n return callee.type === \"Identifier\" && callee.name === pluginName;\n });\n}\n\nfunction enableTrustedFastMode(\n magicString: MagicString,\n source: string,\n call: CallExpression,\n): void {\n if (call.arguments.length === 0) {\n magicString.overwrite(\n call.start,\n call.end,\n `${source.slice(call.start, call.end - 1)}{ trustedFastMode: true })`,\n );\n return;\n }\n\n const argument = call.arguments[0];\n\n if (\n call.arguments.length !== 1 ||\n argument === undefined ||\n argument.type === \"SpreadElement\"\n ) {\n throw new Error(\"SpotPatch init cannot safely update the spotPatch options.\");\n }\n\n const value = unwrapExpression(argument);\n\n if (value.type !== \"ObjectExpression\") {\n throw new Error(\"SpotPatch init requires spotPatch options to be an object.\");\n }\n\n const property = findProperty(value, \"trustedFastMode\");\n\n if (property !== undefined) {\n const propertyValue = unwrapExpression(property.value);\n\n if (propertyValue.type !== \"Literal\" || typeof propertyValue.value !== \"boolean\") {\n throw new Error(\n \"SpotPatch init requires trustedFastMode to be a boolean literal.\",\n );\n }\n\n if (!propertyValue.value) {\n magicString.overwrite(propertyValue.start, propertyValue.end, \"true\");\n }\n\n return;\n }\n\n const indent = childIndent(source, value);\n\n if (value.properties.length === 0) {\n magicString.appendLeft(value.end - 1, \" trustedFastMode: true \");\n } else {\n magicString.appendLeft(\n value.properties[0]?.start ?? value.end - 1,\n `trustedFastMode: true,\\n${indent}`,\n );\n }\n}\n\nfunction addPluginCall(\n magicString: MagicString,\n source: string,\n config: ObjectExpression,\n pluginName: string,\n trustedFastModeAvailable: boolean,\n): void {\n const pluginsProperty = findProperty(config, \"plugins\");\n const call = trustedFastCall(pluginName, trustedFastModeAvailable);\n\n if (pluginsProperty === undefined) {\n const indent = childIndent(source, config);\n\n if (config.properties.length === 0) {\n magicString.appendLeft(config.end - 1, `\\n${indent}plugins: [${call}],\\n`);\n } else {\n magicString.appendLeft(\n config.properties[0]?.start ?? config.end - 1,\n `plugins: [${call}],\\n${indent}`,\n );\n }\n\n return;\n }\n\n const value = unwrapExpression(pluginsProperty.value);\n\n if (value.type !== \"ArrayExpression\") {\n throw new Error(\"SpotPatch init requires vite.config plugins to be an array.\");\n }\n\n const existing = directPluginCalls(value, pluginName);\n\n if (existing.length > 1) {\n throw new Error(\"SpotPatch init found duplicate spotPatch plugins.\");\n }\n\n if (existing[0] !== undefined) {\n if (trustedFastModeAvailable) {\n enableTrustedFastMode(magicString, source, existing[0]);\n }\n\n return;\n }\n\n const first = value.elements.find((element) => element !== null);\n\n if (first === undefined) {\n magicString.appendLeft(value.end - 1, call);\n } else {\n magicString.appendLeft(\n first.start,\n `${call},\\n${lineIndentAt(source, first.start)}`,\n );\n }\n}\n\nfunction transformViteConfig(\n absolutePath: string,\n source: string,\n trustedFastModeAvailable: boolean,\n): string {\n const { program } = parseModule(absolutePath, source);\n const config = resolveConfigObject(program);\n const existingPluginName = importedPluginName(program);\n const pluginName = existingPluginName ?? choosePluginName(program);\n const magicString = new MagicString(source);\n\n if (existingPluginName === undefined) {\n const specifier =\n pluginName === \"spotPatch\" ? \"spotPatch\" : `spotPatch as ${pluginName}`;\n insertStaticImport(\n magicString,\n program,\n `import { ${specifier} } from ${JSON.stringify(ADAPTER_PACKAGE_NAME)};`,\n );\n }\n\n addPluginCall(magicString, source, config, pluginName, trustedFastModeAvailable);\n return magicString.toString();\n}\n\nasync function findViteConfig(appRoot: string): Promise<string> {\n const candidates = (\n await Promise.all(\n CONFIG_FILE_NAMES.map(async (name) => {\n const absolutePath = path.join(appRoot, name);\n return (await integrationPathExists(absolutePath)) ? absolutePath : undefined;\n }),\n )\n ).filter((value): value is string => value !== undefined);\n\n if (candidates.length !== 1 || candidates[0] === undefined) {\n throw new Error(\"SpotPatch init requires exactly one supported vite.config file.\");\n }\n\n return candidates[0];\n}\n\nexport async function planViteIntegration(\n directory = process.cwd(),\n): Promise<ViteIntegrationPlan> {\n const appRoot = path.resolve(directory);\n const configPath = await findViteConfig(appRoot);\n const [configSource, discoveredCheck] = await Promise.all([\n readIntegrationFile(configPath),\n discoverProjectValidationCheck({\n appRoot,\n timeoutMs: DEFAULT_AGENT_LIMITS.checkTimeoutMs,\n }),\n ]);\n const trustedFastModeAvailable = discoveredCheck !== undefined;\n const nextContent = transformViteConfig(\n configPath,\n configSource,\n trustedFastModeAvailable,\n );\n const change = createIntegrationFileChange(\n appRoot,\n configPath,\n nextContent,\n configSource,\n );\n\n return Object.freeze({\n appRoot,\n changes: Object.freeze(change === undefined ? [] : [change]),\n trustedFastModeAvailable,\n });\n}\n\nexport async function applyViteIntegrationPlan(\n plan: ViteIntegrationPlan,\n): Promise<void> {\n await applyIntegrationPlan(plan);\n}\n\nexport async function checkViteIntegration(\n directory = process.cwd(),\n): Promise<ViteIntegrationCheck> {\n try {\n const plan = await planViteIntegration(directory);\n const issues = plan.changes.map(\n (change) => `INTEGRATION_REQUIRED:${change.relativePath}`,\n );\n return Object.freeze({\n appRoot: plan.appRoot,\n issues: Object.freeze(issues),\n ok: issues.length === 0,\n trustedFastModeAvailable: plan.trustedFastModeAvailable,\n });\n } catch (error: unknown) {\n return Object.freeze({\n appRoot: path.resolve(directory),\n issues: Object.freeze([\n error instanceof Error ? error.message : \"SpotPatch integration check failed.\",\n ]),\n ok: false,\n trustedFastModeAvailable: false,\n });\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { access, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport type SupportedPackageManager = \"npm\" | \"pnpm\";\n\ninterface ApplicationManifest {\n readonly packageManager?: unknown;\n}\n\nexport interface InstallCommand {\n readonly arguments: readonly string[];\n readonly executable: string;\n}\n\nasync function pathExists(absolutePath: string): Promise<boolean> {\n try {\n await access(absolutePath);\n return true;\n } catch (error: unknown) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error.code === \"ENOENT\" || error.code === \"ENOTDIR\")\n ) {\n return false;\n }\n\n throw error;\n }\n}\n\nexport async function detectPackageManager(\n appRoot = process.cwd(),\n userAgent = process.env.npm_config_user_agent ?? \"\",\n): Promise<SupportedPackageManager> {\n const manifestPath = path.join(appRoot, \"package.json\");\n const manifest = JSON.parse(\n await readFile(manifestPath, \"utf8\"),\n ) as ApplicationManifest;\n const declared = manifest.packageManager;\n\n if (typeof declared === \"string\") {\n const name = declared.split(\"@\", 1)[0];\n\n if (name === \"pnpm\" || name === \"npm\") {\n return name;\n }\n\n throw new Error(\n `SpotPatch setup supports npm and pnpm projects; package.json declares ${declared}.`,\n );\n }\n\n const [hasPnpmLock, hasNpmLock] = await Promise.all([\n pathExists(path.join(appRoot, \"pnpm-lock.yaml\")),\n pathExists(path.join(appRoot, \"package-lock.json\")),\n ]);\n\n if (hasPnpmLock !== hasNpmLock) {\n return hasPnpmLock ? \"pnpm\" : \"npm\";\n }\n\n if (hasPnpmLock && hasNpmLock) {\n throw new Error(\n \"SpotPatch setup found both pnpm-lock.yaml and package-lock.json; remove the stale lockfile or run installation and init separately.\",\n );\n }\n\n if (userAgent.startsWith(\"pnpm/\")) {\n return \"pnpm\";\n }\n\n if (userAgent.startsWith(\"npm/\")) {\n return \"npm\";\n }\n\n throw new Error(\n \"SpotPatch setup could not determine npm or pnpm; run installation and init separately.\",\n );\n}\n\nexport function createInstallCommand(\n packageManager: SupportedPackageManager,\n platform = process.platform,\n): InstallCommand {\n return Object.freeze({\n executable: platform === \"win32\" ? `${packageManager}.cmd` : packageManager,\n arguments: Object.freeze(\n packageManager === \"pnpm\"\n ? [\"add\", \"-D\", \"@spotpatch/vite@latest\"]\n : [\"install\", \"--save-dev\", \"@spotpatch/vite@latest\"],\n ),\n });\n}\n\nexport async function installLatestAdapter(\n packageManager: SupportedPackageManager,\n appRoot = process.cwd(),\n): Promise<void> {\n const command = createInstallCommand(packageManager);\n\n process.stdout.write(\n `[spotpatch:vite] installing @spotpatch/vite@latest with ${packageManager}...\\n`,\n );\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command.executable, command.arguments, {\n cwd: appRoot,\n env: process.env,\n shell: false,\n stdio: \"inherit\",\n });\n\n child.once(\"error\", reject);\n child.once(\"exit\", (code, signal) => {\n if (code === 0) {\n resolve();\n return;\n }\n\n reject(\n new Error(\n `SpotPatch setup installation failed (${signal ?? `exit ${String(code)}`}).`,\n ),\n );\n });\n });\n}\n"],"mappings":";;;AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,qBAAqB;AAC9B,OAAOC,WAAU;;;ACFjB,OAAO,UAAU;AAEjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,4BAA4B;AACrC,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,OAUK;AAEP,IAAM,uBAAuB;AAC7B,IAAM,oBAAoB,OAAO,OAAO;AAAA,EACtC;AAAA,EACA;AA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,EACrB;AAEA,MAAI,YAAY,SAAS;AACvB,WAAO,SAAS,IAAI;AAAA,EACtB;AAEA,aAAW;AACX,SAAO;AACT;AAEA,IAAI;AACF,UAAQ,WAAW,MAAM,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC;AACrD,SAAS,OAAgB;AACvB,UAAQ,OAAO;AAAA,IACb,oBACE,iBAAiB,QAAQ,MAAM,UAAU,qBAC3C;AAAA;AAAA,EACF;AACA,UAAQ,WAAW;AACrB;","names":["readFile","path","returned","path","path","readFile"]}
package/dist/index.cjs CHANGED
@@ -51,7 +51,7 @@ var import_dev_server = require("@spotpatch/dev-server");
51
51
  // package.json
52
52
  var package_default = {
53
53
  name: "@spotpatch/vite",
54
- version: "1.6.1",
54
+ version: "1.8.0",
55
55
  description: "Vite development plugin for SpotPatch.",
56
56
  license: "MIT",
57
57
  repository: {
@@ -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 resolveProjectOptions,\n} from \"@spotpatch/dev-server\";\nimport { loadEnv, type ConfigEnv, type Plugin, type UserConfig } from \"vite\";\n\nimport type { ViteSpotPatchOptions } from \"./options.js\";\nimport type { SpotPatchPluginContext } from \"./plugin-context.js\";\nimport { createRuntimeInjectionPlugin } from \"./runtime/runtime-injection-plugin.js\";\nimport { createServerPlugin } from \"./server/server-plugin.js\";\nimport { createTransformPlugin } from \"./transform/transform-plugin.js\";\n\nexport function spotPatch(userOptions: ViteSpotPatchOptions = {}): Plugin[] {\n let options = resolveOptions(userOptions);\n let credentialEnvironment: Readonly<Record<string, string | undefined>> =\n Object.freeze({});\n\n if (!options.enabled) {\n return [];\n }\n\n const registry = createSourceRegistry();\n const session = createSession();\n const context = Object.freeze({\n getCredentialEnvironment: () => credentialEnvironment,\n getOptions: () => options,\n } satisfies SpotPatchPluginContext);\n const configure = async (\n config: UserConfig,\n environment: ConfigEnv,\n ): Promise<void> => {\n const root = path.resolve(process.cwd(), config.root ?? \".\");\n const loadedEnvironment =\n config.envDir === false\n ? process.env\n : loadEnv(environment.mode, path.resolve(root, config.envDir ?? \".\"), \"\");\n const environmentAi =\n userOptions.ai === undefined\n ? resolveEnvironmentAiConfiguration(loadedEnvironment).ai\n : false;\n\n options = await resolveProjectOptions({\n appRoot: root,\n environmentAi,\n options: userOptions,\n });\n\n credentialEnvironment = resolveCredentialEnvironment(options, loadedEnvironment);\n };\n\n return [\n createTransformPlugin({ configure, context, registry }),\n createRuntimeInjectionPlugin({ context, session }),\n createServerPlugin({ context, registry, session }),\n ];\n}\n","import { createRequire } from \"node:module\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { 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.6.1\",\n \"description\": \"Vite development plugin for SpotPatch.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/huanglvjing/spotpatch.git\",\n \"directory\": \"packages/vite\"\n },\n \"homepage\": \"https://github.com/huanglvjing/spotpatch#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/huanglvjing/spotpatch/issues\"\n },\n \"keywords\": [\n \"spotpatch\",\n \"vite\",\n \"react\",\n \"developer-tools\",\n \"ai-agent\"\n ],\n \"type\": \"module\",\n \"sideEffects\": false,\n \"engines\": {\n \"node\": \">=20.19.0\"\n },\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"bin\": {\n \"spotpatch-vite\": \"./dist/cli.js\"\n },\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup src/index.ts --format esm,cjs --dts --sourcemap --clean && tsup --config tsup.cli.config.ts && tsup --config tsup.runtime-client.config.ts && tsup --config tsup.runtime-react-adapter.config.ts\",\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 \"magic-string\": \"1.1.0\",\n \"oxc-parser\": \"0.143.0\"\n },\n \"peerDependencies\": {\n \"vite\": \"^5.0.0 || ^6.0.0 || ^7.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n }\n}\n","/**\n * Canonical SpotPatch mark from docs/assets/spotpatch-logo-mark.svg.\n *\n * The Vite development injector consumes this trusted asset separately from\n * the core browser bundle so the Runtime gzip budget remains enforceable.\n */\nexport const BRAND_MARK_CONTENT = `\n <defs>\n <linearGradient id=\"locator-gradient\" x1=\"76\" y1=\"92\" x2=\"436\" y2=\"374\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#B61CFF\" />\n <stop offset=\"0.38\" stop-color=\"#6D35FF\" />\n <stop offset=\"0.72\" stop-color=\"#168EFF\" />\n <stop offset=\"1\" stop-color=\"#00D9E9\" />\n </linearGradient>\n <linearGradient id=\"left-code-gradient\" x1=\"165\" y1=\"166\" x2=\"236\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#A51EFF\" />\n <stop offset=\"1\" stop-color=\"#653BFF\" />\n </linearGradient>\n <linearGradient id=\"right-code-gradient\" x1=\"276\" y1=\"166\" x2=\"347\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#158DFF\" />\n <stop offset=\"1\" stop-color=\"#00D8E9\" />\n </linearGradient>\n <linearGradient id=\"bolt-gradient\" x1=\"270\" y1=\"111\" x2=\"252\" y2=\"365\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#6840FF\" />\n <stop offset=\"0.48\" stop-color=\"#257BFF\" />\n <stop offset=\"1\" stop-color=\"#00CBEF\" />\n </linearGradient>\n </defs>\n <path\n fill=\"url(#locator-gradient)\"\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n d=\"M256 52C345.47 52 418 124.53 418 214C418 267.55 391.98 316.24 354.04 348.02L256 468L157.96 348.02C120.02 316.24 94 267.55 94 214C94 124.53 166.53 52 256 52ZM256 88C186.41 88 130 144.41 130 214C130 258.2 152.76 297.08 187.2 319.57L256 403.8L324.8 319.57C359.24 297.08 382 258.2 382 214C382 144.41 325.59 88 256 88Z\"\n />\n <rect x=\"238\" y=\"20\" width=\"36\" height=\"84\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"62\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"366\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <path\n d=\"M213.5 160L158 211.5L213.5 263L238 236.5L211 211.5L238 186.5L213.5 160Z\"\n fill=\"url(#left-code-gradient)\"\n />\n <path\n d=\"M298.5 160L354 211.5L298.5 263L274 236.5L301 211.5L274 186.5L298.5 160Z\"\n fill=\"url(#right-code-gradient)\"\n />\n <path\n d=\"M283 108L232 212L266 253L238 369L302 237L267 198L283 108Z\"\n fill=\"url(#bolt-gradient)\"\n />\n`;\n","import path from \"node:path\";\n\nimport {\n createAgentJobManager,\n 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?: (\n config: UserConfig,\n environment: ConfigEnv,\n ) => void | Promise<void>;\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n}\n\ninterface ViteTransformOutput {\n readonly code: string;\n readonly map: string;\n}\n\nfunction createCacheKey(id: string, code: string): string {\n const hash = createHash(\"sha256\").update(code).digest(\"base64url\");\n return `${id}\\0${hash}`;\n}\n\nfunction getDisplayPath(root: string, id: string): string {\n const relative = path.relative(root, stripViteQuery(id));\n return relative.split(path.sep).join(\"/\");\n}\n\nexport function createTransformPlugin(input: TransformPluginInput): Plugin {\n let root = process.cwd();\n let filter = createTransformFilter(root, input.context.getOptions());\n let logger: ResolvedConfig[\"logger\"] | undefined;\n const warnedFiles = new Set<string>();\n const cache = new Map<string, ViteTransformOutput | null>();\n\n return {\n name: \"spotpatch:transform\",\n apply: \"serve\",\n enforce: \"pre\",\n\n async config(config, environment) {\n await input.configure?.(config, environment);\n },\n\n configResolved(config) {\n root = path.resolve(config.root);\n filter = createTransformFilter(root, input.context.getOptions());\n logger = config.logger;\n },\n\n transform(code, id) {\n if (!filter.shouldTransform(id, code)) {\n return null;\n }\n\n const cleanId = path.resolve(stripViteQuery(id));\n const cacheKey = createCacheKey(cleanId, code);\n\n if (cache.has(cacheKey)) {\n return cache.get(cacheKey) ?? null;\n }\n\n const startedAt = performance.now();\n const options = input.context.getOptions();\n\n try {\n const result = injectSourceMarkers({\n code,\n absolutePath: cleanId,\n root,\n fileId: input.registry.register(cleanId),\n 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,qBAOO;AACP,IAAAC,eAAsE;;;ACVtE,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,MAAQ;AAAA,EACV;AAAA,EACA,OAAS;AAAA,IACP;AAAA,EACF;AAAA,EACA,MAAQ;AAAA,EACR,QAAU;AAAA,EACV,OAAS;AAAA,EACT,KAAO;AAAA,IACL,kBAAkB;AAAA,EACpB;AAAA,EACA,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,sBAAsB;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IACtD,6BAA6B,EAAE,SAAS,QAAQ,CAAC;AAAA,IACjD,mBAAmB,EAAE,SAAS,UAAU,QAAQ,CAAC;AAAA,EACnD;AACF;;;AO7DA,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 resolveProjectOptions,\n} from \"@spotpatch/dev-server\";\nimport { loadEnv, type ConfigEnv, type Plugin, type UserConfig } from \"vite\";\n\nimport type { ViteSpotPatchOptions } from \"./options.js\";\nimport type { SpotPatchPluginContext } from \"./plugin-context.js\";\nimport { createRuntimeInjectionPlugin } from \"./runtime/runtime-injection-plugin.js\";\nimport { createServerPlugin } from \"./server/server-plugin.js\";\nimport { createTransformPlugin } from \"./transform/transform-plugin.js\";\n\nexport function spotPatch(userOptions: ViteSpotPatchOptions = {}): Plugin[] {\n let options = resolveOptions(userOptions);\n let credentialEnvironment: Readonly<Record<string, string | undefined>> =\n Object.freeze({});\n\n if (!options.enabled) {\n return [];\n }\n\n const registry = createSourceRegistry();\n const session = createSession();\n const context = Object.freeze({\n getCredentialEnvironment: () => credentialEnvironment,\n getOptions: () => options,\n } satisfies SpotPatchPluginContext);\n const configure = async (\n config: UserConfig,\n environment: ConfigEnv,\n ): Promise<void> => {\n const root = path.resolve(process.cwd(), config.root ?? \".\");\n const loadedEnvironment =\n config.envDir === false\n ? process.env\n : loadEnv(environment.mode, path.resolve(root, config.envDir ?? \".\"), \"\");\n const environmentAi =\n userOptions.ai === undefined\n ? resolveEnvironmentAiConfiguration(loadedEnvironment).ai\n : false;\n\n options = await resolveProjectOptions({\n appRoot: root,\n environmentAi,\n options: userOptions,\n });\n\n credentialEnvironment = resolveCredentialEnvironment(options, loadedEnvironment);\n };\n\n return [\n createTransformPlugin({ configure, context, registry }),\n createRuntimeInjectionPlugin({ context, session }),\n createServerPlugin({ context, registry, session }),\n ];\n}\n","import { createRequire } from \"node:module\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { 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.8.0\",\n \"description\": \"Vite development plugin for SpotPatch.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/huanglvjing/spotpatch.git\",\n \"directory\": \"packages/vite\"\n },\n \"homepage\": \"https://github.com/huanglvjing/spotpatch#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/huanglvjing/spotpatch/issues\"\n },\n \"keywords\": [\n \"spotpatch\",\n \"vite\",\n \"react\",\n \"developer-tools\",\n \"ai-agent\"\n ],\n \"type\": \"module\",\n \"sideEffects\": false,\n \"engines\": {\n \"node\": \">=20.19.0\"\n },\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"bin\": {\n \"spotpatch-vite\": \"./dist/cli.js\"\n },\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup src/index.ts --format esm,cjs --dts --sourcemap --clean && tsup --config tsup.cli.config.ts && tsup --config tsup.runtime-client.config.ts && tsup --config tsup.runtime-react-adapter.config.ts\",\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 \"magic-string\": \"1.1.0\",\n \"oxc-parser\": \"0.143.0\"\n },\n \"peerDependencies\": {\n \"vite\": \"^5.0.0 || ^6.0.0 || ^7.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n }\n}\n","/**\n * Canonical SpotPatch mark from docs/assets/spotpatch-logo-mark.svg.\n *\n * The Vite development injector consumes this trusted asset separately from\n * the core browser bundle so the Runtime gzip budget remains enforceable.\n */\nexport const BRAND_MARK_CONTENT = `\n <defs>\n <linearGradient id=\"locator-gradient\" x1=\"76\" y1=\"92\" x2=\"436\" y2=\"374\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#B61CFF\" />\n <stop offset=\"0.38\" stop-color=\"#6D35FF\" />\n <stop offset=\"0.72\" stop-color=\"#168EFF\" />\n <stop offset=\"1\" stop-color=\"#00D9E9\" />\n </linearGradient>\n <linearGradient id=\"left-code-gradient\" x1=\"165\" y1=\"166\" x2=\"236\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#A51EFF\" />\n <stop offset=\"1\" stop-color=\"#653BFF\" />\n </linearGradient>\n <linearGradient id=\"right-code-gradient\" x1=\"276\" y1=\"166\" x2=\"347\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#158DFF\" />\n <stop offset=\"1\" stop-color=\"#00D8E9\" />\n </linearGradient>\n <linearGradient id=\"bolt-gradient\" x1=\"270\" y1=\"111\" x2=\"252\" y2=\"365\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#6840FF\" />\n <stop offset=\"0.48\" stop-color=\"#257BFF\" />\n <stop offset=\"1\" stop-color=\"#00CBEF\" />\n </linearGradient>\n </defs>\n <path\n fill=\"url(#locator-gradient)\"\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n d=\"M256 52C345.47 52 418 124.53 418 214C418 267.55 391.98 316.24 354.04 348.02L256 468L157.96 348.02C120.02 316.24 94 267.55 94 214C94 124.53 166.53 52 256 52ZM256 88C186.41 88 130 144.41 130 214C130 258.2 152.76 297.08 187.2 319.57L256 403.8L324.8 319.57C359.24 297.08 382 258.2 382 214C382 144.41 325.59 88 256 88Z\"\n />\n <rect x=\"238\" y=\"20\" width=\"36\" height=\"84\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"62\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"366\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <path\n d=\"M213.5 160L158 211.5L213.5 263L238 236.5L211 211.5L238 186.5L213.5 160Z\"\n fill=\"url(#left-code-gradient)\"\n />\n <path\n d=\"M298.5 160L354 211.5L298.5 263L274 236.5L301 211.5L274 186.5L298.5 160Z\"\n fill=\"url(#right-code-gradient)\"\n />\n <path\n d=\"M283 108L232 212L266 253L238 369L302 237L267 198L283 108Z\"\n fill=\"url(#bolt-gradient)\"\n />\n`;\n","import path from \"node:path\";\n\nimport {\n createAgentJobManager,\n 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?: (\n config: UserConfig,\n environment: ConfigEnv,\n ) => void | Promise<void>;\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n}\n\ninterface ViteTransformOutput {\n readonly code: string;\n readonly map: string;\n}\n\nfunction createCacheKey(id: string, code: string): string {\n const hash = createHash(\"sha256\").update(code).digest(\"base64url\");\n return `${id}\\0${hash}`;\n}\n\nfunction getDisplayPath(root: string, id: string): string {\n const relative = path.relative(root, stripViteQuery(id));\n return relative.split(path.sep).join(\"/\");\n}\n\nexport function createTransformPlugin(input: TransformPluginInput): Plugin {\n let root = process.cwd();\n let filter = createTransformFilter(root, input.context.getOptions());\n let logger: ResolvedConfig[\"logger\"] | undefined;\n const warnedFiles = new Set<string>();\n const cache = new Map<string, ViteTransformOutput | null>();\n\n return {\n name: \"spotpatch:transform\",\n apply: \"serve\",\n enforce: \"pre\",\n\n async config(config, environment) {\n await input.configure?.(config, environment);\n },\n\n configResolved(config) {\n root = path.resolve(config.root);\n filter = createTransformFilter(root, input.context.getOptions());\n logger = config.logger;\n },\n\n transform(code, id) {\n if (!filter.shouldTransform(id, code)) {\n return null;\n }\n\n const cleanId = path.resolve(stripViteQuery(id));\n const cacheKey = createCacheKey(cleanId, code);\n\n if (cache.has(cacheKey)) {\n return cache.get(cacheKey) ?? null;\n }\n\n const startedAt = performance.now();\n const options = input.context.getOptions();\n\n try {\n const result = injectSourceMarkers({\n code,\n absolutePath: cleanId,\n root,\n fileId: input.registry.register(cleanId),\n 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,qBAOO;AACP,IAAAC,eAAsE;;;ACVtE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E,CAAC,0BAA0B,MAAM;AAAA,UACvG;AAAA,QACF;AAEA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;;;ALjGO,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,OAChB,QACA,gBACkB;AAClB,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,cAAU,UAAM,0CAAsB;AAAA,MACpC,SAAS;AAAA,MACT;AAAA,MACA,SAAS;AAAA,IACX,CAAC;AAED,gCAAwB,iDAA6B,SAAS,iBAAiB;AAAA,EACjF;AAEA,SAAO;AAAA,IACL,sBAAsB,EAAE,WAAW,SAAS,SAAS,CAAC;AAAA,IACtD,6BAA6B,EAAE,SAAS,QAAQ,CAAC;AAAA,IACjD,mBAAmB,EAAE,SAAS,UAAU,QAAQ,CAAC;AAAA,EACnD;AACF;;;AO7DA,IAAAC,qBAKO;;;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
@@ -19,7 +19,7 @@ import { createRuntimeAiConfig } from "@spotpatch/dev-server";
19
19
  // package.json
20
20
  var package_default = {
21
21
  name: "@spotpatch/vite",
22
- version: "1.6.1",
22
+ version: "1.8.0",
23
23
  description: "Vite development plugin for SpotPatch.",
24
24
  license: "MIT",
25
25
  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 resolveProjectOptions,\n} from \"@spotpatch/dev-server\";\nimport { loadEnv, type ConfigEnv, type Plugin, type UserConfig } from \"vite\";\n\nimport type { ViteSpotPatchOptions } from \"./options.js\";\nimport type { SpotPatchPluginContext } from \"./plugin-context.js\";\nimport { createRuntimeInjectionPlugin } from \"./runtime/runtime-injection-plugin.js\";\nimport { createServerPlugin } from \"./server/server-plugin.js\";\nimport { createTransformPlugin } from \"./transform/transform-plugin.js\";\n\nexport function spotPatch(userOptions: ViteSpotPatchOptions = {}): Plugin[] {\n let options = resolveOptions(userOptions);\n let credentialEnvironment: Readonly<Record<string, string | undefined>> =\n Object.freeze({});\n\n if (!options.enabled) {\n return [];\n }\n\n const registry = createSourceRegistry();\n const session = createSession();\n const context = Object.freeze({\n getCredentialEnvironment: () => credentialEnvironment,\n getOptions: () => options,\n } satisfies SpotPatchPluginContext);\n const configure = async (\n config: UserConfig,\n environment: ConfigEnv,\n ): Promise<void> => {\n const root = path.resolve(process.cwd(), config.root ?? \".\");\n const loadedEnvironment =\n config.envDir === false\n ? process.env\n : loadEnv(environment.mode, path.resolve(root, config.envDir ?? \".\"), \"\");\n const environmentAi =\n userOptions.ai === undefined\n ? resolveEnvironmentAiConfiguration(loadedEnvironment).ai\n : false;\n\n options = await resolveProjectOptions({\n appRoot: root,\n environmentAi,\n options: userOptions,\n });\n\n credentialEnvironment = resolveCredentialEnvironment(options, loadedEnvironment);\n };\n\n return [\n createTransformPlugin({ configure, context, registry }),\n createRuntimeInjectionPlugin({ context, session }),\n createServerPlugin({ context, registry, session }),\n ];\n}\n","import { createRequire } from \"node:module\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { 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.6.1\",\n \"description\": \"Vite development plugin for SpotPatch.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/huanglvjing/spotpatch.git\",\n \"directory\": \"packages/vite\"\n },\n \"homepage\": \"https://github.com/huanglvjing/spotpatch#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/huanglvjing/spotpatch/issues\"\n },\n \"keywords\": [\n \"spotpatch\",\n \"vite\",\n \"react\",\n \"developer-tools\",\n \"ai-agent\"\n ],\n \"type\": \"module\",\n \"sideEffects\": false,\n \"engines\": {\n \"node\": \">=20.19.0\"\n },\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"bin\": {\n \"spotpatch-vite\": \"./dist/cli.js\"\n },\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup src/index.ts --format esm,cjs --dts --sourcemap --clean && tsup --config tsup.cli.config.ts && tsup --config tsup.runtime-client.config.ts && tsup --config tsup.runtime-react-adapter.config.ts\",\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 \"magic-string\": \"1.1.0\",\n \"oxc-parser\": \"0.143.0\"\n },\n \"peerDependencies\": {\n \"vite\": \"^5.0.0 || ^6.0.0 || ^7.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n }\n}\n","/**\n * Canonical SpotPatch mark from docs/assets/spotpatch-logo-mark.svg.\n *\n * The Vite development injector consumes this trusted asset separately from\n * the core browser bundle so the Runtime gzip budget remains enforceable.\n */\nexport const BRAND_MARK_CONTENT = `\n <defs>\n <linearGradient id=\"locator-gradient\" x1=\"76\" y1=\"92\" x2=\"436\" y2=\"374\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#B61CFF\" />\n <stop offset=\"0.38\" stop-color=\"#6D35FF\" />\n <stop offset=\"0.72\" stop-color=\"#168EFF\" />\n <stop offset=\"1\" stop-color=\"#00D9E9\" />\n </linearGradient>\n <linearGradient id=\"left-code-gradient\" x1=\"165\" y1=\"166\" x2=\"236\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#A51EFF\" />\n <stop offset=\"1\" stop-color=\"#653BFF\" />\n </linearGradient>\n <linearGradient id=\"right-code-gradient\" x1=\"276\" y1=\"166\" x2=\"347\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#158DFF\" />\n <stop offset=\"1\" stop-color=\"#00D8E9\" />\n </linearGradient>\n <linearGradient id=\"bolt-gradient\" x1=\"270\" y1=\"111\" x2=\"252\" y2=\"365\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#6840FF\" />\n <stop offset=\"0.48\" stop-color=\"#257BFF\" />\n <stop offset=\"1\" stop-color=\"#00CBEF\" />\n </linearGradient>\n </defs>\n <path\n fill=\"url(#locator-gradient)\"\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n d=\"M256 52C345.47 52 418 124.53 418 214C418 267.55 391.98 316.24 354.04 348.02L256 468L157.96 348.02C120.02 316.24 94 267.55 94 214C94 124.53 166.53 52 256 52ZM256 88C186.41 88 130 144.41 130 214C130 258.2 152.76 297.08 187.2 319.57L256 403.8L324.8 319.57C359.24 297.08 382 258.2 382 214C382 144.41 325.59 88 256 88Z\"\n />\n <rect x=\"238\" y=\"20\" width=\"36\" height=\"84\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"62\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"366\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <path\n d=\"M213.5 160L158 211.5L213.5 263L238 236.5L211 211.5L238 186.5L213.5 160Z\"\n fill=\"url(#left-code-gradient)\"\n />\n <path\n d=\"M298.5 160L354 211.5L298.5 263L274 236.5L301 211.5L274 186.5L298.5 160Z\"\n fill=\"url(#right-code-gradient)\"\n />\n <path\n d=\"M283 108L232 212L266 253L238 369L302 237L267 198L283 108Z\"\n fill=\"url(#bolt-gradient)\"\n />\n`;\n","import path from \"node:path\";\n\nimport {\n createAgentJobManager,\n 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?: (\n config: UserConfig,\n environment: ConfigEnv,\n ) => void | Promise<void>;\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n}\n\ninterface ViteTransformOutput {\n readonly code: string;\n readonly map: string;\n}\n\nfunction createCacheKey(id: string, code: string): string {\n const hash = createHash(\"sha256\").update(code).digest(\"base64url\");\n return `${id}\\0${hash}`;\n}\n\nfunction getDisplayPath(root: string, id: string): string {\n const relative = path.relative(root, stripViteQuery(id));\n return relative.split(path.sep).join(\"/\");\n}\n\nexport function createTransformPlugin(input: TransformPluginInput): Plugin {\n let root = process.cwd();\n let filter = createTransformFilter(root, input.context.getOptions());\n let logger: ResolvedConfig[\"logger\"] | undefined;\n const warnedFiles = new Set<string>();\n const cache = new Map<string, ViteTransformOutput | null>();\n\n return {\n name: \"spotpatch:transform\",\n apply: \"serve\",\n enforce: \"pre\",\n\n async config(config, environment) {\n await input.configure?.(config, environment);\n },\n\n configResolved(config) {\n root = path.resolve(config.root);\n filter = createTransformFilter(root, input.context.getOptions());\n logger = config.logger;\n },\n\n transform(code, id) {\n if (!filter.shouldTransform(id, code)) {\n return null;\n }\n\n const cleanId = path.resolve(stripViteQuery(id));\n const cacheKey = createCacheKey(cleanId, code);\n\n if (cache.has(cacheKey)) {\n return cache.get(cacheKey) ?? null;\n }\n\n const startedAt = performance.now();\n const options = input.context.getOptions();\n\n try {\n const result = injectSourceMarkers({\n code,\n absolutePath: cleanId,\n root,\n fileId: input.registry.register(cleanId),\n 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,EACA;AAAA,OACK;AACP,SAAS,eAA6D;;;ACVtE,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,OAAO,UAAU;AAEjB,SAAS,6BAAoD;;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AAa;AAC1E,MAAI,UAAU,eAAe,WAAW;AACxC,MAAI,wBACF,OAAO,OAAO,CAAC,CAAC;AAElB,MAAI,CAAC,QAAQ,SAAS;AACpB,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,WAAW,qBAAqB;AACtC,QAAM,UAAU,cAAc;AAC9B,QAAM,UAAU,OAAO,OAAO;AAAA,IAC5B,0BAA0B,MAAM;AAAA,IAChC,YAAY,MAAM;AAAA,EACpB,CAAkC;AAClC,QAAM,YAAY,OAChB,QACA,gBACkB;AAClB,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,MAAM,sBAAsB;AAAA,MACpC,SAAS;AAAA,MACT;AAAA,MACA,SAAS;AAAA,IACX,CAAC;AAED,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;;;AO7DA;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 resolveProjectOptions,\n} from \"@spotpatch/dev-server\";\nimport { loadEnv, type ConfigEnv, type Plugin, type UserConfig } from \"vite\";\n\nimport type { ViteSpotPatchOptions } from \"./options.js\";\nimport type { SpotPatchPluginContext } from \"./plugin-context.js\";\nimport { createRuntimeInjectionPlugin } from \"./runtime/runtime-injection-plugin.js\";\nimport { createServerPlugin } from \"./server/server-plugin.js\";\nimport { createTransformPlugin } from \"./transform/transform-plugin.js\";\n\nexport function spotPatch(userOptions: ViteSpotPatchOptions = {}): Plugin[] {\n let options = resolveOptions(userOptions);\n let credentialEnvironment: Readonly<Record<string, string | undefined>> =\n Object.freeze({});\n\n if (!options.enabled) {\n return [];\n }\n\n const registry = createSourceRegistry();\n const session = createSession();\n const context = Object.freeze({\n getCredentialEnvironment: () => credentialEnvironment,\n getOptions: () => options,\n } satisfies SpotPatchPluginContext);\n const configure = async (\n config: UserConfig,\n environment: ConfigEnv,\n ): Promise<void> => {\n const root = path.resolve(process.cwd(), config.root ?? \".\");\n const loadedEnvironment =\n config.envDir === false\n ? process.env\n : loadEnv(environment.mode, path.resolve(root, config.envDir ?? \".\"), \"\");\n const environmentAi =\n userOptions.ai === undefined\n ? resolveEnvironmentAiConfiguration(loadedEnvironment).ai\n : false;\n\n options = await resolveProjectOptions({\n appRoot: root,\n environmentAi,\n options: userOptions,\n });\n\n credentialEnvironment = resolveCredentialEnvironment(options, loadedEnvironment);\n };\n\n return [\n createTransformPlugin({ configure, context, registry }),\n createRuntimeInjectionPlugin({ context, session }),\n createServerPlugin({ context, registry, session }),\n ];\n}\n","import { createRequire } from \"node:module\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { 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.8.0\",\n \"description\": \"Vite development plugin for SpotPatch.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/huanglvjing/spotpatch.git\",\n \"directory\": \"packages/vite\"\n },\n \"homepage\": \"https://github.com/huanglvjing/spotpatch#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/huanglvjing/spotpatch/issues\"\n },\n \"keywords\": [\n \"spotpatch\",\n \"vite\",\n \"react\",\n \"developer-tools\",\n \"ai-agent\"\n ],\n \"type\": \"module\",\n \"sideEffects\": false,\n \"engines\": {\n \"node\": \">=20.19.0\"\n },\n \"files\": [\n \"dist\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"bin\": {\n \"spotpatch-vite\": \"./dist/cli.js\"\n },\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup src/index.ts --format esm,cjs --dts --sourcemap --clean && tsup --config tsup.cli.config.ts && tsup --config tsup.runtime-client.config.ts && tsup --config tsup.runtime-react-adapter.config.ts\",\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 \"magic-string\": \"1.1.0\",\n \"oxc-parser\": \"0.143.0\"\n },\n \"peerDependencies\": {\n \"vite\": \"^5.0.0 || ^6.0.0 || ^7.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\",\n \"registry\": \"https://registry.npmjs.org/\"\n }\n}\n","/**\n * Canonical SpotPatch mark from docs/assets/spotpatch-logo-mark.svg.\n *\n * The Vite development injector consumes this trusted asset separately from\n * the core browser bundle so the Runtime gzip budget remains enforceable.\n */\nexport const BRAND_MARK_CONTENT = `\n <defs>\n <linearGradient id=\"locator-gradient\" x1=\"76\" y1=\"92\" x2=\"436\" y2=\"374\" gradientUnits=\"userSpaceOnUse\">\n <stop offset=\"0\" stop-color=\"#B61CFF\" />\n <stop offset=\"0.38\" stop-color=\"#6D35FF\" />\n <stop offset=\"0.72\" stop-color=\"#168EFF\" />\n <stop offset=\"1\" stop-color=\"#00D9E9\" />\n </linearGradient>\n <linearGradient id=\"left-code-gradient\" x1=\"165\" y1=\"166\" x2=\"236\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#A51EFF\" />\n <stop offset=\"1\" stop-color=\"#653BFF\" />\n </linearGradient>\n <linearGradient id=\"right-code-gradient\" x1=\"276\" y1=\"166\" x2=\"347\" y2=\"258\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#158DFF\" />\n <stop offset=\"1\" stop-color=\"#00D8E9\" />\n </linearGradient>\n <linearGradient id=\"bolt-gradient\" x1=\"270\" y1=\"111\" x2=\"252\" y2=\"365\" gradientUnits=\"userSpaceOnUse\">\n <stop stop-color=\"#6840FF\" />\n <stop offset=\"0.48\" stop-color=\"#257BFF\" />\n <stop offset=\"1\" stop-color=\"#00CBEF\" />\n </linearGradient>\n </defs>\n <path\n fill=\"url(#locator-gradient)\"\n fill-rule=\"evenodd\"\n clip-rule=\"evenodd\"\n d=\"M256 52C345.47 52 418 124.53 418 214C418 267.55 391.98 316.24 354.04 348.02L256 468L157.96 348.02C120.02 316.24 94 267.55 94 214C94 124.53 166.53 52 256 52ZM256 88C186.41 88 130 144.41 130 214C130 258.2 152.76 297.08 187.2 319.57L256 403.8L324.8 319.57C359.24 297.08 382 258.2 382 214C382 144.41 325.59 88 256 88Z\"\n />\n <rect x=\"238\" y=\"20\" width=\"36\" height=\"84\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"62\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <rect x=\"366\" y=\"196\" width=\"84\" height=\"36\" rx=\"4\" fill=\"url(#locator-gradient)\" />\n <path\n d=\"M213.5 160L158 211.5L213.5 263L238 236.5L211 211.5L238 186.5L213.5 160Z\"\n fill=\"url(#left-code-gradient)\"\n />\n <path\n d=\"M298.5 160L354 211.5L298.5 263L274 236.5L301 211.5L274 186.5L298.5 160Z\"\n fill=\"url(#right-code-gradient)\"\n />\n <path\n d=\"M283 108L232 212L266 253L238 369L302 237L267 198L283 108Z\"\n fill=\"url(#bolt-gradient)\"\n />\n`;\n","import path from \"node:path\";\n\nimport {\n createAgentJobManager,\n 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?: (\n config: UserConfig,\n environment: ConfigEnv,\n ) => void | Promise<void>;\n readonly context: SpotPatchPluginContext;\n readonly registry: SourceRegistry;\n}\n\ninterface ViteTransformOutput {\n readonly code: string;\n readonly map: string;\n}\n\nfunction createCacheKey(id: string, code: string): string {\n const hash = createHash(\"sha256\").update(code).digest(\"base64url\");\n return `${id}\\0${hash}`;\n}\n\nfunction getDisplayPath(root: string, id: string): string {\n const relative = path.relative(root, stripViteQuery(id));\n return relative.split(path.sep).join(\"/\");\n}\n\nexport function createTransformPlugin(input: TransformPluginInput): Plugin {\n let root = process.cwd();\n let filter = createTransformFilter(root, input.context.getOptions());\n let logger: ResolvedConfig[\"logger\"] | undefined;\n const warnedFiles = new Set<string>();\n const cache = new Map<string, ViteTransformOutput | null>();\n\n return {\n name: \"spotpatch:transform\",\n apply: \"serve\",\n enforce: \"pre\",\n\n async config(config, environment) {\n await input.configure?.(config, environment);\n },\n\n configResolved(config) {\n root = path.resolve(config.root);\n filter = createTransformFilter(root, input.context.getOptions());\n logger = config.logger;\n },\n\n transform(code, id) {\n if (!filter.shouldTransform(id, code)) {\n return null;\n }\n\n const cleanId = path.resolve(stripViteQuery(id));\n const cacheKey = createCacheKey(cleanId, code);\n\n if (cache.has(cacheKey)) {\n return cache.get(cacheKey) ?? null;\n }\n\n const startedAt = performance.now();\n const options = input.context.getOptions();\n\n try {\n const result = injectSourceMarkers({\n code,\n absolutePath: cleanId,\n root,\n fileId: input.registry.register(cleanId),\n 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,EACA;AAAA,OACK;AACP,SAAS,eAA6D;;;ACVtE,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,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AAO,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,MAAM,sBAAsB;AAAA,MACpC,SAAS;AAAA,MACT;AAAA,MACA,SAAS;AAAA,IACX,CAAC;AAED,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;;;AO7DA;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"]}
@@ -253,7 +253,7 @@ ${Pt(e.code.language,J(t.codeLines.join(`
253
253
  .spotpatch-agent-selectors { grid-template-columns: 1fr; }
254
254
  .spotpatch-agent-mode { grid-column: auto; }
255
255
  }
256
- `;function Et(e,t,o,n){let i=e.createElement("option");return i.value=o,i.textContent=n,t.append(i),i}function Xn(e,t,o){let n=o.messages(),i=c(e,"section");i.className="spotpatch-agent",i.hidden=!t.enabled;let r=c(e,"div");r.className="spotpatch-agent-head";let a=c(e,"span");a.className="spotpatch-agent-title";let p=c(e,"span");p.className="spotpatch-agent-badge",r.append(a,p);let E=c(e,"div");E.className="spotpatch-agent-setup";let A=c(e,"div");A.className="spotpatch-agent-selectors";let C=c(e,"label");C.className="spotpatch-agent-mode";let U=c(e,"span"),g=c(e,"select");C.append(U,g);let M=c(e,"label"),$=c(e,"span"),L=c(e,"select");M.append($,L);let x=c(e,"label"),T=c(e,"span"),V=c(e,"select");x.append(T,V),A.append(C,M,x);let te=c(e,"label");te.className="spotpatch-consent";let z=c(e,"input");z.type="checkbox";let f=c(e,"span");te.append(z,f);let b=c(e,"label");b.className="spotpatch-consent spotpatch-workspace-consent",b.hidden=!0;let S=c(e,"input");S.type="checkbox";let w=c(e,"span"),F=c(e,"strong"),ue=c(e,"small");w.append(F,ue),b.append(S,w);let Re=c(e,"div");Re.className="spotpatch-agent-health-list";let Y=c(e,"p");Y.className="spotpatch-agent-workspace",Y.dataset.state="idle";let O=c(e,"p");O.className="spotpatch-agent-capability",O.dataset.state="idle",Re.append(Y,O),E.append(A,te,b,Re);let k=c(e,"div");k.className="spotpatch-agent-job",k.hidden=!0;let ke=c(e,"div");ke.className="spotpatch-agent-job-meta";let He=c(e,"span");He.className="spotpatch-agent-model";let ie=c(e,"span");ie.className="spotpatch-agent-status",ke.append(He,ie);let Be=c(e,"p");Be.className="spotpatch-agent-phase";let de=c(e,"p");de.className="spotpatch-agent-error",de.hidden=!0;let me=c(e,"ul");me.className="spotpatch-agent-activity";let oe=c(e,"div");oe.className="spotpatch-agent-result",oe.hidden=!0;let W=c(e,"p");W.className="spotpatch-agent-summary";let be=c(e,"ul");be.className="spotpatch-agent-files";let Ne=c(e,"div");Ne.className="spotpatch-agent-checks";let Q=c(e,"pre");Q.className="spotpatch-agent-diff",Q.tabIndex=0,Q.setAttribute("aria-label",n.agent.diffAriaLabel),oe.append(W,be,Ne,Q),k.append(ke,Be,de,me,oe),i.append(r,E,k);let ge=ee(e,n.agent.testConnection),Me=ee(e,n.agent.run,"spotpatch-run"),ye=ee(e,n.agent.cancel),fe=ee(e,n.agent.apply,"spotpatch-primary"),xe=ee(e,n.agent.revert),R=ee(e,n.agent.revise),De=t.enabled?t.providers:[],Se=t.enabled&&t.applyMode==="trusted-auto",P=t.enabled?t.applyMode:"review",ve=new Map(De.map(l=>[l.id,l])),Ee=!1,we=!0,re=!1,Z=!1,Oe=!1,_e=!1,Pe,We,se=[],Te,Ae="idle",Le=n.agent.connectionNotTested,Ie,ae="idle",Ue,$e;for(let l of De)Et(e,L,l.id,l.label);t.enabled&&(L.value=t.defaultProvider);let le,ze,Je;P==="auto"?Je=Et(e,g,"auto",n.agent.autoGated):(le=Et(e,g,"review",n.agent.review),Se&&(ze=Et(e,g,"trusted-auto",n.agent.trustedFast)));let Ye=Se?"review":P;g.value=Ye,C.hidden=!Se;let st=()=>g.value==="trusted-auto"?"trusted-auto":Ye,s=()=>st()==="trusted-auto",d=()=>ve.get(L.value),y=l=>l===void 0?n.agent.providerUnavailable:s()?n.agent.trustedFastConsent(l.label):n.agent.consent(l.label),I=()=>s()?z.checked:S.checked,j=()=>{let l=s();te.classList.toggle("spotpatch-trusted-consent",l),p.textContent=l?n.agent.trustedFast:P==="auto"?n.agent.autoGated:n.agent.review,f.textContent=y(d()),b.hidden=l||ae!=="consent-required"},N=()=>{let l=d();if(V.replaceChildren(),l===void 0){f.textContent=y(l);return}for(let _ of l.models)Et(e,V,_.id,_.label);V.value=l.defaultModel,f.textContent=y(l)},q=()=>{let l=t.enabled&&re&&!Z;Me.textContent=Oe?n.agent.verifying:n.agent.run,Me.classList.toggle("spotpatch-primary",_e),ge.hidden=!l,Me.hidden=!l,ge.disabled=!we||Oe||d()===void 0,Me.disabled=!we||Oe||!Ee||!z.checked||ae==="idle"||ae==="checking"||ae==="blocked"||ae==="consent-required"&&!I()||d()===void 0||V.value.length===0,(!Z||!re)&&(ye.hidden=!0,fe.hidden=!0,xe.hidden=!0,R.hidden=!0)},lt=()=>{if(ae==="idle")Y.textContent=n.agent.workspaceNotChecked;else if(ae==="checking")Y.textContent=n.agent.checkingWorkspace;else if(ae==="ready")Y.textContent=n.agent.workspaceReady;else if(ae==="consent-required"){let l=Ue?.changes;Y.textContent=n.agent.workspaceDirty(l?.staged??0,l?.unstaged??0,l?.untracked??0)}else Y.textContent=$e===void 0?n.errors.INTERNAL_ERROR:n.errors[$e]};function pt(){N(),z.checked=!1,O.dataset.state="idle",O.textContent=n.agent.connectionNotTested,Ae="idle",Le=n.agent.connectionNotTested,Ie=void 0,_e=!1,q()}function ut(){O.dataset.state="idle",O.textContent=n.agent.connectionNotTested,Ae="idle",Le=n.agent.connectionNotTested,Ie=void 0,_e=!1,q()}function At(){z.checked=!1,S.checked=!1,j(),q()}N(),g.addEventListener("change",At),L.addEventListener("change",pt),V.addEventListener("change",ut),z.addEventListener("change",q),S.addEventListener("change",q);function u(){if(Pe===void 0)return;let l=Pe,_=We;He.textContent=`${l.providerLabel} · ${l.modelLabel}`,ie.textContent=n.agent.status(l.status),Be.textContent=l.phaseMessage;let K=Te??l.errorCode;de.hidden=K===void 0,de.textContent=K===void 0?"":n.errors[K],me.replaceChildren();for(let H of se.slice(-8)){let G=c(e,"li");G.dataset.state=H.state,G.textContent=H.label,me.append(G)}oe.hidden=_===void 0,W.textContent=_?.summary??"",be.replaceChildren(),Ne.replaceChildren(),Q.textContent=_?.diff??"";for(let H of _?.files??[]){let G=c(e,"li");G.textContent=`${H.kind} ${H.relativePath} (+${String(H.additions)} / -${String(H.deletions)})`,be.append(G)}for(let H of _?.checks??[]){let G=c(e,"details"),Xe=c(e,"summary");Xe.textContent=`${H.label}: ${H.status} · ${String(H.durationMs)} ms`;let B=c(e,"pre");B.textContent=H.output.length===0?n.agent.noOutput:H.output,G.append(Xe,B),Ne.append(G)}ge.hidden=!0,Me.hidden=!0,ye.hidden=!re||!l.canCancel,ye.textContent=l.status==="awaiting-review"?n.agent.discard:n.agent.cancel,fe.hidden=!re||!l.canApply,xe.hidden=!re||!l.canRevert,R.hidden=!re||!["completed","cancelled","reverted","failed"].includes(l.status)}function m(){n=o.messages(),a.textContent=n.agent.title,U.textContent=n.agent.mode,le!==void 0&&(le.textContent=n.agent.review),ze!==void 0&&(ze.textContent=n.agent.trustedFast),Je!==void 0&&(Je.textContent=n.agent.autoGated),$.textContent=n.agent.provider,T.textContent=n.agent.model,L.setAttribute("aria-label",n.agent.providerAriaLabel),V.setAttribute("aria-label",n.agent.modelAriaLabel),F.textContent=n.agent.includeLocalChanges,ue.textContent=n.agent.includeLocalChangesHelp,Q.setAttribute("aria-label",n.agent.diffAriaLabel),ge.textContent=n.agent.testConnection,fe.textContent=n.agent.apply,xe.textContent=n.agent.revert,R.textContent=n.agent.revise,j(),Ae==="idle"?O.textContent=n.agent.connectionNotTested:Ae==="probing"?O.textContent=n.agent.testingCapability:Ae==="ready"?O.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:Ie!==void 0?O.textContent=n.errors[Ie]:d()===void 0?O.textContent=n.agent.providerUnavailable:O.textContent=Le,lt(),q(),u()}let v=o.subscribe(m);return m(),Object.freeze({root:i,modeSelect:g,providerSelect:L,modelSelect:V,consentCheckbox:z,workspaceConsentCheckbox:S,testButton:ge,runButton:Me,cancelButton:ye,applyButton:fe,revertButton:xe,resetButton:R,consentGranted(){return z.checked},workspaceConsentGranted(){return I()},readSelection(){let l=d(),_=l?.models.find(K=>K.id===V.value);return l===void 0||_===void 0?void 0:Object.freeze({applyMode:st(),providerProfileId:l.id,modelProfileId:_.id})},renderCapability(l,_,K,H){Ae=l,Le=_,Ie=H,Oe=l==="probing",_e=l==="ready"&&K?.state==="agent-ready",O.dataset.state=l,O.textContent=K?.state==="agent-ready"?`${_} · ${n.agent.toolsReady}`:_,q()},renderWorkspaceHealth(l,_,K){ae=l,Ue=_,$e=K??_?.errorCode,Y.dataset.state=l,l!=="checking"&&(b.hidden=s()||l!=="consent-required"),(l==="idle"||l==="ready"||l==="blocked")&&(S.checked=!1),lt(),q()},renderJob(l,_,K,H){Z=!0,E.hidden=!0,k.hidden=!1,L.disabled=!0,V.disabled=!0,g.disabled=!0,z.disabled=!0,S.disabled=!0,Pe=l,We=_,se=K,Te=H,u()},resetJob(){Z=!1,Pe=void 0,We=void 0,se=[],Te=void 0,E.hidden=!1,k.hidden=!0,L.disabled=!1,V.disabled=!1,g.disabled=!1,z.disabled=!1,S.disabled=!1,me.replaceChildren(),be.replaceChildren(),Ne.replaceChildren(),Q.textContent="",de.textContent="",de.hidden=!0,q()},setContextReady(l){Ee=l,q()},setEditingEnabled(l){we=l,L.disabled=!l||Z,V.disabled=!l||Z,g.disabled=!l||Z,z.disabled=!l||Z,S.disabled=!l||Z,q()},setProviderConsent(l){z.checked=l,q()},setSelectionVisible(l){re=l,q(),l||(ye.hidden=!0,fe.hidden=!0,xe.hidden=!0,R.hidden=!0)},dispose(){v(),L.removeEventListener("change",pt),V.removeEventListener("change",ut),g.removeEventListener("change",At),z.removeEventListener("change",q),S.removeEventListener("change",q)}})}var Zn="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(Zn,t);for(let[i,r]of Object.entries(o))n.setAttribute(i,r);return n}function Qn(e,t){let o=qr(t),n=Kr(e,"svg",{xmlns:Zn,class:"spotpatch-brand-mark",viewBox:o.viewBox,"aria-hidden":"true",focusable:"false"});return n.innerHTML=o.content,n}function ot(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function eo({dialogHeight:e,dialogWidth:t,target:o,viewportHeight:n,viewportWidth:i}){let r=i-t-16,a=n-e-16,p=ot((i-t)/2,16,r),E=ot((n-e)/2,16,a);if(o===void 0)return Object.freeze({anchorX:ot(t/2,22,t-22),anchorY:ot(e/2,22,e-22),left:p,mode:"viewport",top:E});let A=o.x+o.width/2,C=o.y+o.height/2,U=ot(A-t/2,16,r),g=ot(C-e/2,16,a),M=U,$=g,L="viewport";return o.width>=t+48&&o.height>=e+48?L="center":o.y-e-14>=16?($=o.y-e-14,L="above"):o.y+o.height+14+e<=n-16?($=o.y+o.height+14,L="below"):o.x+o.width+14+t<=i-16?(M=o.x+o.width+14,L="right"):o.x-t-14>=16&&(M=o.x-t-14,L="left"),Object.freeze({anchorX:ot(A-M,22,t-22),anchorY:ot(C-$,22,e-22),left:M,mode:L,top:$})}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({[h.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[h.INVALID_TOKEN]:"The local SpotPatch session expired.",[h.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[h.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[h.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[h.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[h.EDITOR_OPEN_FAILED]:"The editor request failed.",[h.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[h.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[h.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[h.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[h.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[h.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not start or continue the required tool call.",[h.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[h.AGENT_BUSY]:"Another write Agent job is still active.",[h.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[h.AGENT_CANCELLED]:"The Agent job was cancelled.",[h.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[h.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[h.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[h.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[h.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[h.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[h.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[h.TOOL_DENIED]:"A tool request violated local safety policy.",[h.TOOL_INPUT_INVALID]:"Invalid tool request.",[h.TOOL_ARGUMENTS_INVALID]:"Tool arguments are invalid.",[h.TOOL_CALL_ID_CONFLICT]:"Tool ID conflicts in this turn.",[h.TOOL_PATH_DENIED]:"The model requested a protected or external path.",[h.PATCH_REJECTED]:"The patch violated local policy.",[h.VALIDATION_FAILED]:"Required checks failed; changes cannot be applied.",[h.APPLY_CONFLICT]:"Agent-touched files changed; nothing was overwritten.",[h.INTERNAL_ERROR]:"The Agent failed without exposing private details."}),Qr=Object.freeze({[h.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[h.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[h.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[h.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[h.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[h.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[h.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[h.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[h.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[h.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[h.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[h.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[h.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未完成必要的工具调用或结果续接。",[h.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[h.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[h.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[h.AGENT_CANCELLED]:"Agent 任务已取消。",[h.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[h.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[h.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[h.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[h.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[h.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[h.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[h.TOOL_DENIED]:"工具请求违反本地安全策略。",[h.TOOL_INPUT_INVALID]:"工具请求无效。",[h.TOOL_ARGUMENTS_INVALID]:"工具参数无效。",[h.TOOL_CALL_ID_CONFLICT]:"本轮工具 ID 冲突。",[h.TOOL_PATH_DENIED]:"模型请求了受保护或项目外路径。",[h.PATCH_REJECTED]:"补丁违反本地策略。",[h.VALIDATION_FAILED]:"必需检查失败,无法应用变更。",[h.APPLY_CONFLICT]:"Agent 触及文件已变化,未覆盖。",[h.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",mode:"Execution mode",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",mode:"执行方式",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 to(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=to(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(to).find(i=>i!==void 0)??"en-US"}function no(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 oo=460,ro=620,ra=Object.freeze({previewing:560,selected:ro});function aa(e){let t=e.createElement("style");return t.textContent=`
256
+ `;function Et(e,t,o,n){let i=e.createElement("option");return i.value=o,i.textContent=n,t.append(i),i}function Xn(e,t,o){let n=o.messages(),i=c(e,"section");i.className="spotpatch-agent",i.hidden=!t.enabled;let r=c(e,"div");r.className="spotpatch-agent-head";let a=c(e,"span");a.className="spotpatch-agent-title";let p=c(e,"span");p.className="spotpatch-agent-badge",r.append(a,p);let E=c(e,"div");E.className="spotpatch-agent-setup";let A=c(e,"div");A.className="spotpatch-agent-selectors";let C=c(e,"label");C.className="spotpatch-agent-mode";let U=c(e,"span"),g=c(e,"select");C.append(U,g);let M=c(e,"label"),$=c(e,"span"),L=c(e,"select");M.append($,L);let x=c(e,"label"),T=c(e,"span"),V=c(e,"select");x.append(T,V),A.append(C,M,x);let te=c(e,"label");te.className="spotpatch-consent";let z=c(e,"input");z.type="checkbox";let f=c(e,"span");te.append(z,f);let b=c(e,"label");b.className="spotpatch-consent spotpatch-workspace-consent",b.hidden=!0;let S=c(e,"input");S.type="checkbox";let w=c(e,"span"),F=c(e,"strong"),ue=c(e,"small");w.append(F,ue),b.append(S,w);let Re=c(e,"div");Re.className="spotpatch-agent-health-list";let Y=c(e,"p");Y.className="spotpatch-agent-workspace",Y.dataset.state="idle";let O=c(e,"p");O.className="spotpatch-agent-capability",O.dataset.state="idle",Re.append(Y,O),E.append(A,te,b,Re);let k=c(e,"div");k.className="spotpatch-agent-job",k.hidden=!0;let ke=c(e,"div");ke.className="spotpatch-agent-job-meta";let He=c(e,"span");He.className="spotpatch-agent-model";let ie=c(e,"span");ie.className="spotpatch-agent-status",ke.append(He,ie);let Be=c(e,"p");Be.className="spotpatch-agent-phase";let de=c(e,"p");de.className="spotpatch-agent-error",de.hidden=!0;let me=c(e,"ul");me.className="spotpatch-agent-activity";let oe=c(e,"div");oe.className="spotpatch-agent-result",oe.hidden=!0;let W=c(e,"p");W.className="spotpatch-agent-summary";let be=c(e,"ul");be.className="spotpatch-agent-files";let Ne=c(e,"div");Ne.className="spotpatch-agent-checks";let Q=c(e,"pre");Q.className="spotpatch-agent-diff",Q.tabIndex=0,Q.setAttribute("aria-label",n.agent.diffAriaLabel),oe.append(W,be,Ne,Q),k.append(ke,Be,de,me,oe),i.append(r,E,k);let ge=ee(e,n.agent.testConnection),Me=ee(e,n.agent.run,"spotpatch-run"),ye=ee(e,n.agent.cancel),fe=ee(e,n.agent.apply,"spotpatch-primary"),xe=ee(e,n.agent.revert),R=ee(e,n.agent.revise),De=t.enabled?t.providers:[],Se=t.enabled&&t.applyMode==="trusted-auto",P=t.enabled?t.applyMode:"review",ve=new Map(De.map(l=>[l.id,l])),Ee=!1,we=!0,re=!1,Z=!1,Oe=!1,_e=!1,Pe,We,se=[],Te,Ae="idle",Le=n.agent.connectionNotTested,Ie,ae="idle",Ue,$e;for(let l of De)Et(e,L,l.id,l.label);t.enabled&&(L.value=t.defaultProvider);let le,ze,Je;P==="auto"?Je=Et(e,g,"auto",n.agent.autoGated):(le=Et(e,g,"review",n.agent.review),Se&&(ze=Et(e,g,"trusted-auto",n.agent.trustedFast)));let Ye=Se?"review":P;g.value=Ye,C.hidden=!Se;let st=()=>g.value==="trusted-auto"?"trusted-auto":Ye,s=()=>st()==="trusted-auto",d=()=>ve.get(L.value),y=l=>l===void 0?n.agent.providerUnavailable:s()?n.agent.trustedFastConsent(l.label):n.agent.consent(l.label),I=()=>s()?z.checked:S.checked,j=()=>{let l=s();te.classList.toggle("spotpatch-trusted-consent",l),p.textContent=l?n.agent.trustedFast:P==="auto"?n.agent.autoGated:n.agent.review,f.textContent=y(d()),b.hidden=l||ae!=="consent-required"},N=()=>{let l=d();if(V.replaceChildren(),l===void 0){f.textContent=y(l);return}for(let _ of l.models)Et(e,V,_.id,_.label);V.value=l.defaultModel,f.textContent=y(l)},q=()=>{let l=t.enabled&&re&&!Z;Me.textContent=Oe?n.agent.verifying:n.agent.run,Me.classList.toggle("spotpatch-primary",_e),ge.hidden=!l,Me.hidden=!l,ge.disabled=!we||Oe||d()===void 0,Me.disabled=!we||Oe||!Ee||!z.checked||ae==="idle"||ae==="checking"||ae==="blocked"||ae==="consent-required"&&!I()||d()===void 0||V.value.length===0,(!Z||!re)&&(ye.hidden=!0,fe.hidden=!0,xe.hidden=!0,R.hidden=!0)},lt=()=>{if(ae==="idle")Y.textContent=n.agent.workspaceNotChecked;else if(ae==="checking")Y.textContent=n.agent.checkingWorkspace;else if(ae==="ready")Y.textContent=n.agent.workspaceReady;else if(ae==="consent-required"){let l=Ue?.changes;Y.textContent=n.agent.workspaceDirty(l?.staged??0,l?.unstaged??0,l?.untracked??0)}else Y.textContent=$e===void 0?n.errors.INTERNAL_ERROR:n.errors[$e]};function pt(){N(),z.checked=!1,O.dataset.state="idle",O.textContent=n.agent.connectionNotTested,Ae="idle",Le=n.agent.connectionNotTested,Ie=void 0,_e=!1,q()}function ut(){O.dataset.state="idle",O.textContent=n.agent.connectionNotTested,Ae="idle",Le=n.agent.connectionNotTested,Ie=void 0,_e=!1,q()}function At(){z.checked=!1,S.checked=!1,j(),q()}N(),g.addEventListener("change",At),L.addEventListener("change",pt),V.addEventListener("change",ut),z.addEventListener("change",q),S.addEventListener("change",q);function u(){if(Pe===void 0)return;let l=Pe,_=We;He.textContent=`${l.providerLabel} · ${l.modelLabel}`,ie.textContent=n.agent.status(l.status),Be.textContent=l.phaseMessage;let K=Te??l.errorCode;de.hidden=K===void 0,de.textContent=K===void 0?"":n.errors[K],me.replaceChildren();for(let H of se.slice(-8)){let G=c(e,"li");G.dataset.state=H.state,G.textContent=H.label,me.append(G)}oe.hidden=_===void 0,W.textContent=_?.summary??"",be.replaceChildren(),Ne.replaceChildren(),Q.textContent=_?.diff??"";for(let H of _?.files??[]){let G=c(e,"li");G.textContent=`${H.kind} ${H.relativePath} (+${String(H.additions)} / -${String(H.deletions)})`,be.append(G)}for(let H of _?.checks??[]){let G=c(e,"details"),Xe=c(e,"summary");Xe.textContent=`${H.label}: ${H.status} · ${String(H.durationMs)} ms`;let B=c(e,"pre");B.textContent=H.output.length===0?n.agent.noOutput:H.output,G.append(Xe,B),Ne.append(G)}ge.hidden=!0,Me.hidden=!0,ye.hidden=!re||!l.canCancel,ye.textContent=l.status==="awaiting-review"?n.agent.discard:n.agent.cancel,fe.hidden=!re||!l.canApply,xe.hidden=!re||!l.canRevert,R.hidden=!re||!["completed","cancelled","reverted","failed"].includes(l.status)}function m(){n=o.messages(),a.textContent=n.agent.title,U.textContent=n.agent.mode,le!==void 0&&(le.textContent=n.agent.review),ze!==void 0&&(ze.textContent=n.agent.trustedFast),Je!==void 0&&(Je.textContent=n.agent.autoGated),$.textContent=n.agent.provider,T.textContent=n.agent.model,L.setAttribute("aria-label",n.agent.providerAriaLabel),V.setAttribute("aria-label",n.agent.modelAriaLabel),F.textContent=n.agent.includeLocalChanges,ue.textContent=n.agent.includeLocalChangesHelp,Q.setAttribute("aria-label",n.agent.diffAriaLabel),ge.textContent=n.agent.testConnection,fe.textContent=n.agent.apply,xe.textContent=n.agent.revert,R.textContent=n.agent.revise,j(),Ae==="idle"?O.textContent=n.agent.connectionNotTested:Ae==="probing"?O.textContent=n.agent.testingCapability:Ae==="ready"?O.textContent=`${n.agent.capabilityVerified} · ${n.agent.toolsReady}`:Ie!==void 0?O.textContent=n.errors[Ie]:d()===void 0?O.textContent=n.agent.providerUnavailable:O.textContent=Le,lt(),q(),u()}let v=o.subscribe(m);return m(),Object.freeze({root:i,modeSelect:g,providerSelect:L,modelSelect:V,consentCheckbox:z,workspaceConsentCheckbox:S,testButton:ge,runButton:Me,cancelButton:ye,applyButton:fe,revertButton:xe,resetButton:R,consentGranted(){return z.checked},workspaceConsentGranted(){return I()},readSelection(){let l=d(),_=l?.models.find(K=>K.id===V.value);return l===void 0||_===void 0?void 0:Object.freeze({applyMode:st(),providerProfileId:l.id,modelProfileId:_.id})},renderCapability(l,_,K,H){Ae=l,Le=_,Ie=H,Oe=l==="probing",_e=l==="ready"&&K?.state==="agent-ready",O.dataset.state=l,O.textContent=K?.state==="agent-ready"?`${_} · ${n.agent.toolsReady}`:_,q()},renderWorkspaceHealth(l,_,K){ae=l,Ue=_,$e=K??_?.errorCode,Y.dataset.state=l,l!=="checking"&&(b.hidden=s()||l!=="consent-required"),(l==="idle"||l==="ready"||l==="blocked")&&(S.checked=!1),lt(),q()},renderJob(l,_,K,H){Z=!0,E.hidden=!0,k.hidden=!1,L.disabled=!0,V.disabled=!0,g.disabled=!0,z.disabled=!0,S.disabled=!0,Pe=l,We=_,se=K,Te=H,u()},resetJob(){Z=!1,Pe=void 0,We=void 0,se=[],Te=void 0,E.hidden=!1,k.hidden=!0,L.disabled=!1,V.disabled=!1,g.disabled=!1,z.disabled=!1,S.disabled=!1,me.replaceChildren(),be.replaceChildren(),Ne.replaceChildren(),Q.textContent="",de.textContent="",de.hidden=!0,q()},setContextReady(l){Ee=l,q()},setEditingEnabled(l){we=l,L.disabled=!l||Z,V.disabled=!l||Z,g.disabled=!l||Z,z.disabled=!l||Z,S.disabled=!l||Z,q()},setProviderConsent(l){z.checked=l,q()},setSelectionVisible(l){re=l,q(),l||(ye.hidden=!0,fe.hidden=!0,xe.hidden=!0,R.hidden=!0)},dispose(){v(),L.removeEventListener("change",pt),V.removeEventListener("change",ut),g.removeEventListener("change",At),z.removeEventListener("change",q),S.removeEventListener("change",q)}})}var Zn="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(Zn,t);for(let[i,r]of Object.entries(o))n.setAttribute(i,r);return n}function Qn(e,t){let o=qr(t),n=Kr(e,"svg",{xmlns:Zn,class:"spotpatch-brand-mark",viewBox:o.viewBox,"aria-hidden":"true",focusable:"false"});return n.innerHTML=o.content,n}function ot(e,t,o){return Math.min(Math.max(e,t),Math.max(t,o))}function eo({dialogHeight:e,dialogWidth:t,target:o,viewportHeight:n,viewportWidth:i}){let r=i-t-16,a=n-e-16,p=ot((i-t)/2,16,r),E=ot((n-e)/2,16,a);if(o===void 0)return Object.freeze({anchorX:ot(t/2,22,t-22),anchorY:ot(e/2,22,e-22),left:p,mode:"viewport",top:E});let A=o.x+o.width/2,C=o.y+o.height/2,U=ot(A-t/2,16,r),g=ot(C-e/2,16,a),M=U,$=g,L="viewport";return o.width>=t+48&&o.height>=e+48?L="center":o.y-e-14>=16?($=o.y-e-14,L="above"):o.y+o.height+14+e<=n-16?($=o.y+o.height+14,L="below"):o.x+o.width+14+t<=i-16?(M=o.x+o.width+14,L="right"):o.x-t-14>=16&&(M=o.x-t-14,L="left"),Object.freeze({anchorX:ot(A-M,22,t-22),anchorY:ot(C-$,22,e-22),left:M,mode:L,top:$})}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({[h.INVALID_REQUEST]:"The Agent request was rejected as invalid.",[h.INVALID_TOKEN]:"The local SpotPatch session expired.",[h.ORIGIN_NOT_ALLOWED]:"The current page origin is not authorized.",[h.SOURCE_NOT_FOUND]:"The selected source is no longer available.",[h.SOURCE_OUTSIDE_ROOT]:"The selected source is outside the project.",[h.SOURCE_TOO_LARGE]:"The selected source exceeds the safety limit.",[h.EDITOR_OPEN_FAILED]:"The editor request failed.",[h.AI_DISABLED]:"AI execution is disabled in Vite configuration.",[h.PROVIDER_NOT_CONFIGURED]:"The provider Key environment variable is missing on the Vite process.",[h.PROVIDER_AUTH_FAILED]:"The provider rejected authentication. Check the server-side Key.",[h.PROVIDER_PROTOCOL_UNSUPPORTED]:"The relay does not match the configured OpenAI-compatible protocol.",[h.MODEL_NOT_ALLOWED]:"The selected model profile is not allowed.",[h.MODEL_TOOL_CALL_UNSUPPORTED]:"The selected model did not start or continue the required tool call.",[h.PROVIDER_RATE_LIMITED]:"The provider is rate limited. Wait and try again.",[h.AGENT_BUSY]:"Another write Agent job is still active.",[h.AGENT_LIMIT_EXCEEDED]:"The Agent stopped at a configured time, turn, output, or size limit.",[h.AGENT_CANCELLED]:"The Agent job was cancelled.",[h.WORKTREE_DIRTY]:"Confirm inclusion of local changes before running AI.",[h.WORKTREE_NOT_REPOSITORY]:"Vite root must be an initialized Git repository root.",[h.WORKTREE_OPERATION_IN_PROGRESS]:"Finish the active merge, rebase, cherry-pick, or revert.",[h.WORKTREE_CONFLICTED]:"Resolve all Git conflicts before running AI.",[h.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"Reduce untracked files below the safe count and size limits.",[h.WORKTREE_UNTRACKED_UNSUPPORTED]:"An untracked path is missing, linked, or not a regular file.",[h.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"Local changes cannot be isolated safely.",[h.TOOL_DENIED]:"A tool request violated local safety policy.",[h.TOOL_INPUT_INVALID]:"Invalid tool request.",[h.TOOL_ARGUMENTS_INVALID]:"Tool arguments are invalid.",[h.TOOL_CALL_ID_CONFLICT]:"Tool ID conflicts in this turn.",[h.TOOL_PATH_DENIED]:"The model requested a protected or external path.",[h.PATCH_REJECTED]:"The patch violated local policy.",[h.VALIDATION_FAILED]:"Required checks failed; changes cannot be applied.",[h.APPLY_CONFLICT]:"Agent-touched files changed; nothing was overwritten.",[h.INTERNAL_ERROR]:"The Agent failed without exposing private details."}),Qr=Object.freeze({[h.INVALID_REQUEST]:"Agent 请求无效,已被拒绝。",[h.INVALID_TOKEN]:"本地 SpotPatch 会话已失效。",[h.ORIGIN_NOT_ALLOWED]:"当前页面来源未获授权。",[h.SOURCE_NOT_FOUND]:"选中目标对应的源码已不可用。",[h.SOURCE_OUTSIDE_ROOT]:"选中源码位于项目根目录之外。",[h.SOURCE_TOO_LARGE]:"选中源码超过安全大小限制。",[h.EDITOR_OPEN_FAILED]:"编辑器打开请求失败。",[h.AI_DISABLED]:"Vite 配置未启用 AI 执行。",[h.PROVIDER_NOT_CONFIGURED]:"启动 Vite 的进程中缺少模型服务 Key 环境变量。",[h.PROVIDER_AUTH_FAILED]:"模型服务鉴权失败,请检查服务端 Key。",[h.PROVIDER_PROTOCOL_UNSUPPORTED]:"中转服务与配置的 OpenAI 兼容协议不一致。",[h.MODEL_NOT_ALLOWED]:"当前模型配置未获授权。",[h.MODEL_TOOL_CALL_UNSUPPORTED]:"当前模型未完成必要的工具调用或结果续接。",[h.PROVIDER_RATE_LIMITED]:"模型服务正在限流,请稍后重试。",[h.AGENT_BUSY]:"当前项目已有一个写入任务正在运行。",[h.AGENT_LIMIT_EXCEEDED]:"Agent 达到时间、轮次、输出或变更规模限制。",[h.AGENT_CANCELLED]:"Agent 任务已取消。",[h.WORKTREE_DIRTY]:"运行 AI 前,请明确同意将当前本地修改纳入隔离基线。",[h.WORKTREE_NOT_REPOSITORY]:"Vite 根目录不是已初始化 Git 仓库的顶层目录。",[h.WORKTREE_OPERATION_IN_PROGRESS]:"请先完成当前 merge、rebase、cherry-pick 或 revert,再运行 AI。",[h.WORKTREE_CONFLICTED]:"请先解决全部 Git 冲突,再运行 AI。",[h.WORKTREE_LOCAL_CHANGES_TOO_LARGE]:"未跟踪文件超过安全数量或体积上限,请先精简。",[h.WORKTREE_UNTRACKED_UNSUPPORTED]:"未跟踪项已丢失、是符号链接或不是普通文件。",[h.WORKTREE_LOCAL_CHANGES_UNSUPPORTED]:"当前本地修改无法安全隔离。",[h.TOOL_DENIED]:"工具请求违反本地安全策略。",[h.TOOL_INPUT_INVALID]:"工具请求无效。",[h.TOOL_ARGUMENTS_INVALID]:"工具参数无效。",[h.TOOL_CALL_ID_CONFLICT]:"本轮工具 ID 冲突。",[h.TOOL_PATH_DENIED]:"模型请求了受保护或项目外路径。",[h.PATCH_REJECTED]:"补丁违反本地策略。",[h.VALIDATION_FAILED]:"必需检查失败,无法应用变更。",[h.APPLY_CONFLICT]:"Agent 触及文件已变化,未覆盖。",[h.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",mode:"Execution mode",review:"Review",autoGated:"Auto gated",trustedFast:"Trusted direct",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 direct mode for ${e}: send allowed project context, include current local changes, skip project validation checks, and immediately apply AI changes, 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 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",mode:"执行方式",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 to(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=to(t.documentElement.lang);return o!==void 0?o:t.defaultView?.navigator.languages.map(to).find(i=>i!==void 0)??"en-US"}function no(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 oo=460,ro=620,ra=Object.freeze({previewing:560,selected:ro});function aa(e){let t=e.createElement("style");return t.textContent=`
257
257
  :host {
258
258
  all: initial;
259
259
  --spotpatch-bg: #0e0e12;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spotpatch/vite",
3
- "version": "1.6.1",
3
+ "version": "1.8.0",
4
4
  "description": "Vite development plugin for SpotPatch.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -49,10 +49,10 @@
49
49
  "magic-string": "1.1.0",
50
50
  "oxc-parser": "0.143.0",
51
51
  "@spotpatch/compiler": "^0.1.1",
52
- "@spotpatch/dev-server": "^0.3.0",
53
- "@spotpatch/react-adapter": "^1.0.1",
54
- "@spotpatch/runtime": "^1.7.1",
55
- "@spotpatch/shared": "^1.8.0"
52
+ "@spotpatch/dev-server": "^0.4.0",
53
+ "@spotpatch/shared": "^1.8.0",
54
+ "@spotpatch/runtime": "^1.8.0",
55
+ "@spotpatch/react-adapter": "^1.0.1"
56
56
  },
57
57
  "peerDependencies": {
58
58
  "vite": "^5.0.0 || ^6.0.0 || ^7.0.0"