{"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport inject from '@rollup/plugin-inject'\nimport stdLibBrowser from 'node-stdlib-browser'\nimport { handleCircularDependancyWarning } from 'node-stdlib-browser/helpers/rollup/plugin'\nimport esbuildPlugin from 'node-stdlib-browser/helpers/esbuild/plugin'\nimport type { Plugin } from 'vite'\n\nexport type BuildTarget = 'build' | 'dev'\nexport type BooleanOrBuildTarget = boolean | BuildTarget\nexport type ModuleName = keyof typeof stdLibBrowser\nexport type ModuleNameWithoutNodePrefix<T = ModuleName> = T extends `node:${infer P}` ? P : never\n\nexport type PolyfillOptions = {\n  /**\n   * Includes specific modules. If empty, includes all modules\n   * @example\n   *\n   * ```ts\n   * nodePolyfills({\n   *   include: ['fs', 'path'],\n   * })\n   * ```\n  */\n  include?: ModuleNameWithoutNodePrefix[],\n  /**\n   * @example\n   *\n   * ```ts\n   * nodePolyfills({\n   *   exclude: ['fs', 'path'],\n   * })\n   * ```\n   */\n  exclude?: ModuleNameWithoutNodePrefix[],\n  /**\n   * Specify whether specific globals should be polyfilled.\n   *\n   * @example\n   *\n   * ```ts\n   * nodePolyfills({\n   *   globals: {\n   *     Buffer: false,\n   *     global: true,\n   *     process: 'build',\n   *   },\n   * })\n   * ```\n   */\n  globals?: {\n    Buffer?: BooleanOrBuildTarget,\n    global?: BooleanOrBuildTarget,\n    process?: BooleanOrBuildTarget,\n  },\n  /**\n   * Specify alternative modules to use in place of the default polyfills.\n   *\n   * @example\n   *\n   * ```ts\n   * nodePolyfills({\n   *   overrides: {\n   *     fs: 'memfs',\n   *   },\n   * })\n   * ```\n   */\n  overrides?: { [Key in ModuleNameWithoutNodePrefix]?: string },\n  /**\n   * Specify whether the Node protocol version of an import (e.g. `node:buffer`) should be polyfilled too.\n   *\n   * @default true\n   */\n  protocolImports?: boolean,\n}\n\nexport type PolyfillOptionsResolved = {\n  include: ModuleNameWithoutNodePrefix[],\n  exclude: ModuleNameWithoutNodePrefix[],\n  globals: {\n    Buffer: BooleanOrBuildTarget,\n    global: BooleanOrBuildTarget,\n    process: BooleanOrBuildTarget,\n  },\n  overrides: { [Key in ModuleNameWithoutNodePrefix]?: string },\n  protocolImports: boolean,\n}\n\nconst isBuildEnabled = (value: BooleanOrBuildTarget) => {\n  if (!value) return false\n  if (value === true) return true\n\n  return value === 'build'\n}\n\nconst isDevEnabled = (value: BooleanOrBuildTarget) => {\n  if (!value) return false\n  if (value === true) return true\n\n  return value === 'dev'\n}\n\nconst isProtocolImport = (name: string) => {\n  return name.startsWith('node:')\n}\n\nconst stripNodePrefix = (name: ModuleName): ModuleNameWithoutNodePrefix => {\n  return name.replace(/^node:/, '') as ModuleNameWithoutNodePrefix\n}\n\n/**\n * Returns a Vite plugin to polyfill Node's Core Modules for browser environments. Supports `node:` protocol imports.\n *\n * @example\n *\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite'\n * import { nodePolyfills } from 'vite-plugin-node-polyfills'\n *\n * export default defineConfig({\n *   plugins: [\n *     nodePolyfills({\n *       // Specific modules that should not be polyfilled.\n *       exclude: [],\n *       // Whether to polyfill specific globals.\n *       globals: {\n *         Buffer: true, // can also be 'build', 'dev', or false\n *         global: true,\n *         process: true,\n *       },\n *       // Whether to polyfill `node:` protocol imports.\n *       protocolImports: true,\n *     }),\n *   ],\n * })\n * ```\n */\nexport const nodePolyfills = (options: PolyfillOptions = {}): Plugin => {\n  const require = createRequire(import.meta.url)\n  const globalShimsPath = require.resolve('@kev1n-peters/vite-plugin-node-polyfills/shims')\n  const globalShimsBannerPath = require.resolve('@kev1n-peters/vite-plugin-node-polyfills/shims/banner')\n  const globalShimsBanner = readFileSync(globalShimsBannerPath, 'utf-8')\n  const optionsResolved: PolyfillOptionsResolved = {\n    include: [],\n    exclude: [],\n    overrides: {},\n    protocolImports: true,\n    ...options,\n    globals: {\n      Buffer: true,\n      global: true,\n      process: true,\n      ...options.globals,\n    },\n  }\n\n  const compareExcludedModuleNames = (moduleName: string, excludedName: string) => {\n    return moduleName === excludedName || moduleName === `node:${excludedName}`\n  }\n\n  const isExcluded = (name: string) => {\n    if (optionsResolved.include.length) {\n      return !optionsResolved.include.some((excludedName) => compareExcludedModuleNames(name, excludedName))\n    }\n    return optionsResolved.exclude.some((excludedName) => compareExcludedModuleNames(name, excludedName))\n  }\n\n  const toOverride = (name: ModuleNameWithoutNodePrefix): string | void => {\n    if (isDevEnabled(optionsResolved.globals.Buffer) && /^buffer$/.test(name)) {\n      return require.resolve('buffer-polyfill')\n    }\n\n    if (name in optionsResolved.overrides) {\n      return optionsResolved.overrides[name]\n    }\n  }\n\n  return {\n    name: 'vite-plugin-node-polyfills',\n    config: (config, env) => {\n      const isDev = env.command === 'serve'\n      const polyfills = (Object.entries(stdLibBrowser) as Array<[ModuleName, string]>).reduce<Record<ModuleName, string>>((included, [name, value]) => {\n        if (!optionsResolved.protocolImports) {\n          if (isProtocolImport(name)) {\n            return included\n          }\n        }\n\n        if (!isExcluded(name)) {\n          included[name] = toOverride(stripNodePrefix(name)) || value\n        }\n\n        return included\n      }, {} as Record<ModuleName, string>)\n\n      return {\n        build: {\n          rollupOptions: {\n            onwarn: (warning, rollupWarn) => {\n              handleCircularDependancyWarning(warning, () => {\n                if (config.build?.rollupOptions?.onwarn) {\n                  return config.build.rollupOptions.onwarn(warning, rollupWarn)\n                }\n\n                rollupWarn(warning)\n              })\n            },\n            plugins: [\n              {\n                ...inject({\n                  // https://github.com/niksy/node-stdlib-browser/blob/3e7cd7f3d115ac5c4593b550e7d8c4a82a0d4ac4/README.md#vite\n                  ...(isBuildEnabled(optionsResolved.globals.Buffer) ? { Buffer: [globalShimsPath, 'Buffer'] } : {}),\n                  ...(isBuildEnabled(optionsResolved.globals.global) ? { global: [globalShimsPath, 'global'] } : {}),\n                  ...(isBuildEnabled(optionsResolved.globals.process) ? { process: [globalShimsPath, 'process'] } : {}),\n                }),\n              },\n            ],\n          },\n        },\n        esbuild: {\n          // In dev, the global polyfills need to be injected as a banner in order for isolated scripts (such as Vue SFCs) to have access to them.\n          banner: isDev ? globalShimsBanner : undefined,\n        },\n        optimizeDeps: {\n          esbuildOptions: {\n            banner: isDev ? { js: globalShimsBanner } : undefined,\n            // https://github.com/niksy/node-stdlib-browser/blob/3e7cd7f3d115ac5c4593b550e7d8c4a82a0d4ac4/README.md?plain=1#L203-L209\n            define: {\n              ...((isDev && isDevEnabled(optionsResolved.globals.Buffer)) ? { Buffer: 'Buffer' } : {}),\n              ...((isDev && isDevEnabled(optionsResolved.globals.global)) ? { global: 'global' } : {}),\n              ...((isDev && isDevEnabled(optionsResolved.globals.process)) ? { process: 'process' } : {}),\n            },\n            inject: [\n              globalShimsPath,\n            ],\n            plugins: [\n              esbuildPlugin(polyfills),\n              // Supress the 'injected path \"...\" cannot be marked as external' error in Vite 4 (emitted by esbuild).\n              // https://github.com/evanw/esbuild/blob/edede3c49ad6adddc6ea5b3c78c6ea7507e03020/internal/bundler/bundler.go#L1469\n              {\n\n                name: 'vite-plugin-node-polyfills-shims-resolver',\n                setup(build) {\n                  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping\n                  const escapedGlobalShimsPath = globalShimsPath.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n                  const globalShimsFilter = new RegExp(`^${escapedGlobalShimsPath}$`)\n\n                  // https://esbuild.github.io/plugins/#on-resolve\n                  build.onResolve({ filter: globalShimsFilter }, () => {\n                    return {\n                      // https://github.com/evanw/esbuild/blob/edede3c49ad6adddc6ea5b3c78c6ea7507e03020/internal/bundler/bundler.go#L1468\n                      external: false,\n                      path: globalShimsPath,\n                    }\n                  })\n                },\n              },\n            ],\n          },\n        },\n        resolve: {\n          // https://github.com/niksy/node-stdlib-browser/blob/3e7cd7f3d115ac5c4593b550e7d8c4a82a0d4ac4/README.md?plain=1#L150\n          alias: {\n            ...polyfills,\n          },\n        },\n      }\n    },\n  }\n}\n"],"names":["isBuildEnabled","value","isDevEnabled","isProtocolImport","name","stripNodePrefix","nodePolyfills","options","require","createRequire","_documentCurrentScript","globalShimsPath","globalShimsBannerPath","globalShimsBanner","readFileSync","optionsResolved","compareExcludedModuleNames","moduleName","excludedName","isExcluded","toOverride","config","env","isDev","polyfills","stdLibBrowser","included","warning","rollupWarn","handleCircularDependancyWarning","inject","esbuildPlugin","build","escapedGlobalShimsPath","globalShimsFilter"],"mappings":"2aAyFMA,EAAkBC,GACjBA,EACDA,IAAU,GAAa,GAEpBA,IAAU,QAHE,GAMfC,EAAgBD,GACfA,EACDA,IAAU,GAAa,GAEpBA,IAAU,MAHE,GAMfE,EAAoBC,GACjBA,EAAK,WAAW,OAAO,EAG1BC,EAAmBD,GAChBA,EAAK,QAAQ,SAAU,EAAE,EA+BrBE,EAAgB,CAACC,EAA2B,KAAe,CAChE,MAAAC,EAAUC,gBAAc,OAAA,SAAA,IAAA,QAAA,KAAA,EAAA,cAAA,UAAA,EAAA,KAAAC,GAAAA,EAAA,KAAA,IAAA,IAAA,YAAA,SAAA,OAAA,EAAA,IAAe,EACvCC,EAAkBH,EAAQ,QAAQ,gDAAgD,EAClFI,EAAwBJ,EAAQ,QAAQ,uDAAuD,EAC/FK,EAAoBC,EAAAA,aAAaF,EAAuB,OAAO,EAC/DG,EAA2C,CAC/C,QAAS,CAAC,EACV,QAAS,CAAC,EACV,UAAW,CAAC,EACZ,gBAAiB,GACjB,GAAGR,EACH,QAAS,CACP,OAAQ,GACR,OAAQ,GACR,QAAS,GACT,GAAGA,EAAQ,OACb,CAAA,EAGIS,EAA6B,CAACC,EAAoBC,IAC/CD,IAAeC,GAAgBD,IAAe,QAAQC,CAAY,GAGrEC,EAAcf,GACdW,EAAgB,QAAQ,OACnB,CAACA,EAAgB,QAAQ,KAAMG,GAAiBF,EAA2BZ,EAAMc,CAAY,CAAC,EAEhGH,EAAgB,QAAQ,KAAMG,GAAiBF,EAA2BZ,EAAMc,CAAY,CAAC,EAGhGE,EAAchB,GAAqD,C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