next 16.0.2-canary.10 → 16.0.2-canary.12

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.
Files changed (114) hide show
  1. package/dist/bin/next +1 -1
  2. package/dist/build/babel/loader/get-config.js +5 -0
  3. package/dist/build/babel/loader/get-config.js.map +1 -1
  4. package/dist/build/index.js +7 -4
  5. package/dist/build/index.js.map +1 -1
  6. package/dist/build/jest/jest.js +2 -1
  7. package/dist/build/jest/jest.js.map +1 -1
  8. package/dist/build/load-entrypoint.js +1 -2
  9. package/dist/build/load-entrypoint.js.map +1 -1
  10. package/dist/build/lockfile.d.ts +1 -1
  11. package/dist/build/lockfile.js +5 -9
  12. package/dist/build/lockfile.js.map +1 -1
  13. package/dist/build/next-config-ts/transpile-config.js +13 -3
  14. package/dist/build/next-config-ts/transpile-config.js.map +1 -1
  15. package/dist/build/swc/index.d.ts +4 -2
  16. package/dist/build/swc/index.js +54 -51
  17. package/dist/build/swc/index.js.map +1 -1
  18. package/dist/build/swc/install-bindings.d.ts +15 -0
  19. package/dist/build/swc/install-bindings.js +30 -0
  20. package/dist/build/swc/install-bindings.js.map +1 -0
  21. package/dist/build/templates/app-page.js +7 -1
  22. package/dist/build/templates/app-page.js.map +1 -1
  23. package/dist/build/turbopack-build/impl.js +9 -4
  24. package/dist/build/turbopack-build/impl.js.map +1 -1
  25. package/dist/build/webpack/loaders/lightningcss-loader/src/loader.js +7 -2
  26. package/dist/build/webpack/loaders/lightningcss-loader/src/loader.js.map +1 -1
  27. package/dist/build/webpack/loaders/lightningcss-loader/src/minify.js +2 -2
  28. package/dist/build/webpack/loaders/lightningcss-loader/src/minify.js.map +1 -1
  29. package/dist/build/webpack/loaders/next-app-loader/index.js +6 -0
  30. package/dist/build/webpack/loaders/next-app-loader/index.js.map +1 -1
  31. package/dist/build/webpack/loaders/next-barrel-loader.js +5 -0
  32. package/dist/build/webpack/loaders/next-barrel-loader.js.map +1 -1
  33. package/dist/build/webpack/loaders/next-metadata-image-loader.js +5 -0
  34. package/dist/build/webpack/loaders/next-metadata-image-loader.js.map +1 -1
  35. package/dist/build/webpack/loaders/next-metadata-route-loader.js +5 -0
  36. package/dist/build/webpack/loaders/next-metadata-route-loader.js.map +1 -1
  37. package/dist/build/webpack/loaders/next-swc-loader.js +10 -6
  38. package/dist/build/webpack/loaders/next-swc-loader.js.map +1 -1
  39. package/dist/build/webpack-build/impl.js +4 -1
  40. package/dist/build/webpack-build/impl.js.map +1 -1
  41. package/dist/build/webpack-config.js +2 -7
  42. package/dist/build/webpack-config.js.map +1 -1
  43. package/dist/cli/next-typegen.js +3 -0
  44. package/dist/cli/next-typegen.js.map +1 -1
  45. package/dist/client/app-bootstrap.js +1 -1
  46. package/dist/client/index.js +1 -1
  47. package/dist/compiled/@next/font/dist/google/font-data.json +63 -0
  48. package/dist/compiled/@next/font/dist/google/index.d.ts +40 -0
  49. package/dist/esm/build/babel/loader/get-config.js +5 -0
  50. package/dist/esm/build/babel/loader/get-config.js.map +1 -1
  51. package/dist/esm/build/index.js +7 -4
  52. package/dist/esm/build/index.js.map +1 -1
  53. package/dist/esm/build/load-entrypoint.js +2 -3
  54. package/dist/esm/build/load-entrypoint.js.map +1 -1
  55. package/dist/esm/build/lockfile.js +5 -9
  56. package/dist/esm/build/lockfile.js.map +1 -1
  57. package/dist/esm/build/next-config-ts/transpile-config.js +13 -3
  58. package/dist/esm/build/next-config-ts/transpile-config.js.map +1 -1
  59. package/dist/esm/build/swc/index.js +52 -49
  60. package/dist/esm/build/swc/index.js.map +1 -1
  61. package/dist/esm/build/swc/install-bindings.js +20 -0
  62. package/dist/esm/build/swc/install-bindings.js.map +1 -0
  63. package/dist/esm/build/templates/app-page.js +7 -1
  64. package/dist/esm/build/templates/app-page.js.map +1 -1
  65. package/dist/esm/build/turbopack-build/impl.js +10 -5
  66. package/dist/esm/build/turbopack-build/impl.js.map +1 -1
  67. package/dist/esm/build/webpack/loaders/lightningcss-loader/src/loader.js +7 -2
  68. package/dist/esm/build/webpack/loaders/lightningcss-loader/src/loader.js.map +1 -1
  69. package/dist/esm/build/webpack/loaders/lightningcss-loader/src/minify.js +2 -2
  70. package/dist/esm/build/webpack/loaders/lightningcss-loader/src/minify.js.map +1 -1
  71. package/dist/esm/build/webpack/loaders/next-app-loader/index.js +6 -0
  72. package/dist/esm/build/webpack/loaders/next-app-loader/index.js.map +1 -1
  73. package/dist/esm/build/webpack/loaders/next-barrel-loader.js +5 -0
  74. package/dist/esm/build/webpack/loaders/next-barrel-loader.js.map +1 -1
  75. package/dist/esm/build/webpack/loaders/next-metadata-image-loader.js +5 -0
  76. package/dist/esm/build/webpack/loaders/next-metadata-image-loader.js.map +1 -1
  77. package/dist/esm/build/webpack/loaders/next-metadata-route-loader.js +5 -0
  78. package/dist/esm/build/webpack/loaders/next-metadata-route-loader.js.map +1 -1
  79. package/dist/esm/build/webpack/loaders/next-swc-loader.js +11 -7
  80. package/dist/esm/build/webpack/loaders/next-swc-loader.js.map +1 -1
  81. package/dist/esm/build/webpack-build/impl.js +4 -1
  82. package/dist/esm/build/webpack-build/impl.js.map +1 -1
  83. package/dist/esm/build/webpack-config.js +2 -7
  84. package/dist/esm/build/webpack-config.js.map +1 -1
  85. package/dist/esm/client/app-bootstrap.js +1 -1
  86. package/dist/esm/client/index.js +1 -1
  87. package/dist/esm/server/config.js +2 -2
  88. package/dist/esm/server/config.js.map +1 -1
  89. package/dist/esm/server/dev/hot-reloader-turbopack.js +3 -4
  90. package/dist/esm/server/dev/hot-reloader-turbopack.js.map +1 -1
  91. package/dist/esm/server/dev/hot-reloader-webpack.js +1 -1
  92. package/dist/esm/server/lib/app-info-log.js +1 -1
  93. package/dist/esm/server/lib/router-utils/setup-dev-bundler.js +3 -0
  94. package/dist/esm/server/lib/router-utils/setup-dev-bundler.js.map +1 -1
  95. package/dist/esm/server/lib/start-server.js +1 -1
  96. package/dist/esm/server/lib/trace/tracer.js +6 -5
  97. package/dist/esm/server/lib/trace/tracer.js.map +1 -1
  98. package/dist/esm/shared/lib/errors/canary-only-config-error.js +1 -1
  99. package/dist/server/config.js +2 -2
  100. package/dist/server/config.js.map +1 -1
  101. package/dist/server/dev/hot-reloader-turbopack.js +2 -3
  102. package/dist/server/dev/hot-reloader-turbopack.js.map +1 -1
  103. package/dist/server/dev/hot-reloader-webpack.js +1 -1
  104. package/dist/server/lib/app-info-log.js +1 -1
  105. package/dist/server/lib/router-utils/setup-dev-bundler.js +3 -0
  106. package/dist/server/lib/router-utils/setup-dev-bundler.js.map +1 -1
  107. package/dist/server/lib/start-server.js +1 -1
  108. package/dist/server/lib/trace/tracer.js +6 -5
  109. package/dist/server/lib/trace/tracer.js.map +1 -1
  110. package/dist/shared/lib/errors/canary-only-config-error.js +1 -1
  111. package/dist/telemetry/anonymous-meta.js +1 -1
  112. package/dist/telemetry/events/session-stopped.js +2 -2
  113. package/dist/telemetry/events/version.js +2 -2
  114. package/package.json +15 -15
@@ -35,6 +35,7 @@ const _loadjsconfig = /*#__PURE__*/ _interop_require_default(require("../load-js
35
35
  const _log = /*#__PURE__*/ _interop_require_wildcard(require("../output/log"));
36
36
  const _findpagesdir = require("../../lib/find-pages-dir");
37
37
  const _swc = require("../swc");
38
+ const _installbindings = require("../swc/install-bindings");
38
39
  function _interop_require_default(obj) {
39
40
  return obj && obj.__esModule ? obj : {
40
41
  default: obj
@@ -137,7 +138,7 @@ function nextJest(options = {}) {
137
138
  // Ensure provided async config is supported
138
139
  const resolvedJestConfig = (typeof customJestConfig === 'function' ? await customJestConfig() : customJestConfig) ?? {};
139
140
  // eagerly load swc bindings instead of waiting for transform calls
140
- await (0, _swc.loadBindings)(nextConfig == null ? void 0 : (_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.useWasmBinary);
141
+ await (0, _installbindings.installBindings)(nextConfig == null ? void 0 : (_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.useWasmBinary);
141
142
  if (_swc.lockfilePatchPromise.cur) {
142
143
  await _swc.lockfilePatchPromise.cur;
143
144
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/build/jest/jest.ts"],"sourcesContent":["import { loadEnvConfig } from '@next/env'\nimport { resolve, join } from 'path'\nimport loadConfig from '../../server/config'\nimport { PHASE_TEST } from '../../shared/lib/constants'\nimport loadJsConfig from '../load-jsconfig'\nimport * as Log from '../output/log'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport { loadBindings, lockfilePatchPromise } from '../swc'\nimport type { JestTransformerConfig } from '../swc/jest-transformer'\nimport type { Config } from '@jest/types'\n\nconst DEFAULT_TRANSPILED_PACKAGES: string[] = require('../../lib/default-transpiled-packages.json')\n\nasync function getConfig(dir: string) {\n const conf = await loadConfig(PHASE_TEST, dir)\n return conf\n}\n\n/**\n * Loads closest package.json in the directory hierarchy\n */\nfunction loadClosestPackageJson(dir: string, attempts = 1): any {\n if (attempts > 5) {\n throw new Error(\"Can't resolve main package.json file\")\n }\n var mainPath = attempts === 1 ? './' : Array(attempts).join('../')\n try {\n return require(join(dir, mainPath + 'package.json'))\n } catch (e) {\n return loadClosestPackageJson(dir, attempts + 1)\n }\n}\n\n/** Loads dotenv files and sets environment variables based on next config. */\nfunction setUpEnv(dir: string) {\n const dev = false\n loadEnvConfig(dir, dev, Log)\n}\n\n/**\n * @example\n * ```ts\n * // Usage in jest.config.js\n * const nextJest = require('next/jest');\n *\n * // Optionally provide path to Next.js app which will enable loading next.config.js and .env files\n * const createJestConfig = nextJest({ dir })\n *\n * // Any custom config you want to pass to Jest\n * const customJestConfig = {\n * setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],\n * }\n *\n * // createJestConfig is exported in this way to ensure that next/jest can load the Next.js config which is async\n * module.exports = createJestConfig(customJestConfig)\n * ```\n *\n * Read more: [Next.js Docs: Setting up Jest with Next.js](https://nextjs.org/docs/app/building-your-application/testing/jest)\n */\nexport default function nextJest(options: { dir?: string } = {}) {\n // createJestConfig\n return (\n customJestConfig?:\n | Config.InitialProjectOptions\n | (() => Promise<Config.InitialProjectOptions>)\n ) => {\n // Function that is provided as the module.exports of jest.config.js\n // Will be called and awaited by Jest\n return async (): Promise<Config.InitialProjectOptions> => {\n let nextConfig\n let jsConfig\n let resolvedBaseUrl\n let isEsmProject = false\n let pagesDir: string | undefined\n let serverComponents: boolean | undefined\n\n if (options.dir) {\n const resolvedDir = resolve(options.dir)\n const packageConfig = loadClosestPackageJson(resolvedDir)\n isEsmProject = packageConfig.type === 'module'\n\n nextConfig = await getConfig(resolvedDir)\n const findPagesDirResult = findPagesDir(resolvedDir)\n serverComponents = !!findPagesDirResult.appDir\n pagesDir = findPagesDirResult.pagesDir\n setUpEnv(resolvedDir)\n // TODO: revisit when bug in SWC is fixed that strips `.css`\n const result = await loadJsConfig(resolvedDir, nextConfig)\n jsConfig = result.jsConfig\n resolvedBaseUrl = result.resolvedBaseUrl\n }\n // Ensure provided async config is supported\n const resolvedJestConfig =\n (typeof customJestConfig === 'function'\n ? await customJestConfig()\n : customJestConfig) ?? {}\n\n // eagerly load swc bindings instead of waiting for transform calls\n await loadBindings(nextConfig?.experimental?.useWasmBinary)\n\n if (lockfilePatchPromise.cur) {\n await lockfilePatchPromise.cur\n }\n\n const transpiled = (nextConfig?.transpilePackages ?? [])\n .concat(DEFAULT_TRANSPILED_PACKAGES)\n .join('|')\n\n const jestTransformerConfig: JestTransformerConfig = {\n modularizeImports: nextConfig?.modularizeImports,\n swcPlugins: nextConfig?.experimental?.swcPlugins,\n compilerOptions: nextConfig?.compiler,\n jsConfig,\n resolvedBaseUrl,\n serverComponents,\n isEsmProject,\n pagesDir,\n }\n return {\n ...resolvedJestConfig,\n\n moduleNameMapper: {\n // Handle CSS imports (with CSS modules)\n // https://jestjs.io/docs/webpack#mocking-css-modules\n '^.+\\\\.module\\\\.(css|sass|scss)$':\n require.resolve('./object-proxy.js'),\n\n // Handle CSS imports (without CSS modules)\n '^.+\\\\.(css|sass|scss)$': require.resolve('./__mocks__/styleMock.js'),\n\n // Handle image imports\n '^.+\\\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp)$': require.resolve(\n `./__mocks__/fileMock.js`\n ),\n\n // Keep .svg to it's own rule to make overriding easy\n '^.+\\\\.(svg)$': require.resolve(`./__mocks__/fileMock.js`),\n\n // Handle @next/font\n '@next/font/(.*)': require.resolve('./__mocks__/nextFontMock.js'),\n // Handle next/font\n 'next/font/(.*)': require.resolve('./__mocks__/nextFontMock.js'),\n // Disable server-only\n '^server-only$': require.resolve('./__mocks__/empty.js'),\n\n // custom config comes last to ensure the above rules are matched,\n // fixes the case where @pages/(.*) -> src/pages/$! doesn't break\n // CSS/image mocks\n ...(resolvedJestConfig.moduleNameMapper || {}),\n },\n testPathIgnorePatterns: [\n // Don't look for tests in node_modules\n '/node_modules/',\n // Don't look for tests in the Next.js build output\n '/.next/',\n // Custom config can append to testPathIgnorePatterns but not modify it\n // This is to ensure `.next` and `node_modules` are always excluded\n ...(resolvedJestConfig.testPathIgnorePatterns || []),\n ],\n\n transform: {\n // Use SWC to compile tests\n '^.+\\\\.(js|jsx|ts|tsx|mjs)$': [\n require.resolve('../swc/jest-transformer'),\n jestTransformerConfig,\n ],\n // Allow for appending/overriding the default transforms\n ...(resolvedJestConfig.transform || {}),\n },\n\n transformIgnorePatterns: [\n // To match Next.js behavior node_modules is not transformed, only `transpiledPackages`\n ...(transpiled\n ? [\n `/node_modules/(?!.pnpm)(?!(${transpiled})/)`,\n `/node_modules/.pnpm/(?!(${transpiled.replace(\n /\\//g,\n '\\\\+'\n )})@)`,\n ]\n : ['/node_modules/']),\n // CSS modules are mocked so they don't need to be transformed\n '^.+\\\\.module\\\\.(css|sass|scss)$',\n\n // Custom config can append to transformIgnorePatterns but not modify it\n // This is to ensure `node_modules` and .module.css/sass/scss are always excluded\n ...(resolvedJestConfig.transformIgnorePatterns || []),\n ],\n watchPathIgnorePatterns: [\n // Don't re-run tests when the Next.js build output changes\n '/.next/',\n ...(resolvedJestConfig.watchPathIgnorePatterns || []),\n ],\n }\n }\n }\n}\n"],"names":["nextJest","DEFAULT_TRANSPILED_PACKAGES","require","getConfig","dir","conf","loadConfig","PHASE_TEST","loadClosestPackageJson","attempts","Error","mainPath","Array","join","e","setUpEnv","dev","loadEnvConfig","Log","options","customJestConfig","nextConfig","jsConfig","resolvedBaseUrl","isEsmProject","pagesDir","serverComponents","resolvedDir","resolve","packageConfig","type","findPagesDirResult","findPagesDir","appDir","result","loadJsConfig","resolvedJestConfig","loadBindings","experimental","useWasmBinary","lockfilePatchPromise","cur","transpiled","transpilePackages","concat","jestTransformerConfig","modularizeImports","swcPlugins","compilerOptions","compiler","moduleNameMapper","testPathIgnorePatterns","transform","transformIgnorePatterns","replace","watchPathIgnorePatterns"],"mappings":";;;;+BAuCA;;;;;;;;;;;;;;;;;;;CAmBC,GACD;;;eAAwBA;;;qBA3DM;sBACA;+DACP;2BACI;qEACF;6DACJ;8BACQ;qBACsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAInD,MAAMC,8BAAwCC,QAAQ;AAEtD,eAAeC,UAAUC,GAAW;IAClC,MAAMC,OAAO,MAAMC,IAAAA,eAAU,EAACC,qBAAU,EAAEH;IAC1C,OAAOC;AACT;AAEA;;CAEC,GACD,SAASG,uBAAuBJ,GAAW,EAAEK,WAAW,CAAC;IACvD,IAAIA,WAAW,GAAG;QAChB,MAAM,qBAAiD,CAAjD,IAAIC,MAAM,yCAAV,qBAAA;mBAAA;wBAAA;0BAAA;QAAgD;IACxD;IACA,IAAIC,WAAWF,aAAa,IAAI,OAAOG,MAAMH,UAAUI,IAAI,CAAC;IAC5D,IAAI;QACF,OAAOX,QAAQW,IAAAA,UAAI,EAACT,KAAKO,WAAW;IACtC,EAAE,OAAOG,GAAG;QACV,OAAON,uBAAuBJ,KAAKK,WAAW;IAChD;AACF;AAEA,4EAA4E,GAC5E,SAASM,SAASX,GAAW;IAC3B,MAAMY,MAAM;IACZC,IAAAA,kBAAa,EAACb,KAAK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AC;qBAAiB;oBACtB,8DAA8D;oBAC9D;oBAEA,wEAAwE;oBACxE,iFAAiF;uBAC7ElB,mBAAmBiB,uBAAuB,IAAI,EAAE;iBACrD;gBACDE,yBAAyB;oBACvB,2DAA2D;oBAC3D;uBACInB,mBAAmBmB,uBAAuB,IAAI,EAAE;iBACrD;YACH;QACF;IACF;AACF","ignoreList":[0]}
1
+ {"version":3,"sources":["../../../src/build/jest/jest.ts"],"sourcesContent":["import { loadEnvConfig } from '@next/env'\nimport { resolve, join } from 'path'\nimport loadConfig from '../../server/config'\nimport { PHASE_TEST } from '../../shared/lib/constants'\nimport loadJsConfig from '../load-jsconfig'\nimport * as Log from '../output/log'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport { lockfilePatchPromise } from '../swc'\nimport { installBindings } from '../swc/install-bindings'\nimport type { JestTransformerConfig } from '../swc/jest-transformer'\nimport type { Config } from '@jest/types'\n\nconst DEFAULT_TRANSPILED_PACKAGES: string[] = require('../../lib/default-transpiled-packages.json')\n\nasync function getConfig(dir: string) {\n const conf = await loadConfig(PHASE_TEST, dir)\n return conf\n}\n\n/**\n * Loads closest package.json in the directory hierarchy\n */\nfunction loadClosestPackageJson(dir: string, attempts = 1): any {\n if (attempts > 5) {\n throw new Error(\"Can't resolve main package.json file\")\n }\n var mainPath = attempts === 1 ? './' : Array(attempts).join('../')\n try {\n return require(join(dir, mainPath + 'package.json'))\n } catch (e) {\n return loadClosestPackageJson(dir, attempts + 1)\n }\n}\n\n/** Loads dotenv files and sets environment variables based on next config. */\nfunction setUpEnv(dir: string) {\n const dev = false\n loadEnvConfig(dir, dev, Log)\n}\n\n/**\n * @example\n * ```ts\n * // Usage in jest.config.js\n * const nextJest = require('next/jest');\n *\n * // Optionally provide path to Next.js app which will enable loading next.config.js and .env files\n * const createJestConfig = nextJest({ dir })\n *\n * // Any custom config you want to pass to Jest\n * const customJestConfig = {\n * setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],\n * }\n *\n * // createJestConfig is exported in this way to ensure that next/jest can load the Next.js config which is async\n * module.exports = createJestConfig(customJestConfig)\n * ```\n *\n * Read more: [Next.js Docs: Setting up Jest with Next.js](https://nextjs.org/docs/app/building-your-application/testing/jest)\n */\nexport default function nextJest(options: { dir?: string } = {}) {\n // createJestConfig\n return (\n customJestConfig?:\n | Config.InitialProjectOptions\n | (() => Promise<Config.InitialProjectOptions>)\n ) => {\n // Function that is provided as the module.exports of jest.config.js\n // Will be called and awaited by Jest\n return async (): Promise<Config.InitialProjectOptions> => {\n let nextConfig\n let jsConfig\n let resolvedBaseUrl\n let isEsmProject = false\n let pagesDir: string | undefined\n let serverComponents: boolean | undefined\n\n if (options.dir) {\n const resolvedDir = resolve(options.dir)\n const packageConfig = loadClosestPackageJson(resolvedDir)\n isEsmProject = packageConfig.type === 'module'\n\n nextConfig = await getConfig(resolvedDir)\n const findPagesDirResult = findPagesDir(resolvedDir)\n serverComponents = !!findPagesDirResult.appDir\n pagesDir = findPagesDirResult.pagesDir\n setUpEnv(resolvedDir)\n // TODO: revisit when bug in SWC is fixed that strips `.css`\n const result = await loadJsConfig(resolvedDir, nextConfig)\n jsConfig = result.jsConfig\n resolvedBaseUrl = result.resolvedBaseUrl\n }\n // Ensure provided async config is supported\n const resolvedJestConfig =\n (typeof customJestConfig === 'function'\n ? await customJestConfig()\n : customJestConfig) ?? {}\n\n // eagerly load swc bindings instead of waiting for transform calls\n await installBindings(nextConfig?.experimental?.useWasmBinary)\n\n if (lockfilePatchPromise.cur) {\n await lockfilePatchPromise.cur\n }\n\n const transpiled = (nextConfig?.transpilePackages ?? [])\n .concat(DEFAULT_TRANSPILED_PACKAGES)\n .join('|')\n\n const jestTransformerConfig: JestTransformerConfig = {\n modularizeImports: nextConfig?.modularizeImports,\n swcPlugins: nextConfig?.experimental?.swcPlugins,\n compilerOptions: nextConfig?.compiler,\n jsConfig,\n resolvedBaseUrl,\n serverComponents,\n isEsmProject,\n pagesDir,\n }\n return {\n ...resolvedJestConfig,\n\n moduleNameMapper: {\n // Handle CSS imports (with CSS modules)\n // https://jestjs.io/docs/webpack#mocking-css-modules\n '^.+\\\\.module\\\\.(css|sass|scss)$':\n require.resolve('./object-proxy.js'),\n\n // Handle CSS imports (without CSS modules)\n '^.+\\\\.(css|sass|scss)$': require.resolve('./__mocks__/styleMock.js'),\n\n // Handle image imports\n '^.+\\\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp)$': require.resolve(\n `./__mocks__/fileMock.js`\n ),\n\n // Keep .svg to it's own rule to make overriding easy\n '^.+\\\\.(svg)$': require.resolve(`./__mocks__/fileMock.js`),\n\n // Handle @next/font\n '@next/font/(.*)': require.resolve('./__mocks__/nextFontMock.js'),\n // Handle next/font\n 'next/font/(.*)': require.resolve('./__mocks__/nextFontMock.js'),\n // Disable server-only\n '^server-only$': require.resolve('./__mocks__/empty.js'),\n\n // custom config comes last to ensure the above rules are matched,\n // fixes the case where @pages/(.*) -> src/pages/$! doesn't break\n // CSS/image mocks\n ...(resolvedJestConfig.moduleNameMapper || {}),\n },\n testPathIgnorePatterns: [\n // Don't look for tests in node_modules\n '/node_modules/',\n // Don't look for tests in the Next.js build output\n '/.next/',\n // Custom config can append to testPathIgnorePatterns but not modify it\n // This is to ensure `.next` and `node_modules` are always excluded\n ...(resolvedJestConfig.testPathIgnorePatterns || []),\n ],\n\n transform: {\n // Use SWC to compile tests\n '^.+\\\\.(js|jsx|ts|tsx|mjs)$': [\n require.resolve('../swc/jest-transformer'),\n jestTransformerConfig,\n ],\n // Allow for appending/overriding the default transforms\n ...(resolvedJestConfig.transform || {}),\n },\n\n transformIgnorePatterns: [\n // To match Next.js behavior node_modules is not transformed, only `transpiledPackages`\n ...(transpiled\n ? [\n `/node_modules/(?!.pnpm)(?!(${transpiled})/)`,\n `/node_modules/.pnpm/(?!(${transpiled.replace(\n /\\//g,\n '\\\\+'\n )})@)`,\n ]\n : ['/node_modules/']),\n // CSS modules are mocked so they don't need to be transformed\n '^.+\\\\.module\\\\.(css|sass|scss)$',\n\n // Custom config can append to transformIgnorePatterns but not modify it\n // This is to ensure `node_modules` and .module.css/sass/scss are always excluded\n ...(resolvedJestConfig.transformIgnorePatterns || []),\n ],\n watchPathIgnorePatterns: [\n // Don't re-run tests when the Next.js build output changes\n '/.next/',\n ...(resolvedJestConfig.watchPathIgnorePatterns || []),\n ],\n }\n }\n }\n}\n"],"names":["nextJest","DEFAULT_TRANSPILED_PACKAGES","require","getConfig","dir","conf","loadConfig","PHASE_TEST","loadClosestPackageJson","attempts","Error","mainPath","Array","join","e","setUpEnv","dev","loadEnvConfig","Log","options","customJestConfig","nextConfig","jsConfig","resolvedBaseUrl","isEsmProject","pagesDir","serverComponents","resolvedDir","resolve","packageConfig","type","findPagesDirResult","findPagesDir","appDir","result","loadJsConfig","resolvedJestConfig","installBindings","experimental","useWasmBinary","lockfilePatchPromise","cur","transpiled","transpilePackages","concat","jestTransformerConfig","modularizeImports","swcPlugins","compilerOptions","compiler","moduleNameMapper","testPathIgnorePatterns","transform","transformIgnorePatterns","replace","watchPathIgnorePatterns"],"mappings":";;;;+BAwCA;;;;;;;;;;;;;;;;;;;CAmBC,GACD;;;eAAwBA;;;qBA5DM;sBACA;+DACP;2BACI;qEACF;6DACJ;8BACQ;qBACQ;iCACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIhC,MAAMC,8BAAwCC,QAAQ;AAEtD,eAAeC,UAAUC,GAAW;IAClC,MAAMC,OAAO,MAAMC,IAAAA,eAAU,EAACC,qBAAU,EAAEH;IAC1C,OAAOC;AACT;AAEA;;CAEC,GACD,SAASG,uBAAuBJ,GAAW,EAAEK,WAAW,CAAC;IACvD,IAAIA,WAAW,GAAG;QAChB,MAAM,qBAAiD,CAAjD,IAAIC,MAAM,yCAAV,qBAAA;mBAAA;wBAAA;0BAAA;QAAgD;IACxD;IACA,IAAIC,WAAWF,aAAa,IAAI,OAAOG,MAAMH,UAAUI,IAAI,CAAC;IAC5D,IAAI;QACF,OA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AAS,IAAI,CAAC,CAAC;gBACxC;gBAEAC,yBAAyB;oBACvB,uFAAuF;uBACnFX,aACA;wBACE,CAAC,2BAA2B,EAAEA,WAAW,GAAG,CAAC;wBAC7C,CAAC,wBAAwB,EAAEA,WAAWY,OAAO,CAC3C,OACA,OACA,GAAG,CAAC;qBACP,GACD;wBAAC;qBAAiB;oBACtB,8DAA8D;oBAC9D;oBAEA,wEAAwE;oBACxE,iFAAiF;uBAC7ElB,mBAAmBiB,uBAAuB,IAAI,EAAE;iBACrD;gBACDE,yBAAyB;oBACvB,2DAA2D;oBAC3D;uBACInB,mBAAmBmB,uBAAuB,IAAI,EAAE;iBACrD;YACH;QACF;IACF;AACF","ignoreList":[0]}
@@ -21,10 +21,9 @@ const PACKAGE_ROOT = _path.default.normalize(_path.default.join(__dirname, '../.
21
21
  const TEMPLATE_SRC_FOLDER = _path.default.normalize(_path.default.join(__dirname, './templates'));
22
22
  const TEMPLATES_ESM_FOLDER = _path.default.normalize(_path.default.join(__dirname, '../../dist/esm/build/templates'));
23
23
  async function loadEntrypoint(entrypoint, replacements, injections, imports) {
24
- let bindings = await (0, _swc.loadBindings)();
25
24
  const templatePath = _path.default.resolve(_path.default.join(TEMPLATES_ESM_FOLDER, `${entrypoint}.js`));
26
25
  let content = await _promises.default.readFile(templatePath);
27
- return bindings.expandNextJsTemplate(content, // Ensure that we use unix-style path separators for the import paths
26
+ return (0, _swc.getBindingsSync)().expandNextJsTemplate(content, // Ensure that we use unix-style path separators for the import paths
28
27
  _path.default.join(TEMPLATE_SRC_FOLDER, `${entrypoint}.js`).replace(/\\/g, '/'), PACKAGE_ROOT.replace(/\\/g, '/'), replacements, injections ?? {}, imports ?? {});
29
28
  }
30
29
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/build/load-entrypoint.ts"],"sourcesContent":["import fs from 'fs/promises'\nimport path from 'path'\nimport { loadBindings } from './swc'\n\n// NOTE: this should be updated if this loader file is moved.\nconst PACKAGE_ROOT = path.normalize(path.join(__dirname, '../..'))\nconst TEMPLATE_SRC_FOLDER = path.normalize(path.join(__dirname, './templates'))\nconst TEMPLATES_ESM_FOLDER = path.normalize(\n path.join(__dirname, '../../dist/esm/build/templates')\n)\n\n/**\n * Load the entrypoint file from the ESM directory and performs string\n * replacements of the template variables specified in the `replacements`\n * argument.\n *\n * For non-string replacements, the template should use the\n * `declare const ${key}: ${type}` syntax. to ensure that the type is correct\n * and the typescript can compile. You may have to use `@ts-expect-error` to\n * handle replacement values that are related to imports.\n *\n * @param entrypoint the entrypoint to load\n * @param replacements string replacements to perform\n * @param injections code injections to perform\n * @param imports optional imports to insert or set to null\n * @returns the loaded file with the replacements\n */\nexport async function loadEntrypoint(\n entrypoint:\n | 'app-page'\n | 'app-route'\n | 'edge-app-route'\n | 'edge-ssr'\n | 'edge-ssr-app'\n | 'middleware'\n | 'pages'\n | 'pages-api',\n replacements: Record<`VAR_${string}`, string>,\n injections?: Record<string, string>,\n imports?: Record<string, string | null>\n): Promise<string> {\n let bindings = await loadBindings()\n\n const templatePath = path.resolve(\n path.join(TEMPLATES_ESM_FOLDER, `${entrypoint}.js`)\n )\n let content = await fs.readFile(templatePath)\n\n return bindings.expandNextJsTemplate(\n content,\n // Ensure that we use unix-style path separators for the import paths\n path.join(TEMPLATE_SRC_FOLDER, `${entrypoint}.js`).replace(/\\\\/g, '/'),\n PACKAGE_ROOT.replace(/\\\\/g, '/'),\n replacements,\n injections ?? {},\n imports ?? {}\n )\n}\n"],"names":["loadEntrypoint","PACKAGE_ROOT","path","normalize","join","__dirname","TEMPLATE_SRC_FOLDER","TEMPLATES_ESM_FOLDER","entrypoint","replacements","injections","imports","bindings","loadBindings","templatePath","resolve","content","fs","readFile","expandNextJsTemplate","replace"],"mappings":";;;;+BA2BsBA;;;eAAAA;;;iEA3BP;6DACE;qBACY;;;;;;AAE7B,6DAA6D;AAC7D,MAAMC,eAAeC,aAAI,CAACC,SAAS,CAACD,aAAI,CAACE,IAAI,CAACC,WAAW;AACzD,MAAMC,sBAAsBJ,aAAI,CAACC,SAAS,CAACD,aAAI,CAACE,IAAI,CAACC,WAAW;AAChE,MAAME,uBAAuBL,aAAI,CAACC,SAAS,CACzCD,aAAI,CAACE,IAAI,CAACC,WAAW;AAmBhB,eAAeL,eACpBQ,UAQe,EACfC,YAA6C,EAC7CC,UAAmC,EACnCC,OAAuC;IAEvC,IAAIC,WAAW,MAAMC,IAAAA,iBAAY;IAEjC,MAAMC,eAAeZ,aAAI,CAACa,OAAO,CAC/Bb,aAAI,CAACE,IAAI,CAACG,sBAAsB,GAAGC,WAAW,GAAG,CAAC;IAEpD,IAAIQ,UAAU,MAAMC,iBAAE,CAACC,QAAQ,CAACJ;IAEhC,OAAOF,SAASO,oBAAoB,CAClCH,SACA,qEAAqE;IACrEd,aAAI,CAACE,IAAI,CAACE,qBAAqB,GAAGE,WAAW,GAAG,CAAC,EAAEY,OAAO,CAAC,OAAO,MAClEnB,aAAamB,OAAO,CAAC,OAAO,MAC5BX,cACAC,cAAc,CAAC,GACfC,WAAW,CAAC;AAEhB","ignoreList":[0]}
1
+ {"version":3,"sources":["../../src/build/load-entrypoint.ts"],"sourcesContent":["import fs from 'fs/promises'\nimport path from 'path'\nimport { getBindingsSync } from './swc'\n\n// NOTE: this should be updated if this loader file is moved.\nconst PACKAGE_ROOT = path.normalize(path.join(__dirname, '../..'))\nconst TEMPLATE_SRC_FOLDER = path.normalize(path.join(__dirname, './templates'))\nconst TEMPLATES_ESM_FOLDER = path.normalize(\n path.join(__dirname, '../../dist/esm/build/templates')\n)\n\n/**\n * Load the entrypoint file from the ESM directory and performs string\n * replacements of the template variables specified in the `replacements`\n * argument.\n *\n * For non-string replacements, the template should use the\n * `declare const ${key}: ${type}` syntax. to ensure that the type is correct\n * and the typescript can compile. You may have to use `@ts-expect-error` to\n * handle replacement values that are related to imports.\n *\n * @param entrypoint the entrypoint to load\n * @param replacements string replacements to perform\n * @param injections code injections to perform\n * @param imports optional imports to insert or set to null\n * @returns the loaded file with the replacements\n */\nexport async function loadEntrypoint(\n entrypoint:\n | 'app-page'\n | 'app-route'\n | 'edge-app-route'\n | 'edge-ssr'\n | 'edge-ssr-app'\n | 'middleware'\n | 'pages'\n | 'pages-api',\n replacements: Record<`VAR_${string}`, string>,\n injections?: Record<string, string>,\n imports?: Record<string, string | null>\n): Promise<string> {\n const templatePath = path.resolve(\n path.join(TEMPLATES_ESM_FOLDER, `${entrypoint}.js`)\n )\n let content = await fs.readFile(templatePath)\n\n return getBindingsSync().expandNextJsTemplate(\n content,\n // Ensure that we use unix-style path separators for the import paths\n path.join(TEMPLATE_SRC_FOLDER, `${entrypoint}.js`).replace(/\\\\/g, '/'),\n PACKAGE_ROOT.replace(/\\\\/g, '/'),\n replacements,\n injections ?? {},\n imports ?? {}\n )\n}\n"],"names":["loadEntrypoint","PACKAGE_ROOT","path","normalize","join","__dirname","TEMPLATE_SRC_FOLDER","TEMPLATES_ESM_FOLDER","entrypoint","replacements","injections","imports","templatePath","resolve","content","fs","readFile","getBindingsSync","expandNextJsTemplate","replace"],"mappings":";;;;+BA2BsBA;;;eAAAA;;;iEA3BP;6DACE;qBACe;;;;;;AAEhC,6DAA6D;AAC7D,MAAMC,eAAeC,aAAI,CAACC,SAAS,CAACD,aAAI,CAACE,IAAI,CAACC,WAAW;AACzD,MAAMC,sBAAsBJ,aAAI,CAACC,SAAS,CAACD,aAAI,CAACE,IAAI,CAACC,WAAW;AAChE,MAAME,uBAAuBL,aAAI,CAACC,SAAS,CACzCD,aAAI,CAACE,IAAI,CAACC,WAAW;AAmBhB,eAAeL,eACpBQ,UAQe,EACfC,YAA6C,EAC7CC,UAAmC,EACnCC,OAAuC;IAEvC,MAAMC,eAAeV,aAAI,CAACW,OAAO,CAC/BX,aAAI,CAACE,IAAI,CAACG,sBAAsB,GAAGC,WAAW,GAAG,CAAC;IAEpD,IAAIM,UAAU,MAAMC,iBAAE,CAACC,QAAQ,CAACJ;IAEhC,OAAOK,IAAAA,oBAAe,IAAGC,oBAAoB,CAC3CJ,SACA,qEAAqE;IACrEZ,aAAI,CAACE,IAAI,CAACE,qBAAqB,GAAGE,WAAW,GAAG,CAAC,EAAEW,OAAO,CAAC,OAAO,MAClElB,aAAakB,OAAO,CAAC,OAAO,MAC5BV,cACAC,cAAc,CAAC,GACfC,WAAW,CAAC;AAEhB","ignoreList":[0]}
@@ -40,7 +40,7 @@ export declare class Lockfile {
40
40
  * - If we fail to acquire the lock, we return `undefined`.
41
41
  * - If we're on wasm, this always returns a dummy `Lockfile` object.
42
42
  */
43
- static tryAcquire(path: string, unlockOnExit?: boolean): Promise<Lockfile | undefined>;
43
+ static tryAcquire(path: string, unlockOnExit?: boolean): Lockfile | undefined;
44
44
  /**
45
45
  * Attempts to create or acquire a lockfile using `Lockfile.tryAcquire`. If
46
46
  * that returns `undefined`, indicating that another process or caller has the
@@ -10,6 +10,7 @@ Object.defineProperty(exports, "Lockfile", {
10
10
  });
11
11
  const _picocolors = require("../lib/picocolors");
12
12
  const _log = /*#__PURE__*/ _interop_require_wildcard(require("./output/log"));
13
+ const _swc = require("./swc");
13
14
  function _getRequireWildcardCache(nodeInterop) {
14
15
  if (typeof WeakMap !== "function") return null;
15
16
  var cacheBabelInterop = new WeakMap();
@@ -64,20 +65,15 @@ class Lockfile {
64
65
  *
65
66
  * - If we fail to acquire the lock, we return `undefined`.
66
67
  * - If we're on wasm, this always returns a dummy `Lockfile` object.
67
- */ static async tryAcquire(path, unlockOnExit = true) {
68
- const { loadBindings } = require('./swc');
69
- // Ideally we could provide a sync version of `tryAcquire`, but
70
- // `loadBindings` is async. We're okay with skipping async-loaded wasm
71
- // bindings and the internal `loadNative` function is synchronous, but it
72
- // lacks some checks that `loadBindings` has.
73
- const bindings = await loadBindings();
68
+ */ static tryAcquire(path, unlockOnExit = true) {
69
+ const bindings = (0, _swc.getBindingsSync)();
74
70
  if (bindings.isWasm) {
75
71
  _log.info(`Skipping creating a lockfile at ${(0, _picocolors.cyan)(path)} because we're using WASM bindings`);
76
72
  return new Lockfile(bindings, undefined);
77
73
  } else {
78
74
  let nativeLockfile;
79
75
  try {
80
- nativeLockfile = await bindings.lockfileTryAcquire(path);
76
+ nativeLockfile = bindings.lockfileTryAcquireSync(path);
81
77
  } catch (e) {
82
78
  // this happens if there's an IO error (e.g. `ENOENT`), which is
83
79
  // different than if we just didn't acquire the lock
@@ -123,7 +119,7 @@ class Lockfile {
123
119
  const startMs = Date.now();
124
120
  let lockfile;
125
121
  while(Date.now() - startMs < MAX_RETRY_MS){
126
- lockfile = await Lockfile.tryAcquire(path, unlockOnExit);
122
+ lockfile = Lockfile.tryAcquire(path, unlockOnExit);
127
123
  if (lockfile !== undefined) break;
128
124
  await new Promise((resolve)=>setTimeout(resolve, RETRY_DELAY_MS));
129
125
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/build/lockfile.ts"],"sourcesContent":["import { bold, cyan } from '../lib/picocolors'\nimport * as Log from './output/log'\n\nimport type { Binding, Lockfile as NativeLockfile } from './swc/types'\n\nconst RETRY_DELAY_MS = 10\nconst MAX_RETRY_MS = 1000\n\n/**\n * A cross-platform on-disk best-effort advisory exclusive lockfile\n * implementation.\n *\n * On Windows, this opens a file in write mode with the `FILE_SHARE_WRITE` flag\n * unset, so it still allows reading the lockfile. This avoids breaking tools\n * that read the contents of `.next`.\n *\n * On POSIX platforms, this uses `flock()` via `std::fs::File::try_lock`:\n * https://doc.rust-lang.org/std/fs/struct.File.html#method.try_lock\n *\n * On WASM, a dummy implementation is used which always \"succeeds\" in acquiring\n * the lock.\n *\n * This provides a more idiomatic wrapper around the lockfile APIs exposed on\n * the native bindings object.\n *\n * If this lock is not explicitly closed with `unlock`, we will:\n * - If `unlockOnExit` is set (the default), it will make a best-effort attempt\n * to unlock the lockfile using `process.on('exit', ...)`. This is preferrable\n * on Windows where it may take some time after process exit for the operating\n * system to clean up locks that are not explicitly released by the process.\n * - If we fail to ever release the lockfile, the operating system will clean up\n * the lock and file descriptor upon process exit.\n */\nexport class Lockfile {\n /**\n * The underlying `Lockfile` object returned by the native bindings.\n *\n * This can be `undefined` on wasm, where we don't acquire a real lockfile.\n */\n private bindings: Binding\n private nativeLockfile: NativeLockfile | undefined\n private listener: NodeJS.ExitListener | undefined\n\n private constructor(\n bindings: Binding,\n nativeLockfile: NativeLockfile | undefined\n ) {\n this.bindings = bindings\n this.nativeLockfile = nativeLockfile\n }\n\n /**\n * Attempts to create or acquire an exclusive lockfile on disk. Lockfiles are\n * best-effort, depending on the platform.\n *\n * - If we fail to acquire the lock, we return `undefined`.\n * - If we're on wasm, this always returns a dummy `Lockfile` object.\n */\n static async tryAcquire(\n path: string,\n unlockOnExit: boolean = true\n ): Promise<Lockfile | undefined> {\n const { loadBindings } = require('./swc') as typeof import('./swc')\n // Ideally we could provide a sync version of `tryAcquire`, but\n // `loadBindings` is async. We're okay with skipping async-loaded wasm\n // bindings and the internal `loadNative` function is synchronous, but it\n // lacks some checks that `loadBindings` has.\n const bindings = await loadBindings()\n if (bindings.isWasm) {\n Log.info(\n `Skipping creating a lockfile at ${cyan(path)} because we're using WASM bindings`\n )\n return new Lockfile(bindings, undefined)\n } else {\n let nativeLockfile\n try {\n nativeLockfile = await bindings.lockfileTryAcquire(path)\n } catch (e) {\n // this happens if there's an IO error (e.g. `ENOENT`), which is\n // different than if we just didn't acquire the lock\n throw new Error(\n 'An IO error occurred while attempting to create and acquire the lockfile',\n { cause: e }\n )\n }\n if (nativeLockfile != null) {\n const jsLockfile = new Lockfile(bindings, nativeLockfile)\n if (unlockOnExit) {\n const exitListener = () => {\n // Best-Effort: If we don't do this, the operating system will\n // release the lock for us. This gives an opportunity to delete the\n // unlocked lockfile (which is not otherwise deleted on POSIX).\n //\n // This must be synchronous because `process.on('exit', ...)` is\n // synchronous.\n jsLockfile.unlockSync()\n }\n process.on('exit', exitListener)\n jsLockfile.listener = exitListener\n }\n return jsLockfile\n } else {\n return undefined\n }\n }\n }\n\n /**\n * Attempts to create or acquire a lockfile using `Lockfile.tryAcquire`. If\n * that returns `undefined`, indicating that another process or caller has the\n * lockfile, then this will output an error message and exit the process with\n * a non-zero exit code.\n *\n * This will retry a small number of times. This can be useful when running\n * processes in a loop, e.g. if cleanup isn't fully synchronous due to child\n * parent/processes.\n */\n static async acquireWithRetriesOrExit(\n path: string,\n processName: string,\n unlockOnExit: boolean = true\n ): Promise<Lockfile> {\n const startMs = Date.now()\n let lockfile\n while (Date.now() - startMs < MAX_RETRY_MS) {\n lockfile = await Lockfile.tryAcquire(path, unlockOnExit)\n if (lockfile !== undefined) break\n await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS))\n }\n if (lockfile === undefined) {\n Log.error(\n `Unable to acquire lock at ${cyan(path)}, is another instance of ${cyan(processName)} running?`\n )\n Log.info(\n `${bold('Suggestion:')} If you intended to restart ${cyan(processName)}, terminate the other process, and then try again.`\n )\n process.exit(1)\n }\n return lockfile\n }\n\n /**\n * Releases the lockfile and closes the file descriptor.\n *\n * If this is not called, the lock will be released by the operating system\n * when the file handle is closed during process exit.\n */\n async unlock(): Promise<void> {\n const { nativeLockfile, listener } = this\n if (nativeLockfile !== undefined) {\n await this.bindings.lockfileUnlock(nativeLockfile)\n }\n if (listener !== undefined) {\n process.off('exit', listener)\n }\n }\n\n /**\n * A blocking version of `unlock`.\n */\n unlockSync(): void {\n const { nativeLockfile, listener } = this\n if (nativeLockfile !== undefined) {\n this.bindings.lockfileUnlockSync(nativeLockfile)\n }\n if (listener !== undefined) {\n process.off('exit', listener)\n }\n }\n}\n"],"names":["Lockfile","RETRY_DELAY_MS","MAX_RETRY_MS","bindings","nativeLockfile","tryAcquire","path","unlockOnExit","loadBindings","require","isWasm","Log","info","cyan","undefined","lockfileTryAcquire","e","Error","cause","jsLockfile","exitListener","unlockSync","process","on","listener","acquireWithRetriesOrExit","processName","startMs","Date","now","lockfile","Promise","resolve","setTimeout","error","bold","exit","unlock","lockfileUnlock","off","lockfileUnlockSync"],"mappings":";;;;+BAiCaA;;;eAAAA;;;4BAjCc;6DACN;;;;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nBnB,eAAwB,IAAI,EACT;QACnB,MAAMoB,UAAUC,KAAKC,GAAG;QACxB,IAAIC;QACJ,MAAOF,KAAKC,GAAG,KAAKF,UAAUzB,aAAc;YAC1C4B,WAAW,MAAM9B,SAASK,UAAU,CAACC,MAAMC;YAC3C,IAAIuB,aAAahB,WAAW;YAC5B,MAAM,IAAIiB,QAAQ,CAACC,UAAYC,WAAWD,SAAS/B;QACrD;QACA,IAAI6B,aAAahB,WAAW;YAC1BH,KAAIuB,KAAK,CACP,CAAC,0BAA0B,EAAErB,IAAAA,gBAAI,EAACP,MAAM,yBAAyB,EAAEO,IAAAA,gBAAI,EAACa,aAAa,SAAS,CAAC;YAEjGf,KAAIC,IAAI,CACN,GAAGuB,IAAAA,gBAAI,EAAC,eAAe,4BAA4B,EAAEtB,IAAAA,gBAAI,EAACa,aAAa,kDAAkD,CAAC;YAE5HJ,QAAQc,IAAI,CAAC;QACf;QACA,OAAON;IACT;IAEA;;;;;GAKC,GACD,MAAMO,SAAwB;QAC5B,MAAM,EAAEjC,cAAc,EAAEoB,QAAQ,EAAE,GAAG,IAAI;QACzC,IAAIpB,mBAAmBU,WAAW;YAChC,MAAM,IAAI,CAACX,QAAQ,CAACmC,cAAc,CAAClC;QACrC;QACA,IAAIoB,aAAaV,WAAW;YAC1BQ,QAAQiB,GAAG,CAAC,QAAQf;QACtB;IACF;IAEA;;GAEC,GACDH,aAAmB;QACjB,MAAM,EAAEjB,cAAc,EAAEoB,QAAQ,EAAE,GAAG,IAAI;QACzC,IAAIpB,mBAAmBU,WAAW;YAChC,IAAI,CAACX,QAAQ,CAACqC,kBAAkB,CAACpC;QACnC;QACA,IAAIoB,aAAaV,WAAW;YAC1BQ,QAAQiB,GAAG,CAAC,QAAQf;QACtB;IACF;AACF","ignoreList":[0]}
1
+ {"version":3,"sources":["../../src/build/lockfile.ts"],"sourcesContent":["import { bold, cyan } from '../lib/picocolors'\nimport * as Log from './output/log'\nimport { getBindingsSync } from './swc'\n\nimport type { Binding, Lockfile as NativeLockfile } from './swc/types'\n\nconst RETRY_DELAY_MS = 10\nconst MAX_RETRY_MS = 1000\n\n/**\n * A cross-platform on-disk best-effort advisory exclusive lockfile\n * implementation.\n *\n * On Windows, this opens a file in write mode with the `FILE_SHARE_WRITE` flag\n * unset, so it still allows reading the lockfile. This avoids breaking tools\n * that read the contents of `.next`.\n *\n * On POSIX platforms, this uses `flock()` via `std::fs::File::try_lock`:\n * https://doc.rust-lang.org/std/fs/struct.File.html#method.try_lock\n *\n * On WASM, a dummy implementation is used which always \"succeeds\" in acquiring\n * the lock.\n *\n * This provides a more idiomatic wrapper around the lockfile APIs exposed on\n * the native bindings object.\n *\n * If this lock is not explicitly closed with `unlock`, we will:\n * - If `unlockOnExit` is set (the default), it will make a best-effort attempt\n * to unlock the lockfile using `process.on('exit', ...)`. This is preferrable\n * on Windows where it may take some time after process exit for the operating\n * system to clean up locks that are not explicitly released by the process.\n * - If we fail to ever release the lockfile, the operating system will clean up\n * the lock and file descriptor upon process exit.\n */\nexport class Lockfile {\n /**\n * The underlying `Lockfile` object returned by the native bindings.\n *\n * This can be `undefined` on wasm, where we don't acquire a real lockfile.\n */\n private bindings: Binding\n private nativeLockfile: NativeLockfile | undefined\n private listener: NodeJS.ExitListener | undefined\n\n private constructor(\n bindings: Binding,\n nativeLockfile: NativeLockfile | undefined\n ) {\n this.bindings = bindings\n this.nativeLockfile = nativeLockfile\n }\n\n /**\n * Attempts to create or acquire an exclusive lockfile on disk. Lockfiles are\n * best-effort, depending on the platform.\n *\n * - If we fail to acquire the lock, we return `undefined`.\n * - If we're on wasm, this always returns a dummy `Lockfile` object.\n */\n static tryAcquire(\n path: string,\n unlockOnExit: boolean = true\n ): Lockfile | undefined {\n const bindings = getBindingsSync()\n if (bindings.isWasm) {\n Log.info(\n `Skipping creating a lockfile at ${cyan(path)} because we're using WASM bindings`\n )\n return new Lockfile(bindings, undefined)\n } else {\n let nativeLockfile\n try {\n nativeLockfile = bindings.lockfileTryAcquireSync(path)\n } catch (e) {\n // this happens if there's an IO error (e.g. `ENOENT`), which is\n // different than if we just didn't acquire the lock\n throw new Error(\n 'An IO error occurred while attempting to create and acquire the lockfile',\n { cause: e }\n )\n }\n if (nativeLockfile != null) {\n const jsLockfile = new Lockfile(bindings, nativeLockfile)\n if (unlockOnExit) {\n const exitListener = () => {\n // Best-Effort: If we don't do this, the operating system will\n // release the lock for us. This gives an opportunity to delete the\n // unlocked lockfile (which is not otherwise deleted on POSIX).\n //\n // This must be synchronous because `process.on('exit', ...)` is\n // synchronous.\n jsLockfile.unlockSync()\n }\n process.on('exit', exitListener)\n jsLockfile.listener = exitListener\n }\n return jsLockfile\n } else {\n return undefined\n }\n }\n }\n\n /**\n * Attempts to create or acquire a lockfile using `Lockfile.tryAcquire`. If\n * that returns `undefined`, indicating that another process or caller has the\n * lockfile, then this will output an error message and exit the process with\n * a non-zero exit code.\n *\n * This will retry a small number of times. This can be useful when running\n * processes in a loop, e.g. if cleanup isn't fully synchronous due to child\n * parent/processes.\n */\n static async acquireWithRetriesOrExit(\n path: string,\n processName: string,\n unlockOnExit: boolean = true\n ): Promise<Lockfile> {\n const startMs = Date.now()\n let lockfile\n while (Date.now() - startMs < MAX_RETRY_MS) {\n lockfile = Lockfile.tryAcquire(path, unlockOnExit)\n if (lockfile !== undefined) break\n await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS))\n }\n if (lockfile === undefined) {\n Log.error(\n `Unable to acquire lock at ${cyan(path)}, is another instance of ${cyan(processName)} running?`\n )\n Log.info(\n `${bold('Suggestion:')} If you intended to restart ${cyan(processName)}, terminate the other process, and then try again.`\n )\n process.exit(1)\n }\n return lockfile\n }\n\n /**\n * Releases the lockfile and closes the file descriptor.\n *\n * If this is not called, the lock will be released by the operating system\n * when the file handle is closed during process exit.\n */\n async unlock(): Promise<void> {\n const { nativeLockfile, listener } = this\n if (nativeLockfile !== undefined) {\n await this.bindings.lockfileUnlock(nativeLockfile)\n }\n if (listener !== undefined) {\n process.off('exit', listener)\n }\n }\n\n /**\n * A blocking version of `unlock`.\n */\n unlockSync(): void {\n const { nativeLockfile, listener } = this\n if (nativeLockfile !== undefined) {\n this.bindings.lockfileUnlockSync(nativeLockfile)\n }\n if (listener !== undefined) {\n process.off('exit', listener)\n }\n }\n}\n"],"names":["Lockfile","RETRY_DELAY_MS","MAX_RETRY_MS","bindings","nativeLockfile","tryAcquire","path","unlockOnExit","getBindingsSync","isWasm","Log","info","cyan","undefined","lockfileTryAcquireSync","e","Error","cause","jsLockfile","exitListener","unlockSync","process","on","listener","acquireWithRetriesOrExit","processName","startMs","Date","now","lockfile","Promise","resolve","setTimeout","error","bold","exit","unlock","lockfileUnlock","off","lockfileUnlockSync"],"mappings":";;;;+BAkCaA;;;eAAAA;;;4BAlCc;6DACN;qBACW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIhC,MAAMC,iBAAiB;AACvB,MAAMC,eAAe;AA2Bd,MAAMF;IAUX,YACEG,QAAiB,EACjBC,cAA0C,CAC1C;QACA,IAAI,CAACD,QAAQ,GAAGA;QAChB,IAAI,CAACC,cAAc,GAAGA;IACxB;IAEA;;;;;;GAMC,GACD,OAAOC,WACLC,IAAY,EACZC,eAAwB,IAAI,EACN;QACtB,MAAMJ,WAAWK,IAAAA,oBAAe;QAChC,IAAIL,SAASM,MAAM,EAAE;YACnBC,KAAIC,IAAI,CACN,CAAC,gCAAgC,EAAEC,IAAAA,gBAAI,EAACN,MAAM,kCAAkC,CAAC;YAEnF,OAAO,IAAIN,SAASG,UAAUU;QAChC,OAAO;YACL,IAAIT;YACJ,IAAI;gBACFA,iBAAiBD,SAASW,sBAAsB,CAACR;YACnD,EAAE,OAAOS,GAAG;gBACV,gEAAgE;gBAChE,oDAAoD;gBACpD,MAAM,qBAGL,CAHK,IAAIC,MACR,4EACA;oBAAEC,OAAOF;gBAAE,IAFP,qBAAA;2BAAA;gCAAA;kCAAA;gBAGN;YACF;YACA,IAAIX,kBAAkB,MA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IAEA;;GAEC,GACDH,aAAmB;QACjB,MAAM,EAAEhB,cAAc,EAAEmB,QAAQ,EAAE,GAAG,IAAI;QACzC,IAAInB,mBAAmBS,WAAW;YAChC,IAAI,CAACV,QAAQ,CAACoC,kBAAkB,CAACnC;QACnC;QACA,IAAImB,aAAaV,WAAW;YAC1BQ,QAAQiB,GAAG,CAAC,QAAQf;QACtB;IACF;AACF","ignoreList":[0]}
@@ -138,18 +138,28 @@ async function handleCJS({ cwd, nextConfigPath, compilerOptions }) {
138
138
  const swcOptions = resolveSWCOptions(cwd, compilerOptions);
139
139
  let hasRequire = false;
140
140
  try {
141
+ var _config_experimental;
141
142
  const nextConfigString = await (0, _promises.readFile)(nextConfigPath, 'utf8');
142
143
  // lazy require swc since it loads React before even setting NODE_ENV
143
144
  // resulting loading Development React on Production
144
- const { transform } = require('../swc');
145
- const { code } = await transform(nextConfigString, swcOptions);
145
+ const { loadBindings } = require('../swc');
146
+ const bindings = await loadBindings();
147
+ const { code } = await bindings.transform(nextConfigString, swcOptions);
146
148
  // register require hook only if require exists
147
149
  if (code.includes('require(')) {
148
150
  (0, _requirehook.registerHook)(swcOptions);
149
151
  hasRequire = true;
150
152
  }
151
153
  // filename & extension don't matter here
152
- return (0, _requirehook.requireFromString)(code, (0, _nodepath.resolve)(cwd, 'next.config.compiled.js'));
154
+ const config = (0, _requirehook.requireFromString)(code, (0, _nodepath.resolve)(cwd, 'next.config.compiled.js'));
155
+ // At this point we have already loaded the bindings without this configuration setting due to the `transform` call above.
156
+ // Possibly we fell back to wasm in which case, it all works out but if not we need to warn
157
+ // that the configuration was ignored.
158
+ if ((config == null ? void 0 : (_config_experimental = config.experimental) == null ? void 0 : _config_experimental.useWasmBinary) && !bindings.isWasm) {
159
+ (0, _log.warn)('Using a next.config.ts file is incompatible with `experimental.useWasmBinary` unless ' + '`--experimental-next-config-strip-types` is also passed.\nSetting `useWasmBinary` to `false');
160
+ config.experimental.useWasmBinary = false;
161
+ }
162
+ return config;
153
163
  } catch (error) {
154
164
  throw error;
155
165
  } finally{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/build/next-config-ts/transpile-config.ts"],"sourcesContent":["import type { Options as SWCOptions } from '@swc/core'\nimport type { CompilerOptions } from 'typescript'\n\nimport { resolve } from 'node:path'\nimport { readFile } from 'node:fs/promises'\nimport { pathToFileURL } from 'node:url'\nimport { deregisterHook, registerHook, requireFromString } from './require-hook'\nimport { warn, warnOnce } from '../output/log'\nimport { installDependencies } from '../../lib/install-dependencies'\nimport { getNodeOptionsArgs } from '../../server/lib/utils'\n\nfunction resolveSWCOptions(\n cwd: string,\n compilerOptions: CompilerOptions\n): SWCOptions {\n return {\n jsc: {\n parser: {\n syntax: 'typescript',\n },\n ...(compilerOptions.paths ? { paths: compilerOptions.paths } : {}),\n ...(compilerOptions.baseUrl\n ? // Needs to be an absolute path.\n { baseUrl: resolve(cwd, compilerOptions.baseUrl) }\n : compilerOptions.paths\n ? // If paths is given, baseUrl is required.\n { baseUrl: cwd }\n : {}),\n },\n module: {\n type: 'commonjs',\n },\n isModule: 'unknown',\n env: {\n targets: {\n // Setting the Node.js version can reduce unnecessary code generation.\n node: process?.versions?.node ?? '20.19.0',\n },\n },\n } satisfies SWCOptions\n}\n\n// Ported from next/src/lib/verify-typescript-setup.ts\n// Although this overlaps with the later `verifyTypeScriptSetup`,\n// it is acceptable since the time difference in the worst case is trivial,\n// as we are only preparing to install the dependencies once more.\nasync function verifyTypeScriptSetup(cwd: string, configFileName: string) {\n try {\n // Quick module check.\n require.resolve('typescript', { paths: [cwd] })\n } catch (error) {\n if (\n error &&\n typeof error === 'object' &&\n 'code' in error &&\n error.code === 'MODULE_NOT_FOUND'\n ) {\n warn(\n `Installing TypeScript as it was not found while loading \"${configFileName}\".`\n )\n\n await installDependencies(cwd, [{ pkg: 'typescript' }], true).catch(\n (err) => {\n if (err && typeof err === 'object' && 'command' in err) {\n console.error(\n `Failed to install TypeScript, please install it manually to continue:\\n` +\n (err as any).command +\n '\\n'\n )\n }\n throw err\n }\n )\n }\n }\n}\n\nasync function getTsConfig(cwd: string): Promise<CompilerOptions> {\n const ts: typeof import('typescript') = require(\n require.resolve('typescript', { paths: [cwd] })\n )\n\n // NOTE: This doesn't fully cover the edge case for setting\n // \"typescript.tsconfigPath\" in next config which is currently\n // a restriction.\n const tsConfigPath = ts.findConfigFile(\n cwd,\n ts.sys.fileExists,\n 'tsconfig.json'\n )\n\n if (!tsConfigPath) {\n // It is ok to not return ts.getDefaultCompilerOptions() because\n // we are only looking for paths and baseUrl from tsConfig.\n return {}\n }\n\n const configFile = ts.readConfigFile(tsConfigPath, ts.sys.readFile)\n const parsedCommandLine = ts.parseJsonConfigFileContent(\n configFile.config,\n ts.sys,\n cwd\n )\n\n return parsedCommandLine.options\n}\n\nexport async function transpileConfig({\n nextConfigPath,\n configFileName,\n cwd,\n}: {\n nextConfigPath: string\n configFileName: string\n cwd: string\n}) {\n try {\n // envs are passed to the workers and preserve the flag\n if (process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED === 'true') {\n try {\n // Node.js v22.10.0+\n // Value is 'strip' or 'transform' based on how the feature is enabled.\n // https://nodejs.org/api/process.html#processfeaturestypescript\n // TODO: Remove `as any` once we bump @types/node to v22.10.0+\n if ((process.features as any).typescript) {\n // Run import() here to catch errors and fallback to legacy resolution.\n return (await import(pathToFileURL(nextConfigPath).href)).default\n }\n\n if (\n getNodeOptionsArgs().includes('--no-experimental-strip-types') ||\n process.execArgv.includes('--no-experimental-strip-types')\n ) {\n warnOnce(\n `Skipped resolving \"${configFileName}\" using Node.js native TypeScript resolution because it was disabled by the \"--no-experimental-strip-types\" flag.` +\n ' Falling back to legacy resolution.' +\n ' Learn more: https://nextjs.org/docs/app/api-reference/config/typescript#using-nodejs-native-typescript-resolver-for-nextconfigts'\n )\n }\n\n // Feature is not enabled, fallback to legacy resolution for current session.\n process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'false'\n } catch (cause) {\n warnOnce(\n `Failed to import \"${configFileName}\" using Node.js native TypeScript resolution.` +\n ' Falling back to legacy resolution.' +\n ' Learn more: https://nextjs.org/docs/app/api-reference/config/typescript#using-nodejs-native-typescript-resolver-for-nextconfigts',\n { cause }\n )\n // Once failed, fallback to legacy resolution for current session.\n process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'false'\n }\n }\n\n // Ensure TypeScript is installed to use the API.\n await verifyTypeScriptSetup(cwd, configFileName)\n const compilerOptions = await getTsConfig(cwd)\n\n return handleCJS({ cwd, nextConfigPath, compilerOptions })\n } catch (cause) {\n throw new Error(`Failed to transpile \"${configFileName}\".`, { cause })\n }\n}\n\nasync function handleCJS({\n cwd,\n nextConfigPath,\n compilerOptions,\n}: {\n cwd: string\n nextConfigPath: string\n compilerOptions: CompilerOptions\n}) {\n const swcOptions = resolveSWCOptions(cwd, compilerOptions)\n let hasRequire = false\n try {\n const nextConfigString = await readFile(nextConfigPath, 'utf8')\n // lazy require swc since it loads React before even setting NODE_ENV\n // resulting loading Development React on Production\n const { transform } = require('../swc') as typeof import('../swc')\n const { code } = await transform(nextConfigString, swcOptions)\n\n // register require hook only if require exists\n if (code.includes('require(')) {\n registerHook(swcOptions)\n hasRequire = true\n }\n\n // filename & extension don't matter here\n return requireFromString(code, resolve(cwd, 'next.config.compiled.js'))\n } catch (error) {\n throw error\n } finally {\n if (hasRequire) {\n deregisterHook()\n }\n }\n}\n"],"names":["transpileConfig","resolveSWCOptions","cwd","compilerOptions","process","jsc","parser","syntax","paths","baseUrl","resolve","module","type","isModule","env","targets","node","versions","verifyTypeScriptSetup","configFileName","require","error","code","warn","installDependencies","pkg","catch","err","console","command","getTsConfig","ts","tsConfigPath","findConfigFile","sys","fileExists","configFile","readConfigFile","readFile","parsedCommandLine","parseJsonConfigFileContent","config","options","nextConfigPath","__NEXT_NODE_NATIVE_TS_LOADER_ENABLED","features","typescript","pathToFileURL","href","default","getNodeOptionsArgs","includes","execArgv","warnOnce","cause","handleCJS","Error","swcOptions","hasRequire","nextConfigString","transform","registerHook","requireFromString","deregisterHook"],"mappings":";;;;+BA2GsBA;;;eAAAA;;;0BAxGE;0BACC;yBACK;6BACkC;qBACjC;qCACK;uBACD;AAEnC,SAASC,kBACPC,GAAW,EACXC,eAAgC;QAuBpBC,mBAAAA;IArBZ,OAAO;QACLC,KAAK;YACHC,QAAQ;gBACNC,QAAQ;YACV;YACA,GAAIJ,gBAAgBK,KAAK,GAAG;gBAAEA,OAAOL,gBAAgBK,KAAK;YAAC,IAAI,CAAC,CAAC;YACjE,GAAIL,gBAAgBM,OAAO,GAEvB;gBAAEA,SAASC,IAAAA,iBAAO,EAACR,KAAKC,gBAAgBM,OAAO;YAAE,IACjDN,gBAAgBK,KAAK,GAEnB;gBAAEC,SAASP;YAAI,IACf,CAAC,CAAC;QACV;QACAS,QAAQ;YACNC,MAAM;QACR;QACAC,UAAU;QACVC,KAAK;YACHC,SAAS;gBACP,sEAAsE;gBACtEC,MAAMZ,EAAAA,WAAAA,6BAAAA,oBAAAA,SAASa,QAAQ,qBAAjBb,kBAAmBY,IAAI,KAAI;YACnC;QACF;IACF;AACF;AAEA,sDAAsD;AACtD,iEAAiE;AACjE,2EAA2E;AAC3E,kEAAkE;AAClE,eAAeE,sBAAsBhB,GAAW,EAAEiB,cAAsB;IACtE,IAAI;QACF,sBAAsB;QACtBC,QAAQV,OAAO,CAAC,cAAc;YAAEF,OAAO;gBAACN;aAAI;QAAC;IAC/C,EAAE,OAAOmB,OAAO;QACd,IACEA,SACA,OAAOA,UAAU,YACjB,UAAUA,SACVA,MAAMC,IAAI,KAAK,oBACf;YACAC,IAAAA,SAAI,EACF,CAAC,yDAAyD,EAAEJ,eAAe,EAAE,CAAC;YAGhF,MAAMK,IAAAA,wCAAmB,EAACtB,KAAK;gBAAC;oBAAEuB,KAAK;gBAAa;aAAE,EAAE,MAAMC,KAAK,CACjE,CAACC;gBACC,IAAIA,OAAO,OAAOA,QAAQ,YAAY,aAAaA,KAAK;oBACtDC,QAA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version":3,"sources":["../../../src/build/next-config-ts/transpile-config.ts"],"sourcesContent":["import type { Options as SWCOptions } from '@swc/core'\nimport type { CompilerOptions } from 'typescript'\n\nimport { resolve } from 'node:path'\nimport { readFile } from 'node:fs/promises'\nimport { pathToFileURL } from 'node:url'\nimport { deregisterHook, registerHook, requireFromString } from './require-hook'\nimport { warn, warnOnce } from '../output/log'\nimport { installDependencies } from '../../lib/install-dependencies'\nimport { getNodeOptionsArgs } from '../../server/lib/utils'\n\nfunction resolveSWCOptions(\n cwd: string,\n compilerOptions: CompilerOptions\n): SWCOptions {\n return {\n jsc: {\n parser: {\n syntax: 'typescript',\n },\n ...(compilerOptions.paths ? { paths: compilerOptions.paths } : {}),\n ...(compilerOptions.baseUrl\n ? // Needs to be an absolute path.\n { baseUrl: resolve(cwd, compilerOptions.baseUrl) }\n : compilerOptions.paths\n ? // If paths is given, baseUrl is required.\n { baseUrl: cwd }\n : {}),\n },\n module: {\n type: 'commonjs',\n },\n isModule: 'unknown',\n env: {\n targets: {\n // Setting the Node.js version can reduce unnecessary code generation.\n node: process?.versions?.node ?? '20.19.0',\n },\n },\n } satisfies SWCOptions\n}\n\n// Ported from next/src/lib/verify-typescript-setup.ts\n// Although this overlaps with the later `verifyTypeScriptSetup`,\n// it is acceptable since the time difference in the worst case is trivial,\n// as we are only preparing to install the dependencies once more.\nasync function verifyTypeScriptSetup(cwd: string, configFileName: string) {\n try {\n // Quick module check.\n require.resolve('typescript', { paths: [cwd] })\n } catch (error) {\n if (\n error &&\n typeof error === 'object' &&\n 'code' in error &&\n error.code === 'MODULE_NOT_FOUND'\n ) {\n warn(\n `Installing TypeScript as it was not found while loading \"${configFileName}\".`\n )\n\n await installDependencies(cwd, [{ pkg: 'typescript' }], true).catch(\n (err) => {\n if (err && typeof err === 'object' && 'command' in err) {\n console.error(\n `Failed to install TypeScript, please install it manually to continue:\\n` +\n (err as any).command +\n '\\n'\n )\n }\n throw err\n }\n )\n }\n }\n}\n\nasync function getTsConfig(cwd: string): Promise<CompilerOptions> {\n const ts: typeof import('typescript') = require(\n require.resolve('typescript', { paths: [cwd] })\n )\n\n // NOTE: This doesn't fully cover the edge case for setting\n // \"typescript.tsconfigPath\" in next config which is currently\n // a restriction.\n const tsConfigPath = ts.findConfigFile(\n cwd,\n ts.sys.fileExists,\n 'tsconfig.json'\n )\n\n if (!tsConfigPath) {\n // It is ok to not return ts.getDefaultCompilerOptions() because\n // we are only looking for paths and baseUrl from tsConfig.\n return {}\n }\n\n const configFile = ts.readConfigFile(tsConfigPath, ts.sys.readFile)\n const parsedCommandLine = ts.parseJsonConfigFileContent(\n configFile.config,\n ts.sys,\n cwd\n )\n\n return parsedCommandLine.options\n}\n\nexport async function transpileConfig({\n nextConfigPath,\n configFileName,\n cwd,\n}: {\n nextConfigPath: string\n configFileName: string\n cwd: string\n}) {\n try {\n // envs are passed to the workers and preserve the flag\n if (process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED === 'true') {\n try {\n // Node.js v22.10.0+\n // Value is 'strip' or 'transform' based on how the feature is enabled.\n // https://nodejs.org/api/process.html#processfeaturestypescript\n // TODO: Remove `as any` once we bump @types/node to v22.10.0+\n if ((process.features as any).typescript) {\n // Run import() here to catch errors and fallback to legacy resolution.\n return (await import(pathToFileURL(nextConfigPath).href)).default\n }\n\n if (\n getNodeOptionsArgs().includes('--no-experimental-strip-types') ||\n process.execArgv.includes('--no-experimental-strip-types')\n ) {\n warnOnce(\n `Skipped resolving \"${configFileName}\" using Node.js native TypeScript resolution because it was disabled by the \"--no-experimental-strip-types\" flag.` +\n ' Falling back to legacy resolution.' +\n ' Learn more: https://nextjs.org/docs/app/api-reference/config/typescript#using-nodejs-native-typescript-resolver-for-nextconfigts'\n )\n }\n\n // Feature is not enabled, fallback to legacy resolution for current session.\n process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'false'\n } catch (cause) {\n warnOnce(\n `Failed to import \"${configFileName}\" using Node.js native TypeScript resolution.` +\n ' Falling back to legacy resolution.' +\n ' Learn more: https://nextjs.org/docs/app/api-reference/config/typescript#using-nodejs-native-typescript-resolver-for-nextconfigts',\n { cause }\n )\n // Once failed, fallback to legacy resolution for current session.\n process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'false'\n }\n }\n\n // Ensure TypeScript is installed to use the API.\n await verifyTypeScriptSetup(cwd, configFileName)\n const compilerOptions = await getTsConfig(cwd)\n\n return handleCJS({ cwd, nextConfigPath, compilerOptions })\n } catch (cause) {\n throw new Error(`Failed to transpile \"${configFileName}\".`, { cause })\n }\n}\n\nasync function handleCJS({\n cwd,\n nextConfigPath,\n compilerOptions,\n}: {\n cwd: string\n nextConfigPath: string\n compilerOptions: CompilerOptions\n}) {\n const swcOptions = resolveSWCOptions(cwd, compilerOptions)\n let hasRequire = false\n try {\n const nextConfigString = await readFile(nextConfigPath, 'utf8')\n // lazy require swc since it loads React before even setting NODE_ENV\n // resulting loading Development React on Production\n const { loadBindings } = require('../swc') as typeof import('../swc')\n const bindings = await loadBindings()\n const { code } = await bindings.transform(nextConfigString, swcOptions)\n\n // register require hook only if require exists\n if (code.includes('require(')) {\n registerHook(swcOptions)\n hasRequire = true\n }\n\n // filename & extension don't matter here\n const config = requireFromString(\n code,\n resolve(cwd, 'next.config.compiled.js')\n )\n // At this point we have already loaded the bindings without this configuration setting due to the `transform` call above.\n // Possibly we fell back to wasm in which case, it all works out but if not we need to warn\n // that the configuration was ignored.\n if (config?.experimental?.useWasmBinary && !bindings.isWasm) {\n warn(\n 'Using a next.config.ts file is incompatible with `experimental.useWasmBinary` unless ' +\n '`--experimental-next-config-strip-types` is also passed.\\nSetting `useWasmBinary` to `false'\n )\n config.experimental.useWasmBinary = false\n }\n return config\n } catch (error) {\n throw error\n } finally {\n if (hasRequire) {\n deregisterHook()\n }\n }\n}\n"],"names":["transpileConfig","resolveSWCOptions","cwd","compilerOptions","process","jsc","parser","syntax","paths","baseUrl","resolve","module","type","isModule","env","targets","node","versions","verifyTypeScriptSetup","configFileName","require","error","code","warn","installDependencies","pkg","catch","err","console","command","getTsConfig","ts","tsConfigPath","findConfigFile","sys","fileExists","configFile","readConfigFile","readFile","parsedCommandLine","parseJsonConfigFileContent","config","options","nextConfigPath","__NEXT_NODE_NATIVE_TS_LOADER_ENABLED","features","typescript","pathToFileURL","href","default","getNodeOptionsArgs","includes","execArgv","warnOnce","cause","handleCJS","Error","swcOptions","hasRequire","nextConfigString","loadBindings","bindings","transform","registerHook","requireFromString","experimental","useWasmBinary","isWasm","deregisterHook"],"mappings":";;;;+BA2GsBA;;;eAAAA;;;0BAxGE;0BACC;yBACK;6BACkC;qBACjC;qCACK;uBACD;AAEnC,SAASC,kBACPC,GAAW,EACXC,eAAgC;QAuBpBC,mBAAAA;IArBZ,OAAO;QACLC,KAAK;YACHC,QAAQ;gBACNC,QAAQ;YACV;YACA,GAAIJ,gBAAgBK,KAAK,GAAG;gBAAEA,OAAOL,gBAAgBK,KAAK;YAAC,IAAI,CAAC,CAAC;YACjE,GAAIL,gBAAgBM,OAAO,GAEvB;gBAAEA,SAASC,IAAAA,iBAAO,EAACR,KAAKC,gBAAgBM,OAAO;YAAE,IACjDN,gBAAgBK,KAAK,GAEnB;gBAAEC,SAASP;YAAI,IACf,CAAC,CAAC;QACV;QACAS,QAAQ;YACNC,MAAM;QACR;QACAC,UAAU;QACVC,KAAK;YACHC,SAAS;gBACP,sEAAsE;gBACtEC,MAAMZ,EAAAA,WAAAA,6BAAAA,oBAAAA,SAASa,QAAQ,qBAAjBb,kBAAmBY,IAAI,KAAI;YACnC;QACF;IACF;AACF;AAEA,sDAAsD;AACtD,iEAAiE;AACjE,2EAA2E;AAC3E,kEAAkE;AAClE,eAAeE,sBAAsBhB,GAAW,EAAEiB,cAAsB;IACtE,IAAI;QACF,sBAAsB;QACtBC,QAAQV,OAAO,CAAC,cAAc;YAAEF,OAAO;gBAACN;aAAI;QAAC;IAC/C,EAAE,OAAOmB,OAAO;QACd,IACEA,SACA,OAAOA,UAAU,YACjB,U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ACH,kBAAkBF;QAE5D,+CAA+C;QAC/C,IAAInC,KAAK6B,QAAQ,CAAC,aAAa;YAC7BY,IAAAA,yBAAY,EAACN;YACbC,aAAa;QACf;QAEA,yCAAyC;QACzC,MAAMjB,SAASuB,IAAAA,8BAAiB,EAC9B1C,MACAZ,IAAAA,iBAAO,EAACR,KAAK;QAEf,0HAA0H;QAC1H,2FAA2F;QAC3F,sCAAsC;QACtC,IAAIuC,CAAAA,2BAAAA,uBAAAA,OAAQwB,YAAY,qBAApBxB,qBAAsByB,aAAa,KAAI,CAACL,SAASM,MAAM,EAAE;YAC3D5C,IAAAA,SAAI,EACF,0FACE;YAEJkB,OAAOwB,YAAY,CAACC,aAAa,GAAG;QACtC;QACA,OAAOzB;IACT,EAAE,OAAOpB,OAAO;QACd,MAAMA;IACR,SAAU;QACR,IAAIqC,YAAY;YACdU,IAAAA,2BAAc;QAChB;IACF;AACF","ignoreList":[0]}
@@ -8,8 +8,10 @@ export declare function getSupportedArchTriples(): Record<string, any>;
8
8
  export declare const lockfilePatchPromise: {
9
9
  cur?: Promise<void>;
10
10
  };
11
+ /** Access the native bindings which should already have been loaded via `installBindings. Throws if they are not available. */
12
+ export declare function getBindingsSync(): Binding;
11
13
  /**
12
- * Attempts to load a native or wasm binding.
14
+ * Loads the native or wasm binding.
13
15
  *
14
16
  * By default, this first tries to use a native binding, falling back to a wasm binding if that
15
17
  * fails.
@@ -18,8 +20,8 @@ export declare const lockfilePatchPromise: {
18
20
  */
19
21
  export declare function loadBindings(useWasmBinary?: boolean): Promise<Binding>;
20
22
  export declare function createDefineEnv({ isTurbopack, clientRouterFilters, config, dev, distDir, projectPath, fetchCacheKeyPrefix, hasRewrites, middlewareMatchers, rewrites, }: Omit<DefineEnvOptions, 'isClient' | 'isNodeOrEdgeCompilation' | 'isEdgeServer' | 'isNodeServer'>): DefineEnv;
21
- export declare function isWasm(): Promise<boolean>;
22
23
  export declare function transform(src: string, options?: any): Promise<any>;
24
+ /** Synchronously transforms the source and loads the native bindings. */
23
25
  export declare function transformSync(src: string, options?: any): any;
24
26
  export declare function minify(src: string, options: any): Promise<{
25
27
  code: string;
@@ -5,11 +5,11 @@ Object.defineProperty(exports, "__esModule", {
5
5
  0 && (module.exports = {
6
6
  createDefineEnv: null,
7
7
  getBinaryMetadata: null,
8
+ getBindingsSync: null,
8
9
  getModuleNamedExports: null,
9
10
  getSupportedArchTriples: null,
10
11
  initCustomTraceSubscriber: null,
11
12
  isReactCompilerRequired: null,
12
- isWasm: null,
13
13
  loadBindings: null,
14
14
  lockfilePatchPromise: null,
15
15
  minify: null,
@@ -32,6 +32,9 @@ _export(exports, {
32
32
  getBinaryMetadata: function() {
33
33
  return getBinaryMetadata;
34
34
  },
35
+ getBindingsSync: function() {
36
+ return getBindingsSync;
37
+ },
35
38
  getModuleNamedExports: function() {
36
39
  return getModuleNamedExports;
37
40
  },
@@ -44,9 +47,6 @@ _export(exports, {
44
47
  isReactCompilerRequired: function() {
45
48
  return isReactCompilerRequired;
46
49
  },
47
- isWasm: function() {
48
- return isWasm;
49
- },
50
50
  loadBindings: function() {
51
51
  return loadBindings;
52
52
  },
@@ -130,7 +130,7 @@ function _interop_require_wildcard(obj, nodeInterop) {
130
130
  }
131
131
  return newObj;
132
132
  }
133
- const nextVersion = "16.0.2-canary.10";
133
+ const nextVersion = "16.0.2-canary.12";
134
134
  const ArchName = (0, _os.arch)();
135
135
  const PlatformName = (0, _os.platform)();
136
136
  function infoLog(...args) {
@@ -214,18 +214,35 @@ const knownDefaultWasmFallbackTriples = [
214
214
  // If node.js throws an error without error code, this should be `unknown` instead of undefined.
215
215
  // For the wasm-first targets (`knownDefaultWasmFallbackTriples`) this will be `unsupported_target`.
216
216
  let lastNativeBindingsLoadErrorCode = undefined;
217
- // Used to cache calls to `loadBindings`
217
+ // Used to cache racing calls to `loadBindings`
218
218
  let pendingBindings;
219
- // some things call `loadNative` directly instead of `loadBindings`... Cache calls to that
220
- // separately.
221
- let nativeBindings;
222
- // can allow hacky sync access to bindings for loadBindingsSync
223
- let wasmBindings;
219
+ // The cached loaded bindings
220
+ let loadedBindings = undefined;
224
221
  let downloadWasmPromise;
225
222
  let swcTraceFlushGuard;
226
223
  let downloadNativeBindingsPromise = undefined;
227
224
  const lockfilePatchPromise = {};
225
+ function getBindingsSync() {
226
+ if (!loadedBindings) {
227
+ if (pendingBindings) {
228
+ throw Object.defineProperty(new Error('Bindings not loaded yet, but they are being loaded, did you forget to await?'), "__NEXT_ERROR_CODE", {
229
+ value: "E906",
230
+ enumerable: false,
231
+ configurable: true
232
+ });
233
+ }
234
+ throw Object.defineProperty(new Error('bindings not loaded yet. Either call `loadBindings` to wait for them to be available or ensure that `installBindings` has already been called.'), "__NEXT_ERROR_CODE", {
235
+ value: "E907",
236
+ enumerable: false,
237
+ configurable: true
238
+ });
239
+ }
240
+ return loadedBindings;
241
+ }
228
242
  async function loadBindings(useWasmBinary = false) {
243
+ if (loadedBindings) {
244
+ return loadedBindings;
245
+ }
229
246
  if (pendingBindings) {
230
247
  return pendingBindings;
231
248
  }
@@ -298,7 +315,9 @@ async function loadBindings(useWasmBinary = false) {
298
315
  }
299
316
  logLoadFailure(attempts, true);
300
317
  });
301
- return pendingBindings;
318
+ loadedBindings = await pendingBindings;
319
+ pendingBindings = undefined;
320
+ return loadedBindings;
302
321
  }
303
322
  async function tryLoadNativeWithFallback(attempts) {
304
323
  const nativeBindingsDirectory = _path.default.join(_path.default.dirname(require.resolve('next/package.json')), 'next-swc-fallback');
@@ -359,11 +378,6 @@ function loadBindingsSync() {
359
378
  } catch (a) {
360
379
  attempts = attempts.concat(a);
361
380
  }
362
- // HACK: we can leverage the wasm bindings if they are already loaded
363
- // this may introduce race conditions
364
- if (wasmBindings) {
365
- return wasmBindings;
366
- }
367
381
  logLoadFailure(attempts);
368
382
  throw Object.defineProperty(new Error('Failed to load bindings', {
369
383
  cause: attempts
@@ -890,7 +904,7 @@ async function loadWasm(importPath = '') {
890
904
  }
891
905
  // Note wasm binary does not support async intefaces yet, all async
892
906
  // interface coereces to sync interfaces.
893
- wasmBindings = {
907
+ let wasmBindings = {
894
908
  css: {
895
909
  lightning: {
896
910
  transform: function(_options) {
@@ -1011,8 +1025,8 @@ async function loadWasm(importPath = '') {
1011
1025
  * Loads the native (non-wasm) bindings. Prefer `loadBindings` over this API, as that includes a
1012
1026
  * wasm fallback.
1013
1027
  */ function loadNative(importPath) {
1014
- if (nativeBindings) {
1015
- return nativeBindings;
1028
+ if (loadedBindings) {
1029
+ return loadedBindings;
1016
1030
  }
1017
1031
  if (process.env.NEXT_TEST_WASM) {
1018
1032
  throw Object.defineProperty(new Error('cannot run loadNative when `NEXT_TEST_WASM` is set'), "__NEXT_ERROR_CODE", {
@@ -1061,7 +1075,7 @@ async function loadWasm(importPath = '') {
1061
1075
  }
1062
1076
  }
1063
1077
  if (bindings) {
1064
- nativeBindings = {
1078
+ loadedBindings = {
1065
1079
  isWasm: false,
1066
1080
  transform (src, options) {
1067
1081
  var _options_jsc;
@@ -1160,7 +1174,7 @@ async function loadWasm(importPath = '') {
1160
1174
  return bindings.lockfileUnlockSync(lockfile);
1161
1175
  }
1162
1176
  };
1163
- return nativeBindings;
1177
+ return loadedBindings;
1164
1178
  }
1165
1179
  throw attempts;
1166
1180
  }
@@ -1177,48 +1191,39 @@ function getMdxOptions(options = {}) {
1177
1191
  function toBuffer(t) {
1178
1192
  return Buffer.from(JSON.stringify(t));
1179
1193
  }
1180
- async function isWasm() {
1181
- let bindings = await loadBindings();
1182
- return bindings.isWasm;
1183
- }
1184
1194
  async function transform(src, options) {
1185
- let bindings = await loadBindings();
1195
+ let bindings = getBindingsSync();
1186
1196
  return bindings.transform(src, options);
1187
1197
  }
1188
1198
  function transformSync(src, options) {
1189
- let bindings = loadBindingsSync();
1199
+ const bindings = loadBindingsSync();
1190
1200
  return bindings.transformSync(src, options);
1191
1201
  }
1192
- async function minify(src, options) {
1193
- let bindings = await loadBindings();
1202
+ function minify(src, options) {
1203
+ const bindings = getBindingsSync();
1194
1204
  return bindings.minify(src, options);
1195
1205
  }
1196
- async function isReactCompilerRequired(filename) {
1197
- let bindings = await loadBindings();
1206
+ function isReactCompilerRequired(filename) {
1207
+ const bindings = getBindingsSync();
1198
1208
  return bindings.reactCompiler.isReactCompilerRequired(filename);
1199
1209
  }
1200
1210
  async function parse(src, options) {
1201
- let bindings = await loadBindings();
1202
- let parserOptions = (0, _options.getParserOptions)(options);
1203
- return bindings.parse(src, parserOptions).then((astStr)=>JSON.parse(astStr));
1211
+ const bindings = getBindingsSync();
1212
+ const parserOptions = (0, _options.getParserOptions)(options);
1213
+ const parsed = await bindings.parse(src, parserOptions);
1214
+ return JSON.parse(parsed);
1204
1215
  }
1205
1216
  function getBinaryMetadata() {
1206
- var _bindings_getTargetTriple;
1207
- let bindings;
1208
- try {
1209
- bindings = loadNative();
1210
- } catch (e) {
1211
- // Suppress exceptions, this fn allows to fail to load native bindings
1212
- }
1217
+ var _loadedBindings_getTargetTriple;
1213
1218
  return {
1214
- target: bindings == null ? void 0 : (_bindings_getTargetTriple = bindings.getTargetTriple) == null ? void 0 : _bindings_getTargetTriple.call(bindings)
1219
+ target: loadedBindings == null ? void 0 : (_loadedBindings_getTargetTriple = loadedBindings.getTargetTriple) == null ? void 0 : _loadedBindings_getTargetTriple.call(loadedBindings)
1215
1220
  };
1216
1221
  }
1217
1222
  function initCustomTraceSubscriber(traceFileName) {
1218
1223
  if (!swcTraceFlushGuard) {
1224
+ var _getBindingsSync_initCustomTraceSubscriber, _getBindingsSync;
1219
1225
  // Wasm binary doesn't support trace emission
1220
- let bindings = loadNative();
1221
- swcTraceFlushGuard = bindings.initCustomTraceSubscriber == null ? void 0 : bindings.initCustomTraceSubscriber.call(bindings, traceFileName);
1226
+ swcTraceFlushGuard = (_getBindingsSync_initCustomTraceSubscriber = (_getBindingsSync = getBindingsSync()).initCustomTraceSubscriber) == null ? void 0 : _getBindingsSync_initCustomTraceSubscriber.call(_getBindingsSync, traceFileName);
1222
1227
  }
1223
1228
  }
1224
1229
  function once(fn) {
@@ -1232,21 +1237,19 @@ function once(fn) {
1232
1237
  }
1233
1238
  const teardownTraceSubscriber = once(()=>{
1234
1239
  try {
1235
- let bindings = loadNative();
1236
1240
  if (swcTraceFlushGuard) {
1237
- bindings.teardownTraceSubscriber == null ? void 0 : bindings.teardownTraceSubscriber.call(bindings, swcTraceFlushGuard);
1241
+ var _getBindingsSync_teardownTraceSubscriber, _getBindingsSync;
1242
+ (_getBindingsSync_teardownTraceSubscriber = (_getBindingsSync = getBindingsSync()).teardownTraceSubscriber) == null ? void 0 : _getBindingsSync_teardownTraceSubscriber.call(_getBindingsSync, swcTraceFlushGuard);
1238
1243
  }
1239
1244
  } catch (e) {
1240
1245
  // Suppress exceptions, this fn allows to fail to load native bindings
1241
1246
  }
1242
1247
  });
1243
1248
  async function getModuleNamedExports(resourcePath) {
1244
- const bindings = await loadBindings();
1245
- return bindings.rspack.getModuleNamedExports(resourcePath);
1249
+ return getBindingsSync().rspack.getModuleNamedExports(resourcePath);
1246
1250
  }
1247
1251
  async function warnForEdgeRuntime(source, isProduction) {
1248
- const bindings = await loadBindings();
1249
- return bindings.rspack.warnForEdgeRuntime(source, isProduction);
1252
+ return getBindingsSync().rspack.warnForEdgeRuntime(source, isProduction);
1250
1253
  }
1251
1254
 
1252
1255
  //# sourceMappingURL=index.js.map