Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Add origin schema and optimize server resolvedUserconfig renaming #2023

Merged
merged 3 commits into from
Dec 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/core/src/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ const serverSchema = z
middlewares: z.array(z.any()).optional(),
middlewareMode: z.boolean().optional(),
writeToDisk: z.boolean().optional(),
origin: z.string().optional(),
preview: previewServerSchema.optional()
})
.strict();
Expand Down
57 changes: 24 additions & 33 deletions packages/core/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export class Server extends httpServer {
middlewares: connect.Server;
compiler: CompilerType;
root: string;
resolvedUserConfig: ResolvedUserConfig;
config: ResolvedUserConfig;
closeHttpServerFn: () => Promise<void>;
terminateServerFn: (_: unknown, exitCode?: number) => Promise<void>;
postConfigureServerHooks: ((() => void) | void)[] = [];
Expand Down Expand Up @@ -155,21 +155,21 @@ export class Server extends httpServer {
*/
async createServer(): Promise<void> {
try {
this.resolvedUserConfig = await resolveConfig(
this.config = await resolveConfig(
this.inlineConfig,
'start',
'development',
'development'
);

this.logger = this.resolvedUserConfig.logger;
this.logger = this.config.logger;

this.#resolveOptions();

this.compiler = createCompiler(this.resolvedUserConfig);
this.compiler = createCompiler(this.config);

for (const hook of getPluginHooks(
this.resolvedUserConfig.jsPlugins,
this.config.jsPlugins,
'configureCompiler'
)) {
await hook?.(this.compiler);
Expand Down Expand Up @@ -244,7 +244,7 @@ export class Server extends httpServer {
* create watcher
*/
async #createWatcher() {
this.watcher = new Watcher(this.resolvedUserConfig);
this.watcher = new Watcher(this.config);

await this.watcher.createWatcher();

Expand All @@ -262,15 +262,12 @@ export class Server extends httpServer {

this.watcher.on('change', async (file: string) => {
file = normalizePath(file);
const shortFile = getShortName(file, this.resolvedUserConfig.root);
const isConfigFile = this.resolvedUserConfig.configFilePath === file;
const isConfigDependencyFile =
this.resolvedUserConfig.configFileDependencies.some(
(name) => file === name
);
const isEnvFile = this.resolvedUserConfig.envFiles.some(
const shortFile = getShortName(file, this.config.root);
const isConfigFile = this.config.configFilePath === file;
const isConfigDependencyFile = this.config.configFileDependencies.some(
(name) => file === name
);
const isEnvFile = this.config.envFiles.some((name) => file === name);
if (isConfigFile || isConfigDependencyFile || isEnvFile) {
__FARM_GLOBAL__.__FARM_RESTART_DEV_SERVER__ = true;
this.logger.info(
Expand All @@ -281,13 +278,13 @@ export class Server extends httpServer {
try {
await this.restartServer();
} catch (e) {
this.resolvedUserConfig.logger.error(`restart server error ${e}`);
this.config.logger.error(`restart server error ${e}`);
}
}
try {
this.hmrEngine.hmrUpdate(file);
} catch (error) {
this.resolvedUserConfig.logger.error(`Farm Hmr Update Error: ${error}`);
this.config.logger.error(`Farm Hmr Update Error: ${error}`);
}
});
const handleUpdateFinish = (updateResult: JsUpdateResult) => {
Expand Down Expand Up @@ -425,13 +422,9 @@ export class Server extends httpServer {
host: hostname.host
});

this.resolvedUserConfig.compilation.define.FARM_HMR_PORT =
serverPort.toString();
this.config.compilation.define.FARM_HMR_PORT = serverPort.toString();

this.resolvedUrls = await resolveServerUrls(
this.httpServer,
this.resolvedUserConfig
);
this.resolvedUrls = await resolveServerUrls(this.httpServer, this.config);
// compile the project and start the dev server
await this.#startCompile();

Expand All @@ -442,7 +435,7 @@ export class Server extends httpServer {
this.#openServerBrowser();
}
} catch (error) {
this.resolvedUserConfig.logger.error(
this.config.logger.error(
`Start DevServer Error: ${error} \n ${error.stack}`
);
// throw error;
Expand Down Expand Up @@ -486,7 +479,7 @@ export class Server extends httpServer {
return true;
}
});
const { jsPlugins } = this.resolvedUserConfig;
const { jsPlugins } = this.config;

for (const hook of getSortedPluginHooksBindThis(
jsPlugins,
Expand All @@ -512,12 +505,12 @@ export class Server extends httpServer {
},
root,
server
} = this.resolvedUserConfig;
} = this.config;
this.publicPath = publicPath;
this.publicDir = publicDir;
if (server.origin?.endsWith('/')) {
server.origin = server.origin.slice(0, -1);
this.resolvedUserConfig.logger.warn(
this.config.logger.warn(
`${colors.bold('(!)')} server.origin should not end with "/". Using "${
server.origin
}" instead.`
Expand Down Expand Up @@ -563,7 +556,7 @@ export class Server extends httpServer {
this.middlewares.use(publicMiddleware(this));
}

if (this.resolvedUserConfig.compilation.lazyCompilation) {
if (this.config.compilation.lazyCompilation) {
this.middlewares.use(lazyCompilationMiddleware(this));
}

Expand All @@ -590,11 +583,11 @@ export class Server extends httpServer {
async #compile(): Promise<void> {
try {
await this.compiler.compile();
await (this.resolvedUserConfig.server.writeToDisk
await (this.config.server.writeToDisk
? this.compiler.writeResourcesToDisk()
: this.compiler.callWriteResourcesHook());
} catch (err) {
this.resolvedUserConfig.logger.error(
this.config.logger.error(
`Compilation failed: ${convertErrorMessage(err)}`
);
// throw err;
Expand Down Expand Up @@ -634,7 +627,7 @@ export class Server extends httpServer {
* @returns {Promise<Set<string>>} A promise that resolves to a set of public file paths.
*/
async #handlePublicFiles(): Promise<Set<string>> {
const initPublicFilesPromise = initPublicFiles(this.resolvedUserConfig);
const initPublicFilesPromise = initPublicFiles(this.config);
return await initPublicFilesPromise;
}

Expand All @@ -648,9 +641,7 @@ export class Server extends httpServer {

this.ws.wss.on('vite:invalidate', ({ path, message }: any) => {
// find hmr boundary starting from the parent of the file
this.resolvedUserConfig.logger.info(
`HMR invalidate: ${path}. ${message ?? ''} `
);
this.config.logger.info(`HMR invalidate: ${path}. ${message ?? ''} `);
const parentFiles = this.compiler.getParentFiles(path);
const normalizeParentFiles = parentFiles.map((file) =>
normalizePath(file)
Expand Down Expand Up @@ -725,7 +716,7 @@ export class Server extends httpServer {
printServerUrls(
this.resolvedUrls,
this.serverOptions.host,
this.resolvedUserConfig.logger
this.config.logger
);
} else if (this.serverOptions.middlewareMode) {
throw new Error('cannot print server URLs in middleware mode.');
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/server/middlewares/htmlFallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function htmlFallbackMiddleware(
}
const url = cleanUrl(req.url);
const pathname = removeSlash(decodeURIComponent(url));
const headers = app.resolvedUserConfig.server.headers;
const headers = app.config.server.headers;

if (pathname.endsWith('.html')) {
const html = app.compiler.resource(pathname);
Expand Down
14 changes: 5 additions & 9 deletions packages/core/src/server/middlewares/lazyCompilation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export function lazyCompilationMiddleware(
app: Server
): Connect.NextHandleFunction {
return async function handleLazyCompilationMiddleware(req, res, next) {
const { resolvedUserConfig, compiler } = app;
const { config, compiler } = app;

if (!req.url.startsWith(DEFAULT_LAZY_COMPILATION_PATH)) {
return await next();
Expand All @@ -44,7 +44,7 @@ export function lazyCompilationMiddleware(
})
.join(', ');

resolvedUserConfig.logger.info(
config.logger.info(
`${bold(green('✨Lazy compiling'))} ${bold(cyan(pathsStr))}`,
true
);
Expand All @@ -62,19 +62,15 @@ export function lazyCompilationMiddleware(
return next();
}

if (isNodeEnvironment || resolvedUserConfig.server.writeToDisk) {
if (isNodeEnvironment || config.server.writeToDisk) {
compiler.writeResourcesToDisk();
}

resolvedUserConfig.logger.info(
config.logger.info(
`${bold(green(`✓ Lazy compilation done`))} ${bold(
cyan(pathsStr)
)} in ${bold(
green(
resolvedUserConfig.logger.formatExecutionTime(
performance.now() - start
)
)
green(config.logger.formatExecutionTime(performance.now() - start))
)}.`
);

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/server/middlewares/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export function proxyMiddleware(
middlewareServer: HttpServer,
config: NonNullable<CommonServerOptions['proxy']>
): Connect.NextHandleFunction {
const { resolvedUserConfig } = app;
const { config: resolvedUserConfig } = app;

const proxies: Record<string, [Server, ProxyOptions]> = {};
Object.keys(config).forEach((context) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/server/middlewares/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export function resourceMiddleware(app: Server): Connect.NextHandleFunction {
return next();
}
const url = cleanUrl(req.url);
const { compiler, resolvedUserConfig: config, publicPath } = app;
const { compiler, config, publicPath } = app;

if (compiler._isInitialCompile) {
await compiler.waitForInitialCompileFinish();
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/server/middlewares/static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ import sirv, { Options } from 'sirv';
import type { Server } from '../index.js';

export function staticMiddleware(app: Server): Connect.NextHandleFunction {
const { resolvedUserConfig, compiler } = app;
const { config, compiler } = app;
const root = compiler.config.root;
const serve = sirv(
root,
sirvOptions({
getHeaders: () => resolvedUserConfig.server.headers
getHeaders: () => config.server.headers
})
);
return function handleStaticMiddleware(req, res, next) {
Expand Down Expand Up @@ -61,7 +61,7 @@ export function staticMiddleware(app: Server): Connect.NextHandleFunction {
}

export function publicMiddleware(app: Server): Connect.NextHandleFunction {
const { resolvedUserConfig: config, publicDir, publicFiles } = app;
const { config: config, publicDir, publicFiles } = app;
const serve = sirv(
publicDir,
sirvOptions({
Expand Down
18 changes: 9 additions & 9 deletions packages/core/src/server/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export interface PreviewServerOptions extends CommonServerOptions {
* @class
*/
export class PreviewServer extends httpServer {
resolvedUserConfig: ResolvedUserConfig;
config: ResolvedUserConfig;
previewServerOptions: PreviewServerOptions;
httpsOptions: SecureServerOptions;

Expand All @@ -77,15 +77,15 @@ export class PreviewServer extends httpServer {
* @throws {Error} If the server cannot be started.
*/
async createPreviewServer(): Promise<void> {
this.resolvedUserConfig = await resolveConfig(
this.config = await resolveConfig(
this.inlineConfig,
'preview',
'production',
'production',
true
);

this.logger = this.resolvedUserConfig.logger;
this.logger = this.config.logger;

await this.#resolveOptions();

Expand Down Expand Up @@ -115,7 +115,7 @@ export class PreviewServer extends httpServer {
*/
#initializeMiddlewares() {
const { cors, proxy } = this.previewServerOptions;
const { appType, middlewareMode } = this.resolvedUserConfig.server;
const { appType, middlewareMode } = this.config.server;

if (cors !== false) {
this.app.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors));
Expand Down Expand Up @@ -154,7 +154,7 @@ export class PreviewServer extends httpServer {
const {
server,
compilation: { root, output }
} = this.resolvedUserConfig;
} = this.config;

this.publicPath = output.publicPath ?? '/';
const preview = server?.preview;
Expand All @@ -174,7 +174,7 @@ export class PreviewServer extends httpServer {
this.serve = sirv(distDir, {
etag: true,
dev: true,
single: this.resolvedUserConfig.server.appType === 'spa',
single: this.config.server.appType === 'spa',
ignores: false,
setHeaders: (res, pathname) => {
if (knownJavascriptExtensionRE.test(pathname)) {
Expand Down Expand Up @@ -224,13 +224,13 @@ export class PreviewServer extends httpServer {

this.resolvedUrls = await resolveServerUrls(
this.httpServer,
this.resolvedUserConfig,
this.config,
'preview'
);

const shortFile = getShortName(
this.resolvedUserConfig.configFilePath,
this.resolvedUserConfig.root
this.config.configFilePath,
this.config.root
);
this.logger.info(`Using config file at ${bold(green(shortFile))}`);

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/server/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ export class WsServer {
*/
constructor(private readonly app: any) {
this.logger = app.logger ?? new Logger();
this.serverConfig = app.resolvedUserConfig.server as ServerOptions;
this.serverConfig = app.config.server as ServerOptions;
this.createWebSocketServer();
}

Expand Down
Loading