@seedprotocol/vite 0.6.5 → 0.6.7
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.d.ts +16 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +155 -95
- package/dist/index.js.map +1 -1
- package/dist/stream-default-shim.d.ts +38 -0
- package/dist/stream-default-shim.d.ts.map +1 -0
- package/dist/stream-default-shim.js +46 -0
- package/package.json +5 -2
package/dist/index.d.ts
CHANGED
|
@@ -24,9 +24,25 @@ export interface SeedVitePluginOptions {
|
|
|
24
24
|
* Whether to automatically include vite-plugin-node-polyfills with sensible defaults.
|
|
25
25
|
* The SDK depends on that package and aliases its injected shim imports to absolute
|
|
26
26
|
* paths, so consuming apps do not need to install vite-plugin-node-polyfills themselves.
|
|
27
|
+
* Default include list omits full `stream`/`crypto` polyfills (those pull
|
|
28
|
+
* stream-browserify and break Vite SSR / React Router prerender). A minimal
|
|
29
|
+
* `stream` stub is still aliased so sax/rss-parser do not warn. Use `false`
|
|
30
|
+
* for Framework Mode / prerender.
|
|
27
31
|
* @default true
|
|
28
32
|
*/
|
|
29
33
|
includeNodePolyfills?: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Cross-origin isolation headers for sqlocal / SharedArrayBuffer / OPFS.
|
|
36
|
+
* Applied in configureServer and configurePreviewServer, including writeHead,
|
|
37
|
+
* because Vite `server.headers` is not copied onto Framework-Mode HTML responses.
|
|
38
|
+
* Set `false` to disable. Pass `{ coop, coep, corp }` to override values.
|
|
39
|
+
* @default true (`COOP: same-origin`, `COEP: credentialless`, `CORP: same-origin`)
|
|
40
|
+
*/
|
|
41
|
+
isolationHeaders?: boolean | {
|
|
42
|
+
coop?: string;
|
|
43
|
+
coep?: string;
|
|
44
|
+
corp?: string;
|
|
45
|
+
};
|
|
30
46
|
}
|
|
31
47
|
/**
|
|
32
48
|
* Minimal Vite plugin to make the SDK work in browser/Electron renderer:
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAa,MAAM,EAA4C,MAAM,MAAM,CAAA;AASvF,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,EAAE,CAAA;IAEpB;;;;;;;;OAQG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;IAElB;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IAEf;;;;;;;;;OASG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAA;IAE9B;;;;;;OAMG;IACH,gBAAgB,CAAC,EAAE,OAAO,GAAG;QAC3B,IAAI,CAAC,EAAE,MAAM,CAAA;QACb,IAAI,CAAC,EAAE,MAAM,CAAA;QACb,IAAI,CAAC,EAAE,MAAM,CAAA;KACd,CAAA;CACF;AA6oBD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,cAAc,CAAC,OAAO,GAAE,qBAA0B,GAAG,MAAM,EAAE,CA4gB5E"}
|
package/dist/index.js
CHANGED
|
@@ -37,19 +37,40 @@ var l = [
|
|
|
37
37
|
"fs/promises",
|
|
38
38
|
"node:fs",
|
|
39
39
|
"node:fs/promises"
|
|
40
|
-
], u = n.dirname(r(import.meta.url)), d = n.join(u, "arweave-default-shim.js"), f = n.join(u, "debug-default-shim.js"), p = [
|
|
40
|
+
], u = n.dirname(r(import.meta.url)), d = n.join(u, "arweave-default-shim.js"), f = n.join(u, "debug-default-shim.js"), p = n.join(u, "stream-default-shim.js"), m = [
|
|
41
41
|
"debug",
|
|
42
42
|
"random",
|
|
43
43
|
"seedrandom",
|
|
44
44
|
"@georgedoescode/generative-utils",
|
|
45
45
|
"nanoid-dictionary"
|
|
46
|
-
],
|
|
47
|
-
|
|
46
|
+
], h = ["@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk", "@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk > @ethereum-attestation-service/eas-contracts"], g = ["pluralize"], _ = {
|
|
47
|
+
"Cross-Origin-Opener-Policy": "same-origin",
|
|
48
|
+
"Cross-Origin-Embedder-Policy": "credentialless",
|
|
49
|
+
"Cross-Origin-Resource-Policy": "same-origin"
|
|
50
|
+
};
|
|
51
|
+
function v(e) {
|
|
52
|
+
if (e === !1) return null;
|
|
53
|
+
let t = typeof e == "object" && e ? e : {};
|
|
54
|
+
return {
|
|
55
|
+
"Cross-Origin-Opener-Policy": t.coop ?? _["Cross-Origin-Opener-Policy"],
|
|
56
|
+
"Cross-Origin-Embedder-Policy": t.coep ?? _["Cross-Origin-Embedder-Policy"],
|
|
57
|
+
"Cross-Origin-Resource-Policy": t.corp ?? _["Cross-Origin-Resource-Policy"]
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function y(e, t) {
|
|
61
|
+
e.middlewares.use((e, n, r) => {
|
|
62
|
+
let i = () => {
|
|
63
|
+
for (let [e, r] of Object.entries(t)) n.getHeader(e) || n.setHeader(e, r);
|
|
64
|
+
}, a = n.writeHead.bind(n);
|
|
65
|
+
n.writeHead = ((...e) => (i(), a(...e))), i(), r();
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
function b(t, r, i, a) {
|
|
48
69
|
if (!e.existsSync(t)) return;
|
|
49
70
|
let o = r.startsWith("@") ? r.replace("/", "+") : r;
|
|
50
71
|
for (let s of e.readdirSync(t)) (s.startsWith(`${o}@`) || s.startsWith(`${r}@`)) && a.push(n.join(t, s, `node_modules/${r}`, i));
|
|
51
72
|
}
|
|
52
|
-
function
|
|
73
|
+
function x(t, r) {
|
|
53
74
|
let i = [], o = n.resolve(u, "..");
|
|
54
75
|
try {
|
|
55
76
|
let e = a.resolve(`${t}/package.json`);
|
|
@@ -73,12 +94,12 @@ function g(t, r) {
|
|
|
73
94
|
}
|
|
74
95
|
i.push(n.join(o, "node_modules", t, r));
|
|
75
96
|
let s = n.join(process.cwd(), "node_modules");
|
|
76
|
-
i.push(n.join(s, t, r)),
|
|
77
|
-
let c =
|
|
78
|
-
c &&
|
|
97
|
+
i.push(n.join(s, t, r)), b(n.join(s, ".bun"), t, r, i), b(n.join(o, "node_modules", ".bun"), t, r, i);
|
|
98
|
+
let c = S(o);
|
|
99
|
+
c && b(n.join(c, "node_modules", ".bun"), t, r, i);
|
|
79
100
|
for (let t of i) if (e.existsSync(t)) return t;
|
|
80
101
|
}
|
|
81
|
-
function
|
|
102
|
+
function S(t) {
|
|
82
103
|
let r = n.resolve(t);
|
|
83
104
|
for (let t = 0; t < 8; t++) {
|
|
84
105
|
if (e.existsSync(n.join(r, "node_modules", ".bun"))) return r;
|
|
@@ -87,23 +108,23 @@ function _(t) {
|
|
|
87
108
|
r = t;
|
|
88
109
|
}
|
|
89
110
|
}
|
|
90
|
-
function
|
|
111
|
+
function C(e, t) {
|
|
91
112
|
let r = n.resolve(t);
|
|
92
113
|
return e.some((e) => {
|
|
93
114
|
let t = n.resolve(String(e));
|
|
94
115
|
return r === t || r.startsWith(t.endsWith(n.sep) ? t : t + n.sep);
|
|
95
116
|
});
|
|
96
117
|
}
|
|
97
|
-
function
|
|
118
|
+
function w(t) {
|
|
98
119
|
try {
|
|
99
120
|
return e.realpathSync(t);
|
|
100
121
|
} catch {
|
|
101
122
|
return n.resolve(t);
|
|
102
123
|
}
|
|
103
124
|
}
|
|
104
|
-
function
|
|
125
|
+
function T() {
|
|
105
126
|
let e = /* @__PURE__ */ new Set(), t = (t) => {
|
|
106
|
-
t && e.add(
|
|
127
|
+
t && e.add(w(t));
|
|
107
128
|
}, r;
|
|
108
129
|
try {
|
|
109
130
|
r = n.dirname(a.resolve("@seedprotocol/sdk/package.json"));
|
|
@@ -111,20 +132,20 @@ function b() {
|
|
|
111
132
|
r = n.resolve(u, "..");
|
|
112
133
|
}
|
|
113
134
|
t(r);
|
|
114
|
-
let i =
|
|
135
|
+
let i = S(r);
|
|
115
136
|
i && t(i);
|
|
116
137
|
for (let e of ["sqlocal", "@sqlite.org/sqlite-wasm"]) {
|
|
117
|
-
let r =
|
|
138
|
+
let r = x(e, "package.json");
|
|
118
139
|
r && t(n.dirname(r));
|
|
119
140
|
}
|
|
120
141
|
return [...e];
|
|
121
142
|
}
|
|
122
|
-
function
|
|
143
|
+
function E(e) {
|
|
123
144
|
let t = [];
|
|
124
|
-
for (let n of
|
|
145
|
+
for (let n of T()) C(e, n) || (e.push(n), t.push(n));
|
|
125
146
|
return t;
|
|
126
147
|
}
|
|
127
|
-
function
|
|
148
|
+
function D(e) {
|
|
128
149
|
return e ? Array.isArray(e) ? e.filter((e) => !!e && !!e.replacement).map((e) => ({
|
|
129
150
|
find: e.find,
|
|
130
151
|
replacement: e.replacement
|
|
@@ -133,7 +154,7 @@ function S(e) {
|
|
|
133
154
|
replacement: String(t)
|
|
134
155
|
})) : [];
|
|
135
156
|
}
|
|
136
|
-
function
|
|
157
|
+
function O(e, t) {
|
|
137
158
|
let n = [...e], r = (e) => typeof e == "string" ? `s:${e}` : `r:${e.toString()}`, i = new Set(n.map((e) => r(e.find)));
|
|
138
159
|
for (let e of t) {
|
|
139
160
|
let t = r(e.find);
|
|
@@ -141,12 +162,12 @@ function C(e, t) {
|
|
|
141
162
|
}
|
|
142
163
|
return n;
|
|
143
164
|
}
|
|
144
|
-
var
|
|
165
|
+
var k = [
|
|
145
166
|
"vite-plugin-node-polyfills/shims/buffer",
|
|
146
167
|
"vite-plugin-node-polyfills/shims/global",
|
|
147
168
|
"vite-plugin-node-polyfills/shims/process"
|
|
148
169
|
];
|
|
149
|
-
function
|
|
170
|
+
function A(t) {
|
|
150
171
|
let n = a.resolve(t);
|
|
151
172
|
if (n.endsWith(".cjs")) {
|
|
152
173
|
let t = n.slice(0, -4) + ".js";
|
|
@@ -154,10 +175,10 @@ function T(t) {
|
|
|
154
175
|
}
|
|
155
176
|
return n;
|
|
156
177
|
}
|
|
157
|
-
function
|
|
178
|
+
function j() {
|
|
158
179
|
let e = {}, t = [];
|
|
159
|
-
for (let n of
|
|
160
|
-
let t =
|
|
180
|
+
for (let n of k) try {
|
|
181
|
+
let t = A(n);
|
|
161
182
|
n.endsWith("/buffer") ? e.buffer = t : n.endsWith("/global") ? e.global = t : n.endsWith("/process") && (e.process = t);
|
|
162
183
|
} catch {
|
|
163
184
|
t.push(n);
|
|
@@ -167,7 +188,7 @@ function E() {
|
|
|
167
188
|
unresolved: t
|
|
168
189
|
};
|
|
169
190
|
}
|
|
170
|
-
function
|
|
191
|
+
function M(e, t) {
|
|
171
192
|
if ((e.match(/import\s+__buffer_polyfill\b/g) || []).length <= 1 || !t.buffer || !t.global || !t.process) return null;
|
|
172
193
|
let n = e.replace(/import\s+__buffer_polyfill\s+from\s+['"][^'"]+['"];?\s*\n\s*globalThis\.Buffer\s*=\s*globalThis\.Buffer\s*\|\|\s*__buffer_polyfill;?\s*\n\s*import\s+__global_polyfill\s+from\s+['"][^'"]+['"];?\s*\n\s*globalThis\.global\s*=\s*globalThis\.global\s*\|\|\s*__global_polyfill;?\s*\n\s*import\s+__process_polyfill\s+from\s+['"][^'"]+['"];?\s*\n\s*globalThis\.process\s*=\s*globalThis\.process\s*\|\|\s*__process_polyfill;?\s*\n?/g, "");
|
|
173
194
|
return n === e ? null : `import __buffer_polyfill from ${JSON.stringify(t.buffer)};\nglobalThis.Buffer = globalThis.Buffer || __buffer_polyfill;
|
|
@@ -175,7 +196,7 @@ import __global_polyfill from ${JSON.stringify(t.global)};\nglobalThis.global =
|
|
|
175
196
|
import __process_polyfill from ${JSON.stringify(t.process)};\nglobalThis.process = globalThis.process || __process_polyfill;
|
|
176
197
|
` + n;
|
|
177
198
|
}
|
|
178
|
-
function
|
|
199
|
+
function N(e, t) {
|
|
179
200
|
let n = e, r = !1, i = [];
|
|
180
201
|
t.buffer && i.push(["vite-plugin-node-polyfills/shims/buffer", t.buffer]), t.global && i.push(["vite-plugin-node-polyfills/shims/global", t.global]), t.process && i.push(["vite-plugin-node-polyfills/shims/process", t.process]);
|
|
181
202
|
for (let [e, t] of i) {
|
|
@@ -187,7 +208,7 @@ function O(e, t) {
|
|
|
187
208
|
}
|
|
188
209
|
return r ? n : null;
|
|
189
210
|
}
|
|
190
|
-
function
|
|
211
|
+
function P(e, t) {
|
|
191
212
|
t.buffer && e.push({
|
|
192
213
|
find: "vite-plugin-node-polyfills/shims/buffer",
|
|
193
214
|
replacement: t.buffer
|
|
@@ -214,11 +235,11 @@ function k(e, t) {
|
|
|
214
235
|
replacement: t.process
|
|
215
236
|
});
|
|
216
237
|
}
|
|
217
|
-
function
|
|
238
|
+
function F(e) {
|
|
218
239
|
let t = {};
|
|
219
240
|
return e.buffer && (t["vite-plugin-node-polyfills/shims/buffer"] = e.buffer, t.buffer = e.buffer, t["node:buffer"] = e.buffer), e.global && (t["vite-plugin-node-polyfills/shims/global"] = e.global, t.global = e.global), e.process && (t["vite-plugin-node-polyfills/shims/process"] = e.process, t.process = e.process, t["node:process"] = e.process), t;
|
|
220
241
|
}
|
|
221
|
-
var
|
|
242
|
+
var I = /* @__PURE__ */ new Set([
|
|
222
243
|
"vite-plugin-node-polyfills/shims/buffer",
|
|
223
244
|
"vite-plugin-node-polyfills/shims/global",
|
|
224
245
|
"vite-plugin-node-polyfills/shims/process",
|
|
@@ -228,19 +249,19 @@ var j = /* @__PURE__ */ new Set([
|
|
|
228
249
|
"node:process",
|
|
229
250
|
"global"
|
|
230
251
|
]);
|
|
231
|
-
function
|
|
252
|
+
function L(e, t) {
|
|
232
253
|
let n = [];
|
|
233
|
-
if (
|
|
234
|
-
let r = e.filter((e) => typeof e.find != "string" || !
|
|
254
|
+
if (P(n, t), n.length === 0) return e;
|
|
255
|
+
let r = e.filter((e) => typeof e.find != "string" || !I.has(e.find));
|
|
235
256
|
return [...n, ...r];
|
|
236
257
|
}
|
|
237
|
-
function
|
|
238
|
-
let n =
|
|
258
|
+
function R(t) {
|
|
259
|
+
let n = x("nanoid-dictionary", "dist/dictionary.esm.js");
|
|
239
260
|
n && t.push({
|
|
240
261
|
find: /^nanoid-dictionary$/,
|
|
241
262
|
replacement: n
|
|
242
263
|
});
|
|
243
|
-
let r =
|
|
264
|
+
let r = x("@zenfs/core", "dist/index.js"), i = x("@zenfs/core", "dist/path.js");
|
|
244
265
|
r && t.push({
|
|
245
266
|
find: /^@zenfs\/core$/,
|
|
246
267
|
replacement: r
|
|
@@ -248,7 +269,7 @@ function N(t) {
|
|
|
248
269
|
find: /^@zenfs\/core\/path$/,
|
|
249
270
|
replacement: i
|
|
250
271
|
});
|
|
251
|
-
let a =
|
|
272
|
+
let a = x("@zenfs/dom", "dist/index.js");
|
|
252
273
|
a && t.push({
|
|
253
274
|
find: /^@zenfs\/dom$/,
|
|
254
275
|
replacement: a
|
|
@@ -256,22 +277,34 @@ function N(t) {
|
|
|
256
277
|
find: /^debug$/,
|
|
257
278
|
replacement: f
|
|
258
279
|
});
|
|
259
|
-
let o =
|
|
280
|
+
let o = x("debug", "src/browser.js");
|
|
260
281
|
o && t.push({
|
|
261
282
|
find: /^debug\/src\/browser\.js$/,
|
|
262
283
|
replacement: o
|
|
284
|
+
}), e.existsSync(p) && t.push({
|
|
285
|
+
find: /^stream$/,
|
|
286
|
+
replacement: p
|
|
287
|
+
}, {
|
|
288
|
+
find: /^node:stream$/,
|
|
289
|
+
replacement: p
|
|
263
290
|
});
|
|
264
291
|
}
|
|
265
|
-
function
|
|
266
|
-
let e =
|
|
292
|
+
function z() {
|
|
293
|
+
let e = x("debug", "src/browser.js");
|
|
267
294
|
return e ? { "debug/src/browser.js": e } : {};
|
|
268
295
|
}
|
|
269
|
-
function
|
|
296
|
+
function B() {
|
|
297
|
+
return e.existsSync(p) ? {
|
|
298
|
+
stream: p,
|
|
299
|
+
"node:stream": p
|
|
300
|
+
} : {};
|
|
301
|
+
}
|
|
302
|
+
function V(e) {
|
|
270
303
|
let t = e ?? {};
|
|
271
304
|
return t.rolldownOptions ?? t.rollupOptions ?? {};
|
|
272
305
|
}
|
|
273
|
-
function
|
|
274
|
-
let n =
|
|
306
|
+
function H(e, t) {
|
|
307
|
+
let n = V(e), r = n.resolve ?? {}, i = n.transform ?? {}, a = {
|
|
275
308
|
...e?.esbuildOptions?.define ?? {},
|
|
276
309
|
...i.define,
|
|
277
310
|
...t.define
|
|
@@ -291,44 +324,45 @@ function I(e, t) {
|
|
|
291
324
|
} } : {}
|
|
292
325
|
};
|
|
293
326
|
}
|
|
294
|
-
function
|
|
327
|
+
function U(e) {
|
|
295
328
|
let { esbuildOptions: t, rollupOptions: n, ...r } = e ?? {};
|
|
296
329
|
return r;
|
|
297
330
|
}
|
|
298
|
-
function
|
|
299
|
-
let { fsModules: t = l, autoInit: n = !1, debug: r = !1, includeNodePolyfills: a = !0 } = e, o = (...e) => {
|
|
331
|
+
function W(e = {}) {
|
|
332
|
+
let { fsModules: t = l, autoInit: n = !1, debug: r = !1, includeNodePolyfills: a = !0, isolationHeaders: o } = e, s = v(o), u = "production", f = (...e) => {
|
|
300
333
|
r && console.log("[seed-vite-plugin]", ...e);
|
|
301
|
-
}, { paths:
|
|
302
|
-
a &&
|
|
303
|
-
let
|
|
334
|
+
}, { paths: p, unresolved: _ } = j(), b = F(p);
|
|
335
|
+
a && _.length > 0 ? console.warn("[seed-vite-plugin] Could not resolve vite-plugin-node-polyfills shims from the SDK package:\n" + _.map((e) => ` - ${e}`).join("\n") + "\nNode polyfill globals may fail to resolve. Reinstall @seedprotocol/sdk, or set includeNodePolyfills: false and configure polyfills yourself.") : _.length === 0 && f("Resolved vite-plugin-node-polyfills shims to absolute paths");
|
|
336
|
+
let S = {
|
|
304
337
|
name: "seed-protocol:config",
|
|
305
338
|
enforce: "pre",
|
|
306
339
|
configResolved(e) {
|
|
307
|
-
let t =
|
|
308
|
-
t.length > 0 &&
|
|
340
|
+
let t = E(e.server.fs.allow);
|
|
341
|
+
t.length > 0 && f("Extended server.fs.allow for linked SDK / sqlocal worker paths:", t);
|
|
309
342
|
},
|
|
310
|
-
config(e) {
|
|
311
|
-
|
|
343
|
+
config(e, n) {
|
|
344
|
+
n?.mode && (u = n.mode);
|
|
345
|
+
let r = [];
|
|
312
346
|
for (let e of t) {
|
|
313
347
|
let t = e.includes("promises") ? "@zenfs/core/promises" : "@zenfs/core";
|
|
314
|
-
|
|
348
|
+
r.push({
|
|
315
349
|
find: e,
|
|
316
350
|
replacement: t
|
|
317
351
|
});
|
|
318
352
|
}
|
|
319
|
-
let
|
|
320
|
-
|
|
353
|
+
let i = x("eventemitter3", "dist/eventemitter3.esm.js");
|
|
354
|
+
i && r.push({
|
|
321
355
|
find: "eventemitter3",
|
|
322
|
-
replacement:
|
|
356
|
+
replacement: i
|
|
323
357
|
}, {
|
|
324
358
|
find: "eventemitter3/index.mjs",
|
|
325
|
-
replacement:
|
|
359
|
+
replacement: i
|
|
326
360
|
}, {
|
|
327
361
|
find: "eventemitter3/index.js",
|
|
328
|
-
replacement:
|
|
362
|
+
replacement: i
|
|
329
363
|
});
|
|
330
|
-
let
|
|
331
|
-
|
|
364
|
+
let a = x("arweave", "bundles/web.bundle.js");
|
|
365
|
+
a && r.push({
|
|
332
366
|
find: /^arweave$/,
|
|
333
367
|
replacement: d
|
|
334
368
|
}, {
|
|
@@ -336,9 +370,9 @@ function R(e = {}) {
|
|
|
336
370
|
replacement: d
|
|
337
371
|
}, {
|
|
338
372
|
find: /^arweave\/bundles\/web\.bundle\.js$/,
|
|
339
|
-
replacement:
|
|
340
|
-
}),
|
|
341
|
-
let
|
|
373
|
+
replacement: a
|
|
374
|
+
}), R(r), P(r, p);
|
|
375
|
+
let o = e.resolve ?? {}, c = O(D(o.alias), r), l = [
|
|
342
376
|
"@zenfs/core",
|
|
343
377
|
"@zenfs/dom",
|
|
344
378
|
"kerium",
|
|
@@ -347,26 +381,28 @@ function R(e = {}) {
|
|
|
347
381
|
"readable-stream",
|
|
348
382
|
"viem",
|
|
349
383
|
"isows",
|
|
350
|
-
...
|
|
351
|
-
].filter((e) => !!
|
|
352
|
-
...
|
|
384
|
+
...m
|
|
385
|
+
].filter((e) => !!x(e, "package.json")), f = e.optimizeDeps, _ = z(), v = B(), y = {
|
|
386
|
+
...U(f),
|
|
353
387
|
exclude: [
|
|
354
|
-
...
|
|
388
|
+
...f?.exclude ?? [],
|
|
355
389
|
"@seedprotocol/sdk",
|
|
356
390
|
"drizzle-orm",
|
|
357
391
|
"better-sqlite3",
|
|
358
392
|
"sqlocal"
|
|
359
393
|
],
|
|
360
394
|
include: [
|
|
361
|
-
...
|
|
362
|
-
...
|
|
363
|
-
...
|
|
395
|
+
...f?.include ?? [],
|
|
396
|
+
...l,
|
|
397
|
+
...h,
|
|
398
|
+
...g
|
|
364
399
|
],
|
|
365
|
-
rolldownOptions:
|
|
400
|
+
rolldownOptions: H(f, {
|
|
366
401
|
define: { global: "globalThis" },
|
|
367
402
|
alias: {
|
|
368
|
-
...
|
|
369
|
-
...
|
|
403
|
+
..._,
|
|
404
|
+
...v,
|
|
405
|
+
...b
|
|
370
406
|
}
|
|
371
407
|
})
|
|
372
408
|
};
|
|
@@ -374,15 +410,14 @@ function R(e = {}) {
|
|
|
374
410
|
define: {
|
|
375
411
|
...e.define ?? {},
|
|
376
412
|
global: "globalThis",
|
|
377
|
-
"process.env.NODE_ENV": JSON.stringify("production"),
|
|
378
413
|
"process.browser": "true",
|
|
379
414
|
"process.platform": "\"browser\""
|
|
380
415
|
},
|
|
381
416
|
resolve: {
|
|
382
|
-
...
|
|
383
|
-
alias:
|
|
417
|
+
...o,
|
|
418
|
+
alias: c,
|
|
384
419
|
dedupe: Array.from(/* @__PURE__ */ new Set([
|
|
385
|
-
...
|
|
420
|
+
...o.dedupe ?? [],
|
|
386
421
|
"react",
|
|
387
422
|
"react-dom",
|
|
388
423
|
"thirdweb",
|
|
@@ -396,27 +431,43 @@ function R(e = {}) {
|
|
|
396
431
|
"@zenfs/dom"
|
|
397
432
|
]))
|
|
398
433
|
},
|
|
399
|
-
optimizeDeps:
|
|
434
|
+
optimizeDeps: y,
|
|
435
|
+
...s ? {
|
|
436
|
+
server: {
|
|
437
|
+
...e.server ?? {},
|
|
438
|
+
headers: {
|
|
439
|
+
...e.server?.headers ?? {},
|
|
440
|
+
...s
|
|
441
|
+
}
|
|
442
|
+
},
|
|
443
|
+
preview: {
|
|
444
|
+
...e.preview ?? {},
|
|
445
|
+
headers: {
|
|
446
|
+
...e.preview?.headers ?? {},
|
|
447
|
+
...s
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
} : {}
|
|
400
451
|
};
|
|
401
452
|
}
|
|
402
|
-
},
|
|
453
|
+
}, C = {
|
|
403
454
|
name: "seed-protocol:polyfill-resolve",
|
|
404
455
|
enforce: "post",
|
|
405
456
|
config(e) {
|
|
406
|
-
if (Object.keys(
|
|
407
|
-
let t = e.resolve ?? {}, n =
|
|
457
|
+
if (Object.keys(b).length === 0) return;
|
|
458
|
+
let t = e.resolve ?? {}, n = L(D(t.alias), p), r = e.optimizeDeps;
|
|
408
459
|
return {
|
|
409
460
|
resolve: {
|
|
410
461
|
...t,
|
|
411
462
|
alias: n
|
|
412
463
|
},
|
|
413
|
-
optimizeDeps: { rolldownOptions:
|
|
464
|
+
optimizeDeps: { rolldownOptions: H(r, { alias: b }) }
|
|
414
465
|
};
|
|
415
466
|
},
|
|
416
467
|
resolveId: {
|
|
417
468
|
order: "pre",
|
|
418
469
|
handler(e) {
|
|
419
|
-
return e === "vite-plugin-node-polyfills/shims/buffer" ?
|
|
470
|
+
return e === "vite-plugin-node-polyfills/shims/buffer" ? p.buffer ?? null : e === "vite-plugin-node-polyfills/shims/global" ? p.global ?? null : e === "vite-plugin-node-polyfills/shims/process" ? p.process ?? null : a ? e === "buffer" || e === "node:buffer" ? p.buffer ?? null : e === "global" ? p.global ?? null : e === "process" || e === "node:process" ? p.process ?? null : null : null;
|
|
420
471
|
}
|
|
421
472
|
},
|
|
422
473
|
transform: {
|
|
@@ -424,21 +475,27 @@ function R(e = {}) {
|
|
|
424
475
|
handler(e) {
|
|
425
476
|
let t = (e.match(/import\s+__buffer_polyfill\b/g) || []).length, n = e, r = !1;
|
|
426
477
|
if (t > 1) {
|
|
427
|
-
let e =
|
|
478
|
+
let e = M(n, p);
|
|
428
479
|
e && (n = e, r = !0);
|
|
429
480
|
}
|
|
430
|
-
let i =
|
|
481
|
+
let i = N(n, p);
|
|
431
482
|
return i && (n = i, r = !0), r ? {
|
|
432
483
|
code: n,
|
|
433
484
|
map: null
|
|
434
485
|
} : null;
|
|
435
486
|
}
|
|
436
487
|
}
|
|
437
|
-
},
|
|
438
|
-
|
|
488
|
+
}, w = [
|
|
489
|
+
S,
|
|
439
490
|
{
|
|
440
491
|
name: "seed-protocol:main",
|
|
441
492
|
enforce: "post",
|
|
493
|
+
configureServer(e) {
|
|
494
|
+
s && y(e, s);
|
|
495
|
+
},
|
|
496
|
+
configurePreviewServer(e) {
|
|
497
|
+
s && y(e, s);
|
|
498
|
+
},
|
|
442
499
|
config(e) {
|
|
443
500
|
let t = e.build ?? {}, n = t.commonjsOptions ?? {}, r = t.rollupOptions ?? {}, i = t.rolldownOptions, a = r.external ?? [], o = [
|
|
444
501
|
...Array.isArray(n.include) ? n.include : n.include ? [n.include] : [],
|
|
@@ -493,7 +550,12 @@ function R(e = {}) {
|
|
|
493
550
|
console.warn("");
|
|
494
551
|
},
|
|
495
552
|
transformIndexHtml(e) {
|
|
496
|
-
let t =
|
|
553
|
+
let t = `<script>
|
|
554
|
+
(function(){
|
|
555
|
+
if(typeof globalThis.global==='undefined')globalThis.global=globalThis;
|
|
556
|
+
if(typeof globalThis.process==='undefined')globalThis.process={env:{NODE_ENV:${JSON.stringify(u)}},browser:true,version:'v18.0.0',versions:{},platform:'browser',cwd:function(){return'/'},nextTick:function(fn){setTimeout(fn,0)}};
|
|
557
|
+
})();
|
|
558
|
+
<\/script>`, r = e;
|
|
497
559
|
if (r = r.includes("<head>") ? r.replace("<head>", `<head>\n${t}`) : t + r, !n) return r;
|
|
498
560
|
let i = "\n<script type=\"module\">\nimport { configure } from '@zenfs/core';\nimport { IndexedDB } from '@zenfs/dom';\n\nif (!window.__seedFsReady) {\n window.__seedFsReady = configure({\n mounts: { '/': IndexedDB },\n }).catch((err) => {\n console.error('[seed-vite-plugin] ZenFS initialization failed', err);\n });\n}\n<\/script>";
|
|
499
561
|
return r.includes("</head>") ? r.replace("</head>", `${i}\n</head>`) : r + i;
|
|
@@ -513,17 +575,15 @@ function R(e = {}) {
|
|
|
513
575
|
}
|
|
514
576
|
];
|
|
515
577
|
if (a) {
|
|
516
|
-
|
|
578
|
+
f("Including vite-plugin-node-polyfills with default settings");
|
|
517
579
|
let e = i({
|
|
518
580
|
exclude: ["readline"],
|
|
519
581
|
include: [
|
|
520
582
|
"path",
|
|
521
|
-
"crypto",
|
|
522
|
-
"stream",
|
|
523
|
-
"util",
|
|
524
583
|
"buffer",
|
|
525
584
|
"events",
|
|
526
|
-
"string_decoder"
|
|
585
|
+
"string_decoder",
|
|
586
|
+
"util"
|
|
527
587
|
],
|
|
528
588
|
globals: {
|
|
529
589
|
Buffer: !0,
|
|
@@ -532,11 +592,11 @@ function R(e = {}) {
|
|
|
532
592
|
},
|
|
533
593
|
protocolImports: !0
|
|
534
594
|
});
|
|
535
|
-
Array.isArray(e) ?
|
|
595
|
+
Array.isArray(e) ? w.push(...e) : w.push(e);
|
|
536
596
|
}
|
|
537
|
-
return Object.keys(
|
|
597
|
+
return Object.keys(b).length > 0 && w.push(C), w;
|
|
538
598
|
}
|
|
539
599
|
//#endregion
|
|
540
|
-
export {
|
|
600
|
+
export { W as seedVitePlugin };
|
|
541
601
|
|
|
542
602
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import type { Plugin, UserConfig } from 'vite'\nimport fs from 'node:fs'\nimport { createRequire } from 'node:module'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { nodePolyfills } from 'vite-plugin-node-polyfills'\n\nconst _req = createRequire(import.meta.url)\n\nexport interface SeedVitePluginOptions {\n /**\n * Additional modules to alias to ZenFS equivalents.\n * @default ['fs', 'fs/promises', 'node:fs', 'node:fs/promises']\n */\n fsModules?: string[]\n\n /**\n * Whether to inject automatic ZenFS initialization script into index.html.\n * When true, injects a <script type=\"module\"> that imports from '@zenfs/core'/'@zenfs/dom'.\n * Browsers cannot resolve those bare specifiers, so the script fails at runtime unless you use\n * an import map or load ZenFS another way. Prefer false and initialize ZenFS in your entry:\n * import { configure } from '@zenfs/core'; import { IndexedDB } from '@zenfs/dom';\n * await configure({ mounts: { '/': IndexedDB } });\n * @default false\n */\n autoInit?: boolean\n\n /**\n * Enable debug logging.\n * @default false\n */\n debug?: boolean\n\n /**\n * Whether to automatically include vite-plugin-node-polyfills with sensible defaults.\n * The SDK depends on that package and aliases its injected shim imports to absolute\n * paths, so consuming apps do not need to install vite-plugin-node-polyfills themselves.\n * @default true\n */\n includeNodePolyfills?: boolean\n}\n\n// Node.js globals that are undefined in browsers and will throw at runtime.\n// Keyed by identifier; value is the safe typeof-guard pattern so we can skip those.\nconst BROWSER_DANGEROUS_GLOBALS: Record<string, RegExp> = {\n global: /\\btypeof\\s+global\\b/,\n process: /\\btypeof\\s+process\\b/,\n Buffer: /\\btypeof\\s+Buffer\\b/,\n __dirname: /\\btypeof\\s+__dirname\\b/,\n __filename: /\\btypeof\\s+__filename\\b/,\n}\n\n/**\n * Strip JS string literals, template literals, and comments from source text\n * so that identifier searches don't false-positive on string content.\n * This is intentionally approximate — good enough for a lint-style warning pass.\n */\nfunction stripStringsAndComments(code: string): string {\n return code\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, (m) => ' '.repeat(m.length)) // /* block comments */\n .replace(/\\/\\/[^\\n]*/g, (m) => ' '.repeat(m.length)) // // line comments\n .replace(/`(?:[^`\\\\]|\\\\.)*`/gs, (m) => '`' + ' '.repeat(m.length - 2) + '`') // template literals\n .replace(/\"(?:[^\"\\\\]|\\\\.)*\"/g, (m) => '\"' + ' '.repeat(m.length - 2) + '\"') // double-quoted strings\n .replace(/'(?:[^'\\\\]|\\\\.)*'/g, (m) => \"'\" + ' '.repeat(m.length - 2) + \"'\") // single-quoted strings\n}\n\ninterface GlobalHit {\n global: string\n /** zero-based character offset in the stripped source */\n offset: number\n /** 1-based line number */\n line: number\n /** surrounding raw source for context */\n context: string\n}\n\nfunction findDangerousGlobals(rawCode: string): GlobalHit[] {\n const stripped = stripStringsAndComments(rawCode)\n const hits: GlobalHit[] = []\n\n for (const [name, typeofGuard] of Object.entries(BROWSER_DANGEROUS_GLOBALS)) {\n // Skip globalThis when checking 'global'\n const re = new RegExp(`(?<![.\\\\w$])\\\\b${name}\\\\b(?!This)(?![\\\\w$])`, 'g')\n let m: RegExpExecArray | null\n while ((m = re.exec(stripped)) !== null) {\n const offset = m.index\n // Check for typeof guard in the ~20 chars before the match\n const before = stripped.slice(Math.max(0, offset - 20), offset)\n if (typeofGuard.test(before)) continue\n\n // Compute 1-based line number from raw source (positions are preserved because\n // we replace with equal-length spaces, so offsets are stable)\n const linesBefore = rawCode.slice(0, offset).split('\\n')\n const line = linesBefore.length\n const colOffset = linesBefore.at(-1)?.length ?? 0\n const rawLine = rawCode.split('\\n')[line - 1] ?? ''\n const ctx = rawLine.slice(Math.max(0, colOffset - 40), colOffset + name.length + 40).trim()\n\n hits.push({ global: name, offset, line, context: ctx })\n }\n }\n\n return hits\n}\n\nconst DEFAULT_FS_MODULES = [\n 'fs',\n 'fs/promises',\n 'node:fs',\n 'node:fs/promises',\n]\nconst SDK_DIST_DIR = path.dirname(fileURLToPath(import.meta.url))\nconst ARWEAVE_SHIM_FILE = path.join(SDK_DIST_DIR, 'arweave-default-shim.js')\nconst DEBUG_SHIM_FILE = path.join(SDK_DIST_DIR, 'debug-default-shim.js')\n\n/** Fragile renderer deps pre-bundled for stable CJS/ESM interop (aligned with permapress). */\nconst FRAGILE_RENDERER_OPTIMIZE_INCLUDES = [\n 'debug',\n 'random',\n 'seedrandom',\n '@georgedoescode/generative-utils',\n 'nanoid-dictionary',\n] as const\n\n/**\n * Always force-include (do not gate on resolvePackageFile): under bun these live nested\n * under @seedprotocol/sdk, and eas-sdk's ESM named-imports CJS eas-contracts. Without\n * prebundling, Vite serves raw /@fs CJS and the browser throws\n * \"does not provide an export named 'EAS__factory'\" during SchemaEncoder encode.\n */\nconst EAS_OPTIMIZE_INCLUDES = [\n '@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk',\n '@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk > @ethereum-attestation-service/eas-contracts',\n] as const\n\ntype AliasEntry = { find: string | RegExp; replacement: string }\n\nfunction pushBunPackageCandidates(\n bunDir: string,\n packageName: string,\n relativePath: string,\n candidates: string[],\n): void {\n if (!fs.existsSync(bunDir)) return\n // Nested scopes (@scope/name) live under .bun as @scope+name@version/...\n const bunPrefix = packageName.startsWith('@')\n ? packageName.replace('/', '+')\n : packageName\n for (const entry of fs.readdirSync(bunDir)) {\n if (!entry.startsWith(`${bunPrefix}@`) && !entry.startsWith(`${packageName}@`)) continue\n candidates.push(path.join(bunDir, entry, `node_modules/${packageName}`, relativePath))\n }\n}\n\nfunction resolvePackageFile(packageName: string, relativePath: string): string | undefined {\n const candidates: string[] = []\n const sdkRoot = path.resolve(SDK_DIST_DIR, '..')\n\n try {\n const pkgJson = _req.resolve(`${packageName}/package.json`)\n candidates.push(path.join(path.dirname(pkgJson), relativePath))\n } catch {\n // Many packages (e.g. sqlocal) omit package.json from \"exports\". Resolve an\n // entry file and walk up to the package root instead.\n try {\n const entry = _req.resolve(packageName)\n let dir = path.dirname(entry)\n for (let i = 0; i < 8; i++) {\n const pkgJsonPath = path.join(dir, 'package.json')\n if (fs.existsSync(pkgJsonPath)) {\n try {\n const pkgName = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8')).name\n if (pkgName === packageName) {\n candidates.push(path.join(dir, relativePath))\n break\n }\n } catch {\n // ignore invalid package.json\n }\n }\n const parent = path.dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n } catch {\n // package may be hoisted/unavailable in this graph\n }\n }\n\n // Linked/file installs: deps often live under the SDK package, not the app cwd.\n candidates.push(path.join(sdkRoot, 'node_modules', packageName, relativePath))\n\n const cwdNodeModules = path.join(process.cwd(), 'node_modules')\n candidates.push(path.join(cwdNodeModules, packageName, relativePath))\n\n pushBunPackageCandidates(\n path.join(cwdNodeModules, '.bun'),\n packageName,\n relativePath,\n candidates,\n )\n pushBunPackageCandidates(\n path.join(sdkRoot, 'node_modules', '.bun'),\n packageName,\n relativePath,\n candidates,\n )\n const bunInstallRoot = findNodeModulesBunRoot(sdkRoot)\n if (bunInstallRoot) {\n pushBunPackageCandidates(\n path.join(bunInstallRoot, 'node_modules', '.bun'),\n packageName,\n relativePath,\n candidates,\n )\n }\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate\n }\n return undefined\n}\n\n/** Walk up from startDir looking for a directory that contains node_modules/.bun. */\nfunction findNodeModulesBunRoot(startDir: string): string | undefined {\n let dir = path.resolve(startDir)\n for (let i = 0; i < 8; i++) {\n if (fs.existsSync(path.join(dir, 'node_modules', '.bun'))) return dir\n const parent = path.dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n return undefined\n}\n\nfunction isFsAllowCovering(allow: readonly string[], filePath: string): boolean {\n const child = path.resolve(filePath)\n return allow.some((uri) => {\n const parent = path.resolve(String(uri))\n return (\n child === parent ||\n child.startsWith(parent.endsWith(path.sep) ? parent : parent + path.sep)\n )\n })\n}\n\nfunction realpathOrResolve(p: string): string {\n try {\n return fs.realpathSync(p)\n } catch {\n return path.resolve(p)\n }\n}\n\n/**\n * When the SDK is linked (file:/symlink) into an external app, sqlocal's worker\n * and sqlite-wasm assets resolve into the SDK install tree (often bun's .bun\n * store). Vite's default server.fs.allow only covers the consumer workspace, so\n * those absolute /@fs requests 403 unless we allowlist the install roots.\n */\nfunction collectDevServerFsAllowPaths(): string[] {\n const paths = new Set<string>()\n const add = (p?: string) => {\n if (!p) return\n paths.add(realpathOrResolve(p))\n }\n\n let sdkPkgDir: string\n try {\n sdkPkgDir = path.dirname(_req.resolve('@seedprotocol/sdk/package.json'))\n } catch {\n sdkPkgDir = path.resolve(SDK_DIST_DIR, '..')\n }\n add(sdkPkgDir)\n\n const bunInstallRoot = findNodeModulesBunRoot(sdkPkgDir)\n if (bunInstallRoot) add(bunInstallRoot)\n\n for (const pkg of ['sqlocal', '@sqlite.org/sqlite-wasm'] as const) {\n const pkgJson = resolvePackageFile(pkg, 'package.json')\n if (pkgJson) add(path.dirname(pkgJson))\n }\n\n return [...paths]\n}\n\nfunction ensureDevServerFsAllow(allow: string[]): string[] {\n const added: string[] = []\n for (const dir of collectDevServerFsAllowPaths()) {\n if (isFsAllowCovering(allow, dir)) continue\n allow.push(dir)\n added.push(dir)\n }\n return added\n}\n\nfunction normalizeAliasEntries(\n alias: NonNullable<UserConfig['resolve']>['alias'] | undefined\n): AliasEntry[] {\n if (!alias) return []\n if (Array.isArray(alias)) {\n return alias\n .filter((entry): entry is AliasEntry => !!entry && !!(entry as AliasEntry).replacement)\n .map((entry) => ({ find: entry.find, replacement: entry.replacement }))\n }\n\n return Object.entries(alias).map(([find, replacement]) => ({\n find,\n replacement: String(replacement),\n }))\n}\n\nfunction mergeAliasEntries(existing: AliasEntry[], additions: AliasEntry[]): AliasEntry[] {\n const merged = [...existing]\n const keyOf = (find: string | RegExp) =>\n typeof find === 'string' ? `s:${find}` : `r:${find.toString()}`\n const seen = new Set(merged.map((entry) => keyOf(entry.find)))\n\n for (const entry of additions) {\n const key = keyOf(entry.find)\n if (seen.has(key)) continue\n seen.add(key)\n merged.push(entry)\n }\n\n return merged\n}\n\n/** Bare IDs that vite-plugin-node-polyfills injects into every transformed module. */\nconst NODE_POLYFILL_SHIM_IDS = [\n 'vite-plugin-node-polyfills/shims/buffer',\n 'vite-plugin-node-polyfills/shims/global',\n 'vite-plugin-node-polyfills/shims/process',\n] as const\n\ntype NodePolyfillShimPaths = {\n buffer?: string\n global?: string\n process?: string\n}\n\n/**\n * Prefer the package \"import\" ESM build (index.js). createRequire resolves the\n * \"require\" condition (index.cjs); Vite then serves `/@fs/...cjs?import` and\n * default-import fails in the browser.\n */\nfunction resolvePolyfillShimFile(shimId: string): string {\n const resolved = _req.resolve(shimId)\n if (resolved.endsWith('.cjs')) {\n const esm = resolved.slice(0, -4) + '.js'\n if (fs.existsSync(esm)) return esm\n }\n return resolved\n}\n\nfunction resolveNodePolyfillShimPaths(): {\n paths: NodePolyfillShimPaths\n unresolved: string[]\n} {\n const paths: NodePolyfillShimPaths = {}\n const unresolved: string[] = []\n for (const id of NODE_POLYFILL_SHIM_IDS) {\n try {\n const abs = resolvePolyfillShimFile(id)\n if (id.endsWith('/buffer')) paths.buffer = abs\n else if (id.endsWith('/global')) paths.global = abs\n else if (id.endsWith('/process')) paths.process = abs\n } catch {\n unresolved.push(id)\n }\n }\n return { paths, unresolved }\n}\n\n/**\n * Collapse repeated vite-plugin-node-polyfills globals banners (Vite 8 optimizer + serve).\n * Re-inject with absolute ESM paths: this runs in transform order \"post\" (after\n * import-analysis), so bare package ids would reach the browser unresolved\n * (\"Relative references must start with /, ./, or ../\").\n */\nfunction dedupeNodePolyfillBanner(\n code: string,\n paths: NodePolyfillShimPaths,\n): string | null {\n const importCount = (code.match(/import\\s+__buffer_polyfill\\b/g) || []).length\n if (importCount <= 1) return null\n if (!paths.buffer || !paths.global || !paths.process) return null\n\n const bannerRe =\n /import\\s+__buffer_polyfill\\s+from\\s+['\"][^'\"]+['\"];?\\s*\\n\\s*globalThis\\.Buffer\\s*=\\s*globalThis\\.Buffer\\s*\\|\\|\\s*__buffer_polyfill;?\\s*\\n\\s*import\\s+__global_polyfill\\s+from\\s+['\"][^'\"]+['\"];?\\s*\\n\\s*globalThis\\.global\\s*=\\s*globalThis\\.global\\s*\\|\\|\\s*__global_polyfill;?\\s*\\n\\s*import\\s+__process_polyfill\\s+from\\s+['\"][^'\"]+['\"];?\\s*\\n\\s*globalThis\\.process\\s*=\\s*globalThis\\.process\\s*\\|\\|\\s*__process_polyfill;?\\s*\\n?/g\n\n const cleaned = code.replace(bannerRe, '')\n if (cleaned === code) return null\n\n const banner =\n `import __buffer_polyfill from ${JSON.stringify(paths.buffer)};\\n` +\n 'globalThis.Buffer = globalThis.Buffer || __buffer_polyfill;\\n' +\n `import __global_polyfill from ${JSON.stringify(paths.global)};\\n` +\n 'globalThis.global = globalThis.global || __global_polyfill;\\n' +\n `import __process_polyfill from ${JSON.stringify(paths.process)};\\n` +\n 'globalThis.process = globalThis.process || __process_polyfill;\\n'\n\n return banner + cleaned\n}\n\n/** Rewrite leftover bare shim package ids to absolute ESM files (post import-analysis). */\nfunction rewriteBarePolyfillShimImports(\n code: string,\n paths: NodePolyfillShimPaths,\n): string | null {\n let next = code\n let changed = false\n const replacements: Array<[string, string]> = []\n if (paths.buffer) {\n replacements.push(['vite-plugin-node-polyfills/shims/buffer', paths.buffer])\n }\n if (paths.global) {\n replacements.push(['vite-plugin-node-polyfills/shims/global', paths.global])\n }\n if (paths.process) {\n replacements.push(['vite-plugin-node-polyfills/shims/process', paths.process])\n }\n for (const [bare, abs] of replacements) {\n const absLiteral = JSON.stringify(abs)\n for (const quote of ['\"', \"'\"] as const) {\n const from = `${quote}${bare}${quote}`\n if (!next.includes(from)) continue\n next = next.split(from).join(absLiteral)\n changed = true\n }\n }\n return changed ? next : null\n}\n\n/**\n * Alias polyfill shim bare imports + buffer/process/global module ids to absolute\n * paths resolved from this package. Nested installs under @seedprotocol/sdk are\n * invisible to consumer-project resolution (and to Vite 8's Rolldown optimizer)\n * unless we rewrite to absolute files.\n */\nfunction addNodePolyfillShimAliases(\n aliasEntries: AliasEntry[],\n paths: NodePolyfillShimPaths,\n): void {\n if (paths.buffer) {\n aliasEntries.push(\n { find: 'vite-plugin-node-polyfills/shims/buffer', replacement: paths.buffer },\n { find: /^buffer$/, replacement: paths.buffer },\n { find: /^node:buffer$/, replacement: paths.buffer },\n )\n }\n if (paths.global) {\n aliasEntries.push(\n { find: 'vite-plugin-node-polyfills/shims/global', replacement: paths.global },\n { find: /^global$/, replacement: paths.global },\n )\n }\n if (paths.process) {\n aliasEntries.push(\n { find: 'vite-plugin-node-polyfills/shims/process', replacement: paths.process },\n { find: /^process$/, replacement: paths.process },\n { find: /^node:process$/, replacement: paths.process },\n )\n }\n}\n\n/** Object-form aliases for optimizeDeps.rolldown/rollup resolve (string keys). */\nfunction nodePolyfillShimAliasObject(paths: NodePolyfillShimPaths): Record<string, string> {\n const alias: Record<string, string> = {}\n if (paths.buffer) {\n alias['vite-plugin-node-polyfills/shims/buffer'] = paths.buffer\n alias.buffer = paths.buffer\n alias['node:buffer'] = paths.buffer\n }\n if (paths.global) {\n alias['vite-plugin-node-polyfills/shims/global'] = paths.global\n alias.global = paths.global\n }\n if (paths.process) {\n alias['vite-plugin-node-polyfills/shims/process'] = paths.process\n alias.process = paths.process\n alias['node:process'] = paths.process\n }\n return alias\n}\n\nconst POLYFILL_ALIAS_FINDS_TO_REPLACE = new Set([\n 'vite-plugin-node-polyfills/shims/buffer',\n 'vite-plugin-node-polyfills/shims/global',\n 'vite-plugin-node-polyfills/shims/process',\n 'buffer',\n 'node:buffer',\n 'process',\n 'node:process',\n 'global',\n])\n\n/**\n * Put absolute polyfill aliases first and drop bare/package-id entries that\n * vite-plugin-node-polyfills may have added for the same modules (first match wins).\n */\nfunction withPreferredPolyfillAliases(\n existing: AliasEntry[],\n paths: NodePolyfillShimPaths,\n): AliasEntry[] {\n const preferred: AliasEntry[] = []\n addNodePolyfillShimAliases(preferred, paths)\n if (preferred.length === 0) return existing\n\n const filtered = existing.filter((entry) => {\n if (typeof entry.find !== 'string') return true\n return !POLYFILL_ALIAS_FINDS_TO_REPLACE.has(entry.find)\n })\n return [...preferred, ...filtered]\n}\n\nfunction addRendererCompatibilityAliases(aliasEntries: AliasEntry[]): void {\n const nanoidDictionaryEsm = resolvePackageFile(\n 'nanoid-dictionary',\n 'dist/dictionary.esm.js',\n )\n if (nanoidDictionaryEsm) {\n aliasEntries.push({\n find: /^nanoid-dictionary$/,\n replacement: nanoidDictionaryEsm,\n })\n }\n\n const zenfsCoreIndex = resolvePackageFile('@zenfs/core', 'dist/index.js')\n const zenfsCorePath = resolvePackageFile('@zenfs/core', 'dist/path.js')\n if (zenfsCoreIndex) {\n aliasEntries.push({ find: /^@zenfs\\/core$/, replacement: zenfsCoreIndex })\n }\n if (zenfsCorePath) {\n aliasEntries.push({ find: /^@zenfs\\/core\\/path$/, replacement: zenfsCorePath })\n }\n\n const zenfsDomIndex = resolvePackageFile('@zenfs/dom', 'dist/index.js')\n if (zenfsDomIndex) {\n aliasEntries.push({ find: /^@zenfs\\/dom$/, replacement: zenfsDomIndex })\n }\n\n if (fs.existsSync(DEBUG_SHIM_FILE)) {\n // Only alias the package root. Do not alias debug/src/browser.js to this shim:\n // the shim imports that path and aliasing it back creates a circular module.\n aliasEntries.push({ find: /^debug$/, replacement: DEBUG_SHIM_FILE })\n }\n\n const debugBrowserEntry = resolvePackageFile('debug', 'src/browser.js')\n if (debugBrowserEntry) {\n aliasEntries.push({\n find: /^debug\\/src\\/browser\\.js$/,\n replacement: debugBrowserEntry,\n })\n }\n}\n\n/** Object-form aliases for optimizeDeps pre-bundle (debug shim subpath). */\nfunction debugShimOptimizeAliasObject(): Record<string, string> {\n const debugBrowserEntry = resolvePackageFile('debug', 'src/browser.js')\n return debugBrowserEntry ? { 'debug/src/browser.js': debugBrowserEntry } : {}\n}\n\ntype OptimizeDepsConfig = NonNullable<UserConfig['optimizeDeps']>\n\n/** Read Rolldown optimizer options, falling back to deprecated rollup/esbuild shapes. */\nfunction readOptimizeDepsRolldownBase(\n existing: OptimizeDepsConfig | undefined,\n): Record<string, unknown> {\n const opt = existing ?? {}\n return (\n opt.rolldownOptions ??\n (opt as { rollupOptions?: Record<string, unknown> }).rollupOptions ??\n {}\n ) as Record<string, unknown>\n}\n\n/**\n * Merge Vite 8 `optimizeDeps.rolldownOptions` without returning deprecated\n * `esbuildOptions` / `rollupOptions` keys from plugin config hooks.\n */\nfunction mergeOptimizeDepsRolldownOptions(\n existing: OptimizeDepsConfig | undefined,\n patch: {\n define?: Record<string, string>\n alias?: Record<string, string>\n },\n): OptimizeDepsConfig['rolldownOptions'] {\n const base = readOptimizeDepsRolldownBase(existing)\n const existingResolve = (base.resolve as { alias?: Record<string, string> } | undefined) ?? {}\n const existingTransform = (base.transform as { define?: Record<string, string> } | undefined) ?? {}\n const legacyDefine = existing?.esbuildOptions?.define ?? {}\n\n const mergedDefine = {\n ...legacyDefine,\n ...existingTransform.define,\n ...patch.define,\n }\n const mergedAlias = {\n ...existingResolve.alias,\n ...patch.alias,\n }\n\n return {\n ...base,\n ...(Object.keys(mergedDefine).length > 0\n ? {\n transform: {\n ...existingTransform,\n define: mergedDefine,\n },\n }\n : {}),\n ...(Object.keys(mergedAlias).length > 0\n ? {\n resolve: {\n ...existingResolve,\n alias: mergedAlias,\n },\n }\n : {}),\n }\n}\n\n/** Spread optimizeDeps while omitting deprecated optimizer option keys. */\nfunction omitDeprecatedOptimizeDepsKeys(\n existing: OptimizeDepsConfig | undefined,\n): Omit<OptimizeDepsConfig, 'esbuildOptions' | 'rollupOptions'> {\n const { esbuildOptions: _e, rollupOptions: _r, ...rest } = existing ?? {}\n return rest\n}\n\n/**\n * Minimal Vite plugin to make the SDK work in browser/Electron renderer:\n * - Aliases fs → @zenfs/core (and promises variant)\n * - Aliases path → path-browserify\n * - Ensures CommonJS in SDK dist is transformed by Vite's CommonJS plugin\n * - Allowlists linked SDK / sqlocal worker paths on server.fs.allow for Vite dev\n * - Optionally injects a simple ZenFS initialization script\n * - Optionally wires up vite-plugin-node-polyfills with safe defaults\n *\n * This plugin assumes the SDK does not bundle Node-only code in the browser entry.\n * For Electron, Node-only work (e.g. better-sqlite3) should run in the\n * main process; the renderer should only use browser-safe SDK usage.\n *\n * For the renderer build:\n * - Use the SDK's ESM entry: import from '@seedprotocol/sdk' (resolves to dist/main.js).\n * - When autoInit is false (default), initialize ZenFS in your entry:\n * import { configure } from '@zenfs/core'; import { IndexedDB } from '@zenfs/dom';\n * await configure({ mounts: { '/': IndexedDB } });\n */\nexport function seedVitePlugin(options: SeedVitePluginOptions = {}): Plugin[] {\n const {\n fsModules = DEFAULT_FS_MODULES,\n autoInit = false,\n debug = false,\n includeNodePolyfills = true,\n } = options\n\n const log = (...args: unknown[]) => {\n if (debug) console.log('[seed-vite-plugin]', ...args)\n }\n\n const { paths: polyfillShimPaths, unresolved: unresolvedPolyfillShims } =\n resolveNodePolyfillShimPaths()\n const polyfillShimAliasObj = nodePolyfillShimAliasObject(polyfillShimPaths)\n\n if (includeNodePolyfills && unresolvedPolyfillShims.length > 0) {\n console.warn(\n '[seed-vite-plugin] Could not resolve vite-plugin-node-polyfills shims from the SDK package:\\n' +\n unresolvedPolyfillShims.map((id) => ` - ${id}`).join('\\n') +\n '\\nNode polyfill globals may fail to resolve. Reinstall @seedprotocol/sdk, or set includeNodePolyfills: false and configure polyfills yourself.',\n )\n } else if (unresolvedPolyfillShims.length === 0) {\n log('Resolved vite-plugin-node-polyfills shims to absolute paths')\n }\n\n /**\n * Pre-plugin: configure aliases and optimizeDeps.\n */\n const configPlugin: Plugin = {\n name: 'seed-protocol:config',\n enforce: 'pre',\n\n configResolved(resolvedConfig) {\n const addedAllowPaths = ensureDevServerFsAllow(resolvedConfig.server.fs.allow)\n if (addedAllowPaths.length > 0) {\n log(\n 'Extended server.fs.allow for linked SDK / sqlocal worker paths:',\n addedAllowPaths,\n )\n }\n },\n\n config(userConfig) {\n const aliasEntries: AliasEntry[] = []\n for (const mod of fsModules) {\n const isPromises = mod.includes('promises')\n const target = isPromises ? '@zenfs/core/promises' : '@zenfs/core'\n aliasEntries.push({ find: mod, replacement: target })\n }\n\n const eventEmitterEsm = resolvePackageFile('eventemitter3', 'dist/eventemitter3.esm.js')\n if (eventEmitterEsm) {\n aliasEntries.push(\n { find: 'eventemitter3', replacement: eventEmitterEsm },\n { find: 'eventemitter3/index.mjs', replacement: eventEmitterEsm },\n { find: 'eventemitter3/index.js', replacement: eventEmitterEsm },\n )\n }\n\n const arweaveBundle = resolvePackageFile('arweave', 'bundles/web.bundle.js')\n if (arweaveBundle) {\n aliasEntries.push(\n { find: /^arweave$/, replacement: ARWEAVE_SHIM_FILE },\n { find: /^arweave\\/web\\/index\\.js$/, replacement: ARWEAVE_SHIM_FILE },\n { find: /^arweave\\/bundles\\/web\\.bundle\\.js$/, replacement: arweaveBundle },\n )\n }\n\n addRendererCompatibilityAliases(aliasEntries)\n addNodePolyfillShimAliases(aliasEntries, polyfillShimPaths)\n\n const existingResolve = userConfig.resolve ?? {}\n const mergedAlias = mergeAliasEntries(\n normalizeAliasEntries(existingResolve.alias),\n aliasEntries,\n )\n\n const desiredOptimizeIncludes = [\n '@zenfs/core',\n '@zenfs/dom',\n 'kerium',\n 'utilium',\n 'memium',\n 'readable-stream',\n 'viem',\n 'isows',\n ...FRAGILE_RENDERER_OPTIMIZE_INCLUDES,\n ]\n const resolvableOptimizeIncludes = desiredOptimizeIncludes.filter(\n (dep) => !!resolvePackageFile(dep, 'package.json'),\n )\n\n const existingOptimize = userConfig.optimizeDeps\n const debugOptimizeAliases = debugShimOptimizeAliasObject()\n\n const optimizeDeps: UserConfig['optimizeDeps'] = {\n ...omitDeprecatedOptimizeDepsKeys(existingOptimize),\n exclude: [\n ...(existingOptimize?.exclude ?? []),\n // Do not prebundle the SDK itself or clearly node-only tools\n '@seedprotocol/sdk',\n 'drizzle-orm',\n 'better-sqlite3',\n // sqlocal uses workers and should not be prebundled\n 'sqlocal',\n ],\n include: [\n ...(existingOptimize?.include ?? []),\n ...resolvableOptimizeIncludes,\n ...EAS_OPTIMIZE_INCLUDES,\n ],\n // Keep `global` shim in optimizer Rolldown options; top-level Vite `define`\n // can be rejected by Rolldown in some consumer setups.\n rolldownOptions: mergeOptimizeDepsRolldownOptions(existingOptimize, {\n define: { global: 'globalThis' },\n alias: {\n ...debugOptimizeAliases,\n ...polyfillShimAliasObj,\n },\n }),\n }\n\n return {\n // Apply global → globalThis for Rollup production builds too.\n // optimizeDeps.rolldownOptions.transform.define only covers the dev pre-bundle step;\n // this top-level define is picked up by @rollup/plugin-replace during build\n // and covers all chunks, including code-split migrator/commonjs-helper chunks.\n define: {\n ...(userConfig.define ?? {}),\n global: 'globalThis',\n // process is referenced by path-browserify (drizzle migrator's node:path dep)\n // and other CJS modules. Point at globalThis.process which is set by the\n // synchronous inline shim script injected into index.html before any modules load.\n 'process.env.NODE_ENV': JSON.stringify('production'),\n 'process.browser': 'true',\n 'process.platform': '\"browser\"',\n },\n resolve: {\n ...existingResolve,\n alias: mergedAlias,\n // Prevent duplicate React/thirdweb instances when @seedprotocol/publish is workspace-linked.\n // Multiple copies break context (e.g. useActiveAccount must be used within ThirdwebProvider).\n // Also dedupe XState and Seed packages: two xstate copies cause Object.assign _version errors;\n // two @seedprotocol/sdk copies leave BaseDb facade / Db.appDb on different module instances\n // (\"App DB not found\", undefined.$with on PostsPage).\n // Two @zenfs copies leave configureSingle / WebAccess on different module instances\n // and can remount OPFS against a stale handle.\n dedupe: Array.from(\n new Set([\n ...(existingResolve.dedupe ?? []),\n 'react',\n 'react-dom',\n 'thirdweb',\n 'xstate',\n '@xstate/react',\n '@seedprotocol/sdk',\n '@seedprotocol/react',\n '@seedprotocol/publish',\n '@seedprotocol/feed',\n '@zenfs/core',\n '@zenfs/dom',\n ])\n ),\n },\n optimizeDeps,\n }\n },\n }\n\n /**\n * Runs after vite-plugin-node-polyfills so absolute shim aliases win over its bare\n * package-id aliases in both resolve.alias and the Rolldown optimizeDeps graph.\n */\n const polyfillResolvePlugin: Plugin = {\n name: 'seed-protocol:polyfill-resolve',\n enforce: 'post',\n\n config(userConfig) {\n if (Object.keys(polyfillShimAliasObj).length === 0) return\n\n const existingResolve = userConfig.resolve ?? {}\n const mergedAlias = withPreferredPolyfillAliases(\n normalizeAliasEntries(existingResolve.alias),\n polyfillShimPaths,\n )\n\n const existingOptimize = userConfig.optimizeDeps\n\n return {\n resolve: {\n ...existingResolve,\n alias: mergedAlias,\n },\n optimizeDeps: {\n rolldownOptions: mergeOptimizeDepsRolldownOptions(existingOptimize, {\n // Later merge overwrites bare shim ids from vite-plugin-node-polyfills.\n alias: polyfillShimAliasObj,\n }),\n },\n }\n },\n\n resolveId: {\n order: 'pre',\n handler(id) {\n // Always rewrite injected shim package ids (safe even if nested under the SDK).\n if (id === 'vite-plugin-node-polyfills/shims/buffer') {\n return polyfillShimPaths.buffer ?? null\n }\n if (id === 'vite-plugin-node-polyfills/shims/global') {\n return polyfillShimPaths.global ?? null\n }\n if (id === 'vite-plugin-node-polyfills/shims/process') {\n return polyfillShimPaths.process ?? null\n }\n // Only remap node globals when we own the polyfills plugin config.\n if (!includeNodePolyfills) return null\n if (id === 'buffer' || id === 'node:buffer') return polyfillShimPaths.buffer ?? null\n if (id === 'global') return polyfillShimPaths.global ?? null\n if (id === 'process' || id === 'node:process') return polyfillShimPaths.process ?? null\n return null\n },\n },\n\n transform: {\n // After polyfills banner/inject so we collapse duplicates left in optimized deps.\n // Must emit absolute shim paths: order \"post\" runs after import-analysis.\n order: 'post',\n handler(code) {\n const count = (code.match(/import\\s+__buffer_polyfill\\b/g) || []).length\n let next = code\n let mutated = false\n\n if (count > 1) {\n const deduped = dedupeNodePolyfillBanner(next, polyfillShimPaths)\n if (deduped) {\n next = deduped\n mutated = true\n }\n }\n\n const rewritten = rewriteBarePolyfillShimImports(next, polyfillShimPaths)\n if (rewritten) {\n next = rewritten\n mutated = true\n }\n\n if (mutated) return { code: next, map: null }\n return null\n },\n },\n }\n\n /**\n * Post-plugin: build configuration + optional ZenFS init.\n */\n const mainPlugin: Plugin = {\n name: 'seed-protocol:main',\n enforce: 'post',\n\n config(userConfig) {\n const existingBuild = userConfig.build ?? {}\n const existingCommonjs = existingBuild.commonjsOptions ?? {}\n const existingRollupOptions = existingBuild.rollupOptions ?? {}\n const existingRolldownOptions = (existingBuild as Record<string, unknown>).rolldownOptions as\n | Record<string, unknown>\n | undefined\n const existingExternal = existingRollupOptions.external ?? []\n\n const include = [\n // Anything the user already had\n ...(Array.isArray(existingCommonjs.include)\n ? existingCommonjs.include\n : existingCommonjs.include\n ? [existingCommonjs.include]\n : []),\n // Always process node_modules and the SDK dist so require() is transformed\n /node_modules/,\n /seed-protocol-sdk[\\\\/]+dist[\\\\/]/,\n ]\n\n // Exclude packages that are already ESM or have special worker handling\n const exclude = [\n ...(Array.isArray(existingCommonjs.exclude)\n ? existingCommonjs.exclude\n : existingCommonjs.exclude\n ? [existingCommonjs.exclude]\n : []),\n // sqlocal is ESM and uses workers - don't transform it\n /node_modules[\\\\/]+sqlocal[\\\\/]/,\n ]\n\n const commonjsOptions = {\n ...existingCommonjs,\n include,\n exclude,\n transformMixedEsModules: true,\n }\n\n // Externalize Node.js-only packages that should never be bundled for the browser\n const nodeOnlyPackages = [\n 'better-sqlite3', // Native SQLite binding (Node.js only)\n ]\n\n const isNodeOnlyExternal = (id: string) =>\n nodeOnlyPackages.some(\n (pkg) =>\n id === pkg ||\n id.startsWith(`${pkg}/`) ||\n id.includes(`/${pkg}/`) ||\n id.endsWith(`/${pkg}`)\n )\n\n const externalList = (id: string, importer?: string, isResolved?: boolean) => {\n if (isNodeOnlyExternal(id)) return true\n if (typeof existingExternal === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (existingExternal as any)(id, importer, isResolved ?? false)\n }\n if (Array.isArray(existingExternal)) {\n return existingExternal.some((ext) => ext === id || id.startsWith(`${ext}/`))\n }\n return false\n }\n\n const rollupOptions = {\n ...existingRollupOptions,\n external: externalList,\n }\n\n const build: Record<string, unknown> = {\n ...existingBuild,\n commonjsOptions,\n }\n if (existingRolldownOptions) {\n build.rolldownOptions = {\n ...existingRolldownOptions,\n external: externalList,\n }\n } else {\n build.rollupOptions = rollupOptions\n }\n\n // Worker options are TOP-LEVEL in Vite config, not under build.\n // Default 'iife' breaks when workers use code-splitting (e.g. sqlocal).\n const existingWorker = userConfig.worker ?? {}\n const worker = {\n ...existingWorker,\n format: existingWorker.format ?? 'es',\n }\n\n return {\n build,\n worker,\n }\n },\n\n generateBundle(_options, bundle) {\n const allHits: Array<{ chunk: string } & GlobalHit> = []\n\n for (const [chunkName, asset] of Object.entries(bundle)) {\n if (asset.type !== 'chunk') continue\n const hits = findDangerousGlobals(asset.code)\n for (const hit of hits) {\n allHits.push({ chunk: chunkName, ...hit })\n }\n }\n\n if (allHits.length === 0) return\n\n console.warn(\n '\\n[seed-vite-plugin] ⚠️ Bare Node.js globals detected in browser bundle chunks.' +\n ' These will throw ReferenceError at runtime unless shimmed.\\n'\n )\n const byChunk = new Map<string, typeof allHits>()\n for (const hit of allHits) {\n const list = byChunk.get(hit.chunk) ?? []\n list.push(hit)\n byChunk.set(hit.chunk, list)\n }\n for (const [chunk, hits] of byChunk) {\n console.warn(` ${chunk}`)\n for (const h of hits) {\n console.warn(` line ${h.line}: \\`${h.global}\\` — ${h.context}`)\n }\n }\n console.warn('')\n },\n\n transformIndexHtml(html) {\n // Synchronous inline script runs before any <script type=\"module\">, so\n // global and process are guaranteed to exist when CJS wrappers evaluate.\n // vite-plugin-node-polyfills injects polyfills via module imports, which\n // resolve too late for @rollup/plugin-commonjs-generated wrapper code.\n const shimScript = `<script>\n(function(){\n if(typeof globalThis.global==='undefined')globalThis.global=globalThis;\n if(typeof globalThis.process==='undefined')globalThis.process={env:{NODE_ENV:'production'},browser:true,version:'v18.0.0',versions:{},platform:'browser',cwd:function(){return'/'},nextTick:function(fn){setTimeout(fn,0)}};\n})();\n</script>`\n\n let result = html\n if (result.includes('<head>')) {\n result = result.replace('<head>', `<head>\\n${shimScript}`)\n } else {\n result = shimScript + result\n }\n\n if (!autoInit) return result\n\n const initScript = `\n<script type=\"module\">\nimport { configure } from '@zenfs/core';\nimport { IndexedDB } from '@zenfs/dom';\n\nif (!window.__seedFsReady) {\n window.__seedFsReady = configure({\n mounts: { '/': IndexedDB },\n }).catch((err) => {\n console.error('[seed-vite-plugin] ZenFS initialization failed', err);\n });\n}\n</script>`\n\n if (result.includes('</head>')) {\n return result.replace('</head>', `${initScript}\\n</head>`)\n }\n\n return result + initScript\n },\n }\n\n const sdkImportFixPlugin: Plugin = {\n name: 'seed-protocol:sdk-import-fix',\n enforce: 'post',\n transform(code, id) {\n if (!id.includes('@seedprotocol/sdk') || !id.includes('FileManager')) {\n return null\n }\n const hasDefaultPathBrowserifyImport =\n /import\\s+path\\s+from\\s+['\"]path-browserify['\"]/.test(code)\n if (!hasDefaultPathBrowserifyImport) {\n return null\n }\n const transformed = code.replace(\n /import\\s+path\\s+from\\s+['\"]path-browserify['\"];/g,\n \"import * as path from 'path';\",\n )\n if (transformed === code) {\n return null\n }\n return { code: transformed, map: null }\n },\n }\n\n const plugins: Plugin[] = [configPlugin, mainPlugin, sdkImportFixPlugin]\n\n if (includeNodePolyfills) {\n log('Including vite-plugin-node-polyfills with default settings')\n // vite-plugin-node-polyfills ≥0.27 returns Plugin[]; older versions returned a single Plugin.\n const polyfillPlugins = nodePolyfills({\n // Let fs be handled by @zenfs/core instead of polyfills\n exclude: ['readline',],\n // Common set of browser-friendly polyfills used by many deps\n include: ['path', 'crypto', 'stream', 'util', 'buffer', 'events', 'string_decoder',],\n globals: {\n Buffer: true,\n global: true,\n process: true,\n },\n protocolImports: true,\n }) as unknown as Plugin | Plugin[]\n if (Array.isArray(polyfillPlugins)) {\n plugins.push(...polyfillPlugins)\n } else {\n plugins.push(polyfillPlugins)\n }\n }\n\n // After nodePolyfills so config() can overwrite its bare shim aliases.\n if (Object.keys(polyfillShimAliasObj).length > 0) {\n plugins.push(polyfillResolvePlugin)\n }\n\n return plugins\n}\n"],"mappings":";;;;;;AAOA,IAAM,IAAO,EAAc,YAAY,GAAG,GAqCpC,IAAoD;CACxD,QAAY;CACZ,SAAY;CACZ,QAAY;CACZ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;EAGmD;CAAkB;CAEvE,IAAI,GAAsB;EACxB,EAAI,4DAA4D;EAEhE,IAAM,IAAkB,EAAc;GAEpC,SAAS,CAAC,UAAW;GAErB,SAAS;IAAC;IAAQ;IAAU;IAAU;IAAQ;IAAU;IAAU;GAAiB;GACnF,SAAS;IACP,QAAQ;IACR,QAAQ;IACR,SAAS;GACX;GACA,iBAAiB;EACnB,CAAC;EACD,AAAI,MAAM,QAAQ,CAAe,IAC/B,EAAQ,KAAK,GAAG,CAAe,IAE/B,EAAQ,KAAK,CAAe;CAEhC;CAOA,OAJI,OAAO,KAAK,CAAoB,CAAC,CAAC,SAAS,KAC7C,EAAQ,KAAK,CAAqB,GAG7B;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import type { ConfigEnv, Plugin, PreviewServer, UserConfig, ViteDevServer } from 'vite'\nimport fs from 'node:fs'\nimport { createRequire } from 'node:module'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { nodePolyfills } from 'vite-plugin-node-polyfills'\n\nconst _req = createRequire(import.meta.url)\n\nexport interface SeedVitePluginOptions {\n /**\n * Additional modules to alias to ZenFS equivalents.\n * @default ['fs', 'fs/promises', 'node:fs', 'node:fs/promises']\n */\n fsModules?: string[]\n\n /**\n * Whether to inject automatic ZenFS initialization script into index.html.\n * When true, injects a <script type=\"module\"> that imports from '@zenfs/core'/'@zenfs/dom'.\n * Browsers cannot resolve those bare specifiers, so the script fails at runtime unless you use\n * an import map or load ZenFS another way. Prefer false and initialize ZenFS in your entry:\n * import { configure } from '@zenfs/core'; import { IndexedDB } from '@zenfs/dom';\n * await configure({ mounts: { '/': IndexedDB } });\n * @default false\n */\n autoInit?: boolean\n\n /**\n * Enable debug logging.\n * @default false\n */\n debug?: boolean\n\n /**\n * Whether to automatically include vite-plugin-node-polyfills with sensible defaults.\n * The SDK depends on that package and aliases its injected shim imports to absolute\n * paths, so consuming apps do not need to install vite-plugin-node-polyfills themselves.\n * Default include list omits full `stream`/`crypto` polyfills (those pull\n * stream-browserify and break Vite SSR / React Router prerender). A minimal\n * `stream` stub is still aliased so sax/rss-parser do not warn. Use `false`\n * for Framework Mode / prerender.\n * @default true\n */\n includeNodePolyfills?: boolean\n\n /**\n * Cross-origin isolation headers for sqlocal / SharedArrayBuffer / OPFS.\n * Applied in configureServer and configurePreviewServer, including writeHead,\n * because Vite `server.headers` is not copied onto Framework-Mode HTML responses.\n * Set `false` to disable. Pass `{ coop, coep, corp }` to override values.\n * @default true (`COOP: same-origin`, `COEP: credentialless`, `CORP: same-origin`)\n */\n isolationHeaders?: boolean | {\n coop?: string\n coep?: string\n corp?: string\n }\n}\n\n// Node.js globals that are undefined in browsers and will throw at runtime.\n// Keyed by identifier; value is the safe typeof-guard pattern so we can skip those.\nconst BROWSER_DANGEROUS_GLOBALS: Record<string, RegExp> = {\n global: /\\btypeof\\s+global\\b/,\n process: /\\btypeof\\s+process\\b/,\n Buffer: /\\btypeof\\s+Buffer\\b/,\n __dirname: /\\btypeof\\s+__dirname\\b/,\n __filename: /\\btypeof\\s+__filename\\b/,\n}\n\n/**\n * Strip JS string literals, template literals, and comments from source text\n * so that identifier searches don't false-positive on string content.\n * This is intentionally approximate — good enough for a lint-style warning pass.\n */\nfunction stripStringsAndComments(code: string): string {\n return code\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, (m) => ' '.repeat(m.length)) // /* block comments */\n .replace(/\\/\\/[^\\n]*/g, (m) => ' '.repeat(m.length)) // // line comments\n .replace(/`(?:[^`\\\\]|\\\\.)*`/gs, (m) => '`' + ' '.repeat(m.length - 2) + '`') // template literals\n .replace(/\"(?:[^\"\\\\]|\\\\.)*\"/g, (m) => '\"' + ' '.repeat(m.length - 2) + '\"') // double-quoted strings\n .replace(/'(?:[^'\\\\]|\\\\.)*'/g, (m) => \"'\" + ' '.repeat(m.length - 2) + \"'\") // single-quoted strings\n}\n\ninterface GlobalHit {\n global: string\n /** zero-based character offset in the stripped source */\n offset: number\n /** 1-based line number */\n line: number\n /** surrounding raw source for context */\n context: string\n}\n\nfunction findDangerousGlobals(rawCode: string): GlobalHit[] {\n const stripped = stripStringsAndComments(rawCode)\n const hits: GlobalHit[] = []\n\n for (const [name, typeofGuard] of Object.entries(BROWSER_DANGEROUS_GLOBALS)) {\n // Skip globalThis when checking 'global'\n const re = new RegExp(`(?<![.\\\\w$])\\\\b${name}\\\\b(?!This)(?![\\\\w$])`, 'g')\n let m: RegExpExecArray | null\n while ((m = re.exec(stripped)) !== null) {\n const offset = m.index\n // Check for typeof guard in the ~20 chars before the match\n const before = stripped.slice(Math.max(0, offset - 20), offset)\n if (typeofGuard.test(before)) continue\n\n // Compute 1-based line number from raw source (positions are preserved because\n // we replace with equal-length spaces, so offsets are stable)\n const linesBefore = rawCode.slice(0, offset).split('\\n')\n const line = linesBefore.length\n const colOffset = linesBefore.at(-1)?.length ?? 0\n const rawLine = rawCode.split('\\n')[line - 1] ?? ''\n const ctx = rawLine.slice(Math.max(0, colOffset - 40), colOffset + name.length + 40).trim()\n\n hits.push({ global: name, offset, line, context: ctx })\n }\n }\n\n return hits\n}\n\nconst DEFAULT_FS_MODULES = [\n 'fs',\n 'fs/promises',\n 'node:fs',\n 'node:fs/promises',\n]\nconst SDK_DIST_DIR = path.dirname(fileURLToPath(import.meta.url))\nconst ARWEAVE_SHIM_FILE = path.join(SDK_DIST_DIR, 'arweave-default-shim.js')\nconst DEBUG_SHIM_FILE = path.join(SDK_DIST_DIR, 'debug-default-shim.js')\nconst STREAM_SHIM_FILE = path.join(SDK_DIST_DIR, 'stream-default-shim.js')\n\n/** Fragile renderer deps pre-bundled for stable CJS/ESM interop (aligned with permapress). */\nconst FRAGILE_RENDERER_OPTIMIZE_INCLUDES = [\n 'debug',\n 'random',\n 'seedrandom',\n '@georgedoescode/generative-utils',\n 'nanoid-dictionary',\n] as const\n\n/**\n * Always force-include (do not gate on resolvePackageFile): under bun these live nested\n * under @seedprotocol/sdk, and eas-sdk's ESM named-imports CJS eas-contracts. Without\n * prebundling, Vite serves raw /@fs CJS and the browser throws\n * \"does not provide an export named 'EAS__factory'\" during SchemaEncoder encode.\n */\nconst EAS_OPTIMIZE_INCLUDES = [\n '@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk',\n '@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk > @ethereum-attestation-service/eas-contracts',\n] as const\n\n/** CJS packages Seed ESM default-imports. Always include (do not gate on resolve). */\nconst CJS_OPTIMIZE_INCLUDES = ['pluralize'] as const\n\nconst DEFAULT_ISOLATION_HEADERS = {\n 'Cross-Origin-Opener-Policy': 'same-origin',\n 'Cross-Origin-Embedder-Policy': 'credentialless',\n 'Cross-Origin-Resource-Policy': 'same-origin',\n} as const\n\nfunction resolveIsolationHeaders(\n option: SeedVitePluginOptions['isolationHeaders'],\n): Record<string, string> | null {\n if (option === false) return null\n const overrides = typeof option === 'object' && option ? option : {}\n return {\n 'Cross-Origin-Opener-Policy': overrides.coop ?? DEFAULT_ISOLATION_HEADERS['Cross-Origin-Opener-Policy'],\n 'Cross-Origin-Embedder-Policy': overrides.coep ?? DEFAULT_ISOLATION_HEADERS['Cross-Origin-Embedder-Policy'],\n 'Cross-Origin-Resource-Policy': overrides.corp ?? DEFAULT_ISOLATION_HEADERS['Cross-Origin-Resource-Policy'],\n }\n}\n\nfunction applyIsolationHeaderMiddleware(\n server: ViteDevServer | PreviewServer,\n headers: Record<string, string>,\n): void {\n server.middlewares.use((_req, res, next) => {\n const apply = () => {\n for (const [key, value] of Object.entries(headers)) {\n if (!res.getHeader(key)) {\n res.setHeader(key, value)\n }\n }\n }\n const originalWriteHead = res.writeHead.bind(res)\n res.writeHead = ((...args: Parameters<typeof res.writeHead>) => {\n apply()\n return originalWriteHead(...args)\n }) as typeof res.writeHead\n apply()\n next()\n })\n}\n\ntype AliasEntry = { find: string | RegExp; replacement: string }\n\nfunction pushBunPackageCandidates(\n bunDir: string,\n packageName: string,\n relativePath: string,\n candidates: string[],\n): void {\n if (!fs.existsSync(bunDir)) return\n // Nested scopes (@scope/name) live under .bun as @scope+name@version/...\n const bunPrefix = packageName.startsWith('@')\n ? packageName.replace('/', '+')\n : packageName\n for (const entry of fs.readdirSync(bunDir)) {\n if (!entry.startsWith(`${bunPrefix}@`) && !entry.startsWith(`${packageName}@`)) continue\n candidates.push(path.join(bunDir, entry, `node_modules/${packageName}`, relativePath))\n }\n}\n\nfunction resolvePackageFile(packageName: string, relativePath: string): string | undefined {\n const candidates: string[] = []\n const sdkRoot = path.resolve(SDK_DIST_DIR, '..')\n\n try {\n const pkgJson = _req.resolve(`${packageName}/package.json`)\n candidates.push(path.join(path.dirname(pkgJson), relativePath))\n } catch {\n // Many packages (e.g. sqlocal) omit package.json from \"exports\". Resolve an\n // entry file and walk up to the package root instead.\n try {\n const entry = _req.resolve(packageName)\n let dir = path.dirname(entry)\n for (let i = 0; i < 8; i++) {\n const pkgJsonPath = path.join(dir, 'package.json')\n if (fs.existsSync(pkgJsonPath)) {\n try {\n const pkgName = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8')).name\n if (pkgName === packageName) {\n candidates.push(path.join(dir, relativePath))\n break\n }\n } catch {\n // ignore invalid package.json\n }\n }\n const parent = path.dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n } catch {\n // package may be hoisted/unavailable in this graph\n }\n }\n\n // Linked/file installs: deps often live under the SDK package, not the app cwd.\n candidates.push(path.join(sdkRoot, 'node_modules', packageName, relativePath))\n\n const cwdNodeModules = path.join(process.cwd(), 'node_modules')\n candidates.push(path.join(cwdNodeModules, packageName, relativePath))\n\n pushBunPackageCandidates(\n path.join(cwdNodeModules, '.bun'),\n packageName,\n relativePath,\n candidates,\n )\n pushBunPackageCandidates(\n path.join(sdkRoot, 'node_modules', '.bun'),\n packageName,\n relativePath,\n candidates,\n )\n const bunInstallRoot = findNodeModulesBunRoot(sdkRoot)\n if (bunInstallRoot) {\n pushBunPackageCandidates(\n path.join(bunInstallRoot, 'node_modules', '.bun'),\n packageName,\n relativePath,\n candidates,\n )\n }\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate\n }\n return undefined\n}\n\n/** Walk up from startDir looking for a directory that contains node_modules/.bun. */\nfunction findNodeModulesBunRoot(startDir: string): string | undefined {\n let dir = path.resolve(startDir)\n for (let i = 0; i < 8; i++) {\n if (fs.existsSync(path.join(dir, 'node_modules', '.bun'))) return dir\n const parent = path.dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n return undefined\n}\n\nfunction isFsAllowCovering(allow: readonly string[], filePath: string): boolean {\n const child = path.resolve(filePath)\n return allow.some((uri) => {\n const parent = path.resolve(String(uri))\n return (\n child === parent ||\n child.startsWith(parent.endsWith(path.sep) ? parent : parent + path.sep)\n )\n })\n}\n\nfunction realpathOrResolve(p: string): string {\n try {\n return fs.realpathSync(p)\n } catch {\n return path.resolve(p)\n }\n}\n\n/**\n * When the SDK is linked (file:/symlink) into an external app, sqlocal's worker\n * and sqlite-wasm assets resolve into the SDK install tree (often bun's .bun\n * store). Vite's default server.fs.allow only covers the consumer workspace, so\n * those absolute /@fs requests 403 unless we allowlist the install roots.\n */\nfunction collectDevServerFsAllowPaths(): string[] {\n const paths = new Set<string>()\n const add = (p?: string) => {\n if (!p) return\n paths.add(realpathOrResolve(p))\n }\n\n let sdkPkgDir: string\n try {\n sdkPkgDir = path.dirname(_req.resolve('@seedprotocol/sdk/package.json'))\n } catch {\n sdkPkgDir = path.resolve(SDK_DIST_DIR, '..')\n }\n add(sdkPkgDir)\n\n const bunInstallRoot = findNodeModulesBunRoot(sdkPkgDir)\n if (bunInstallRoot) add(bunInstallRoot)\n\n for (const pkg of ['sqlocal', '@sqlite.org/sqlite-wasm'] as const) {\n const pkgJson = resolvePackageFile(pkg, 'package.json')\n if (pkgJson) add(path.dirname(pkgJson))\n }\n\n return [...paths]\n}\n\nfunction ensureDevServerFsAllow(allow: string[]): string[] {\n const added: string[] = []\n for (const dir of collectDevServerFsAllowPaths()) {\n if (isFsAllowCovering(allow, dir)) continue\n allow.push(dir)\n added.push(dir)\n }\n return added\n}\n\nfunction normalizeAliasEntries(\n alias: NonNullable<UserConfig['resolve']>['alias'] | undefined\n): AliasEntry[] {\n if (!alias) return []\n if (Array.isArray(alias)) {\n return alias\n .filter((entry): entry is AliasEntry => !!entry && !!(entry as AliasEntry).replacement)\n .map((entry) => ({ find: entry.find, replacement: entry.replacement }))\n }\n\n return Object.entries(alias).map(([find, replacement]) => ({\n find,\n replacement: String(replacement),\n }))\n}\n\nfunction mergeAliasEntries(existing: AliasEntry[], additions: AliasEntry[]): AliasEntry[] {\n const merged = [...existing]\n const keyOf = (find: string | RegExp) =>\n typeof find === 'string' ? `s:${find}` : `r:${find.toString()}`\n const seen = new Set(merged.map((entry) => keyOf(entry.find)))\n\n for (const entry of additions) {\n const key = keyOf(entry.find)\n if (seen.has(key)) continue\n seen.add(key)\n merged.push(entry)\n }\n\n return merged\n}\n\n/** Bare IDs that vite-plugin-node-polyfills injects into every transformed module. */\nconst NODE_POLYFILL_SHIM_IDS = [\n 'vite-plugin-node-polyfills/shims/buffer',\n 'vite-plugin-node-polyfills/shims/global',\n 'vite-plugin-node-polyfills/shims/process',\n] as const\n\ntype NodePolyfillShimPaths = {\n buffer?: string\n global?: string\n process?: string\n}\n\n/**\n * Prefer the package \"import\" ESM build (index.js). createRequire resolves the\n * \"require\" condition (index.cjs); Vite then serves `/@fs/...cjs?import` and\n * default-import fails in the browser.\n */\nfunction resolvePolyfillShimFile(shimId: string): string {\n const resolved = _req.resolve(shimId)\n if (resolved.endsWith('.cjs')) {\n const esm = resolved.slice(0, -4) + '.js'\n if (fs.existsSync(esm)) return esm\n }\n return resolved\n}\n\nfunction resolveNodePolyfillShimPaths(): {\n paths: NodePolyfillShimPaths\n unresolved: string[]\n} {\n const paths: NodePolyfillShimPaths = {}\n const unresolved: string[] = []\n for (const id of NODE_POLYFILL_SHIM_IDS) {\n try {\n const abs = resolvePolyfillShimFile(id)\n if (id.endsWith('/buffer')) paths.buffer = abs\n else if (id.endsWith('/global')) paths.global = abs\n else if (id.endsWith('/process')) paths.process = abs\n } catch {\n unresolved.push(id)\n }\n }\n return { paths, unresolved }\n}\n\n/**\n * Collapse repeated vite-plugin-node-polyfills globals banners (Vite 8 optimizer + serve).\n * Re-inject with absolute ESM paths: this runs in transform order \"post\" (after\n * import-analysis), so bare package ids would reach the browser unresolved\n * (\"Relative references must start with /, ./, or ../\").\n */\nfunction dedupeNodePolyfillBanner(\n code: string,\n paths: NodePolyfillShimPaths,\n): string | null {\n const importCount = (code.match(/import\\s+__buffer_polyfill\\b/g) || []).length\n if (importCount <= 1) return null\n if (!paths.buffer || !paths.global || !paths.process) return null\n\n const bannerRe =\n /import\\s+__buffer_polyfill\\s+from\\s+['\"][^'\"]+['\"];?\\s*\\n\\s*globalThis\\.Buffer\\s*=\\s*globalThis\\.Buffer\\s*\\|\\|\\s*__buffer_polyfill;?\\s*\\n\\s*import\\s+__global_polyfill\\s+from\\s+['\"][^'\"]+['\"];?\\s*\\n\\s*globalThis\\.global\\s*=\\s*globalThis\\.global\\s*\\|\\|\\s*__global_polyfill;?\\s*\\n\\s*import\\s+__process_polyfill\\s+from\\s+['\"][^'\"]+['\"];?\\s*\\n\\s*globalThis\\.process\\s*=\\s*globalThis\\.process\\s*\\|\\|\\s*__process_polyfill;?\\s*\\n?/g\n\n const cleaned = code.replace(bannerRe, '')\n if (cleaned === code) return null\n\n const banner =\n `import __buffer_polyfill from ${JSON.stringify(paths.buffer)};\\n` +\n 'globalThis.Buffer = globalThis.Buffer || __buffer_polyfill;\\n' +\n `import __global_polyfill from ${JSON.stringify(paths.global)};\\n` +\n 'globalThis.global = globalThis.global || __global_polyfill;\\n' +\n `import __process_polyfill from ${JSON.stringify(paths.process)};\\n` +\n 'globalThis.process = globalThis.process || __process_polyfill;\\n'\n\n return banner + cleaned\n}\n\n/** Rewrite leftover bare shim package ids to absolute ESM files (post import-analysis). */\nfunction rewriteBarePolyfillShimImports(\n code: string,\n paths: NodePolyfillShimPaths,\n): string | null {\n let next = code\n let changed = false\n const replacements: Array<[string, string]> = []\n if (paths.buffer) {\n replacements.push(['vite-plugin-node-polyfills/shims/buffer', paths.buffer])\n }\n if (paths.global) {\n replacements.push(['vite-plugin-node-polyfills/shims/global', paths.global])\n }\n if (paths.process) {\n replacements.push(['vite-plugin-node-polyfills/shims/process', paths.process])\n }\n for (const [bare, abs] of replacements) {\n const absLiteral = JSON.stringify(abs)\n for (const quote of ['\"', \"'\"] as const) {\n const from = `${quote}${bare}${quote}`\n if (!next.includes(from)) continue\n next = next.split(from).join(absLiteral)\n changed = true\n }\n }\n return changed ? next : null\n}\n\n/**\n * Alias polyfill shim bare imports + buffer/process/global module ids to absolute\n * paths resolved from this package. Nested installs under @seedprotocol/sdk are\n * invisible to consumer-project resolution (and to Vite 8's Rolldown optimizer)\n * unless we rewrite to absolute files.\n */\nfunction addNodePolyfillShimAliases(\n aliasEntries: AliasEntry[],\n paths: NodePolyfillShimPaths,\n): void {\n if (paths.buffer) {\n aliasEntries.push(\n { find: 'vite-plugin-node-polyfills/shims/buffer', replacement: paths.buffer },\n { find: /^buffer$/, replacement: paths.buffer },\n { find: /^node:buffer$/, replacement: paths.buffer },\n )\n }\n if (paths.global) {\n aliasEntries.push(\n { find: 'vite-plugin-node-polyfills/shims/global', replacement: paths.global },\n { find: /^global$/, replacement: paths.global },\n )\n }\n if (paths.process) {\n aliasEntries.push(\n { find: 'vite-plugin-node-polyfills/shims/process', replacement: paths.process },\n { find: /^process$/, replacement: paths.process },\n { find: /^node:process$/, replacement: paths.process },\n )\n }\n}\n\n/** Object-form aliases for optimizeDeps.rolldown/rollup resolve (string keys). */\nfunction nodePolyfillShimAliasObject(paths: NodePolyfillShimPaths): Record<string, string> {\n const alias: Record<string, string> = {}\n if (paths.buffer) {\n alias['vite-plugin-node-polyfills/shims/buffer'] = paths.buffer\n alias.buffer = paths.buffer\n alias['node:buffer'] = paths.buffer\n }\n if (paths.global) {\n alias['vite-plugin-node-polyfills/shims/global'] = paths.global\n alias.global = paths.global\n }\n if (paths.process) {\n alias['vite-plugin-node-polyfills/shims/process'] = paths.process\n alias.process = paths.process\n alias['node:process'] = paths.process\n }\n return alias\n}\n\nconst POLYFILL_ALIAS_FINDS_TO_REPLACE = new Set([\n 'vite-plugin-node-polyfills/shims/buffer',\n 'vite-plugin-node-polyfills/shims/global',\n 'vite-plugin-node-polyfills/shims/process',\n 'buffer',\n 'node:buffer',\n 'process',\n 'node:process',\n 'global',\n])\n\n/**\n * Put absolute polyfill aliases first and drop bare/package-id entries that\n * vite-plugin-node-polyfills may have added for the same modules (first match wins).\n */\nfunction withPreferredPolyfillAliases(\n existing: AliasEntry[],\n paths: NodePolyfillShimPaths,\n): AliasEntry[] {\n const preferred: AliasEntry[] = []\n addNodePolyfillShimAliases(preferred, paths)\n if (preferred.length === 0) return existing\n\n const filtered = existing.filter((entry) => {\n if (typeof entry.find !== 'string') return true\n return !POLYFILL_ALIAS_FINDS_TO_REPLACE.has(entry.find)\n })\n return [...preferred, ...filtered]\n}\n\nfunction addRendererCompatibilityAliases(aliasEntries: AliasEntry[]): void {\n const nanoidDictionaryEsm = resolvePackageFile(\n 'nanoid-dictionary',\n 'dist/dictionary.esm.js',\n )\n if (nanoidDictionaryEsm) {\n aliasEntries.push({\n find: /^nanoid-dictionary$/,\n replacement: nanoidDictionaryEsm,\n })\n }\n\n const zenfsCoreIndex = resolvePackageFile('@zenfs/core', 'dist/index.js')\n const zenfsCorePath = resolvePackageFile('@zenfs/core', 'dist/path.js')\n if (zenfsCoreIndex) {\n aliasEntries.push({ find: /^@zenfs\\/core$/, replacement: zenfsCoreIndex })\n }\n if (zenfsCorePath) {\n aliasEntries.push({ find: /^@zenfs\\/core\\/path$/, replacement: zenfsCorePath })\n }\n\n const zenfsDomIndex = resolvePackageFile('@zenfs/dom', 'dist/index.js')\n if (zenfsDomIndex) {\n aliasEntries.push({ find: /^@zenfs\\/dom$/, replacement: zenfsDomIndex })\n }\n\n if (fs.existsSync(DEBUG_SHIM_FILE)) {\n // Only alias the package root. Do not alias debug/src/browser.js to this shim:\n // the shim imports that path and aliasing it back creates a circular module.\n aliasEntries.push({ find: /^debug$/, replacement: DEBUG_SHIM_FILE })\n }\n\n const debugBrowserEntry = resolvePackageFile('debug', 'src/browser.js')\n if (debugBrowserEntry) {\n aliasEntries.push({\n find: /^debug\\/src\\/browser\\.js$/,\n replacement: debugBrowserEntry,\n })\n }\n\n // Minimal stream stub (not stream-browserify) so sax/rss-parser init is quiet.\n if (fs.existsSync(STREAM_SHIM_FILE)) {\n aliasEntries.push(\n { find: /^stream$/, replacement: STREAM_SHIM_FILE },\n { find: /^node:stream$/, replacement: STREAM_SHIM_FILE },\n )\n }\n}\n\n/** Object-form aliases for optimizeDeps pre-bundle (debug shim subpath). */\nfunction debugShimOptimizeAliasObject(): Record<string, string> {\n const debugBrowserEntry = resolvePackageFile('debug', 'src/browser.js')\n return debugBrowserEntry ? { 'debug/src/browser.js': debugBrowserEntry } : {}\n}\n\n/** Object-form aliases so optimizeDeps prebundles (rss-parser → sax) use our stream stub. */\nfunction streamShimOptimizeAliasObject(): Record<string, string> {\n if (!fs.existsSync(STREAM_SHIM_FILE)) return {}\n return {\n stream: STREAM_SHIM_FILE,\n 'node:stream': STREAM_SHIM_FILE,\n }\n}\n\ntype OptimizeDepsConfig = NonNullable<UserConfig['optimizeDeps']>\n\n/** Read Rolldown optimizer options, falling back to deprecated rollup/esbuild shapes. */\nfunction readOptimizeDepsRolldownBase(\n existing: OptimizeDepsConfig | undefined,\n): Record<string, unknown> {\n const opt = existing ?? {}\n return (\n opt.rolldownOptions ??\n (opt as { rollupOptions?: Record<string, unknown> }).rollupOptions ??\n {}\n ) as Record<string, unknown>\n}\n\n/**\n * Merge Vite 8 `optimizeDeps.rolldownOptions` without returning deprecated\n * `esbuildOptions` / `rollupOptions` keys from plugin config hooks.\n */\nfunction mergeOptimizeDepsRolldownOptions(\n existing: OptimizeDepsConfig | undefined,\n patch: {\n define?: Record<string, string>\n alias?: Record<string, string>\n },\n): OptimizeDepsConfig['rolldownOptions'] {\n const base = readOptimizeDepsRolldownBase(existing)\n const existingResolve = (base.resolve as { alias?: Record<string, string> } | undefined) ?? {}\n const existingTransform = (base.transform as { define?: Record<string, string> } | undefined) ?? {}\n const legacyDefine = existing?.esbuildOptions?.define ?? {}\n\n const mergedDefine = {\n ...legacyDefine,\n ...existingTransform.define,\n ...patch.define,\n }\n const mergedAlias = {\n ...existingResolve.alias,\n ...patch.alias,\n }\n\n return {\n ...base,\n ...(Object.keys(mergedDefine).length > 0\n ? {\n transform: {\n ...existingTransform,\n define: mergedDefine,\n },\n }\n : {}),\n ...(Object.keys(mergedAlias).length > 0\n ? {\n resolve: {\n ...existingResolve,\n alias: mergedAlias,\n },\n }\n : {}),\n }\n}\n\n/** Spread optimizeDeps while omitting deprecated optimizer option keys. */\nfunction omitDeprecatedOptimizeDepsKeys(\n existing: OptimizeDepsConfig | undefined,\n): Omit<OptimizeDepsConfig, 'esbuildOptions' | 'rollupOptions'> {\n const { esbuildOptions: _e, rollupOptions: _r, ...rest } = existing ?? {}\n return rest\n}\n\n/**\n * Minimal Vite plugin to make the SDK work in browser/Electron renderer:\n * - Aliases fs → @zenfs/core (and promises variant)\n * - Aliases path → path-browserify\n * - Ensures CommonJS in SDK dist is transformed by Vite's CommonJS plugin\n * - Allowlists linked SDK / sqlocal worker paths on server.fs.allow for Vite dev\n * - Optionally injects a simple ZenFS initialization script\n * - Optionally wires up vite-plugin-node-polyfills with safe defaults\n *\n * This plugin assumes the SDK does not bundle Node-only code in the browser entry.\n * For Electron, Node-only work (e.g. better-sqlite3) should run in the\n * main process; the renderer should only use browser-safe SDK usage.\n *\n * For the renderer build:\n * - Use the SDK's ESM entry: import from '@seedprotocol/sdk' (resolves to dist/main.js).\n * - When autoInit is false (default), initialize ZenFS in your entry:\n * import { configure } from '@zenfs/core'; import { IndexedDB } from '@zenfs/dom';\n * await configure({ mounts: { '/': IndexedDB } });\n */\nexport function seedVitePlugin(options: SeedVitePluginOptions = {}): Plugin[] {\n const {\n fsModules = DEFAULT_FS_MODULES,\n autoInit = false,\n debug = false,\n includeNodePolyfills = true,\n isolationHeaders: isolationHeadersOption,\n } = options\n\n const isolationHeaders = resolveIsolationHeaders(isolationHeadersOption)\n let htmlNodeEnv = 'production'\n\n const log = (...args: unknown[]) => {\n if (debug) console.log('[seed-vite-plugin]', ...args)\n }\n\n const { paths: polyfillShimPaths, unresolved: unresolvedPolyfillShims } =\n resolveNodePolyfillShimPaths()\n const polyfillShimAliasObj = nodePolyfillShimAliasObject(polyfillShimPaths)\n\n if (includeNodePolyfills && unresolvedPolyfillShims.length > 0) {\n console.warn(\n '[seed-vite-plugin] Could not resolve vite-plugin-node-polyfills shims from the SDK package:\\n' +\n unresolvedPolyfillShims.map((id) => ` - ${id}`).join('\\n') +\n '\\nNode polyfill globals may fail to resolve. Reinstall @seedprotocol/sdk, or set includeNodePolyfills: false and configure polyfills yourself.',\n )\n } else if (unresolvedPolyfillShims.length === 0) {\n log('Resolved vite-plugin-node-polyfills shims to absolute paths')\n }\n\n /**\n * Pre-plugin: configure aliases and optimizeDeps.\n */\n const configPlugin: Plugin = {\n name: 'seed-protocol:config',\n enforce: 'pre',\n\n configResolved(resolvedConfig) {\n const addedAllowPaths = ensureDevServerFsAllow(resolvedConfig.server.fs.allow)\n if (addedAllowPaths.length > 0) {\n log(\n 'Extended server.fs.allow for linked SDK / sqlocal worker paths:',\n addedAllowPaths,\n )\n }\n },\n\n config(userConfig, env) {\n if (env?.mode) {\n htmlNodeEnv = env.mode\n }\n const aliasEntries: AliasEntry[] = []\n for (const mod of fsModules) {\n const isPromises = mod.includes('promises')\n const target = isPromises ? '@zenfs/core/promises' : '@zenfs/core'\n aliasEntries.push({ find: mod, replacement: target })\n }\n\n const eventEmitterEsm = resolvePackageFile('eventemitter3', 'dist/eventemitter3.esm.js')\n if (eventEmitterEsm) {\n aliasEntries.push(\n { find: 'eventemitter3', replacement: eventEmitterEsm },\n { find: 'eventemitter3/index.mjs', replacement: eventEmitterEsm },\n { find: 'eventemitter3/index.js', replacement: eventEmitterEsm },\n )\n }\n\n const arweaveBundle = resolvePackageFile('arweave', 'bundles/web.bundle.js')\n if (arweaveBundle) {\n aliasEntries.push(\n { find: /^arweave$/, replacement: ARWEAVE_SHIM_FILE },\n { find: /^arweave\\/web\\/index\\.js$/, replacement: ARWEAVE_SHIM_FILE },\n { find: /^arweave\\/bundles\\/web\\.bundle\\.js$/, replacement: arweaveBundle },\n )\n }\n\n addRendererCompatibilityAliases(aliasEntries)\n addNodePolyfillShimAliases(aliasEntries, polyfillShimPaths)\n\n const existingResolve = userConfig.resolve ?? {}\n const mergedAlias = mergeAliasEntries(\n normalizeAliasEntries(existingResolve.alias),\n aliasEntries,\n )\n\n const desiredOptimizeIncludes = [\n '@zenfs/core',\n '@zenfs/dom',\n 'kerium',\n 'utilium',\n 'memium',\n 'readable-stream',\n 'viem',\n 'isows',\n ...FRAGILE_RENDERER_OPTIMIZE_INCLUDES,\n ]\n const resolvableOptimizeIncludes = desiredOptimizeIncludes.filter(\n (dep) => !!resolvePackageFile(dep, 'package.json'),\n )\n\n const existingOptimize = userConfig.optimizeDeps\n const debugOptimizeAliases = debugShimOptimizeAliasObject()\n const streamOptimizeAliases = streamShimOptimizeAliasObject()\n\n const optimizeDeps: UserConfig['optimizeDeps'] = {\n ...omitDeprecatedOptimizeDepsKeys(existingOptimize),\n exclude: [\n ...(existingOptimize?.exclude ?? []),\n // Do not prebundle the SDK itself or clearly node-only tools\n '@seedprotocol/sdk',\n 'drizzle-orm',\n 'better-sqlite3',\n // sqlocal uses workers and should not be prebundled\n 'sqlocal',\n ],\n include: [\n ...(existingOptimize?.include ?? []),\n ...resolvableOptimizeIncludes,\n ...EAS_OPTIMIZE_INCLUDES,\n ...CJS_OPTIMIZE_INCLUDES,\n ],\n // Keep `global` shim in optimizer Rolldown options; top-level Vite `define`\n // can be rejected by Rolldown in some consumer setups.\n rolldownOptions: mergeOptimizeDepsRolldownOptions(existingOptimize, {\n define: { global: 'globalThis' },\n alias: {\n ...debugOptimizeAliases,\n ...streamOptimizeAliases,\n ...polyfillShimAliasObj,\n },\n }),\n }\n\n return {\n // Apply global → globalThis for Rollup production builds too.\n // optimizeDeps.rolldownOptions.transform.define only covers the dev pre-bundle step;\n // this top-level define is picked up by @rollup/plugin-replace during build\n // and covers all chunks, including code-split migrator/commonjs-helper chunks.\n define: {\n ...(userConfig.define ?? {}),\n global: 'globalThis',\n // process is referenced by path-browserify and other CJS modules.\n // Point at globalThis.process which is set by the synchronous inline\n // shim script injected into index.html before any modules load.\n // Do not define process.env.NODE_ENV — Vite already sets it from mode,\n // and forcing \"production\" during `vite serve` compiles out React Refresh.\n 'process.browser': 'true',\n 'process.platform': '\"browser\"',\n },\n resolve: {\n ...existingResolve,\n alias: mergedAlias,\n // Prevent duplicate React/thirdweb instances when @seedprotocol/publish is workspace-linked.\n // Multiple copies break context (e.g. useActiveAccount must be used within ThirdwebProvider).\n // Also dedupe XState and Seed packages: two xstate copies cause Object.assign _version errors;\n // two @seedprotocol/sdk copies leave BaseDb facade / Db.appDb on different module instances\n // (\"App DB not found\", undefined.$with on PostsPage).\n // Two @zenfs copies leave configureSingle / WebAccess on different module instances\n // and can remount OPFS against a stale handle.\n dedupe: Array.from(\n new Set([\n ...(existingResolve.dedupe ?? []),\n 'react',\n 'react-dom',\n 'thirdweb',\n 'xstate',\n '@xstate/react',\n '@seedprotocol/sdk',\n '@seedprotocol/react',\n '@seedprotocol/publish',\n '@seedprotocol/feed',\n '@zenfs/core',\n '@zenfs/dom',\n ])\n ),\n },\n optimizeDeps,\n ...(isolationHeaders\n ? {\n server: {\n ...(userConfig.server ?? {}),\n headers: {\n ...(userConfig.server?.headers ?? {}),\n ...isolationHeaders,\n },\n },\n preview: {\n ...(userConfig.preview ?? {}),\n headers: {\n ...(userConfig.preview?.headers ?? {}),\n ...isolationHeaders,\n },\n },\n }\n : {}),\n }\n },\n }\n\n /**\n * Runs after vite-plugin-node-polyfills so absolute shim aliases win over its bare\n * package-id aliases in both resolve.alias and the Rolldown optimizeDeps graph.\n */\n const polyfillResolvePlugin: Plugin = {\n name: 'seed-protocol:polyfill-resolve',\n enforce: 'post',\n\n config(userConfig) {\n if (Object.keys(polyfillShimAliasObj).length === 0) return\n\n const existingResolve = userConfig.resolve ?? {}\n const mergedAlias = withPreferredPolyfillAliases(\n normalizeAliasEntries(existingResolve.alias),\n polyfillShimPaths,\n )\n\n const existingOptimize = userConfig.optimizeDeps\n\n return {\n resolve: {\n ...existingResolve,\n alias: mergedAlias,\n },\n optimizeDeps: {\n rolldownOptions: mergeOptimizeDepsRolldownOptions(existingOptimize, {\n // Later merge overwrites bare shim ids from vite-plugin-node-polyfills.\n alias: polyfillShimAliasObj,\n }),\n },\n }\n },\n\n resolveId: {\n order: 'pre',\n handler(id) {\n // Always rewrite injected shim package ids (safe even if nested under the SDK).\n if (id === 'vite-plugin-node-polyfills/shims/buffer') {\n return polyfillShimPaths.buffer ?? null\n }\n if (id === 'vite-plugin-node-polyfills/shims/global') {\n return polyfillShimPaths.global ?? null\n }\n if (id === 'vite-plugin-node-polyfills/shims/process') {\n return polyfillShimPaths.process ?? null\n }\n // Only remap node globals when we own the polyfills plugin config.\n if (!includeNodePolyfills) return null\n if (id === 'buffer' || id === 'node:buffer') return polyfillShimPaths.buffer ?? null\n if (id === 'global') return polyfillShimPaths.global ?? null\n if (id === 'process' || id === 'node:process') return polyfillShimPaths.process ?? null\n return null\n },\n },\n\n transform: {\n // After polyfills banner/inject so we collapse duplicates left in optimized deps.\n // Must emit absolute shim paths: order \"post\" runs after import-analysis.\n order: 'post',\n handler(code) {\n const count = (code.match(/import\\s+__buffer_polyfill\\b/g) || []).length\n let next = code\n let mutated = false\n\n if (count > 1) {\n const deduped = dedupeNodePolyfillBanner(next, polyfillShimPaths)\n if (deduped) {\n next = deduped\n mutated = true\n }\n }\n\n const rewritten = rewriteBarePolyfillShimImports(next, polyfillShimPaths)\n if (rewritten) {\n next = rewritten\n mutated = true\n }\n\n if (mutated) return { code: next, map: null }\n return null\n },\n },\n }\n\n /**\n * Post-plugin: build configuration + optional ZenFS init.\n */\n const mainPlugin: Plugin = {\n name: 'seed-protocol:main',\n enforce: 'post',\n\n configureServer(server) {\n if (isolationHeaders) applyIsolationHeaderMiddleware(server, isolationHeaders)\n },\n\n configurePreviewServer(server) {\n if (isolationHeaders) applyIsolationHeaderMiddleware(server, isolationHeaders)\n },\n\n config(userConfig) {\n const existingBuild = userConfig.build ?? {}\n const existingCommonjs = existingBuild.commonjsOptions ?? {}\n const existingRollupOptions = existingBuild.rollupOptions ?? {}\n const existingRolldownOptions = (existingBuild as Record<string, unknown>).rolldownOptions as\n | Record<string, unknown>\n | undefined\n const existingExternal = existingRollupOptions.external ?? []\n\n const include = [\n // Anything the user already had\n ...(Array.isArray(existingCommonjs.include)\n ? existingCommonjs.include\n : existingCommonjs.include\n ? [existingCommonjs.include]\n : []),\n // Always process node_modules and the SDK dist so require() is transformed\n /node_modules/,\n /seed-protocol-sdk[\\\\/]+dist[\\\\/]/,\n ]\n\n // Exclude packages that are already ESM or have special worker handling\n const exclude = [\n ...(Array.isArray(existingCommonjs.exclude)\n ? existingCommonjs.exclude\n : existingCommonjs.exclude\n ? [existingCommonjs.exclude]\n : []),\n // sqlocal is ESM and uses workers - don't transform it\n /node_modules[\\\\/]+sqlocal[\\\\/]/,\n ]\n\n const commonjsOptions = {\n ...existingCommonjs,\n include,\n exclude,\n transformMixedEsModules: true,\n }\n\n // Externalize Node.js-only packages that should never be bundled for the browser\n const nodeOnlyPackages = [\n 'better-sqlite3', // Native SQLite binding (Node.js only)\n ]\n\n const isNodeOnlyExternal = (id: string) =>\n nodeOnlyPackages.some(\n (pkg) =>\n id === pkg ||\n id.startsWith(`${pkg}/`) ||\n id.includes(`/${pkg}/`) ||\n id.endsWith(`/${pkg}`)\n )\n\n const externalList = (id: string, importer?: string, isResolved?: boolean) => {\n if (isNodeOnlyExternal(id)) return true\n if (typeof existingExternal === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (existingExternal as any)(id, importer, isResolved ?? false)\n }\n if (Array.isArray(existingExternal)) {\n return existingExternal.some((ext) => ext === id || id.startsWith(`${ext}/`))\n }\n return false\n }\n\n const rollupOptions = {\n ...existingRollupOptions,\n external: externalList,\n }\n\n const build: Record<string, unknown> = {\n ...existingBuild,\n commonjsOptions,\n }\n if (existingRolldownOptions) {\n build.rolldownOptions = {\n ...existingRolldownOptions,\n external: externalList,\n }\n } else {\n build.rollupOptions = rollupOptions\n }\n\n // Worker options are TOP-LEVEL in Vite config, not under build.\n // Default 'iife' breaks when workers use code-splitting (e.g. sqlocal).\n const existingWorker = userConfig.worker ?? {}\n const worker = {\n ...existingWorker,\n format: existingWorker.format ?? 'es',\n }\n\n return {\n build,\n worker,\n }\n },\n\n generateBundle(_options, bundle) {\n const allHits: Array<{ chunk: string } & GlobalHit> = []\n\n for (const [chunkName, asset] of Object.entries(bundle)) {\n if (asset.type !== 'chunk') continue\n const hits = findDangerousGlobals(asset.code)\n for (const hit of hits) {\n allHits.push({ chunk: chunkName, ...hit })\n }\n }\n\n if (allHits.length === 0) return\n\n console.warn(\n '\\n[seed-vite-plugin] ⚠️ Bare Node.js globals detected in browser bundle chunks.' +\n ' These will throw ReferenceError at runtime unless shimmed.\\n'\n )\n const byChunk = new Map<string, typeof allHits>()\n for (const hit of allHits) {\n const list = byChunk.get(hit.chunk) ?? []\n list.push(hit)\n byChunk.set(hit.chunk, list)\n }\n for (const [chunk, hits] of byChunk) {\n console.warn(` ${chunk}`)\n for (const h of hits) {\n console.warn(` line ${h.line}: \\`${h.global}\\` — ${h.context}`)\n }\n }\n console.warn('')\n },\n\n transformIndexHtml(html) {\n // Synchronous inline script runs before any <script type=\"module\">, so\n // global and process are guaranteed to exist when CJS wrappers evaluate.\n // vite-plugin-node-polyfills injects polyfills via module imports, which\n // resolve too late for @rollup/plugin-commonjs-generated wrapper code.\n const nodeEnvLiteral = JSON.stringify(htmlNodeEnv)\n const shimScript = `<script>\n(function(){\n if(typeof globalThis.global==='undefined')globalThis.global=globalThis;\n if(typeof globalThis.process==='undefined')globalThis.process={env:{NODE_ENV:${nodeEnvLiteral}},browser:true,version:'v18.0.0',versions:{},platform:'browser',cwd:function(){return'/'},nextTick:function(fn){setTimeout(fn,0)}};\n})();\n</script>`\n\n let result = html\n if (result.includes('<head>')) {\n result = result.replace('<head>', `<head>\\n${shimScript}`)\n } else {\n result = shimScript + result\n }\n\n if (!autoInit) return result\n\n const initScript = `\n<script type=\"module\">\nimport { configure } from '@zenfs/core';\nimport { IndexedDB } from '@zenfs/dom';\n\nif (!window.__seedFsReady) {\n window.__seedFsReady = configure({\n mounts: { '/': IndexedDB },\n }).catch((err) => {\n console.error('[seed-vite-plugin] ZenFS initialization failed', err);\n });\n}\n</script>`\n\n if (result.includes('</head>')) {\n return result.replace('</head>', `${initScript}\\n</head>`)\n }\n\n return result + initScript\n },\n }\n\n const sdkImportFixPlugin: Plugin = {\n name: 'seed-protocol:sdk-import-fix',\n enforce: 'post',\n transform(code, id) {\n if (!id.includes('@seedprotocol/sdk') || !id.includes('FileManager')) {\n return null\n }\n const hasDefaultPathBrowserifyImport =\n /import\\s+path\\s+from\\s+['\"]path-browserify['\"]/.test(code)\n if (!hasDefaultPathBrowserifyImport) {\n return null\n }\n const transformed = code.replace(\n /import\\s+path\\s+from\\s+['\"]path-browserify['\"];/g,\n \"import * as path from 'path';\",\n )\n if (transformed === code) {\n return null\n }\n return { code: transformed, map: null }\n },\n }\n\n const plugins: Plugin[] = [configPlugin, mainPlugin, sdkImportFixPlugin]\n\n if (includeNodePolyfills) {\n log('Including vite-plugin-node-polyfills with default settings')\n // vite-plugin-node-polyfills ≥0.27 returns Plugin[]; older versions returned a single Plugin.\n const polyfillPlugins = nodePolyfills({\n // Let fs be handled by @zenfs/core instead of polyfills\n exclude: ['readline',],\n // Common set of browser-friendly polyfills used by many deps\n include: ['path', 'buffer', 'events', 'string_decoder', 'util'],\n globals: {\n Buffer: true,\n global: true,\n process: true,\n },\n protocolImports: true,\n }) as unknown as Plugin | Plugin[]\n if (Array.isArray(polyfillPlugins)) {\n plugins.push(...polyfillPlugins)\n } else {\n plugins.push(polyfillPlugins)\n }\n }\n\n // After nodePolyfills so config() can overwrite its bare shim aliases.\n if (Object.keys(polyfillShimAliasObj).length > 0) {\n plugins.push(polyfillResolvePlugin)\n }\n\n return plugins\n}\n"],"mappings":";;;;;;AAOA,IAAM,IAAO,EAAc,YAAY,GAAG,GAsDpC,IAAoD;CACxD,QAAY;CACZ,SAAY;CACZ,QAAY;CACZ,WAAY;CACZ,YAAY;AACd;AAOA,SAAS,EAAwB,GAAsB;CACrD,OAAO,EACJ,QAAQ,sBAAsB,MAAM,IAAI,OAAO,EAAE,MAAM,CAAC,CAAC,CACzD,QAAQ,gBAAgB,MAAM,IAAI,OAAO,EAAE,MAAM,CAAC,CAAC,CACnD,QAAQ,wBAAwB,MAAM,MAAM,IAAI,OAAO,EAAE,SAAS,CAAC,IAAI,GAAG,CAAC,CAC3E,QAAQ,uBAAuB,MAAM,OAAM,IAAI,OAAO,EAAE,SAAS,CAAC,IAAI,IAAG,CAAC,CAC1E,QAAQ,uBAAuB,MAAM,MAAM,IAAI,OAAO,EAAE,SAAS,CAAC,IAAI,GAAG;AAC9E;AAYA,SAAS,EAAqB,GAA8B;CAC1D,IAAM,IAAW,EAAwB,CAAO,GAC1C,IAAoB,CAAC;CAE3B,KAAK,IAAM,CAAC,GAAM,MAAgB,OAAO,QAAQ,CAAyB,GAAG;EAE3E,IAAM,IAAS,OAAO,kBAAkB,EAAK,wBAAwB,GAAG,GACpE;EACJ,QAAQ,IAAI,EAAG,KAAK,CAAQ,OAAO,OAAM;GACvC,IAAM,IAAS,EAAE,OAEX,IAAS,EAAS,MAAM,KAAK,IAAI,GAAG,IAAS,EAAE,GAAG,CAAM;GAC9D,IAAI,EAAY,KAAK,CAAM,GAAG;GAI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addListener: typeof noop;
|
|
7
|
+
removeListener: typeof noop;
|
|
8
|
+
removeAllListeners: typeof noop;
|
|
9
|
+
emit(): boolean;
|
|
10
|
+
pipe(dest: any): any;
|
|
11
|
+
}
|
|
12
|
+
export const Readable: typeof Stream;
|
|
13
|
+
export const Writable: typeof Stream;
|
|
14
|
+
export const Duplex: typeof Stream;
|
|
15
|
+
export const Transform: typeof Stream;
|
|
16
|
+
export const PassThrough: typeof Stream;
|
|
17
|
+
export default api;
|
|
18
|
+
/**
|
|
19
|
+
* Minimal Node `stream` stub for browser/renderer bundles.
|
|
20
|
+
*
|
|
21
|
+
* Vite externalizes bare `stream` and warns on property access. Deps such as
|
|
22
|
+
* `sax` (pulled in by `rss-parser` via `@seedprotocol/feed` / `@seedprotocol/mapping`)
|
|
23
|
+
* do `require('stream').Stream` inside try/catch at module init — the external
|
|
24
|
+
* stub warns instead of throwing, so the warning still appears.
|
|
25
|
+
*
|
|
26
|
+
* This shim provides a no-op Stream constructor so that path stays quiet without
|
|
27
|
+
* pulling in `stream-browserify` (which breaks Vite SSR / React Router prerender).
|
|
28
|
+
*/
|
|
29
|
+
declare function noop(): any;
|
|
30
|
+
declare namespace api {
|
|
31
|
+
export { Stream };
|
|
32
|
+
export { Readable };
|
|
33
|
+
export { Writable };
|
|
34
|
+
export { Duplex };
|
|
35
|
+
export { Transform };
|
|
36
|
+
export { PassThrough };
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=stream-default-shim.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stream-default-shim.d.ts","sourceRoot":"","sources":["../src/stream-default-shim.js"],"names":[],"mappings":"AAgBA,+BAA2B;;IAC3B,gBAAmB;IACnB,kBAAqB;IACrB,iBAAoB;IACpB,yBAA4B;IAC5B,4BAA+B;IAC/B,gCAAmC;IACnC,gBAEC;IACD,qBAEC;;AAED,qCAA8B;AAC9B,qCAA8B;AAC9B,mCAA4B;AAC5B,sCAA+B;AAC/B,wCAAiC;;AAlCjC;;;;;;;;;;GAUG;AAEH,6BAEC"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal Node `stream` stub for browser/renderer bundles.
|
|
3
|
+
*
|
|
4
|
+
* Vite externalizes bare `stream` and warns on property access. Deps such as
|
|
5
|
+
* `sax` (pulled in by `rss-parser` via `@seedprotocol/feed` / `@seedprotocol/mapping`)
|
|
6
|
+
* do `require('stream').Stream` inside try/catch at module init — the external
|
|
7
|
+
* stub warns instead of throwing, so the warning still appears.
|
|
8
|
+
*
|
|
9
|
+
* This shim provides a no-op Stream constructor so that path stays quiet without
|
|
10
|
+
* pulling in `stream-browserify` (which breaks Vite SSR / React Router prerender).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
function noop() {
|
|
14
|
+
return this
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function Stream() {}
|
|
18
|
+
Stream.prototype.on = noop
|
|
19
|
+
Stream.prototype.once = noop
|
|
20
|
+
Stream.prototype.off = noop
|
|
21
|
+
Stream.prototype.addListener = noop
|
|
22
|
+
Stream.prototype.removeListener = noop
|
|
23
|
+
Stream.prototype.removeAllListeners = noop
|
|
24
|
+
Stream.prototype.emit = function emit() {
|
|
25
|
+
return false
|
|
26
|
+
}
|
|
27
|
+
Stream.prototype.pipe = function pipe(dest) {
|
|
28
|
+
return dest
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const Readable = Stream
|
|
32
|
+
export const Writable = Stream
|
|
33
|
+
export const Duplex = Stream
|
|
34
|
+
export const Transform = Stream
|
|
35
|
+
export const PassThrough = Stream
|
|
36
|
+
|
|
37
|
+
const api = {
|
|
38
|
+
Stream,
|
|
39
|
+
Readable,
|
|
40
|
+
Writable,
|
|
41
|
+
Duplex,
|
|
42
|
+
Transform,
|
|
43
|
+
PassThrough,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export default api
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seedprotocol/vite",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.7",
|
|
4
4
|
"description": "Vite plugin for Seed Protocol browser/renderer apps",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
],
|
|
23
23
|
"scripts": {
|
|
24
24
|
"build": "rimraf dist && tsc -p tsconfig.build.json && vite build",
|
|
25
|
-
"test": "vitest run --reporter=default",
|
|
25
|
+
"test": "vitest run --reporter=default && node ../../scripts/check-browser-entry-graph.js --fail",
|
|
26
26
|
"prepublishOnly": "bun run build && node ../../scripts/sync-versions.js"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
@@ -43,6 +43,9 @@
|
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"@types/bun": "latest",
|
|
45
45
|
"@types/node": "^24.10.1",
|
|
46
|
+
"@vitejs/plugin-react": "^6.0.0",
|
|
47
|
+
"react": "^19.0.0",
|
|
48
|
+
"react-dom": "^19.0.0",
|
|
46
49
|
"rimraf": "^6.0.1",
|
|
47
50
|
"typescript": "~5.9.3",
|
|
48
51
|
"vite": "^8.0.0",
|