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

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