@seedprotocol/vite 0.6.10 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
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"}
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;AAqlBD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,cAAc,CAAC,OAAO,GAAE,qBAA0B,GAAG,MAAM,EAAE,CAsf5E"}
package/dist/index.js CHANGED
@@ -43,21 +43,21 @@ var l = [
43
43
  "seedrandom",
44
44
  "@georgedoescode/generative-utils",
45
45
  "nanoid-dictionary"
46
- ], h = ["@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk", "@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk > @ethereum-attestation-service/eas-contracts"], g = ["pluralize"], _ = {
46
+ ], h = ["@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk", "@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk > @ethereum-attestation-service/eas-contracts"], g = ["viem", "isows"], _ = ["pluralize"], v = {
47
47
  "Cross-Origin-Opener-Policy": "same-origin",
48
48
  "Cross-Origin-Embedder-Policy": "credentialless",
49
49
  "Cross-Origin-Resource-Policy": "same-origin"
50
50
  };
51
- function v(e) {
51
+ function y(e) {
52
52
  if (e === !1) return null;
53
53
  let t = typeof e == "object" && e ? e : {};
54
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"]
55
+ "Cross-Origin-Opener-Policy": t.coop ?? v["Cross-Origin-Opener-Policy"],
56
+ "Cross-Origin-Embedder-Policy": t.coep ?? v["Cross-Origin-Embedder-Policy"],
57
+ "Cross-Origin-Resource-Policy": t.corp ?? v["Cross-Origin-Resource-Policy"]
58
58
  };
59
59
  }
60
- function y(e, t) {
60
+ function b(e, t) {
61
61
  e.middlewares.use((e, n, r) => {
62
62
  let i = () => {
63
63
  for (let [e, r] of Object.entries(t)) n.getHeader(e) || n.setHeader(e, r);
@@ -65,12 +65,15 @@ function y(e, t) {
65
65
  n.writeHead = ((...e) => (i(), a(...e))), i(), r();
66
66
  });
67
67
  }
68
- function b(t, r, i, a) {
68
+ function x(t, r, i, a) {
69
69
  if (!e.existsSync(t)) return;
70
70
  let o = r.startsWith("@") ? r.replace("/", "+") : r;
71
71
  for (let s of e.readdirSync(t)) (s.startsWith(`${o}@`) || s.startsWith(`${r}@`)) && a.push(n.join(t, s, `node_modules/${r}`, i));
72
72
  }
73
- function x(t, r) {
73
+ function S(r, i) {
74
+ return (t(n.join(i, "package.json")).resolve.paths(r) ?? []).some((t) => e.existsSync(n.join(t, r, "package.json")));
75
+ }
76
+ function C(t, r) {
74
77
  let i = [], o = n.resolve(u, "..");
75
78
  try {
76
79
  let e = a.resolve(`${t}/package.json`);
@@ -94,12 +97,12 @@ function x(t, r) {
94
97
  }
95
98
  i.push(n.join(o, "node_modules", t, r));
96
99
  let s = n.join(process.cwd(), "node_modules");
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);
100
+ i.push(n.join(s, t, r)), x(n.join(s, ".bun"), t, r, i), x(n.join(o, "node_modules", ".bun"), t, r, i);
101
+ let c = w(o);
102
+ c && x(n.join(c, "node_modules", ".bun"), t, r, i);
100
103
  for (let t of i) if (e.existsSync(t)) return t;
101
104
  }
102
- function S(t) {
105
+ function w(t) {
103
106
  let r = n.resolve(t);
104
107
  for (let t = 0; t < 8; t++) {
105
108
  if (e.existsSync(n.join(r, "node_modules", ".bun"))) return r;
@@ -108,23 +111,23 @@ function S(t) {
108
111
  r = t;
109
112
  }
110
113
  }
111
- function C(e, t) {
114
+ function T(e, t) {
112
115
  let r = n.resolve(t);
113
116
  return e.some((e) => {
114
117
  let t = n.resolve(String(e));
115
118
  return r === t || r.startsWith(t.endsWith(n.sep) ? t : t + n.sep);
116
119
  });
117
120
  }
118
- function w(t) {
121
+ function E(t) {
119
122
  try {
120
123
  return e.realpathSync(t);
121
124
  } catch {
122
125
  return n.resolve(t);
123
126
  }
124
127
  }
125
- function T() {
128
+ function D() {
126
129
  let e = /* @__PURE__ */ new Set(), t = (t) => {
127
- t && e.add(w(t));
130
+ t && e.add(E(t));
128
131
  }, r;
129
132
  try {
130
133
  r = n.dirname(a.resolve("@seedprotocol/sdk/package.json"));
@@ -132,20 +135,20 @@ function T() {
132
135
  r = n.resolve(u, "..");
133
136
  }
134
137
  t(r);
135
- let i = S(r);
138
+ let i = w(r);
136
139
  i && t(i);
137
140
  for (let e of ["sqlocal", "@sqlite.org/sqlite-wasm"]) {
138
- let r = x(e, "package.json");
141
+ let r = C(e, "package.json");
139
142
  r && t(n.dirname(r));
140
143
  }
141
144
  return [...e];
142
145
  }
143
- function E(e) {
146
+ function O(e) {
144
147
  let t = [];
145
- for (let n of T()) C(e, n) || (e.push(n), t.push(n));
148
+ for (let n of D()) T(e, n) || (e.push(n), t.push(n));
146
149
  return t;
147
150
  }
148
- function D(e) {
151
+ function k(e) {
149
152
  return e ? Array.isArray(e) ? e.filter((e) => !!e && !!e.replacement).map((e) => ({
150
153
  find: e.find,
151
154
  replacement: e.replacement
@@ -154,7 +157,7 @@ function D(e) {
154
157
  replacement: String(t)
155
158
  })) : [];
156
159
  }
157
- function O(e, t) {
160
+ function A(e, t) {
158
161
  let n = [...e], r = (e) => typeof e == "string" ? `s:${e}` : `r:${e.toString()}`, i = new Set(n.map((e) => r(e.find)));
159
162
  for (let e of t) {
160
163
  let t = r(e.find);
@@ -162,12 +165,12 @@ function O(e, t) {
162
165
  }
163
166
  return n;
164
167
  }
165
- var k = [
168
+ var j = [
166
169
  "vite-plugin-node-polyfills/shims/buffer",
167
170
  "vite-plugin-node-polyfills/shims/global",
168
171
  "vite-plugin-node-polyfills/shims/process"
169
172
  ];
170
- function A(t) {
173
+ function M(t) {
171
174
  let n = a.resolve(t);
172
175
  if (n.endsWith(".cjs")) {
173
176
  let t = n.slice(0, -4) + ".js";
@@ -175,10 +178,10 @@ function A(t) {
175
178
  }
176
179
  return n;
177
180
  }
178
- function j() {
181
+ function N() {
179
182
  let e = {}, t = [];
180
- for (let n of k) try {
181
- let t = A(n);
183
+ for (let n of j) try {
184
+ let t = M(n);
182
185
  n.endsWith("/buffer") ? e.buffer = t : n.endsWith("/global") ? e.global = t : n.endsWith("/process") && (e.process = t);
183
186
  } catch {
184
187
  t.push(n);
@@ -188,15 +191,7 @@ function j() {
188
191
  unresolved: t
189
192
  };
190
193
  }
191
- function M(e, t) {
192
- if ((e.match(/import\s+__buffer_polyfill\b/g) || []).length <= 1 || !t.buffer || !t.global || !t.process) return null;
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, "");
194
- return n === e ? null : `import __buffer_polyfill from ${JSON.stringify(t.buffer)};\nglobalThis.Buffer = globalThis.Buffer || __buffer_polyfill;
195
- import __global_polyfill from ${JSON.stringify(t.global)};\nglobalThis.global = globalThis.global || __global_polyfill;
196
- import __process_polyfill from ${JSON.stringify(t.process)};\nglobalThis.process = globalThis.process || __process_polyfill;
197
- ` + n;
198
- }
199
- function N(e, t) {
194
+ function P(e, t) {
200
195
  let n = e, r = !1, i = [];
201
196
  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]);
202
197
  for (let [e, t] of i) {
@@ -208,7 +203,7 @@ function N(e, t) {
208
203
  }
209
204
  return r ? n : null;
210
205
  }
211
- function P(e, t) {
206
+ function F(e, t) {
212
207
  t.buffer && e.push({
213
208
  find: "vite-plugin-node-polyfills/shims/buffer",
214
209
  replacement: t.buffer
@@ -235,11 +230,11 @@ function P(e, t) {
235
230
  replacement: t.process
236
231
  });
237
232
  }
238
- function F(e) {
233
+ function I(e) {
239
234
  let t = {};
240
235
  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;
241
236
  }
242
- var I = /* @__PURE__ */ new Set([
237
+ var L = /* @__PURE__ */ new Set([
243
238
  "vite-plugin-node-polyfills/shims/buffer",
244
239
  "vite-plugin-node-polyfills/shims/global",
245
240
  "vite-plugin-node-polyfills/shims/process",
@@ -249,19 +244,19 @@ var I = /* @__PURE__ */ new Set([
249
244
  "node:process",
250
245
  "global"
251
246
  ]);
252
- function L(e, t) {
247
+ function R(e, t) {
253
248
  let n = [];
254
- if (P(n, t), n.length === 0) return e;
255
- let r = e.filter((e) => typeof e.find != "string" || !I.has(e.find));
249
+ if (F(n, t), n.length === 0) return e;
250
+ let r = e.filter((e) => typeof e.find != "string" || !L.has(e.find));
256
251
  return [...n, ...r];
257
252
  }
258
- function R(t) {
259
- let n = x("nanoid-dictionary", "dist/dictionary.esm.js");
253
+ function z(t) {
254
+ let n = C("nanoid-dictionary", "dist/dictionary.esm.js");
260
255
  n && t.push({
261
256
  find: /^nanoid-dictionary$/,
262
257
  replacement: n
263
258
  });
264
- let r = x("@zenfs/core", "dist/index.js"), i = x("@zenfs/core", "dist/path.js");
259
+ let r = C("@zenfs/core", "dist/index.js"), i = C("@zenfs/core", "dist/path.js");
265
260
  r && t.push({
266
261
  find: /^@zenfs\/core$/,
267
262
  replacement: r
@@ -269,7 +264,7 @@ function R(t) {
269
264
  find: /^@zenfs\/core\/path$/,
270
265
  replacement: i
271
266
  });
272
- let a = x("@zenfs/dom", "dist/index.js");
267
+ let a = C("@zenfs/dom", "dist/index.js");
273
268
  a && t.push({
274
269
  find: /^@zenfs\/dom$/,
275
270
  replacement: a
@@ -277,7 +272,7 @@ function R(t) {
277
272
  find: /^debug$/,
278
273
  replacement: f
279
274
  });
280
- let o = x("debug", "src/browser.js");
275
+ let o = C("debug", "src/browser.js");
281
276
  o && t.push({
282
277
  find: /^debug\/src\/browser\.js$/,
283
278
  replacement: o
@@ -289,80 +284,61 @@ function R(t) {
289
284
  replacement: p
290
285
  });
291
286
  }
292
- function z() {
293
- let e = x("debug", "src/browser.js");
287
+ function B() {
288
+ let e = C("debug", "src/browser.js");
294
289
  return e ? { "debug/src/browser.js": e } : {};
295
290
  }
296
- function B() {
291
+ function V() {
297
292
  return e.existsSync(p) ? {
298
293
  stream: p,
299
294
  "node:stream": p
300
295
  } : {};
301
296
  }
302
- function V(e) {
303
- let t = e ?? {};
304
- return t.rolldownOptions ?? t.rollupOptions ?? {};
305
- }
306
297
  function H(e, t) {
307
- let n = V(e), r = n.resolve ?? {}, i = n.transform ?? {}, a = {
308
- ...e?.esbuildOptions?.define ?? {},
309
- ...i.define,
298
+ let n = {
299
+ ...e?.esbuildOptions?.define,
310
300
  ...t.define
311
- }, o = {
312
- ...r.alias,
313
- ...t.alias
314
- };
301
+ }, r = t.alias ?? {};
315
302
  return {
316
- ...n,
317
- ...Object.keys(a).length > 0 ? { transform: {
318
- ...i,
319
- define: a
320
- } } : {},
321
- ...Object.keys(o).length > 0 ? { resolve: {
322
- ...r,
323
- alias: o
324
- } } : {}
303
+ ...Object.keys(n).length > 0 ? { transform: { define: n } } : {},
304
+ ...Object.keys(r).length > 0 ? { resolve: { alias: r } } : {}
325
305
  };
326
306
  }
327
- function U(e) {
328
- let { esbuildOptions: t, rollupOptions: n, ...r } = e ?? {};
329
- return r;
330
- }
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) => {
333
- r && console.log("[seed-vite-plugin]", ...e);
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 = {
307
+ function U(e = {}) {
308
+ let { fsModules: t = l, autoInit: r = !1, debug: a = !1, includeNodePolyfills: o = !0, isolationHeaders: s } = e, u = y(s), f = "production", p = (...e) => {
309
+ a && console.log("[seed-vite-plugin]", ...e);
310
+ }, { paths: v, unresolved: x } = N(), w = I(v);
311
+ o && x.length > 0 ? console.warn("[seed-vite-plugin] Could not resolve vite-plugin-node-polyfills shims from the SDK package:\n" + x.map((e) => ` - ${e}`).join("\n") + "\nNode polyfill globals may fail to resolve. Reinstall @seedprotocol/sdk, or set includeNodePolyfills: false and configure polyfills yourself.") : x.length === 0 && p("Resolved vite-plugin-node-polyfills shims to absolute paths");
312
+ let T = {
337
313
  name: "seed-protocol:config",
338
314
  enforce: "pre",
339
315
  configResolved(e) {
340
- let t = E(e.server.fs.allow);
341
- t.length > 0 && f("Extended server.fs.allow for linked SDK / sqlocal worker paths:", t);
316
+ let t = O(e.server.fs.allow);
317
+ t.length > 0 && p("Extended server.fs.allow for linked SDK / sqlocal worker paths:", t);
342
318
  },
343
- config(e, n) {
344
- n?.mode && (u = n.mode);
345
- let r = [];
319
+ config(e, r) {
320
+ r?.mode && (f = r.mode);
321
+ let i = [];
346
322
  for (let e of t) {
347
323
  let t = e.includes("promises") ? "@zenfs/core/promises" : "@zenfs/core";
348
- r.push({
324
+ i.push({
349
325
  find: e,
350
326
  replacement: t
351
327
  });
352
328
  }
353
- let i = x("eventemitter3", "dist/eventemitter3.esm.js");
354
- i && r.push({
329
+ let a = C("eventemitter3", "dist/eventemitter3.esm.js");
330
+ a && i.push({
355
331
  find: "eventemitter3",
356
- replacement: i
332
+ replacement: a
357
333
  }, {
358
334
  find: "eventemitter3/index.mjs",
359
- replacement: i
335
+ replacement: a
360
336
  }, {
361
337
  find: "eventemitter3/index.js",
362
- replacement: i
338
+ replacement: a
363
339
  });
364
- let a = x("arweave", "bundles/web.bundle.js");
365
- a && r.push({
340
+ let o = C("arweave", "bundles/web.bundle.js");
341
+ o && i.push({
366
342
  find: /^arweave$/,
367
343
  replacement: d
368
344
  }, {
@@ -370,39 +346,34 @@ function W(e = {}) {
370
346
  replacement: d
371
347
  }, {
372
348
  find: /^arweave\/bundles\/web\.bundle\.js$/,
373
- replacement: a
374
- }), R(r), P(r, p);
375
- let o = e.resolve ?? {}, c = O(D(o.alias), r), l = [
349
+ replacement: o
350
+ }), z(i), F(i, v);
351
+ let s = e.resolve ?? {}, c = A(k(s.alias), i), l = [
376
352
  "@zenfs/core",
377
353
  "@zenfs/dom",
378
354
  "kerium",
379
355
  "utilium",
380
356
  "memium",
381
357
  "readable-stream",
382
- "viem",
383
- "isows",
384
358
  ...m
385
- ].filter((e) => !!x(e, "package.json")), f = e.optimizeDeps, _ = z(), v = B(), y = {
386
- ...U(f),
359
+ ], p = n.resolve(e.root ?? process.cwd()), y = [...l.filter((e) => !!C(e, "package.json")), ...g.filter((e) => S(e, p))], b = e.optimizeDeps, x = B(), T = V(), E = {
387
360
  exclude: [
388
- ...f?.exclude ?? [],
389
361
  "@seedprotocol/sdk",
390
362
  "drizzle-orm",
391
363
  "better-sqlite3",
392
364
  "sqlocal"
393
365
  ],
394
366
  include: [
395
- ...f?.include ?? [],
396
- ...l,
367
+ ...y,
397
368
  ...h,
398
- ...g
369
+ ..._
399
370
  ],
400
- rolldownOptions: H(f, {
371
+ rolldownOptions: H(b, {
401
372
  define: { global: "globalThis" },
402
373
  alias: {
403
- ..._,
404
- ...v,
405
- ...b
374
+ ...x,
375
+ ...T,
376
+ ...w
406
377
  }
407
378
  })
408
379
  };
@@ -414,10 +385,10 @@ function W(e = {}) {
414
385
  "process.platform": "\"browser\""
415
386
  },
416
387
  resolve: {
417
- ...o,
388
+ ...s,
418
389
  alias: c,
419
390
  dedupe: Array.from(/* @__PURE__ */ new Set([
420
- ...o.dedupe ?? [],
391
+ ...s.dedupe ?? [],
421
392
  "react",
422
393
  "react-dom",
423
394
  "thirdweb",
@@ -431,70 +402,63 @@ function W(e = {}) {
431
402
  "@zenfs/dom"
432
403
  ]))
433
404
  },
434
- optimizeDeps: y,
435
- ...s ? {
405
+ optimizeDeps: E,
406
+ ...u ? {
436
407
  server: {
437
408
  ...e.server ?? {},
438
409
  headers: {
439
410
  ...e.server?.headers ?? {},
440
- ...s
411
+ ...u
441
412
  }
442
413
  },
443
414
  preview: {
444
415
  ...e.preview ?? {},
445
416
  headers: {
446
417
  ...e.preview?.headers ?? {},
447
- ...s
418
+ ...u
448
419
  }
449
420
  }
450
421
  } : {}
451
422
  };
452
423
  }
453
- }, C = {
424
+ }, E = {
454
425
  name: "seed-protocol:polyfill-resolve",
455
426
  enforce: "post",
456
427
  config(e) {
457
- if (Object.keys(b).length === 0) return;
458
- let t = e.resolve ?? {}, n = L(D(t.alias), p), r = e.optimizeDeps;
459
- return {
460
- resolve: {
461
- ...t,
462
- alias: n
463
- },
464
- optimizeDeps: { rolldownOptions: H(r, { alias: b }) }
428
+ if (Object.keys(w).length !== 0) return {
429
+ resolve: { alias: R(k((e.resolve ?? {}).alias), v) },
430
+ optimizeDeps: { rolldownOptions: H(void 0, {
431
+ define: { global: "globalThis" },
432
+ alias: w
433
+ }) }
465
434
  };
466
435
  },
467
436
  resolveId: {
468
437
  order: "pre",
469
438
  handler(e) {
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;
439
+ return e === "vite-plugin-node-polyfills/shims/buffer" ? v.buffer ?? null : e === "vite-plugin-node-polyfills/shims/global" ? v.global ?? null : e === "vite-plugin-node-polyfills/shims/process" ? v.process ?? null : o ? e === "buffer" || e === "node:buffer" ? v.buffer ?? null : e === "global" ? v.global ?? null : e === "process" || e === "node:process" ? v.process ?? null : null : null;
471
440
  }
472
441
  },
473
442
  transform: {
474
443
  order: "post",
475
444
  handler(e) {
476
- let t = (e.match(/import\s+__buffer_polyfill\b/g) || []).length, n = e, r = !1;
477
- if (t > 1) {
478
- let e = M(n, p);
479
- e && (n = e, r = !0);
480
- }
481
- let i = N(n, p);
482
- return i && (n = i, r = !0), r ? {
483
- code: n,
445
+ let t = P(e, v);
446
+ return t ? {
447
+ code: t,
484
448
  map: null
485
449
  } : null;
486
450
  }
487
451
  }
488
- }, w = [
489
- S,
452
+ }, D = [
453
+ T,
490
454
  {
491
455
  name: "seed-protocol:main",
492
456
  enforce: "post",
493
457
  configureServer(e) {
494
- s && y(e, s);
458
+ u && b(e, u);
495
459
  },
496
460
  configurePreviewServer(e) {
497
- s && y(e, s);
461
+ u && b(e, u);
498
462
  },
499
463
  config(e) {
500
464
  let t = e.build ?? {}, n = t.commonjsOptions ?? {}, r = t.rollupOptions ?? {}, i = t.rolldownOptions, a = r.external ?? [], o = [
@@ -553,12 +517,12 @@ function W(e = {}) {
553
517
  let t = `<script>
554
518
  (function(){
555
519
  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)}};
520
+ if(typeof globalThis.process==='undefined')globalThis.process={env:{NODE_ENV:${JSON.stringify(f)}},browser:true,version:'v18.0.0',versions:{},platform:'browser',cwd:function(){return'/'},nextTick:function(fn){setTimeout(fn,0)}};
557
521
  })();
558
- <\/script>`, r = e;
559
- if (r = r.includes("<head>") ? r.replace("<head>", `<head>\n${t}`) : t + r, !n) return r;
522
+ <\/script>`, n = e;
523
+ if (n = n.includes("<head>") ? n.replace("<head>", `<head>\n${t}`) : t + n, !r) return n;
560
524
  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>";
561
- return r.includes("</head>") ? r.replace("</head>", `${i}\n</head>`) : r + i;
525
+ return n.includes("</head>") ? n.replace("</head>", `${i}\n</head>`) : n + i;
562
526
  }
563
527
  },
564
528
  {
@@ -574,8 +538,8 @@ function W(e = {}) {
574
538
  }
575
539
  }
576
540
  ];
577
- if (a) {
578
- f("Including vite-plugin-node-polyfills with default settings");
541
+ if (o) {
542
+ p("Including vite-plugin-node-polyfills with default settings");
579
543
  let e = i({
580
544
  exclude: ["readline"],
581
545
  include: [
@@ -592,11 +556,11 @@ function W(e = {}) {
592
556
  },
593
557
  protocolImports: !0
594
558
  });
595
- Array.isArray(e) ? w.push(...e) : w.push(e);
559
+ Array.isArray(e) ? D.push(...e) : D.push(e);
596
560
  }
597
- return Object.keys(b).length > 0 && w.push(C), w;
561
+ return Object.keys(w).length > 0 && D.push(E), D;
598
562
  }
599
563
  //#endregion
600
- export { W as seedVitePlugin };
564
+ export { U as seedVitePlugin };
601
565
 
602
566
  //# 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 { 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 &lt;script type=\"module\"&gt; 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,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AS,aAAa,KAK/D,CADF,iDAAiD,KAAK,CACnD,GACH,OAAO;IAET,IAAM,IAAc,EAAK,QACvB,oDACA,+BACF;IAIA,OAHI,MAAgB,IACX,OAEF;KAAE,MAAM;KAAa,KAAK;IAAK;GACxC;EAGmD;CAAkB;CAEvE,IAAI,GAAsB;EACxB,EAAI,4DAA4D;EAEhE,IAAM,IAAkB,EAAc;GAEpC,SAAS,CAAC,UAAW;GAErB,SAAS;IAAC;IAAQ;IAAU;IAAU;IAAkB;GAAM;GAC9D,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":["fs","path","_req","createRequire","BROWSER_DANGEROUS_GLOBALS","stripStringsAndComments","code","m","findDangerousGlobals","stripped","rawCode","hits","name","typeofGuard","re","offset","before","linesBefore","line","colOffset","ctx","DEFAULT_FS_MODULES","SDK_DIST_DIR","fileURLToPath","ARWEAVE_SHIM_FILE","DEBUG_SHIM_FILE","STREAM_SHIM_FILE","FRAGILE_RENDERER_OPTIMIZE_INCLUDES","EAS_OPTIMIZE_INCLUDES","APP_OPTIONAL_OPTIMIZE_INCLUDES","CJS_OPTIMIZE_INCLUDES","DEFAULT_ISOLATION_HEADERS","resolveIsolationHeaders","option","overrides","applyIsolationHeaderMiddleware","apply","key","value","headers","res","originalWriteHead","args","next","pushBunPackageCandidates","bunDir","bunPrefix","packageName","entry","candidates","relativePath","isResolvableFromRoot","root","dir","resolvePackageFile","sdkRoot","pkgJson","i","pkgJsonPath","parent","cwdNodeModules","bunInstallRoot","findNodeModulesBunRoot","candidate","startDir","isFsAllowCovering","child","filePath","allow","uri","realpathOrResolve","p","collectDevServerFsAllowPaths","paths","add","sdkPkgDir","pkg","ensureDevServerFsAllow","added","normalizeAliasEntries","alias","find","replacement","mergeAliasEntries","merged","existing","keyOf","seen","additions","NODE_POLYFILL_SHIM_IDS","resolvePolyfillShimFile","resolved","shimId","esm","resolveNodePolyfillShimPaths","unresolved","id","abs","rewriteBarePolyfillShimImports","changed","replacements","bare","absLiteral","quote","from","addNodePolyfillShimAliases","aliasEntries","nodePolyfillShimAliasObject","POLYFILL_ALIAS_FINDS_TO_REPLACE","withPreferredPolyfillAliases","preferred","filtered","addRendererCompatibilityAliases","nanoidDictionaryEsm","zenfsCoreIndex","zenfsCorePath","zenfsDomIndex","debugBrowserEntry","debugShimOptimizeAliasObject","streamShimOptimizeAliasObject","optimizeDepsRolldownPatch","define","patch","seedVitePlugin","isolationHeadersOption","options","isolationHeaders","htmlNodeEnv","log","debug","polyfillShimPaths","unresolvedPolyfillShims","polyfillShimAliasObj","includeNodePolyfills","configPlugin","addedAllowPaths","resolvedConfig","env","mod","fsModules","target","eventEmitterEsm","arweaveBundle","existingResolve","userConfig","mergedAlias","desiredOptimizeIncludes","appRoot","resolvableOptimizeIncludes","dep","existingOptimize","debugOptimizeAliases","streamOptimizeAliases","optimizeDeps","polyfillResolvePlugin","rewritten","plugins","server","existingBuild","existingCommonjs","existingRollupOptions","existingRolldownOptions","existingExternal","include","exclude","commonjsOptions","nodeOnlyPackages","isNodeOnlyExternal","externalList","importer","isResolved","ext","rollupOptions","build","existingWorker","allHits","chunkName","asset","bundle","hit","byChunk","list","chunk","h","shimScript","result","html","autoInit","initScript","transformed","polyfillPlugins","nodePolyfills"],"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 &lt;script type=\"module\"&gt; 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/**\n * Prebundled only when the app itself can resolve them (they come from\n * @seedprotocol/publish, not the SDK). Vite resolves `include` entries from the\n * app root, so finding them elsewhere in node_modules is not enough.\n */\nconst APP_OPTIONAL_OPTIMIZE_INCLUDES = ['viem', 'isows'] 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\n/** Whether a package is installed where Vite's optimizer looks for it (the app root upward). */\nfunction isResolvableFromRoot(packageName: string, root: string): boolean {\n const lookupDirs = createRequire(path.join(root, 'package.json')).resolve.paths(packageName) ?? []\n return lookupDirs.some((dir) => fs.existsSync(path.join(dir, packageName, 'package.json')))\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/** 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/**\n * Build a Vite 8 `optimizeDeps.rolldownOptions` patch for a plugin `config()` hook.\n *\n * Returns only what this plugin adds. Vite deep-merges hook results into the\n * user config and concatenates arrays, so echoing existing options back would\n * duplicate them — e.g. vite-plugin-node-polyfills' optimizer banner plugin,\n * which then declares `__buffer_polyfill` twice in every prebundled chunk.\n * Legacy `esbuildOptions.define` is carried into `transform.define` so\n * definitions survive the move off the deprecated key.\n */\nfunction optimizeDepsRolldownPatch(\n existing: OptimizeDepsConfig | undefined,\n patch: {\n define?: Record<string, string>\n alias?: Record<string, string>\n },\n): OptimizeDepsConfig['rolldownOptions'] {\n const define = {\n ...existing?.esbuildOptions?.define,\n ...patch.define,\n }\n const alias = patch.alias ?? {}\n\n return {\n ...(Object.keys(define).length > 0 ? { transform: { define } } : {}),\n ...(Object.keys(alias).length > 0 ? { resolve: { alias } } : {}),\n }\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 ...FRAGILE_RENDERER_OPTIMIZE_INCLUDES,\n ]\n const appRoot = path.resolve(userConfig.root ?? process.cwd())\n const resolvableOptimizeIncludes = [\n ...desiredOptimizeIncludes.filter((dep) => !!resolvePackageFile(dep, 'package.json')),\n ...APP_OPTIONAL_OPTIMIZE_INCLUDES.filter((dep) => isResolvableFromRoot(dep, appRoot)),\n ]\n\n const existingOptimize = userConfig.optimizeDeps\n const debugOptimizeAliases = debugShimOptimizeAliasObject()\n const streamOptimizeAliases = streamShimOptimizeAliasObject()\n\n // Only this plugin's additions: Vite concatenates them onto the user's arrays.\n const optimizeDeps: UserConfig['optimizeDeps'] = {\n 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 ...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: optimizeDepsRolldownPatch(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 return {\n resolve: {\n alias: mergedAlias,\n },\n optimizeDeps: {\n rolldownOptions: optimizeDepsRolldownPatch(undefined, {\n // Later merges overwrite vite-plugin-node-polyfills' serve-time\n // `global: 'global'` define and its bare shim-id aliases.\n define: { global: 'globalThis' },\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 // Must emit absolute shim paths: order \"post\" runs after import-analysis.\n order: 'post',\n handler(code) {\n const rewritten = rewriteBarePolyfillShimImports(code, polyfillShimPaths)\n return rewritten ? { code: rewritten, map: null } : 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,IAAME,IAAOC,EAAc,YAAY,GAAG,GAsDpCC,IAAoD;CACxD,QAAY;CACZ,SAAY;CACZ,QAAY;CACZ,WAAY;CACZ,YAAY;AACd;AAOA,SAASC,EAAwB,GAAsB;CACrD,OAAOC,EACJ,QAAQ,sBAAsB,MAAM,IAAI,OAAOC,EAAE,MAAM,CAAC,CAAC,CACzD,QAAQ,gBAAgB,MAAM,IAAI,OAAOA,EAAE,MAAM,CAAC,CAAC,CACnD,QAAQ,wBAAwB,MAAM,MAAM,IAAI,OAAOA,EAAE,SAAS,CAAC,IAAI,GAAG,CAAC,CAC3E,QAAQ,uBAAuB,MAAM,OAAM,IAAI,OAAOA,EAAE,SAAS,CAAC,IAAI,IAAG,CAAC,CAC1E,QAAQ,uBAAuB,MAAM,MAAM,IAAI,OAAOA,EAAE,SAAS,CAAC,IAAI,GAAG;AAC9E;AAYA,SAASC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I,CAAC5F,EAAG,SAAS,mBAAmB,KAAK,CAACA,EAAG,SAAS,aAAa,KAK/D,CADF,iDAAiD,KAAK1F,CACnD,GACH,OAAO;IAET,IAAMuL,IAAcvL,EAAK,QACvB,oDACA,+BACF;IAIA,OAHIuL,MAAgBvL,IACX,OAEF;KAAE,MAAMuL;KAAa,KAAK;IAAK;GACxC;EAGmD;CAAkB;CAEvE,IAAIxD,GAAsB;EACxB,EAAI,4DAA4D;EAEhE,IAAMyD,IAAkBC,EAAc;GAEpC,SAAS,CAAC,UAAW;GAErB,SAAS;IAAC;IAAQ;IAAU;IAAU;IAAkB;GAAM;GAC9D,SAAS;IACP,QAAQ;IACR,QAAQ;IACR,SAAS;GACX;GACA,iBAAiB;EACnB,CAAC;EACD,AAAI,MAAM,QAAQD,CAAe,IAC/BlC,EAAQ,KAAK,GAAGkC,CAAe,IAE/BlC,EAAQ,KAAKkC,CAAe;CAEhC;CAOA,OAJI,OAAO,KAAK1D,CAAoB,CAAC,CAAC,SAAS,KAC7CwB,EAAQ,KAAKF,CAAqB,GAG7BE;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seedprotocol/vite",
3
- "version": "0.6.10",
3
+ "version": "0.7.1",
4
4
  "description": "Vite plugin for Seed Protocol browser/renderer apps",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -49,7 +49,7 @@
49
49
  "rimraf": "^6.0.1",
50
50
  "typescript": "~5.9.3",
51
51
  "vite": "^8.0.0",
52
- "vitest": "^3.0.0"
52
+ "vitest": "^4.1.11"
53
53
  },
54
54
  "author": "Keith Axline <keith@journodao.xyz>",
55
55
  "license": "MIT",