@seedprotocol/sdk 0.4.29 → 0.4.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ArweaveClient-BeW65rGS.js → ArweaveClient-CZpZgmR2.js} +3 -3
- package/dist/{ArweaveClient-BeW65rGS.js.map → ArweaveClient-CZpZgmR2.js.map} +1 -1
- package/dist/{ArweaveClient-lm4d-WFB.js → ArweaveClient-Cs7AL9dp.js} +3 -3
- package/dist/{ArweaveClient-lm4d-WFB.js.map → ArweaveClient-Cs7AL9dp.js.map} +1 -1
- package/dist/{Db-VYLhDCFW.js → Db-CF6R7HIy.js} +4 -4
- package/dist/{Db-VYLhDCFW.js.map → Db-CF6R7HIy.js.map} +1 -1
- package/dist/{Db-CbS7T1_D.js → Db-CZkONsdT.js} +4 -4
- package/dist/{Db-CbS7T1_D.js.map → Db-CZkONsdT.js.map} +1 -1
- package/dist/{EasClient-BsdrEbha.js → EasClient-PXOzSzPG.js} +2 -2
- package/dist/{EasClient-McZ-yLnh.js.map → EasClient-PXOzSzPG.js.map} +1 -1
- package/dist/{EasClient-McZ-yLnh.js → EasClient-qfTiM2we.js} +2 -2
- package/dist/{EasClient-BsdrEbha.js.map → EasClient-qfTiM2we.js.map} +1 -1
- package/dist/{FileManager-8X0RFG8j.js → FileManager-5GkHtxF7.js} +2 -2
- package/dist/{FileManager-8X0RFG8j.js.map → FileManager-5GkHtxF7.js.map} +1 -1
- package/dist/{FileManager-wXAlwkmU.js → FileManager-jORQ8Bb6.js} +5 -5
- package/dist/FileManager-jORQ8Bb6.js.map +1 -0
- package/dist/{ModelProperty-e1IIoSSC.js → ModelProperty-e_hXSFvf.js} +17 -17
- package/dist/{ModelProperty-e1IIoSSC.js.map → ModelProperty-e_hXSFvf.js.map} +1 -1
- package/dist/{PathResolver-CCuiAvIu.js → PathResolver-B4_X69Rd.js} +2 -2
- package/dist/{PathResolver-CCuiAvIu.js.map → PathResolver-B4_X69Rd.js.map} +1 -1
- package/dist/{PathResolver-C_AdI9lp.js → PathResolver-Dz0RVGIz.js} +2 -2
- package/dist/{PathResolver-C_AdI9lp.js.map → PathResolver-Dz0RVGIz.js.map} +1 -1
- package/dist/{QueryClient-BCuLIB8_.js → QueryClient-CXHZ239d.js} +2 -2
- package/dist/{QueryClient-BCuLIB8_.js.map → QueryClient-CXHZ239d.js.map} +1 -1
- package/dist/{QueryClient-F2a7YH_K.js → QueryClient-D_UK4YLm.js} +2 -2
- package/dist/{QueryClient-F2a7YH_K.js.map → QueryClient-D_UK4YLm.js.map} +1 -1
- package/dist/{Schema-3_R_m7fn.js → Schema-DonRkUOJ.js} +22 -22
- package/dist/{Schema-3_R_m7fn.js.map → Schema-DonRkUOJ.js.map} +1 -1
- package/dist/{SchemaValidationService-BAPhc_z8.js → SchemaValidationService-DcmfhQae.js} +2 -2
- package/dist/{SchemaValidationService-BAPhc_z8.js.map → SchemaValidationService-DcmfhQae.js.map} +1 -1
- package/dist/{backfillMetadataPropertyIds-pnhgDwmf.js → backfillMetadataPropertyIds-CKTfvFgQ.js} +2 -2
- package/dist/{backfillMetadataPropertyIds-pnhgDwmf.js.map → backfillMetadataPropertyIds-CKTfvFgQ.js.map} +1 -1
- package/dist/cjs/{ModelProperty-B_wtA6Tp.js → ModelProperty-BQYU5hPQ.js} +17 -17
- package/dist/cjs/{ModelProperty-B_wtA6Tp.js.map → ModelProperty-BQYU5hPQ.js.map} +1 -1
- package/dist/cjs/{Schema-DycmdXix.js → Schema-BcRHcQ0W.js} +20 -20
- package/dist/cjs/{Schema-DycmdXix.js.map → Schema-BcRHcQ0W.js.map} +1 -1
- package/dist/cjs/{SchemaValidationService-CutWcs3L.js → SchemaValidationService-CQNDgyZl.js} +2 -2
- package/dist/cjs/{SchemaValidationService-CutWcs3L.js.map → SchemaValidationService-CQNDgyZl.js.map} +1 -1
- package/dist/cjs/{backfillMetadataPropertyIds-BtL7WeI5.js → backfillMetadataPropertyIds-Dn4oVmEv.js} +2 -2
- package/dist/cjs/{backfillMetadataPropertyIds-BtL7WeI5.js.map → backfillMetadataPropertyIds-Dn4oVmEv.js.map} +1 -1
- package/dist/cjs/{getItem-B1qXuyLl.js → getItem-DpnPrzl3.js} +2 -2
- package/dist/cjs/{getItem-B1qXuyLl.js.map → getItem-DpnPrzl3.js.map} +1 -1
- package/dist/cjs/{getPublishPayload-DGtDyXfX.js → getPublishPayload-CGKMEL3H.js} +11 -11
- package/dist/cjs/{getPublishPayload-DGtDyXfX.js.map → getPublishPayload-CGKMEL3H.js.map} +1 -1
- package/dist/cjs/{getPublishUploads-BMVJ2gfR.js → getPublishUploads-DeI0f2UN.js} +4 -4
- package/dist/cjs/{getPublishUploads-BMVJ2gfR.js.map → getPublishUploads-DeI0f2UN.js.map} +1 -1
- package/dist/cjs/{getSegmentedItemProperties-V0HYWzgM.js → getSegmentedItemProperties-BgS_FhAx.js} +3 -3
- package/dist/cjs/{getSegmentedItemProperties-V0HYWzgM.js.map → getSegmentedItemProperties-BgS_FhAx.js.map} +1 -1
- package/dist/cjs/{index-Dbu8yrzO.js → index-BnAqr2le.js} +3 -3
- package/dist/cjs/index-BnAqr2le.js.map +1 -0
- package/dist/cjs/{index-C0v35eOT.js → index-ByozbTn_.js} +53 -41
- package/dist/cjs/index-ByozbTn_.js.map +1 -0
- package/dist/cjs/{ownership-BPK6LY7d.js → ownership-CsWuaNfH.js} +2 -2
- package/dist/cjs/{ownership-BPK6LY7d.js.map → ownership-CsWuaNfH.js.map} +1 -1
- package/dist/cjs/{property-Ctv4ZGoa.js → property-CeR45LMx.js} +4 -4
- package/dist/cjs/{property-Ctv4ZGoa.js.map → property-CeR45LMx.js.map} +1 -1
- package/dist/cjs/{syncDbWithEas-DgZ7Acmb.js → syncDbWithEas-CA2Lum5V.js} +5 -5
- package/dist/cjs/{syncDbWithEas-DgZ7Acmb.js.map → syncDbWithEas-CA2Lum5V.js.map} +1 -1
- package/dist/debug-default-shim.js +27 -0
- package/dist/{getItem-2pjRoJa0.js → getItem-GOXWo_Iy.js} +2 -2
- package/dist/{getItem-2pjRoJa0.js.map → getItem-GOXWo_Iy.js.map} +1 -1
- package/dist/{getPublishPayload-BAPoXumQ.js → getPublishPayload-D16enahU.js} +11 -11
- package/dist/{getPublishPayload-BAPoXumQ.js.map → getPublishPayload-D16enahU.js.map} +1 -1
- package/dist/{getPublishUploads-D75w3Et5.js → getPublishUploads-wGqH19UY.js} +4 -4
- package/dist/{getPublishUploads-D75w3Et5.js.map → getPublishUploads-wGqH19UY.js.map} +1 -1
- package/dist/{getSegmentedItemProperties-BLU_UBYI.js → getSegmentedItemProperties-Be3kYWY3.js} +3 -3
- package/dist/{getSegmentedItemProperties-BLU_UBYI.js.map → getSegmentedItemProperties-Be3kYWY3.js.map} +1 -1
- package/dist/{index-CKY29lZp.js → index-BFyMxc7e.js} +2 -2
- package/dist/index-BFyMxc7e.js.map +1 -0
- package/dist/{index-DKXcFcFk.js → index-BcXKZQpX.js} +64 -52
- package/dist/index-BcXKZQpX.js.map +1 -0
- package/dist/{index-CjrqUOwu.js → index-C9p-skT3.js} +3 -3
- package/dist/index-C9p-skT3.js.map +1 -0
- package/dist/main.cjs +1 -1
- package/dist/main.js +13 -13
- package/dist/node.js +10 -10
- package/dist/{ownership-BbSCKuz4.js → ownership-C17YhE7J.js} +2 -2
- package/dist/{ownership-BbSCKuz4.js.map → ownership-C17YhE7J.js.map} +1 -1
- package/dist/{property-D0iZYPNc.js → property-CRAau-Q-.js} +5 -5
- package/dist/{property-D0iZYPNc.js.map → property-CRAau-Q-.js.map} +1 -1
- package/dist/{queries-D4DDYMy9.js → queries-Ct7CcQ3g.js} +2 -2
- package/dist/{queries-D4DDYMy9.js.map → queries-Ct7CcQ3g.js.map} +1 -1
- package/dist/src/ItemProperty/ItemProperty.d.ts.map +1 -1
- package/dist/src/helpers/mediaRef.d.ts.map +1 -1
- package/dist/src/vite/debug-default-shim.d.ts +3 -0
- package/dist/src/vite/debug-default-shim.d.ts.map +1 -0
- package/dist/src/vite/index.d.ts.map +1 -1
- package/dist/{syncDbWithEas-D3gGL9OM.js → syncDbWithEas-CB5aXPtf.js} +6 -6
- package/dist/{syncDbWithEas-D3gGL9OM.js.map → syncDbWithEas-CB5aXPtf.js.map} +1 -1
- package/dist/{updateSeedRevokedAt-DrtFzF85.js → updateSeedRevokedAt-BIu5Q4Po.js} +2 -2
- package/dist/{updateSeedRevokedAt-DrtFzF85.js.map → updateSeedRevokedAt-BIu5Q4Po.js.map} +1 -1
- package/dist/vite.cjs +158 -5
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.js +158 -5
- package/dist/vite.js.map +1 -1
- package/package.json +4 -4
- package/dist/FileManager-wXAlwkmU.js.map +0 -1
- package/dist/cjs/index-C0v35eOT.js.map +0 -1
- package/dist/cjs/index-Dbu8yrzO.js.map +0 -1
- package/dist/index-CKY29lZp.js.map +0 -1
- package/dist/index-CjrqUOwu.js.map +0 -1
- package/dist/index-DKXcFcFk.js.map +0 -1
package/dist/vite.cjs
CHANGED
|
@@ -8,6 +8,53 @@ var vitePluginNodePolyfills = require('vite-plugin-node-polyfills');
|
|
|
8
8
|
|
|
9
9
|
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
10
10
|
const _req = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('vite.cjs', document.baseURI).href)));
|
|
11
|
+
// Node.js globals that are undefined in browsers and will throw at runtime.
|
|
12
|
+
// Keyed by identifier; value is the safe typeof-guard pattern so we can skip those.
|
|
13
|
+
const BROWSER_DANGEROUS_GLOBALS = {
|
|
14
|
+
global: /\btypeof\s+global\b/,
|
|
15
|
+
process: /\btypeof\s+process\b/,
|
|
16
|
+
Buffer: /\btypeof\s+Buffer\b/,
|
|
17
|
+
__dirname: /\btypeof\s+__dirname\b/,
|
|
18
|
+
__filename: /\btypeof\s+__filename\b/,
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Strip JS string literals, template literals, and comments from source text
|
|
22
|
+
* so that identifier searches don't false-positive on string content.
|
|
23
|
+
* This is intentionally approximate — good enough for a lint-style warning pass.
|
|
24
|
+
*/
|
|
25
|
+
function stripStringsAndComments(code) {
|
|
26
|
+
return code
|
|
27
|
+
.replace(/\/\*[\s\S]*?\*\//g, (m) => ' '.repeat(m.length)) // /* block comments */
|
|
28
|
+
.replace(/\/\/[^\n]*/g, (m) => ' '.repeat(m.length)) // // line comments
|
|
29
|
+
.replace(/`(?:[^`\\]|\\.)*`/gs, (m) => '`' + ' '.repeat(m.length - 2) + '`') // template literals
|
|
30
|
+
.replace(/"(?:[^"\\]|\\.)*"/g, (m) => '"' + ' '.repeat(m.length - 2) + '"') // double-quoted strings
|
|
31
|
+
.replace(/'(?:[^'\\]|\\.)*'/g, (m) => "'" + ' '.repeat(m.length - 2) + "'"); // single-quoted strings
|
|
32
|
+
}
|
|
33
|
+
function findDangerousGlobals(rawCode) {
|
|
34
|
+
const stripped = stripStringsAndComments(rawCode);
|
|
35
|
+
const hits = [];
|
|
36
|
+
for (const [name, typeofGuard] of Object.entries(BROWSER_DANGEROUS_GLOBALS)) {
|
|
37
|
+
// Skip globalThis when checking 'global'
|
|
38
|
+
const re = new RegExp(`(?<![.\\w$])\\b${name}\\b(?!This)(?![\\w$])`, 'g');
|
|
39
|
+
let m;
|
|
40
|
+
while ((m = re.exec(stripped)) !== null) {
|
|
41
|
+
const offset = m.index;
|
|
42
|
+
// Check for typeof guard in the ~20 chars before the match
|
|
43
|
+
const before = stripped.slice(Math.max(0, offset - 20), offset);
|
|
44
|
+
if (typeofGuard.test(before))
|
|
45
|
+
continue;
|
|
46
|
+
// Compute 1-based line number from raw source (positions are preserved because
|
|
47
|
+
// we replace with equal-length spaces, so offsets are stable)
|
|
48
|
+
const linesBefore = rawCode.slice(0, offset).split('\n');
|
|
49
|
+
const line = linesBefore.length;
|
|
50
|
+
const colOffset = linesBefore[linesBefore.length - 1].length;
|
|
51
|
+
const rawLine = rawCode.split('\n')[line - 1] ?? '';
|
|
52
|
+
const ctx = rawLine.slice(Math.max(0, colOffset - 40), colOffset + name.length + 40).trim();
|
|
53
|
+
hits.push({ global: name, offset, line, context: ctx });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return hits;
|
|
57
|
+
}
|
|
11
58
|
const DEFAULT_FS_MODULES = [
|
|
12
59
|
'fs',
|
|
13
60
|
'fs/promises',
|
|
@@ -16,6 +63,15 @@ const DEFAULT_FS_MODULES = [
|
|
|
16
63
|
];
|
|
17
64
|
const SDK_DIST_DIR = path.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('vite.cjs', document.baseURI).href))));
|
|
18
65
|
const ARWEAVE_SHIM_FILE = path.join(SDK_DIST_DIR, 'arweave-default-shim.js');
|
|
66
|
+
const DEBUG_SHIM_FILE = path.join(SDK_DIST_DIR, 'debug-default-shim.js');
|
|
67
|
+
/** Fragile renderer deps pre-bundled for stable CJS/ESM interop (aligned with permapress). */
|
|
68
|
+
const FRAGILE_RENDERER_OPTIMIZE_INCLUDES = [
|
|
69
|
+
'debug',
|
|
70
|
+
'random',
|
|
71
|
+
'seedrandom',
|
|
72
|
+
'@georgedoescode/generative-utils',
|
|
73
|
+
'nanoid-dictionary',
|
|
74
|
+
];
|
|
19
75
|
function resolvePackageFile(packageName, relativePath) {
|
|
20
76
|
const candidates = [];
|
|
21
77
|
try {
|
|
@@ -67,6 +123,32 @@ function mergeAliasEntries(existing, additions) {
|
|
|
67
123
|
}
|
|
68
124
|
return merged;
|
|
69
125
|
}
|
|
126
|
+
function addRendererCompatibilityAliases(aliasEntries) {
|
|
127
|
+
const nanoidDictionaryEsm = resolvePackageFile('nanoid-dictionary', 'dist/dictionary.esm.js');
|
|
128
|
+
if (nanoidDictionaryEsm) {
|
|
129
|
+
aliasEntries.push({
|
|
130
|
+
find: /^nanoid-dictionary$/,
|
|
131
|
+
replacement: nanoidDictionaryEsm,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
const zenfsCoreIndex = resolvePackageFile('@zenfs/core', 'dist/index.js');
|
|
135
|
+
const zenfsCorePath = resolvePackageFile('@zenfs/core', 'dist/path.js');
|
|
136
|
+
if (zenfsCoreIndex) {
|
|
137
|
+
aliasEntries.push({ find: /^@zenfs\/core$/, replacement: zenfsCoreIndex });
|
|
138
|
+
}
|
|
139
|
+
if (zenfsCorePath) {
|
|
140
|
+
aliasEntries.push({ find: /^@zenfs\/core\/path$/, replacement: zenfsCorePath });
|
|
141
|
+
}
|
|
142
|
+
const zenfsDomIndex = resolvePackageFile('@zenfs/dom', 'dist/index.js');
|
|
143
|
+
if (zenfsDomIndex) {
|
|
144
|
+
aliasEntries.push({ find: /^@zenfs\/dom$/, replacement: zenfsDomIndex });
|
|
145
|
+
}
|
|
146
|
+
if (fs.existsSync(DEBUG_SHIM_FILE)) {
|
|
147
|
+
// Only alias the package root. Do not alias debug/src/browser.js to this shim:
|
|
148
|
+
// the shim imports that path and aliasing it back creates a circular module.
|
|
149
|
+
aliasEntries.push({ find: /^debug$/, replacement: DEBUG_SHIM_FILE });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
70
152
|
/**
|
|
71
153
|
* Minimal Vite plugin to make the SDK work in browser/Electron renderer:
|
|
72
154
|
* - Aliases fs → @zenfs/core (and promises variant)
|
|
@@ -108,6 +190,7 @@ function seedVitePlugin(options = {}) {
|
|
|
108
190
|
if (arweaveBundle) {
|
|
109
191
|
aliasEntries.push({ find: /^arweave$/, replacement: ARWEAVE_SHIM_FILE }, { find: /^arweave\/web\/index\.js$/, replacement: ARWEAVE_SHIM_FILE }, { find: /^arweave\/bundles\/web\.bundle\.js$/, replacement: arweaveBundle });
|
|
110
192
|
}
|
|
193
|
+
addRendererCompatibilityAliases(aliasEntries);
|
|
111
194
|
const existingResolve = userConfig.resolve ?? {};
|
|
112
195
|
const mergedAlias = mergeAliasEntries(normalizeAliasEntries(existingResolve.alias), aliasEntries);
|
|
113
196
|
const desiredOptimizeIncludes = [
|
|
@@ -119,6 +202,7 @@ function seedVitePlugin(options = {}) {
|
|
|
119
202
|
'readable-stream',
|
|
120
203
|
'viem',
|
|
121
204
|
'isows',
|
|
205
|
+
...FRAGILE_RENDERER_OPTIMIZE_INCLUDES,
|
|
122
206
|
];
|
|
123
207
|
const resolvableOptimizeIncludes = desiredOptimizeIncludes.filter((dep) => !!resolvePackageFile(dep, 'package.json'));
|
|
124
208
|
const optimizeDeps = {
|
|
@@ -155,6 +239,12 @@ function seedVitePlugin(options = {}) {
|
|
|
155
239
|
define: {
|
|
156
240
|
...(userConfig.define ?? {}),
|
|
157
241
|
global: 'globalThis',
|
|
242
|
+
// process is referenced by path-browserify (drizzle migrator's node:path dep)
|
|
243
|
+
// and other CJS modules. Point at globalThis.process which is set by the
|
|
244
|
+
// synchronous inline shim script injected into index.html before any modules load.
|
|
245
|
+
'process.env.NODE_ENV': JSON.stringify('production'),
|
|
246
|
+
'process.browser': 'true',
|
|
247
|
+
'process.platform': '"browser"',
|
|
158
248
|
},
|
|
159
249
|
resolve: {
|
|
160
250
|
...existingResolve,
|
|
@@ -279,9 +369,54 @@ function seedVitePlugin(options = {}) {
|
|
|
279
369
|
worker,
|
|
280
370
|
};
|
|
281
371
|
},
|
|
372
|
+
generateBundle(_options, bundle) {
|
|
373
|
+
const allHits = [];
|
|
374
|
+
for (const [chunkName, asset] of Object.entries(bundle)) {
|
|
375
|
+
if (asset.type !== 'chunk')
|
|
376
|
+
continue;
|
|
377
|
+
const hits = findDangerousGlobals(asset.code);
|
|
378
|
+
for (const hit of hits) {
|
|
379
|
+
allHits.push({ chunk: chunkName, ...hit });
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
if (allHits.length === 0)
|
|
383
|
+
return;
|
|
384
|
+
console.warn('\n[seed-vite-plugin] ⚠️ Bare Node.js globals detected in browser bundle chunks.' +
|
|
385
|
+
' These will throw ReferenceError at runtime unless shimmed.\n');
|
|
386
|
+
const byChunk = new Map();
|
|
387
|
+
for (const hit of allHits) {
|
|
388
|
+
const list = byChunk.get(hit.chunk) ?? [];
|
|
389
|
+
list.push(hit);
|
|
390
|
+
byChunk.set(hit.chunk, list);
|
|
391
|
+
}
|
|
392
|
+
for (const [chunk, hits] of byChunk) {
|
|
393
|
+
console.warn(` ${chunk}`);
|
|
394
|
+
for (const h of hits) {
|
|
395
|
+
console.warn(` line ${h.line}: \`${h.global}\` — ${h.context}`);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
console.warn('');
|
|
399
|
+
},
|
|
282
400
|
transformIndexHtml(html) {
|
|
401
|
+
// Synchronous inline script runs before any <script type="module">, so
|
|
402
|
+
// global and process are guaranteed to exist when CJS wrappers evaluate.
|
|
403
|
+
// vite-plugin-node-polyfills injects polyfills via module imports, which
|
|
404
|
+
// resolve too late for @rollup/plugin-commonjs-generated wrapper code.
|
|
405
|
+
const shimScript = `<script>
|
|
406
|
+
(function(){
|
|
407
|
+
if(typeof globalThis.global==='undefined')globalThis.global=globalThis;
|
|
408
|
+
if(typeof globalThis.process==='undefined')globalThis.process={env:{NODE_ENV:'production'},browser:true,version:'v18.0.0',versions:{},platform:'browser',cwd:function(){return'/'},nextTick:function(fn){setTimeout(fn,0)}};
|
|
409
|
+
})();
|
|
410
|
+
</script>`;
|
|
411
|
+
let result = html;
|
|
412
|
+
if (result.includes('<head>')) {
|
|
413
|
+
result = result.replace('<head>', `<head>\n${shimScript}`);
|
|
414
|
+
}
|
|
415
|
+
else {
|
|
416
|
+
result = shimScript + result;
|
|
417
|
+
}
|
|
283
418
|
if (!autoInit)
|
|
284
|
-
return
|
|
419
|
+
return result;
|
|
285
420
|
const initScript = `
|
|
286
421
|
<script type="module">
|
|
287
422
|
import { configure } from '@zenfs/core';
|
|
@@ -295,13 +430,31 @@ if (!window.__seedFsReady) {
|
|
|
295
430
|
});
|
|
296
431
|
}
|
|
297
432
|
</script>`;
|
|
298
|
-
if (
|
|
299
|
-
return
|
|
433
|
+
if (result.includes('</head>')) {
|
|
434
|
+
return result.replace('</head>', `${initScript}\n</head>`);
|
|
435
|
+
}
|
|
436
|
+
return result + initScript;
|
|
437
|
+
},
|
|
438
|
+
};
|
|
439
|
+
const sdkImportFixPlugin = {
|
|
440
|
+
name: 'seed-protocol:sdk-import-fix',
|
|
441
|
+
enforce: 'post',
|
|
442
|
+
transform(code, id) {
|
|
443
|
+
if (!id.includes('@seedprotocol/sdk') || !id.includes('FileManager')) {
|
|
444
|
+
return null;
|
|
445
|
+
}
|
|
446
|
+
const hasDefaultPathBrowserifyImport = /import\s+path\s+from\s+['"]path-browserify['"]/.test(code);
|
|
447
|
+
if (!hasDefaultPathBrowserifyImport) {
|
|
448
|
+
return null;
|
|
449
|
+
}
|
|
450
|
+
const transformed = code.replace(/import\s+path\s+from\s+['"]path-browserify['"];/g, "import * as path from 'path';");
|
|
451
|
+
if (transformed === code) {
|
|
452
|
+
return null;
|
|
300
453
|
}
|
|
301
|
-
return
|
|
454
|
+
return { code: transformed, map: null };
|
|
302
455
|
},
|
|
303
456
|
};
|
|
304
|
-
const plugins = [configPlugin, mainPlugin];
|
|
457
|
+
const plugins = [configPlugin, mainPlugin, sdkImportFixPlugin];
|
|
305
458
|
if (includeNodePolyfills) {
|
|
306
459
|
plugins.push(vitePluginNodePolyfills.nodePolyfills({
|
|
307
460
|
// Let fs be handled by @zenfs/core instead of polyfills
|
package/dist/vite.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.cjs","sources":["../../src/vite/index.ts"],"sourcesContent":["import type { Plugin, UserConfig } from 'vite'\nimport fs from 'node:fs'\nimport { createRequire } from 'node:module'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { nodePolyfills } from 'vite-plugin-node-polyfills'\n\nconst _req = createRequire(import.meta.url)\n\nexport interface SeedVitePluginOptions {\n /**\n * Additional modules to alias to ZenFS equivalents.\n * @default ['fs', 'fs/promises', 'node:fs', 'node:fs/promises']\n */\n fsModules?: string[]\n\n /**\n * Whether to inject automatic ZenFS initialization script into index.html.\n * When true, injects a <script type=\"module\"> that imports from '@zenfs/core'/'@zenfs/dom'.\n * Browsers cannot resolve those bare specifiers, so the script fails at runtime unless you use\n * an import map or load ZenFS another way. Prefer false and initialize ZenFS in your entry:\n * import { configure } from '@zenfs/core'; import { IndexedDB } from '@zenfs/dom';\n * await configure({ mounts: { '/': IndexedDB } });\n * @default false\n */\n autoInit?: boolean\n\n /**\n * Enable debug logging.\n * @default false\n */\n debug?: boolean\n\n /**\n * Whether to automatically include vite-plugin-node-polyfills with sensible defaults.\n * @default true\n */\n includeNodePolyfills?: boolean\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')\n\ntype AliasEntry = { find: string | RegExp; replacement: string }\n\nfunction resolvePackageFile(packageName: string, relativePath: string): string | undefined {\n const candidates: string[] = []\n\n try {\n const pkgJson = _req.resolve(`${packageName}/package.json`)\n candidates.push(path.join(path.dirname(pkgJson), relativePath))\n } catch {\n // package may be hoisted/unavailable in this graph\n }\n\n const cwdNodeModules = path.join(process.cwd(), 'node_modules')\n candidates.push(path.join(cwdNodeModules, packageName, relativePath))\n\n const bunDir = path.join(cwdNodeModules, '.bun')\n if (fs.existsSync(bunDir)) {\n for (const entry of fs.readdirSync(bunDir)) {\n if (!entry.startsWith(`${packageName}@`)) continue\n candidates.push(path.join(bunDir, entry, `node_modules/${packageName}`, relativePath))\n }\n }\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate\n }\n return undefined\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/**\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 * - 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. drizzle-kit, better-sqlite3) should run in the\n * main process; the renderer should only use browser-safe SDK usage.\n *\n * For the renderer build:\n * - Use the SDK's ESM entry: import from '@seedprotocol/sdk' (resolves to dist/main.js).\n * - When autoInit is false (default), initialize ZenFS in your entry:\n * import { configure } from '@zenfs/core'; import { IndexedDB } from '@zenfs/dom';\n * await configure({ mounts: { '/': IndexedDB } });\n */\nexport function seedVitePlugin(options: SeedVitePluginOptions = {}): Plugin[] {\n const {\n fsModules = DEFAULT_FS_MODULES,\n autoInit = false,\n debug = false,\n includeNodePolyfills = true,\n } = options\n\n const log = (...args: unknown[]) => {\n }\n\n /**\n * Pre-plugin: configure aliases and optimizeDeps.\n */\n const configPlugin: Plugin = {\n name: 'seed-protocol:config',\n enforce: 'pre',\n\n config(userConfig) {\n const aliasEntries: AliasEntry[] = []\n for (const mod of fsModules) {\n const isPromises = mod.includes('promises')\n const target = isPromises ? '@zenfs/core/promises' : '@zenfs/core'\n aliasEntries.push({ find: mod, replacement: target })\n }\n\n const eventEmitterEsm = resolvePackageFile('eventemitter3', 'dist/eventemitter3.esm.js')\n if (eventEmitterEsm) {\n aliasEntries.push(\n { find: 'eventemitter3', replacement: eventEmitterEsm },\n { find: 'eventemitter3/index.mjs', replacement: eventEmitterEsm },\n { find: 'eventemitter3/index.js', replacement: eventEmitterEsm },\n )\n }\n\n const arweaveBundle = resolvePackageFile('arweave', 'bundles/web.bundle.js')\n if (arweaveBundle) {\n aliasEntries.push(\n { find: /^arweave$/, replacement: ARWEAVE_SHIM_FILE },\n { find: /^arweave\\/web\\/index\\.js$/, replacement: ARWEAVE_SHIM_FILE },\n { find: /^arweave\\/bundles\\/web\\.bundle\\.js$/, replacement: arweaveBundle },\n )\n }\n\n 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 ]\n const resolvableOptimizeIncludes = desiredOptimizeIncludes.filter(\n (dep) => !!resolvePackageFile(dep, 'package.json')\n )\n\n const optimizeDeps: UserConfig['optimizeDeps'] = {\n ...(userConfig.optimizeDeps ?? {}),\n exclude: [\n ...(userConfig.optimizeDeps?.exclude ?? []),\n // Do not prebundle the SDK itself or clearly node-only tools\n '@seedprotocol/sdk',\n 'drizzle-kit',\n 'drizzle-orm',\n 'better-sqlite3',\n // sqlocal uses workers and should not be prebundled\n 'sqlocal',\n ],\n include: [\n ...(userConfig.optimizeDeps?.include ?? []),\n ...resolvableOptimizeIncludes,\n ],\n // Keep `global` shim in optimizer esbuild options; top-level Vite `define`\n // can be rejected by Rolldown in some consumer setups.\n esbuildOptions: {\n ...(userConfig.optimizeDeps?.esbuildOptions ?? {}),\n define: {\n ...(userConfig.optimizeDeps?.esbuildOptions?.define ?? {}),\n global: 'globalThis',\n },\n },\n }\n\n return {\n // Apply global → globalThis for Rollup production builds too.\n // optimizeDeps.esbuildOptions.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 },\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.PlatformClass / Db.appDb on different module instances\n // (\"App DB not found\", undefined.$with on PostsPage).\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 ])\n ),\n },\n optimizeDeps,\n }\n },\n }\n\n /**\n * Post-plugin: build configuration + optional ZenFS init.\n */\n const mainPlugin: Plugin = {\n name: 'seed-protocol:main',\n enforce: 'post',\n\n config(userConfig) {\n const existingBuild = userConfig.build ?? {}\n const existingCommonjs = existingBuild.commonjsOptions ?? {}\n const existingRollupOptions = existingBuild.rollupOptions ?? {}\n const existingRolldownOptions = (existingBuild as Record<string, unknown>).rolldownOptions as\n | Record<string, unknown>\n | undefined\n const existingExternal = existingRollupOptions.external ?? []\n\n const include = [\n // Anything the user already had\n ...(Array.isArray(existingCommonjs.include)\n ? existingCommonjs.include\n : existingCommonjs.include\n ? [existingCommonjs.include]\n : []),\n // Always process node_modules and the SDK dist so require() is transformed\n /node_modules/,\n /seed-protocol-sdk[\\\\/]+dist[\\\\/]/,\n ]\n\n // Exclude packages that are already ESM or have special worker handling\n const exclude = [\n ...(Array.isArray(existingCommonjs.exclude)\n ? existingCommonjs.exclude\n : existingCommonjs.exclude\n ? [existingCommonjs.exclude]\n : []),\n // sqlocal is ESM and uses workers - don't transform it\n /node_modules[\\\\/]+sqlocal[\\\\/]/,\n ]\n\n const commonjsOptions = {\n ...existingCommonjs,\n include,\n exclude,\n transformMixedEsModules: true,\n }\n\n // Externalize Node.js-only dev/build tools that should never be bundled\n const nodeOnlyPackages = [\n 'drizzle-kit',\n 'better-sqlite3', // Native SQLite binding (Node.js only)\n // Database drivers that drizzle-kit dynamically imports (should not be bundled)\n '@electric-sql/pglite',\n 'pg',\n 'postgres',\n '@vercel/postgres',\n '@neondatabase/serverless',\n 'mysql2',\n 'mysql2/promise',\n '@planetscale/database',\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 transformIndexHtml(html) {\n if (!autoInit) return html\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 (html.includes('</head>')) {\n return html.replace('</head>', `${initScript}\\n</head>`)\n }\n\n return html + initScript\n },\n }\n\n const plugins: Plugin[] = [configPlugin, mainPlugin]\n\n if (includeNodePolyfills) {\n log('Including vite-plugin-node-polyfills with default settings')\n plugins.push(\n nodePolyfills({\n // Let fs be handled by @zenfs/core instead of polyfills\n exclude: ['readline',],\n // Common set of browser-friendly polyfills used by many deps\n include: ['path', 'crypto', 'stream', 'util', 'buffer', 'events', 'string_decoder',],\n globals: {\n Buffer: true,\n global: true,\n process: true,\n },\n protocolImports: true,\n }) as unknown as Plugin,\n )\n }\n\n return plugins\n}\n"],"names":["createRequire","fileURLToPath","nodePolyfills"],"mappings":";;;;;;;;;AAOA,MAAM,IAAI,GAAGA,yBAAa,CAAC,0PAAe,CAAC;AAiC3C,MAAM,kBAAkB,GAAG;IACzB,IAAI;IACJ,aAAa;IACb,SAAS;IACT,kBAAkB;CACnB;AACD,MAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAACC,sBAAa,CAAC,0PAAe,CAAC,CAAC;AACjE,MAAM,iBAAiB,GAAG,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,yBAAyB,CAAC;AAI5E,SAAS,kBAAkB,CAAC,WAAmB,EAAE,YAAoB,EAAA;IACnE,MAAM,UAAU,GAAa,EAAE;AAE/B,IAAA,IAAI;QACF,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,CAAA,EAAG,WAAW,CAAA,aAAA,CAAe,CAAC;AAC3D,QAAA,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,IAA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EA,IAAA,OAAO,OAAO;AAChB;;;;"}
|
|
1
|
+
{"version":3,"file":"vite.cjs","sources":["../../src/vite/index.ts"],"sourcesContent":["import type { Plugin, UserConfig } from 'vite'\nimport fs from 'node:fs'\nimport { createRequire } from 'node:module'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { nodePolyfills } from 'vite-plugin-node-polyfills'\n\nconst _req = createRequire(import.meta.url)\n\nexport interface SeedVitePluginOptions {\n /**\n * Additional modules to alias to ZenFS equivalents.\n * @default ['fs', 'fs/promises', 'node:fs', 'node:fs/promises']\n */\n fsModules?: string[]\n\n /**\n * Whether to inject automatic ZenFS initialization script into index.html.\n * When true, injects a <script type=\"module\"> that imports from '@zenfs/core'/'@zenfs/dom'.\n * Browsers cannot resolve those bare specifiers, so the script fails at runtime unless you use\n * an import map or load ZenFS another way. Prefer false and initialize ZenFS in your entry:\n * import { configure } from '@zenfs/core'; import { IndexedDB } from '@zenfs/dom';\n * await configure({ mounts: { '/': IndexedDB } });\n * @default false\n */\n autoInit?: boolean\n\n /**\n * Enable debug logging.\n * @default false\n */\n debug?: boolean\n\n /**\n * Whether to automatically include vite-plugin-node-polyfills with sensible defaults.\n * @default true\n */\n includeNodePolyfills?: boolean\n}\n\n// Node.js globals that are undefined in browsers and will throw at runtime.\n// Keyed by identifier; value is the safe typeof-guard pattern so we can skip those.\nconst BROWSER_DANGEROUS_GLOBALS: Record<string, RegExp> = {\n global: /\\btypeof\\s+global\\b/,\n process: /\\btypeof\\s+process\\b/,\n Buffer: /\\btypeof\\s+Buffer\\b/,\n __dirname: /\\btypeof\\s+__dirname\\b/,\n __filename: /\\btypeof\\s+__filename\\b/,\n}\n\n/**\n * Strip JS string literals, template literals, and comments from source text\n * so that identifier searches don't false-positive on string content.\n * This is intentionally approximate — good enough for a lint-style warning pass.\n */\nfunction stripStringsAndComments(code: string): string {\n return code\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, (m) => ' '.repeat(m.length)) // /* block comments */\n .replace(/\\/\\/[^\\n]*/g, (m) => ' '.repeat(m.length)) // // line comments\n .replace(/`(?:[^`\\\\]|\\\\.)*`/gs, (m) => '`' + ' '.repeat(m.length - 2) + '`') // template literals\n .replace(/\"(?:[^\"\\\\]|\\\\.)*\"/g, (m) => '\"' + ' '.repeat(m.length - 2) + '\"') // double-quoted strings\n .replace(/'(?:[^'\\\\]|\\\\.)*'/g, (m) => \"'\" + ' '.repeat(m.length - 2) + \"'\") // single-quoted strings\n}\n\ninterface GlobalHit {\n global: string\n /** zero-based character offset in the stripped source */\n offset: number\n /** 1-based line number */\n line: number\n /** surrounding raw source for context */\n context: string\n}\n\nfunction findDangerousGlobals(rawCode: string): GlobalHit[] {\n const stripped = stripStringsAndComments(rawCode)\n const hits: GlobalHit[] = []\n\n for (const [name, typeofGuard] of Object.entries(BROWSER_DANGEROUS_GLOBALS)) {\n // Skip globalThis when checking 'global'\n const re = new RegExp(`(?<![.\\\\w$])\\\\b${name}\\\\b(?!This)(?![\\\\w$])`, 'g')\n let m: RegExpExecArray | null\n while ((m = re.exec(stripped)) !== null) {\n const offset = m.index\n // Check for typeof guard in the ~20 chars before the match\n const before = stripped.slice(Math.max(0, offset - 20), offset)\n if (typeofGuard.test(before)) continue\n\n // Compute 1-based line number from raw source (positions are preserved because\n // we replace with equal-length spaces, so offsets are stable)\n const linesBefore = rawCode.slice(0, offset).split('\\n')\n const line = linesBefore.length\n const colOffset = linesBefore[linesBefore.length - 1].length\n const rawLine = rawCode.split('\\n')[line - 1] ?? ''\n const ctx = rawLine.slice(Math.max(0, colOffset - 40), colOffset + name.length + 40).trim()\n\n hits.push({ global: name, offset, line, context: ctx })\n }\n }\n\n return hits\n}\n\nconst DEFAULT_FS_MODULES = [\n 'fs',\n 'fs/promises',\n 'node:fs',\n 'node:fs/promises',\n]\nconst SDK_DIST_DIR = path.dirname(fileURLToPath(import.meta.url))\nconst ARWEAVE_SHIM_FILE = path.join(SDK_DIST_DIR, 'arweave-default-shim.js')\nconst DEBUG_SHIM_FILE = path.join(SDK_DIST_DIR, 'debug-default-shim.js')\n\n/** Fragile renderer deps pre-bundled for stable CJS/ESM interop (aligned with permapress). */\nconst FRAGILE_RENDERER_OPTIMIZE_INCLUDES = [\n 'debug',\n 'random',\n 'seedrandom',\n '@georgedoescode/generative-utils',\n 'nanoid-dictionary',\n] as const\n\ntype AliasEntry = { find: string | RegExp; replacement: string }\n\nfunction resolvePackageFile(packageName: string, relativePath: string): string | undefined {\n const candidates: string[] = []\n\n try {\n const pkgJson = _req.resolve(`${packageName}/package.json`)\n candidates.push(path.join(path.dirname(pkgJson), relativePath))\n } catch {\n // package may be hoisted/unavailable in this graph\n }\n\n const cwdNodeModules = path.join(process.cwd(), 'node_modules')\n candidates.push(path.join(cwdNodeModules, packageName, relativePath))\n\n const bunDir = path.join(cwdNodeModules, '.bun')\n if (fs.existsSync(bunDir)) {\n for (const entry of fs.readdirSync(bunDir)) {\n if (!entry.startsWith(`${packageName}@`)) continue\n candidates.push(path.join(bunDir, entry, `node_modules/${packageName}`, relativePath))\n }\n }\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate\n }\n return undefined\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\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\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 * - 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. drizzle-kit, better-sqlite3) should run in the\n * main process; the renderer should only use browser-safe SDK usage.\n *\n * For the renderer build:\n * - Use the SDK's ESM entry: import from '@seedprotocol/sdk' (resolves to dist/main.js).\n * - When autoInit is false (default), initialize ZenFS in your entry:\n * import { configure } from '@zenfs/core'; import { IndexedDB } from '@zenfs/dom';\n * await configure({ mounts: { '/': IndexedDB } });\n */\nexport function seedVitePlugin(options: SeedVitePluginOptions = {}): Plugin[] {\n const {\n fsModules = DEFAULT_FS_MODULES,\n autoInit = false,\n debug = false,\n includeNodePolyfills = true,\n } = options\n\n const log = (...args: unknown[]) => {\n }\n\n /**\n * Pre-plugin: configure aliases and optimizeDeps.\n */\n const configPlugin: Plugin = {\n name: 'seed-protocol:config',\n enforce: 'pre',\n\n config(userConfig) {\n const aliasEntries: AliasEntry[] = []\n for (const mod of fsModules) {\n const isPromises = mod.includes('promises')\n const target = isPromises ? '@zenfs/core/promises' : '@zenfs/core'\n aliasEntries.push({ find: mod, replacement: target })\n }\n\n const eventEmitterEsm = resolvePackageFile('eventemitter3', 'dist/eventemitter3.esm.js')\n if (eventEmitterEsm) {\n aliasEntries.push(\n { find: 'eventemitter3', replacement: eventEmitterEsm },\n { find: 'eventemitter3/index.mjs', replacement: eventEmitterEsm },\n { find: 'eventemitter3/index.js', replacement: eventEmitterEsm },\n )\n }\n\n const arweaveBundle = resolvePackageFile('arweave', 'bundles/web.bundle.js')\n if (arweaveBundle) {\n aliasEntries.push(\n { find: /^arweave$/, replacement: ARWEAVE_SHIM_FILE },\n { find: /^arweave\\/web\\/index\\.js$/, replacement: ARWEAVE_SHIM_FILE },\n { find: /^arweave\\/bundles\\/web\\.bundle\\.js$/, replacement: arweaveBundle },\n )\n }\n\n addRendererCompatibilityAliases(aliasEntries)\n\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 optimizeDeps: UserConfig['optimizeDeps'] = {\n ...(userConfig.optimizeDeps ?? {}),\n exclude: [\n ...(userConfig.optimizeDeps?.exclude ?? []),\n // Do not prebundle the SDK itself or clearly node-only tools\n '@seedprotocol/sdk',\n 'drizzle-kit',\n 'drizzle-orm',\n 'better-sqlite3',\n // sqlocal uses workers and should not be prebundled\n 'sqlocal',\n ],\n include: [\n ...(userConfig.optimizeDeps?.include ?? []),\n ...resolvableOptimizeIncludes,\n ],\n // Keep `global` shim in optimizer esbuild options; top-level Vite `define`\n // can be rejected by Rolldown in some consumer setups.\n esbuildOptions: {\n ...(userConfig.optimizeDeps?.esbuildOptions ?? {}),\n define: {\n ...(userConfig.optimizeDeps?.esbuildOptions?.define ?? {}),\n global: 'globalThis',\n },\n },\n }\n\n return {\n // Apply global → globalThis for Rollup production builds too.\n // optimizeDeps.esbuildOptions.define only covers the dev pre-bundle step;\n // this top-level define is picked up by @rollup/plugin-replace during build\n // and covers all chunks, including code-split migrator/commonjs-helper chunks.\n define: {\n ...(userConfig.define ?? {}),\n global: 'globalThis',\n // process is referenced by path-browserify (drizzle migrator's node:path dep)\n // and other CJS modules. Point at globalThis.process which is set by the\n // synchronous inline shim script injected into index.html before any modules load.\n 'process.env.NODE_ENV': JSON.stringify('production'),\n 'process.browser': 'true',\n 'process.platform': '\"browser\"',\n },\n resolve: {\n ...existingResolve,\n alias: mergedAlias,\n // Prevent duplicate React/thirdweb instances when @seedprotocol/publish is workspace-linked.\n // Multiple copies break context (e.g. useActiveAccount must be used within ThirdwebProvider).\n // Also dedupe XState and Seed packages: two xstate copies cause Object.assign _version errors;\n // two @seedprotocol/sdk copies leave BaseDb.PlatformClass / Db.appDb on different module instances\n // (\"App DB not found\", undefined.$with on PostsPage).\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 ])\n ),\n },\n optimizeDeps,\n }\n },\n }\n\n /**\n * Post-plugin: build configuration + optional ZenFS init.\n */\n const mainPlugin: Plugin = {\n name: 'seed-protocol:main',\n enforce: 'post',\n\n config(userConfig) {\n const existingBuild = userConfig.build ?? {}\n const existingCommonjs = existingBuild.commonjsOptions ?? {}\n const existingRollupOptions = existingBuild.rollupOptions ?? {}\n const existingRolldownOptions = (existingBuild as Record<string, unknown>).rolldownOptions as\n | Record<string, unknown>\n | undefined\n const existingExternal = existingRollupOptions.external ?? []\n\n const include = [\n // Anything the user already had\n ...(Array.isArray(existingCommonjs.include)\n ? existingCommonjs.include\n : existingCommonjs.include\n ? [existingCommonjs.include]\n : []),\n // Always process node_modules and the SDK dist so require() is transformed\n /node_modules/,\n /seed-protocol-sdk[\\\\/]+dist[\\\\/]/,\n ]\n\n // Exclude packages that are already ESM or have special worker handling\n const exclude = [\n ...(Array.isArray(existingCommonjs.exclude)\n ? existingCommonjs.exclude\n : existingCommonjs.exclude\n ? [existingCommonjs.exclude]\n : []),\n // sqlocal is ESM and uses workers - don't transform it\n /node_modules[\\\\/]+sqlocal[\\\\/]/,\n ]\n\n const commonjsOptions = {\n ...existingCommonjs,\n include,\n exclude,\n transformMixedEsModules: true,\n }\n\n // Externalize Node.js-only dev/build tools that should never be bundled\n const nodeOnlyPackages = [\n 'drizzle-kit',\n 'better-sqlite3', // Native SQLite binding (Node.js only)\n // Database drivers that drizzle-kit dynamically imports (should not be bundled)\n '@electric-sql/pglite',\n 'pg',\n 'postgres',\n '@vercel/postgres',\n '@neondatabase/serverless',\n 'mysql2',\n 'mysql2/promise',\n '@planetscale/database',\n ]\n\n const isNodeOnlyExternal = (id: string) =>\n nodeOnlyPackages.some(\n (pkg) =>\n id === pkg ||\n id.startsWith(`${pkg}/`) ||\n id.includes(`/${pkg}/`) ||\n id.endsWith(`/${pkg}`)\n )\n\n const externalList = (id: string, importer?: string, isResolved?: boolean) => {\n if (isNodeOnlyExternal(id)) return true\n if (typeof existingExternal === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (existingExternal as any)(id, importer, isResolved ?? false)\n }\n if (Array.isArray(existingExternal)) {\n return existingExternal.some((ext) => ext === id || id.startsWith(`${ext}/`))\n }\n return false\n }\n\n const rollupOptions = {\n ...existingRollupOptions,\n external: externalList,\n }\n\n const build: Record<string, unknown> = {\n ...existingBuild,\n commonjsOptions,\n }\n if (existingRolldownOptions) {\n build.rolldownOptions = {\n ...existingRolldownOptions,\n external: externalList,\n }\n } else {\n build.rollupOptions = rollupOptions\n }\n\n // Worker options are TOP-LEVEL in Vite config, not under build.\n // Default 'iife' breaks when workers use code-splitting (e.g. sqlocal).\n const existingWorker = userConfig.worker ?? {}\n const worker = {\n ...existingWorker,\n format: existingWorker.format ?? 'es',\n }\n\n return {\n build,\n worker,\n }\n },\n\n generateBundle(_options, bundle) {\n const allHits: Array<{ chunk: string } & GlobalHit> = []\n\n for (const [chunkName, asset] of Object.entries(bundle)) {\n if (asset.type !== 'chunk') continue\n const hits = findDangerousGlobals(asset.code)\n for (const hit of hits) {\n allHits.push({ chunk: chunkName, ...hit })\n }\n }\n\n if (allHits.length === 0) return\n\n console.warn(\n '\\n[seed-vite-plugin] ⚠️ Bare Node.js globals detected in browser bundle chunks.' +\n ' These will throw ReferenceError at runtime unless shimmed.\\n'\n )\n const byChunk = new Map<string, typeof allHits>()\n for (const hit of allHits) {\n const list = byChunk.get(hit.chunk) ?? []\n list.push(hit)\n byChunk.set(hit.chunk, list)\n }\n for (const [chunk, hits] of byChunk) {\n console.warn(` ${chunk}`)\n for (const h of hits) {\n console.warn(` line ${h.line}: \\`${h.global}\\` — ${h.context}`)\n }\n }\n console.warn('')\n },\n\n transformIndexHtml(html) {\n // Synchronous inline script runs before any <script type=\"module\">, so\n // global and process are guaranteed to exist when CJS wrappers evaluate.\n // vite-plugin-node-polyfills injects polyfills via module imports, which\n // resolve too late for @rollup/plugin-commonjs-generated wrapper code.\n const shimScript = `<script>\n(function(){\n if(typeof globalThis.global==='undefined')globalThis.global=globalThis;\n if(typeof globalThis.process==='undefined')globalThis.process={env:{NODE_ENV:'production'},browser:true,version:'v18.0.0',versions:{},platform:'browser',cwd:function(){return'/'},nextTick:function(fn){setTimeout(fn,0)}};\n})();\n</script>`\n\n let result = html\n if (result.includes('<head>')) {\n result = result.replace('<head>', `<head>\\n${shimScript}`)\n } else {\n result = shimScript + result\n }\n\n if (!autoInit) return result\n\n const initScript = `\n<script type=\"module\">\nimport { configure } from '@zenfs/core';\nimport { IndexedDB } from '@zenfs/dom';\n\nif (!window.__seedFsReady) {\n window.__seedFsReady = configure({\n mounts: { '/': IndexedDB },\n }).catch((err) => {\n console.error('[seed-vite-plugin] ZenFS initialization failed', err);\n });\n}\n</script>`\n\n if (result.includes('</head>')) {\n return result.replace('</head>', `${initScript}\\n</head>`)\n }\n\n return result + initScript\n },\n }\n\n const sdkImportFixPlugin: Plugin = {\n name: 'seed-protocol:sdk-import-fix',\n enforce: 'post',\n transform(code, id) {\n if (!id.includes('@seedprotocol/sdk') || !id.includes('FileManager')) {\n return null\n }\n const hasDefaultPathBrowserifyImport =\n /import\\s+path\\s+from\\s+['\"]path-browserify['\"]/.test(code)\n if (!hasDefaultPathBrowserifyImport) {\n return null\n }\n const transformed = code.replace(\n /import\\s+path\\s+from\\s+['\"]path-browserify['\"];/g,\n \"import * as path from 'path';\",\n )\n if (transformed === code) {\n return null\n }\n return { code: transformed, map: null }\n },\n }\n\n const plugins: Plugin[] = [configPlugin, mainPlugin, sdkImportFixPlugin]\n\n if (includeNodePolyfills) {\n log('Including vite-plugin-node-polyfills with default settings')\n plugins.push(\n nodePolyfills({\n // Let fs be handled by @zenfs/core instead of polyfills\n exclude: ['readline',],\n // Common set of browser-friendly polyfills used by many deps\n include: ['path', 'crypto', 'stream', 'util', 'buffer', 'events', 'string_decoder',],\n globals: {\n Buffer: true,\n global: true,\n process: true,\n },\n protocolImports: true,\n }) as unknown as Plugin,\n )\n }\n\n return plugins\n}\n"],"names":["createRequire","fileURLToPath","nodePoly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AAC,IAAI,CACVC,qCAAa,CAAC;;YAEZ,OAAO,EAAE,CAAC,UAAU,EAAE;;AAEtB,YAAA,OAAO,EAAE,CAAC,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,gBAAgB,EAAE;AACpF,YAAA,OAAO,EAAE;AACP,gBAAA,MAAM,EAAE,IAAI;AACZ,gBAAA,MAAM,EAAE,IAAI;AACZ,gBAAA,OAAO,EAAE,IAAI;AACd,aAAA;AACD,YAAA,eAAe,EAAE,IAAI;AACtB,SAAA,CAAsB,CACxB;IACH;AAEA,IAAA,OAAO,OAAO;AAChB;;;;"}
|
package/dist/vite.js
CHANGED
|
@@ -5,6 +5,53 @@ import { fileURLToPath } from 'node:url';
|
|
|
5
5
|
import { nodePolyfills } from 'vite-plugin-node-polyfills';
|
|
6
6
|
|
|
7
7
|
const _req = createRequire(import.meta.url);
|
|
8
|
+
// Node.js globals that are undefined in browsers and will throw at runtime.
|
|
9
|
+
// Keyed by identifier; value is the safe typeof-guard pattern so we can skip those.
|
|
10
|
+
const BROWSER_DANGEROUS_GLOBALS = {
|
|
11
|
+
global: /\btypeof\s+global\b/,
|
|
12
|
+
process: /\btypeof\s+process\b/,
|
|
13
|
+
Buffer: /\btypeof\s+Buffer\b/,
|
|
14
|
+
__dirname: /\btypeof\s+__dirname\b/,
|
|
15
|
+
__filename: /\btypeof\s+__filename\b/,
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Strip JS string literals, template literals, and comments from source text
|
|
19
|
+
* so that identifier searches don't false-positive on string content.
|
|
20
|
+
* This is intentionally approximate — good enough for a lint-style warning pass.
|
|
21
|
+
*/
|
|
22
|
+
function stripStringsAndComments(code) {
|
|
23
|
+
return code
|
|
24
|
+
.replace(/\/\*[\s\S]*?\*\//g, (m) => ' '.repeat(m.length)) // /* block comments */
|
|
25
|
+
.replace(/\/\/[^\n]*/g, (m) => ' '.repeat(m.length)) // // line comments
|
|
26
|
+
.replace(/`(?:[^`\\]|\\.)*`/gs, (m) => '`' + ' '.repeat(m.length - 2) + '`') // template literals
|
|
27
|
+
.replace(/"(?:[^"\\]|\\.)*"/g, (m) => '"' + ' '.repeat(m.length - 2) + '"') // double-quoted strings
|
|
28
|
+
.replace(/'(?:[^'\\]|\\.)*'/g, (m) => "'" + ' '.repeat(m.length - 2) + "'"); // single-quoted strings
|
|
29
|
+
}
|
|
30
|
+
function findDangerousGlobals(rawCode) {
|
|
31
|
+
const stripped = stripStringsAndComments(rawCode);
|
|
32
|
+
const hits = [];
|
|
33
|
+
for (const [name, typeofGuard] of Object.entries(BROWSER_DANGEROUS_GLOBALS)) {
|
|
34
|
+
// Skip globalThis when checking 'global'
|
|
35
|
+
const re = new RegExp(`(?<![.\\w$])\\b${name}\\b(?!This)(?![\\w$])`, 'g');
|
|
36
|
+
let m;
|
|
37
|
+
while ((m = re.exec(stripped)) !== null) {
|
|
38
|
+
const offset = m.index;
|
|
39
|
+
// Check for typeof guard in the ~20 chars before the match
|
|
40
|
+
const before = stripped.slice(Math.max(0, offset - 20), offset);
|
|
41
|
+
if (typeofGuard.test(before))
|
|
42
|
+
continue;
|
|
43
|
+
// Compute 1-based line number from raw source (positions are preserved because
|
|
44
|
+
// we replace with equal-length spaces, so offsets are stable)
|
|
45
|
+
const linesBefore = rawCode.slice(0, offset).split('\n');
|
|
46
|
+
const line = linesBefore.length;
|
|
47
|
+
const colOffset = linesBefore[linesBefore.length - 1].length;
|
|
48
|
+
const rawLine = rawCode.split('\n')[line - 1] ?? '';
|
|
49
|
+
const ctx = rawLine.slice(Math.max(0, colOffset - 40), colOffset + name.length + 40).trim();
|
|
50
|
+
hits.push({ global: name, offset, line, context: ctx });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return hits;
|
|
54
|
+
}
|
|
8
55
|
const DEFAULT_FS_MODULES = [
|
|
9
56
|
'fs',
|
|
10
57
|
'fs/promises',
|
|
@@ -13,6 +60,15 @@ const DEFAULT_FS_MODULES = [
|
|
|
13
60
|
];
|
|
14
61
|
const SDK_DIST_DIR = path.dirname(fileURLToPath(import.meta.url));
|
|
15
62
|
const ARWEAVE_SHIM_FILE = path.join(SDK_DIST_DIR, 'arweave-default-shim.js');
|
|
63
|
+
const DEBUG_SHIM_FILE = path.join(SDK_DIST_DIR, 'debug-default-shim.js');
|
|
64
|
+
/** Fragile renderer deps pre-bundled for stable CJS/ESM interop (aligned with permapress). */
|
|
65
|
+
const FRAGILE_RENDERER_OPTIMIZE_INCLUDES = [
|
|
66
|
+
'debug',
|
|
67
|
+
'random',
|
|
68
|
+
'seedrandom',
|
|
69
|
+
'@georgedoescode/generative-utils',
|
|
70
|
+
'nanoid-dictionary',
|
|
71
|
+
];
|
|
16
72
|
function resolvePackageFile(packageName, relativePath) {
|
|
17
73
|
const candidates = [];
|
|
18
74
|
try {
|
|
@@ -64,6 +120,32 @@ function mergeAliasEntries(existing, additions) {
|
|
|
64
120
|
}
|
|
65
121
|
return merged;
|
|
66
122
|
}
|
|
123
|
+
function addRendererCompatibilityAliases(aliasEntries) {
|
|
124
|
+
const nanoidDictionaryEsm = resolvePackageFile('nanoid-dictionary', 'dist/dictionary.esm.js');
|
|
125
|
+
if (nanoidDictionaryEsm) {
|
|
126
|
+
aliasEntries.push({
|
|
127
|
+
find: /^nanoid-dictionary$/,
|
|
128
|
+
replacement: nanoidDictionaryEsm,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
const zenfsCoreIndex = resolvePackageFile('@zenfs/core', 'dist/index.js');
|
|
132
|
+
const zenfsCorePath = resolvePackageFile('@zenfs/core', 'dist/path.js');
|
|
133
|
+
if (zenfsCoreIndex) {
|
|
134
|
+
aliasEntries.push({ find: /^@zenfs\/core$/, replacement: zenfsCoreIndex });
|
|
135
|
+
}
|
|
136
|
+
if (zenfsCorePath) {
|
|
137
|
+
aliasEntries.push({ find: /^@zenfs\/core\/path$/, replacement: zenfsCorePath });
|
|
138
|
+
}
|
|
139
|
+
const zenfsDomIndex = resolvePackageFile('@zenfs/dom', 'dist/index.js');
|
|
140
|
+
if (zenfsDomIndex) {
|
|
141
|
+
aliasEntries.push({ find: /^@zenfs\/dom$/, replacement: zenfsDomIndex });
|
|
142
|
+
}
|
|
143
|
+
if (fs.existsSync(DEBUG_SHIM_FILE)) {
|
|
144
|
+
// Only alias the package root. Do not alias debug/src/browser.js to this shim:
|
|
145
|
+
// the shim imports that path and aliasing it back creates a circular module.
|
|
146
|
+
aliasEntries.push({ find: /^debug$/, replacement: DEBUG_SHIM_FILE });
|
|
147
|
+
}
|
|
148
|
+
}
|
|
67
149
|
/**
|
|
68
150
|
* Minimal Vite plugin to make the SDK work in browser/Electron renderer:
|
|
69
151
|
* - Aliases fs → @zenfs/core (and promises variant)
|
|
@@ -105,6 +187,7 @@ function seedVitePlugin(options = {}) {
|
|
|
105
187
|
if (arweaveBundle) {
|
|
106
188
|
aliasEntries.push({ find: /^arweave$/, replacement: ARWEAVE_SHIM_FILE }, { find: /^arweave\/web\/index\.js$/, replacement: ARWEAVE_SHIM_FILE }, { find: /^arweave\/bundles\/web\.bundle\.js$/, replacement: arweaveBundle });
|
|
107
189
|
}
|
|
190
|
+
addRendererCompatibilityAliases(aliasEntries);
|
|
108
191
|
const existingResolve = userConfig.resolve ?? {};
|
|
109
192
|
const mergedAlias = mergeAliasEntries(normalizeAliasEntries(existingResolve.alias), aliasEntries);
|
|
110
193
|
const desiredOptimizeIncludes = [
|
|
@@ -116,6 +199,7 @@ function seedVitePlugin(options = {}) {
|
|
|
116
199
|
'readable-stream',
|
|
117
200
|
'viem',
|
|
118
201
|
'isows',
|
|
202
|
+
...FRAGILE_RENDERER_OPTIMIZE_INCLUDES,
|
|
119
203
|
];
|
|
120
204
|
const resolvableOptimizeIncludes = desiredOptimizeIncludes.filter((dep) => !!resolvePackageFile(dep, 'package.json'));
|
|
121
205
|
const optimizeDeps = {
|
|
@@ -152,6 +236,12 @@ function seedVitePlugin(options = {}) {
|
|
|
152
236
|
define: {
|
|
153
237
|
...(userConfig.define ?? {}),
|
|
154
238
|
global: 'globalThis',
|
|
239
|
+
// process is referenced by path-browserify (drizzle migrator's node:path dep)
|
|
240
|
+
// and other CJS modules. Point at globalThis.process which is set by the
|
|
241
|
+
// synchronous inline shim script injected into index.html before any modules load.
|
|
242
|
+
'process.env.NODE_ENV': JSON.stringify('production'),
|
|
243
|
+
'process.browser': 'true',
|
|
244
|
+
'process.platform': '"browser"',
|
|
155
245
|
},
|
|
156
246
|
resolve: {
|
|
157
247
|
...existingResolve,
|
|
@@ -276,9 +366,54 @@ function seedVitePlugin(options = {}) {
|
|
|
276
366
|
worker,
|
|
277
367
|
};
|
|
278
368
|
},
|
|
369
|
+
generateBundle(_options, bundle) {
|
|
370
|
+
const allHits = [];
|
|
371
|
+
for (const [chunkName, asset] of Object.entries(bundle)) {
|
|
372
|
+
if (asset.type !== 'chunk')
|
|
373
|
+
continue;
|
|
374
|
+
const hits = findDangerousGlobals(asset.code);
|
|
375
|
+
for (const hit of hits) {
|
|
376
|
+
allHits.push({ chunk: chunkName, ...hit });
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (allHits.length === 0)
|
|
380
|
+
return;
|
|
381
|
+
console.warn('\n[seed-vite-plugin] ⚠️ Bare Node.js globals detected in browser bundle chunks.' +
|
|
382
|
+
' These will throw ReferenceError at runtime unless shimmed.\n');
|
|
383
|
+
const byChunk = new Map();
|
|
384
|
+
for (const hit of allHits) {
|
|
385
|
+
const list = byChunk.get(hit.chunk) ?? [];
|
|
386
|
+
list.push(hit);
|
|
387
|
+
byChunk.set(hit.chunk, list);
|
|
388
|
+
}
|
|
389
|
+
for (const [chunk, hits] of byChunk) {
|
|
390
|
+
console.warn(` ${chunk}`);
|
|
391
|
+
for (const h of hits) {
|
|
392
|
+
console.warn(` line ${h.line}: \`${h.global}\` — ${h.context}`);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
console.warn('');
|
|
396
|
+
},
|
|
279
397
|
transformIndexHtml(html) {
|
|
398
|
+
// Synchronous inline script runs before any <script type="module">, so
|
|
399
|
+
// global and process are guaranteed to exist when CJS wrappers evaluate.
|
|
400
|
+
// vite-plugin-node-polyfills injects polyfills via module imports, which
|
|
401
|
+
// resolve too late for @rollup/plugin-commonjs-generated wrapper code.
|
|
402
|
+
const shimScript = `<script>
|
|
403
|
+
(function(){
|
|
404
|
+
if(typeof globalThis.global==='undefined')globalThis.global=globalThis;
|
|
405
|
+
if(typeof globalThis.process==='undefined')globalThis.process={env:{NODE_ENV:'production'},browser:true,version:'v18.0.0',versions:{},platform:'browser',cwd:function(){return'/'},nextTick:function(fn){setTimeout(fn,0)}};
|
|
406
|
+
})();
|
|
407
|
+
</script>`;
|
|
408
|
+
let result = html;
|
|
409
|
+
if (result.includes('<head>')) {
|
|
410
|
+
result = result.replace('<head>', `<head>\n${shimScript}`);
|
|
411
|
+
}
|
|
412
|
+
else {
|
|
413
|
+
result = shimScript + result;
|
|
414
|
+
}
|
|
280
415
|
if (!autoInit)
|
|
281
|
-
return
|
|
416
|
+
return result;
|
|
282
417
|
const initScript = `
|
|
283
418
|
<script type="module">
|
|
284
419
|
import { configure } from '@zenfs/core';
|
|
@@ -292,13 +427,31 @@ if (!window.__seedFsReady) {
|
|
|
292
427
|
});
|
|
293
428
|
}
|
|
294
429
|
</script>`;
|
|
295
|
-
if (
|
|
296
|
-
return
|
|
430
|
+
if (result.includes('</head>')) {
|
|
431
|
+
return result.replace('</head>', `${initScript}\n</head>`);
|
|
432
|
+
}
|
|
433
|
+
return result + initScript;
|
|
434
|
+
},
|
|
435
|
+
};
|
|
436
|
+
const sdkImportFixPlugin = {
|
|
437
|
+
name: 'seed-protocol:sdk-import-fix',
|
|
438
|
+
enforce: 'post',
|
|
439
|
+
transform(code, id) {
|
|
440
|
+
if (!id.includes('@seedprotocol/sdk') || !id.includes('FileManager')) {
|
|
441
|
+
return null;
|
|
442
|
+
}
|
|
443
|
+
const hasDefaultPathBrowserifyImport = /import\s+path\s+from\s+['"]path-browserify['"]/.test(code);
|
|
444
|
+
if (!hasDefaultPathBrowserifyImport) {
|
|
445
|
+
return null;
|
|
446
|
+
}
|
|
447
|
+
const transformed = code.replace(/import\s+path\s+from\s+['"]path-browserify['"];/g, "import * as path from 'path';");
|
|
448
|
+
if (transformed === code) {
|
|
449
|
+
return null;
|
|
297
450
|
}
|
|
298
|
-
return
|
|
451
|
+
return { code: transformed, map: null };
|
|
299
452
|
},
|
|
300
453
|
};
|
|
301
|
-
const plugins = [configPlugin, mainPlugin];
|
|
454
|
+
const plugins = [configPlugin, mainPlugin, sdkImportFixPlugin];
|
|
302
455
|
if (includeNodePolyfills) {
|
|
303
456
|
plugins.push(nodePolyfills({
|
|
304
457
|
// Let fs be handled by @zenfs/core instead of polyfills
|