Initial commit

This commit is contained in:
makearmy 2025-09-22 10:37:53 -04:00
commit 78f8d225ee
21173 changed files with 2907774 additions and 0 deletions

View file

@ -0,0 +1,182 @@
import path from 'path';
import { validateTurboNextConfig } from '../../lib/turbopack-warning';
import { formatIssue, getTurbopackJsConfig, isPersistentCachingEnabled, isRelevantWarning } from '../../shared/lib/turbopack/utils';
import { NextBuildContext } from '../build-context';
import { createDefineEnv, loadBindings } from '../swc';
import { rawEntrypointsToEntrypoints, handleRouteType } from '../handle-entrypoints';
import { TurbopackManifestLoader } from '../../shared/lib/turbopack/manifest-loader';
import { promises as fs } from 'fs';
import { PHASE_PRODUCTION_BUILD } from '../../shared/lib/constants';
import loadConfig from '../../server/config';
import { hasCustomExportOutput } from '../../export/utils';
import { Telemetry } from '../../telemetry/storage';
import { setGlobal } from '../../trace';
export async function turbopackBuild() {
var _config_experimental, _config_turbopack, _config_experimental1;
await validateTurboNextConfig({
dir: NextBuildContext.dir,
isDev: false
});
const config = NextBuildContext.config;
const dir = NextBuildContext.dir;
const distDir = NextBuildContext.distDir;
const buildId = NextBuildContext.buildId;
const encryptionKey = NextBuildContext.encryptionKey;
const previewProps = NextBuildContext.previewProps;
const hasRewrites = NextBuildContext.hasRewrites;
const rewrites = NextBuildContext.rewrites;
const appDirOnly = NextBuildContext.appDirOnly;
const noMangling = NextBuildContext.noMangling;
const startTime = process.hrtime();
const bindings = await loadBindings(config == null ? void 0 : (_config_experimental = config.experimental) == null ? void 0 : _config_experimental.useWasmBinary);
const dev = false;
// const supportedBrowsers = await getSupportedBrowsers(dir, dev)
const supportedBrowsers = [
'last 1 Chrome versions, last 1 Firefox versions, last 1 Safari versions, last 1 Edge versions'
];
const persistentCaching = isPersistentCachingEnabled(config);
const project = await bindings.turbo.createProject({
projectPath: dir,
rootPath: ((_config_turbopack = config.turbopack) == null ? void 0 : _config_turbopack.root) || config.outputFileTracingRoot || dir,
distDir,
nextConfig: config,
jsConfig: await getTurbopackJsConfig(dir, config),
watch: {
enable: false
},
dev,
env: process.env,
defineEnv: createDefineEnv({
isTurbopack: true,
clientRouterFilters: NextBuildContext.clientRouterFilters,
config,
dev,
distDir,
fetchCacheKeyPrefix: config.experimental.fetchCacheKeyPrefix,
hasRewrites,
// Implemented separately in Turbopack, doesn't have to be passed here.
middlewareMatchers: undefined
}),
buildId,
encryptionKey,
previewProps,
browserslistQuery: supportedBrowsers.join(', '),
noMangling
}, {
persistentCaching,
memoryLimit: (_config_experimental1 = config.experimental) == null ? void 0 : _config_experimental1.turbopackMemoryLimit,
dependencyTracking: persistentCaching
});
try {
// Write an empty file in a known location to signal this was built with Turbopack
await fs.writeFile(path.join(distDir, 'turbopack'), '');
await fs.mkdir(path.join(distDir, 'server'), {
recursive: true
});
await fs.mkdir(path.join(distDir, 'static', buildId), {
recursive: true
});
await fs.writeFile(path.join(distDir, 'package.json'), JSON.stringify({
type: 'commonjs'
}, null, 2));
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const entrypoints = await project.writeAllEntrypointsToDisk(appDirOnly);
const manifestLoader = new TurbopackManifestLoader({
buildId,
distDir,
encryptionKey
});
const topLevelErrors = [];
const topLevelWarnings = [];
for (const issue of entrypoints.issues){
if (issue.severity === 'error' || issue.severity === 'fatal') {
topLevelErrors.push(formatIssue(issue));
} else if (isRelevantWarning(issue)) {
topLevelWarnings.push(formatIssue(issue));
}
}
if (topLevelWarnings.length > 0) {
console.warn(`Turbopack build encountered ${topLevelWarnings.length} warnings:\n${topLevelWarnings.join('\n')}`);
}
if (topLevelErrors.length > 0) {
throw Object.defineProperty(new Error(`Turbopack build failed with ${topLevelErrors.length} errors:\n${topLevelErrors.join('\n')}`), "__NEXT_ERROR_CODE", {
value: "E425",
enumerable: false,
configurable: true
});
}
const currentEntrypoints = await rawEntrypointsToEntrypoints(entrypoints);
const promises = [];
if (!appDirOnly) {
for (const [page, route] of currentEntrypoints.page){
promises.push(handleRouteType({
page,
route,
manifestLoader
}));
}
}
for (const [page, route] of currentEntrypoints.app){
promises.push(handleRouteType({
page,
route,
manifestLoader
}));
}
await Promise.all(promises);
await Promise.all([
manifestLoader.loadBuildManifest('_app'),
manifestLoader.loadPagesManifest('_app'),
manifestLoader.loadFontManifest('_app'),
manifestLoader.loadPagesManifest('_document'),
manifestLoader.loadBuildManifest('_error'),
manifestLoader.loadPagesManifest('_error'),
manifestLoader.loadFontManifest('_error'),
entrypoints.instrumentation && manifestLoader.loadMiddlewareManifest('instrumentation', 'instrumentation'),
entrypoints.middleware && await manifestLoader.loadMiddlewareManifest('middleware', 'middleware')
]);
await manifestLoader.writeManifests({
devRewrites: undefined,
productionRewrites: rewrites,
entrypoints: currentEntrypoints
});
const shutdownPromise = project.shutdown();
const time = process.hrtime(startTime);
return {
duration: time[0] + time[1] / 1e9,
buildTraceContext: undefined,
shutdownPromise
};
} catch (err) {
await project.shutdown();
throw err;
}
}
let shutdownPromise;
export async function workerMain(workerData) {
// setup new build context from the serialized data passed from the parent
Object.assign(NextBuildContext, workerData.buildContext);
/// load the config because it's not serializable
NextBuildContext.config = await loadConfig(PHASE_PRODUCTION_BUILD, NextBuildContext.dir);
// Matches handling in build/index.ts
// https://github.com/vercel/next.js/blob/84f347fc86f4efc4ec9f13615c215e4b9fb6f8f0/packages/next/src/build/index.ts#L815-L818
// Ensures the `config.distDir` option is matched.
if (hasCustomExportOutput(NextBuildContext.config)) {
NextBuildContext.config.distDir = '.next';
}
// Clone the telemetry for worker
const telemetry = new Telemetry({
distDir: NextBuildContext.config.distDir
});
setGlobal('telemetry', telemetry);
const result = await turbopackBuild();
shutdownPromise = result.shutdownPromise;
return result;
}
export async function waitForShutdown() {
if (shutdownPromise) {
await shutdownPromise;
}
}
//# sourceMappingURL=impl.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,64 @@
import path from 'path';
import { formatNodeOptions, getParsedNodeOptionsWithoutInspect } from '../../server/lib/utils';
import { Worker } from '../../lib/worker';
import { NextBuildContext } from '../build-context';
async function turbopackBuildWithWorker() {
const nodeOptions = getParsedNodeOptionsWithoutInspect();
try {
const worker = new Worker(path.join(__dirname, 'impl.js'), {
exposedMethods: [
'workerMain',
'waitForShutdown'
],
numWorkers: 1,
maxRetries: 0,
forkOptions: {
env: {
...process.env,
NEXT_PRIVATE_BUILD_WORKER: '1',
NODE_OPTIONS: formatNodeOptions(nodeOptions)
}
}
});
const { nextBuildSpan, ...prunedBuildContext } = NextBuildContext;
const result = await worker.workerMain({
buildContext: prunedBuildContext
});
// destroy worker when Turbopack has shutdown so it's not sticking around using memory
// We need to wait for shutdown to make sure persistent cache is flushed
result.shutdownPromise = worker.waitForShutdown().then(()=>{
worker.end();
});
return result;
} catch (err) {
// When the error is a serialized `Error` object we need to recreate the `Error` instance
// in order to keep the consistent error reporting behavior.
if (err.type === 'Error') {
const error = Object.defineProperty(new Error(err.message), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
if (err.name) {
error.name = err.name;
}
if (err.cause) {
error.cause = err.cause;
}
error.message = err.message;
error.stack = err.stack;
throw error;
}
throw err;
}
}
export function turbopackBuild(withWorker) {
if (withWorker) {
return turbopackBuildWithWorker();
} else {
const build = require('./impl').turbopackBuild;
return build();
}
}
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/build/turbopack-build/index.ts"],"sourcesContent":["import path from 'path'\nimport {\n formatNodeOptions,\n getParsedNodeOptionsWithoutInspect,\n} from '../../server/lib/utils'\nimport { Worker } from '../../lib/worker'\nimport { NextBuildContext } from '../build-context'\n\nasync function turbopackBuildWithWorker() {\n const nodeOptions = getParsedNodeOptionsWithoutInspect()\n\n try {\n const worker = new Worker(path.join(__dirname, 'impl.js'), {\n exposedMethods: ['workerMain', 'waitForShutdown'],\n numWorkers: 1,\n maxRetries: 0,\n forkOptions: {\n env: {\n ...process.env,\n NEXT_PRIVATE_BUILD_WORKER: '1',\n NODE_OPTIONS: formatNodeOptions(nodeOptions),\n },\n },\n }) as Worker & typeof import('./impl')\n const { nextBuildSpan, ...prunedBuildContext } = NextBuildContext\n const result = await worker.workerMain({\n buildContext: prunedBuildContext,\n })\n\n // destroy worker when Turbopack has shutdown so it's not sticking around using memory\n // We need to wait for shutdown to make sure persistent cache is flushed\n result.shutdownPromise = worker.waitForShutdown().then(() => {\n worker.end()\n })\n\n return result\n } catch (err: any) {\n // When the error is a serialized `Error` object we need to recreate the `Error` instance\n // in order to keep the consistent error reporting behavior.\n if (err.type === 'Error') {\n const error = new Error(err.message)\n if (err.name) {\n error.name = err.name\n }\n if (err.cause) {\n error.cause = err.cause\n }\n error.message = err.message\n error.stack = err.stack\n throw error\n }\n throw err\n }\n}\n\nexport function turbopackBuild(\n withWorker: boolean\n): ReturnType<typeof import('./impl').turbopackBuild> {\n if (withWorker) {\n return turbopackBuildWithWorker()\n } else {\n const build = (require('./impl') as typeof import('./impl')).turbopackBuild\n return build()\n }\n}\n"],"names":["path","formatNodeOptions","getParsedNodeOptionsWithoutInspect","Worker","NextBuildContext","turbopackBuildWithWorker","nodeOptions","worker","join","__dirname","exposedMethods","numWorkers","maxRetries","forkOptions","env","process","NEXT_PRIVATE_BUILD_WORKER","NODE_OPTIONS","nextBuildSpan","prunedBuildContext","result","workerMain","buildContext","shutdownPromise","waitForShutdown","then","end","err","type","error","Error","message","name","cause","stack","turbopackBuild","withWorker","build","require"],"mappings":"AAAA,OAAOA,UAAU,OAAM;AACvB,SACEC,iBAAiB,EACjBC,kCAAkC,QAC7B,yBAAwB;AAC/B,SAASC,MAAM,QAAQ,mBAAkB;AACzC,SAASC,gBAAgB,QAAQ,mBAAkB;AAEnD,eAAeC;IACb,MAAMC,cAAcJ;IAEpB,IAAI;QACF,MAAMK,SAAS,IAAIJ,OAAOH,KAAKQ,IAAI,CAACC,WAAW,YAAY;YACzDC,gBAAgB;gBAAC;gBAAc;aAAkB;YACjDC,YAAY;YACZC,YAAY;YACZC,aAAa;gBACXC,KAAK;oBACH,GAAGC,QAAQD,GAAG;oBACdE,2BAA2B;oBAC3BC,cAA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