Skip to content

Commit

Permalink
chore: optimize code (#2043)
Browse files Browse the repository at this point in the history
  • Loading branch information
ErKeLost authored Jan 5, 2025
1 parent 4c04834 commit d7eaeff
Show file tree
Hide file tree
Showing 7 changed files with 92 additions and 91 deletions.
2 changes: 2 additions & 0 deletions packages/core/src/compiler/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,9 @@ export class Compiler {
this._updateQueue.push({ paths, resolve });
return promise;
}

this.compiling = true;

try {
const res = await this._bindingCompiler.update(
paths,
Expand Down
107 changes: 20 additions & 87 deletions packages/core/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
Expand All @@ -12,11 +11,11 @@ import { JsPlugin } from '../index.js';
import {
type RustPlugin,
getSortedPlugins,
handleVitePlugins,
resolveAsyncPlugins,
resolveConfigHook,
resolveConfigResolvedHook,
resolveFarmPlugins
resolveFarmPlugins,
resolveVitePlugins
} from '../plugin/index.js';

import {
Expand Down Expand Up @@ -46,7 +45,6 @@ import { normalizePersistentCache } from './normalize-config/normalize-persisten
import { parseUserConfig } from './schema.js';

import { externalAdapter } from '../plugin/js/external-adapter.js';
import { ViteModuleGraphAdapter } from '../plugin/js/vite-server-adapter.js';
import { convertErrorMessage } from '../utils/error.js';
import { resolveHostname } from '../utils/http.js';
import merge from '../utils/merge.js';
Expand All @@ -64,15 +62,15 @@ import { normalizeExternal } from './normalize-config/normalize-external.js';
import { normalizePartialBundling } from './normalize-config/normalize-partial-bundling.js';
import { normalizeResolve } from './normalize-config/normalize-resolve.js';

import { wrapPluginUpdateModules } from '../plugin/js/utils.js';
import type {
ConfigEnv,
ConfigResult,
DefaultOptionsType,
EnvResult,
FarmCliOptions,
Format,
HmrOptions,
ModuleContext,
ModuleNode,
NormalizedServerConfig,
ResolvedCompilation,
ResolvedUserConfig,
Expand Down Expand Up @@ -283,16 +281,12 @@ export async function normalizeUserCompilationConfig(
const { compilation, root } = resolvedUserConfig;

// resolve root path

const resolvedRootPath = normalizePath(root);

resolvedUserConfig.root = resolvedRootPath;

// if normalize default config, skip check input option
const inputIndexConfig = await checkCompilationInputValue(
resolvedUserConfig,
resolvedUserConfig.logger
);
const inputIndexConfig = await checkCompilationInputValue(resolvedUserConfig);

const resolvedCompilation: ResolvedCompilation = merge(
{},
Expand Down Expand Up @@ -772,19 +766,13 @@ export async function loadConfigFile(
inlineOptions: FarmCliOptions & UserConfig,
configEnv: ConfigEnv,
mode: CompilationMode = 'development'
): Promise<
| {
config: UserConfig;
configFilePath: string;
}
| undefined
> {
const { root = '.' } = inlineOptions;
): Promise<ConfigResult | undefined> {
const { root = '.', configFile } = inlineOptions;
const configRootPath = path.resolve(root);
let resolvedConfigFilePath: string | undefined;
try {
resolvedConfigFilePath = await resolveConfigFilePath(
inlineOptions.configFile,
configFile,
root,
configRootPath
);
Expand Down Expand Up @@ -825,8 +813,7 @@ export async function loadConfigFile(
}

export async function checkCompilationInputValue(
userConfig: UserConfig,
logger: Logger
userConfig: ResolvedUserConfig
) {
const { compilation } = userConfig;
const targetEnv = compilation?.output?.targetEnv;
Expand Down Expand Up @@ -875,7 +862,7 @@ export async function checkCompilationInputValue(

// If no index file is found, throw an error
if (!inputIndexConfig.index) {
logger.error(
userConfig.logger.error(
`Build failed due to errors: Can not resolve ${
isTargetNode ? 'index.js or index.ts' : 'index.html'
} from ${userConfig.root}. \n${errorMessage}`
Expand Down Expand Up @@ -911,23 +898,19 @@ export async function resolvePlugins(
userConfig: UserConfig,
mode: CompilationMode
) {
const { jsPlugins: rawJsPlugins, rustPlugins } =
await resolveFarmPlugins(userConfig);
const jsPlugins = (await resolveAndFilterAsyncPlugins(rawJsPlugins)).map(
wrapPluginUpdateModules
);
const vitePlugins = (userConfig?.vitePlugins ?? []).filter(Boolean);

const vitePluginAdapters = vitePlugins.length
? await handleVitePlugins(vitePlugins, userConfig, mode)
: [];
const [farmPlugins, vitePluginAdapters] = await Promise.all([
resolveFarmPlugins(userConfig),
resolveVitePlugins(userConfig, mode)
]);

return {
jsPlugins,
vitePlugins,
rustPlugins,
const resolvePluginsResult = {
jsPlugins: farmPlugins.jsPlugins.map(wrapPluginUpdateModules),
vitePlugins: (userConfig?.vitePlugins ?? []).filter(Boolean),
rustPlugins: farmPlugins.rustPlugins,
vitePluginAdapters
};

return resolvePluginsResult;
}

export async function resolveDefaultUserConfig(options: DefaultOptionsType) {
Expand Down Expand Up @@ -985,7 +968,6 @@ export async function resolveUserConfig(
resolvedUserConfig.env = {
...userEnv,
NODE_ENV: userConfig.compilation.mode,
// TODO publicPath rewrite to BASE_URL
BASE_URL: userConfig.compilation.output.publicPath ?? '/',
mode: userConfig.mode,
DEV: userConfig.compilation.mode === ENV_DEVELOPMENT,
Expand Down Expand Up @@ -1069,17 +1051,6 @@ export async function resolveConfigFilePath(
}
}

export function checkClearScreen(
inlineConfig: FarmCliOptions | ResolvedUserConfig
) {
if (
inlineConfig?.clearScreen &&
!__FARM_GLOBAL__.__FARM_RESTART_DEV_SERVER__
) {
clearScreen();
}
}

export function getFormat(configFilePath: string): Format {
return process.env.FARM_CONFIG_FORMAT === 'cjs'
? 'cjs'
Expand Down Expand Up @@ -1114,41 +1085,3 @@ function getNamespaceName(rootPath: string) {
}
return FARM_DEFAULT_NAMESPACE;
}

function wrapPluginUpdateModules(plugin: JsPlugin): JsPlugin {
if (!plugin.updateModules?.executor) {
return plugin;
}
const originalExecutor = plugin.updateModules.executor;
const moduleGraph = new ViteModuleGraphAdapter(plugin.name);

plugin.updateModules.executor = async ({ paths }, ctx) => {
moduleGraph.context = ctx;
for (const [file, type] of paths) {
const mods = moduleGraph.getModulesByFile(
file
) as unknown as ModuleNode[];

const filename = normalizePath(file);
const moduleContext: ModuleContext = {
file: filename,
timestamp: Date.now(),
type,
paths,
modules: (mods ?? []).map(
(m) =>
({
...m,
id: normalizePath(m.id),
file: normalizePath(m.file)
}) as ModuleNode
),
read: function (): string | Promise<string> {
return readFile(file, 'utf-8');
}
};
return originalExecutor.call(plugin, moduleContext);
}
};
return plugin;
}
5 changes: 5 additions & 0 deletions packages/core/src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,3 +297,8 @@ export interface ModuleContext {
paths: string[];
read: (file: string) => string | Promise<string>;
}

export interface ConfigResult {
config: UserConfig;
configFilePath: string;
}
18 changes: 16 additions & 2 deletions packages/core/src/plugin/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,28 @@
export * from './js/index.js';
export * from './rust/index.js';

import { ResolvedUserConfig, type UserConfig } from '../config/index.js';
import {
CompilationMode,
ResolvedUserConfig,
type UserConfig
} from '../config/index.js';
import { isArray, isObject } from '../utils/index.js';
import merge from '../utils/merge.js';
import { convertPlugin } from './js/index.js';
import { convertPlugin, handleVitePlugins } from './js/index.js';
import { rustPluginResolver } from './rust/index.js';

import type { JsPlugin } from './type.js';

export async function resolveVitePlugins(
config: UserConfig,
mode: CompilationMode
) {
const plugins = config?.vitePlugins?.filter(Boolean) ?? [];
if (!plugins.length) return [];

return handleVitePlugins(plugins, config, mode);
}

export async function resolveFarmPlugins(config: UserConfig) {
const plugins = config.plugins ?? [];

Expand Down
44 changes: 43 additions & 1 deletion packages/core/src/plugin/js/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,16 @@ import type {

import { VITE_ADAPTER_VIRTUAL_MODULE } from './constants.js';

import { readFile } from 'node:fs/promises';
import { ModuleContext, ModuleNode } from '../../config/types.js';
import type { Config } from '../../types/binding.js';
import type {
JsPlugin,
JsResourcePotInfoData,
Resource,
ResourcePotInfo
} from '../type.js';
import { createModuleGraph } from './vite-server-adapter.js';

export type WatchChangeEvents = 'create' | 'update' | 'delete';

Expand Down Expand Up @@ -479,6 +483,44 @@ export function normalizeFilterPath(path: string): string {
return path;
}

function compatibleWin32Path(path: string): string {
export function compatibleWin32Path(path: string): string {
return path.replaceAll('/', '\\\\');
}

export function wrapPluginUpdateModules(plugin: JsPlugin): JsPlugin {
if (!plugin.updateModules?.executor) {
return plugin;
}
const originalExecutor = plugin.updateModules.executor;
const moduleGraph = createModuleGraph(plugin.name);

plugin.updateModules.executor = async ({ paths }, ctx) => {
moduleGraph.context = ctx;
for (const [file, type] of paths) {
const mods = moduleGraph.getModulesByFile(
file
) as unknown as ModuleNode[];

const filename = normalizePath(file);
const moduleContext: ModuleContext = {
file: filename,
timestamp: Date.now(),
type,
paths,
modules: (mods ?? []).map(
(m) =>
({
...m,
id: normalizePath(m.id),
file: normalizePath(m.file)
}) as ModuleNode
),
read: function (): string | Promise<string> {
return readFile(file, 'utf-8');
}
};
return originalExecutor.call(plugin, moduleContext);
}
};
return plugin;
}
6 changes: 5 additions & 1 deletion packages/core/src/plugin/js/vite-server-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,11 @@ export class ViteModuleGraphAdapter {
}
}

function proxyViteModuleNode(
export function createModuleGraph(pluginName: string) {
return new ViteModuleGraphAdapter(pluginName);
}

export function proxyViteModuleNode(
node: ViteModule,
pluginName: string,
context: CompilationContext
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/server/hmr-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ export class HmrEngine {
}
`);
});
// TODO optimize this part
// } catch (err) {
// checkClearScreen(this.app.compiler.config.config);
// this.app.logger.error(convertErrorMessage(err));
Expand Down

0 comments on commit d7eaeff

Please sign in to comment.