Skip to content

Commit

Permalink
chore: update resolve compiler config
Browse files Browse the repository at this point in the history
  • Loading branch information
ErKeLost committed Oct 8, 2024
1 parent e8a06f3 commit 202aed4
Show file tree
Hide file tree
Showing 13 changed files with 2,395 additions and 2,200 deletions.
54 changes: 26 additions & 28 deletions packages/core/src/compiler/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { Compiler as BindingCompiler } from '../../binding/index.js';

import type { Resource } from '../index.js';
import type { Config, JsUpdateResult } from '../types/binding.js';
import { type ILogger, Logger } from '../utils/logger.js';
import { Compiler as BindingCompiler } from '../../binding/index.js';
import type { ResolvedUserConfig, Resource } from '../index.js';
import type { JsUpdateResult } from '../types/binding.js';

export const VIRTUAL_FARM_DYNAMIC_IMPORT_SUFFIX =
'.farm_dynamic_import_virtual_module';
'.farm_dynamic_import_virtual_module' as const;

/**
* Cause the update process is async, we need to keep the update queue to make sure the update process is executed in order.
Expand Down Expand Up @@ -40,11 +39,13 @@ export class Compiler {
private _resolveCompileFinish: (() => void) | null = null;
_isInitialCompile = true;

constructor(
public config: Config,
private logger: ILogger = new Logger()
) {
this._bindingCompiler = new BindingCompiler(this.config);
constructor(public config: ResolvedUserConfig) {
this._bindingCompiler = new BindingCompiler({
// @ts-ignore
config: { ...config.compilation, ...config.config },
jsPlugins: config.jsPlugins,
rustPlugins: config.rustPlugins
});
}

async traceDependencies() {
Expand All @@ -59,14 +60,15 @@ export class Compiler {
this.checkCompiling();
this._createCompileFinishPromise();
this.compiling = true;
if (process.env.FARM_PROFILE) {
this._bindingCompiler.compileSync();
} else {
await this._bindingCompiler.compile();
}
this.compiling = false;
this._resolveCompileFinishPromise();
if (this._isInitialCompile) {
try {
if (process.env.FARM_PROFILE) {
this._bindingCompiler.compileSync();
} else {
await this._bindingCompiler.compile();
}
} finally {
this.compiling = false;
this._resolveCompileFinishPromise();
this._isInitialCompile = false;
}
}
Expand Down Expand Up @@ -160,15 +162,11 @@ export class Compiler {
const resources = this.resources();
const outputPath = this.getOutputPath();

for (const [name, resource] of Object.entries(resources)) {
Object.entries(resources).forEach(([name, resource]) => {
const filePath = path.join(outputPath, name.split(/[?#]/)[0]);

if (!existsSync(path.dirname(filePath))) {
mkdirSync(path.dirname(filePath), { recursive: true });
}

mkdirSync(path.dirname(filePath), { recursive: true });
writeFileSync(filePath, new Uint8Array(resource));
}
});

this.callWriteResourcesHook();
}
Expand All @@ -180,7 +178,7 @@ export class Compiler {
string,
Resource
>,
config: this.config.config
config: this.config.compilation
});
}
}
Expand Down Expand Up @@ -255,14 +253,14 @@ export class Compiler {

private checkCompiling() {
if (this.compiling) {
this.logger.error('Already compiling', {
this.config.logger.error('Already compiling', {
exit: true
});
}
}

private getOutputPath(): string {
const { output, root } = this.config.config;
const { output, root } = this.config.compilation;
const configOutputPath = output.path;
const outputPath = path.isAbsolute(configOutputPath)
? configOutputPath
Expand Down
43 changes: 10 additions & 33 deletions packages/core/src/compiler/utils.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,20 @@
import { ResolvedUserConfig } from '../config/types.js';
import { getPluginHooks } from '../plugin/index.js';
import { Compiler } from './index.js';

export function createCompiler(resolvedUserConfig: ResolvedUserConfig) {
const {
jsPlugins,
rustPlugins,
compilation: compilationConfig,
logger
} = resolvedUserConfig;

const compiler = new Compiler(
{
config: compilationConfig,
jsPlugins,
rustPlugins
},
logger
);
return compiler;
}
import type {
ResolvedCompilation,
ResolvedUserConfig
} from '../config/types.js';

export async function resolveConfigureCompilerHook(
compiler: Compiler,
config: ResolvedUserConfig
) {
for (const hook of getPluginHooks(config.jsPlugins, 'configureCompiler')) {
await hook?.(compiler);
}
export function createCompiler(resolvedUserConfig: ResolvedUserConfig) {
return new Compiler(resolvedUserConfig);
}

export async function createInlineCompiler(
export function createInlineCompiler(
config: ResolvedUserConfig,
options = {}
options: ResolvedCompilation = {}
) {
const { Compiler } = await import('./index.js');
return new Compiler({
config: { ...config.compilation, ...options },
jsPlugins: config.jsPlugins,
rustPlugins: config.rustPlugins
...config,
compilation: { ...config.compilation, ...options }
});
}
10 changes: 4 additions & 6 deletions packages/core/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,7 @@ export async function resolveConfig(
const resolvedUserConfig = await resolveUserConfig(
config,
configFilePath,
compileMode,
logger
compileMode
);

resolvedUserConfig.logger = logger;
Expand Down Expand Up @@ -672,7 +671,7 @@ export async function readConfigFile(
);

const compiler = new Compiler({
config: normalizedConfig,
compilation: normalizedConfig,
jsPlugins: [],
rustPlugins: [[replaceDirnamePlugin, '{}']]
});
Expand Down Expand Up @@ -908,8 +907,7 @@ export async function resolveDefaultUserConfig(options: any) {
export async function resolveUserConfig(
userConfig: UserConfig,
configFilePath?: string | undefined,
mode: 'development' | 'production' | string = 'development',
logger: Logger = new Logger()
mode: 'development' | 'production' | string = 'development'
): Promise<ResolvedUserConfig> {
const resolvedUserConfig = {
...userConfig,
Expand All @@ -918,7 +916,7 @@ export async function resolveUserConfig(

// set internal config
if (configFilePath) {
const dependencies = await traceDependencies(configFilePath, logger);
const dependencies = await traceDependencies(configFilePath);
resolvedUserConfig.configFileDependencies = dependencies.sort();
resolvedUserConfig.configFilePath = configFilePath;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,7 @@ export async function normalizePersistentCache(
) {
const files = resolvedUserConfig?.configFileDependencies?.length
? resolvedUserConfig.configFileDependencies
: await traceDependencies(
resolvedUserConfig.configFilePath,
resolvedUserConfig.logger
);
: await traceDependencies(resolvedUserConfig.configFilePath);

const packages = [];

Expand Down
13 changes: 8 additions & 5 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,11 @@ import path from 'node:path';

import { JsUpdateResult } from '../binding/binding.js';
import { Compiler } from './compiler/index.js';
import {
createCompiler,
resolveConfigureCompilerHook
} from './compiler/utils.js';
import { createCompiler } from './compiler/utils.js';
import { __FARM_GLOBAL__ } from './config/_global.js';
import { UserConfig, resolveConfig } from './config/index.js';
import type { FarmCliOptions, ResolvedUserConfig } from './config/types.js';
import { getPluginHooks } from './plugin/index.js';
import { Server } from './server/index.js';
import { PersistentCacheBrand, bold, colors, green } from './utils/color.js';
import { convertErrorMessage } from './utils/error.js';
Expand Down Expand Up @@ -59,8 +57,13 @@ export async function build(

try {
const compiler = await createCompiler(resolvedUserConfig);
await resolveConfigureCompilerHook(compiler, resolvedUserConfig);

for (const hook of getPluginHooks(
resolvedUserConfig.jsPlugins,
'configureCompiler'
)) {
await hook?.(compiler);
}
if (output?.clean) {
compiler.removeOutputPathDir();
}
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/server/hmr-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@ export class HmrEngine {
let updatedFilesStr = queue
.map((item) => {
if (isAbsolute(item)) {
return relative(this.app.compiler.config.config.root, item);
return relative(this.app.compiler.config.root, item);
} else {
const resolvedPath = this.app.compiler.transformModulePath(
this.app.compiler.config.config.root,
this.app.compiler.config.root,
item
);
return relative(this.app.compiler.config.config.root, resolvedPath);
return relative(this.app.compiler.config.root, resolvedPath);
}
})
.join(', ');
Expand Down
33 changes: 16 additions & 17 deletions packages/core/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ import { openBrowser } from './open.js';
import { WsServer } from './ws.js';

import { __FARM_GLOBAL__ } from '../config/_global.js';
import { getSortedPluginHooksBindThis } from '../plugin/index.js';
import {
getPluginHooks,
getSortedPluginHooksBindThis
} from '../plugin/index.js';
import { getCacheDir, isCacheDirExists } from '../utils/cacheDir.js';
import { createDebugger } from '../utils/debug.js';
import { resolveServerUrls, teardownSIGTERMListener } from '../utils/http.js';
Expand Down Expand Up @@ -40,10 +43,7 @@ import type {
import type { Http2SecureServer } from 'node:http2';
import type * as net from 'node:net';

import {
createCompiler,
resolveConfigureCompilerHook
} from '../compiler/utils.js';
import { createCompiler } from '../compiler/utils.js';
import type {
FarmCliOptions,
HmrOptions,
Expand Down Expand Up @@ -160,10 +160,14 @@ export class Server extends httpServer {
this.#resolveOptions();

this.compiler = await createCompiler(this.resolvedUserConfig);
await resolveConfigureCompilerHook(
this.compiler,
this.resolvedUserConfig
);

for (const hook of getPluginHooks(
this.resolvedUserConfig.jsPlugins,
'configureCompiler'
)) {
await hook?.(this.compiler);
}

const [httpsOptions, publicFiles] = await Promise.all([
this.resolveHttpsConfig(this.serverOptions.https),
this.#handlePublicFiles()
Expand Down Expand Up @@ -418,7 +422,7 @@ export class Server extends httpServer {
__FARM_GLOBAL__.__FARM_SHOW_DEV_SERVER_URL__ && this.printUrls();
} catch (error) {
this.resolvedUserConfig.logger.error(
`start farm dev server error: ${error}`
`start farm dev server error: ${error} \n ${error.stack}`
);
// throw error;
}
Expand Down Expand Up @@ -626,20 +630,15 @@ export class Server extends httpServer {
*/
async #startCompile() {
// check if cache dir exists
const { persistentCache } = this.compiler.config.config;
const { persistentCache } = this.compiler.config.compilation;
const hasCacheDir = await isCacheDirExists(
getCacheDir(this.root, persistentCache)
);
const start = performance.now();
await this.#compile();

const duration = performance.now() - start;
bootstrap(
duration,
this.compiler.config,
hasCacheDir,
this.resolvedUserConfig
);
bootstrap(duration, this.compiler.config, hasCacheDir);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/server/middlewares/adaptorVite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export function adaptorViteMiddleware(app: Server): Connect.NextHandleFunction {

// try local file system
const localFilePath = path.join(
compiler.config.config.root,
compiler.config.root,
resourceWithoutPublicPath
);

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/server/middlewares/lazyCompilation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export function lazyCompilationMiddleware(
const paths = (parsedUrl.query.paths as string).split(',');

const isNodeEnvironment = parsedUrl.query.node;
const root = compiler.config.config.root;
const root = compiler.config.root;
const pathsStr = paths
.map((p) => {
if (
Expand Down
23 changes: 17 additions & 6 deletions packages/core/src/utils/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,29 @@ export function convertErrorMessage(error: Error) {

try {
const parsedErrors = JSON.parse(error.message);

if (Array.isArray(parsedErrors)) {
errorMessages = parsedErrors.map(
(item) => JSON.parse(item).message || String(item)
);
errorMessages = parsedErrors.map(parseErrorItem);
} else {
errorMessages = [
JSON.parse(parsedErrors).message || String(parsedErrors)
];
errorMessages = [parseErrorItem(parsedErrors)];
}
} catch {
errorMessages = [error.message];
}

return errorMessages.join('\n');
}

function parseErrorItem(item: any): string {
try {
const parsedItem = typeof item === 'string' ? JSON.parse(item) : item;

if (typeof parsedItem === 'object' && parsedItem !== null) {
return parsedItem.message || JSON.stringify(parsedItem);
} else {
return String(parsedItem);
}
} catch {
return String(item);
}
}
Loading

0 comments on commit 202aed4

Please sign in to comment.