@seedprotocol/vite 0.7.1 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -5
- package/dist/index.js.map +1 -1
- package/package.json +6 -1
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,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;
|
|
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;AA8lBD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,cAAc,CAAC,OAAO,GAAE,qBAA0B,GAAG,MAAM,EAAE,CAkf5E"}
|
package/dist/index.js
CHANGED
|
@@ -43,7 +43,14 @@ 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 = [
|
|
46
|
+
], h = ["@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk", "@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk > @ethereum-attestation-service/eas-contracts"], g = [
|
|
47
|
+
"kerium",
|
|
48
|
+
"utilium",
|
|
49
|
+
"memium",
|
|
50
|
+
"readable-stream",
|
|
51
|
+
"viem",
|
|
52
|
+
"isows"
|
|
53
|
+
], _ = ["pluralize"], v = {
|
|
47
54
|
"Cross-Origin-Opener-Policy": "same-origin",
|
|
48
55
|
"Cross-Origin-Embedder-Policy": "credentialless",
|
|
49
56
|
"Cross-Origin-Resource-Policy": "same-origin"
|
|
@@ -351,10 +358,6 @@ function U(e = {}) {
|
|
|
351
358
|
let s = e.resolve ?? {}, c = A(k(s.alias), i), l = [
|
|
352
359
|
"@zenfs/core",
|
|
353
360
|
"@zenfs/dom",
|
|
354
|
-
"kerium",
|
|
355
|
-
"utilium",
|
|
356
|
-
"memium",
|
|
357
|
-
"readable-stream",
|
|
358
361
|
...m
|
|
359
362
|
], 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 = {
|
|
360
363
|
exclude: [
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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 <script type=\"module\"> that imports from '@zenfs/core'/'@zenfs/dom'.\n * Browsers cannot resolve those bare specifiers, so the script fails at runtime unless you use\n * an import map or load ZenFS another way. Prefer false and initialize ZenFS in your entry:\n * import { configure } from '@zenfs/core'; import { IndexedDB } from '@zenfs/dom';\n * await configure({ mounts: { '/': IndexedDB } });\n * @default false\n */\n autoInit?: boolean\n\n /**\n * Enable debug logging.\n * @default false\n */\n debug?: boolean\n\n /**\n * Whether to automatically include vite-plugin-node-polyfills with sensible defaults.\n * The SDK depends on that package and aliases its injected shim imports to absolute\n * paths, so consuming apps do not need to install vite-plugin-node-polyfills themselves.\n * Default include list omits full `stream`/`crypto` polyfills (those pull\n * stream-browserify and break Vite SSR / React Router prerender). A minimal\n * `stream` stub is still aliased so sax/rss-parser do not warn. Use `false`\n * for Framework Mode / prerender.\n * @default true\n */\n includeNodePolyfills?: boolean\n\n /**\n * Cross-origin isolation headers for sqlocal / SharedArrayBuffer / OPFS.\n * Applied in configureServer and configurePreviewServer, including writeHead,\n * because Vite `server.headers` is not copied onto Framework-Mode HTML responses.\n * Set `false` to disable. Pass `{ coop, coep, corp }` to override values.\n * @default true (`COOP: same-origin`, `COEP: credentialless`, `CORP: same-origin`)\n */\n isolationHeaders?: boolean | {\n coop?: string\n coep?: string\n corp?: string\n }\n}\n\n// Node.js globals that are undefined in browsers and will throw at runtime.\n// Keyed by identifier; value is the safe typeof-guard pattern so we can skip those.\nconst BROWSER_DANGEROUS_GLOBALS: Record<string, RegExp> = {\n global: /\\btypeof\\s+global\\b/,\n process: /\\btypeof\\s+process\\b/,\n Buffer: /\\btypeof\\s+Buffer\\b/,\n __dirname: /\\btypeof\\s+__dirname\\b/,\n __filename: /\\btypeof\\s+__filename\\b/,\n}\n\n/**\n * Strip JS string literals, template literals, and comments from source text\n * so that identifier searches don't false-positive on string content.\n * This is intentionally approximate — good enough for a lint-style warning pass.\n */\nfunction stripStringsAndComments(code: string): string {\n return code\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, (m) => ' '.repeat(m.length)) // /* block comments */\n .replace(/\\/\\/[^\\n]*/g, (m) => ' '.repeat(m.length)) // // line comments\n .replace(/`(?:[^`\\\\]|\\\\.)*`/gs, (m) => '`' + ' '.repeat(m.length - 2) + '`') // template literals\n .replace(/\"(?:[^\"\\\\]|\\\\.)*\"/g, (m) => '\"' + ' '.repeat(m.length - 2) + '\"') // double-quoted strings\n .replace(/'(?:[^'\\\\]|\\\\.)*'/g, (m) => \"'\" + ' '.repeat(m.length - 2) + \"'\") // single-quoted strings\n}\n\ninterface GlobalHit {\n global: string\n /** zero-based character offset in the stripped source */\n offset: number\n /** 1-based line number */\n line: number\n /** surrounding raw source for context */\n context: string\n}\n\nfunction findDangerousGlobals(rawCode: string): GlobalHit[] {\n const stripped = stripStringsAndComments(rawCode)\n const hits: GlobalHit[] = []\n\n for (const [name, typeofGuard] of Object.entries(BROWSER_DANGEROUS_GLOBALS)) {\n // Skip globalThis when checking 'global'\n const re = new RegExp(`(?<![.\\\\w$])\\\\b${name}\\\\b(?!This)(?![\\\\w$])`, 'g')\n let m: RegExpExecArray | null\n while ((m = re.exec(stripped)) !== null) {\n const offset = m.index\n // Check for typeof guard in the ~20 chars before the match\n const before = stripped.slice(Math.max(0, offset - 20), offset)\n if (typeofGuard.test(before)) continue\n\n // Compute 1-based line number from raw source (positions are preserved because\n // we replace with equal-length spaces, so offsets are stable)\n const linesBefore = rawCode.slice(0, offset).split('\\n')\n const line = linesBefore.length\n const colOffset = linesBefore.at(-1)?.length ?? 0\n const rawLine = rawCode.split('\\n')[line - 1] ?? ''\n const ctx = rawLine.slice(Math.max(0, colOffset - 40), colOffset + name.length + 40).trim()\n\n hits.push({ global: name, offset, line, context: ctx })\n }\n }\n\n return hits\n}\n\nconst DEFAULT_FS_MODULES = [\n 'fs',\n 'fs/promises',\n 'node:fs',\n 'node:fs/promises',\n]\nconst SDK_DIST_DIR = path.dirname(fileURLToPath(import.meta.url))\nconst ARWEAVE_SHIM_FILE = path.join(SDK_DIST_DIR, 'arweave-default-shim.js')\nconst DEBUG_SHIM_FILE = path.join(SDK_DIST_DIR, 'debug-default-shim.js')\nconst STREAM_SHIM_FILE = path.join(SDK_DIST_DIR, 'stream-default-shim.js')\n\n/** Fragile renderer deps pre-bundled for stable CJS/ESM interop (aligned with permapress). */\nconst FRAGILE_RENDERER_OPTIMIZE_INCLUDES = [\n 'debug',\n 'random',\n 'seedrandom',\n '@georgedoescode/generative-utils',\n 'nanoid-dictionary',\n] as const\n\n/**\n * Always force-include (do not gate on resolvePackageFile): under bun these live nested\n * under @seedprotocol/sdk, and eas-sdk's ESM named-imports CJS eas-contracts. Without\n * prebundling, Vite serves raw /@fs CJS and the browser throws\n * \"does not provide an export named 'EAS__factory'\" during SchemaEncoder encode.\n */\nconst EAS_OPTIMIZE_INCLUDES = [\n '@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk',\n '@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk > @ethereum-attestation-service/eas-contracts',\n] as const\n\n/**\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,EAAqB,GAA8B;CAC1D,IAAMC,IAAWJ,EAAwBK,CAAO,GAC1CC,IAAoB,CAAC;CAE3B,KAAK,IAAM,CAACC,GAAMC,MAAgB,OAAO,QAAQT,CAAyB,GAAG;EAE3E,IAAMU,IAAS,OAAO,kBAAkBF,EAAK,wBAAwB,GAAG,GACpEL;EACJ,QAAQ,IAAIO,EAAG,KAAKL,CAAQ,OAAO,OAAM;GACvC,IAAMM,IAASR,EAAE,OAEXS,IAASP,EAAS,MAAM,KAAK,IAAI,GAAGM,IAAS,EAAE,GAAGA,CAAM;GAC9D,IAAIF,EAAY,KAAKG,CAAM,GAAG;GAI9B,IAAMC,IAAcP,EAAQ,MAAM,GAAGK,CAAM,CAAC,CAAC,MAAM,IAAI,GACjDG,IAAOD,EAAY,QACnBE,IAAYF,EAAY,GAAG,EAAE,CAAC,EAAE,UAAU,GAE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/BlC,EAAQ,KAAKkC,CAAe;CAEhC;CAOA,OAJI,OAAO,KAAK1D,CAAoB,CAAC,CAAC,SAAS,KAC7CwB,EAAQ,KAAKF,CAAqB,GAG7BE;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 <script type=\"module\"> that imports from '@zenfs/core'/'@zenfs/dom'.\n * Browsers cannot resolve those bare specifiers, so the script fails at runtime unless you use\n * an import map or load ZenFS another way. Prefer false and initialize ZenFS in your entry:\n * import { configure } from '@zenfs/core'; import { IndexedDB } from '@zenfs/dom';\n * await configure({ mounts: { '/': IndexedDB } });\n * @default false\n */\n autoInit?: boolean\n\n /**\n * Enable debug logging.\n * @default false\n */\n debug?: boolean\n\n /**\n * Whether to automatically include vite-plugin-node-polyfills with sensible defaults.\n * The SDK depends on that package and aliases its injected shim imports to absolute\n * paths, so consuming apps do not need to install vite-plugin-node-polyfills themselves.\n * Default include list omits full `stream`/`crypto` polyfills (those pull\n * stream-browserify and break Vite SSR / React Router prerender). A minimal\n * `stream` stub is still aliased so sax/rss-parser do not warn. Use `false`\n * for Framework Mode / prerender.\n * @default true\n */\n includeNodePolyfills?: boolean\n\n /**\n * Cross-origin isolation headers for sqlocal / SharedArrayBuffer / OPFS.\n * Applied in configureServer and configurePreviewServer, including writeHead,\n * because Vite `server.headers` is not copied onto Framework-Mode HTML responses.\n * Set `false` to disable. Pass `{ coop, coep, corp }` to override values.\n * @default true (`COOP: same-origin`, `COEP: credentialless`, `CORP: same-origin`)\n */\n isolationHeaders?: boolean | {\n coop?: string\n coep?: string\n corp?: string\n }\n}\n\n// Node.js globals that are undefined in browsers and will throw at runtime.\n// Keyed by identifier; value is the safe typeof-guard pattern so we can skip those.\nconst BROWSER_DANGEROUS_GLOBALS: Record<string, RegExp> = {\n global: /\\btypeof\\s+global\\b/,\n process: /\\btypeof\\s+process\\b/,\n Buffer: /\\btypeof\\s+Buffer\\b/,\n __dirname: /\\btypeof\\s+__dirname\\b/,\n __filename: /\\btypeof\\s+__filename\\b/,\n}\n\n/**\n * Strip JS string literals, template literals, and comments from source text\n * so that identifier searches don't false-positive on string content.\n * This is intentionally approximate — good enough for a lint-style warning pass.\n */\nfunction stripStringsAndComments(code: string): string {\n return code\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, (m) => ' '.repeat(m.length)) // /* block comments */\n .replace(/\\/\\/[^\\n]*/g, (m) => ' '.repeat(m.length)) // // line comments\n .replace(/`(?:[^`\\\\]|\\\\.)*`/gs, (m) => '`' + ' '.repeat(m.length - 2) + '`') // template literals\n .replace(/\"(?:[^\"\\\\]|\\\\.)*\"/g, (m) => '\"' + ' '.repeat(m.length - 2) + '\"') // double-quoted strings\n .replace(/'(?:[^'\\\\]|\\\\.)*'/g, (m) => \"'\" + ' '.repeat(m.length - 2) + \"'\") // single-quoted strings\n}\n\ninterface GlobalHit {\n global: string\n /** zero-based character offset in the stripped source */\n offset: number\n /** 1-based line number */\n line: number\n /** surrounding raw source for context */\n context: string\n}\n\nfunction findDangerousGlobals(rawCode: string): GlobalHit[] {\n const stripped = stripStringsAndComments(rawCode)\n const hits: GlobalHit[] = []\n\n for (const [name, typeofGuard] of Object.entries(BROWSER_DANGEROUS_GLOBALS)) {\n // Skip globalThis when checking 'global'\n const re = new RegExp(`(?<![.\\\\w$])\\\\b${name}\\\\b(?!This)(?![\\\\w$])`, 'g')\n let m: RegExpExecArray | null\n while ((m = re.exec(stripped)) !== null) {\n const offset = m.index\n // Check for typeof guard in the ~20 chars before the match\n const before = stripped.slice(Math.max(0, offset - 20), offset)\n if (typeofGuard.test(before)) continue\n\n // Compute 1-based line number from raw source (positions are preserved because\n // we replace with equal-length spaces, so offsets are stable)\n const linesBefore = rawCode.slice(0, offset).split('\\n')\n const line = linesBefore.length\n const colOffset = linesBefore.at(-1)?.length ?? 0\n const rawLine = rawCode.split('\\n')[line - 1] ?? ''\n const ctx = rawLine.slice(Math.max(0, colOffset - 40), colOffset + name.length + 40).trim()\n\n hits.push({ global: name, offset, line, context: ctx })\n }\n }\n\n return hits\n}\n\nconst DEFAULT_FS_MODULES = [\n 'fs',\n 'fs/promises',\n 'node:fs',\n 'node:fs/promises',\n]\nconst SDK_DIST_DIR = path.dirname(fileURLToPath(import.meta.url))\nconst ARWEAVE_SHIM_FILE = path.join(SDK_DIST_DIR, 'arweave-default-shim.js')\nconst DEBUG_SHIM_FILE = path.join(SDK_DIST_DIR, 'debug-default-shim.js')\nconst STREAM_SHIM_FILE = path.join(SDK_DIST_DIR, 'stream-default-shim.js')\n\n/** Fragile renderer deps pre-bundled for stable CJS/ESM interop (aligned with permapress). */\nconst FRAGILE_RENDERER_OPTIMIZE_INCLUDES = [\n 'debug',\n 'random',\n 'seedrandom',\n '@georgedoescode/generative-utils',\n 'nanoid-dictionary',\n] as const\n\n/**\n * Always force-include (do not gate on resolvePackageFile): under bun these live nested\n * under @seedprotocol/sdk, and eas-sdk's ESM named-imports CJS eas-contracts. Without\n * prebundling, Vite serves raw /@fs CJS and the browser throws\n * \"does not provide an export named 'EAS__factory'\" during SchemaEncoder encode.\n */\nconst EAS_OPTIMIZE_INCLUDES = [\n '@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk',\n '@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk > @ethereum-attestation-service/eas-contracts',\n] as const\n\n/**\n * Prebundled only when the app itself can resolve them. Vite resolves `include`\n * entries from the app root, so finding them under a linked SDK is not enough\n * (Vite would skip them with \"Failed to resolve dependency\"). The zenfs helpers\n * are bundled into the @zenfs chunks anyway; viem/isows come from\n * @seedprotocol/publish, not the SDK.\n */\nconst APP_OPTIONAL_OPTIMIZE_INCLUDES = [\n 'kerium',\n 'utilium',\n 'memium',\n 'readable-stream',\n 'viem',\n 'isows',\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\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 ...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,EAAqB,GAA8B;CAC1D,IAAMC,IAAWJ,EAAwBK,CAAO,GAC1CC,IAAoB,CAAC;CAE3B,KAAK,IAAM,CAACC,GAAMC,MAAgB,OAAO,QAAQT,CAAyB,GAAG;EAE3E,IAAMU,IAAS,OAAO,kBAAkBF,EAAK,wBAAwB,GAAG,GACpEL;EACJ,QAAQ,IAAIO,EAAG,KAAKL,CAAQ,OAAO,OAAM;GACvC,IAAMM,IAASR,EAAE,OAEXS,IAASP,EAAS,MAAM,KAAK,IAAI,GAAGM,IAAS,EAAE,GAAGA,CAAM;GAC9D,IAAIF,EAAY,K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kB;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.7.
|
|
3
|
+
"version": "0.7.2",
|
|
4
4
|
"description": "Vite plugin for Seed Protocol browser/renderer apps",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -53,6 +53,11 @@
|
|
|
53
53
|
},
|
|
54
54
|
"author": "Keith Axline <keith@journodao.xyz>",
|
|
55
55
|
"license": "MIT",
|
|
56
|
+
"repository": {
|
|
57
|
+
"type": "git",
|
|
58
|
+
"url": "git+https://github.com/JournoLabs/seed-protocol-sdk.git",
|
|
59
|
+
"directory": "packages/vite"
|
|
60
|
+
},
|
|
56
61
|
"publishConfig": {
|
|
57
62
|
"access": "public"
|
|
58
63
|
}
|