{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/bundle/index.ts"],"sourcesContent":["import { exec } from 'node:child_process';\nimport { mkdir, rm, writeFile } from 'node:fs/promises';\nimport { isAbsolute, join, resolve } from 'node:path';\nimport { promisify } from 'node:util';\nimport packageJSON from '@intlayer/types/package.json' with { type: 'json' };\nimport { type BuildOptions, build, type Plugin } from 'esbuild';\nimport {\n  type GetConfigurationOptions,\n  getConfiguration,\n} from '../configFile/getConfiguration';\nimport { getConfigEnvVars } from '../envVars/envVars';\nimport { getAlias } from '../utils/alias';\nimport { BundleLogger } from './logBundle';\n\nconst execAsync = promisify(exec);\n\nexport const packageList = [\n  'next-intlayer',\n  'react-intlayer',\n  'vue-intlayer',\n  'svelte-intlayer',\n  'preact-intlayer',\n  'solid-intlayer',\n  'angular-intlayer',\n  'lit-intlayer',\n  'express-intlayer',\n  'hono-intlayer',\n  'fastify-intlayer',\n  'adonis-intlayer',\n  'vanilla-intlayer',\n  'intlayer',\n] as const;\n\nconst defaultVersion = packageJSON.version;\n\nexport type BundleIntlayerOptions = {\n  outfile?: string;\n  configOptions?: GetConfigurationOptions;\n  bundlePackages?: string[];\n  version?: string;\n} & BuildOptions;\n\n/**\n * Bundle the application content using esbuild.\n * It uses the Intlayer configuration to set up aliases and other esbuild options.\n *\n * @param options - Bundle options including entryPoint, outfile, and esbuild options.\n * @returns The build result.\n */\nexport const bundleIntlayer = async (options: BundleIntlayerOptions) => {\n  const {\n    outfile = 'intlayer-bundle.js',\n    configOptions,\n    bundlePackages = [...packageList],\n    version = defaultVersion,\n    ...esbuildOptions\n  } = options;\n\n  const intlayerConfig = getConfiguration(configOptions);\n\n  const logger = new BundleLogger(intlayerConfig);\n\n  const alias = getAlias({\n    configuration: intlayerConfig,\n    formatter: (value: string) => resolve(process.cwd(), value),\n  });\n\n  // Fetch dictionaries and calculate tree-shaking variables\n\n  const treeShakingDefines = getConfigEnvVars(\n    intlayerConfig,\n    (key) => `process.env.${key}`,\n    (value) => `\"${value}\"` // Properly wraps the string in quotes\n  );\n\n  const intlayerBundlePlugin: Plugin = {\n    name: 'intlayer-bundle-plugin',\n    setup(build) {\n      // Create a regex that matches the provided packages\n      // It matches both the package name and any sub-exports\n      const packagesRegex = new RegExp(\n        `^(${bundlePackages\n          .map((packages) => packages.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n          .join('|')})(\\\\/.*)?$`\n      );\n\n      build.onResolve({ filter: packagesRegex }, () => ({\n        external: false,\n      }));\n\n      // Also ensure @intlayer/ packages are bundled if not explicitly excluded\n      build.onResolve({ filter: /^@intlayer\\// }, () => ({\n        external: false,\n      }));\n    },\n  };\n\n  const tempDir = join(intlayerConfig.system.tempDir, 'intlayer-bundle-tmp');\n\n  logger.setStatus('installing');\n\n  try {\n    // Clean and prepare temp directory\n    await rm(tempDir, { recursive: true, force: true });\n    await mkdir(tempDir, { recursive: true });\n\n    // Write package.json to fetch packages via npm/bun\n    const deps = Object.fromEntries(\n      bundlePackages.map((pkg) => [pkg, version])\n    );\n    await writeFile(\n      join(tempDir, 'package.json'),\n      JSON.stringify({ dependencies: deps, type: 'module' })\n    );\n\n    // Determine package manager (prefer bun if available)\n    let pm = 'npm install';\n    try {\n      await execAsync('bun --version');\n      pm = 'bun install';\n    } catch {}\n\n    // Install the packages in the temp directory\n    await execAsync(pm, { cwd: tempDir });\n\n    const absoluteOutfile = isAbsolute(outfile)\n      ? outfile\n      : join(process.cwd(), outfile);\n\n    const buildOptions: BuildOptions = {\n      bundle: true,\n      outfile: absoluteOutfile,\n      absWorkingDir: tempDir,\n      platform: 'browser',\n      conditions: ['browser', 'module', 'import', 'default'],\n      minify: true,\n      minifyIdentifiers: true,\n      treeShaking: true,\n      format: 'iife',\n      ignoreAnnotations: true,\n      stdin: {\n        contents: bundlePackages\n          .map((packageName) => {\n            // Convert package name to global name (e.g. vanilla-intlayer -> VanillaIntlayer)\n            const globalName = packageName\n              .split('-')\n              .map((part) => `${part.charAt(0).toUpperCase()}${part.slice(1)}`)\n              .join('');\n            // Create a global variable for each package\n            return `import * as ${globalName} from '${packageName}';\\nif (typeof window !== 'undefined') { window['${globalName}'] = ${globalName}; }`;\n          })\n          .join('\\n'),\n        resolveDir: tempDir,\n      },\n      define: {\n        'process.env': '{}', // Fix ReferenceError: process is not defined\n        // Inject generated environment variables\n        ...treeShakingDefines,\n        ...esbuildOptions.define,\n      },\n      alias: {\n        ...alias,\n        ...esbuildOptions.alias,\n      },\n      ...esbuildOptions,\n      plugins: [intlayerBundlePlugin, ...(esbuildOptions.plugins || [])],\n    };\n\n    logger.setStatus('bundling');\n    const result = await build(buildOptions);\n    logger.setStatus('success');\n    return result;\n  } catch (error) {\n    logger.setError(error);\n    throw error;\n  } finally {\n    // Clean up temp directory\n    await rm(tempDir, { recursive: true, force: true });\n  }\n};\n"],"mappings":";;;;;;;;;;;;AAcA,MAAM,YAAY,UAAU,KAAK;AAEjC,MAAa,cAAc;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,iBAAiB,YAAY;;;;;;;;AAgBnC,MAAa,iBAAiB,OAAO,YAAmC;CACtE,MAAM,EACJ,UAAU,sBACV,eACA,iBAAiB,CAAC,GAAG,YAAY,EACjC,UAAU,gBACV,GAAG,mBACD;CAEJ,MAAM,iBAAiB,iBAAiB,cAAc;CAEtD,MAAM,SAAS,IAAI,aAAa,eAAe;CAE/C,MAAM,QAAQ,SAAS;EACrB,eAAe;EACf,YAAY,UAAkB,QAAQ,QAAQ,KAAK,EAAE,MAAM;EAC5D,CAAC;CAIF,MAAM,qBAAqB,iBACzB,iBACC,QAAQ,eAAe,QACvB,UAAU,IAAI,MAAM,GACtB;CAED,MAAM,uBAA+B;EACnC,MAAM;EACN,MAAM,OAAO;GAGX,MAAM,gBAAgB,IAAI,OACxB,KAAK,eACF,KAAK,aAAa,SAAS,QAAQ,uBAAuB,OAAO,CAAC,CAClE,KAAK,IAAI,CAAC,YACd;AAED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