@leadconnector/vite-tanstack-config 0.3.2 → 0.3.3-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,544 +1,414 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var src_exports = {};
32
- __export(src_exports, {
33
- defineConfig: () => defineConfig
34
- });
35
- module.exports = __toCommonJS(src_exports);
36
- var import_vibe_tagger = require("@leadconnector/vibe-tagger");
37
- var import_node_path2 = require("path");
38
- var import_vite2 = require("vite");
39
-
40
- // src/bundledDev.ts
41
- var import_node_module = require("module");
42
- var import_promises = require("fs/promises");
43
- var import_node_path = require("path");
44
- var BUNDLED_DEV_ENV_VAR = "VIBE_FEATURE_BUNDLED_DEV";
45
- var CSS_URL_VIRTUAL_PREFIX = "\0vibe-bundled-dev-css-url:";
46
- var CSS_URL_VIRTUAL_SUFFIX = ".shim.js";
47
- var NODEJS_COMPAT_DEFAULT_ON_DATE = "2026-08-04";
48
- var DEFAULT_SANDBOX_SERVER_DIR = "dist/server";
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _leadconnector_vibe_tagger = require("@leadconnector/vibe-tagger");
3
+ let node_path = require("node:path");
4
+ let vite = require("vite");
5
+ let node_module = require("node:module");
6
+ let node_fs_promises = require("node:fs/promises");
7
+ //#region src/bundledDev.ts
8
+ const BUNDLED_DEV_ENV_VAR = "VIBE_FEATURE_BUNDLED_DEV";
9
+ const CSS_URL_VIRTUAL_PREFIX = "\0vibe-bundled-dev-css-url:";
10
+ const CSS_URL_VIRTUAL_SUFFIX = ".shim.js";
11
+ const NODEJS_COMPAT_DEFAULT_ON_DATE = "2026-08-04";
12
+ const DEFAULT_SANDBOX_SERVER_DIR = "dist/server";
49
13
  function bundledDevRequested() {
50
- return process.env[BUNDLED_DEV_ENV_VAR] === "true";
14
+ return process.env[BUNDLED_DEV_ENV_VAR] === "true";
51
15
  }
52
16
  function viteVersionSupportsBundledDev(version) {
53
- if (!version || version.includes("-"))
54
- return false;
55
- const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
56
- if (!match)
57
- return false;
58
- const major = Number(match[1]);
59
- const minor = Number(match[2]);
60
- return major > 8 || major === 8 && minor >= 1;
17
+ if (!version || version.includes("-")) return false;
18
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
19
+ if (!match) return false;
20
+ const major = Number(match[1]);
21
+ const minor = Number(match[2]);
22
+ return major > 8 || major === 8 && minor >= 1;
61
23
  }
62
24
  function resolveInstalledViteVersion(cwd = process.cwd()) {
63
- try {
64
- const manifest = (0, import_node_module.createRequire)(`${cwd}/package.json`)(
65
- "vite/package.json"
66
- );
67
- return typeof manifest.version === "string" ? manifest.version : void 0;
68
- } catch {
69
- return void 0;
70
- }
71
- }
25
+ try {
26
+ const manifest = (0, node_module.createRequire)(`${cwd}/package.json`)("vite/package.json");
27
+ return typeof manifest.version === "string" ? manifest.version : void 0;
28
+ } catch {
29
+ return;
30
+ }
31
+ }
32
+ /**
33
+ * Bundled dev does not emit CSS assets for `?url` imports. Convert them to a
34
+ * data URL backed by Vite's inline CSS transform so callers retain a URL.
35
+ */
72
36
  function bundledDevCssUrlShim() {
73
- return {
74
- name: "vibe-bundled-dev-css-url-shim",
75
- apply: "serve",
76
- enforce: "pre",
77
- async resolveId(id, importer) {
78
- if (!id.endsWith(".css?url"))
79
- return null;
80
- const resolved = await this.resolve(id.slice(0, -4), importer, {
81
- skipSelf: true
82
- });
83
- return resolved ? `${CSS_URL_VIRTUAL_PREFIX}${resolved.id}${CSS_URL_VIRTUAL_SUFFIX}` : null;
84
- },
85
- load(id) {
86
- if (!id.startsWith(CSS_URL_VIRTUAL_PREFIX) || !id.endsWith(CSS_URL_VIRTUAL_SUFFIX)) {
87
- return null;
88
- }
89
- const cssId = id.slice(
90
- CSS_URL_VIRTUAL_PREFIX.length,
91
- -CSS_URL_VIRTUAL_SUFFIX.length
92
- );
93
- const inlineSpecifier = cssId.includes("?") ? `${cssId}&inline` : `${cssId}?inline`;
94
- return [
95
- `import css from ${JSON.stringify(inlineSpecifier)};`,
96
- 'const b64 = typeof Buffer !== "undefined" ? Buffer.from(css, "utf8").toString("base64") : btoa(unescape(encodeURIComponent(css)));',
97
- 'export default "data:text/css;base64," + b64;'
98
- ].join("\n");
99
- }
100
- };
101
- }
37
+ return {
38
+ name: "vibe-bundled-dev-css-url-shim",
39
+ apply: "serve",
40
+ enforce: "pre",
41
+ async resolveId(id, importer) {
42
+ if (!id.endsWith(".css?url")) return null;
43
+ const resolved = await this.resolve(id.slice(0, -4), importer, { skipSelf: true });
44
+ return resolved ? `${CSS_URL_VIRTUAL_PREFIX}${resolved.id}${CSS_URL_VIRTUAL_SUFFIX}` : null;
45
+ },
46
+ load(id) {
47
+ if (!id.startsWith(CSS_URL_VIRTUAL_PREFIX) || !id.endsWith(CSS_URL_VIRTUAL_SUFFIX)) return null;
48
+ const cssId = id.slice(26, -8);
49
+ const inlineSpecifier = cssId.includes("?") ? `${cssId}&inline` : `${cssId}?inline`;
50
+ return [
51
+ `import css from ${JSON.stringify(inlineSpecifier)};`,
52
+ "const b64 = typeof Buffer !== \"undefined\" ? Buffer.from(css, \"utf8\").toString(\"base64\") : btoa(unescape(encodeURIComponent(css)));",
53
+ "export default \"data:text/css;base64,\" + b64;"
54
+ ].join("\n");
55
+ }
56
+ };
57
+ }
58
+ /**
59
+ * Workers enables nodejs_compat by default from the compatibility date below,
60
+ * so Nitro's generated flag becomes redundant (and triggers Wrangler advice).
61
+ */
102
62
  function isCanonicalCompatibilityDate(value) {
103
- return /^\d{4}-\d{2}-\d{2}$/.test(value);
63
+ return /^\d{4}-\d{2}-\d{2}$/.test(value);
104
64
  }
105
65
  function stripRedundantNodejsCompatFlag(serverDir = DEFAULT_SANDBOX_SERVER_DIR) {
106
- let root = process.cwd();
107
- let warn = (message) => console.warn(message);
108
- return {
109
- name: "vibe-strip-redundant-nodejs-compat",
110
- apply: "build",
111
- configResolved(config) {
112
- root = config.root;
113
- if (typeof config.logger?.warn === "function") {
114
- warn = config.logger.warn.bind(config.logger);
115
- }
116
- },
117
- buildApp: {
118
- order: "post",
119
- async handler() {
120
- const configPath = (0, import_node_path.join)(
121
- (0, import_node_path.isAbsolute)(serverDir) ? serverDir : (0, import_node_path.resolve)(root, serverDir),
122
- "wrangler.json"
123
- );
124
- let parsed;
125
- try {
126
- parsed = JSON.parse(await (0, import_promises.readFile)(configPath, "utf8"));
127
- } catch {
128
- return;
129
- }
130
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
131
- return;
132
- }
133
- const config = parsed;
134
- if (typeof config.compatibility_date !== "string" || !isCanonicalCompatibilityDate(config.compatibility_date) || config.compatibility_date < NODEJS_COMPAT_DEFAULT_ON_DATE || !Array.isArray(config.compatibility_flags)) {
135
- return;
136
- }
137
- const flags = config.compatibility_flags.filter(
138
- (flag) => flag !== "nodejs_compat"
139
- );
140
- if (flags.length === config.compatibility_flags.length)
141
- return;
142
- try {
143
- await (0, import_promises.writeFile)(
144
- configPath,
145
- `${JSON.stringify({ ...config, compatibility_flags: flags }, null, 2)}
146
- `
147
- );
148
- } catch {
149
- warn(
150
- `[@leadconnector/vite-tanstack-config] Unable to remove redundant nodejs_compat from ${configPath}; continuing with the generated configuration.`
151
- );
152
- }
153
- }
154
- }
155
- };
156
- }
157
-
158
- // src/diagnostics.ts
159
- var SSR_CAPTURE_KEY = "__VIBE_TANSTACK_CAPTURE_SSR_ERROR__";
160
- var HANDLER_RAN_KEY = "__VIBE_TANSTACK_HANDLER_RAN__";
161
- var SERVER_FN_SEND_KEY = "__VIBE_TANSTACK_SERVER_FN_HMR_SEND__";
162
- var MAX_JSON_LENGTH = 6e3;
163
- var MAX_STRING_LENGTH = 2e3;
164
- var MAX_ITEMS = 20;
165
- var MAX_DEPTH = 4;
166
- var ERROR_FIELDS = [
167
- "name",
168
- "message",
169
- "plugin",
170
- "pluginCode",
171
- "id",
172
- "moduleId",
173
- "hook",
174
- "code",
175
- "loc",
176
- "frame",
177
- "stack",
178
- "cause"
66
+ let root = process.cwd();
67
+ let warn = (message) => console.warn(message);
68
+ return {
69
+ name: "vibe-strip-redundant-nodejs-compat",
70
+ apply: "build",
71
+ configResolved(config) {
72
+ root = config.root;
73
+ if (typeof config.logger?.warn === "function") warn = config.logger.warn.bind(config.logger);
74
+ },
75
+ buildApp: {
76
+ order: "post",
77
+ async handler() {
78
+ const configPath = (0, node_path.join)((0, node_path.isAbsolute)(serverDir) ? serverDir : (0, node_path.resolve)(root, serverDir), "wrangler.json");
79
+ let parsed;
80
+ try {
81
+ parsed = JSON.parse(await (0, node_fs_promises.readFile)(configPath, "utf8"));
82
+ } catch {
83
+ return;
84
+ }
85
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return;
86
+ const config = parsed;
87
+ if (typeof config.compatibility_date !== "string" || !isCanonicalCompatibilityDate(config.compatibility_date) || config.compatibility_date < NODEJS_COMPAT_DEFAULT_ON_DATE || !Array.isArray(config.compatibility_flags)) return;
88
+ const flags = config.compatibility_flags.filter((flag) => flag !== "nodejs_compat");
89
+ if (flags.length === config.compatibility_flags.length) return;
90
+ try {
91
+ await (0, node_fs_promises.writeFile)(configPath, `${JSON.stringify({
92
+ ...config,
93
+ compatibility_flags: flags
94
+ }, null, 2)}\n`);
95
+ } catch {
96
+ warn(`[@leadconnector/vite-tanstack-config] Unable to remove redundant nodejs_compat from ${configPath}; continuing with the generated configuration.`);
97
+ }
98
+ }
99
+ }
100
+ };
101
+ }
102
+ //#endregion
103
+ //#region src/diagnostics.ts
104
+ const SSR_CAPTURE_KEY = "__VIBE_TANSTACK_CAPTURE_SSR_ERROR__";
105
+ const HANDLER_RAN_KEY = "__VIBE_TANSTACK_HANDLER_RAN__";
106
+ const SERVER_FN_SEND_KEY = "__VIBE_TANSTACK_SERVER_FN_HMR_SEND__";
107
+ const MAX_JSON_LENGTH = 6e3;
108
+ const MAX_STRING_LENGTH = 2e3;
109
+ const MAX_ITEMS = 20;
110
+ const MAX_DEPTH = 4;
111
+ const ERROR_FIELDS = [
112
+ "name",
113
+ "message",
114
+ "plugin",
115
+ "pluginCode",
116
+ "id",
117
+ "moduleId",
118
+ "hook",
119
+ "code",
120
+ "loc",
121
+ "frame",
122
+ "stack",
123
+ "cause"
179
124
  ];
180
125
  function truncate(value, max = MAX_STRING_LENGTH) {
181
- return value.length > max ? `${value.slice(0, max)}...[truncated]` : value;
126
+ return value.length > max ? `${value.slice(0, max)}...[truncated]` : value;
182
127
  }
183
128
  function readProperty(value, key) {
184
- try {
185
- return value[key];
186
- } catch (error) {
187
- return `[unreadable: ${error instanceof Error ? error.message : String(error)}]`;
188
- }
129
+ try {
130
+ return value[key];
131
+ } catch (error) {
132
+ return `[unreadable: ${error instanceof Error ? error.message : String(error)}]`;
133
+ }
189
134
  }
190
135
  function describePrimitive(value) {
191
- if (typeof value === "symbol") {
192
- return value.description ? `Symbol(${value.description})` : "Symbol()";
193
- }
194
- if (typeof value === "function") {
195
- return `[function ${value.name || "anonymous"}]`;
196
- }
197
- return String(value);
136
+ if (typeof value === "symbol") return value.description ? `Symbol(${value.description})` : "Symbol()";
137
+ if (typeof value === "function") return `[function ${value.name || "anonymous"}]`;
138
+ return String(value);
198
139
  }
199
140
  function serializeDiagnosticValue(value, depth = 0, seen = /* @__PURE__ */ new WeakSet()) {
200
- if (value == null)
201
- return value;
202
- if (typeof value === "string")
203
- return truncate(value);
204
- if (typeof value === "number" || typeof value === "boolean")
205
- return value;
206
- if (typeof value !== "object")
207
- return describePrimitive(value);
208
- if (seen.has(value))
209
- return "[circular]";
210
- if (depth >= MAX_DEPTH)
211
- return "[max depth]";
212
- seen.add(value);
213
- try {
214
- if (Array.isArray(value)) {
215
- const entries = value.slice(0, MAX_ITEMS).map((entry) => serializeDiagnosticValue(entry, depth + 1, seen));
216
- if (value.length > MAX_ITEMS) {
217
- entries.push(`[${value.length - MAX_ITEMS} items truncated]`);
218
- }
219
- return entries;
220
- }
221
- const output = {};
222
- for (const field of ERROR_FIELDS) {
223
- if (!(field in value))
224
- continue;
225
- const nested = readProperty(value, field);
226
- if (nested == null || nested === "")
227
- continue;
228
- output[field] = serializeDiagnosticValue(nested, depth + 1, seen);
229
- }
230
- const nestedErrors = readProperty(value, "errors");
231
- if (nestedErrors != null && nestedErrors !== "") {
232
- output.errors = serializeDiagnosticValue(
233
- Array.isArray(nestedErrors) ? nestedErrors.slice(0, MAX_ITEMS) : nestedErrors,
234
- depth + 1,
235
- seen
236
- );
237
- }
238
- if (Object.keys(output).length > 0)
239
- return output;
240
- const keys = Object.keys(value);
241
- for (const key of keys.slice(0, MAX_ITEMS)) {
242
- const nested = readProperty(value, key);
243
- if (nested == null || nested === "")
244
- continue;
245
- output[truncate(key, 200)] = serializeDiagnosticValue(
246
- nested,
247
- depth + 1,
248
- seen
249
- );
250
- }
251
- if (keys.length > MAX_ITEMS) {
252
- output.properties_truncated = keys.length - MAX_ITEMS;
253
- }
254
- return Object.keys(output).length > 0 ? output : Object.prototype.toString.call(value);
255
- } catch (error) {
256
- return `[unreadable object: ${error instanceof Error ? error.message : String(error)}]`;
257
- } finally {
258
- seen.delete(value);
259
- }
141
+ if (value == null) return value;
142
+ if (typeof value === "string") return truncate(value);
143
+ if (typeof value === "number" || typeof value === "boolean") return value;
144
+ if (typeof value !== "object") return describePrimitive(value);
145
+ if (seen.has(value)) return "[circular]";
146
+ if (depth >= MAX_DEPTH) return "[max depth]";
147
+ seen.add(value);
148
+ try {
149
+ if (Array.isArray(value)) {
150
+ const entries = value.slice(0, MAX_ITEMS).map((entry) => serializeDiagnosticValue(entry, depth + 1, seen));
151
+ if (value.length > MAX_ITEMS) entries.push(`[${value.length - MAX_ITEMS} items truncated]`);
152
+ return entries;
153
+ }
154
+ const output = {};
155
+ for (const field of ERROR_FIELDS) {
156
+ if (!(field in value)) continue;
157
+ const nested = readProperty(value, field);
158
+ if (nested == null || nested === "") continue;
159
+ output[field] = serializeDiagnosticValue(nested, depth + 1, seen);
160
+ }
161
+ const nestedErrors = readProperty(value, "errors");
162
+ if (nestedErrors != null && nestedErrors !== "") output.errors = serializeDiagnosticValue(Array.isArray(nestedErrors) ? nestedErrors.slice(0, MAX_ITEMS) : nestedErrors, depth + 1, seen);
163
+ if (Object.keys(output).length > 0) return output;
164
+ const keys = Object.keys(value);
165
+ for (const key of keys.slice(0, MAX_ITEMS)) {
166
+ const nested = readProperty(value, key);
167
+ if (nested == null || nested === "") continue;
168
+ output[truncate(key, 200)] = serializeDiagnosticValue(nested, depth + 1, seen);
169
+ }
170
+ if (keys.length > MAX_ITEMS) output.properties_truncated = keys.length - MAX_ITEMS;
171
+ return Object.keys(output).length > 0 ? output : Object.prototype.toString.call(value);
172
+ } catch (error) {
173
+ return `[unreadable object: ${error instanceof Error ? error.message : String(error)}]`;
174
+ } finally {
175
+ seen.delete(value);
176
+ }
260
177
  }
261
178
  function stringifyDiagnosticPayload(value) {
262
- const serialized = serializeDiagnosticValue(value);
263
- const full = JSON.stringify(serialized);
264
- if (full.length <= MAX_JSON_LENGTH)
265
- return full;
266
- const compact = serializeDiagnosticValue(value, 2);
267
- const compactPayload = compact && typeof compact === "object" && !Array.isArray(compact) ? { ...compact, diagnostics_truncated: true } : { diagnostics_truncated: true, value: compact };
268
- const compactJson = JSON.stringify(compactPayload);
269
- if (compactJson.length <= MAX_JSON_LENGTH)
270
- return compactJson;
271
- return JSON.stringify({
272
- diagnostics_truncated: true,
273
- message: "Diagnostic payload exceeded output budget."
274
- });
179
+ const serialized = serializeDiagnosticValue(value);
180
+ const full = JSON.stringify(serialized);
181
+ if (full.length <= MAX_JSON_LENGTH) return full;
182
+ const compact = serializeDiagnosticValue(value, 2);
183
+ const compactPayload = compact && typeof compact === "object" && !Array.isArray(compact) ? {
184
+ ...compact,
185
+ diagnostics_truncated: true
186
+ } : {
187
+ diagnostics_truncated: true,
188
+ value: compact
189
+ };
190
+ const compactJson = JSON.stringify(compactPayload);
191
+ if (compactJson.length <= MAX_JSON_LENGTH) return compactJson;
192
+ return JSON.stringify({
193
+ diagnostics_truncated: true,
194
+ message: "Diagnostic payload exceeded output budget."
195
+ });
275
196
  }
276
197
  function boundedData(value) {
277
- try {
278
- const parsed = JSON.parse(stringifyDiagnosticPayload(value));
279
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : { value: parsed };
280
- } catch {
281
- return { message: "Diagnostic payload could not be serialized." };
282
- }
198
+ try {
199
+ const parsed = JSON.parse(stringifyDiagnosticPayload(value));
200
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : { value: parsed };
201
+ } catch {
202
+ return { message: "Diagnostic payload could not be serialized." };
203
+ }
283
204
  }
284
205
  function createBuildErrorDiagnostics() {
285
- let emitted = false;
286
- const emit = (error) => {
287
- if (!error || emitted)
288
- return;
289
- emitted = true;
290
- try {
291
- const output = `
292
- [vibe-build-error-diagnostics]
293
- ${stringifyDiagnosticPayload(
294
- error
295
- )}
296
- [/vibe-build-error-diagnostics]
297
- `;
298
- let written = false;
299
- const write = () => {
300
- if (written)
301
- return;
302
- written = true;
303
- try {
304
- process.stderr.write(output);
305
- } catch {
306
- }
307
- };
308
- setImmediate(write);
309
- process.once("exit", write);
310
- } catch {
311
- }
312
- };
313
- return {
314
- name: "vibe-build-error-diagnostics",
315
- apply: "build",
316
- buildEnd: emit,
317
- renderError: emit
318
- };
206
+ let emitted = false;
207
+ const emit = (error) => {
208
+ if (!error || emitted) return;
209
+ emitted = true;
210
+ try {
211
+ const output = `\n[vibe-build-error-diagnostics]\n${stringifyDiagnosticPayload(error)}\n[/vibe-build-error-diagnostics]\n`;
212
+ let written = false;
213
+ const write = () => {
214
+ if (written) return;
215
+ written = true;
216
+ try {
217
+ process.stderr.write(output);
218
+ } catch {}
219
+ };
220
+ setImmediate(write);
221
+ process.once("exit", write);
222
+ } catch {}
223
+ };
224
+ return {
225
+ name: "vibe-build-error-diagnostics",
226
+ apply: "build",
227
+ buildEnd: emit,
228
+ renderError: emit
229
+ };
319
230
  }
320
231
  function isEsbuildMessageArray(errors) {
321
- return Array.isArray(errors) && errors.length > 0 && errors.every(
322
- (entry) => entry != null && typeof entry === "object" && "text" in entry && "location" in entry
323
- );
232
+ return Array.isArray(errors) && errors.length > 0 && errors.every((entry) => entry != null && typeof entry === "object" && "text" in entry && "location" in entry);
324
233
  }
325
234
  function isBuildError(error) {
326
- const messagePattern = /transform failed with \d+ error|failed to parse source/i;
327
- if (typeof error === "string")
328
- return messagePattern.test(error);
329
- if (!error || typeof error !== "object")
330
- return false;
331
- const record = error;
332
- if (typeof record.plugin === "string" && (record.plugin.startsWith("vite:") || record.plugin.startsWith("esbuild:"))) {
333
- return true;
334
- }
335
- if (record.frame != null && record.loc != null)
336
- return true;
337
- if (isEsbuildMessageArray(record.errors))
338
- return true;
339
- return typeof record.message === "string" && messagePattern.test(record.message);
235
+ const messagePattern = /transform failed with \d+ error|failed to parse source/i;
236
+ if (typeof error === "string") return messagePattern.test(error);
237
+ if (!error || typeof error !== "object") return false;
238
+ const record = error;
239
+ if (typeof record.plugin === "string" && (record.plugin.startsWith("vite:") || record.plugin.startsWith("esbuild:"))) return true;
240
+ if (record.frame != null && record.loc != null) return true;
241
+ if (isEsbuildMessageArray(record.errors)) return true;
242
+ return typeof record.message === "string" && messagePattern.test(record.message);
340
243
  }
341
244
  function isRequestResponseModule(id) {
342
- const normalized = id.replaceAll("\\", "/").split("?")[0];
343
- return normalized.includes(
344
- "/@tanstack/start-server-core/src/request-response.ts"
345
- ) || normalized.includes(
346
- "/@tanstack/start-server-core/dist/esm/request-response.js"
347
- );
245
+ const normalized = id.replaceAll("\\", "/").split("?")[0];
246
+ return normalized.includes("/@tanstack/start-server-core/src/request-response.ts") || normalized.includes("/@tanstack/start-server-core/dist/esm/request-response.js");
348
247
  }
349
248
  function isServerFunctionsHandlerModule(id) {
350
- const normalized = id.replaceAll("\\", "/").split("?")[0];
351
- return normalized.includes(
352
- "/@tanstack/start-server-core/src/server-functions-handler.ts"
353
- ) || normalized.includes(
354
- "/@tanstack/start-server-core/dist/esm/server-functions-handler.js"
355
- );
356
- }
357
- var runtimeGlobal = globalThis;
358
- var ssrGlobalRegistrations = [];
359
- var serverFnGlobalRegistrations = [];
360
- var originalSsrCapture;
361
- var originalSsrMark;
362
- var originalServerFnSend;
249
+ const normalized = id.replaceAll("\\", "/").split("?")[0];
250
+ return normalized.includes("/@tanstack/start-server-core/src/server-functions-handler.ts") || normalized.includes("/@tanstack/start-server-core/dist/esm/server-functions-handler.js");
251
+ }
252
+ const runtimeGlobal = globalThis;
253
+ const ssrGlobalRegistrations = [];
254
+ const serverFnGlobalRegistrations = [];
255
+ let originalSsrCapture;
256
+ let originalSsrMark;
257
+ let originalServerFnSend;
363
258
  function snapshotGlobal(key) {
364
- return {
365
- existed: Object.prototype.hasOwnProperty.call(runtimeGlobal, key),
366
- value: runtimeGlobal[key]
367
- };
259
+ return {
260
+ existed: Object.prototype.hasOwnProperty.call(runtimeGlobal, key),
261
+ value: runtimeGlobal[key]
262
+ };
368
263
  }
369
264
  function restoreGlobal(key, snapshot) {
370
- if (snapshot.existed)
371
- runtimeGlobal[key] = snapshot.value;
372
- else
373
- delete runtimeGlobal[key];
265
+ if (snapshot.existed) runtimeGlobal[key] = snapshot.value;
266
+ else delete runtimeGlobal[key];
374
267
  }
375
268
  function registerSsrGlobals(registration) {
376
- if (ssrGlobalRegistrations.length === 0) {
377
- originalSsrCapture = snapshotGlobal(SSR_CAPTURE_KEY);
378
- originalSsrMark = snapshotGlobal(HANDLER_RAN_KEY);
379
- }
380
- ssrGlobalRegistrations.push(registration);
381
- runtimeGlobal[SSR_CAPTURE_KEY] = registration.capture;
382
- runtimeGlobal[HANDLER_RAN_KEY] = registration.mark;
269
+ if (ssrGlobalRegistrations.length === 0) {
270
+ originalSsrCapture = snapshotGlobal(SSR_CAPTURE_KEY);
271
+ originalSsrMark = snapshotGlobal(HANDLER_RAN_KEY);
272
+ }
273
+ ssrGlobalRegistrations.push(registration);
274
+ runtimeGlobal[SSR_CAPTURE_KEY] = registration.capture;
275
+ runtimeGlobal[HANDLER_RAN_KEY] = registration.mark;
383
276
  }
384
277
  function unregisterSsrGlobals(registration) {
385
- const index = ssrGlobalRegistrations.indexOf(registration);
386
- if (index === -1)
387
- return;
388
- ssrGlobalRegistrations.splice(index, 1);
389
- const active = ssrGlobalRegistrations.at(-1);
390
- if (active) {
391
- runtimeGlobal[SSR_CAPTURE_KEY] = active.capture;
392
- runtimeGlobal[HANDLER_RAN_KEY] = active.mark;
393
- return;
394
- }
395
- restoreGlobal(SSR_CAPTURE_KEY, originalSsrCapture);
396
- restoreGlobal(HANDLER_RAN_KEY, originalSsrMark);
397
- originalSsrCapture = void 0;
398
- originalSsrMark = void 0;
278
+ const index = ssrGlobalRegistrations.indexOf(registration);
279
+ if (index === -1) return;
280
+ ssrGlobalRegistrations.splice(index, 1);
281
+ const active = ssrGlobalRegistrations.at(-1);
282
+ if (active) {
283
+ runtimeGlobal[SSR_CAPTURE_KEY] = active.capture;
284
+ runtimeGlobal[HANDLER_RAN_KEY] = active.mark;
285
+ return;
286
+ }
287
+ restoreGlobal(SSR_CAPTURE_KEY, originalSsrCapture);
288
+ restoreGlobal(HANDLER_RAN_KEY, originalSsrMark);
289
+ originalSsrCapture = void 0;
290
+ originalSsrMark = void 0;
399
291
  }
400
292
  function registerServerFnGlobal(registration) {
401
- if (serverFnGlobalRegistrations.length === 0) {
402
- originalServerFnSend = snapshotGlobal(SERVER_FN_SEND_KEY);
403
- }
404
- serverFnGlobalRegistrations.push(registration);
405
- runtimeGlobal[SERVER_FN_SEND_KEY] = registration.dispatch;
293
+ if (serverFnGlobalRegistrations.length === 0) originalServerFnSend = snapshotGlobal(SERVER_FN_SEND_KEY);
294
+ serverFnGlobalRegistrations.push(registration);
295
+ runtimeGlobal[SERVER_FN_SEND_KEY] = registration.dispatch;
406
296
  }
407
297
  function unregisterServerFnGlobal(registration) {
408
- const index = serverFnGlobalRegistrations.indexOf(registration);
409
- if (index === -1)
410
- return;
411
- serverFnGlobalRegistrations.splice(index, 1);
412
- const active = serverFnGlobalRegistrations.at(-1);
413
- if (active) {
414
- runtimeGlobal[SERVER_FN_SEND_KEY] = active.dispatch;
415
- return;
416
- }
417
- restoreGlobal(SERVER_FN_SEND_KEY, originalServerFnSend);
418
- originalServerFnSend = void 0;
298
+ const index = serverFnGlobalRegistrations.indexOf(registration);
299
+ if (index === -1) return;
300
+ serverFnGlobalRegistrations.splice(index, 1);
301
+ const active = serverFnGlobalRegistrations.at(-1);
302
+ if (active) {
303
+ runtimeGlobal[SERVER_FN_SEND_KEY] = active.dispatch;
304
+ return;
305
+ }
306
+ restoreGlobal(SERVER_FN_SEND_KEY, originalServerFnSend);
307
+ originalServerFnSend = void 0;
419
308
  }
420
309
  function createSsrErrorLogger() {
421
- const handlerRan = Symbol("vibeHandlerRan");
422
- const capturedError = Symbol("vibeCapturedSsrError");
423
- const generations = [];
424
- let globalsInstalled = false;
425
- const responseFromEvent = (event) => {
426
- const response = event?.node?.res;
427
- return response && typeof response === "object" ? response : void 0;
428
- };
429
- const capture = (error, event) => {
430
- const response = responseFromEvent(event);
431
- if (!response)
432
- return;
433
- response[handlerRan] = true;
434
- response[capturedError] = error;
435
- };
436
- const consumeCapture = (response) => {
437
- const error = response[capturedError];
438
- delete response[capturedError];
439
- return error;
440
- };
441
- const markHandlerRan = (event) => {
442
- const response = responseFromEvent(event);
443
- if (response)
444
- response[handlerRan] = true;
445
- };
446
- const registration = { capture, mark: markHandlerRan };
447
- const installGlobals = () => {
448
- if (globalsInstalled)
449
- return;
450
- registerSsrGlobals(registration);
451
- globalsInstalled = true;
452
- };
453
- const restoreGlobals = () => {
454
- if (!globalsInstalled || generations.length > 0)
455
- return;
456
- globalsInstalled = false;
457
- unregisterSsrGlobals(registration);
458
- };
459
- const retireOldestDetached = () => {
460
- generations.find((generation) => !generation.httpServer)?.close();
461
- };
462
- return {
463
- name: "vibe-ssr-error-logger",
464
- apply: "serve",
465
- configureServer(server) {
466
- installGlobals();
467
- const httpServer = server.httpServer;
468
- let closed = false;
469
- const generation = {};
470
- const cleanup = () => {
471
- if (closed)
472
- return;
473
- closed = true;
474
- httpServer?.off("close", cleanup);
475
- const index = generations.indexOf(generation);
476
- if (index !== -1)
477
- generations.splice(index, 1);
478
- restoreGlobals();
479
- };
480
- generation.close = cleanup;
481
- generation.httpServer = httpServer ?? void 0;
482
- generations.push(generation);
483
- httpServer?.once("close", cleanup);
484
- server.middlewares.use((request, response, next) => {
485
- let handled = false;
486
- const handleErrorResponse = () => {
487
- if (handled || response.statusCode < 500)
488
- return;
489
- handled = true;
490
- const responseRecord = response;
491
- const captured = consumeCapture(responseRecord);
492
- const ranHandler = Boolean(responseRecord[handlerRan]);
493
- const source = !ranHandler ? "vite" : isBuildError(captured) ? "build" : "app";
494
- if (!response.headersSent) {
495
- try {
496
- response.setHeader("x-vibe-error-source", source);
497
- } catch {
498
- }
499
- }
500
- const where = [request.method, request.url].filter(Boolean).join(" ") || "the request";
501
- const data = captured !== void 0 ? boundedData(captured) : {
502
- message: ranHandler ? `The app returned ${response.statusCode} while handling ${where}, but no stack was captured.` : `The dev server returned ${response.statusCode} for ${where} before the app handler ran.`
503
- };
504
- try {
505
- server.ws.send({
506
- type: "custom",
507
- event: "vibe:server-ssr-error",
508
- data
509
- });
510
- } catch {
511
- }
512
- };
513
- const writeHead = response.writeHead.bind(response);
514
- response.writeHead = (...args) => {
515
- if (typeof args[0] === "number")
516
- response.statusCode = args[0];
517
- handleErrorResponse();
518
- return writeHead(...args);
519
- };
520
- const end = response.end.bind(response);
521
- response.end = (...args) => {
522
- handleErrorResponse();
523
- return end(...args);
524
- };
525
- next();
526
- });
527
- },
528
- transform(code, id) {
529
- if (!isRequestResponseModule(id))
530
- return null;
531
- if (code.includes(SSR_CAPTURE_KEY))
532
- return null;
533
- const needle = "handler(request, requestOpts)";
534
- if (!code.includes(needle)) {
535
- throw new Error(
536
- `[@leadconnector/vite-tanstack-config] unsupported @tanstack/start-server-core request-response transform: expected ${JSON.stringify(needle)} in ${id}.`
537
- );
538
- }
539
- return code.replace(
540
- needle,
541
- `(() => {
310
+ const handlerRan = Symbol("vibeHandlerRan");
311
+ const capturedError = Symbol("vibeCapturedSsrError");
312
+ const generations = [];
313
+ let globalsInstalled = false;
314
+ const responseFromEvent = (event) => {
315
+ const response = event?.node?.res;
316
+ return response && typeof response === "object" ? response : void 0;
317
+ };
318
+ const capture = (error, event) => {
319
+ const response = responseFromEvent(event);
320
+ if (!response) return;
321
+ response[handlerRan] = true;
322
+ response[capturedError] = error;
323
+ };
324
+ const consumeCapture = (response) => {
325
+ const error = response[capturedError];
326
+ delete response[capturedError];
327
+ return error;
328
+ };
329
+ const markHandlerRan = (event) => {
330
+ const response = responseFromEvent(event);
331
+ if (response) response[handlerRan] = true;
332
+ };
333
+ const registration = {
334
+ capture,
335
+ mark: markHandlerRan
336
+ };
337
+ const installGlobals = () => {
338
+ if (globalsInstalled) return;
339
+ registerSsrGlobals(registration);
340
+ globalsInstalled = true;
341
+ };
342
+ const restoreGlobals = () => {
343
+ if (!globalsInstalled || generations.length > 0) return;
344
+ globalsInstalled = false;
345
+ unregisterSsrGlobals(registration);
346
+ };
347
+ const retireOldestDetached = () => {
348
+ generations.find((generation) => !generation.httpServer)?.close();
349
+ };
350
+ return {
351
+ name: "vibe-ssr-error-logger",
352
+ apply: "serve",
353
+ configureServer(server) {
354
+ installGlobals();
355
+ const httpServer = server.httpServer;
356
+ let closed = false;
357
+ const generation = {};
358
+ const cleanup = () => {
359
+ if (closed) return;
360
+ closed = true;
361
+ httpServer?.off("close", cleanup);
362
+ const index = generations.indexOf(generation);
363
+ if (index !== -1) generations.splice(index, 1);
364
+ restoreGlobals();
365
+ };
366
+ generation.close = cleanup;
367
+ generation.httpServer = httpServer ?? void 0;
368
+ generations.push(generation);
369
+ httpServer?.once("close", cleanup);
370
+ server.middlewares.use((request, response, next) => {
371
+ let handled = false;
372
+ const handleErrorResponse = () => {
373
+ if (handled || response.statusCode < 500) return;
374
+ handled = true;
375
+ const responseRecord = response;
376
+ const captured = consumeCapture(responseRecord);
377
+ const ranHandler = Boolean(responseRecord[handlerRan]);
378
+ const source = !ranHandler ? "vite" : isBuildError(captured) ? "build" : "app";
379
+ if (!response.headersSent) try {
380
+ response.setHeader("x-vibe-error-source", source);
381
+ } catch {}
382
+ const where = [request.method, request.url].filter(Boolean).join(" ") || "the request";
383
+ const data = captured !== void 0 ? boundedData(captured) : { message: ranHandler ? `The app returned ${response.statusCode} while handling ${where}, but no stack was captured.` : `The dev server returned ${response.statusCode} for ${where} before the app handler ran.` };
384
+ try {
385
+ server.ws.send({
386
+ type: "custom",
387
+ event: "vibe:server-ssr-error",
388
+ data
389
+ });
390
+ } catch {}
391
+ };
392
+ const writeHead = response.writeHead.bind(response);
393
+ response.writeHead = ((...args) => {
394
+ if (typeof args[0] === "number") response.statusCode = args[0];
395
+ handleErrorResponse();
396
+ return writeHead(...args);
397
+ });
398
+ const end = response.end.bind(response);
399
+ response.end = ((...args) => {
400
+ handleErrorResponse();
401
+ return end(...args);
402
+ });
403
+ next();
404
+ });
405
+ },
406
+ transform(code, id) {
407
+ if (!isRequestResponseModule(id)) return null;
408
+ if (code.includes(SSR_CAPTURE_KEY)) return null;
409
+ const needle = "handler(request, requestOpts)";
410
+ if (!code.includes(needle)) throw new Error(`[@leadconnector/vite-tanstack-config] unsupported @tanstack/start-server-core request-response transform: expected ${JSON.stringify(needle)} in ${id}.`);
411
+ return code.replace(needle, `(() => {
542
412
  const __vibeSsrEvent = typeof h3Event === "undefined" ? undefined : h3Event
543
413
  globalThis.${HANDLER_RAN_KEY}?.(__vibeSsrEvent)
544
414
  try {
@@ -550,87 +420,76 @@ function createSsrErrorLogger() {
550
420
  globalThis.${SSR_CAPTURE_KEY}?.(err, __vibeSsrEvent)
551
421
  throw err
552
422
  }
553
- })()`
554
- );
555
- },
556
- closeWatcher() {
557
- },
558
- closeBundle() {
559
- retireOldestDetached();
560
- }
561
- };
423
+ })()`);
424
+ },
425
+ closeWatcher() {},
426
+ closeBundle() {
427
+ retireOldestDetached();
428
+ }
429
+ };
562
430
  }
563
431
  function createServerFnErrorLogger() {
564
- const generations = [];
565
- let globalInstalled = false;
566
- const dispatch = (data) => {
567
- generations.at(-1)?.send(data);
568
- };
569
- const registration = { dispatch };
570
- const installGlobal = () => {
571
- if (globalInstalled)
572
- return;
573
- registerServerFnGlobal(registration);
574
- globalInstalled = true;
575
- };
576
- const restoreGlobal2 = () => {
577
- if (!globalInstalled || generations.length > 0)
578
- return;
579
- globalInstalled = false;
580
- unregisterServerFnGlobal(registration);
581
- };
582
- const retireOldestDetached = () => {
583
- generations.find((generation) => !generation.httpServer)?.close();
584
- };
585
- return {
586
- name: "vibe-server-fn-error-logger",
587
- apply: "serve",
588
- enforce: "pre",
589
- configureServer(server) {
590
- installGlobal();
591
- const send = (data) => {
592
- try {
593
- server.ws.send({
594
- type: "custom",
595
- event: "vibe:server-fn-error",
596
- data: boundedData(data)
597
- });
598
- } catch {
599
- }
600
- };
601
- const httpServer = server.httpServer;
602
- let closed = false;
603
- const generation = {};
604
- const cleanup = () => {
605
- if (closed)
606
- return;
607
- closed = true;
608
- httpServer?.off("close", cleanup);
609
- const index = generations.indexOf(generation);
610
- if (index !== -1)
611
- generations.splice(index, 1);
612
- restoreGlobal2();
613
- };
614
- generation.close = cleanup;
615
- generation.httpServer = httpServer ?? void 0;
616
- generation.send = send;
617
- generations.push(generation);
618
- httpServer?.once("close", cleanup);
619
- },
620
- transform(code, id) {
621
- if (!isServerFunctionsHandlerModule(id))
622
- return null;
623
- if (code.includes(SERVER_FN_SEND_KEY))
624
- return null;
625
- const needle = "const unwrapped = res.result || res.error";
626
- if (!code.includes(needle)) {
627
- throw new Error(
628
- `[@leadconnector/vite-tanstack-config] unsupported @tanstack/start-server-core server-functions-handler transform: expected ${JSON.stringify(needle)} in ${id}.`
629
- );
630
- }
631
- return code.replace(
632
- needle,
633
- `${needle}
432
+ const generations = [];
433
+ let globalInstalled = false;
434
+ const dispatch = (data) => {
435
+ generations.at(-1)?.send(data);
436
+ };
437
+ const registration = { dispatch };
438
+ const installGlobal = () => {
439
+ if (globalInstalled) return;
440
+ registerServerFnGlobal(registration);
441
+ globalInstalled = true;
442
+ };
443
+ const restoreGlobal = () => {
444
+ if (!globalInstalled || generations.length > 0) return;
445
+ globalInstalled = false;
446
+ unregisterServerFnGlobal(registration);
447
+ };
448
+ const retireOldestDetached = () => {
449
+ generations.find((generation) => !generation.httpServer)?.close();
450
+ };
451
+ return {
452
+ name: "vibe-server-fn-error-logger",
453
+ apply: "serve",
454
+ enforce: "pre",
455
+ configureServer(server) {
456
+ installGlobal();
457
+ const send = (data) => {
458
+ try {
459
+ server.ws.send({
460
+ type: "custom",
461
+ event: "vibe:server-fn-error",
462
+ data: boundedData(data)
463
+ });
464
+ } catch {}
465
+ };
466
+ const httpServer = server.httpServer;
467
+ let closed = false;
468
+ const generation = {};
469
+ const cleanup = () => {
470
+ if (closed) return;
471
+ closed = true;
472
+ httpServer?.off("close", cleanup);
473
+ const index = generations.indexOf(generation);
474
+ if (index !== -1) generations.splice(index, 1);
475
+ restoreGlobal();
476
+ };
477
+ generation.close = cleanup;
478
+ generation.httpServer = httpServer ?? void 0;
479
+ generation.send = send;
480
+ generations.push(generation);
481
+ httpServer?.once("close", cleanup);
482
+ },
483
+ transform(code, id) {
484
+ if (!isServerFunctionsHandlerModule(id)) return null;
485
+ if (code.includes(SERVER_FN_SEND_KEY)) return null;
486
+ const needle = [
487
+ "const unwrapped = res.result || res.error",
488
+ "const unwrapped = res.error !== undefined ? res.error : res.result",
489
+ "const unwrapped = res.error !== void 0 ? res.error : res.result"
490
+ ].find((candidate) => code.includes(candidate));
491
+ if (!needle) throw new Error(`[@leadconnector/vite-tanstack-config] unsupported @tanstack/start-server-core server-functions-handler transform: expected an unwrapped-result line in ${id}.`);
492
+ return code.replace(needle, `${needle}
634
493
 
635
494
  if (res?.error) {
636
495
  const err = res.error
@@ -648,482 +507,385 @@ function createServerFnErrorLogger() {
648
507
  message: clipVibeDiagnostic(err?.message ?? err),
649
508
  stack: typeof err?.stack === "string" ? clipVibeDiagnostic(err.stack) : undefined,
650
509
  })
651
- }`
652
- );
653
- },
654
- closeWatcher() {
655
- },
656
- closeBundle() {
657
- retireOldestDetached();
658
- }
659
- };
660
- }
661
-
662
- // src/env.ts
663
- var VIBE_SANDBOX_ENV_VAR = "VIBE_SANDBOX";
510
+ }`);
511
+ },
512
+ closeWatcher() {},
513
+ closeBundle() {
514
+ retireOldestDetached();
515
+ }
516
+ };
517
+ }
518
+ //#endregion
519
+ //#region src/env.ts
520
+ const VIBE_SANDBOX_ENV_VAR = "VIBE_SANDBOX";
664
521
  function isSandboxEnvironment() {
665
- return process.env[VIBE_SANDBOX_ENV_VAR] === "1";
522
+ return process.env[VIBE_SANDBOX_ENV_VAR] === "1";
666
523
  }
667
-
668
- // src/nitro.ts
524
+ //#endregion
525
+ //#region src/nitro.ts
669
526
  function shouldRunNitro(command, nitroOpt, isSandbox) {
670
- const explicit = nitroOpt === true || typeof nitroOpt === "object" && nitroOpt !== null;
671
- return nitroOpt !== false && command === "build" && (explicit || isSandbox);
527
+ return nitroOpt !== false && command === "build" && (nitroOpt === true || typeof nitroOpt === "object" && nitroOpt !== null || isSandbox);
672
528
  }
673
529
  function buildNitroOptions(nitroOpt, isSandbox) {
674
- const user = typeof nitroOpt === "object" && nitroOpt ? nitroOpt : {};
675
- const opts = { defaultPreset: "cloudflare-module", ...user };
676
- if (isSandbox) {
677
- delete opts.defaultPreset;
678
- opts.preset = "cloudflare-module";
679
- opts.output = { dir: "dist", serverDir: "dist/server", publicDir: "dist/client" };
680
- opts.cloudflare = { nodeCompat: true, deployConfig: true, ...user.cloudflare };
681
- }
682
- return opts;
530
+ const user = typeof nitroOpt === "object" && nitroOpt ? nitroOpt : {};
531
+ const opts = {
532
+ defaultPreset: "cloudflare-module",
533
+ ...user
534
+ };
535
+ if (isSandbox) {
536
+ delete opts.defaultPreset;
537
+ opts.preset = "cloudflare-module";
538
+ opts.output = {
539
+ dir: "dist",
540
+ serverDir: "dist/server",
541
+ publicDir: "dist/client"
542
+ };
543
+ opts.cloudflare = {
544
+ nodeCompat: true,
545
+ deployConfig: true,
546
+ ...user.cloudflare
547
+ };
548
+ }
549
+ return opts;
683
550
  }
684
551
  async function loadNitroPlugin(importer, requiredReason) {
685
- let nitroModule;
686
- try {
687
- nitroModule = await importer();
688
- } catch (error) {
689
- throw new Error(
690
- `[@leadconnector/vite-tanstack-config] ${requiredReason}, but the \`nitro\` package could not be loaded. Install \`nitro\` in devDependencies (peerDependency >=3.0.260603-beta). Original import error: ${error instanceof Error ? error.message : String(error)}`,
691
- { cause: error }
692
- );
693
- }
694
- const nitro = nitroModule.nitro;
695
- if (typeof nitro !== "function") {
696
- throw new Error(
697
- `[@leadconnector/vite-tanstack-config] could not resolve the Nitro plugin (expected a named \`nitro\` export from \`nitro/vite\`). Installed exports: ${Object.keys(nitroModule).join(", ") || "(none)"}.`
698
- );
699
- }
700
- return nitro;
701
- }
702
-
703
- // src/server.ts
704
- var import_vite = require("vite");
705
- var TOOL_MANAGED_WATCH_IGNORES = [
706
- "**/.workspace/**",
707
- "**/.agents/**",
708
- "**/.claude/**",
709
- "**/.lovable/**",
710
- "**/.tanstack/tmp/**"
552
+ let nitroModule;
553
+ try {
554
+ nitroModule = await importer();
555
+ } catch (error) {
556
+ throw new Error(`[@leadconnector/vite-tanstack-config] ${requiredReason}, but the \`nitro\` package could not be loaded. Install \`nitro\` in devDependencies (peerDependency >=3.0.260603-beta). Original import error: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
557
+ }
558
+ const nitro = nitroModule.nitro;
559
+ if (typeof nitro !== "function") throw new Error(`[@leadconnector/vite-tanstack-config] could not resolve the Nitro plugin (expected a named \`nitro\` export from \`nitro/vite\`). Installed exports: ${Object.keys(nitroModule).join(", ") || "(none)"}.`);
560
+ return nitro;
561
+ }
562
+ //#endregion
563
+ //#region src/server.ts
564
+ const TOOL_MANAGED_WATCH_IGNORES = [
565
+ "**/.workspace/**",
566
+ "**/.agents/**",
567
+ "**/.claude/**",
568
+ "**/.lovable/**",
569
+ "**/.tanstack/tmp/**"
711
570
  ];
712
- var MAX_WARNING_ITEMS = 8;
713
- var MAX_WARNING_LENGTH = 800;
714
- function logWarning(message) {
715
- const bounded = message.length > MAX_WARNING_LENGTH ? `${message.slice(0, MAX_WARNING_LENGTH)}...[truncated]` : message;
716
- console.warn(`[@leadconnector/vite-tanstack-config] ${bounded}`);
571
+ const MAX_WARNING_ITEMS = 8;
572
+ const MAX_WARNING_LENGTH = 800;
573
+ function logWarning$1(message) {
574
+ const bounded = message.length > MAX_WARNING_LENGTH ? `${message.slice(0, MAX_WARNING_LENGTH)}...[truncated]` : message;
575
+ console.warn(`[@leadconnector/vite-tanstack-config] ${bounded}`);
717
576
  }
718
577
  function boundedList(values) {
719
- const shown = values.slice(0, MAX_WARNING_ITEMS);
720
- const omitted = values.length - shown.length;
721
- return `${shown.join(", ")}${omitted > 0 ? ` (+${omitted} more)` : ""}`;
578
+ const shown = values.slice(0, MAX_WARNING_ITEMS);
579
+ const omitted = values.length - shown.length;
580
+ return `${shown.join(", ")}${omitted > 0 ? ` (+${omitted} more)` : ""}`;
722
581
  }
723
582
  function normalizeIgnored(value) {
724
- if (typeof value === "string" || typeof value === "function" || value instanceof RegExp) {
725
- return [value];
726
- }
727
- if (!Array.isArray(value))
728
- return [];
729
- return value.filter(
730
- (entry) => typeof entry === "string" || typeof entry === "function" || entry instanceof RegExp
731
- );
583
+ if (typeof value === "string" || typeof value === "function" || value instanceof RegExp) return [value];
584
+ if (!Array.isArray(value)) return [];
585
+ return value.filter((entry) => typeof entry === "string" || typeof entry === "function" || entry instanceof RegExp);
732
586
  }
733
587
  function previewAllowedHosts() {
734
- const hosts = /* @__PURE__ */ new Set([".modal.host"]);
735
- const addHost = (value) => {
736
- const trimmed = value.trim();
737
- if (!trimmed)
738
- return;
739
- try {
740
- const parsed = new URL(
741
- trimmed.includes("://") ? trimmed : `https://${trimmed}`
742
- );
743
- if (!["http:", "https:"].includes(parsed.protocol))
744
- throw new Error();
745
- if (parsed.username || parsed.password)
746
- throw new Error();
747
- const hostname = parsed.hostname.toLowerCase();
748
- const hostnameBody = hostname.startsWith(".") ? hostname.slice(1) : hostname;
749
- const validHostname = hostnameBody === "localhost" || /^\[[0-9a-f:]+\]$/i.test(hostnameBody) || hostnameBody.split(".").every(
750
- (label) => label.length > 0 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(label)
751
- );
752
- if (!validHostname || hostname === "*")
753
- throw new Error();
754
- hosts.add(hostname);
755
- } catch {
756
- logWarning(`Ignoring invalid preview host ${JSON.stringify(trimmed)}.`);
757
- }
758
- };
759
- if (process.env.VIBE_PREVIEW_HOST)
760
- addHost(process.env.VIBE_PREVIEW_HOST);
761
- for (const host of (process.env.VIBE_PREVIEW_HOSTS ?? "").split(",")) {
762
- addHost(host);
763
- }
764
- return [...hosts];
765
- }
766
- var DEPRECATED_HMR_WEBSOCKET_KEYS = [
767
- "protocol",
768
- "host",
769
- "port",
770
- "path",
771
- "clientPort",
772
- "timeout",
773
- "server"
588
+ const hosts = /* @__PURE__ */ new Set([".modal.host"]);
589
+ const addHost = (value) => {
590
+ const trimmed = value.trim();
591
+ if (!trimmed) return;
592
+ try {
593
+ const parsed = new URL(trimmed.includes("://") ? trimmed : `https://${trimmed}`);
594
+ if (!["http:", "https:"].includes(parsed.protocol)) throw new Error();
595
+ if (parsed.username || parsed.password) throw new Error();
596
+ const hostname = parsed.hostname.toLowerCase();
597
+ const hostnameBody = hostname.startsWith(".") ? hostname.slice(1) : hostname;
598
+ if (!(hostnameBody === "localhost" || /^\[[0-9a-f:]+\]$/i.test(hostnameBody) || hostnameBody.split(".").every((label) => label.length > 0 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(label))) || hostname === "*") throw new Error();
599
+ hosts.add(hostname);
600
+ } catch {
601
+ logWarning$1(`Ignoring invalid preview host ${JSON.stringify(trimmed)}.`);
602
+ }
603
+ };
604
+ if (process.env.VIBE_PREVIEW_HOST) addHost(process.env.VIBE_PREVIEW_HOST);
605
+ for (const host of (process.env.VIBE_PREVIEW_HOSTS ?? "").split(",")) addHost(host);
606
+ return [...hosts];
607
+ }
608
+ const DEPRECATED_HMR_WEBSOCKET_KEYS = [
609
+ "protocol",
610
+ "host",
611
+ "port",
612
+ "path",
613
+ "clientPort",
614
+ "timeout",
615
+ "server"
774
616
  ];
775
617
  function withoutDeprecatedHmrWebsocketOptions(config) {
776
- const hmr = config.server?.hmr;
777
- if (hmr === false || hmr == null || typeof hmr !== "object") {
778
- return config;
779
- }
780
- const nextHmr = { ...hmr };
781
- let stripped = false;
782
- for (const key of DEPRECATED_HMR_WEBSOCKET_KEYS) {
783
- if (key in nextHmr) {
784
- delete nextHmr[key];
785
- stripped = true;
786
- }
787
- }
788
- if (!stripped)
789
- return config;
790
- return {
791
- ...config,
792
- server: {
793
- ...config.server,
794
- hmr: nextHmr
795
- }
796
- };
618
+ const hmr = config.server?.hmr;
619
+ if (hmr === false || hmr == null || typeof hmr !== "object") return config;
620
+ const nextHmr = { ...hmr };
621
+ let stripped = false;
622
+ for (const key of DEPRECATED_HMR_WEBSOCKET_KEYS) if (key in nextHmr) {
623
+ delete nextHmr[key];
624
+ stripped = true;
625
+ }
626
+ if (!stripped) return config;
627
+ return {
628
+ ...config,
629
+ server: {
630
+ ...config.server,
631
+ hmr: nextHmr
632
+ }
633
+ };
797
634
  }
798
635
  function warnAndStripUnsupportedServerFields(config) {
799
- const server = config.server;
800
- if (!server)
801
- return config;
802
- if (server.headers) {
803
- logWarning(
804
- `Sandbox mode removed unsupported server.headers: ${boundedList(
805
- Object.keys(server.headers)
806
- )}.`
807
- );
808
- }
809
- if (server.cors !== void 0) {
810
- logWarning("Sandbox mode removed unsupported custom server.cors.");
811
- }
812
- if (server.proxy) {
813
- logWarning(
814
- `Sandbox mode removed unsupported server.proxy routes: ${boundedList(
815
- Object.keys(server.proxy)
816
- )}.`
817
- );
818
- }
819
- if (server.headers === void 0 && server.cors === void 0 && server.proxy === void 0) {
820
- return config;
821
- }
822
- const {
823
- headers: _headers,
824
- cors: _cors,
825
- proxy: _proxy,
826
- ...supportedServer
827
- } = server;
828
- return { ...config, server: supportedServer };
636
+ const server = config.server;
637
+ if (!server) return config;
638
+ if (server.headers) logWarning$1(`Sandbox mode removed unsupported server.headers: ${boundedList(Object.keys(server.headers))}.`);
639
+ if (server.cors !== void 0) logWarning$1("Sandbox mode removed unsupported custom server.cors.");
640
+ if (server.proxy) logWarning$1(`Sandbox mode removed unsupported server.proxy routes: ${boundedList(Object.keys(server.proxy))}.`);
641
+ if (server.headers === void 0 && server.cors === void 0 && server.proxy === void 0) return config;
642
+ const { headers: _headers, cors: _cors, proxy: _proxy, ...supportedServer } = server;
643
+ return {
644
+ ...config,
645
+ server: supportedServer
646
+ };
829
647
  }
830
648
  function applyNonSandboxWatchDefaults(config) {
831
- if (config.server?.watch === null)
832
- return config;
833
- return (0, import_vite.mergeConfig)({
834
- server: {
835
- watch: {
836
- awaitWriteFinish: {
837
- stabilityThreshold: 1e3,
838
- pollInterval: 100
839
- }
840
- }
841
- }
842
- }, config);
649
+ if (config.server?.watch === null) return config;
650
+ return (0, vite.mergeConfig)({ server: { watch: { awaitWriteFinish: {
651
+ stabilityThreshold: 1e3,
652
+ pollInterval: 100
653
+ } } } }, config);
843
654
  }
844
655
  function applySandboxServerInvariants(config) {
845
- const userWatch = config.server?.watch ?? {};
846
- const ignored = [
847
- ...normalizeIgnored(userWatch.ignored),
848
- ...TOOL_MANAGED_WATCH_IGNORES
849
- ];
850
- const dedupedIgnored = [...new Set(ignored)];
851
- const allowedHosts = previewAllowedHosts();
852
- const sanitized = withoutDeprecatedHmrWebsocketOptions(config);
853
- const userHmr = sanitized.server?.hmr;
854
- const sandboxHmr = userHmr === false ? false : { overlay: false };
855
- const merged = (0, import_vite.mergeConfig)(sanitized, {
856
- server: {
857
- host: "::",
858
- port: 8080,
859
- strictPort: true,
860
- allowedHosts,
861
- watch: { ...userWatch, ignored: dedupedIgnored },
862
- hmr: sandboxHmr
863
- }
864
- });
865
- const mergedServer = merged.server ?? {};
866
- const invariantConfig = {
867
- ...merged,
868
- server: {
869
- ...mergedServer,
870
- host: "::",
871
- port: 8080,
872
- strictPort: true,
873
- allowedHosts,
874
- watch: {
875
- ...mergedServer.watch,
876
- ignored: dedupedIgnored
877
- },
878
- hmr: sandboxHmr
879
- }
880
- };
881
- return warnAndStripUnsupportedServerFields(invariantConfig);
882
- }
883
-
884
- // src/index.ts
885
- var OPTION_KEYS = /* @__PURE__ */ new Set([
886
- "vite",
887
- "nitro",
888
- "tanstackStart",
889
- "react",
890
- "envDefine",
891
- "hmrGate",
892
- "devServerBridge",
893
- "ssrErrorLogger",
894
- "serverFnErrorLogger"
656
+ const userWatch = config.server?.watch ?? {};
657
+ const ignored = [...normalizeIgnored(userWatch.ignored), ...TOOL_MANAGED_WATCH_IGNORES];
658
+ const dedupedIgnored = [...new Set(ignored)];
659
+ const allowedHosts = previewAllowedHosts();
660
+ const sanitized = withoutDeprecatedHmrWebsocketOptions(config);
661
+ const sandboxHmr = sanitized.server?.hmr === false ? false : { overlay: false };
662
+ const merged = (0, vite.mergeConfig)(sanitized, { server: {
663
+ host: "::",
664
+ port: 8080,
665
+ strictPort: true,
666
+ allowedHosts,
667
+ watch: {
668
+ ...userWatch,
669
+ ignored: dedupedIgnored
670
+ },
671
+ hmr: sandboxHmr
672
+ } });
673
+ const mergedServer = merged.server ?? {};
674
+ return warnAndStripUnsupportedServerFields({
675
+ ...merged,
676
+ server: {
677
+ ...mergedServer,
678
+ host: "::",
679
+ port: 8080,
680
+ strictPort: true,
681
+ allowedHosts,
682
+ watch: {
683
+ ...mergedServer.watch,
684
+ ignored: dedupedIgnored
685
+ },
686
+ hmr: sandboxHmr
687
+ }
688
+ });
689
+ }
690
+ //#endregion
691
+ //#region src/index.ts
692
+ const OPTION_KEYS = /* @__PURE__ */ new Set([
693
+ "vite",
694
+ "nitro",
695
+ "tanstackStart",
696
+ "react",
697
+ "envDefine",
698
+ "hmrGate",
699
+ "devServerBridge",
700
+ "ssrErrorLogger",
701
+ "serverFnErrorLogger"
895
702
  ]);
896
- var DEFAULT_IMPORT_PROTECTION = {
897
- behavior: "error",
898
- client: {
899
- files: ["**/server/**"],
900
- specifiers: ["server-only"]
901
- }
703
+ const DEFAULT_IMPORT_PROTECTION = {
704
+ behavior: "error",
705
+ client: {
706
+ files: ["**/server/**"],
707
+ specifiers: ["server-only"]
708
+ }
902
709
  };
903
- var DEFAULT_DEDUPE = [
904
- "react",
905
- "react-dom",
906
- "react/jsx-runtime",
907
- "react/jsx-dev-runtime",
908
- "@tanstack/react-query",
909
- "@tanstack/query-core"
710
+ const DEFAULT_DEDUPE = [
711
+ "react",
712
+ "react-dom",
713
+ "react/jsx-runtime",
714
+ "react/jsx-dev-runtime",
715
+ "@tanstack/react-query",
716
+ "@tanstack/query-core"
910
717
  ];
911
- var DEFAULT_OPTIMIZE_DEPS = [
912
- "react",
913
- "react-dom",
914
- "react-dom/client",
915
- "react/jsx-runtime",
916
- "react/jsx-dev-runtime"
718
+ const DEFAULT_OPTIMIZE_DEPS = [
719
+ "react",
720
+ "react-dom",
721
+ "react-dom/client",
722
+ "react/jsx-runtime",
723
+ "react/jsx-dev-runtime"
917
724
  ];
918
- function logWarning2(message) {
919
- console.warn(`[@leadconnector/vite-tanstack-config] ${message}`);
725
+ function logWarning(message) {
726
+ console.warn(`[@leadconnector/vite-tanstack-config] ${message}`);
920
727
  }
921
728
  function isPromiseLike(value) {
922
- return !!value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
729
+ return !!value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
923
730
  }
924
731
  function isExplicitOptions(value) {
925
- return Object.keys(value).some((key) => OPTION_KEYS.has(key));
732
+ return Object.keys(value).some((key) => OPTION_KEYS.has(key));
926
733
  }
927
734
  async function normalizeOptions(input, env) {
928
- if (typeof input === "function") {
929
- return { vite: await Promise.resolve(input(env)) };
930
- }
931
- if (isPromiseLike(input))
932
- return { vite: await input };
933
- const object = input && typeof input === "object" ? input : {};
934
- return isExplicitOptions(object) ? object : { vite: object };
735
+ if (typeof input === "function") return { vite: await Promise.resolve(input(env)) };
736
+ if (isPromiseLike(input)) return { vite: await input };
737
+ const object = input && typeof input === "object" ? input : {};
738
+ return isExplicitOptions(object) ? object : { vite: object };
935
739
  }
936
740
  function pluginEnabled(option, isSandbox) {
937
- return isSandbox ? option !== false : option === true || !!option;
741
+ return isSandbox ? option !== false : option === true || !!option;
938
742
  }
939
743
  function pluginOptions(option) {
940
- return option && typeof option === "object" ? option : {};
744
+ return option && typeof option === "object" ? option : {};
941
745
  }
942
746
  function platformDevServerBridgeOptions(option, isSandbox) {
943
- const configured = pluginOptions(option);
944
- if (!isSandbox || !configured.errorCollector || typeof configured.errorCollector !== "object") {
945
- return configured;
946
- }
947
- return {
948
- ...configured,
949
- errorCollector: {
950
- ...configured.errorCollector,
951
- endpoint: "/__vibe/error-collector"
952
- }
953
- };
747
+ const configured = pluginOptions(option);
748
+ if (!isSandbox || !configured.errorCollector || typeof configured.errorCollector !== "object") return configured;
749
+ return {
750
+ ...configured,
751
+ errorCollector: {
752
+ ...configured.errorCollector,
753
+ endpoint: "/__vibe/error-collector"
754
+ }
755
+ };
954
756
  }
955
757
  function withUserAliasPrecedence(config, userConfig) {
956
- const userAlias = userConfig.resolve?.alias;
957
- if (!userAlias)
958
- return config;
959
- if (Array.isArray(userAlias)) {
960
- const userAtAliases = userAlias.filter((entry) => entry.find === "@");
961
- if (userAtAliases.length === 0)
962
- return config;
963
- const merged = Array.isArray(config.resolve?.alias) ? config.resolve.alias : Object.entries(config.resolve?.alias ?? {}).map(
964
- ([find, replacement]) => ({ find, replacement })
965
- );
966
- return {
967
- ...config,
968
- resolve: {
969
- ...config.resolve,
970
- alias: [
971
- ...userAtAliases,
972
- ...merged.filter((entry) => entry.find !== "@")
973
- ]
974
- }
975
- };
976
- }
977
- const userAliasRecord = userAlias;
978
- if (!Object.prototype.hasOwnProperty.call(userAliasRecord, "@"))
979
- return config;
980
- const mergedAlias = Array.isArray(config.resolve?.alias) ? config.resolve.alias.filter((entry) => entry.find !== "@") : config.resolve?.alias;
981
- return {
982
- ...config,
983
- resolve: {
984
- ...config.resolve,
985
- alias: Array.isArray(mergedAlias) ? [{ find: "@", replacement: userAliasRecord["@"] }, ...mergedAlias] : { ...mergedAlias, "@": userAliasRecord["@"] }
986
- }
987
- };
758
+ const userAlias = userConfig.resolve?.alias;
759
+ if (!userAlias) return config;
760
+ if (Array.isArray(userAlias)) {
761
+ const userAtAliases = userAlias.filter((entry) => entry.find === "@");
762
+ if (userAtAliases.length === 0) return config;
763
+ const merged = Array.isArray(config.resolve?.alias) ? config.resolve.alias : Object.entries(config.resolve?.alias ?? {}).map(([find, replacement]) => ({
764
+ find,
765
+ replacement
766
+ }));
767
+ return {
768
+ ...config,
769
+ resolve: {
770
+ ...config.resolve,
771
+ alias: [...userAtAliases, ...merged.filter((entry) => entry.find !== "@")]
772
+ }
773
+ };
774
+ }
775
+ const userAliasRecord = userAlias;
776
+ if (!Object.prototype.hasOwnProperty.call(userAliasRecord, "@")) return config;
777
+ const mergedAlias = Array.isArray(config.resolve?.alias) ? config.resolve.alias.filter((entry) => entry.find !== "@") : config.resolve?.alias;
778
+ return {
779
+ ...config,
780
+ resolve: {
781
+ ...config.resolve,
782
+ alias: Array.isArray(mergedAlias) ? [{
783
+ find: "@",
784
+ replacement: userAliasRecord["@"]
785
+ }, ...mergedAlias] : {
786
+ ...mergedAlias,
787
+ "@": userAliasRecord["@"]
788
+ }
789
+ }
790
+ };
988
791
  }
989
792
  function defineConfig(configOrOptions = {}) {
990
- return async (env) => {
991
- const { command, mode } = env;
992
- const isSandbox = isSandboxEnvironment();
993
- const options = await normalizeOptions(configOrOptions, env);
994
- const internalPlugins = [];
995
- if (mode === "development") {
996
- const { devtools } = await import("@tanstack/devtools-vite");
997
- internalPlugins.push(
998
- devtools({
999
- logging: false,
1000
- eventBusConfig: { enabled: false },
1001
- enhancedLogs: { enabled: false },
1002
- consolePiping: { enabled: false },
1003
- removeDevtoolsOnBuild: false,
1004
- injectSource: { enabled: true }
1005
- })
1006
- );
1007
- }
1008
- if (command === "serve" && mode === "development") {
1009
- internalPlugins.push(
1010
- (0, import_vibe_tagger.componentTagger)({ jsxSource: true, tailwindConfig: true })
1011
- );
1012
- }
1013
- const tailwindcss = (await import("@tailwindcss/vite")).default;
1014
- const tsConfigPaths = (await import("vite-tsconfig-paths")).default;
1015
- internalPlugins.push(tailwindcss());
1016
- internalPlugins.push(tsConfigPaths({ projects: ["./tsconfig.json"] }));
1017
- if (options.serverFnErrorLogger !== false) {
1018
- internalPlugins.push(createServerFnErrorLogger());
1019
- }
1020
- if (options.ssrErrorLogger !== false) {
1021
- internalPlugins.push(createSsrErrorLogger());
1022
- }
1023
- if (command === "build" && isSandbox) {
1024
- internalPlugins.push(createBuildErrorDiagnostics());
1025
- }
1026
- const { tanstackStart } = await import("@tanstack/react-start/plugin/vite");
1027
- const tanstackStartOptions = (0, import_vite2.mergeConfig)(
1028
- { importProtection: DEFAULT_IMPORT_PROTECTION },
1029
- options.tanstackStart ?? {}
1030
- );
1031
- internalPlugins.push(tanstackStart(tanstackStartOptions));
1032
- if (shouldRunNitro(command, options.nitro, isSandbox)) {
1033
- const requiredReason = options.nitro === true || typeof options.nitro === "object" && options.nitro !== null ? "an explicit `nitro` option was set" : "running inside a Vibe sandbox";
1034
- const nitroFn = await loadNitroPlugin(
1035
- // nitro is an optional peer dependency, so keep the import dynamic.
1036
- // @ts-expect-error -- optional peer types are intentionally unavailable.
1037
- () => import("nitro/vite"),
1038
- requiredReason
1039
- );
1040
- const nitroOptions = buildNitroOptions(options.nitro, isSandbox);
1041
- internalPlugins.push(nitroFn(nitroOptions));
1042
- if (isSandbox) {
1043
- const output = nitroOptions.output;
1044
- internalPlugins.push(
1045
- stripRedundantNodejsCompatFlag(
1046
- typeof output?.serverDir === "string" ? output.serverDir : "dist/server"
1047
- )
1048
- );
1049
- }
1050
- }
1051
- const viteReact = (await import("@vitejs/plugin-react")).default;
1052
- internalPlugins.push(viteReact(options.react ?? {}));
1053
- if (command === "serve" && pluginEnabled(options.hmrGate, isSandbox)) {
1054
- const { hmrGatePlugin } = await import("@leadconnector/vite-plugin-hmr-gate");
1055
- internalPlugins.push(
1056
- hmrGatePlugin(pluginOptions(options.hmrGate))
1057
- );
1058
- }
1059
- if (command === "serve" && pluginEnabled(options.devServerBridge, isSandbox)) {
1060
- const { devServerBridgePlugin } = await import("@leadconnector/vite-plugin-dev-server-bridge");
1061
- internalPlugins.push(
1062
- devServerBridgePlugin(
1063
- platformDevServerBridgeOptions(options.devServerBridge, isSandbox)
1064
- )
1065
- );
1066
- }
1067
- const userConfig = options.vite ?? {};
1068
- const projectRoot = (0, import_node_path2.resolve)(process.cwd(), userConfig.root ?? ".");
1069
- const envDirectory = userConfig.envDir === false ? void 0 : (0, import_node_path2.resolve)(projectRoot, userConfig.envDir ?? ".");
1070
- const envDefine = {};
1071
- if (options.envDefine !== false && envDirectory) {
1072
- const loadedEnv = (0, import_vite2.loadEnv)(mode, envDirectory, "VITE_");
1073
- for (const [key, value] of Object.entries(loadedEnv)) {
1074
- envDefine[`import.meta.env.${key}`] = JSON.stringify(value);
1075
- }
1076
- }
1077
- const isDevBuild = command === "build" && mode === "development";
1078
- const baseConfig = {
1079
- define: {
1080
- ...envDefine,
1081
- ...isDevBuild ? {
1082
- "process.env.NODE_ENV": JSON.stringify("development")
1083
- } : {}
1084
- },
1085
- ...isDevBuild ? {
1086
- environments: {
1087
- client: {
1088
- define: {
1089
- "process.env.NODE_ENV": JSON.stringify("development")
1090
- }
1091
- }
1092
- },
1093
- esbuild: { keepNames: true }
1094
- } : {},
1095
- css: { transformer: "lightningcss" },
1096
- resolve: {
1097
- alias: { "@": (0, import_node_path2.resolve)(projectRoot, "src") },
1098
- dedupe: DEFAULT_DEDUPE
1099
- },
1100
- optimizeDeps: {
1101
- include: DEFAULT_OPTIMIZE_DEPS,
1102
- ignoreOutdatedRequests: true
1103
- },
1104
- plugins: [...internalPlugins, ...options.plugins ?? []],
1105
- server: { host: "::", port: 8080 }
1106
- };
1107
- let config = (0, import_vite2.mergeConfig)(baseConfig, userConfig);
1108
- config = withUserAliasPrecedence(config, userConfig);
1109
- if (command === "serve" && isSandbox && bundledDevRequested()) {
1110
- const viteVersion = resolveInstalledViteVersion(projectRoot);
1111
- if (viteVersionSupportsBundledDev(viteVersion)) {
1112
- config = (0, import_vite2.mergeConfig)(config, {
1113
- experimental: { bundledDev: true },
1114
- plugins: [bundledDevCssUrlShim()]
1115
- });
1116
- } else {
1117
- logWarning2(
1118
- `Bundled dev requested (${BUNDLED_DEV_ENV_VAR}=true), but installed Vite ${viteVersion ?? "unresolved"} is missing, prerelease, or below 8.1. Starting classic dev.`
1119
- );
1120
- }
1121
- }
1122
- return isSandbox ? applySandboxServerInvariants(config) : applyNonSandboxWatchDefaults(config);
1123
- };
1124
- }
1125
- // Annotate the CommonJS export names for ESM import in node:
1126
- 0 && (module.exports = {
1127
- defineConfig
1128
- });
793
+ return async (env) => {
794
+ const { command, mode } = env;
795
+ const isSandbox = isSandboxEnvironment();
796
+ const options = await normalizeOptions(configOrOptions, env);
797
+ const internalPlugins = [];
798
+ if (mode === "development") {
799
+ const { devtools } = await import("@tanstack/devtools-vite");
800
+ internalPlugins.push(devtools({
801
+ logging: false,
802
+ eventBusConfig: { enabled: false },
803
+ enhancedLogs: { enabled: false },
804
+ consolePiping: { enabled: false },
805
+ removeDevtoolsOnBuild: false,
806
+ injectSource: { enabled: true }
807
+ }));
808
+ }
809
+ if (command === "serve" && mode === "development") internalPlugins.push((0, _leadconnector_vibe_tagger.componentTagger)({
810
+ jsxSource: true,
811
+ tailwindConfig: true
812
+ }));
813
+ const tailwindcss = (await import("@tailwindcss/vite")).default;
814
+ const tsConfigPaths = (await import("vite-tsconfig-paths")).default;
815
+ internalPlugins.push(tailwindcss());
816
+ internalPlugins.push(tsConfigPaths({ projects: ["./tsconfig.json"] }));
817
+ if (options.serverFnErrorLogger !== false) internalPlugins.push(createServerFnErrorLogger());
818
+ if (options.ssrErrorLogger !== false) internalPlugins.push(createSsrErrorLogger());
819
+ if (command === "build" && isSandbox) internalPlugins.push(createBuildErrorDiagnostics());
820
+ const { tanstackStart } = await import("@tanstack/react-start/plugin/vite");
821
+ const tanstackStartOptions = (0, vite.mergeConfig)({ importProtection: DEFAULT_IMPORT_PROTECTION }, options.tanstackStart ?? {});
822
+ internalPlugins.push(tanstackStart(tanstackStartOptions));
823
+ if (shouldRunNitro(command, options.nitro, isSandbox)) {
824
+ const nitroFn = await loadNitroPlugin(() => import("nitro/vite"), options.nitro === true || typeof options.nitro === "object" && options.nitro !== null ? "an explicit `nitro` option was set" : "running inside a Vibe sandbox");
825
+ const nitroOptions = buildNitroOptions(options.nitro, isSandbox);
826
+ internalPlugins.push(nitroFn(nitroOptions));
827
+ if (isSandbox) {
828
+ const output = nitroOptions.output;
829
+ internalPlugins.push(stripRedundantNodejsCompatFlag(typeof output?.serverDir === "string" ? output.serverDir : "dist/server"));
830
+ }
831
+ }
832
+ const viteReact = (await import("@vitejs/plugin-react")).default;
833
+ internalPlugins.push(viteReact(options.react ?? {}));
834
+ if (command === "serve" && pluginEnabled(options.hmrGate, isSandbox)) {
835
+ const { hmrGatePlugin } = await import("@leadconnector/vite-plugin-hmr-gate");
836
+ internalPlugins.push(hmrGatePlugin(pluginOptions(options.hmrGate)));
837
+ }
838
+ if (command === "serve" && pluginEnabled(options.devServerBridge, isSandbox)) {
839
+ const { devServerBridgePlugin } = await import("@leadconnector/vite-plugin-dev-server-bridge");
840
+ internalPlugins.push(devServerBridgePlugin(platformDevServerBridgeOptions(options.devServerBridge, isSandbox)));
841
+ }
842
+ const userConfig = options.vite ?? {};
843
+ const projectRoot = (0, node_path.resolve)(process.cwd(), userConfig.root ?? ".");
844
+ const envDirectory = userConfig.envDir === false ? void 0 : (0, node_path.resolve)(projectRoot, userConfig.envDir ?? ".");
845
+ const envDefine = {};
846
+ if (options.envDefine !== false && envDirectory) {
847
+ const loadedEnv = (0, vite.loadEnv)(mode, envDirectory, "VITE_");
848
+ for (const [key, value] of Object.entries(loadedEnv)) envDefine[`import.meta.env.${key}`] = JSON.stringify(value);
849
+ }
850
+ const isDevBuild = command === "build" && mode === "development";
851
+ const baseConfig = {
852
+ define: {
853
+ ...envDefine,
854
+ ...isDevBuild ? { "process.env.NODE_ENV": JSON.stringify("development") } : {}
855
+ },
856
+ ...isDevBuild ? {
857
+ environments: { client: { define: { "process.env.NODE_ENV": JSON.stringify("development") } } },
858
+ esbuild: { keepNames: true }
859
+ } : {},
860
+ css: { transformer: "lightningcss" },
861
+ resolve: {
862
+ alias: { "@": (0, node_path.resolve)(projectRoot, "src") },
863
+ dedupe: DEFAULT_DEDUPE
864
+ },
865
+ optimizeDeps: {
866
+ include: DEFAULT_OPTIMIZE_DEPS,
867
+ ignoreOutdatedRequests: true
868
+ },
869
+ plugins: [...internalPlugins, ...options.plugins ?? []],
870
+ server: {
871
+ host: "::",
872
+ port: 8080
873
+ }
874
+ };
875
+ let config = (0, vite.mergeConfig)(baseConfig, userConfig);
876
+ config = withUserAliasPrecedence(config, userConfig);
877
+ if (command === "serve" && isSandbox && bundledDevRequested()) {
878
+ const viteVersion = resolveInstalledViteVersion(projectRoot);
879
+ if (viteVersionSupportsBundledDev(viteVersion)) config = (0, vite.mergeConfig)(config, {
880
+ experimental: { bundledDev: true },
881
+ plugins: [bundledDevCssUrlShim()]
882
+ });
883
+ else logWarning(`Bundled dev requested (${BUNDLED_DEV_ENV_VAR}=true), but installed Vite ${viteVersion ?? "unresolved"} is missing, prerelease, or below 8.1. Starting classic dev.`);
884
+ }
885
+ return isSandbox ? applySandboxServerInvariants(config) : applyNonSandboxWatchDefaults(config);
886
+ };
887
+ }
888
+ //#endregion
889
+ exports.defineConfig = defineConfig;
890
+
1129
891
  //# sourceMappingURL=index.cjs.map