@varlock/nextjs-integration 0.3.2 → 0.3.3
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/next-env-compat.js +2 -1
- package/dist/next-env-compat.js.map +1 -1
- package/dist/plugin.js +1 -0
- package/dist/plugin.js.map +1 -1
- package/package.json +5 -4
package/dist/next-env-compat.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
var fs = require('fs');
|
|
4
4
|
var path = require('path');
|
|
5
|
+
require('varlock');
|
|
5
6
|
var env = require('varlock/env');
|
|
6
7
|
var patchConsole = require('varlock/patch-console');
|
|
7
8
|
var execSyncVarlock = require('varlock/exec-sync-varlock');
|
|
@@ -36,7 +37,7 @@ var parsedEnv;
|
|
|
36
37
|
var loadedEnvFiles = [];
|
|
37
38
|
var rootDir;
|
|
38
39
|
function getVarlockSourcesAsLoadedEnvFiles() {
|
|
39
|
-
const envFilesLabels = varlockLoadedEnv.sources.filter((s) => s.enabled &&
|
|
40
|
+
const envFilesLabels = varlockLoadedEnv.sources.filter((s) => s.enabled && s.type !== "container" && s.type !== "import-alias").map((s) => s.label);
|
|
40
41
|
if (envFilesLabels.length) {
|
|
41
42
|
envFilesLabels.push("\n \u2728 loaded by varlock \u2728");
|
|
42
43
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/next-env-compat.ts"],"names":["initialEnv","path","fs","resetRedactionMap","patchGlobalConsole","execSyncVarlock","initVarlockEnv"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBWA;AAEX,IAAI,YAAA;AAEJ,IAAI,gBAAA;AACJ,IAAI,WAAA;AACJ,IAAI,SAAA;AAEJ,IAAI,iBAAiC,EAAC;AACtC,IAAI,OAAA;AAIJ,SAAS,iCAAA,GAAoD;AAC3D,EAAA,MAAM,iBAAiB,gBAAA,CAAiB,OAAA,CAGrC,OAAO,CAAC,CAAA,KAAM,EAA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CAAU,OAAO,IAAI,QAAA,CAAS,KAAA;AAAA,EAChC;AACA,EAAA,KAAA,CAAM,eAAe,SAAS,CAAA;AAC9B,EAAA,OAAA,CAAQ,GAAA,CAAI,aAAA,GAAgB,IAAA,CAAK,SAAA,CAAU,gBAAgB,CAAA;AAC3D,EAAAC,kBAAA,EAAe;AAEf,EAAAH,qBAAA,CAAkB,gBAAgB,CAAA;AAClC,EAAA,KAAA,CAAM,wCAAwC,CAAA;AAC9C,EAAAC,+BAAA,EAAmB;AAEnB,EAAA,WAAA,GAAc,EAAE,GAAGJ,kBAAA,EAAY,GAAG,SAAA,EAAU;AAC5C,EAAA,cAAA,GAAiB,iCAAA,EAAkC;AAInD,EAAA,IAAI,GAAA,EAAK,uBAAA,CAAwB,gBAAA,CAAiB,OAAA,EAAS,iBAAiB,QAAQ,CAAA;AAOpF,EAAA,OAAO,EAAE,WAAA,EAAa,SAAA,EAAW,cAAA,EAAe;AAClD","file":"next-env-compat.js","sourcesContent":["/**\n * Drop-in replacement for @next/env that uses varlock instead of dotenv\n *\n * This must be the default export of the module, and it must stay compatible with @next/env\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { execSync } from 'child_process';\nimport { type SerializedEnvGraph } from 'varlock';\nimport { initVarlockEnv, resetRedactionMap } from 'varlock/env';\nimport { patchGlobalConsole } from 'varlock/patch-console';\nimport { execSyncVarlock } from 'varlock/exec-sync-varlock';\n\nexport type Env = { [key: string]: string | undefined };\nexport type LoadedEnvFiles = Array<{\n path: string\n contents: string\n env: Env\n}>;\n\n/** will store the original values of process.env */\nexport let initialEnv: Env | undefined;\n\nlet lastReloadAt: Date | undefined;\n\nlet varlockLoadedEnv: SerializedEnvGraph;\nlet combinedEnv: Env | undefined;\nlet parsedEnv: Env | undefined;\n// this is used by next just to display the list of .env files in a startup log\nlet loadedEnvFiles: LoadedEnvFiles = [];\nlet rootDir: string | undefined;\n\n// @next/env exports this info and currently it is only used to display\n// a list of filenames loaded, for example: `Environments: .env, .env.development`\nfunction getVarlockSourcesAsLoadedEnvFiles(): LoadedEnvFiles {\n const envFilesLabels = varlockLoadedEnv.sources\n // TODO expose more info so we can filter out disabled sources\n // and maybe show relative paths\n .filter((s) => s.enabled && !s.label.startsWith('directory -'))\n .map((s) => s.label);\n if (envFilesLabels.length) {\n // this adds an additional line, below the list of files\n envFilesLabels.push('\\n ✨ loaded by varlock ✨');\n }\n // files can be imported multiple times, so we deduplicate the labels here\n const uniqueLabels = [...new Set(envFilesLabels)];\n // Next.js expects an array of objects, even though it is not used for anything\n return uniqueLabels.map((label) => ({\n path: label,\n contents: '',\n env: {},\n }));\n}\n\nconst IS_WORKER = !!process.env.NEXT_PRIVATE_WORKER;\nfunction debug(...args: Array<any>) {\n if (!process.env.DEBUG_VARLOCK_NEXT_INTEGRATION) return;\n // eslint-disable-next-line no-console\n console.log(\n IS_WORKER ? 'worker -- ' : 'server -- ',\n ...args,\n );\n}\ndebug('✨ LOADED @next/env module!');\n\n\n// Next.js only watches a fixed set of .env files for changes. Varlock may load\n// additional files (e.g. .env.schema, .env.staging, custom sources). We watch\n// those extra files and trigger a reload by touching one of Next's watched files.\nconst NEXT_WATCHED_ENV_FILES = ['.env', '.env.local', '.env.development', '.env.development.local'];\nconst watchedExtraFiles = new Set<string>();\n\nfunction enableExtraFileWatchers(sources: SerializedEnvGraph['sources'], basePath?: string) {\n if (IS_WORKER || !rootDir) return;\n\n // Collect absolute paths of source files that Next.js does NOT already watch\n const nextWatchedAbsolute = new Set(NEXT_WATCHED_ENV_FILES.map((f) => path.join(rootDir!, f)));\n const extraFilePaths: Array<string> = [];\n for (const source of sources) {\n if (!source.enabled || !source.path) continue;\n const absPath = basePath ? path.resolve(basePath, source.path) : path.resolve(rootDir!, source.path);\n if (!nextWatchedAbsolute.has(absPath) && !watchedExtraFiles.has(absPath)) {\n extraFilePaths.push(absPath);\n }\n }\n // Also always watch .env.schema even if it wasn't in sources (it may not exist yet)\n const envSchemaPath = path.join(rootDir!, '.env.schema');\n if (!nextWatchedAbsolute.has(envSchemaPath) && !watchedExtraFiles.has(envSchemaPath)) {\n extraFilePaths.push(envSchemaPath);\n }\n\n if (!extraFilePaths.length) return;\n\n // Find a Next-watched file to touch as the reload trigger.\n // Prefer an existing file (cheaper), otherwise we'll create+destroy .env\n let triggerFilePath: string | null = null;\n for (const envFileName of NEXT_WATCHED_ENV_FILES) {\n const filePath = path.join(rootDir!, envFileName);\n if (fs.existsSync(filePath)) {\n triggerFilePath = filePath;\n break;\n }\n }\n const mustDestroyTriggerFile = !triggerFilePath;\n triggerFilePath ||= path.join(rootDir!, '.env');\n\n function triggerNextReload(changedPath: string) {\n debug('extra file changed, triggering reload:', changedPath);\n if (mustDestroyTriggerFile) {\n fs.writeFileSync(triggerFilePath!, [\n '# This file was created by @varlock/nextjs-integration',\n '# It is used to trigger Next.js to reload when non-standard .env files change',\n '# You can safely ignore and delete it',\n '# @disable',\n '# ---',\n ].join('\\n'), 'utf-8');\n setTimeout(() => {\n // eslint-disable-next-line\n try { fs.unlinkSync(triggerFilePath!); } catch { /* may already be gone */ }\n }, 1000);\n } else {\n const currentContents = fs.readFileSync(triggerFilePath!, 'utf-8');\n fs.writeFileSync(triggerFilePath!, currentContents, 'utf-8');\n }\n }\n\n debug('setting up extra file watchers for:', extraFilePaths);\n for (const filePath of extraFilePaths) {\n watchedExtraFiles.add(filePath);\n fs.watchFile(filePath, { interval: 500 }, () => {\n triggerNextReload(filePath);\n });\n }\n}\n\nfunction detectOpenNextCloudflareBuild() {\n try {\n // the above works if the build is happening within CI, but we may need to do this for local builds or other CI platforms\n // so we can try to detect if we are within an open-next build by looking at the process info\n\n // we will look at the process tree to try to determine if we are in a opennext build\n // process tree looks like:\n // - opennext-cloudflare build > npm run build > next build\n\n // get grandparent process id\n const pppid = parseInt(execSync(`ps -o ppid= -p ${process.ppid}`).toString().trim());\n // const processInfo = execSync('ps -p '+grandparentPid+' -o command');\n // output looks like\n // ---\n // COMMAND\n // node /.../node_modules/.bin/opennextjs-cloudflare build\n //\n // ---\n const commandName = execSync(`ps -p ${pppid} -o command`).toString().split('\\n')[1];\n if (commandName.endsWith('.bin/opennextjs-cloudflare build')) {\n return true;\n }\n } catch (err) {\n // do nothing\n }\n return false;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction writeResolvedEnvFile() {\n // things get complicated on platforms like vercel/cloudflare, they do some of their own magic to load env vars\n // our loader (this file) will run during the _build_ process, but not when the platform is handling server rendered requests\n // also opennext is needed to run outside of vercel, so that adds other changes\n // so we export an additional .env file which the platform itself will automatically load\n\n const dotEnvStrLines = [];\n for (const [itemKey, itemInfo] of Object.entries(varlockLoadedEnv.config)) {\n if (itemInfo.value !== undefined) dotEnvStrLines.push(`${itemKey}=${JSON.stringify(itemInfo.value)}`);\n }\n\n if (\n detectOpenNextCloudflareBuild()\n || process.env.VERCEL || process.env.WORKERS_CI || process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE\n ) {\n dotEnvStrLines.unshift(`\n# 🛑 DO NOT CHECK THIS FILE INTO VERSION CONTROL 🛑\n# This file was automatically generated by @varlock/nextjs-integration\n# It contains a _fully resolved env_ to pass to platforms (ex: vercel, cloudflare, etc)\n# that are doing their own magic when booting up nextjs in certain scenarios\n#\n# It likely contains sensitive config data and should be deleted after use\n#\n# @disable # tells varlock to ignore this file\n# ---\n `);\n // this is the fully resolved env, which includes additional metadata about each item\n // our runtime code uses this to provide coerced values, redact sensitive values, etc\n dotEnvStrLines.push(`__VARLOCK_ENV=${JSON.stringify(varlockLoadedEnv)}`);\n\n let resolvedEnvFileName = '.env.production.local';\n if (process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE && !(['true', '1'].includes(process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE))) {\n resolvedEnvFileName = process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE;\n }\n if (!rootDir) throw new Error('expected rootDir to be set');\n const resolvedEnvFilePath = path.resolve(rootDir, resolvedEnvFileName);\n fs.writeFileSync(resolvedEnvFilePath, dotEnvStrLines.join('\\n'), 'utf-8');\n debug('wrote resolved env file:', resolvedEnvFilePath);\n }\n}\n\n// - these methods are the same as the original module -----------------\n\nexport function updateInitialEnv(newEnv: Env) {\n if (Object.keys(newEnv).length) {\n debug('updateInitialEnv', newEnv);\n Object.assign(initialEnv || {}, newEnv);\n }\n}\n\ntype Log = {\n info: (...args: Array<any>) => void\n error: (...args: Array<any>) => void\n};\n\nfunction replaceProcessEnv(sourceEnv: Env) {\n Object.keys(process.env).forEach((key) => {\n // Allow mutating internal Next.js env variables after the server has initiated.\n // This is necessary for dynamic things like the IPC server port.\n if (!key.startsWith('__NEXT_PRIVATE')) {\n if (sourceEnv[key] === undefined || sourceEnv[key] === '') {\n delete process.env[key];\n }\n }\n });\n\n Object.entries(sourceEnv).forEach(([key, value]) => {\n process.env[key] = value;\n });\n}\n\n// in original module, but does not appear to be used\nexport function processEnv(\n _loadedEnvFiles: LoadedEnvFiles,\n _dir?: string,\n _log: Log = console,\n _forceReload = false,\n _onReload?: (envFilePath: string) => void,\n) {\n return [process.env];\n}\n\nexport function resetEnv() {\n if (initialEnv) {\n replaceProcessEnv(initialEnv);\n }\n}\n\ntype LoadedEnvConfig = {\n combinedEnv: Env\n parsedEnv: Env | undefined\n loadedEnvFiles: LoadedEnvFiles\n};\n\nlet loadCount = 0;\n\nexport function loadEnvConfig(\n dir: string,\n dev?: boolean,\n _log: Log = console,\n forceReload = false,\n _onReload?: (envFilePath: string) => void,\n): LoadedEnvConfig {\n // store actual process.env so we can restore it later\n initialEnv ||= { ...process.env };\n\n loadCount++;\n debug('loadEnvConfig!', 'forceReload = ', forceReload);\n\n // onReload is used to show a log of which .env file changed\n // TODO: add similar log to show which env file changed\n\n rootDir ||= dir;\n if (rootDir !== dir) throw new Error('root directory changed');\n\n // Always watch .env.schema early — even before the first successful load —\n // so that if the load fails (e.g. validation error), the user can fix the\n // schema and have the dev server automatically retry without a restart.\n if (dev) enableExtraFileWatchers([], undefined);\n\n let useCachedEnv = !!process.env.__VARLOCK_ENV;\n if (forceReload) {\n // Throttle reloads to at most once per second to avoid spinning during\n // rapid file-change bursts (Next.js may fire multiple events per edit)\n if (!lastReloadAt || lastReloadAt.getTime() < Date.now() - 1000) {\n lastReloadAt = new Date();\n useCachedEnv = false;\n }\n }\n\n if (useCachedEnv) {\n if (!varlockLoadedEnv) {\n varlockLoadedEnv = JSON.parse(process.env.__VARLOCK_ENV || '{}');\n parsedEnv = Object.fromEntries(\n Object.entries(varlockLoadedEnv.config).map(([key, value]) => [key, value.value]),\n );\n\n resetRedactionMap(varlockLoadedEnv);\n debug('patching console with varlock redactor');\n patchGlobalConsole();\n }\n\n combinedEnv = { ...initialEnv, ...parsedEnv };\n\n if (dev) enableExtraFileWatchers(varlockLoadedEnv.sources, varlockLoadedEnv.basePath);\n\n debug('>> USING CACHED ENV');\n\n return { combinedEnv, parsedEnv, loadedEnvFiles };\n }\n\n lastReloadAt = new Date();\n\n debug('>> RELOADING ENV');\n replaceProcessEnv(initialEnv);\n\n // we must match @next/env default behaviour for which .env.XXX files to load\n // which is based on the current command (`next dev` vs `next build`) and `NODE_ENV=test`\n // however we will pass it through and let the user ignore it by setting their own `@currentEnv`\n let envFromNextCommand = dev ? 'development' : 'production';\n if (process.env.NODE_ENV === 'test') envFromNextCommand = 'test';\n debug('Inferred env mode (to match @next/env):', envFromNextCommand);\n\n try {\n // strip DEBUG_VARLOCK from env to prevent debug output from contaminating JSON stdout\n const cleanEnv = { ...initialEnv };\n delete cleanEnv.DEBUG_VARLOCK;\n const varlockLoadedEnvStr = execSyncVarlock(`load --format json-full --env ${envFromNextCommand}`, {\n showLogsOnError: true,\n // in a build, we want to fail and exit, while in dev we can keep retrying when changes are detected\n exitOnError: !dev,\n env: cleanEnv as any,\n });\n if (loadCount >= 2) {\n // eslint-disable-next-line no-console\n console.log('✅ env reloaded and validated');\n }\n varlockLoadedEnv = JSON.parse(varlockLoadedEnvStr);\n } catch (err) {\n // this error message comes from execSyncVarlock when it cannot find varlock\n if ((err as any).message.includes('Unable to find varlock executable')) {\n // eslint-disable-next-line no-console\n console.error([\n '',\n '❌ ERROR: varlock not found',\n 'varlock is a required peer dependency of @varlock/nextjs-integration',\n '',\n 'Please add varlock as a dependency to your project (e.g., `npm install varlock`)',\n ].join('\\n'));\n process.exit(1);\n }\n\n // showLogsOnError already printed the formatted CLI output above,\n // so we only add a short note here (err.message duplicates stderr)\n // eslint-disable-next-line no-console\n console.error('[varlock] ⚠️ failed to load env — see error above');\n\n // if we dont do this, we'll see an error that looks like `process.env.__VARLOCK_ENV is not set` which is misleading.\n // Ideally we would pass through an error of some kind and trigger the webpack runtime error popup\n process.env.__VARLOCK_ENV = JSON.stringify({\n sources: [],\n config: {},\n settings: {},\n });\n\n return { combinedEnv: {}, parsedEnv: {}, loadedEnvFiles: [] };\n }\n\n parsedEnv = {};\n for (const [itemKey, itemInfo] of Object.entries(varlockLoadedEnv.config)) {\n parsedEnv[itemKey] = itemInfo.value;\n }\n debug('LOADED ENV:', parsedEnv);\n process.env.__VARLOCK_ENV = JSON.stringify(varlockLoadedEnv);\n initVarlockEnv(); // calling this will set process.env vars\n\n resetRedactionMap(varlockLoadedEnv);\n debug('patching console with varlock redactor');\n patchGlobalConsole();\n\n combinedEnv = { ...initialEnv, ...parsedEnv };\n loadedEnvFiles = getVarlockSourcesAsLoadedEnvFiles();\n\n // Set up watchers for source files that Next.js doesn't natively watch.\n // Called after every reload so newly-added sources get watched too.\n if (dev) enableExtraFileWatchers(varlockLoadedEnv.sources, varlockLoadedEnv.basePath);\n\n // write a resolved .env file for platforms like Vercel/Cloudflare that need\n // pre-resolved env values at runtime (they don't re-run @next/env on boot)\n // TODO: re-enable once we verify instrumentation approach works for prod\n // if (!dev) writeResolvedEnvFile();\n\n return { combinedEnv, parsedEnv, loadedEnvFiles };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/next-env-compat.ts"],"names":["initialEnv","path","fs","resetRedactionMap","patchGlobalConsole","execS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AA,MACV,QAAQ,EAAC;AAAA,MACT,UAAU;AAAC,KACZ,CAAA;AAED,IAAA,OAAO,EAAE,aAAa,EAAC,EAAG,WAAW,EAAC,EAAG,cAAA,EAAgB,EAAC,EAAE;AAAA,EAC9D;AAEA,EAAA,SAAA,GAAY,EAAC;AACb,EAAA,KAAA,MAAW,CAAC,SAAS,QAAQ,CAAA,IAAK,OAAO,OAAA,CAAQ,gBAAA,CAAiB,MAAM,CAAA,EAAG;AACzE,IAAA,SAAA,CAAU,OAAO,IAAI,QAAA,CAAS,KAAA;AAAA,EAChC;AACA,EAAA,KAAA,CAAM,eAAe,SAAS,CAAA;AAC9B,EAAA,OAAA,CAAQ,GAAA,CAAI,aAAA,GAAgB,IAAA,CAAK,SAAA,CAAU,gBAAgB,CAAA;AAC3D,EAAAC,kBAAA,EAAe;AAEf,EAAAH,qBAAA,CAAkB,gBAAgB,CAAA;AAClC,EAAA,KAAA,CAAM,wCAAwC,CAAA;AAC9C,EAAAC,+BAAA,EAAmB;AAEnB,EAAA,WAAA,GAAc,EAAE,GAAGJ,kBAAA,EAAY,GAAG,SAAA,EAAU;AAC5C,EAAA,cAAA,GAAiB,iCAAA,EAAkC;AAInD,EAAA,IAAI,GAAA,EAAK,uBAAA,CAAwB,gBAAA,CAAiB,OAAA,EAAS,iBAAiB,QAAQ,CAAA;AAOpF,EAAA,OAAO,EAAE,WAAA,EAAa,SAAA,EAAW,cAAA,EAAe;AAClD","file":"next-env-compat.js","sourcesContent":["/**\n * Drop-in replacement for @next/env that uses varlock instead of dotenv\n *\n * This must be the default export of the module, and it must stay compatible with @next/env\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { execSync } from 'child_process';\nimport { type SerializedEnvGraph } from 'varlock';\nimport { initVarlockEnv, resetRedactionMap } from 'varlock/env';\nimport { patchGlobalConsole } from 'varlock/patch-console';\nimport { execSyncVarlock } from 'varlock/exec-sync-varlock';\n\nexport type Env = { [key: string]: string | undefined };\nexport type LoadedEnvFiles = Array<{\n path: string\n contents: string\n env: Env\n}>;\n\n/** will store the original values of process.env */\nexport let initialEnv: Env | undefined;\n\nlet lastReloadAt: Date | undefined;\n\nlet varlockLoadedEnv: SerializedEnvGraph;\nlet combinedEnv: Env | undefined;\nlet parsedEnv: Env | undefined;\n// this is used by next just to display the list of .env files in a startup log\nlet loadedEnvFiles: LoadedEnvFiles = [];\nlet rootDir: string | undefined;\n\n// @next/env exports this info and currently it is only used to display\n// a list of filenames loaded, for example: `Environments: .env, .env.development`\nfunction getVarlockSourcesAsLoadedEnvFiles(): LoadedEnvFiles {\n const envFilesLabels = varlockLoadedEnv.sources\n .filter((s) => s.enabled && s.type !== 'container' && s.type !== 'import-alias')\n .map((s) => s.label);\n if (envFilesLabels.length) {\n // this adds an additional line, below the list of files\n envFilesLabels.push('\\n ✨ loaded by varlock ✨');\n }\n // files can be imported multiple times, so we deduplicate the labels here\n const uniqueLabels = [...new Set(envFilesLabels)];\n // Next.js expects an array of objects, even though it is not used for anything\n return uniqueLabels.map((label) => ({\n path: label,\n contents: '',\n env: {},\n }));\n}\n\nconst IS_WORKER = !!process.env.NEXT_PRIVATE_WORKER;\nfunction debug(...args: Array<any>) {\n if (!process.env.DEBUG_VARLOCK_NEXT_INTEGRATION) return;\n // eslint-disable-next-line no-console\n console.log(\n IS_WORKER ? 'worker -- ' : 'server -- ',\n ...args,\n );\n}\ndebug('✨ LOADED @next/env module!');\n\n\n// Next.js only watches a fixed set of .env files for changes. Varlock may load\n// additional files (e.g. .env.schema, .env.staging, custom sources). We watch\n// those extra files and trigger a reload by touching one of Next's watched files.\nconst NEXT_WATCHED_ENV_FILES = ['.env', '.env.local', '.env.development', '.env.development.local'];\nconst watchedExtraFiles = new Set<string>();\n\nfunction enableExtraFileWatchers(sources: SerializedEnvGraph['sources'], basePath?: string) {\n if (IS_WORKER || !rootDir) return;\n\n // Collect absolute paths of source files that Next.js does NOT already watch\n const nextWatchedAbsolute = new Set(NEXT_WATCHED_ENV_FILES.map((f) => path.join(rootDir!, f)));\n const extraFilePaths: Array<string> = [];\n for (const source of sources) {\n if (!source.enabled || !source.path) continue;\n const absPath = basePath ? path.resolve(basePath, source.path) : path.resolve(rootDir!, source.path);\n if (!nextWatchedAbsolute.has(absPath) && !watchedExtraFiles.has(absPath)) {\n extraFilePaths.push(absPath);\n }\n }\n // Also always watch .env.schema even if it wasn't in sources (it may not exist yet)\n const envSchemaPath = path.join(rootDir!, '.env.schema');\n if (!nextWatchedAbsolute.has(envSchemaPath) && !watchedExtraFiles.has(envSchemaPath)) {\n extraFilePaths.push(envSchemaPath);\n }\n\n if (!extraFilePaths.length) return;\n\n // Find a Next-watched file to touch as the reload trigger.\n // Prefer an existing file (cheaper), otherwise we'll create+destroy .env\n let triggerFilePath: string | null = null;\n for (const envFileName of NEXT_WATCHED_ENV_FILES) {\n const filePath = path.join(rootDir!, envFileName);\n if (fs.existsSync(filePath)) {\n triggerFilePath = filePath;\n break;\n }\n }\n const mustDestroyTriggerFile = !triggerFilePath;\n triggerFilePath ||= path.join(rootDir!, '.env');\n\n function triggerNextReload(changedPath: string) {\n debug('extra file changed, triggering reload:', changedPath);\n if (mustDestroyTriggerFile) {\n fs.writeFileSync(triggerFilePath!, [\n '# This file was created by @varlock/nextjs-integration',\n '# It is used to trigger Next.js to reload when non-standard .env files change',\n '# You can safely ignore and delete it',\n '# @disable',\n '# ---',\n ].join('\\n'), 'utf-8');\n setTimeout(() => {\n // eslint-disable-next-line\n try { fs.unlinkSync(triggerFilePath!); } catch { /* may already be gone */ }\n }, 1000);\n } else {\n const currentContents = fs.readFileSync(triggerFilePath!, 'utf-8');\n fs.writeFileSync(triggerFilePath!, currentContents, 'utf-8');\n }\n }\n\n debug('setting up extra file watchers for:', extraFilePaths);\n for (const filePath of extraFilePaths) {\n watchedExtraFiles.add(filePath);\n fs.watchFile(filePath, { interval: 500 }, () => {\n triggerNextReload(filePath);\n });\n }\n}\n\nfunction detectOpenNextCloudflareBuild() {\n try {\n // the above works if the build is happening within CI, but we may need to do this for local builds or other CI platforms\n // so we can try to detect if we are within an open-next build by looking at the process info\n\n // we will look at the process tree to try to determine if we are in a opennext build\n // process tree looks like:\n // - opennext-cloudflare build > npm run build > next build\n\n // get grandparent process id\n const pppid = parseInt(execSync(`ps -o ppid= -p ${process.ppid}`).toString().trim());\n // const processInfo = execSync('ps -p '+grandparentPid+' -o command');\n // output looks like\n // ---\n // COMMAND\n // node /.../node_modules/.bin/opennextjs-cloudflare build\n //\n // ---\n const commandName = execSync(`ps -p ${pppid} -o command`).toString().split('\\n')[1];\n if (commandName.endsWith('.bin/opennextjs-cloudflare build')) {\n return true;\n }\n } catch (err) {\n // do nothing\n }\n return false;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction writeResolvedEnvFile() {\n // things get complicated on platforms like vercel/cloudflare, they do some of their own magic to load env vars\n // our loader (this file) will run during the _build_ process, but not when the platform is handling server rendered requests\n // also opennext is needed to run outside of vercel, so that adds other changes\n // so we export an additional .env file which the platform itself will automatically load\n\n const dotEnvStrLines = [];\n for (const [itemKey, itemInfo] of Object.entries(varlockLoadedEnv.config)) {\n if (itemInfo.value !== undefined) dotEnvStrLines.push(`${itemKey}=${JSON.stringify(itemInfo.value)}`);\n }\n\n if (\n detectOpenNextCloudflareBuild()\n || process.env.VERCEL || process.env.WORKERS_CI || process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE\n ) {\n dotEnvStrLines.unshift(`\n# 🛑 DO NOT CHECK THIS FILE INTO VERSION CONTROL 🛑\n# This file was automatically generated by @varlock/nextjs-integration\n# It contains a _fully resolved env_ to pass to platforms (ex: vercel, cloudflare, etc)\n# that are doing their own magic when booting up nextjs in certain scenarios\n#\n# It likely contains sensitive config data and should be deleted after use\n#\n# @disable # tells varlock to ignore this file\n# ---\n `);\n // this is the fully resolved env, which includes additional metadata about each item\n // our runtime code uses this to provide coerced values, redact sensitive values, etc\n dotEnvStrLines.push(`__VARLOCK_ENV=${JSON.stringify(varlockLoadedEnv)}`);\n\n let resolvedEnvFileName = '.env.production.local';\n if (process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE && !(['true', '1'].includes(process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE))) {\n resolvedEnvFileName = process.env._VARLOCK_EXPORT_RESOLVED_ENV_FILE;\n }\n if (!rootDir) throw new Error('expected rootDir to be set');\n const resolvedEnvFilePath = path.resolve(rootDir, resolvedEnvFileName);\n fs.writeFileSync(resolvedEnvFilePath, dotEnvStrLines.join('\\n'), 'utf-8');\n debug('wrote resolved env file:', resolvedEnvFilePath);\n }\n}\n\n// - these methods are the same as the original module -----------------\n\nexport function updateInitialEnv(newEnv: Env) {\n if (Object.keys(newEnv).length) {\n debug('updateInitialEnv', newEnv);\n Object.assign(initialEnv || {}, newEnv);\n }\n}\n\ntype Log = {\n info: (...args: Array<any>) => void\n error: (...args: Array<any>) => void\n};\n\nfunction replaceProcessEnv(sourceEnv: Env) {\n Object.keys(process.env).forEach((key) => {\n // Allow mutating internal Next.js env variables after the server has initiated.\n // This is necessary for dynamic things like the IPC server port.\n if (!key.startsWith('__NEXT_PRIVATE')) {\n if (sourceEnv[key] === undefined || sourceEnv[key] === '') {\n delete process.env[key];\n }\n }\n });\n\n Object.entries(sourceEnv).forEach(([key, value]) => {\n process.env[key] = value;\n });\n}\n\n// in original module, but does not appear to be used\nexport function processEnv(\n _loadedEnvFiles: LoadedEnvFiles,\n _dir?: string,\n _log: Log = console,\n _forceReload = false,\n _onReload?: (envFilePath: string) => void,\n) {\n return [process.env];\n}\n\nexport function resetEnv() {\n if (initialEnv) {\n replaceProcessEnv(initialEnv);\n }\n}\n\ntype LoadedEnvConfig = {\n combinedEnv: Env\n parsedEnv: Env | undefined\n loadedEnvFiles: LoadedEnvFiles\n};\n\nlet loadCount = 0;\n\nexport function loadEnvConfig(\n dir: string,\n dev?: boolean,\n _log: Log = console,\n forceReload = false,\n _onReload?: (envFilePath: string) => void,\n): LoadedEnvConfig {\n // store actual process.env so we can restore it later\n initialEnv ||= { ...process.env };\n\n loadCount++;\n debug('loadEnvConfig!', 'forceReload = ', forceReload);\n\n // onReload is used to show a log of which .env file changed\n // TODO: add similar log to show which env file changed\n\n rootDir ||= dir;\n if (rootDir !== dir) throw new Error('root directory changed');\n\n // Always watch .env.schema early — even before the first successful load —\n // so that if the load fails (e.g. validation error), the user can fix the\n // schema and have the dev server automatically retry without a restart.\n if (dev) enableExtraFileWatchers([], undefined);\n\n let useCachedEnv = !!process.env.__VARLOCK_ENV;\n if (forceReload) {\n // Throttle reloads to at most once per second to avoid spinning during\n // rapid file-change bursts (Next.js may fire multiple events per edit)\n if (!lastReloadAt || lastReloadAt.getTime() < Date.now() - 1000) {\n lastReloadAt = new Date();\n useCachedEnv = false;\n }\n }\n\n if (useCachedEnv) {\n if (!varlockLoadedEnv) {\n varlockLoadedEnv = JSON.parse(process.env.__VARLOCK_ENV || '{}');\n parsedEnv = Object.fromEntries(\n Object.entries(varlockLoadedEnv.config).map(([key, value]) => [key, value.value]),\n );\n\n resetRedactionMap(varlockLoadedEnv);\n debug('patching console with varlock redactor');\n patchGlobalConsole();\n }\n\n combinedEnv = { ...initialEnv, ...parsedEnv };\n\n if (dev) enableExtraFileWatchers(varlockLoadedEnv.sources, varlockLoadedEnv.basePath);\n\n debug('>> USING CACHED ENV');\n\n return { combinedEnv, parsedEnv, loadedEnvFiles };\n }\n\n lastReloadAt = new Date();\n\n debug('>> RELOADING ENV');\n replaceProcessEnv(initialEnv);\n\n // we must match @next/env default behaviour for which .env.XXX files to load\n // which is based on the current command (`next dev` vs `next build`) and `NODE_ENV=test`\n // however we will pass it through and let the user ignore it by setting their own `@currentEnv`\n let envFromNextCommand = dev ? 'development' : 'production';\n if (process.env.NODE_ENV === 'test') envFromNextCommand = 'test';\n debug('Inferred env mode (to match @next/env):', envFromNextCommand);\n\n try {\n // strip DEBUG_VARLOCK from env to prevent debug output from contaminating JSON stdout\n const cleanEnv = { ...initialEnv };\n delete cleanEnv.DEBUG_VARLOCK;\n const varlockLoadedEnvStr = execSyncVarlock(`load --format json-full --env ${envFromNextCommand}`, {\n showLogsOnError: true,\n // in a build, we want to fail and exit, while in dev we can keep retrying when changes are detected\n exitOnError: !dev,\n env: cleanEnv as any,\n });\n if (loadCount >= 2) {\n // eslint-disable-next-line no-console\n console.log('✅ env reloaded and validated');\n }\n varlockLoadedEnv = JSON.parse(varlockLoadedEnvStr);\n } catch (err) {\n // this error message comes from execSyncVarlock when it cannot find varlock\n if ((err as any).message.includes('Unable to find varlock executable')) {\n // eslint-disable-next-line no-console\n console.error([\n '',\n '❌ ERROR: varlock not found',\n 'varlock is a required peer dependency of @varlock/nextjs-integration',\n '',\n 'Please add varlock as a dependency to your project (e.g., `npm install varlock`)',\n ].join('\\n'));\n process.exit(1);\n }\n\n // showLogsOnError already printed the formatted CLI output above,\n // so we only add a short note here (err.message duplicates stderr)\n // eslint-disable-next-line no-console\n console.error('[varlock] ⚠️ failed to load env — see error above');\n\n // if we dont do this, we'll see an error that looks like `process.env.__VARLOCK_ENV is not set` which is misleading.\n // Ideally we would pass through an error of some kind and trigger the webpack runtime error popup\n process.env.__VARLOCK_ENV = JSON.stringify({\n sources: [],\n config: {},\n settings: {},\n });\n\n return { combinedEnv: {}, parsedEnv: {}, loadedEnvFiles: [] };\n }\n\n parsedEnv = {};\n for (const [itemKey, itemInfo] of Object.entries(varlockLoadedEnv.config)) {\n parsedEnv[itemKey] = itemInfo.value;\n }\n debug('LOADED ENV:', parsedEnv);\n process.env.__VARLOCK_ENV = JSON.stringify(varlockLoadedEnv);\n initVarlockEnv(); // calling this will set process.env vars\n\n resetRedactionMap(varlockLoadedEnv);\n debug('patching console with varlock redactor');\n patchGlobalConsole();\n\n combinedEnv = { ...initialEnv, ...parsedEnv };\n loadedEnvFiles = getVarlockSourcesAsLoadedEnvFiles();\n\n // Set up watchers for source files that Next.js doesn't natively watch.\n // Called after every reload so newly-added sources get watched too.\n if (dev) enableExtraFileWatchers(varlockLoadedEnv.sources, varlockLoadedEnv.basePath);\n\n // write a resolved .env file for platforms like Vercel/Cloudflare that need\n // pre-resolved env values at runtime (they don't re-run @next/env on boot)\n // TODO: re-enable once we verify instrumentation approach works for prod\n // if (!dev) writeResolvedEnvFile();\n\n return { combinedEnv, parsedEnv, loadedEnvFiles };\n}\n"]}
|
package/dist/plugin.js
CHANGED
|
@@ -5,6 +5,7 @@ var path2 = require('path');
|
|
|
5
5
|
var env = require('varlock/env');
|
|
6
6
|
var patchConsole = require('varlock/patch-console');
|
|
7
7
|
var patchServerResponse = require('varlock/patch-server-response');
|
|
8
|
+
require('varlock');
|
|
8
9
|
|
|
9
10
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
10
11
|
|
package/dist/plugin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/webpack-plugin.ts","../src/turbopack-runtime-inject.ts","../src/plugin.ts"],"names":["debug","patchGlobalFsMethods","varlockSettings","patchGlobalServerResponse","scanForLeaks","fs","redactSensitiveConfig","path","patchGlobalConsole","initVarlockEnv","getRedactionMapInfo"],"mappings":";;;;;;;;;;;;;;;;;;;AAUA,IAAM,mBAAA,GAAsB,0BAAA;AAO5B,IAAI,sBAAA;AACJ,SAAS,8BAA8BA,MAAAA,EAAsC;AAC3E,EAAA,OAAO,IAAI,KAAA,CAAM,EAAC,EAA6B;AAAA,IAC7C,QAAQ,OAAA,EAAS;AACf,MAAA,sBAAA,GAAyB,IAAA,CAAK,KAAA,CAAM,OAAA,CAAQ,GAAA,CAAI,iBAAiB,IAAI,CAAA;AACrE,MAAA,MAAM,cAAc,EAAC;AACrB,MAAA,KAAA,MAAW,OAAA,IAAW,uBAAuB,MAAA,EAAQ;AACnD,QAAA,MAAM,IAAA,GAAO,sBAAA,CAAuB,MAAA,CAAO,OAAO,CAAA;AAClD,QAAA,IAAI,CAAC,IAAA,CAAK,WAAA,cAAyB,IAAA,CAAK,CAAA,IAAA,EAAO,OAAO,CAAA,CAAE,C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AAA;AAAA,QACH,GAAG,WAAA,IAAe;AAAA,UAChB,WAAY,kBAAA,CAA2B;AAAA,SACzC;AAAA,QACA,GAAG,CAAC,YAAA,IAAgB;AAAA,UAClB,OAAA,EAAS,qBAAA,CAAsB,kBAAA,EAAoB,oBAAA,EAAsBA,QAAO,OAAO;AAAA;AACzF,OACF;AAAA,IACF,CAAA;AAAA,EACF,CAAA;AACF","file":"plugin.js","sourcesContent":["import fs from 'node:fs';\n\nimport {\n redactSensitiveConfig, scanForLeaks, varlockSettings,\n} from 'varlock/env';\nimport { patchGlobalServerResponse } from 'varlock/patch-server-response';\n\nimport { type SerializedEnvGraph } from 'varlock';\nimport type { NextConfig } from 'next';\n\nconst WEBPACK_PLUGIN_NAME = 'VarlockNextWebpackPlugin';\n\n// We use a proxy object for the static replacements that we pass to webpack.DefinePlugin\n// because this plugin/webpack code is not invoked again when env files change\n// instead next is direcly messing with the existing plugins for their own changes\n// so instead we use a proxy object, and grab the values off of process.env.__VARLOCK_ENV\n// which will have been updated by our next-env-compat code\nlet latestLoadedVarlockEnv: SerializedEnvGraph | undefined;\nfunction createStaticReplacementsProxy(debug: (...args: Array<any>) => void) {\n return new Proxy({} as Record<string, string>, {\n ownKeys(_target) {\n latestLoadedVarlockEnv = JSON.parse(process.env.__VARLOCK_ENV || '{}') as SerializedEnvGraph;\n const replaceKeys = [] as Array<string>;\n for (const itemKey in latestLoadedVarlockEnv.config) {\n const item = latestLoadedVarlockEnv.config[itemKey];\n if (!item.isSensitive) replaceKeys.push(`ENV.${itemKey}`);\n }\n debug('reloaded static replacements keys', replaceKeys);\n return replaceKeys;\n },\n getOwnPropertyDescriptor(_target, prop) {\n const itemKey = prop.toString().split('.')[1];\n const item = latestLoadedVarlockEnv?.config[itemKey];\n if (!item || item.isSensitive) return;\n return {\n value: '', // this value is not used, the get handler will return the value\n writable: false,\n enumerable: true,\n configurable: true,\n };\n },\n get(_target, prop) {\n const itemKey = prop.toString().split('.')[1];\n const item = latestLoadedVarlockEnv?.config[itemKey];\n if (item && !item.isSensitive) return JSON.stringify(item.value);\n },\n });\n}\n\nexport function createWebpackConfigFn(\n resolvedNextConfig: NextConfig,\n patchGlobalFsMethods: () => void,\n debug: (...args: Array<any>) => void,\n isBuild: boolean,\n) {\n const staticReplacementsProxy = createStaticReplacementsProxy(debug);\n\n return function webpackConfigFn(webpackConfig: any, options: any) {\n debug('varlockNextConfigPlugin webpack config patching');\n\n const { dev } = options; // also available - isServer, nextRuntime\n\n // only patch fs methods during builds — they create \"hooks\" for post-build\n // scanning/scrubbing and are unnecessary during dev\n if (isBuild) patchGlobalFsMethods();\n\n if (varlockSettings.preventLeaks) {\n // have to wait to run this until here when we know if this is dev mode or not\n patchGlobalServerResponse({\n ignoreUrlPatterns: [\n /^\\/__nextjs_source-map\\?.*/, // sourcemaps\n /[?&]_rsc=/, // RSC payloads are server-side and expected to contain sensitive data\n ],\n // in dev mode, we redact the secrets rather than throwing, because otherwise the dev server crashes\n redactInsteadOfThrow: dev,\n });\n }\n\n // webpack itself is passed in so we dont have to import it (or make it a dependency)\n const webpack = options.webpack;\n\n // apply existing user customizations if there are any\n if (resolvedNextConfig.webpack) {\n webpackConfig = resolvedNextConfig.webpack(webpackConfig, options);\n }\n\n if (!process.env.__VARLOCK_ENV) throw new Error('VarlockNextWebpackPlugin: __VARLOCK_ENV is not set');\n\n // Add per-file init guard for server (non-edge) compilations.\n // Pre-rendering workers may receive compiled code via IPC rather than loading\n // runtime files from disk, so runtime injection alone isn't sufficient.\n // The loader ensures initVarlockEnv() and patchGlobalConsole() run in every worker.\n // alwaysRepatchConsole: in webpack, React wraps console for RSC dev replay AFTER\n // our initial patch in the runtime file, so we re-patch in each file to ensure\n // our redaction wraps React's wrapper. (Turbopack doesn't need this.)\n if (options.isServer && options.nextRuntime !== 'edge') {\n webpackConfig.module.rules.push({\n test: /\\.(js|jsx|ts|tsx|mjs|mts)$/,\n exclude: /node_modules/,\n use: [\n {\n loader: require.resolve('./loader'),\n options: { bundler: 'webpack' },\n },\n ],\n });\n }\n // Edge compilation: also re-patch console to wrap React's RSC dev replay wrapper.\n // Edge can't use require(), so we call globalThis.__varlockPatchConsole which the\n // init-edge bundle exposes after running.\n if (options.isServer && options.nextRuntime === 'edge') {\n webpackConfig.module.rules.push({\n test: /\\.(js|jsx|ts|tsx|mjs|mts)$/,\n exclude: /node_modules/,\n use: [\n {\n loader: require.resolve('./loader'),\n options: { bundler: 'webpack', isEdge: true },\n },\n ],\n });\n }\n\n // Set up build-time replacements / rewrites - using webpack.DefinePlugin and a proxy\n // TODO: use shared helpers from core library?\n debug('adding ENV.xxx static replacements proxy object');\n webpackConfig.plugins.push(new webpack.DefinePlugin(staticReplacementsProxy));\n\n if (varlockSettings.preventLeaks) {\n webpackConfig.plugins.push({\n apply(compiler: any) {\n compiler.hooks.assetEmitted.tap(WEBPACK_PLUGIN_NAME, (_file: any, assetDetails: any) => {\n const { content, targetPath } = assetDetails;\n\n if (\n targetPath.includes('/.next/static/chunks/')\n || targetPath.endsWith('.html')\n // .rsc and .body are server-side (RSC payloads), not client-facing\n ) {\n // NOTE - in dev mode the request hangs on the error, but the console error should help\n // and during a build, it will actually fail the build\n try {\n scanForLeaks(content, {\n method: '@varlock/nextjs-integration/plugin - assetEmitted hook',\n file: targetPath,\n });\n } catch (err) {\n if (dev) {\n // overwrite file with redacted version\n fs.writeFileSync(targetPath, redactSensitiveConfig(content.toString()));\n } else {\n throw err;\n }\n }\n }\n });\n },\n });\n }\n\n // Inject varlock init into webpack runtime files.\n // We prepend the self-contained init bundle as raw JS so it runs before any module code.\n // Server runtimes get the full init (with server-response patching),\n // edge runtimes get the edge-safe init (no node:zlib/node:http).\n function injectVarlockInitIntoWebpackRuntime(edgeRuntime = false) {\n return function assetUpdateFn(origSource: any) {\n const origSourceStr = origSource.source();\n\n const initBundleName = edgeRuntime ? 'init-edge' : 'init-server';\n const injectorPath = require.resolve(`varlock/${initBundleName}`);\n const injectorSrc = fs.readFileSync(injectorPath, 'utf8');\n\n // inline the resolved env so it's baked into the build\n // this removes the need for a .env.production.local file on platforms like Vercel\n const rawEnv = process.env.__VARLOCK_ENV;\n const envInline = rawEnv\n ? `process.env.__VARLOCK_ENV = process.env.__VARLOCK_ENV || ${JSON.stringify(rawEnv)};`\n : '';\n\n const updatedSourceStr = [\n envInline,\n // Wrap in IIFE to avoid symbol collisions when bundlers concatenate files.\n // Provide dummy exports/module since the CJS bundle uses `exports.X = ...`\n `(function(exports,module){${injectorSrc}})({},{exports:{}});`,\n origSourceStr,\n ].join('\\n');\n\n return new webpack.sources.RawSource(updatedSourceStr);\n };\n }\n\n const isEdgeRuntime = options.nextRuntime === 'edge';\n webpackConfig.plugins.push({\n apply(compiler: any) {\n compiler.hooks.thisCompilation.tap(WEBPACK_PLUGIN_NAME, (compilation: any) => {\n compilation.hooks.processAssets.tap(\n {\n name: WEBPACK_PLUGIN_NAME,\n stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,\n },\n () => {\n if (isEdgeRuntime) {\n // Edge compilation — only inject the edge-safe init bundle (no node builtins)\n if (compilation.getAsset('edge-runtime-webpack.js')) {\n compilation.updateAsset('edge-runtime-webpack.js', injectVarlockInitIntoWebpackRuntime(true));\n }\n // Edge compilation also has webpack-runtime.js — inject init-edge there too\n for (const name of ['webpack-runtime.js', '../webpack-runtime.js']) {\n if (compilation.getAsset(name)) {\n compilation.updateAsset(name, injectVarlockInitIntoWebpackRuntime(true));\n }\n }\n } else if (options.isServer) {\n // Server (node.js) compilation — inject full init with server-response patching\n for (const name of ['webpack-runtime.js', '../webpack-runtime.js', 'webpack-api-runtime.js', '../webpack-api-runtime.js']) {\n if (compilation.getAsset(name)) {\n compilation.updateAsset(name, injectVarlockInitIntoWebpackRuntime());\n }\n }\n }\n },\n );\n });\n },\n });\n\n return webpackConfig; // must return the modified config\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nfunction debug(...args: Array<any>) {\n if (!process.env.DEBUG_VARLOCK_NEXT_INTEGRATION) return;\n // eslint-disable-next-line no-console\n console.log('[varlock]', ...args);\n}\n\n/**\n * Inject varlock init bundle into turbopack runtime files (analogous to webpack runtime injection).\n * Turbopack writes `[turbopack]_runtime.js` files during compilation — these are loaded by\n * the deployed server before any user code runs, making them the ideal injection point.\n *\n * Note: pre-rendering workers during builds receive compiled code via IPC (not from disk),\n * so this injection only takes effect for the deployed server. Build-time init is handled\n * by the turbopack loader's init guard snippet.\n */\nlet injectedTurbopackRuntime = false;\nexport function injectVarlockInitIntoTurbopackRuntime(nextDirPath: string) {\n if (injectedTurbopackRuntime) return;\n\n const rawEnv = process.env.__VARLOCK_ENV;\n if (!rawEnv) {\n return;\n }\n\n // Find turbopack runtime files ([turbopack]_runtime.js) and edge-wrapper files.\n // Node.js SSR/build uses [turbopack]_runtime.js, while edge runtime uses\n // edge-wrapper JS files (no [turbopack]_runtime.js exists for edge).\n const serverRuntimeFiles: Array<string> = [];\n const edgeWrapperFiles: Array<string> = [];\n const walkDir = (dir: string) => {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (entry.isDirectory()) {\n walkDir(path.join(dir, entry.name));\n } else if (entry.name === '[turbopack]_runtime.js') {\n serverRuntimeFiles.push(path.join(dir, entry.name));\n } else if (entry.name.includes('edge-wrapper') && entry.name.endsWith('.js')) {\n edgeWrapperFiles.push(path.join(dir, entry.name));\n }\n }\n };\n walkDir(nextDirPath);\n\n debug(`turbopack runtime injection: found ${serverRuntimeFiles.length} server runtime files, ${edgeWrapperFiles.length} edge wrapper files`);\n\n if (!serverRuntimeFiles.length) {\n // Runtime files may not exist yet — turbopack (Rust) writes them directly.\n // We'll retry on subsequent fs writes until they appear.\n return;\n }\n\n // Mark as done so we don't retry\n injectedTurbopackRuntime = true;\n\n // Load both init bundles — server (full, node:zlib/node:http) and edge (no node builtins)\n const initServerSrc = fs.readFileSync(require.resolve('varlock/init-server'), 'utf8');\n const initEdgeSrc = fs.readFileSync(require.resolve('varlock/init-edge'), 'utf8');\n const envInline = `process.env.__VARLOCK_ENV = process.env.__VARLOCK_ENV || ${JSON.stringify(rawEnv)};`;\n\n // The CJS init bundles use `exports.X = ...` at the end, so we must provide\n // a dummy `exports` object when wrapping in an IIFE to avoid ReferenceError.\n const iifeWrap = (src: string) => `(function(exports,module){${src}})({},{exports:{}});`;\n\n // Inject init-server into [turbopack]_runtime.js files (node.js SSR + build)\n for (const runtimeFile of serverRuntimeFiles) {\n const origSource = fs.readFileSync(runtimeFile, 'utf8');\n const updatedSource = [\n envInline,\n iifeWrap(initServerSrc),\n origSource,\n ].join('\\n');\n fs.writeFileSync(runtimeFile, updatedSource);\n debug(`injected init-server into turbopack runtime: ${runtimeFile}`);\n }\n\n // Inject init-edge into edge-wrapper files (edge runtime — no node builtins)\n for (const wrapperFile of edgeWrapperFiles) {\n const origSource = fs.readFileSync(wrapperFile, 'utf8');\n const updatedSource = [\n envInline,\n iifeWrap(initEdgeSrc),\n origSource,\n ].join('\\n');\n fs.writeFileSync(wrapperFile, updatedSource);\n debug(`injected init-edge into edge wrapper: ${wrapperFile}`);\n }\n}\n\nexport function isInjectedTurbopackRuntime() {\n return injectedTurbopackRuntime;\n}\n","/* eslint-disable no-console */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { NextConfig } from 'next';\n\nimport {\n getRedactionMapInfo, initVarlockEnv, redactSensitiveConfig, scanForLeaks, varlockSettings,\n} from 'varlock/env';\nimport { patchGlobalConsole } from 'varlock/patch-console';\nimport { patchGlobalServerResponse } from 'varlock/patch-server-response';\n\nimport { type SerializedEnvGraph } from 'varlock';\nimport { createWebpackConfigFn } from './webpack-plugin';\nimport { injectVarlockInitIntoTurbopackRuntime, isInjectedTurbopackRuntime } from './turbopack-runtime-inject';\n\n// make sure varlock has actually loaded the env files\n// NOTE - we don't need to call `initVarlockEnv` because the next-env-compat has already been loaded and called it\nif (!process.env.__VARLOCK_ENV) {\n console.error([\n '🚨 process.env.__VARLOCK_ENV is not set 🚨',\n '',\n 'To use this plugin, you must override @next/env with @varlock/next-integration',\n 'See https://varlock.dev/integrations/nextjs for more information',\n '',\n ].join('\\n'));\n throw new Error('VarlockNextWebpackPlugin: __VARLOCK_ENV is not set');\n}\n\npatchGlobalConsole();\n\n// Turbopack detection at module level — needed to apply patches in worker processes\n// (the config function only runs in the main process, but workers also load this module)\nconst IS_TURBOPACK = !!(\n process.env.TURBOPACK\n || process.env.TURBOPACK_DEV\n || process.env.TURBOPACK_BUILD\n || process.env.npm_config_turbopack\n);\n\n// For turbopack, apply server response patching at module level so it takes effect\n// in worker processes (which serve actual responses). The config function's turbopack\n// branch only runs in the main process, which doesn't handle HTTP responses.\nif (IS_TURBOPACK && varlockSettings.preventLeaks) {\n patchGlobalServerResponse({\n ignoreUrlPatterns: [\n /^\\/__nextjs_source-map\\?.*/, // sourcemaps\n /[?&]_rsc=/, // RSC payloads are server-side and expected to contain sensitive data\n ],\n // always redact in dev to avoid crashing the dev server; prod builds override via init bundles\n redactInsteadOfThrow: true,\n });\n}\n\nconst IS_WORKER = !!process.env.NEXT_PRIVATE_WORKER;\nfunction debug(...args: Array<any>) {\n if (!process.env.DEBUG_VARLOCK_NEXT_INTEGRATION) return;\n console.log(\n 'plugin',\n IS_WORKER ? '[worker] ' : '[server]',\n '--',\n ...args,\n );\n}\ndebug('✨ LOADED @varlock/next-integration/plugin module!');\n\ntype VarlockPluginOptions = {\n // injectResolvedConfigAtBuildTime: boolean,\n};\n\nlet scannedStaticFiles = false;\nasync function scanStaticFiles(nextDirPath: string) {\n scannedStaticFiles = true;\n for await (const file of fs.promises.glob(`${nextDirPath}/**/*.html`)) {\n const fileContents = await fs.promises.readFile(file, 'utf8');\n scanForLeaks(fileContents, { method: 'nextjs scan static html files', file });\n }\n}\n\nlet scrubbedSourcemaps = false;\nasync function scrubSourcemaps(nextDirPath: string) {\n if (scrubbedSourcemaps) return;\n scrubbedSourcemaps = true;\n\n // build a list of sensitive values and their same-length replacements\n const envGraph: SerializedEnvGraph = JSON.parse(process.env.__VARLOCK_ENV || '{}');\n const sensitiveValues: Array<{ value: string, replacement: string }> = [];\n for (const itemKey in envGraph.config) {\n const item = envGraph.config[itemKey];\n if (item.isSensitive && item.value && typeof item.value === 'string' && item.value.length > 0) {\n // same-length replacement to preserve sourcemap column offsets\n sensitiveValues.push({\n value: item.value,\n replacement: '*'.repeat(item.value.length),\n });\n }\n }\n if (!sensitiveValues.length) {\n debug('no sensitive values to scrub from sourcemaps');\n return;\n }\n // sort longest first for maximal munch\n sensitiveValues.sort((a, b) => b.value.length - a.value.length);\n\n let scrubCount = 0;\n for await (const mapFile of fs.promises.glob(`${nextDirPath}/**/*.map`)) {\n const contents = await fs.promises.readFile(mapFile, 'utf8');\n let scrubbed = contents;\n for (const { value, replacement } of sensitiveValues) {\n scrubbed = scrubbed.replaceAll(value, replacement);\n }\n if (scrubbed !== contents) {\n await fs.promises.writeFile(mapFile, scrubbed);\n scrubCount++;\n }\n }\n debug(`scrubbed sensitive values from ${scrubCount} sourcemap files`);\n}\n\nlet scannedBuildOutput = false;\nasync function scanBuildOutputForLeaks(nextDirPath: string, opts?: { failBuild?: boolean }) {\n if (scannedBuildOutput) return;\n scannedBuildOutput = true;\n\n // varlockSettings may not be populated if initVarlockEnv hasn't run in this process,\n // so fall back to reading the setting directly from the env data\n let preventLeaks = varlockSettings.preventLeaks;\n if (preventLeaks === undefined && process.env.__VARLOCK_ENV) {\n try {\n const envGraph: SerializedEnvGraph = JSON.parse(process.env.__VARLOCK_ENV);\n preventLeaks = envGraph.settings?.preventLeaks;\n } catch { /* ignore */ }\n }\n // Ensure the redaction map is populated so scanForLeaks knows what to look for.\n // initVarlockEnv may not have run in this process (the plugin's main process).\n if (process.env.__VARLOCK_ENV) {\n // eslint-disable-next-line @stylistic/max-statements-per-line\n try { initVarlockEnv(); } catch { /* ignore if already initialized or fails */ }\n }\n const redactionInfo = getRedactionMapInfo();\n debug(`scanBuildOutputForLeaks: preventLeaks=${preventLeaks}, redactionInfo=${JSON.stringify(redactionInfo)}`);\n if (!preventLeaks) return;\n\n const leakedFiles: Array<string> = [];\n let scannedCount = 0;\n\n // scan JS chunks in .next/static/chunks/ — these are client-facing bundles\n // that should never contain sensitive values\n for await (const file of fs.promises.glob(`${nextDirPath}/static/chunks/**/*.js`)) {\n scannedCount++;\n const fileContents = await fs.promises.readFile(file, 'utf8');\n try {\n scanForLeaks(fileContents, {\n method: 'nextjs post-build scan (static chunks)',\n file,\n });\n } catch (err) {\n leakedFiles.push(file);\n // redact the file so the leak doesn't ship\n await fs.promises.writeFile(file, redactSensitiveConfig(fileContents));\n }\n }\n\n debug(`scanned ${scannedCount} static chunk files in ${nextDirPath}/static/chunks/`);\n\n // scan prerendered HTML files (client-facing static output)\n // NOTE: .rsc and .body files are server-side (RSC payloads) and are expected\n // to access sensitive data, so we don't scan those\n for (const ext of ['html']) {\n for await (const file of fs.promises.glob(`${nextDirPath}/**/*.${ext}`)) {\n scannedCount++;\n const fileContents = await fs.promises.readFile(file, 'utf8');\n try {\n scanForLeaks(fileContents, {\n method: `nextjs post-build scan (.${ext})`,\n file,\n });\n } catch (err) {\n leakedFiles.push(file);\n await fs.promises.writeFile(file, redactSensitiveConfig(fileContents));\n }\n }\n }\n\n debug(`scanned ${scannedCount} total build output files`);\n\n if (leakedFiles.length > 0) {\n const msg = `[varlock] ⚠️ found and redacted leaked secrets in ${leakedFiles.length} build output file(s):\\n${leakedFiles.map((f) => ` - ${f}`).join('\\n')}`;\n if (opts?.failBuild) {\n throw new Error(msg);\n }\n console.error(msg);\n } else {\n debug('✅ no leaks found in build output');\n }\n}\n\n// not all file writes go through this, at least in Next 15\n// (likely because webpack and prerendering are happening in workers)\n// but we can use this to monitor writing of certain files and give ourselves a \"hook\"\n// which we can then scan existing files\nfunction patchGlobalFsMethods() {\n debug('patching global fs methods');\n // patch fs.promises.writeFile\n const origWriteFileFn = fs.promises.writeFile;\n fs.promises.writeFile = async function dmnoPatchedWriteFile(...args) {\n const filePath = args[0].toString();\n debug('fs.promises.writeFile:', filePath);\n\n // BUILD_ID is written after turbopack compilation completes but before pre-rendering.\n // This is our hook to inject the init bundle into turbopack runtime files.\n if (!isInjectedTurbopackRuntime() && filePath.endsWith('/.next/export-detail.json')) {\n const nextDirPath = filePath.substring(0, filePath.lastIndexOf('/'));\n injectVarlockInitIntoTurbopackRuntime(nextDirPath);\n }\n\n if (filePath.endsWith('/.next/next-server.js.nft.json') && !scannedStaticFiles) {\n const nextDirPath = filePath.substring(0, filePath.lastIndexOf('/'));\n await scanStaticFiles(nextDirPath);\n }\n // next-server.js.nft.json is written near the end of the build, after prerendering (webpack)\n // prerender-manifest.json is written after \"Generating static pages\" completes (turbopack + webpack)\n if (\n filePath.endsWith('/.next/next-server.js.nft.json')\n || filePath.endsWith('/.next/prerender-manifest.json')\n ) {\n const nextDirPath = filePath.substring(0, filePath.lastIndexOf('/'));\n if (!scrubbedSourcemaps) await scrubSourcemaps(nextDirPath);\n if (!scannedBuildOutput) await scanBuildOutputForLeaks(nextDirPath, { failBuild: true });\n }\n\n return origWriteFileFn.call(this, ...args);\n };\n\n // also patch sync version in case turbopack uses it\n const origWriteFileSyncFn = fs.writeFileSync;\n fs.writeFileSync = function dmnoPatchedWriteFileSync(...args: Parameters<typeof fs.writeFileSync>) {\n const filePath = args[0].toString();\n debug('fs.writeFileSync:', filePath);\n\n if (!isInjectedTurbopackRuntime() && filePath.endsWith('/.next/diagnostics/build-diagnostics.json')) {\n const nextDirPath = filePath.substring(0, filePath.lastIndexOf('/'));\n injectVarlockInitIntoTurbopackRuntime(nextDirPath);\n }\n\n return origWriteFileSyncFn.call(this, ...args);\n };\n}\n\n\nexport type NextConfigFunction = (\n phase: string,\n defaults: { defaultConfig: NextConfig },\n) => NextConfig | PromiseLike<NextConfig>;\n\n\n// we make this a plugin a function because we'll likely end up adding some options\nexport function varlockNextConfigPlugin(_pluginOptions?: VarlockPluginOptions) {\n // nextjs doesnt have a proper plugin system :(\n // so we use a function which takes in a config object and returns an augmented one\n return (nextConfig: any | NextConfig | NextConfigFunction): NextConfigFunction => {\n debug('varlockNextConfigPlugin init fn');\n\n return async (phase: string, defaults: { defaultConfig: NextConfig }) => {\n let resolvedNextConfig: NextConfig;\n if (typeof nextConfig === 'function') {\n const nextConfigFnResult = nextConfig(phase, defaults);\n resolvedNextConfig = await nextConfigFnResult;\n } else {\n resolvedNextConfig = nextConfig;\n }\n\n // Next 16+ uses Turbopack by default for dev, but may not set TURBOPACK env var\n const isTurbopack = !!(\n process.env.TURBOPACK\n || process.env.TURBOPACK_DEV\n || process.env.TURBOPACK_BUILD\n || process.env.npm_config_turbopack\n );\n const isBuild = phase === 'phase-production-build';\n debug(`turbopack detection: TURBOPACK=${process.env.TURBOPACK}, TURBOPACK_DEV=${process.env.TURBOPACK_DEV}, TURBOPACK_BUILD=${process.env.TURBOPACK_BUILD}, phase=${phase}, isTurbopack=${isTurbopack}, isBuild=${isBuild}`);\n\n // For production builds, schedule a post-build scan as a safety net.\n // The fs.writeFile patches may not intercept all writes (workers), and\n // BUILD_ID is written before prerendering completes. beforeExit fires\n // after the build finishes, ensuring all output files exist.\n if (isBuild) {\n process.once('beforeExit', () => {\n const nextDirPath = path.resolve(process.cwd(), '.next');\n const scanPromises: Array<Promise<void>> = [];\n if (!scrubbedSourcemaps) scanPromises.push(scrubSourcemaps(nextDirPath));\n if (!scannedBuildOutput) scanPromises.push(scanBuildOutputForLeaks(nextDirPath, { failBuild: true }));\n if (scanPromises.length > 0) {\n // The async work keeps the event loop alive, and beforeExit\n // will fire again once it completes (but the guards prevent re-runs)\n Promise.all(scanPromises).catch((err) => {\n console.error('[varlock] post-build scan failed:', err);\n process.exitCode = 1;\n });\n }\n });\n }\n\n if (isTurbopack) {\n debug('turbopack detected, injecting loader rules');\n // only patch fs methods during builds — they create \"hooks\" for post-build\n // scanning/scrubbing and are unnecessary (and noisy) during dev\n if (isBuild) patchGlobalFsMethods();\n\n // turbopack config can be under `turbopack` (Next 15+) or `experimental.turbo` (older)\n let turbopackConfig = (resolvedNextConfig as any).turbopack\n ?? (resolvedNextConfig as any).experimental?.turbo;\n\n if (!turbopackConfig) {\n turbopackConfig = {};\n (resolvedNextConfig as any).turbopack = turbopackConfig;\n }\n\n // inject loader rules\n const loaderRule = {\n loaders: [require.resolve('./loader')],\n };\n turbopackConfig.rules ||= {};\n turbopackConfig.rules['*.{js,jsx,ts,tsx,mjs,mts}'] = loaderRule;\n\n // Turbopack can't resolve symlinked packages (e.g. link: or workspace: installs).\n // If varlock is symlinked, we copy dist files into node_modules/.varlock/ as real\n // files and set up resolve aliases so turbopack can find them.\n const varlockNodeModulesPath = path.resolve(process.cwd(), 'node_modules/varlock');\n let isSymlinked = false;\n try {\n isSymlinked = fs.lstatSync(varlockNodeModulesPath).isSymbolicLink();\n } catch { /* not found — might be hoisted or nested, skip */ }\n\n if (isSymlinked) {\n debug('varlock is symlinked, copying dist files for turbopack');\n const varlockDistDir = path.resolve(path.dirname(require.resolve('varlock/env')), '..');\n const varlockRoot = path.resolve(varlockDistDir, '..');\n const cacheDir = path.resolve(process.cwd(), 'node_modules/.varlock');\n const cacheDistDir = path.join(cacheDir, 'dist');\n try {\n fs.mkdirSync(cacheDir, { recursive: true });\n // copy dist/ and package.json so turbopack can resolve subpath exports\n fs.cpSync(varlockDistDir, cacheDistDir, { recursive: true });\n fs.copyFileSync(path.join(varlockRoot, 'package.json'), path.join(cacheDir, 'package.json'));\n debug('copied varlock package files to', cacheDir);\n } catch (err) {\n console.warn('[varlock] failed to copy varlock package files:', err);\n }\n\n turbopackConfig.resolveAlias ||= {};\n turbopackConfig.resolveAlias['varlock/env'] = './node_modules/.varlock/dist/runtime/env.js';\n turbopackConfig.resolveAlias['varlock/patch-console'] = './node_modules/.varlock/dist/runtime/patch-console.js';\n turbopackConfig.resolveAlias['varlock/patch-server-response'] = './node_modules/.varlock/dist/runtime/patch-server-response.js';\n turbopackConfig.resolveAlias['varlock/patch-response'] = './node_modules/.varlock/dist/runtime/patch-response.js';\n turbopackConfig.resolveAlias['varlock/init-server'] = './node_modules/.varlock/dist/runtime/init-server.cjs';\n turbopackConfig.resolveAlias['varlock/init-edge'] = './node_modules/.varlock/dist/runtime/init-edge.cjs';\n debug('set resolveAlias for varlock subpaths -> ./node_modules/.varlock/dist/...');\n } else {\n debug('varlock is not symlinked, turbopack can resolve it natively');\n }\n }\n\n return {\n ...resolvedNextConfig,\n ...isTurbopack && {\n turbopack: (resolvedNextConfig as any).turbopack,\n },\n ...!IS_TURBOPACK && {\n webpack: createWebpackConfigFn(resolvedNextConfig, patchGlobalFsMethods, debug, isBuild),\n },\n };\n };\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/webpack-plugin.ts","../src/turbopack-runtime-inject.ts","../src/plugin.ts"],"names":["debug","patchGlobalFsMethods","varlockSettings","patchGlobalServerResponse","scanForLeaks","fs","redactSensitiveConfig","path","patchGlobalConsole","initVarlockEnv","getRedactionMapInfo"],"mappings":";;;;;;;;;;;;;;;;;;;;AAUA,IAAM,mBAAA,GAAsB,0BAAA;AAO5B,IAAI,sBAAA;AACJ,SAAS,8BAA8BA,MAAAA,EAAsC;AAC3E,EAAA,OAAO,IAAI,KAAA,CAAM,EAAC,EAA6B;AAAA,IAC7C,QAAQ,OAAA,EAAS;AACf,MAAA,sBAAA,GAAyB,IAAA,CAAK,KAAA,CAAM,OAAA,CAAQ,GAAA,CAAI,iBAAiB,IAAI,CAAA;AACrE,MAAA,MAAM,cAAc,EAAC;AACrB,MAAA,KAAA,MAAW,OAAA,IAAW,uBAAuB,MAAA,EAAQ;AACnD,QAAA,MAAM,IAAA,GAAO,sBAAA,CAAuB,MAAA,CAAO,OAAO,CAAA;AAClD,QAAA,IAAI,CAAC,IAAA,CAAK,WAAA,cAAyB,IAAA,CAAK,CAAA,IAAA,EAAO,OAAO,CAAA,CAAE,CAAA;AAAA,MAC1D;AACA,MAAAA,MAAAA,CAAM,qCAAqC,WAAW,CAAA;AACtD,MAAA,OAAO,WAAA;AAAA,IACT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AC,YAAA,IAAgB;AAAA,UAClB,OAAA,EAAS,qBAAA,CAAsB,kBAAA,EAAoB,oBAAA,EAAsBA,QAAO,OAAO;AAAA;AACzF,OACF;AAAA,IACF,CAAA;AAAA,EACF,CAAA;AACF","file":"plugin.js","sourcesContent":["import fs from 'node:fs';\n\nimport {\n redactSensitiveConfig, scanForLeaks, varlockSettings,\n} from 'varlock/env';\nimport { patchGlobalServerResponse } from 'varlock/patch-server-response';\n\nimport { type SerializedEnvGraph } from 'varlock';\nimport type { NextConfig } from 'next';\n\nconst WEBPACK_PLUGIN_NAME = 'VarlockNextWebpackPlugin';\n\n// We use a proxy object for the static replacements that we pass to webpack.DefinePlugin\n// because this plugin/webpack code is not invoked again when env files change\n// instead next is direcly messing with the existing plugins for their own changes\n// so instead we use a proxy object, and grab the values off of process.env.__VARLOCK_ENV\n// which will have been updated by our next-env-compat code\nlet latestLoadedVarlockEnv: SerializedEnvGraph | undefined;\nfunction createStaticReplacementsProxy(debug: (...args: Array<any>) => void) {\n return new Proxy({} as Record<string, string>, {\n ownKeys(_target) {\n latestLoadedVarlockEnv = JSON.parse(process.env.__VARLOCK_ENV || '{}') as SerializedEnvGraph;\n const replaceKeys = [] as Array<string>;\n for (const itemKey in latestLoadedVarlockEnv.config) {\n const item = latestLoadedVarlockEnv.config[itemKey];\n if (!item.isSensitive) replaceKeys.push(`ENV.${itemKey}`);\n }\n debug('reloaded static replacements keys', replaceKeys);\n return replaceKeys;\n },\n getOwnPropertyDescriptor(_target, prop) {\n const itemKey = prop.toString().split('.')[1];\n const item = latestLoadedVarlockEnv?.config[itemKey];\n if (!item || item.isSensitive) return;\n return {\n value: '', // this value is not used, the get handler will return the value\n writable: false,\n enumerable: true,\n configurable: true,\n };\n },\n get(_target, prop) {\n const itemKey = prop.toString().split('.')[1];\n const item = latestLoadedVarlockEnv?.config[itemKey];\n if (item && !item.isSensitive) return JSON.stringify(item.value);\n },\n });\n}\n\nexport function createWebpackConfigFn(\n resolvedNextConfig: NextConfig,\n patchGlobalFsMethods: () => void,\n debug: (...args: Array<any>) => void,\n isBuild: boolean,\n) {\n const staticReplacementsProxy = createStaticReplacementsProxy(debug);\n\n return function webpackConfigFn(webpackConfig: any, options: any) {\n debug('varlockNextConfigPlugin webpack config patching');\n\n const { dev } = options; // also available - isServer, nextRuntime\n\n // only patch fs methods during builds — they create \"hooks\" for post-build\n // scanning/scrubbing and are unnecessary during dev\n if (isBuild) patchGlobalFsMethods();\n\n if (varlockSettings.preventLeaks) {\n // have to wait to run this until here when we know if this is dev mode or not\n patchGlobalServerResponse({\n ignoreUrlPatterns: [\n /^\\/__nextjs_source-map\\?.*/, // sourcemaps\n /[?&]_rsc=/, // RSC payloads are server-side and expected to contain sensitive data\n ],\n // in dev mode, we redact the secrets rather than throwing, because otherwise the dev server crashes\n redactInsteadOfThrow: dev,\n });\n }\n\n // webpack itself is passed in so we dont have to import it (or make it a dependency)\n const webpack = options.webpack;\n\n // apply existing user customizations if there are any\n if (resolvedNextConfig.webpack) {\n webpackConfig = resolvedNextConfig.webpack(webpackConfig, options);\n }\n\n if (!process.env.__VARLOCK_ENV) throw new Error('VarlockNextWebpackPlugin: __VARLOCK_ENV is not set');\n\n // Add per-file init guard for server (non-edge) compilations.\n // Pre-rendering workers may receive compiled code via IPC rather than loading\n // runtime files from disk, so runtime injection alone isn't sufficient.\n // The loader ensures initVarlockEnv() and patchGlobalConsole() run in every worker.\n // alwaysRepatchConsole: in webpack, React wraps console for RSC dev replay AFTER\n // our initial patch in the runtime file, so we re-patch in each file to ensure\n // our redaction wraps React's wrapper. (Turbopack doesn't need this.)\n if (options.isServer && options.nextRuntime !== 'edge') {\n webpackConfig.module.rules.push({\n test: /\\.(js|jsx|ts|tsx|mjs|mts)$/,\n exclude: /node_modules/,\n use: [\n {\n loader: require.resolve('./loader'),\n options: { bundler: 'webpack' },\n },\n ],\n });\n }\n // Edge compilation: also re-patch console to wrap React's RSC dev replay wrapper.\n // Edge can't use require(), so we call globalThis.__varlockPatchConsole which the\n // init-edge bundle exposes after running.\n if (options.isServer && options.nextRuntime === 'edge') {\n webpackConfig.module.rules.push({\n test: /\\.(js|jsx|ts|tsx|mjs|mts)$/,\n exclude: /node_modules/,\n use: [\n {\n loader: require.resolve('./loader'),\n options: { bundler: 'webpack', isEdge: true },\n },\n ],\n });\n }\n\n // Set up build-time replacements / rewrites - using webpack.DefinePlugin and a proxy\n // TODO: use shared helpers from core library?\n debug('adding ENV.xxx static replacements proxy object');\n webpackConfig.plugins.push(new webpack.DefinePlugin(staticReplacementsProxy));\n\n if (varlockSettings.preventLeaks) {\n webpackConfig.plugins.push({\n apply(compiler: any) {\n compiler.hooks.assetEmitted.tap(WEBPACK_PLUGIN_NAME, (_file: any, assetDetails: any) => {\n const { content, targetPath } = assetDetails;\n\n if (\n targetPath.includes('/.next/static/chunks/')\n || targetPath.endsWith('.html')\n // .rsc and .body are server-side (RSC payloads), not client-facing\n ) {\n // NOTE - in dev mode the request hangs on the error, but the console error should help\n // and during a build, it will actually fail the build\n try {\n scanForLeaks(content, {\n method: '@varlock/nextjs-integration/plugin - assetEmitted hook',\n file: targetPath,\n });\n } catch (err) {\n if (dev) {\n // overwrite file with redacted version\n fs.writeFileSync(targetPath, redactSensitiveConfig(content.toString()));\n } else {\n throw err;\n }\n }\n }\n });\n },\n });\n }\n\n // Inject varlock init into webpack runtime files.\n // We prepend the self-contained init bundle as raw JS so it runs before any module code.\n // Server runtimes get the full init (with server-response patching),\n // edge runtimes get the edge-safe init (no node:zlib/node:http).\n function injectVarlockInitIntoWebpackRuntime(edgeRuntime = false) {\n return function assetUpdateFn(origSource: any) {\n const origSourceStr = origSource.source();\n\n const initBundleName = edgeRuntime ? 'init-edge' : 'init-server';\n const injectorPath = require.resolve(`varlock/${initBundleName}`);\n const injectorSrc = fs.readFileSync(injectorPath, 'utf8');\n\n // inline the resolved env so it's baked into the build\n // this removes the need for a .env.production.local file on platforms like Vercel\n const rawEnv = process.env.__VARLOCK_ENV;\n const envInline = rawEnv\n ? `process.env.__VARLOCK_ENV = process.env.__VARLOCK_ENV || ${JSON.stringify(rawEnv)};`\n : '';\n\n const updatedSourceStr = [\n envInline,\n // Wrap in IIFE to avoid symbol collisions when bundlers concatenate files.\n // Provide dummy exports/module since the CJS bundle uses `exports.X = ...`\n `(function(exports,module){${injectorSrc}})({},{exports:{}});`,\n origSourceStr,\n ].join('\\n');\n\n return new webpack.sources.RawSource(updatedSourceStr);\n };\n }\n\n const isEdgeRuntime = options.nextRuntime === 'edge';\n webpackConfig.plugins.push({\n apply(compiler: any) {\n compiler.hooks.thisCompilation.tap(WEBPACK_PLUGIN_NAME, (compilation: any) => {\n compilation.hooks.processAssets.tap(\n {\n name: WEBPACK_PLUGIN_NAME,\n stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,\n },\n () => {\n if (isEdgeRuntime) {\n // Edge compilation — only inject the edge-safe init bundle (no node builtins)\n if (compilation.getAsset('edge-runtime-webpack.js')) {\n compilation.updateAsset('edge-runtime-webpack.js', injectVarlockInitIntoWebpackRuntime(true));\n }\n // Edge compilation also has webpack-runtime.js — inject init-edge there too\n for (const name of ['webpack-runtime.js', '../webpack-runtime.js']) {\n if (compilation.getAsset(name)) {\n compilation.updateAsset(name, injectVarlockInitIntoWebpackRuntime(true));\n }\n }\n } else if (options.isServer) {\n // Server (node.js) compilation — inject full init with server-response patching\n for (const name of ['webpack-runtime.js', '../webpack-runtime.js', 'webpack-api-runtime.js', '../webpack-api-runtime.js']) {\n if (compilation.getAsset(name)) {\n compilation.updateAsset(name, injectVarlockInitIntoWebpackRuntime());\n }\n }\n }\n },\n );\n });\n },\n });\n\n return webpackConfig; // must return the modified config\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nfunction debug(...args: Array<any>) {\n if (!process.env.DEBUG_VARLOCK_NEXT_INTEGRATION) return;\n // eslint-disable-next-line no-console\n console.log('[varlock]', ...args);\n}\n\n/**\n * Inject varlock init bundle into turbopack runtime files (analogous to webpack runtime injection).\n * Turbopack writes `[turbopack]_runtime.js` files during compilation — these are loaded by\n * the deployed server before any user code runs, making them the ideal injection point.\n *\n * Note: pre-rendering workers during builds receive compiled code via IPC (not from disk),\n * so this injection only takes effect for the deployed server. Build-time init is handled\n * by the turbopack loader's init guard snippet.\n */\nlet injectedTurbopackRuntime = false;\nexport function injectVarlockInitIntoTurbopackRuntime(nextDirPath: string) {\n if (injectedTurbopackRuntime) return;\n\n const rawEnv = process.env.__VARLOCK_ENV;\n if (!rawEnv) {\n return;\n }\n\n // Find turbopack runtime files ([turbopack]_runtime.js) and edge-wrapper files.\n // Node.js SSR/build uses [turbopack]_runtime.js, while edge runtime uses\n // edge-wrapper JS files (no [turbopack]_runtime.js exists for edge).\n const serverRuntimeFiles: Array<string> = [];\n const edgeWrapperFiles: Array<string> = [];\n const walkDir = (dir: string) => {\n if (!fs.existsSync(dir)) return;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (entry.isDirectory()) {\n walkDir(path.join(dir, entry.name));\n } else if (entry.name === '[turbopack]_runtime.js') {\n serverRuntimeFiles.push(path.join(dir, entry.name));\n } else if (entry.name.includes('edge-wrapper') && entry.name.endsWith('.js')) {\n edgeWrapperFiles.push(path.join(dir, entry.name));\n }\n }\n };\n walkDir(nextDirPath);\n\n debug(`turbopack runtime injection: found ${serverRuntimeFiles.length} server runtime files, ${edgeWrapperFiles.length} edge wrapper files`);\n\n if (!serverRuntimeFiles.length) {\n // Runtime files may not exist yet — turbopack (Rust) writes them directly.\n // We'll retry on subsequent fs writes until they appear.\n return;\n }\n\n // Mark as done so we don't retry\n injectedTurbopackRuntime = true;\n\n // Load both init bundles — server (full, node:zlib/node:http) and edge (no node builtins)\n const initServerSrc = fs.readFileSync(require.resolve('varlock/init-server'), 'utf8');\n const initEdgeSrc = fs.readFileSync(require.resolve('varlock/init-edge'), 'utf8');\n const envInline = `process.env.__VARLOCK_ENV = process.env.__VARLOCK_ENV || ${JSON.stringify(rawEnv)};`;\n\n // The CJS init bundles use `exports.X = ...` at the end, so we must provide\n // a dummy `exports` object when wrapping in an IIFE to avoid ReferenceError.\n const iifeWrap = (src: string) => `(function(exports,module){${src}})({},{exports:{}});`;\n\n // Inject init-server into [turbopack]_runtime.js files (node.js SSR + build)\n for (const runtimeFile of serverRuntimeFiles) {\n const origSource = fs.readFileSync(runtimeFile, 'utf8');\n const updatedSource = [\n envInline,\n iifeWrap(initServerSrc),\n origSource,\n ].join('\\n');\n fs.writeFileSync(runtimeFile, updatedSource);\n debug(`injected init-server into turbopack runtime: ${runtimeFile}`);\n }\n\n // Inject init-edge into edge-wrapper files (edge runtime — no node builtins)\n for (const wrapperFile of edgeWrapperFiles) {\n const origSource = fs.readFileSync(wrapperFile, 'utf8');\n const updatedSource = [\n envInline,\n iifeWrap(initEdgeSrc),\n origSource,\n ].join('\\n');\n fs.writeFileSync(wrapperFile, updatedSource);\n debug(`injected init-edge into edge wrapper: ${wrapperFile}`);\n }\n}\n\nexport function isInjectedTurbopackRuntime() {\n return injectedTurbopackRuntime;\n}\n","/* eslint-disable no-console */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { NextConfig } from 'next';\n\nimport {\n getRedactionMapInfo, initVarlockEnv, redactSensitiveConfig, scanForLeaks, varlockSettings,\n} from 'varlock/env';\nimport { patchGlobalConsole } from 'varlock/patch-console';\nimport { patchGlobalServerResponse } from 'varlock/patch-server-response';\n\nimport { type SerializedEnvGraph } from 'varlock';\nimport { createWebpackConfigFn } from './webpack-plugin';\nimport { injectVarlockInitIntoTurbopackRuntime, isInjectedTurbopackRuntime } from './turbopack-runtime-inject';\n\n// make sure varlock has actually loaded the env files\n// NOTE - we don't need to call `initVarlockEnv` because the next-env-compat has already been loaded and called it\nif (!process.env.__VARLOCK_ENV) {\n console.error([\n '🚨 process.env.__VARLOCK_ENV is not set 🚨',\n '',\n 'To use this plugin, you must override @next/env with @varlock/next-integration',\n 'See https://varlock.dev/integrations/nextjs for more information',\n '',\n ].join('\\n'));\n throw new Error('VarlockNextWebpackPlugin: __VARLOCK_ENV is not set');\n}\n\npatchGlobalConsole();\n\n// Turbopack detection at module level — needed to apply patches in worker processes\n// (the config function only runs in the main process, but workers also load this module)\nconst IS_TURBOPACK = !!(\n process.env.TURBOPACK\n || process.env.TURBOPACK_DEV\n || process.env.TURBOPACK_BUILD\n || process.env.npm_config_turbopack\n);\n\n// For turbopack, apply server response patching at module level so it takes effect\n// in worker processes (which serve actual responses). The config function's turbopack\n// branch only runs in the main process, which doesn't handle HTTP responses.\nif (IS_TURBOPACK && varlockSettings.preventLeaks) {\n patchGlobalServerResponse({\n ignoreUrlPatterns: [\n /^\\/__nextjs_source-map\\?.*/, // sourcemaps\n /[?&]_rsc=/, // RSC payloads are server-side and expected to contain sensitive data\n ],\n // always redact in dev to avoid crashing the dev server; prod builds override via init bundles\n redactInsteadOfThrow: true,\n });\n}\n\nconst IS_WORKER = !!process.env.NEXT_PRIVATE_WORKER;\nfunction debug(...args: Array<any>) {\n if (!process.env.DEBUG_VARLOCK_NEXT_INTEGRATION) return;\n console.log(\n 'plugin',\n IS_WORKER ? '[worker] ' : '[server]',\n '--',\n ...args,\n );\n}\ndebug('✨ LOADED @varlock/next-integration/plugin module!');\n\ntype VarlockPluginOptions = {\n // injectResolvedConfigAtBuildTime: boolean,\n};\n\nlet scannedStaticFiles = false;\nasync function scanStaticFiles(nextDirPath: string) {\n scannedStaticFiles = true;\n for await (const file of fs.promises.glob(`${nextDirPath}/**/*.html`)) {\n const fileContents = await fs.promises.readFile(file, 'utf8');\n scanForLeaks(fileContents, { method: 'nextjs scan static html files', file });\n }\n}\n\nlet scrubbedSourcemaps = false;\nasync function scrubSourcemaps(nextDirPath: string) {\n if (scrubbedSourcemaps) return;\n scrubbedSourcemaps = true;\n\n // build a list of sensitive values and their same-length replacements\n const envGraph: SerializedEnvGraph = JSON.parse(process.env.__VARLOCK_ENV || '{}');\n const sensitiveValues: Array<{ value: string, replacement: string }> = [];\n for (const itemKey in envGraph.config) {\n const item = envGraph.config[itemKey];\n if (item.isSensitive && item.value && typeof item.value === 'string' && item.value.length > 0) {\n // same-length replacement to preserve sourcemap column offsets\n sensitiveValues.push({\n value: item.value,\n replacement: '*'.repeat(item.value.length),\n });\n }\n }\n if (!sensitiveValues.length) {\n debug('no sensitive values to scrub from sourcemaps');\n return;\n }\n // sort longest first for maximal munch\n sensitiveValues.sort((a, b) => b.value.length - a.value.length);\n\n let scrubCount = 0;\n for await (const mapFile of fs.promises.glob(`${nextDirPath}/**/*.map`)) {\n const contents = await fs.promises.readFile(mapFile, 'utf8');\n let scrubbed = contents;\n for (const { value, replacement } of sensitiveValues) {\n scrubbed = scrubbed.replaceAll(value, replacement);\n }\n if (scrubbed !== contents) {\n await fs.promises.writeFile(mapFile, scrubbed);\n scrubCount++;\n }\n }\n debug(`scrubbed sensitive values from ${scrubCount} sourcemap files`);\n}\n\nlet scannedBuildOutput = false;\nasync function scanBuildOutputForLeaks(nextDirPath: string, opts?: { failBuild?: boolean }) {\n if (scannedBuildOutput) return;\n scannedBuildOutput = true;\n\n // varlockSettings may not be populated if initVarlockEnv hasn't run in this process,\n // so fall back to reading the setting directly from the env data\n let preventLeaks = varlockSettings.preventLeaks;\n if (preventLeaks === undefined && process.env.__VARLOCK_ENV) {\n try {\n const envGraph: SerializedEnvGraph = JSON.parse(process.env.__VARLOCK_ENV);\n preventLeaks = envGraph.settings?.preventLeaks;\n } catch { /* ignore */ }\n }\n // Ensure the redaction map is populated so scanForLeaks knows what to look for.\n // initVarlockEnv may not have run in this process (the plugin's main process).\n if (process.env.__VARLOCK_ENV) {\n // eslint-disable-next-line @stylistic/max-statements-per-line\n try { initVarlockEnv(); } catch { /* ignore if already initialized or fails */ }\n }\n const redactionInfo = getRedactionMapInfo();\n debug(`scanBuildOutputForLeaks: preventLeaks=${preventLeaks}, redactionInfo=${JSON.stringify(redactionInfo)}`);\n if (!preventLeaks) return;\n\n const leakedFiles: Array<string> = [];\n let scannedCount = 0;\n\n // scan JS chunks in .next/static/chunks/ — these are client-facing bundles\n // that should never contain sensitive values\n for await (const file of fs.promises.glob(`${nextDirPath}/static/chunks/**/*.js`)) {\n scannedCount++;\n const fileContents = await fs.promises.readFile(file, 'utf8');\n try {\n scanForLeaks(fileContents, {\n method: 'nextjs post-build scan (static chunks)',\n file,\n });\n } catch (err) {\n leakedFiles.push(file);\n // redact the file so the leak doesn't ship\n await fs.promises.writeFile(file, redactSensitiveConfig(fileContents));\n }\n }\n\n debug(`scanned ${scannedCount} static chunk files in ${nextDirPath}/static/chunks/`);\n\n // scan prerendered HTML files (client-facing static output)\n // NOTE: .rsc and .body files are server-side (RSC payloads) and are expected\n // to access sensitive data, so we don't scan those\n for (const ext of ['html']) {\n for await (const file of fs.promises.glob(`${nextDirPath}/**/*.${ext}`)) {\n scannedCount++;\n const fileContents = await fs.promises.readFile(file, 'utf8');\n try {\n scanForLeaks(fileContents, {\n method: `nextjs post-build scan (.${ext})`,\n file,\n });\n } catch (err) {\n leakedFiles.push(file);\n await fs.promises.writeFile(file, redactSensitiveConfig(fileContents));\n }\n }\n }\n\n debug(`scanned ${scannedCount} total build output files`);\n\n if (leakedFiles.length > 0) {\n const msg = `[varlock] ⚠️ found and redacted leaked secrets in ${leakedFiles.length} build output file(s):\\n${leakedFiles.map((f) => ` - ${f}`).join('\\n')}`;\n if (opts?.failBuild) {\n throw new Error(msg);\n }\n console.error(msg);\n } else {\n debug('✅ no leaks found in build output');\n }\n}\n\n// not all file writes go through this, at least in Next 15\n// (likely because webpack and prerendering are happening in workers)\n// but we can use this to monitor writing of certain files and give ourselves a \"hook\"\n// which we can then scan existing files\nfunction patchGlobalFsMethods() {\n debug('patching global fs methods');\n // patch fs.promises.writeFile\n const origWriteFileFn = fs.promises.writeFile;\n fs.promises.writeFile = async function dmnoPatchedWriteFile(...args) {\n const filePath = args[0].toString();\n debug('fs.promises.writeFile:', filePath);\n\n // BUILD_ID is written after turbopack compilation completes but before pre-rendering.\n // This is our hook to inject the init bundle into turbopack runtime files.\n if (!isInjectedTurbopackRuntime() && filePath.endsWith('/.next/export-detail.json')) {\n const nextDirPath = filePath.substring(0, filePath.lastIndexOf('/'));\n injectVarlockInitIntoTurbopackRuntime(nextDirPath);\n }\n\n if (filePath.endsWith('/.next/next-server.js.nft.json') && !scannedStaticFiles) {\n const nextDirPath = filePath.substring(0, filePath.lastIndexOf('/'));\n await scanStaticFiles(nextDirPath);\n }\n // next-server.js.nft.json is written near the end of the build, after prerendering (webpack)\n // prerender-manifest.json is written after \"Generating static pages\" completes (turbopack + webpack)\n if (\n filePath.endsWith('/.next/next-server.js.nft.json')\n || filePath.endsWith('/.next/prerender-manifest.json')\n ) {\n const nextDirPath = filePath.substring(0, filePath.lastIndexOf('/'));\n if (!scrubbedSourcemaps) await scrubSourcemaps(nextDirPath);\n if (!scannedBuildOutput) await scanBuildOutputForLeaks(nextDirPath, { failBuild: true });\n }\n\n return origWriteFileFn.call(this, ...args);\n };\n\n // also patch sync version in case turbopack uses it\n const origWriteFileSyncFn = fs.writeFileSync;\n fs.writeFileSync = function dmnoPatchedWriteFileSync(...args: Parameters<typeof fs.writeFileSync>) {\n const filePath = args[0].toString();\n debug('fs.writeFileSync:', filePath);\n\n if (!isInjectedTurbopackRuntime() && filePath.endsWith('/.next/diagnostics/build-diagnostics.json')) {\n const nextDirPath = filePath.substring(0, filePath.lastIndexOf('/'));\n injectVarlockInitIntoTurbopackRuntime(nextDirPath);\n }\n\n return origWriteFileSyncFn.call(this, ...args);\n };\n}\n\n\nexport type NextConfigFunction = (\n phase: string,\n defaults: { defaultConfig: NextConfig },\n) => NextConfig | PromiseLike<NextConfig>;\n\n\n// we make this a plugin a function because we'll likely end up adding some options\nexport function varlockNextConfigPlugin(_pluginOptions?: VarlockPluginOptions) {\n // nextjs doesnt have a proper plugin system :(\n // so we use a function which takes in a config object and returns an augmented one\n return (nextConfig: any | NextConfig | NextConfigFunction): NextConfigFunction => {\n debug('varlockNextConfigPlugin init fn');\n\n return async (phase: string, defaults: { defaultConfig: NextConfig }) => {\n let resolvedNextConfig: NextConfig;\n if (typeof nextConfig === 'function') {\n const nextConfigFnResult = nextConfig(phase, defaults);\n resolvedNextConfig = await nextConfigFnResult;\n } else {\n resolvedNextConfig = nextConfig;\n }\n\n // Next 16+ uses Turbopack by default for dev, but may not set TURBOPACK env var\n const isTurbopack = !!(\n process.env.TURBOPACK\n || process.env.TURBOPACK_DEV\n || process.env.TURBOPACK_BUILD\n || process.env.npm_config_turbopack\n );\n const isBuild = phase === 'phase-production-build';\n debug(`turbopack detection: TURBOPACK=${process.env.TURBOPACK}, TURBOPACK_DEV=${process.env.TURBOPACK_DEV}, TURBOPACK_BUILD=${process.env.TURBOPACK_BUILD}, phase=${phase}, isTurbopack=${isTurbopack}, isBuild=${isBuild}`);\n\n // For production builds, schedule a post-build scan as a safety net.\n // The fs.writeFile patches may not intercept all writes (workers), and\n // BUILD_ID is written before prerendering completes. beforeExit fires\n // after the build finishes, ensuring all output files exist.\n if (isBuild) {\n process.once('beforeExit', () => {\n const nextDirPath = path.resolve(process.cwd(), '.next');\n const scanPromises: Array<Promise<void>> = [];\n if (!scrubbedSourcemaps) scanPromises.push(scrubSourcemaps(nextDirPath));\n if (!scannedBuildOutput) scanPromises.push(scanBuildOutputForLeaks(nextDirPath, { failBuild: true }));\n if (scanPromises.length > 0) {\n // The async work keeps the event loop alive, and beforeExit\n // will fire again once it completes (but the guards prevent re-runs)\n Promise.all(scanPromises).catch((err) => {\n console.error('[varlock] post-build scan failed:', err);\n process.exitCode = 1;\n });\n }\n });\n }\n\n if (isTurbopack) {\n debug('turbopack detected, injecting loader rules');\n // only patch fs methods during builds — they create \"hooks\" for post-build\n // scanning/scrubbing and are unnecessary (and noisy) during dev\n if (isBuild) patchGlobalFsMethods();\n\n // turbopack config can be under `turbopack` (Next 15+) or `experimental.turbo` (older)\n let turbopackConfig = (resolvedNextConfig as any).turbopack\n ?? (resolvedNextConfig as any).experimental?.turbo;\n\n if (!turbopackConfig) {\n turbopackConfig = {};\n (resolvedNextConfig as any).turbopack = turbopackConfig;\n }\n\n // inject loader rules\n const loaderRule = {\n loaders: [require.resolve('./loader')],\n };\n turbopackConfig.rules ||= {};\n turbopackConfig.rules['*.{js,jsx,ts,tsx,mjs,mts}'] = loaderRule;\n\n // Turbopack can't resolve symlinked packages (e.g. link: or workspace: installs).\n // If varlock is symlinked, we copy dist files into node_modules/.varlock/ as real\n // files and set up resolve aliases so turbopack can find them.\n const varlockNodeModulesPath = path.resolve(process.cwd(), 'node_modules/varlock');\n let isSymlinked = false;\n try {\n isSymlinked = fs.lstatSync(varlockNodeModulesPath).isSymbolicLink();\n } catch { /* not found — might be hoisted or nested, skip */ }\n\n if (isSymlinked) {\n debug('varlock is symlinked, copying dist files for turbopack');\n const varlockDistDir = path.resolve(path.dirname(require.resolve('varlock/env')), '..');\n const varlockRoot = path.resolve(varlockDistDir, '..');\n const cacheDir = path.resolve(process.cwd(), 'node_modules/.varlock');\n const cacheDistDir = path.join(cacheDir, 'dist');\n try {\n fs.mkdirSync(cacheDir, { recursive: true });\n // copy dist/ and package.json so turbopack can resolve subpath exports\n fs.cpSync(varlockDistDir, cacheDistDir, { recursive: true });\n fs.copyFileSync(path.join(varlockRoot, 'package.json'), path.join(cacheDir, 'package.json'));\n debug('copied varlock package files to', cacheDir);\n } catch (err) {\n console.warn('[varlock] failed to copy varlock package files:', err);\n }\n\n turbopackConfig.resolveAlias ||= {};\n turbopackConfig.resolveAlias['varlock/env'] = './node_modules/.varlock/dist/runtime/env.js';\n turbopackConfig.resolveAlias['varlock/patch-console'] = './node_modules/.varlock/dist/runtime/patch-console.js';\n turbopackConfig.resolveAlias['varlock/patch-server-response'] = './node_modules/.varlock/dist/runtime/patch-server-response.js';\n turbopackConfig.resolveAlias['varlock/patch-response'] = './node_modules/.varlock/dist/runtime/patch-response.js';\n turbopackConfig.resolveAlias['varlock/init-server'] = './node_modules/.varlock/dist/runtime/init-server.cjs';\n turbopackConfig.resolveAlias['varlock/init-edge'] = './node_modules/.varlock/dist/runtime/init-edge.cjs';\n debug('set resolveAlias for varlock subpaths -> ./node_modules/.varlock/dist/...');\n } else {\n debug('varlock is not symlinked, turbopack can resolve it natively');\n }\n }\n\n return {\n ...resolvedNextConfig,\n ...isTurbopack && {\n turbopack: (resolvedNextConfig as any).turbopack,\n },\n ...!IS_TURBOPACK && {\n webpack: createWebpackConfigFn(resolvedNextConfig, patchGlobalFsMethods, debug, isBuild),\n },\n };\n };\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@varlock/nextjs-integration",
|
|
3
3
|
"description": "drop-in replacement for @next/env that uses varlock to load .env files with validation and extra security features",
|
|
4
|
-
"version": "0.3.
|
|
4
|
+
"version": "0.3.3",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "https://github.com/dmno-dev/varlock.git",
|
|
@@ -20,7 +20,8 @@
|
|
|
20
20
|
],
|
|
21
21
|
"scripts": {
|
|
22
22
|
"dev": "tsup --watch",
|
|
23
|
-
"build": "rm -rf dist && tsup"
|
|
23
|
+
"build": "rm -rf dist && tsup",
|
|
24
|
+
"typecheck": "tsc --noEmit"
|
|
24
25
|
},
|
|
25
26
|
"keywords": [
|
|
26
27
|
"varlock",
|
|
@@ -42,13 +43,13 @@
|
|
|
42
43
|
"node": ">=22"
|
|
43
44
|
},
|
|
44
45
|
"peerDependencies": {
|
|
45
|
-
"varlock": "^0.7.
|
|
46
|
+
"varlock": "^0.7.2",
|
|
46
47
|
"next": ">=14"
|
|
47
48
|
},
|
|
48
49
|
"devDependencies": {
|
|
49
50
|
"@types/node": "25.3.2",
|
|
50
51
|
"tsup": "^8.5.1",
|
|
51
|
-
"varlock": "^0.7.
|
|
52
|
+
"varlock": "^0.7.2",
|
|
52
53
|
"vitest": "^4.0.18"
|
|
53
54
|
}
|
|
54
55
|
}
|