Skip to content

Commit

Permalink
chore: optimize proxy middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
ErKeLost committed Dec 19, 2024
1 parent 61e0f89 commit 5025fb5
Show file tree
Hide file tree
Showing 10 changed files with 119 additions and 81 deletions.
3 changes: 2 additions & 1 deletion examples/arcgis/farm.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import visualizer from "@farmfe/js-plugin-visualizer";

export default defineConfig((env) => ({
compilation: {
// lazyCompilation: false,
// persistentCache: false,
minify: env.mode === 'production' ? {
exclude: [
Expand All @@ -27,4 +28,4 @@ export default defineConfig((env) => ({
plugins: [
process.env.FARM_VISUALIZER ? visualizer() : null
]
}))
}))
22 changes: 11 additions & 11 deletions packages/cli/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,24 @@ export interface GlobalCliOptions {
config?: string;
base?: string;
m?: string;
mode?: 'development' | 'production' | string;
mode?: string;
clearScreen?: boolean;
}

interface BaseServerOptions {
host?: string;
port?: number;
open?: boolean;
cors?: boolean;
strictPort?: boolean;
}

export interface CleanOptions {
recursive?: boolean;
}

export interface CliServerOptions {
port?: number;
open?: boolean;
export interface CliServerOptions extends BaseServerOptions {
hmr?: boolean;
cors?: boolean;
strictPort?: boolean;
}

export interface CliBuildOptions {
Expand Down Expand Up @@ -48,10 +52,6 @@ export interface CliBuildOptions {
| 'library-node';
}

export interface CliPreviewOptions {
host?: string | boolean;
port?: number;
open?: boolean | string;
export interface CliPreviewOptions extends BaseServerOptions {
outDir?: string;
strictPort?: boolean;
}
6 changes: 5 additions & 1 deletion packages/core/src/compiler/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export class Compiler {
});

// if there is already a update process, we need to wait for it to finish
if (this.compiling && !ignoreCompilingCheck) {
if (this.isCompilingAndCheckIgnored(ignoreCompilingCheck)) {
this._updateQueue.push({ paths, resolve });
return promise;
}
Expand Down Expand Up @@ -143,6 +143,10 @@ export class Compiler {
}
}

private isCompilingAndCheckIgnored(ignoreCompilingCheck: boolean): boolean {
return this.compiling && !ignoreCompilingCheck;
}

hasModule(resolvedPath: string): boolean {
return this._bindingCompiler.hasModule(resolvedPath);
}
Expand Down
45 changes: 21 additions & 24 deletions packages/core/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
Logger,
clearScreen,
colors,
determineEnvironment,
isArray,
isEmptyObject,
isObject,
Expand Down Expand Up @@ -61,10 +62,12 @@ 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 type { OutputConfig } from '../types/binding.js';
import type {
ConfigEnv,
DefaultOptionsType,
EnvResult,
FarmCliOptions,
Format,
HmrOptions,
NormalizedServerConfig,
ResolvedCompilation,
Expand All @@ -91,6 +94,8 @@ export function defineFarmConfig(config: UserConfigExport): UserConfigExport {
return config;
}

type UserConfigPromise = Promise<UserConfig | undefined>;

const COMMANDS = {
START: 'start',
BUILD: 'build',
Expand Down Expand Up @@ -337,11 +342,14 @@ export async function normalizeUserCompilationConfig(
// for node target, we should not define process.env.NODE_ENV
resolvedCompilation.output?.targetEnv === 'node'
? {}
: Object.keys(resolvedUserConfig.env || {}).reduce((env: any, key) => {
env[`$__farm_regex:(global(This)?\\.)?process\\.env\\.${key}`] =
JSON.stringify(resolvedUserConfig.env[key]);
return env;
}, {})
: Object.keys(resolvedUserConfig.env || {}).reduce<EnvResult>(
(env, key) => {
env[`$__farm_regex:(global(This)?\\.)?process\\.env\\.${key}`] =
JSON.stringify(resolvedUserConfig.env[key]);
return env;
},
{} as EnvResult
)
);

const require = createRequire(import.meta.url);
Expand Down Expand Up @@ -384,16 +392,9 @@ export async function normalizeUserCompilationConfig(
resolvedCompilation.mode ??= mode;

setProcessEnv(resolvedCompilation.mode);

// TODO add targetEnv `lib-browser` and `lib-node` support
const is_entry_html =
!resolvedCompilation.input ||
Object.values(resolvedCompilation.input).some(
(value) => value && value.endsWith('.html')
);

const targetEnv = determineEnvironment(resolvedCompilation.output.targetEnv);
if (
resolvedCompilation.output.targetEnv !== 'node' &&
targetEnv !== 'node' &&
isArray(resolvedCompilation.runtime.plugins) &&
resolvedUserConfig.server?.hmr &&
!resolvedCompilation.runtime.plugins.includes(hmrClientPluginPath)
Expand Down Expand Up @@ -551,7 +552,7 @@ export const DEFAULT_DEV_SERVER_OPTIONS: NormalizedServerConfig = {
name: 'localhost',
host: undefined
},
host: true,
host: 'localhost',
proxy: undefined,
hmr: DEFAULT_HMR_OPTIONS,
middlewareMode: false,
Expand Down Expand Up @@ -598,8 +599,6 @@ export const DEFAULT_COMPILATION_OPTIONS: Partial<ResolvedCompilation> = {
}
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any

function tryHttpsAsFileRead(value: unknown): string | Buffer | unknown {
if (typeof value === 'string') {
try {
Expand Down Expand Up @@ -647,7 +646,6 @@ export function normalizeDevServerConfig(
}) as NormalizedServerConfig;
}

type Format = Exclude<OutputConfig['format'], undefined>;
const formatFromExt: Record<string, Format> = {
cjs: 'cjs',
mjs: 'esm',
Expand All @@ -666,7 +664,7 @@ export async function readConfigFile(
configFilePath: string,
configEnv: ConfigEnv,
mode: CompilationMode = 'development'
): Promise<UserConfig | undefined> {
): UserConfigPromise {
if (!fse.existsSync(configFilePath)) return;

const format = getFormat(configFilePath);
Expand Down Expand Up @@ -826,7 +824,7 @@ export async function checkCompilationInputValue(
const { compilation } = userConfig;
const targetEnv = compilation?.output?.targetEnv;
const inputValue = Object.values(compilation?.input).filter(Boolean);
const isTargetNode = targetEnv === 'node';
const isTargetNode = determineEnvironment(targetEnv) === 'node';
const defaultHtmlPath = './index.html';
let inputIndexConfig: {
index?: string;
Expand Down Expand Up @@ -874,7 +872,6 @@ export async function checkCompilationInputValue(
`Build failed due to errors: Can not resolve ${
isTargetNode ? 'index.js or index.ts' : 'index.html'
} from ${userConfig.root}. \n${errorMessage}`
// { exit: true }
);
}
}
Expand Down Expand Up @@ -925,7 +922,7 @@ export async function resolvePlugins(
};
}

export async function resolveDefaultUserConfig(options: any) {
export async function resolveDefaultUserConfig(options: DefaultOptionsType) {
const defaultConfig: UserConfig = createDefaultConfig(options);

const resolvedUserConfig: ResolvedUserConfig = await resolveUserConfig(
Expand Down Expand Up @@ -995,7 +992,7 @@ export async function resolveUserConfig(
return resolvedUserConfig;
}

export function createDefaultConfig(options: any): UserConfig {
export function createDefaultConfig(options: DefaultOptionsType): UserConfig {
const { inlineOptions, mode, format, outputPath, fileName, configFilePath } =
options;

Expand Down
16 changes: 8 additions & 8 deletions packages/core/src/config/mergeConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,10 @@ import { isArray, isObject } from '../utils/share.js';
import { CompilationMode } from './env.js';
import { FarmCliOptions, UserConfig } from './types.js';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function mergeConfig<T extends Record<string, any>>(
userConfig: T,
target: T
): T {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result: Record<string, any> = { ...userConfig };
for (const key of Object.keys(target)) {
const left = result[key];
Expand Down Expand Up @@ -112,7 +110,7 @@ export function mergeFarmCliConfig(
left = mergeConfig(left, { compilation: { minify: options.minify } });
}

if (options.compilation.output.outDir) {
if (options.compilation.output.path) {
left = mergeConfig(left, {
compilation: { output: { path: options.outDir } }
});
Expand Down Expand Up @@ -151,21 +149,23 @@ export function mergeFarmCliConfig(
return mergeConfig(left, target);
}

export function initialCliOptions(options: any): any {
export function initialCliOptions(
options: FarmCliOptions & UserConfig
): FarmCliOptions & UserConfig {
const { mode, watch } = options;

const compilationOptions = options.compilation || {};
const { minify, sourcemap, treeShaking } = compilationOptions;
const { outDir, target, format } = compilationOptions.output || {};
const { path, targetEnv, format } = compilationOptions.output || {};

const input = compilationOptions.input
? Object.values(compilationOptions.input).filter(Boolean)
: [];
const hasInput = input.length > 0;

const output: UserConfig['compilation']['output'] = {
...(outDir && { path: outDir }),
...(target && { targetEnv: target }),
...(path && { path }),
...(targetEnv && { targetEnv }),
...(format && { format })
};

Expand All @@ -177,7 +177,7 @@ export function initialCliOptions(options: any): any {
...(treeShaking && { treeShaking })
};

const defaultOptions: any = {
const defaultOptions = {
compilation,
watch: !!watch,
root: options.root,
Expand Down
19 changes: 17 additions & 2 deletions packages/core/src/config/types.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { SecureServerOptions } from 'node:http2';

import { Server } from '../index.js';
import { CompilationMode, Server } from '../index.js';

import type { OutgoingHttpHeaders } from 'http';
import type { ServerOptions as HttpsServerOptions } from 'node:https';
import type { WatchOptions } from 'chokidar';
import type { RustPlugin } from '../plugin/rust/index.js';
import type { JsPlugin } from '../plugin/type.js';
import type { Config, CssConfig } from '../types/binding.js';
import type { Config, CssConfig, OutputConfig } from '../types/binding.js';
import type { Logger } from '../utils/index.js';

export interface HmrOptions {
Expand Down Expand Up @@ -262,3 +262,18 @@ export interface Alias {
find: string;
replacement: string;
}
export type Format = Exclude<OutputConfig['format'], undefined>;

export type DefaultOptionsType = {
inlineOptions?: FarmCliOptions;
configFilePath?: string;
format?: Format;
outputPath?: string;
fileName?: string;
mode?: CompilationMode;
};

export type EnvResult = Record<
`$__farm_regex:(global(This)?\\.)?process\\.env\\.${string}`,
string
>;
8 changes: 5 additions & 3 deletions packages/core/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -533,11 +533,13 @@ export class Server extends httpServer {

if (proxy) {
const middlewareServer =
isObject(middlewareMode) && 'server' in middlewareMode
(isObject(middlewareMode) && 'server' in middlewareMode
? middlewareMode.server
: this.httpServer;
: null) || this.httpServer;

this.middlewares.use(proxyMiddleware(this, middlewareServer));
this.middlewares.use(
proxyMiddleware(this, middlewareServer as HttpServer)
);
}

if (this.publicPath !== '/') {
Expand Down
Loading

0 comments on commit 5025fb5

Please sign in to comment.