Skip to content

Commit

Permalink
Develop improvement (#11)
Browse files Browse the repository at this point in the history
* build(build): ⚗️ change target node to bun and add `semver` as external

* refactor(utils): 👽 improve `highlighter` utils funciton

* refactor(utils): 🚸 compatible framework version checking added

* refactor(utils): 🚸 `getPluginVersion` utils function added

get current plugin version

* refactor(handlers): 🎨 Replace Promise chaining with `Promise.all`

* style(src): 🎨 simpler & improve conditions & functions
  • Loading branch information
krishna-gujjjar authored Feb 11, 2024
1 parent d3dfc92 commit 7ebf1d7
Show file tree
Hide file tree
Showing 14 changed files with 70 additions and 72 deletions.
8 changes: 3 additions & 5 deletions build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import { minify } from "minify";
console.log("\n🛠️ Starting building library... \n");
const bundler = await Bun.build({
minify: true,
target: "bun",
outdir: "./dist",
target: "node",
sourcemap: "none",
entrypoints: ["./src/index.ts"],
external: ["vite", "picocolors", "vite-plugin-full-reload"]
external: ["vite", "semver", "picocolors", "vite-plugin-full-reload"]
});

if (!bundler.success) {
Expand All @@ -34,9 +34,7 @@ import { minify } from "minify";
return;
}

await Bun.write("./dist/index.html", compressHtml, {
createPath: true
});
await Bun.write("./dist/index.html", compressHtml, { createPath: true });

console.log("✅ Library build successfully.");
})();
Binary file modified bun.lockb
Binary file not shown.
11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,26 +40,27 @@
],
"scripts": {
"prebuild": "rm -rf dist",
"build": "tsc --emitDeclarationOnly --project tsconfig.json",
"build": "tsc --emitDeclarationOnly --project tsconfig.build.json",
"postbuild": "bun run build.config.ts"
},
"peerDependencies": {
"vite": "^5.0.0"
},
"devDependencies": {
"@types/bun": "latest",
"@types/bun": "^1.0.5",
"@types/minify": "^9.1.4",
"@types/node": "^20.11.8",
"@types/node": "^20.11.17",
"@typescript-eslint/eslint-plugin": "latest",
"@typescript-eslint/parser": "latest",
"eslint": "latest",
"minify": "^11.0.1",
"prettier": "^3.2.4",
"prettier": "^3.2.5",
"typescript": "^5.3.3",
"vite": "^5.0.12"
"vite": "^5.1.1"
},
"dependencies": {
"picocolors": "^1.0.0",
"semver": "^7.6.0",
"vite-plugin-full-reload": "^1.1.0"
}
}
10 changes: 0 additions & 10 deletions src/handlers/_devServerUrl.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { ResolvedConfig } from "vite";
import { isIpv6 } from "@utils/uri";
import { HTTP_PROTOCOLS } from "@config/http";

export const _getServerUrl = (address: AddressInfo, config: ResolvedConfig): string => {
export const _getDevServerUrl = (address: AddressInfo, config: ResolvedConfig): string => {
const configHmrProtocol =
typeof config.server.hmr === "object" ? config.server.hmr.protocol : null;
const clientProtocol = configHmrProtocol
Expand All @@ -24,5 +24,5 @@ export const _getServerUrl = (address: AddressInfo, config: ResolvedConfig): str
typeof config.server.hmr === "object" ? config.server.hmr.clientPort : null;
const port = configHmrClientPort ?? address.port;

return `${protocol}://${host}:${port}`;
return config.server?.origin ?? `${protocol}://${host}:${port}`;
};
10 changes: 5 additions & 5 deletions src/handlers/_handleDevServer.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { loadEnv } from "vite";
import type { ResolvedConfig, ViteDevServer } from "vite";
import type { ViteDevServer } from "vite";

import { joinPaths } from "@utils/string";
import { getCurrentPath } from "@utils/uri";
import { appConfig } from "@config/constant";
import { readFileAsString } from "@utils/io";

export const _handleDevServer = (config: ResolvedConfig, server: ViteDevServer) => {
const envDir = config.envDir || process.cwd();
export const _handleDevServer = ({ config, middlewares }: ViteDevServer) => {
const { serverListener, placeholder, placeholderRegExp } = appConfig;
const appUrl = loadEnv(config.mode, envDir, "")[placeholder] ?? "undefined";
const appUrl =
loadEnv(config.mode, config.envDir || process.cwd(), "")[placeholder] ?? "undefined";

return server.middlewares.use(async (req, res, next) => {
return middlewares.use(async (req, res, next) => {
if (req.url === `/${serverListener}`) {
res.writeHead(200, { "Content-Type": "text/html" });
res.end(
Expand Down
34 changes: 24 additions & 10 deletions src/handlers/_logger.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,38 @@
import { loadEnv } from "vite";
import type { ViteDevServer } from "vite";

import { getFrameworkVersion } from "@utils/version";
import { appConfig } from "@config/constant";
import { highlighter } from "@utils/decorate";
import packageJson from "./../../package.json";
import { getFrameworkVersion, getPluginVersion } from "@utils/version";

export const _handleLogger = (server: ViteDevServer): void => {
const { placeholder } = appConfig;
const { mode, envDir, logger } = server.config;
const appUrl = {
name: "App Url",
version: loadEnv(mode, envDir || process.cwd(), "")[placeholder] ?? "undefined"
};

setTimeout(() => {
server.config.logger.info("");
logger.info("");

getFrameworkVersion()
.then((framework) => {
Promise.all([getFrameworkVersion(), getPluginVersion()])
.then((values) => {
if (server.resolvedUrls) {
server.config.logger.info(highlighter([framework, packageJson]));
for (const value of values) {
logger.info(
highlighter({
name: value.name,
version: `v${value.version.replace("v", "")}`
})
);
}
}

return framework;
})
.catch((error) => {
server.config.logger.error(error);
logger.error(error);
server.close();
});
})
.finally(() => logger.info("\n" + highlighter(appUrl)));
}, 100);
};
11 changes: 5 additions & 6 deletions src/handlers/server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type ResolvedConfig, type ViteDevServer } from "vite";
import type { ViteDevServer } from "vite";

import { writingFile } from "@utils/io";
import { joinPaths } from "@utils/string";
Expand All @@ -7,13 +7,12 @@ import { appConfig } from "@config/constant";
import { Errors, errorMessages } from "@utils/errors";

import { _handleLogger } from "./_logger";
import { _devServerUrl } from "./_devServerUrl";
import { _handleExitProcess } from "./_processes";
import { _getDevServerUrl } from "./_getDevServerUrl";
import { _handleDevServer } from "./_handleDevServer";

export const handleConfigureServer = (
server: ViteDevServer,
config: ResolvedConfig
server: ViteDevServer
): (() => void) | void | Promise<(() => void) | void> => {
const { publicDirectory, hotFile } = appConfig;
const hotFilePath = joinPaths(publicDirectory, hotFile);
Expand All @@ -22,7 +21,7 @@ export const handleConfigureServer = (
const address = server.httpServer?.address();

if (isAddressInfo(address)) {
writingFile(hotFilePath, _devServerUrl(config, server, address))
writingFile(hotFilePath, _getDevServerUrl(address, server.config))
.then(() => _handleLogger(server))
.catch(() => {
server.config.logger.error(errorMessages(Errors.UnableToWriteHotFile));
Expand All @@ -33,5 +32,5 @@ export const handleConfigureServer = (

_handleExitProcess();

return () => _handleDevServer(config, server);
return () => _handleDevServer(server);
};
2 changes: 1 addition & 1 deletion src/plugins/ci4.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ export const ci4 = (_config: Required<PluginConfig>): Ci4Plugin => {
return _config.transformOnServe(code, devServerUrl);
}
},
configureServer: (server) => handleConfigureServer(server, config)
configureServer: handleConfigureServer
};
};
26 changes: 11 additions & 15 deletions src/resolvers/_aliases.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
/* eslint-disable indent */
import type { AliasOptions, UserConfig } from "vite";
import { appConfig } from "@config/constant";

export const _resolveAliases = (config: UserConfig): AliasOptions => {
if (Array.isArray(config.resolve?.alias)) {
return [
...(config.resolve?.alias ?? []),
...Object.keys(appConfig.alias).map((alias) => ({
find: alias,
replacement: appConfig.alias[alias]
}))
];
}
return {
...appConfig.alias,
...config.resolve?.alias
};
};
export const _resolveAliases = (config: UserConfig): AliasOptions =>
Array.isArray(config.resolve?.alias)
? [
...(config.resolve?.alias ?? []),
...Object.keys(appConfig.alias).map((alias) => ({
find: alias,
replacement: appConfig.alias[alias]
}))
]
: { ...appConfig.alias, ...config.resolve?.alias };
9 changes: 2 additions & 7 deletions src/utils/decorate.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
import colors from "picocolors";
import type { JsonVersion } from "src/types";

export const highlighter = (plugins: JsonVersion[]): string => {
let versionString = "";
for (const plugin of plugins) {
versionString = ` ${colors.green("➜")} ${colors.white(plugin.name)}: ${colors.cyan(`v${plugin.version.replace("v", "")}`)}`;
}
return versionString;
};
export const highlighter = (plugin: JsonVersion): string =>
` ${colors.green("➜")} ${colors.white(plugin.name)}: ${colors.cyan(plugin.version)}`;
7 changes: 5 additions & 2 deletions src/utils/version.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import semver from "semver/functions/gt";
import { lt } from "semver";

import { appConfig } from "@config/constant";
import type { JsonVersion } from "src/types";
Expand All @@ -9,7 +9,7 @@ export const getFrameworkVersion = async (): Promise<JsonVersion> => {
({ name }) => name === appConfig.framework
) as JsonVersion;

if (!semver(framework.version, appConfig.frameworkCompatibleVersion)) {
if (lt(framework.version, appConfig.frameworkCompatibleVersion)) {
throw new Error(
`CompatibilityError: ${framework.name}@${framework.version} is not compatible with ${appConfig.pluginName}. Use ${appConfig.frameworkName}@${appConfig.frameworkCompatibleVersion}`,
{ cause: "CompatibilityError" }
Expand All @@ -18,3 +18,6 @@ export const getFrameworkVersion = async (): Promise<JsonVersion> => {

return framework;
};

export const getPluginVersion = async (): Promise<JsonVersion> =>
await readFileAsJson(appConfig.packageJsonPath);
5 changes: 5 additions & 0 deletions tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": ["./tsconfig.json"],
"compilerOptions": { "rootDir": "./src/" },
"exclude": ["tests"]
}
5 changes: 1 addition & 4 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,17 @@
"useUnknownInCatchVariables": true,
"noPropertyAccessFromIndexSignature": true,
"outDir": "dist",
"types": ["vite", "bun"],

// Paths
"baseUrl": ".",
"rootDir": "./src",
"paths": {
"@config/*": ["./src/config/*"],
"@handlers/*": ["./src/handlers/*"],
"@plugins/*": ["./src/plugins/*"],
"@resolvers/*": ["./src/resolvers/*"],
// "@type": ["./src/types/index.ts"],
"@utils/*": ["./src/utils/*"]
}
},
"include": ["src"],
"include": ["src", "tests"],
"exclude": ["node_modules"]
}

0 comments on commit 7ebf1d7

Please sign in to comment.