@spotpatch/vite 1.8.0 → 1.9.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
@@ -20,26 +20,22 @@ SpotPatch runs only with the Vite development server. Production builds contain
20
20
  ### One-command setup (recommended)
21
21
 
22
22
  ```bash
23
- # pnpm project
24
- pnpm dlx @spotpatch/vite@latest setup
25
-
26
- # npm project
27
23
  npx --yes @spotpatch/vite@latest setup
28
24
  ```
29
25
 
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.
26
+ This npm-bootstrap command supports both npm and pnpm projects. It fetches the registry's actual latest CLI, detects the project package manager, installs that CLI's exact SpotPatch version, updates a supported `vite.config.*`, and verifies the result. The exact-version handoff avoids pnpm 11's default 24-hour `minimumReleaseAge` policy silently resolving `@latest` to an older mature release.
27
+
28
+ The initializer supports configuration objects and object-returning `defineConfig` callbacks, while ambiguous dynamic configurations fail without writing the config.
31
29
 
32
- For separate steps, use `@latest` when you intend to upgrade an existing lockfile entry:
30
+ For npm, installation and initialization can also be kept separate:
33
31
 
34
32
  ```bash
35
33
  npm install --save-dev @spotpatch/vite@latest
36
34
  npx spotpatch-vite init
37
-
38
- # or
39
- pnpm add -D @spotpatch/vite@latest
40
- pnpm exec spotpatch-vite init
41
35
  ```
42
36
 
37
+ With pnpm 11, use the recommended setup command, install a trusted exact version, or wait until the release is 24 hours old. SpotPatch does not globally disable the project's supply-chain quarantine.
38
+
43
39
  The initializer places SpotPatch before the React plugin so source markers are injected before React transforms the module:
44
40
 
45
41
  ```ts
@@ -49,11 +45,11 @@ import react from "@vitejs/plugin-react-swc";
49
45
  import { defineConfig } from "vite";
50
46
 
51
47
  export default defineConfig({
52
- plugins: [spotPatch({ trustedFastMode: true }), react()],
48
+ plugins: [spotPatch({ dataFlow: {}, trustedFastMode: true }), react()],
53
49
  });
54
50
  ```
55
51
 
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.
52
+ When no safe local TypeScript check can be discovered, it generates `spotPatch({ dataFlow: {} })` and keeps Review mode. Unsupported dynamic configuration can still be integrated manually using the same plugin order.
57
53
 
58
54
  Start the application normally:
59
55
 
@@ -63,6 +59,12 @@ pnpm dev
63
59
 
64
60
  Select **Select element** in the bottom-right corner or press `Mod+Shift+S`. SpotPatch can collect multiple targets across same-project pages, preserve them through navigation and workbench close/reopen cycles, keep a separate instruction for each one, open the exact source location in Cursor or VS Code, and generate a structured prompt without requiring AI configuration.
65
61
 
62
+ ### Component data flow (Beta)
63
+
64
+ The current `setup/init` writes `spotPatch({ dataFlow: {} })` automatically; use the same option for manual integration. The Vite + React 18 development-only **Data flow** and **Page APIs** tabs show proven method/path, parameter keys, source-consumed response fields, data destinations, actually dispatched requests, and unassigned current-page traffic. Query values and response bodies are not collected. A relationship is reported only when stable component/source/callsite/invocation evidence agrees; ambiguous traffic remains unknown or unassigned. Data-flow AI, safe JSON response inspection, and Next.js are not included in this Beta. See the repository's [exact implementation status](https://github.com/huanglvjing/spotpatch/blob/main/docs/%E6%8A%80%E6%9C%AF%E6%96%B9%E6%A1%88/%E7%BB%84%E4%BB%B6%E6%95%B0%E6%8D%AE%E9%93%BE%E8%B7%AF/13-Beta%E5%AE%9E%E7%8E%B0%E7%8A%B6%E6%80%81%E4%B8%8E%E4%BD%BF%E7%94%A8%E6%89%8B%E5%86%8C.md).
65
+
66
+ Supported adapters include direct/component-service `fetch`, Axios, React Query/TanStack Query callbacks, and experimental tRPC logical procedures. tRPC batch HTTP transport remains separate evidence and is never assigned by timing or URL similarity.
67
+
66
68
  ### Compatibility
67
69
 
68
70
  | Dependency | Supported range |
@@ -87,6 +89,7 @@ spotPatch({
87
89
  locale: "auto",
88
90
  maxTargets: 8,
89
91
  ai: false,
92
+ dataFlow: false,
90
93
  });
91
94
  ```
92
95
 
@@ -104,6 +107,7 @@ spotPatch({
104
107
  | `locale` | `"auto"` | Resolves `en-US` or `zh-CN`. |
105
108
  | `maxTargets` | `8` | Targets allowed in one change request by default. |
106
109
  | `ai` | disabled or a detected complete environment | Optional provider and Agent settings. |
110
+ | `dataFlow` | `false` | Opt-in dispatch-only component data-flow Beta. |
107
111
  | `trustedFastMode` | `false` | Exposes Review/Trusted direct and discovers TypeScript for Review. |
108
112
 
109
113
  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.
@@ -157,8 +161,8 @@ The page defaults to Review. Choosing Trusted direct uses the exact SpotPatch so
157
161
 
158
162
  ### Troubleshooting
159
163
 
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.
164
+ - **pnpm 11 installs an older version for `@latest`:** its default 24-hour `minimumReleaseAge` policy selects the newest mature release. Use the recommended `npx ... setup`, specify a trusted exact version, or wait 24 hours.
165
+ - **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({ dataFlow: {} })` manually before the React plugin.
162
166
  - **No selection button:** confirm `spotPatch()` appears before the React plugin and that the app is running through `vite`/`vite dev`, not `vite preview`.
163
167
  - **No exact source location:** confirm the component is authored in an included `.jsx` or `.tsx` file under `src`, or configure `include` explicitly.
164
168
  - **AI is unavailable:** provide all three required environment values or set `ai: false`; partial environment configuration fails closed.
@@ -182,26 +186,22 @@ SpotPatch 只在 Vite 开发服务器中运行。生产构建不包含 SpotPatch
182
186
  ### 一条命令接入(推荐)
183
187
 
184
188
  ```bash
185
- # pnpm 项目
186
- pnpm dlx @spotpatch/vite@latest setup
187
-
188
- # npm 项目
189
189
  npx --yes @spotpatch/vite@latest setup
190
190
  ```
191
191
 
192
- `setup` 会识别 npm pnpm,显式安装或升级 npm `latest` 标签,安全更新受支持的 `vite.config.*` 并验证结果。初始化器支持配置对象和返回对象的 `defineConfig` 回调;有歧义的动态配置会在不写入配置文件的情况下失败。
192
+ 这条由 npm 引导的命令同时支持 npm pnpm 项目。它先取得 registry 真正的最新 CLI,再识别项目包管理器、安装该 CLI 对应的 SpotPatch 精确版本、安全更新受支持的 `vite.config.*` 并验证结果。精确版本交接可以避免 pnpm 11 默认 24 小时 `minimumReleaseAge` 把 `@latest` 解析成较旧的成熟版本。
193
+
194
+ 初始化器支持配置对象和返回对象的 `defineConfig` 回调;有歧义的动态配置会在不写入配置文件的情况下失败。
193
195
 
194
- 需要分开执行时,如果要升级锁文件里的已有版本,请显式使用 `@latest`:
196
+ npm 项目也可以分开安装和初始化:
195
197
 
196
198
  ```bash
197
199
  npm install --save-dev @spotpatch/vite@latest
198
200
  npx spotpatch-vite init
199
-
200
- # 或
201
- pnpm add -D @spotpatch/vite@latest
202
- pnpm exec spotpatch-vite init
203
201
  ```
204
202
 
203
+ pnpm 11 项目请使用推荐的 setup 命令、安装已确认的精确版本,或等待发布满 24 小时。SpotPatch 不会全局关闭项目的供应链隔离策略。
204
+
205
205
  初始化器会将 SpotPatch 放在 React 插件之前,确保源码标记在 React 转换前注入:
206
206
 
207
207
  ```ts
@@ -211,11 +211,11 @@ import react from "@vitejs/plugin-react-swc";
211
211
  import { defineConfig } from "vite";
212
212
 
213
213
  export default defineConfig({
214
- plugins: [spotPatch({ trustedFastMode: true }), react()],
214
+ plugins: [spotPatch({ dataFlow: {}, trustedFastMode: true }), react()],
215
215
  });
216
216
  ```
217
217
 
218
- 无法发现安全的本地 TypeScript 检查时,初始化器会生成 `spotPatch()` 并保持审阅模式。不受支持的动态配置仍可按相同插件顺序手动接入。
218
+ 无法发现安全的本地 TypeScript 检查时,初始化器会生成 `spotPatch({ dataFlow: {} })` 并保持审阅模式。不受支持的动态配置仍可按相同插件顺序手动接入。
219
219
 
220
220
  照常启动应用:
221
221
 
@@ -225,6 +225,12 @@ pnpm dev
225
225
 
226
226
  点击右下角的 **选择元素** 或按下 `Mod+Shift+S`。SpotPatch 支持跨同一项目的多个页面采集目标,在页面跳转及工作台关闭/重开后保留目标与独立修改要求,在 Cursor 或 VS Code 中打开精确位置,并且在完全不配置 AI 的情况下生成结构化 Prompt。
227
227
 
228
+ ### 组件数据链路(Beta)
229
+
230
+ 新版 `setup/init` 会自动写入 `spotPatch({ dataFlow: {} })`,手工接入时使用同一选项。Vite + React 18 开发期的 **数据链路** 与 **页面接口** 页签会显示有证据的 method/path、参数键、源码消费字段、数据去向、实际 dispatch 请求和当前页面未归属流量;不采集 query 值或响应体。只有稳定组件、源码、callsite 与 invocation 证据一致时才建立关联,歧义流量保持 unknown/unassigned。当前不包含 data-flow AI、安全 JSON 响应读取或 Next.js 支持。准确范围见仓库中的 [实现状态文档](https://github.com/huanglvjing/spotpatch/blob/main/docs/%E6%8A%80%E6%9C%AF%E6%96%B9%E6%A1%88/%E7%BB%84%E4%BB%B6%E6%95%B0%E6%8D%AE%E9%93%BE%E8%B7%AF/13-Beta%E5%AE%9E%E7%8E%B0%E7%8A%B6%E6%80%81%E4%B8%8E%E4%BD%BF%E7%94%A8%E6%89%8B%E5%86%8C.md)。
231
+
232
+ 已支持的适配器包括组件直接/Service `fetch`、Axios、React Query/TanStack Query 回调和实验性的 tRPC 逻辑 procedure。tRPC batch HTTP 传输保持为独立证据,绝不按时间或 URL 相似度强行归属。
233
+
228
234
  ### 兼容范围
229
235
 
230
236
  | 依赖 | 正式支持范围 |
@@ -249,6 +255,7 @@ spotPatch({
249
255
  locale: "auto",
250
256
  maxTargets: 8,
251
257
  ai: false,
258
+ dataFlow: false,
252
259
  });
253
260
  ```
254
261
 
@@ -266,6 +273,7 @@ spotPatch({
266
273
  | `locale` | `"auto"` | 自动解析 `en-US` 或 `zh-CN`。 |
267
274
  | `maxTargets` | `8` | 一次修改任务默认允许的目标数。 |
268
275
  | `ai` | 关闭或检测到完整环境配置 | 可选 Provider 和 Agent 配置。 |
276
+ | `dataFlow` | `false` | 可选 dispatch-only 组件数据链路 Beta。 |
269
277
  | `trustedFastMode` | `false` | 开放审阅/可信极速选择;TypeScript 检查供审阅模式使用。 |
270
278
 
271
279
  本包导出选项类型、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)。
@@ -319,8 +327,8 @@ spotPatch({ trustedFastMode: true });
319
327
 
320
328
  ### 常见问题
321
329
 
322
- - **仍然安装了旧版本:**请使用 `@spotpatch/vite@latest`;不带标签的 add 可能继续复用锁文件中满足范围的旧版本。
323
- - **初始化器拒绝配置:**请使用配置对象,或只含一个明确对象返回的回调。存在条件返回或动态插件数组时,手动将 `spotPatch()` 放到 React 插件之前。
330
+ - **pnpm 11 对 `@latest` 安装了旧版本:**默认 24 小时 `minimumReleaseAge` 会选择最新的成熟版本。请使用推荐的 `npx ... setup`、安装已确认的精确版本,或等待 24 小时。
331
+ - **初始化器拒绝配置:**请使用配置对象,或只含一个明确对象返回的回调。存在条件返回或动态插件数组时,手动将 `spotPatch({ dataFlow: {} })` 放到 React 插件之前。
324
332
  - **没有选择元素按钮:**确认 `spotPatch()` 位于 React 插件之前,并且应用通过 `vite`/`vite dev` 而不是 `vite preview` 启动。
325
333
  - **没有精确源码位置:**确认组件来自 include 范围内的 `.jsx` 或 `.tsx` 文件,默认范围是 `src`。
326
334
  - **AI 不可用:**提供全部三个必需环境变量,或者显式设置 `ai: false`;不完整配置会安全失败。
package/dist/cli.js CHANGED
@@ -68,6 +68,16 @@ function insertStaticImport(magicString, program, statement) {
68
68
  magicString.appendRight(offset, `
69
69
  ${statement}`);
70
70
  }
71
+ function importQuote(source, program) {
72
+ const firstImport = importsOf(program)[0];
73
+ if (firstImport !== void 0) {
74
+ const quote = source[firstImport.source.start];
75
+ if (quote === '"' || quote === "'") {
76
+ return quote;
77
+ }
78
+ }
79
+ return '"';
80
+ }
71
81
  function collectIdentifierNames(program) {
72
82
  const names = /* @__PURE__ */ new Set();
73
83
  new Visitor({
@@ -249,8 +259,12 @@ function childIndent(source, object) {
249
259
  }
250
260
  return `${lineIndentAt(source, object.start)} `;
251
261
  }
252
- function trustedFastCall(pluginName, enabled) {
253
- return enabled ? `${pluginName}({ trustedFastMode: true })` : `${pluginName}()`;
262
+ function initializedPluginCall(pluginName, trustedFastMode) {
263
+ const options = [
264
+ "dataFlow: {}",
265
+ ...trustedFastMode ? ["trustedFastMode: true"] : []
266
+ ];
267
+ return `${pluginName}({ ${options.join(", ")} })`;
254
268
  }
255
269
  function directPluginCalls(plugins, pluginName) {
256
270
  return plugins.elements.filter((element) => {
@@ -261,12 +275,12 @@ function directPluginCalls(plugins, pluginName) {
261
275
  return callee.type === "Identifier" && callee.name === pluginName;
262
276
  });
263
277
  }
264
- function enableTrustedFastMode(magicString, source, call) {
278
+ function enableInitializedOptions(magicString, source, call, trustedFastMode) {
265
279
  if (call.arguments.length === 0) {
266
280
  magicString.overwrite(
267
281
  call.start,
268
282
  call.end,
269
- `${source.slice(call.start, call.end - 1)}{ trustedFastMode: true })`
283
+ initializedPluginCall(source.slice(call.start, call.callee.end), trustedFastMode)
270
284
  );
271
285
  return;
272
286
  }
@@ -278,33 +292,55 @@ function enableTrustedFastMode(magicString, source, call) {
278
292
  if (value.type !== "ObjectExpression") {
279
293
  throw new Error("SpotPatch init requires spotPatch options to be an object.");
280
294
  }
281
- const property = findProperty(value, "trustedFastMode");
282
- if (property !== void 0) {
283
- const propertyValue = unwrapExpression(property.value);
295
+ if (value.properties.some((property) => property.type === "SpreadElement")) {
296
+ throw new Error(
297
+ "SpotPatch init cannot prove dataFlow through spread spotPatch options."
298
+ );
299
+ }
300
+ const dataFlowProperty = findProperty(value, "dataFlow");
301
+ const trustedFastModeProperty = findProperty(value, "trustedFastMode");
302
+ const missingProperties = [];
303
+ if (dataFlowProperty === void 0) {
304
+ missingProperties.push("dataFlow: {}");
305
+ } else {
306
+ const dataFlowValue = unwrapExpression(dataFlowProperty.value);
307
+ if (dataFlowValue.type === "Literal" && dataFlowValue.value === false) {
308
+ magicString.overwrite(dataFlowValue.start, dataFlowValue.end, "{}");
309
+ } else if (dataFlowValue.type !== "ObjectExpression") {
310
+ throw new Error(
311
+ "SpotPatch init requires dataFlow to be false or an options object."
312
+ );
313
+ }
314
+ }
315
+ if (trustedFastMode && trustedFastModeProperty === void 0) {
316
+ missingProperties.push("trustedFastMode: true");
317
+ } else if (trustedFastModeProperty !== void 0) {
318
+ const propertyValue = unwrapExpression(trustedFastModeProperty.value);
284
319
  if (propertyValue.type !== "Literal" || typeof propertyValue.value !== "boolean") {
285
320
  throw new Error(
286
321
  "SpotPatch init requires trustedFastMode to be a boolean literal."
287
322
  );
288
323
  }
289
- if (!propertyValue.value) {
324
+ if (trustedFastMode && !propertyValue.value) {
290
325
  magicString.overwrite(propertyValue.start, propertyValue.end, "true");
291
326
  }
292
- return;
293
327
  }
328
+ if (missingProperties.length === 0) return;
294
329
  const indent = childIndent(source, value);
295
330
  if (value.properties.length === 0) {
296
- magicString.appendLeft(value.end - 1, " trustedFastMode: true ");
331
+ magicString.appendLeft(value.end - 1, ` ${missingProperties.join(", ")} `);
297
332
  } else {
298
333
  magicString.appendLeft(
299
334
  value.properties[0]?.start ?? value.end - 1,
300
- `trustedFastMode: true,
335
+ `${missingProperties.join(`,
336
+ ${indent}`)},
301
337
  ${indent}`
302
338
  );
303
339
  }
304
340
  }
305
341
  function addPluginCall(magicString, source, config, pluginName, trustedFastModeAvailable) {
306
342
  const pluginsProperty = findProperty(config, "plugins");
307
- const call = trustedFastCall(pluginName, trustedFastModeAvailable);
343
+ const call = initializedPluginCall(pluginName, trustedFastModeAvailable);
308
344
  if (pluginsProperty === void 0) {
309
345
  const indent = childIndent(source, config);
310
346
  if (config.properties.length === 0) {
@@ -329,14 +365,19 @@ ${indent}`
329
365
  throw new Error("SpotPatch init found duplicate spotPatch plugins.");
330
366
  }
331
367
  if (existing[0] !== void 0) {
332
- if (trustedFastModeAvailable) {
333
- enableTrustedFastMode(magicString, source, existing[0]);
334
- }
368
+ enableInitializedOptions(
369
+ magicString,
370
+ source,
371
+ existing[0],
372
+ trustedFastModeAvailable
373
+ );
335
374
  return;
336
375
  }
337
376
  const first = value.elements.find((element) => element !== null);
338
377
  if (first === void 0) {
339
378
  magicString.appendLeft(value.end - 1, call);
379
+ } else if (!source.slice(value.start, first.start).includes("\n")) {
380
+ magicString.appendLeft(first.start, `${call}, `);
340
381
  } else {
341
382
  magicString.appendLeft(
342
383
  first.start,
@@ -353,10 +394,11 @@ function transformViteConfig(absolutePath, source, trustedFastModeAvailable) {
353
394
  const magicString = new MagicString(source);
354
395
  if (existingPluginName === void 0) {
355
396
  const specifier = pluginName === "spotPatch" ? "spotPatch" : `spotPatch as ${pluginName}`;
397
+ const quote = importQuote(source, program);
356
398
  insertStaticImport(
357
399
  magicString,
358
400
  program,
359
- `import { ${specifier} } from ${JSON.stringify(ADAPTER_PACKAGE_NAME)};`
401
+ `import { ${specifier} } from ${quote}${ADAPTER_PACKAGE_NAME}${quote};`
360
402
  );
361
403
  }
362
404
  addPluginCall(magicString, source, config, pluginName, trustedFastModeAvailable);
@@ -433,6 +475,7 @@ async function checkViteIntegration(directory = process.cwd()) {
433
475
  import { spawn } from "child_process";
434
476
  import { access, readFile } from "fs/promises";
435
477
  import path2 from "path";
478
+ var VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
436
479
  async function pathExists(absolutePath) {
437
480
  try {
438
481
  await access(absolutePath);
@@ -481,18 +524,33 @@ async function detectPackageManager(appRoot = process.cwd(), userAgent = process
481
524
  "SpotPatch setup could not determine npm or pnpm; run installation and init separately."
482
525
  );
483
526
  }
484
- function createInstallCommand(packageManager, platform = process.platform) {
527
+ function createInstallCommand(packageManager, version, platform = process.platform) {
528
+ if (!VERSION_PATTERN.test(version)) {
529
+ throw new Error("SpotPatch setup could not determine its package version.");
530
+ }
531
+ const packageSpecifier = `@spotpatch/vite@${version}`;
485
532
  return Object.freeze({
486
533
  executable: platform === "win32" ? `${packageManager}.cmd` : packageManager,
487
534
  arguments: Object.freeze(
488
- packageManager === "pnpm" ? ["add", "-D", "@spotpatch/vite@latest"] : ["install", "--save-dev", "@spotpatch/vite@latest"]
535
+ packageManager === "pnpm" ? ["add", "-D", packageSpecifier] : ["install", "--save-dev", packageSpecifier]
489
536
  )
490
537
  });
491
538
  }
492
- async function installLatestAdapter(packageManager, appRoot = process.cwd()) {
493
- const command = createInstallCommand(packageManager);
539
+ async function readCurrentAdapterVersion() {
540
+ const manifest = JSON.parse(
541
+ await readFile(new URL("../package.json", import.meta.url), "utf8")
542
+ );
543
+ const version = manifest.version;
544
+ if (typeof version !== "string" || !VERSION_PATTERN.test(version)) {
545
+ throw new Error("SpotPatch setup could not determine its package version.");
546
+ }
547
+ return version;
548
+ }
549
+ async function installCurrentAdapter(packageManager, appRoot = process.cwd()) {
550
+ const version = await readCurrentAdapterVersion();
551
+ const command = createInstallCommand(packageManager, version);
494
552
  process.stdout.write(
495
- `[spotpatch:vite] installing @spotpatch/vite@latest with ${packageManager}...
553
+ `[spotpatch:vite] installing @spotpatch/vite@${version} with ${packageManager}...
496
554
  `
497
555
  );
498
556
  await new Promise((resolve, reject) => {
@@ -518,10 +576,10 @@ async function installLatestAdapter(packageManager, appRoot = process.cwd()) {
518
576
  }
519
577
 
520
578
  // src/cli.ts
521
- var VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/u;
579
+ var VERSION_PATTERN2 = /^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/u;
522
580
  function writeUsage() {
523
581
  process.stderr.write(
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"
582
+ "Usage: spotpatch-vite <setup|init|check>\n setup Install this CLI's exact @spotpatch/vite version, then initialize it.\n init Preview and apply safe Vite integration changes.\n check Verify the Vite integration without writing files.\n"
525
583
  );
526
584
  }
527
585
  async function inspectViteProject(appRoot = process.cwd()) {
@@ -542,7 +600,7 @@ async function inspectViteProject(appRoot = process.cwd()) {
542
600
  }
543
601
  const manifest = JSON.parse(await readFile2(viteManifestPath, "utf8"));
544
602
  const version = typeof manifest === "object" && manifest !== null && "version" in manifest && typeof manifest.version === "string" ? manifest.version : void 0;
545
- const match = version === void 0 ? null : VERSION_PATTERN.exec(version);
603
+ const match = version === void 0 ? null : VERSION_PATTERN2.exec(version);
546
604
  const major = Number(match?.[1]);
547
605
  if (version === void 0 || match === null || !Number.isSafeInteger(major) || major < 5 || major >= 8) {
548
606
  throw new Error(
@@ -589,7 +647,7 @@ async function runSetup(arguments_) {
589
647
  throw new Error("SpotPatch setup does not accept positional arguments.");
590
648
  }
591
649
  const packageManager = await detectPackageManager();
592
- await installLatestAdapter(packageManager);
650
+ await installCurrentAdapter(packageManager);
593
651
  return runInit([]);
594
652
  }
595
653
  async function runCheck(arguments_) {
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/initializer.ts","../src/setup.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\n\nimport {\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;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,OAA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W,GAAG;AAC3B,UAAM,IAAI,MAAM,uDAAuD;AAAA,EACzE;AAEA,QAAM,iBAAiB,MAAM,qBAAqB;AAClD,QAAM,qBAAqB,cAAc;AACzC,SAAO,QAAQ,CAAC,CAAC;AACnB;AAEA,eAAe,SAAS,YAAgD;AACtE,MAAI,WAAW,WAAW,GAAG;AAC3B,UAAM,IAAI,MAAM,uDAAuD;AAAA,EACzE;AAEA,QAAM,UAAU,MAAM,mBAAmB;AACzC,QAAM,SAAS,MAAM,qBAAqB;AAE1C,MAAI,CAAC,OAAO,IAAI;AACd,eAAW,SAAS,OAAO,QAAQ;AACjC,cAAQ,OAAO,MAAM,oBAAoB,KAAK;AAAA,CAAI;AAAA,IACpD;AAEA,WAAO;AAAA,EACT;AAEA,QAAM,OAAO,OAAO,2BAChB,gCACA;AACJ,UAAQ,OAAO;AAAA,IACb,kDAAkD,OAAO,SAAM,IAAI;AAAA;AAAA,EACrE;AACA,SAAO;AACT;AAEA,eAAe,KAAK,YAAgD;AAClE,QAAM,CAAC,SAAS,GAAG,IAAI,IAAI;AAE3B,MAAI,YAAY,SAAS;AACvB,WAAO,SAAS,IAAI;AAAA,EACtB;AAEA,MAAI,YAAY,QAAQ;AACtB,WAAO,QAAQ,IAAI;AAAA,EACrB;AAEA,MAAI,YAAY,SAAS;AACvB,WAAO,SAAS,IAAI;AAAA,EACtB;AAEA,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"]}
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, installCurrentAdapter } from \"./setup.js\";\n\nconst VERSION_PATTERN = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-[0-9A-Za-z.-]+)?$/u;\n\nfunction writeUsage(): void {\n process.stderr.write(\n \"Usage: spotpatch-vite <setup|init|check>\\n\" +\n \" setup Install this CLI's exact @spotpatch/vite version, then initialize it.\\n\" +\n \" init Preview and apply safe Vite integration changes.\\n\" +\n \" check Verify the Vite integration without writing files.\\n\",\n );\n}\n\nasync function inspectViteProject(appRoot = process.cwd()): Promise<string> {\n const resolveFromApplication = createRequire(path.join(appRoot, \"package.json\"));\n let adapterEntry: string;\n let viteManifestPath: string;\n\n try {\n adapterEntry = resolveFromApplication.resolve(\"@spotpatch/vite\");\n viteManifestPath = resolveFromApplication.resolve(\"vite/package.json\");\n } catch (error: unknown) {\n throw new Error(\n \"SpotPatch could not resolve the local @spotpatch/vite and Vite packages.\",\n { cause: error },\n );\n }\n\n if (adapterEntry.length === 0) {\n throw new Error(\"SpotPatch could not resolve the Vite adapter export.\");\n }\n\n const manifest = JSON.parse(await readFile(viteManifestPath, \"utf8\")) as unknown;\n const version =\n typeof manifest === \"object\" &&\n manifest !== null &&\n \"version\" in manifest &&\n typeof manifest.version === \"string\"\n ? manifest.version\n : undefined;\n const match = version === undefined ? null : VERSION_PATTERN.exec(version);\n const major = Number(match?.[1]);\n\n if (\n version === undefined ||\n match === null ||\n !Number.isSafeInteger(major) ||\n major < 5 ||\n major >= 8\n ) {\n throw new Error(\n `SpotPatch Vite requires Vite >=5.0.0 <8.0.0; found ${version ?? \"unknown\"}.`,\n );\n }\n\n return version;\n}\n\nfunction writeTrustedModeStatus(available: boolean): void {\n process.stdout.write(\n available\n ? \"[spotpatch:vite] trusted fast mode is available in the page selector.\\n\"\n : \"[spotpatch:vite] review mode is ready; trusted fast mode needs a local TypeScript project check.\\n\",\n );\n}\n\nasync function runInit(arguments_: readonly string[]): Promise<number> {\n if (arguments_.length !== 0) {\n throw new Error(\"SpotPatch init does not accept positional arguments.\");\n }\n\n await inspectViteProject();\n const plan = await planViteIntegration();\n\n if (plan.changes.length === 0) {\n process.stdout.write(\"[spotpatch:vite] integration is already up to date.\\n\");\n writeTrustedModeStatus(plan.trustedFastModeAvailable);\n return 0;\n }\n\n process.stdout.write(\"[spotpatch:vite] integration preview (resulting files):\\n\");\n\n for (const change of plan.changes) {\n process.stdout.write(`\\n--- ${change.relativePath}\\n${change.nextContent}`);\n\n if (!change.nextContent.endsWith(\"\\n\")) {\n process.stdout.write(\"\\n\");\n }\n }\n\n await applyViteIntegrationPlan(plan);\n process.stdout.write(\n `[spotpatch:vite] updated ${String(plan.changes.length)} integration file(s).\\n`,\n );\n writeTrustedModeStatus(plan.trustedFastModeAvailable);\n\n return 0;\n}\n\nasync function runSetup(arguments_: readonly string[]): Promise<number> {\n if (arguments_.length !== 0) {\n throw new Error(\"SpotPatch setup does not accept positional arguments.\");\n }\n\n const packageManager = await detectPackageManager();\n await installCurrentAdapter(packageManager);\n return runInit([]);\n}\n\nasync function runCheck(arguments_: readonly string[]): Promise<number> {\n if (arguments_.length !== 0) {\n throw new Error(\"SpotPatch check does not accept positional arguments.\");\n }\n\n const version = await inspectViteProject();\n const result = await checkViteIntegration();\n\n if (!result.ok) {\n for (const issue of result.issues) {\n process.stderr.write(`[spotpatch:vite] ${issue}\\n`);\n }\n\n return 1;\n }\n\n const mode = result.trustedFastModeAvailable\n ? \"trusted fast mode available\"\n : \"review mode\";\n process.stdout.write(\n `[spotpatch:vite] integration verified for Vite ${version} · ${mode}.\\n`,\n );\n return 0;\n}\n\nasync function main(arguments_: readonly string[]): Promise<number> {\n const [command, ...rest] = arguments_;\n\n if (command === \"setup\") {\n return runSetup(rest);\n }\n\n if (command === \"init\") {\n return runInit(rest);\n }\n\n if (command === \"check\") {\n return runCheck(rest);\n }\n\n writeUsage();\n return 1;\n}\n\ntry {\n process.exitCode = await main(process.argv.slice(2));\n} catch (error: unknown) {\n process.stderr.write(\n `[spotpatch:vite] ${\n error instanceof Error ? error.message : \"The command failed.\"\n }\\n`,\n );\n process.exitCode = 1;\n}\n","import path from \"node:path\";\n\nimport {\n applyIntegrationPlan,\n createIntegrationFileChange,\n discoverProjectValidationCheck,\n integrationPathExists,\n readIntegrationFile,\n type IntegrationFileChange,\n} from \"@spotpatch/dev-server\";\nimport { DEFAULT_AGENT_LIMITS } from \"@spotpatch/shared\";\nimport { MagicString } from \"magic-string\";\nimport {\n parseSync,\n Visitor,\n type ArrayExpression,\n type CallExpression,\n type ExportDefaultDeclaration,\n type Expression,\n type ImportDeclaration,\n type ObjectExpression,\n type ObjectProperty,\n type Program,\n type ReturnStatement,\n} from \"oxc-parser\";\n\nconst ADAPTER_PACKAGE_NAME = \"@spotpatch/vite\";\nconst CONFIG_FILE_NAMES = Object.freeze([\n \"vite.config.ts\",\n \"vite.config.mts\",\n \"vite.config.js\",\n \"vite.config.mjs\",\n] as const);\n\nexport interface ViteIntegrationPlan {\n readonly appRoot: string;\n readonly changes: readonly IntegrationFileChange[];\n readonly trustedFastModeAvailable: boolean;\n}\n\nexport interface ViteIntegrationCheck {\n readonly appRoot: string;\n readonly issues: readonly string[];\n readonly ok: boolean;\n readonly trustedFastModeAvailable: boolean;\n}\n\ninterface ParsedModule {\n readonly program: Program;\n readonly source: string;\n}\n\nfunction isParserErrorSeverity(value: unknown): boolean {\n return value === \"Error\";\n}\n\nfunction parseModule(absolutePath: string, source: string): ParsedModule {\n const result = parseSync(absolutePath, source, {\n sourceType: \"module\",\n showSemanticErrors: true,\n });\n const error = result.errors.find((entry) => isParserErrorSeverity(entry.severity));\n\n if (error !== undefined) {\n throw new SyntaxError(\n `SpotPatch could not safely parse ${path.basename(absolutePath)} (${error.message}).`,\n );\n }\n\n return Object.freeze({ program: result.program, source });\n}\n\nfunction importsOf(program: Program): readonly ImportDeclaration[] {\n return program.body.filter(\n (statement): statement is ImportDeclaration =>\n statement.type === \"ImportDeclaration\",\n );\n}\n\nfunction importInsertionOffset(program: Program): number {\n const lastImport = importsOf(program).at(-1);\n\n if (lastImport !== undefined) {\n return lastImport.end;\n }\n\n const directives = program.body.filter(\n (statement) =>\n statement.type === \"ExpressionStatement\" &&\n typeof statement.directive === \"string\",\n );\n return directives.at(-1)?.end ?? program.hashbang?.end ?? 0;\n}\n\nfunction insertStaticImport(\n magicString: MagicString,\n program: Program,\n statement: string,\n): void {\n const offset = importInsertionOffset(program);\n\n if (offset === 0) {\n magicString.prepend(`${statement}\\n`);\n return;\n }\n\n magicString.appendRight(offset, `\\n${statement}`);\n}\n\nfunction importQuote(source: string, program: Program): '\"' | \"'\" {\n const firstImport = importsOf(program)[0];\n\n if (firstImport !== undefined) {\n const quote = source[firstImport.source.start];\n\n if (quote === '\"' || quote === \"'\") {\n return quote;\n }\n }\n\n return '\"';\n}\n\nfunction collectIdentifierNames(program: Program): ReadonlySet<string> {\n const names = new Set<string>();\n new Visitor({\n Identifier(node) {\n names.add(node.name);\n },\n }).visit(program);\n return names;\n}\n\nfunction choosePluginName(program: Program): string {\n const names = collectIdentifierNames(program);\n let suffix = 0;\n let candidate = \"spotPatch\";\n\n while (names.has(candidate)) {\n suffix += 1;\n candidate = `spotPatch${String(suffix)}`;\n }\n\n return candidate;\n}\n\nfunction importedPluginName(program: Program): string | undefined {\n const adapterImports = importsOf(program).filter(\n (statement) => statement.source.value === ADAPTER_PACKAGE_NAME,\n );\n\n if (adapterImports.length > 1) {\n throw new Error(\"SpotPatch init found duplicate @spotpatch/vite imports.\");\n }\n\n const adapterImport = adapterImports[0];\n\n if (adapterImport === undefined) {\n return undefined;\n }\n\n const plugin = adapterImport.specifiers.find(\n (specifier) =>\n specifier.type === \"ImportSpecifier\" &&\n specifier.imported.type === \"Identifier\" &&\n specifier.imported.name === \"spotPatch\" &&\n specifier.importKind !== \"type\",\n );\n\n if (plugin === undefined) {\n throw new Error(\n \"SpotPatch init cannot safely merge the existing @spotpatch/vite import.\",\n );\n }\n\n return plugin.local.name;\n}\n\nfunction unwrapExpression(expression: Expression): Expression {\n let current = expression;\n\n while (\n current.type === \"ParenthesizedExpression\" ||\n current.type === \"TSAsExpression\" ||\n current.type === \"TSSatisfiesExpression\" ||\n current.type === \"TSTypeAssertion\" ||\n current.type === \"TSNonNullExpression\"\n ) {\n current = current.expression;\n }\n\n return current;\n}\n\nfunction findDefaultExport(program: Program): ExportDefaultDeclaration {\n const exports = program.body.filter(\n (statement): statement is ExportDefaultDeclaration =>\n statement.type === \"ExportDefaultDeclaration\",\n );\n\n if (exports.length !== 1 || exports[0] === undefined) {\n throw new Error(\n \"SpotPatch init requires exactly one ESM default export in vite.config.\",\n );\n }\n\n return exports[0];\n}\n\nfunction findVariableInitializer(\n program: Program,\n name: string,\n): Expression | undefined {\n for (const statement of program.body) {\n if (statement.type !== \"VariableDeclaration\") {\n continue;\n }\n\n for (const declaration of statement.declarations) {\n if (\n declaration.id.type === \"Identifier\" &&\n declaration.id.name === name &&\n declaration.init !== null\n ) {\n return declaration.init;\n }\n }\n }\n\n return undefined;\n}\n\nfunction resolveConfigExpression(program: Program): Expression {\n const exported = findDefaultExport(program).declaration;\n\n if (\n exported.type === \"FunctionDeclaration\" ||\n exported.type === \"ClassDeclaration\" ||\n exported.type === \"TSInterfaceDeclaration\"\n ) {\n throw new Error(\n \"SpotPatch init requires vite.config to export a configuration expression.\",\n );\n }\n\n const expression = unwrapExpression(exported);\n const resolved =\n expression.type === \"Identifier\"\n ? findVariableInitializer(program, expression.name)\n : expression;\n\n if (resolved === undefined) {\n throw new Error(\"SpotPatch init could not resolve the vite.config export.\");\n }\n\n return unwrapExpression(resolved);\n}\n\nfunction resolveFactoryConfigObject(\n expression: Expression,\n): ObjectExpression | undefined {\n const factory = unwrapExpression(expression);\n\n if (\n factory.type !== \"ArrowFunctionExpression\" &&\n factory.type !== \"FunctionExpression\"\n ) {\n return undefined;\n }\n\n if (factory.body === null) {\n throw new Error(\n \"SpotPatch init cannot use a defineConfig callback without a body.\",\n );\n }\n\n if (factory.body.type !== \"BlockStatement\") {\n const returned = unwrapExpression(factory.body);\n return returned.type === \"ObjectExpression\" ? returned : undefined;\n }\n\n const returns: ReturnStatement[] = [];\n new Visitor({\n ReturnStatement(statement) {\n returns.push(statement);\n },\n }).visit({\n type: \"Program\",\n body: factory.body.body,\n sourceType: \"module\",\n hashbang: null,\n start: factory.body.start,\n end: factory.body.end,\n });\n\n const onlyReturn = returns.length === 1 ? returns[0] : undefined;\n\n if (onlyReturn?.argument == null) {\n throw new Error(\n \"SpotPatch init requires a defineConfig callback with exactly one top-level object return.\",\n );\n }\n\n const returned = unwrapExpression(onlyReturn.argument);\n\n if (returned.type !== \"ObjectExpression\") {\n throw new Error(\n \"SpotPatch init requires the defineConfig callback to return a configuration object directly.\",\n );\n }\n\n return returned;\n}\n\nfunction resolveConfigObject(program: Program): ObjectExpression {\n const expression = resolveConfigExpression(program);\n\n if (expression.type === \"ObjectExpression\") {\n return expression;\n }\n\n if (expression.type === \"CallExpression\") {\n const callee = unwrapExpression(expression.callee);\n const argument = expression.arguments[0];\n\n if (\n callee.type === \"Identifier\" &&\n callee.name === \"defineConfig\" &&\n expression.arguments.length === 1 &&\n argument !== undefined &&\n argument.type !== \"SpreadElement\"\n ) {\n const value = unwrapExpression(argument);\n\n if (value.type === \"ObjectExpression\") {\n return value;\n }\n\n const callbackObject = resolveFactoryConfigObject(value);\n\n if (callbackObject !== undefined) {\n return callbackObject;\n }\n }\n }\n\n throw new Error(\n \"SpotPatch init supports a configuration object or an object-returning callback passed to defineConfig.\",\n );\n}\n\nfunction propertyName(property: ObjectProperty): string | undefined {\n if (property.computed) {\n return undefined;\n }\n\n if (property.key.type === \"Identifier\") {\n return property.key.name;\n }\n\n if (property.key.type === \"Literal\" && typeof property.key.value === \"string\") {\n return property.key.value;\n }\n\n return undefined;\n}\n\nfunction findProperty(\n object: ObjectExpression,\n name: string,\n): ObjectProperty | undefined {\n const matches = object.properties.filter(\n (property): property is ObjectProperty =>\n property.type === \"Property\" && propertyName(property) === name,\n );\n\n if (matches.length > 1) {\n throw new Error(`SpotPatch init found duplicate ${name} properties.`);\n }\n\n return matches[0];\n}\n\nfunction lineIndentAt(source: string, offset: number): string {\n const lineStart = source.lastIndexOf(\"\\n\", Math.max(0, offset - 1)) + 1;\n return /^[\\t ]*/u.exec(source.slice(lineStart, offset))?.[0] ?? \"\";\n}\n\nfunction childIndent(source: string, object: ObjectExpression): string {\n const first = object.properties[0];\n\n if (first !== undefined) {\n return lineIndentAt(source, first.start);\n }\n\n return `${lineIndentAt(source, object.start)} `;\n}\n\nfunction initializedPluginCall(pluginName: string, trustedFastMode: boolean): string {\n const options = [\n \"dataFlow: {}\",\n ...(trustedFastMode ? [\"trustedFastMode: true\"] : []),\n ];\n return `${pluginName}({ ${options.join(\", \")} })`;\n}\n\nfunction directPluginCalls(\n plugins: ArrayExpression,\n pluginName: string,\n): readonly CallExpression[] {\n return plugins.elements.filter((element): element is CallExpression => {\n if (element?.type !== \"CallExpression\") {\n return false;\n }\n\n const callee = unwrapExpression(element.callee);\n return callee.type === \"Identifier\" && callee.name === pluginName;\n });\n}\n\nfunction enableInitializedOptions(\n magicString: MagicString,\n source: string,\n call: CallExpression,\n trustedFastMode: boolean,\n): void {\n if (call.arguments.length === 0) {\n magicString.overwrite(\n call.start,\n call.end,\n initializedPluginCall(source.slice(call.start, call.callee.end), trustedFastMode),\n );\n return;\n }\n\n const argument = call.arguments[0];\n\n if (\n call.arguments.length !== 1 ||\n argument === undefined ||\n argument.type === \"SpreadElement\"\n ) {\n throw new Error(\"SpotPatch init cannot safely update the spotPatch options.\");\n }\n\n const value = unwrapExpression(argument);\n\n if (value.type !== \"ObjectExpression\") {\n throw new Error(\"SpotPatch init requires spotPatch options to be an object.\");\n }\n\n if (value.properties.some((property) => property.type === \"SpreadElement\")) {\n throw new Error(\n \"SpotPatch init cannot prove dataFlow through spread spotPatch options.\",\n );\n }\n\n const dataFlowProperty = findProperty(value, \"dataFlow\");\n const trustedFastModeProperty = findProperty(value, \"trustedFastMode\");\n const missingProperties: string[] = [];\n\n if (dataFlowProperty === undefined) {\n missingProperties.push(\"dataFlow: {}\");\n } else {\n const dataFlowValue = unwrapExpression(dataFlowProperty.value);\n\n if (dataFlowValue.type === \"Literal\" && dataFlowValue.value === false) {\n magicString.overwrite(dataFlowValue.start, dataFlowValue.end, \"{}\");\n } else if (dataFlowValue.type !== \"ObjectExpression\") {\n throw new Error(\n \"SpotPatch init requires dataFlow to be false or an options object.\",\n );\n }\n }\n\n if (trustedFastMode && trustedFastModeProperty === undefined) {\n missingProperties.push(\"trustedFastMode: true\");\n } else if (trustedFastModeProperty !== undefined) {\n const propertyValue = unwrapExpression(trustedFastModeProperty.value);\n\n if (propertyValue.type !== \"Literal\" || typeof propertyValue.value !== \"boolean\") {\n throw new Error(\n \"SpotPatch init requires trustedFastMode to be a boolean literal.\",\n );\n }\n\n if (trustedFastMode && !propertyValue.value) {\n magicString.overwrite(propertyValue.start, propertyValue.end, \"true\");\n }\n }\n\n if (missingProperties.length === 0) return;\n\n const indent = childIndent(source, value);\n\n if (value.properties.length === 0) {\n magicString.appendLeft(value.end - 1, ` ${missingProperties.join(\", \")} `);\n } else {\n magicString.appendLeft(\n value.properties[0]?.start ?? value.end - 1,\n `${missingProperties.join(`,\\n${indent}`)},\\n${indent}`,\n );\n }\n}\n\nfunction addPluginCall(\n magicString: MagicString,\n source: string,\n config: ObjectExpression,\n pluginName: string,\n trustedFastModeAvailable: boolean,\n): void {\n const pluginsProperty = findProperty(config, \"plugins\");\n const call = initializedPluginCall(pluginName, trustedFastModeAvailable);\n\n if (pluginsProperty === undefined) {\n const indent = childIndent(source, config);\n\n if (config.properties.length === 0) {\n magicString.appendLeft(config.end - 1, `\\n${indent}plugins: [${call}],\\n`);\n } else {\n magicString.appendLeft(\n config.properties[0]?.start ?? config.end - 1,\n `plugins: [${call}],\\n${indent}`,\n );\n }\n\n return;\n }\n\n const value = unwrapExpression(pluginsProperty.value);\n\n if (value.type !== \"ArrayExpression\") {\n throw new Error(\"SpotPatch init requires vite.config plugins to be an array.\");\n }\n\n const existing = directPluginCalls(value, pluginName);\n\n if (existing.length > 1) {\n throw new Error(\"SpotPatch init found duplicate spotPatch plugins.\");\n }\n\n if (existing[0] !== undefined) {\n enableInitializedOptions(\n magicString,\n source,\n existing[0],\n trustedFastModeAvailable,\n );\n\n return;\n }\n\n const first = value.elements.find((element) => element !== null);\n\n if (first === undefined) {\n magicString.appendLeft(value.end - 1, call);\n } else if (!source.slice(value.start, first.start).includes(\"\\n\")) {\n magicString.appendLeft(first.start, `${call}, `);\n } else {\n magicString.appendLeft(\n first.start,\n `${call},\\n${lineIndentAt(source, first.start)}`,\n );\n }\n}\n\nfunction transformViteConfig(\n absolutePath: string,\n source: string,\n trustedFastModeAvailable: boolean,\n): string {\n const { program } = parseModule(absolutePath, source);\n const config = resolveConfigObject(program);\n const existingPluginName = importedPluginName(program);\n const pluginName = existingPluginName ?? choosePluginName(program);\n const magicString = new MagicString(source);\n\n if (existingPluginName === undefined) {\n const specifier =\n pluginName === \"spotPatch\" ? \"spotPatch\" : `spotPatch as ${pluginName}`;\n const quote = importQuote(source, program);\n insertStaticImport(\n magicString,\n program,\n `import { ${specifier} } from ${quote}${ADAPTER_PACKAGE_NAME}${quote};`,\n );\n }\n\n addPluginCall(magicString, source, config, pluginName, trustedFastModeAvailable);\n return magicString.toString();\n}\n\nasync function findViteConfig(appRoot: string): Promise<string> {\n const candidates = (\n await Promise.all(\n CONFIG_FILE_NAMES.map(async (name) => {\n const absolutePath = path.join(appRoot, name);\n return (await integrationPathExists(absolutePath)) ? absolutePath : undefined;\n }),\n )\n ).filter((value): value is string => value !== undefined);\n\n if (candidates.length !== 1 || candidates[0] === undefined) {\n throw new Error(\"SpotPatch init requires exactly one supported vite.config file.\");\n }\n\n return candidates[0];\n}\n\nexport async function planViteIntegration(\n directory = process.cwd(),\n): Promise<ViteIntegrationPlan> {\n const appRoot = path.resolve(directory);\n const configPath = await findViteConfig(appRoot);\n const [configSource, discoveredCheck] = await Promise.all([\n readIntegrationFile(configPath),\n discoverProjectValidationCheck({\n appRoot,\n timeoutMs: DEFAULT_AGENT_LIMITS.checkTimeoutMs,\n }),\n ]);\n const trustedFastModeAvailable = discoveredCheck !== undefined;\n const nextContent = transformViteConfig(\n configPath,\n configSource,\n trustedFastModeAvailable,\n );\n const change = createIntegrationFileChange(\n appRoot,\n configPath,\n nextContent,\n configSource,\n );\n\n return Object.freeze({\n appRoot,\n changes: Object.freeze(change === undefined ? [] : [change]),\n trustedFastModeAvailable,\n });\n}\n\nexport async function applyViteIntegrationPlan(\n plan: ViteIntegrationPlan,\n): Promise<void> {\n await applyIntegrationPlan(plan);\n}\n\nexport async function checkViteIntegration(\n directory = process.cwd(),\n): Promise<ViteIntegrationCheck> {\n try {\n const plan = await planViteIntegration(directory);\n const issues = plan.changes.map(\n (change) => `INTEGRATION_REQUIRED:${change.relativePath}`,\n );\n return Object.freeze({\n appRoot: plan.appRoot,\n issues: Object.freeze(issues),\n ok: issues.length === 0,\n trustedFastModeAvailable: plan.trustedFastModeAvailable,\n });\n } catch (error: unknown) {\n return Object.freeze({\n appRoot: path.resolve(directory),\n issues: Object.freeze([\n error instanceof Error ? error.message : \"SpotPatch integration check failed.\",\n ]),\n ok: false,\n trustedFastModeAvailable: false,\n });\n }\n}\n","import { spawn } from \"node:child_process\";\nimport { access, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport type SupportedPackageManager = \"npm\" | \"pnpm\";\n\ninterface ApplicationManifest {\n readonly packageManager?: unknown;\n}\n\nexport interface InstallCommand {\n readonly arguments: readonly string[];\n readonly executable: string;\n}\n\nconst VERSION_PATTERN = /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u;\n\ninterface AdapterManifest {\n readonly version?: unknown;\n}\n\nasync function pathExists(absolutePath: string): Promise<boolean> {\n try {\n await access(absolutePath);\n return true;\n } catch (error: unknown) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n (error.code === \"ENOENT\" || error.code === \"ENOTDIR\")\n ) {\n return false;\n }\n\n throw error;\n }\n}\n\nexport async function detectPackageManager(\n appRoot = process.cwd(),\n userAgent = process.env.npm_config_user_agent ?? \"\",\n): Promise<SupportedPackageManager> {\n const manifestPath = path.join(appRoot, \"package.json\");\n const manifest = JSON.parse(\n await readFile(manifestPath, \"utf8\"),\n ) as ApplicationManifest;\n const declared = manifest.packageManager;\n\n if (typeof declared === \"string\") {\n const name = declared.split(\"@\", 1)[0];\n\n if (name === \"pnpm\" || name === \"npm\") {\n return name;\n }\n\n throw new Error(\n `SpotPatch setup supports npm and pnpm projects; package.json declares ${declared}.`,\n );\n }\n\n const [hasPnpmLock, hasNpmLock] = await Promise.all([\n pathExists(path.join(appRoot, \"pnpm-lock.yaml\")),\n pathExists(path.join(appRoot, \"package-lock.json\")),\n ]);\n\n if (hasPnpmLock !== hasNpmLock) {\n return hasPnpmLock ? \"pnpm\" : \"npm\";\n }\n\n if (hasPnpmLock && hasNpmLock) {\n throw new Error(\n \"SpotPatch setup found both pnpm-lock.yaml and package-lock.json; remove the stale lockfile or run installation and init separately.\",\n );\n }\n\n if (userAgent.startsWith(\"pnpm/\")) {\n return \"pnpm\";\n }\n\n if (userAgent.startsWith(\"npm/\")) {\n return \"npm\";\n }\n\n throw new Error(\n \"SpotPatch setup could not determine npm or pnpm; run installation and init separately.\",\n );\n}\n\nexport function createInstallCommand(\n packageManager: SupportedPackageManager,\n version: string,\n platform = process.platform,\n): InstallCommand {\n if (!VERSION_PATTERN.test(version)) {\n throw new Error(\"SpotPatch setup could not determine its package version.\");\n }\n\n const packageSpecifier = `@spotpatch/vite@${version}`;\n\n return Object.freeze({\n executable: platform === \"win32\" ? `${packageManager}.cmd` : packageManager,\n arguments: Object.freeze(\n packageManager === \"pnpm\"\n ? [\"add\", \"-D\", packageSpecifier]\n : [\"install\", \"--save-dev\", packageSpecifier],\n ),\n });\n}\n\nexport async function readCurrentAdapterVersion(): Promise<string> {\n const manifest = JSON.parse(\n await readFile(new URL(\"../package.json\", import.meta.url), \"utf8\"),\n ) as AdapterManifest;\n const version = manifest.version;\n\n if (typeof version !== \"string\" || !VERSION_PATTERN.test(version)) {\n throw new Error(\"SpotPatch setup could not determine its package version.\");\n }\n\n return version;\n}\n\nexport async function installCurrentAdapter(\n packageManager: SupportedPackageManager,\n appRoot = process.cwd(),\n): Promise<void> {\n const version = await readCurrentAdapterVersion();\n const command = createInstallCommand(packageManager, version);\n\n process.stdout.write(\n `[spotpatch:vite] installing @spotpatch/vite@${version} with ${packageManager}...\\n`,\n );\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(command.executable, command.arguments, {\n cwd: appRoot,\n env: process.env,\n shell: false,\n stdio: \"inherit\",\n });\n\n child.once(\"error\", reject);\n child.once(\"exit\", (code, signal) => {\n if (code === 0) {\n resolve();\n return;\n }\n\n reject(\n new Error(\n `SpotPatch setup installation failed (${signal ?? `exit ${String(code)}`}).`,\n ),\n );\n });\n });\n}\n"],"mappings":";;;AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,qBAAqB;AAC9B,OAAOC,WAAU;;;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;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,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