{"version":3,"file":"parseFileContent.cjs","names":["getProjectRequire","loadEnvFile"],"sources":["../../../src/loadExternalFile/parseFileContent.ts"],"sourcesContent":["import { type Context, runInNewContext } from 'node:vm';\nimport * as esbuild from 'esbuild';\nimport { type LoadEnvFileOptions, loadEnvFile } from '../loadEnvFile';\nimport { getProjectRequire } from '../utils/ESMxCJSHelpers';\n\nexport type SandBoxContextOptions = {\n  envVarOptions?: LoadEnvFileOptions;\n  projectRequire?: NodeJS.Require;\n  additionalEnvVars?: Record<string, string>;\n  /**\n   * Map of specifier -> mocked export to be returned when code in the VM calls require(specifier).\n   * Example:\n   *   mocks: {\n   *     '@intlayer/config/built': { getConfig: () => ({}), Locales: {} }\n   *   }\n   */\n  mocks?: Record<string, any>;\n  /**\n   * Optional alias map if you want to redirect specifiers.\n   * Useful when user code imports a subpath you want to collapse.\n   * Example:\n   *   aliases: { '@intlayer/config/built': '@intlayer/config' }\n   */\n  aliases?: Record<string, string>;\n};\n\n// Inject only Node.js-specific globals that are absent from a plain V8 context.\n// JS built-ins (Object, Array, Promise, Math, Date, JSON, Symbol, etc.) are\n// provided automatically by runInNewContext — no need to copy them.\n// Copying all of globalThis would retain hundreds of references (including the\n// full module cache via `global`) inside every sandbox, causing a memory leak.\nconst NODE_GLOBALS = [\n  'Buffer',\n  'setTimeout',\n  'clearTimeout',\n  'setInterval',\n  'clearInterval',\n  'setImmediate',\n  'clearImmediate',\n  'queueMicrotask',\n  'URL',\n  'URLSearchParams',\n  'TextEncoder',\n  'TextDecoder',\n  'AbortController',\n  'AbortSignal',\n  'performance',\n  'fetch',\n  'crypto',\n  'structuredClone',\n] as const;\n\n/**\n * Cache of the project's React module (or the JSX-capturing fallback) keyed by\n * the require's resolution paths. Node does not cache *failed* resolutions, so\n * without this every sandbox creation in a non-React project (Vue, Svelte,\n * Angular…) pays a full node_modules walk that ends in a throw.\n */\nconst reactModuleCache = new Map<string, { React: unknown }>();\n\n/**\n * Fallback React implementation used when React is not installed in the\n * project. It captures JSX elements as plain objects so JSX can be used in\n * content declarations (esbuild's tsx loader defaults to React.createElement).\n */\nconst createFallbackReact = () => ({\n  createElement: (type: any, props: any, ...children: any[]) => ({\n    type,\n    props: {\n      ...props,\n      children: children.length <= 1 ? children[0] : children,\n    },\n  }),\n  Fragment: Symbol.for('react.fragment'),\n});\n\nconst getReactGlobal = (baseRequire: NodeJS.Require): { React: unknown } => {\n  // resolve.paths() is computed in-memory (no fs access) and identifies the\n  // node_modules chain this require instance resolves against.\n  const resolutionKey =\n    baseRequire.resolve.paths?.('react')?.join('|') ?? '<default>';\n\n  const cachedReactModule = reactModuleCache.get(resolutionKey);\n  if (cachedReactModule) return cachedReactModule;\n\n  let reactGlobal: { React: unknown };\n  try {\n    // Dynamically try to require React if it's installed in the project\n    reactGlobal = { React: baseRequire('react') };\n  } catch (_err) {\n    reactGlobal = { React: createFallbackReact() };\n  }\n\n  reactModuleCache.set(resolutionKey, reactGlobal);\n\n  return reactGlobal;\n};\n\n/**\n * Snapshot of the non-env `process` properties, taken once at module load.\n * Spreading `process` enumerates ~100 properties (some behind getters); doing\n * it per sandbox is wasteful since everything except `env` is static.\n */\nconst processSnapshot = { ...process };\n\n/**\n * Builds the global context handed to `runInNewContext`.\n *\n * SECURITY NOTE: this sandbox exists for global-scope hygiene (fresh\n * module/exports, controlled env), NOT for containment. It exposes the real\n * project `require`, a copy of `process`, and `fetch` — code executed here has\n * full host privileges. Only ever run trusted, build-time project files\n * (same trust model as `vite.config.ts`).\n */\nexport const getSandBoxContext = (options?: SandBoxContextOptions): Context => {\n  const { envVarOptions, projectRequire, additionalEnvVars, mocks, aliases } =\n    options ?? {};\n\n  const baseRequire: NodeJS.Require =\n    typeof projectRequire === 'function' ? projectRequire : getProjectRequire();\n\n  // Wrap require to honor mocks and aliases inside the VM\n  const mockedRequire: NodeJS.Require = (() => {\n    const mockTable = Object.assign(\n      {\n        esbuild,\n      },\n      mocks\n    );\n    const aliasTable = Object.assign({}, aliases);\n\n    const wrappedRequire = function mockableRequire(id: string) {\n      const target = aliasTable?.[id] ? aliasTable[id] : id;\n\n      if (mockTable && Object.hasOwn(mockTable, target)) {\n        return mockTable[target];\n      }\n\n      // If the original id was aliased, allow mocks to be defined on either key.\n      if (target !== id && mockTable && Object.hasOwn(mockTable, id)) {\n        return mockTable[id];\n      }\n\n      return baseRequire(target);\n    } as NodeJS.Require;\n\n    // Mirror NodeJS.Require properties\n    wrappedRequire.resolve = baseRequire.resolve.bind(baseRequire);\n    wrappedRequire.main = baseRequire.main;\n    wrappedRequire.extensions = baseRequire.extensions;\n    wrappedRequire.cache = baseRequire.cache;\n\n    return wrappedRequire;\n  })();\n\n  const sandboxContext: Context = {\n    exports: {\n      default: {},\n    },\n    module: {\n      exports: {},\n    },\n    process: {\n      ...processSnapshot,\n      env: {\n        ...process.env,\n        ...loadEnvFile(envVarOptions),\n        ...additionalEnvVars,\n      },\n    },\n    console,\n    require: mockedRequire,\n    ...getReactGlobal(baseRequire),\n  };\n\n  for (const key of NODE_GLOBALS) {\n    if (!(key in sandboxContext) && key in globalThis) {\n      (sandboxContext as Record<string, unknown>)[key] =\n        globalThis[key as keyof typeof globalThis];\n    }\n  }\n\n  return sandboxContext;\n};\n\nexport const parseFileContent = <T>(\n  fileContentString: string,\n  options?: SandBoxContextOptions\n): T | undefined => {\n  const sandboxContext = getSandBoxContext(options);\n\n  // Force strict mode so illegal writes throw instead of silently failing.\n  runInNewContext(`\"use strict\";\\n${fileContentString}`, sandboxContext);\n\n  const candidates: unknown[] = [\n    sandboxContext.exports?.default,\n    sandboxContext.module?.exports?.defaults,\n    sandboxContext.module?.exports?.default,\n    sandboxContext.module?.exports,\n  ];\n\n  let result: T | undefined;\n  for (const candidate of candidates) {\n    if (\n      candidate &&\n      typeof candidate === 'object' &&\n      Object.keys(candidate as object).length > 0\n    ) {\n      result = candidate as T;\n      break;\n    }\n  }\n\n  // Drop heavy references so the V8 context created by runInNewContext can be\n  // garbage-collected promptly. The extracted `result` is a plain data object\n  // and does not retain the sandbox.\n  (sandboxContext as Record<string, unknown>).require = undefined;\n  (sandboxContext as Record<string, unknown>).process = undefined;\n  (sandboxContext as Record<string, unknown>).React = undefined;\n  (sandboxContext as Record<string, unknown>).module = undefined;\n  (sandboxContext as Record<string, unknown>).exports = undefined;\n\n  return result;\n};\n"],"mappings":";;;;;;;;;AA+BA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AAQA,MAAM,mCAAmB,IAAI,IAAgC;;;;;;AAO7D,MAAM,6BAA6B;CACjC,gBAAgB,MAAW,OAAY,GAAG,cAAqB;EAC7D;EACA,OAAO;GACL,GAAG;GACH,UAAU,SAAS,UAAU,IAAI,SAAS,KAAK;EACjD;CACF;CACA,UAAU,OAAO,IAAI,gBAAgB;AACvC;AAEA,MAAM,kBAAkB,gBAAoD;CAG1E,MAAM,gBACJ,YAAY,QAAQ,QAAQ,OAAO,CAAC,EAAE,KAAK,GAAG,KAAK;CAErD,MAAM,oBAAoB,iBAAiB,IAAI,aAAa;CAC5D,IAAI,mBAAmB,OAAO;CAE9B,IAAI;CACJ,IAAI;EAEF,cAAc,EAAE,OAAO,YAAY,OAAO,EAAE;CAC9C,SAAS,MAAM;EACb,cAAc,EAAE,OAAO,oBAAoB,EAAE;CAC/C;CAEA,iBAAiB,IAAI,eAAe,WAAW;CAE/C,OAAO;AACT;;;;;;AAOA,MAAM,kBAAkB,EAAE,GAAG,QAAQ;;;;;;;;;;AAWrC,MAAa,qBAAqB,YAA6C;CAC7E,MAAM,EAAE,eAAe,gBAAgB,mBAAmB,OAAO,YAC/D,WAAW,CAAC;CAEd,MAAM,cACJ,OAAO,mBAAmB,aAAa,iBAAiBA,+CAAkB;CAG5E,MAAM,uBAAuC;EAC3C,MAAM,YAAY,OAAO,OACvB,EACE,QACF,GACA,KACF;EACA,MAAM,aAAa,OAAO,OAAO,CAAC,GAAG,OAAO;EA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