diff --git a/.eslintrc b/.eslintrc deleted file mode 100644 index ccd23e74..00000000 --- a/.eslintrc +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": ["@curev"], - "rules": { - "@typescript-eslint/no-var-requires": "off" - } -} diff --git a/.gitignore b/.gitignore index 88ed6c83..d728b868 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,6 @@ node_modules .temp .tmp .cache -.vscode # Yarn **/.yarn/cache @@ -38,8 +37,6 @@ coverage *.lcov .nyc_output -# VSCode -.vscode # Intellij idea *.iml diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..69ef5478 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,36 @@ +{ + // Enable the ESlint flat config support + "eslint.experimental.useFlatConfig": true, + + // Disable the default formatter, use eslint instead + "prettier.enable": false, + "editor.formatOnSave": false, + + // Auto fix + "editor.codeActionsOnSave": { + "source.fixAll.eslint": "explicit", + "source.organizeImports": "never" + }, + + // Enable eslint for all supported languages + "eslint.validate": [ + "javascript", + "javascriptreact", + "typescript", + "typescriptreact", + "vue", + "html", + "markdown", + "json", + "jsonc", + "yaml", + "toml" + ], + + "pair-diff.patterns": [ + { + "source": "./fixtures/output/**/*.*", + "target": "./fixtures/input/" + } + ] +} diff --git a/README.md b/README.md index 8e90e484..3aa3e711 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,17 @@

Fourze

Api route framework for the browser and node.js.

- `pnpm add @fourze/core` create a router file `src/mock/example.ts` ```ts import { defineRouter } from "@fourze/core"; -export default defineRouter(router => { +export default defineRouter((router) => { router.get("/hello", () => { return "hello,world"; }); }); - ``` configure vite config @@ -29,7 +27,6 @@ export default defineConfig({ }) ], }); - ``` then you can fetch `/api/hello` to get response. @@ -37,7 +34,6 @@ then you can fetch `/api/hello` to get response. # Features [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fchizukicn%2Ffourze.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fchizukicn%2Ffourze?ref=badge_shield) - - Simple api route register - Mock XHR/fetch/http.request response @@ -46,7 +42,6 @@ then you can fetch `/api/hello` to get response. - Node.js and browser support - # Development ```shell pnpm install @@ -67,7 +62,6 @@ export default defineNuxtConfig({ base: "/api" } }); - ``` # Node.js Server @@ -81,7 +75,7 @@ import { createServer } from "@fourze/server"; const server = createServer({ base: "/api" }); -server.use(defineRouter(router => { +server.use(defineRouter((router) => { router.get("/hello", (_, res) => { res.send("hello,world"); }); @@ -100,7 +94,6 @@ const middleware = createServer({ const app = express(); app.use(middleware); app.listen(7609); - ``` # Register Router @@ -109,7 +102,7 @@ src/mock/example.ts ```ts import { defineRouter } from "@fourze/core"; -export default defineRouter(router => { +export default defineRouter((router) => { // base = '/api' router.post("/user/{id}", (req) => { return { @@ -118,7 +111,6 @@ export default defineRouter(router => { }; }); }); - ``` Set `base` to `/api` in vite/nuxt config, then you can fetch `/api/user/1` to get response. @@ -131,7 +123,6 @@ Response `{"id":"1","name":"test"}` - # Thanks This project is heavily inspired by the following awesome projects. @@ -151,9 +142,5 @@ This project is heavily inspired by the following awesome projects. - [jiti](https://github.com/unjs/jiti.git) - - - - ## License -[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fchizukicn%2Ffourze.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fchizukicn%2Ffourze?ref=badge_large) \ No newline at end of file +[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fchizukicn%2Ffourze.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fchizukicn%2Ffourze?ref=badge_large) diff --git a/alias.ts b/alias.ts index 94cc267f..b9146b18 100644 --- a/alias.ts +++ b/alias.ts @@ -16,4 +16,3 @@ export const alias: Record = Object.keys(paths).reduce( }, {} ); - diff --git a/bench/compare.ts b/bench/compare.ts index cb9ab145..d9e557a1 100644 --- a/bench/compare.ts +++ b/bench/compare.ts @@ -1,6 +1,7 @@ import { arch, cpus, platform, totalmem } from "node:os"; import { join } from "node:path"; import { readFileSync, readdirSync, writeFileSync } from "node:fs"; +import process from "node:process"; import { program } from "commander"; import Table from "cli-table"; import chalk from "chalk"; @@ -31,9 +32,9 @@ if (!getAvailableResults().length) { function getAvailableResults() { return readdirSync(resultsPath) - .filter((file) => file.match(/(.+)\.json$/)) + .filter(file => file.match(/(.+)\.json$/)) .sort() - .map((choice) => choice.replace(".json", "")); + .map(choice => choice.replace(".json", "")); } function formatHasRouter(hasRouter: boolean | string) { diff --git a/bench/lib/autocannon.ts b/bench/lib/autocannon.ts index 1ac17d17..774b0a93 100644 --- a/bench/lib/autocannon.ts +++ b/bench/lib/autocannon.ts @@ -1,10 +1,11 @@ import { access, mkdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; +import process from "node:process"; import autocannon from "autocannon"; const resultsDirectory = join(process.cwd(), "results"); -const run = (opts: autocannon.Options = { url: "http://localhost:3000" }) => { +function run(opts: autocannon.Options = { url: "http://localhost:3000" }) { return new Promise((resolve, reject) => { opts.url = "http://localhost:3000"; autocannon(opts, (err, result) => { @@ -15,7 +16,7 @@ const run = (opts: autocannon.Options = { url: "http://localhost:3000" }) => { } }); }); -}; +} export async function fire( opts: autocannon.Options, diff --git a/bench/lib/bench.ts b/bench/lib/bench.ts index dcff6079..c5b1cdb7 100644 --- a/bench/lib/bench.ts +++ b/bench/lib/bench.ts @@ -7,7 +7,7 @@ import { fire } from "./autocannon"; const __dirname = fileURLToPath(new URL(".", import.meta.url)); -const doBench = async (opts: any, handler: string) => { +async function doBench(opts: any, handler: string) { const spinner = ora(`Started ${handler}`).start(); const forked = fork(join(__dirname, "../modules", `${handler}.js`)); try { @@ -30,10 +30,10 @@ const doBench = async (opts: any, handler: string) => { } catch (error) { return console.error(error); } -}; +} let index = 0; -const start = async (opts: any, module: string[] | string): Promise => { +async function start(opts: any, module: string[] | string): Promise { if (typeof module === "string") { module = [module]; } @@ -49,6 +49,6 @@ const start = async (opts: any, module: string[] | string): Promise => { } catch (error) { console.error(error); } -}; +} export default start; diff --git a/bench/lib/packages.ts b/bench/lib/packages.ts index 375fa1d6..06850164 100644 --- a/bench/lib/packages.ts +++ b/bench/lib/packages.ts @@ -1,13 +1,14 @@ import { createRequire } from "node:module"; import path from "node:path"; +import process from "node:process"; import pkgJson from "../package.json"; const packages: Record = { "fourze": { checked: true, hasRouter: true, package: "@fourze/core" }, "fourze-router": { checked: true, hasRouter: true, package: "@fourze/core" }, @@ -46,7 +47,7 @@ export function list(extra = false) { : null; return null; }) - .filter((c) => c); + .filter(c => c); } export function info(module: string) { return packages[module]; diff --git a/bench/lib/suite.ts b/bench/lib/suite.ts index 15faceba..28f1eeaf 100644 --- a/bench/lib/suite.ts +++ b/bench/lib/suite.ts @@ -1,13 +1,12 @@ import consola from "consola"; -export const suite = async (name: string, frequency: number, fn: () => void | Promise) => { +export async function suite(name: string, frequency: number, fn: () => void | Promise) { const start = performance.now(); - const list = new Array(frequency).fill(0); + const list = Array.from({ length: frequency }).fill(0); for (let i = 0; i < frequency; i++) { list[i] = fn(); } await Promise.all(list); const end = performance.now(); consola.log(`suit-${name}`, `time: ${(end - start).toFixed(3)}ms`); -}; - +} diff --git a/bench/modules/express.js b/bench/modules/express.js index b3a751f9..d835267b 100644 --- a/bench/modules/express.js +++ b/bench/modules/express.js @@ -8,4 +8,3 @@ app.get("/", (req, res) => { }); }); app.listen(3000); - diff --git a/bench/modules/fastify.js b/bench/modules/fastify.js index 06563881..3e6a85f2 100644 --- a/bench/modules/fastify.js +++ b/bench/modules/fastify.js @@ -1,4 +1,5 @@ import fastify from "fastify"; + const app = fastify(); const schema = { diff --git a/bench/modules/fourze-router.js b/bench/modules/fourze-router.js index 66e3025e..ab04daa6 100644 --- a/bench/modules/fourze-router.js +++ b/bench/modules/fourze-router.js @@ -1,8 +1,9 @@ +import process from "node:process"; import { defineRouter } from "@fourze/core"; import { createServer } from "@fourze/server"; -const router = defineRouter(router => { +const router = defineRouter((router) => { router.get("/", () => { return { hello: "world" diff --git a/bench/modules/fourze.js b/bench/modules/fourze.js index 8e324956..dac91279 100644 --- a/bench/modules/fourze.js +++ b/bench/modules/fourze.js @@ -1,4 +1,5 @@ import { createServer } from "node:http"; +import process from "node:process"; import { connect } from "@fourze/server"; import { createApp } from "@fourze/core"; diff --git a/bench/modules/koa.js b/bench/modules/koa.js index f711748c..c54549ef 100644 --- a/bench/modules/koa.js +++ b/bench/modules/koa.js @@ -1,7 +1,9 @@ +import process from "node:process"; import Koa from "koa"; + const app = new Koa(); -app.use(ctx => { +app.use((ctx) => { ctx.body = { hello: "world" }; }); diff --git a/bench/modules/nodehttp.js b/bench/modules/nodehttp.js index f4be9953..2ae199e9 100644 --- a/bench/modules/nodehttp.js +++ b/bench/modules/nodehttp.js @@ -1,4 +1,5 @@ import http from "node:http"; +import process from "node:process"; const server = http.createServer((req, res) => { res.writeHead(200, { "Content-Type": "application/json" }); diff --git a/bench/package.json b/bench/package.json index ab6694f8..f7428a13 100644 --- a/bench/package.json +++ b/bench/package.json @@ -19,7 +19,7 @@ "connect": "^3.7.0", "consola": "^3.2.3", "express": "^4.18.2", - "fastify": "^4.25.2", + "fastify": "^4.26.0", "h3": "^1.10.1", "inquirer": "^9.2.13", "koa": "^2.15.0" diff --git a/bench/run.ts b/bench/run.ts index 3f8ea949..99d2dfca 100644 --- a/bench/run.ts +++ b/bench/run.ts @@ -1,3 +1,4 @@ +import process from "node:process"; import inquirer from "inquirer"; import { program } from "commander"; import { choices, list } from "./lib/packages"; @@ -5,11 +6,11 @@ import bench from "./lib/bench"; let argv: string[] = []; -const run = async () => { +async function run() { const options = await getBenchmarkOptions(); const modules = options.all ? choices : await select(); return bench(options, modules); -}; +} argv = program .option("-t --target ", "module to benchmark") @@ -27,7 +28,7 @@ argv = program } }).parse(process.argv).args; -const parseArgv = async () => { +async function parseArgv() { const [all, connections, pipelining, duration] = argv; return { all: all === "y", @@ -35,7 +36,7 @@ const parseArgv = async () => { pipelining: +pipelining, duration: +duration }; -}; +} async function getBenchmarkOptions() { if (argv.length) { diff --git a/bench/unit/array.ts b/bench/unit/array.ts index 0d782c54..1ecd2a1a 100644 --- a/bench/unit/array.ts +++ b/bench/unit/array.ts @@ -1,20 +1,19 @@ import { CollectionQueryClass, createQuery } from "@fourze/core"; import { suite } from "../lib/suite"; -const source = new Array(100).fill(0).map((_, i) => i); +const source = Array.from({ length: 100 }).fill(0).map((_, i) => i); suite("query-func", 100000, () => { const query = createQuery(source); - query.where((i) => i % 2 === 0).select((i) => i * 2); + query.where(i => i % 2 === 0).select(i => i * 2); }); suite("query-class", 100000, () => { const query = new CollectionQueryClass(source); - query.where(i => i % 2 === 0).select((i) => i * 2); + query.where(i => i % 2 === 0).select(i => i * 2); }); suite("array", 100000, () => { const array = Array.from(source); - array.filter((i) => i % 2 === 0).map((i) => i * 2); + array.filter(i => i % 2 === 0).map(i => i * 2); }); - diff --git a/bench/unit/path.ts b/bench/unit/path.ts index 877604e1..32bb8cea 100644 --- a/bench/unit/path.ts +++ b/bench/unit/path.ts @@ -11,4 +11,3 @@ suite("replace", 100000, () => { const b = "/api"; normalizeURL((a.replace(b, ""))); }); - diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 00000000..d5565a0e --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,9 @@ +const { curev } = require("@curev/eslint-config"); + +module.exports = curev({ + rules: { + "ts/no-var-requires": "off", + "ts/no-require-imports": "off", + "node/prefer-global/buffer": "off" + } +}); diff --git a/package.json b/package.json index be9dece0..a8a34f61 100644 --- a/package.json +++ b/package.json @@ -40,13 +40,13 @@ "typecheck": "tsc --noEmit --skipLibCheck" }, "devDependencies": { - "@curev/eslint-config": "^0.2.2", + "@curev/eslint-config": "^0.3.4", "@fourze/core": "workspace:*", "@fourze/mock": "workspace:*", "@fourze/server": "workspace:*", "@fourze/swagger": "workspace:*", "@types/fs-extra": "^11.0.4", - "@types/node": "^20.11.10", + "@types/node": "^20.11.13", "@vitest/coverage-v8": "^1.2.2", "@vitest/ui": "^1.2.2", "autocannon": "^7.14.0", @@ -57,7 +57,7 @@ "jsdom": "^24.0.0", "lint-staged": "^15.2.0", "node-fetch": "^3.3.2", - "nolyfill": "^1.0.27", + "nolyfill": "^1.0.28", "rimraf": "^5.0.5", "simple-git-hooks": "^2.9.0", "taze": "^0.13.1", @@ -72,17 +72,17 @@ "array.prototype.flat": "npm:@nolyfill/array.prototype.flat@latest", "array.prototype.flatmap": "npm:@nolyfill/array.prototype.flatmap@latest", "deep-equal": "npm:@nolyfill/deep-equal@latest", - "has": "npm:@nolyfill/has@latest", - "is-generator-function": "npm:@nolyfill/is-generator-function@latest", - "object.values": "npm:@nolyfill/object.values@latest", - "side-channel": "npm:@nolyfill/side-channel@latest", "function-bind": "npm:@nolyfill/function-bind@latest", "gopd": "npm:@nolyfill/gopd@latest", + "has": "npm:@nolyfill/has@latest", "has-property-descriptors": "npm:@nolyfill/has-property-descriptors@latest", "has-proto": "npm:@nolyfill/has-proto@latest", "has-symbols": "npm:@nolyfill/has-symbols@latest", "hasown": "npm:@nolyfill/hasown@latest", - "isarray": "npm:@nolyfill/isarray@latest" + "is-generator-function": "npm:@nolyfill/is-generator-function@latest", + "isarray": "npm:@nolyfill/isarray@latest", + "object.values": "npm:@nolyfill/object.values@latest", + "side-channel": "npm:@nolyfill/side-channel@latest" } }, "simple-git-hooks": { diff --git a/packages/core/README.md b/packages/core/README.md index 9f3b9d9b..df003379 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -1,14 +1,13 @@ # Fourze Core - ## Register Route ```ts import { defineRouter } from "@fourze/core"; -export default defineRouter(router => { +export default defineRouter((router) => { router.get("/hello", (_, res) => { res.send("hello,world"); }); }); -``` \ No newline at end of file +``` diff --git a/packages/core/package.json b/packages/core/package.json index e2533a24..2a36ddd6 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -17,8 +17,8 @@ "exports": { ".": { "types": "./dist/index.d.ts", - "require": "./dist/index.cjs", - "import": "./dist/index.mjs" + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" } }, "main": "dist/index.cjs", diff --git a/packages/core/src/app.ts b/packages/core/src/app.ts index e1375742..d8bd0266 100644 --- a/packages/core/src/app.ts +++ b/packages/core/src/app.ts @@ -1,7 +1,9 @@ import type { MaybePromise, MaybeRegex } from "maybe-types"; import { withBase, withTrailingSlash, withoutBase, withoutTrailingSlash } from "ufo"; import { - createSingletonPromise, deleteBy, isArray, + createSingletonPromise, + deleteBy, + isArray, isFunction, isMatch, isObject, @@ -28,32 +30,32 @@ export type FourzeAppSetup = ( ) => MaybePromise; export interface FourzeAppOptions { - base?: string + base?: string; - modules?: FourzeModule[] + modules?: FourzeModule[]; /** * 允许的路径规则,默认为所有 * @default [] */ - allow?: MaybeRegex[] + allow?: MaybeRegex[]; /** * 不允许的路径规则 */ - deny?: MaybeRegex[] + deny?: MaybeRegex[]; - meta?: FourzeAppMeta + meta?: FourzeAppMeta; - setup?: FourzeAppSetup + setup?: FourzeAppSetup; - fallback?: FourzeNext + fallback?: FourzeNext; } export interface FourzeMiddlewareNode { - middleware: FourzeMiddleware - path: string - order: number + middleware: FourzeMiddleware; + path: string; + order: number; } export function createApp(): FourzeApp; @@ -129,8 +131,8 @@ export function createApp( if (url) { return middlewareStore .sort((a, b) => a.order - b.order) - .filter((r) => url.match(r.path)) - .map((r) => [r.path, r.middleware] as [string, FourzeMiddleware]); + .filter(r => url.match(r.path)) + .map(r => [r.path, r.middleware] as [string, FourzeMiddleware]); } return []; }; @@ -173,8 +175,8 @@ export function createApp( app.remove = function (arg: FourzeMiddleware | string) { if (isString(arg)) { - deleteBy(middlewareStore, (r) => r.middleware.name === arg); - deleteBy(persistenceMiddlewareStore, (r) => r.middleware.name === arg); + deleteBy(middlewareStore, r => r.middleware.name === arg); + deleteBy(persistenceMiddlewareStore, r => r.middleware.name === arg); } return this; }; @@ -192,8 +194,6 @@ export function createApp( return { request, response }; }; - - app.isAllow = function (this: FourzeApp, url: string) { return isMatch(url, allows, denys); }; @@ -291,7 +291,7 @@ export function createApp( Object.defineProperties(app, { middlewares: { get() { - return middlewareStore.map((r) => r.middleware); + return middlewareStore.map(r => r.middleware); }, enumerable: true }, diff --git a/packages/core/src/element.ts b/packages/core/src/element.ts index 774f302b..46128357 100644 --- a/packages/core/src/element.ts +++ b/packages/core/src/element.ts @@ -31,7 +31,7 @@ export async function createElement( children: any[] ): Promise { if (Array.isArray(children)) { - const tasks = children.map(async (c) => + const tasks = children.map(async c => Array.isArray(c) ? renderChildren(c) : resolveElement(c) ); return await Promise.all(tasks).then(r => r.join("")); @@ -49,13 +49,13 @@ export const h = createElement; export const FourzeComponentFlag = "__isFourzeComponent"; export interface FourzeComponentOption { - name?: string - setup?: () => MaybePromise> - render?: () => MaybePromise + name?: string; + setup?: () => MaybePromise>; + render?: () => MaybePromise; } export interface FourzeComponent extends FourzeComponentOption { - [FourzeComponentFlag]: true + [FourzeComponentFlag]: true; } export function defineFourzeComponent( @@ -75,4 +75,3 @@ export function isFourzeComponent( ): component is FourzeComponent { return component && component[FourzeComponentFlag]; } - diff --git a/packages/core/src/logger.ts b/packages/core/src/logger.ts index 242ab7fe..51daa71a 100644 --- a/packages/core/src/logger.ts +++ b/packages/core/src/logger.ts @@ -1,4 +1,4 @@ -/* eslint-disable @typescript-eslint/no-duplicate-enum-values */ +/* eslint-disable ts/no-duplicate-enum-values */ import { createConsola } from "consola/core"; import type { ConsolaInstance } from "consola"; diff --git a/packages/core/src/polyfill/form-data.ts b/packages/core/src/polyfill/form-data.ts index 33150d81..e6d44e30 100644 --- a/packages/core/src/polyfill/form-data.ts +++ b/packages/core/src/polyfill/form-data.ts @@ -26,11 +26,11 @@ export class PolyfillFile { } interface FormDataPart { - name: string - fileName?: string - value: string - contentType: string - encoding?: BufferEncoding + name: string; + fileName?: string; + value: string; + contentType: string; + encoding?: BufferEncoding; } const CONTENT_DISPOSITION_REGEX diff --git a/packages/core/src/polyfill/header.ts b/packages/core/src/polyfill/header.ts index 0d21612e..4a65c34e 100644 --- a/packages/core/src/polyfill/header.ts +++ b/packages/core/src/polyfill/header.ts @@ -73,12 +73,12 @@ export interface TransformHeaderOptions { /** * @default ", " */ - separator?: string + separator?: string; /** * @default "lower" */ - caseInsensitive?: "lower" | "upper" | "none" + caseInsensitive?: "lower" | "upper" | "none"; } export function getHeader(headers: Record, key: string) { @@ -110,8 +110,8 @@ export function getHeaderRawValue( ): string | undefined { if (Array.isArray(value)) { return value - .map((v) => getHeaderRawValue(v, options)) - .filter((r) => !!r) + .map(v => getHeaderRawValue(v, options)) + .filter(r => !!r) .join(options.separator ?? ", "); } return value ? String(value) : undefined; @@ -143,7 +143,7 @@ export interface FlatHeadersOptions { /** * @default "lower" */ - caseInsensitive?: "lower" | "upper" | "none" + caseInsensitive?: "lower" | "upper" | "none"; } function transformCase( diff --git a/packages/core/src/router.ts b/packages/core/src/router.ts index f8a673a5..cdd7469d 100644 --- a/packages/core/src/router.ts +++ b/packages/core/src/router.ts @@ -4,7 +4,8 @@ import type { FourzeRouteMeta, MetaInstance } from "./shared/meta"; import { injectMeta } from "./shared/meta"; import type { DefaultData, - FourzeApp, FourzeBaseRoute, + FourzeApp, + FourzeBaseRoute, FourzeHandle, FourzeMiddleware, FourzeNext, @@ -47,48 +48,48 @@ type FourzeRouteChain = { options: Omit, "path" | "method">, handle: FourzeHandle ): FourzeRouteChain> & { - route: FourzeRouter["route"] - } + route: FourzeRouter["route"]; + }; ( handle: FourzeHandle ): FourzeRouteChain> & { - route: FourzeRouter["route"] - } + route: FourzeRouter["route"]; + }; } } & { - route: FourzeRouter["route"] + route: FourzeRouter["route"]; }; export interface FourzeRouter extends FourzeMiddleware, FourzeRouteGenerator, MetaInstance { - reset(): void + reset(): void; - route(path: string): FourzeRouteChain + route(path: string): FourzeRouteChain; - route(path: string, method: RequestMethod, options: FourzeRouteOptions, handle: FourzeHandle): this + route(path: string, method: RequestMethod, options: FourzeRouteOptions, handle: FourzeHandle): this; - route(path: string, method: RequestMethod, handle: FourzeHandle): this + route(path: string, method: RequestMethod, handle: FourzeHandle): this; - route(path: string, options: FourzeRouteOptions, handle: FourzeHandle): this + route(path: string, options: FourzeRouteOptions, handle: FourzeHandle): this; - route(path: string, handle: FourzeHandle): this + route(path: string, handle: FourzeHandle): this; - route(route: FourzeBaseRoute): this + route(route: FourzeBaseRoute): this; - route(route: FourzeBaseRoute[]): this + route(route: FourzeBaseRoute[]): this; - setup(app?: FourzeApp): Promise + setup(app?: FourzeApp): Promise; - readonly meta: Record + readonly meta: Record; - readonly name: string + readonly name: string; - readonly routes: FourzeRoute[] + readonly routes: FourzeRoute[]; - [FourzeRouterFlag]: true + [FourzeRouterFlag]: true; } export type FourzeRouterSetup = ( @@ -97,10 +98,10 @@ export type FourzeRouterSetup = ( ) => MaybePromise; export interface FourzeRouterOptions { - name?: string - meta?: FourzeRouterMeta - routes?: FourzeBaseRoute[] - setup?: FourzeRouterSetup + name?: string; + meta?: FourzeRouterMeta; + routes?: FourzeBaseRoute[]; + setup?: FourzeRouterSetup; } export function defineRouter(): FourzeRouter; @@ -213,7 +214,7 @@ export function defineRouter( } return chain; } else if (Array.isArray(firstArg)) { - firstArg.forEach((r) => addRoute(r)); + firstArg.forEach(r => addRoute(r)); } else { addRoute(firstArg); } @@ -250,14 +251,14 @@ export function defineRouter( const rs = await setup?.(router, app); if (rs) { if (Array.isArray(rs)) { - rs.forEach((r) => addRoute(r)); + rs.forEach(r => addRoute(r)); } else if (rs !== router && isObject(rs)) { options.name = rs.name ?? options.name; if (rs.meta) { Object.assign(meta, rs.meta); } if (rs.routes) { - rs.routes.forEach((r) => addRoute(r)); + rs.routes.forEach(r => addRoute(r)); } } } @@ -289,7 +290,7 @@ export function defineRouter( routes: { get() { const routes: FourzeRoute[] = []; - matcher.traverse((payload) => routes.push(payload)); + matcher.traverse(payload => routes.push(payload)); return routes; }, enumerable: true @@ -305,4 +306,3 @@ export function defineRouter( export function isRouter(value: any): value is FourzeRouter { return !!value && !!value[FourzeRouterFlag]; } - diff --git a/packages/core/src/shared/context.ts b/packages/core/src/shared/context.ts index 864ff489..30d83b46 100644 --- a/packages/core/src/shared/context.ts +++ b/packages/core/src/shared/context.ts @@ -5,19 +5,19 @@ import type { FourzeResponse } from "./response"; import { createResponse } from "./response"; export interface FourzeContextOptions { - url: string - method?: string - headers?: Record - body?: any - request?: IncomingMessage - response?: OutgoingMessage - contextPath?: string - contentTypeParsers?: Record any> + url: string; + method?: string; + headers?: Record; + body?: any; + request?: IncomingMessage; + response?: OutgoingMessage; + contextPath?: string; + contentTypeParsers?: Record any>; } export interface FourzeServiceContext { - request: FourzeRequest - response: FourzeResponse + request: FourzeRequest; + response: FourzeResponse; } export function createServiceContext(options: FourzeContextOptions): FourzeServiceContext { diff --git a/packages/core/src/shared/interface.ts b/packages/core/src/shared/interface.ts index bd194b68..8c5dd022 100644 --- a/packages/core/src/shared/interface.ts +++ b/packages/core/src/shared/interface.ts @@ -12,7 +12,9 @@ const FourzeMiddlewareFlag = "__isFourzeMiddleware"; export type FourzeNext = () => MaybePromise; export type FourzeHandle< - R = unknown, Props extends ObjectProps = DefaultData, Meta = FourzeRouteMeta + R = unknown, +Props extends ObjectProps = DefaultData, +Meta = FourzeRouteMeta > = ( request: FourzeRequest, response: FourzeResponse @@ -23,7 +25,7 @@ export interface CommonMiddleware { req: IncomingMessage, res: OutgoingMessage, next?: FourzeNext - ): MaybePromise + ): MaybePromise; } export interface FourzeMiddlewareHandler { @@ -31,13 +33,13 @@ export interface FourzeMiddlewareHandler { req: FourzeRequest, res: FourzeResponse, next: FourzeNext - ): MaybePromise + ): MaybePromise; } export interface FourzeMiddleware extends FourzeMiddlewareHandler { - name?: string - setup?: (app?: FourzeApp) => MaybePromise - readonly order?: number + name?: string; + setup?: (app?: FourzeApp) => MaybePromise; + readonly order?: number; } export function defineMiddleware(name: string, order: number, handler: FourzeMiddlewareHandler): FourzeMiddleware; @@ -83,41 +85,41 @@ export function isFourzeMiddleware(obj: any): obj is FourzeMiddleware { } export interface FourzeApp extends FourzeMiddleware, MetaInstance { - use(path: string, ...middlewares: FourzeMiddleware[]): this + use(path: string, ...middlewares: FourzeMiddleware[]): this; - use(...modules: FourzeModule[]): this + use(...modules: FourzeModule[]): this; - remove(name: string): this + remove(name: string): this; /** * 是否允许 * @param url */ - isAllow(url: string): boolean + isAllow(url: string): boolean; - allow(...rules: MaybeRegex[]): this + allow(...rules: MaybeRegex[]): this; - deny(...rules: MaybeRegex[]): this + deny(...rules: MaybeRegex[]): this; - relative(url: string): string | null + relative(url: string): string | null; - match(url: string): [string, FourzeMiddleware][] + match(url: string): [string, FourzeMiddleware][]; - service(context: FourzeContextOptions, fallback?: FourzeHandle): Promise + service(context: FourzeContextOptions, fallback?: FourzeHandle): Promise; - ready(): Promise + ready(): Promise; - reset(): Promise + reset(): Promise; - readonly meta: FourzeAppMeta + readonly meta: FourzeAppMeta; - readonly base: string + readonly base: string; - readonly middlewares: FourzeMiddleware[] + readonly middlewares: FourzeMiddleware[]; - readonly isReady: boolean + readonly isReady: boolean; - readonly isReadying: boolean + readonly isReadying: boolean; } @@ -125,13 +127,13 @@ export type FourzeModule = FourzePlugin | FourzeMiddleware; const FourzePluginFlag = "__isFourzePlugin"; export interface FourzePluginInstall { - (app: FourzeApp): MaybePromise + (app: FourzeApp): MaybePromise; } export interface FourzePlugin { - name?: string - install: FourzePluginInstall - readonly [FourzePluginFlag]: true + name?: string; + install: FourzePluginInstall; + readonly [FourzePluginFlag]: true; } export function definePlugin(install: FourzePluginInstall): FourzePlugin; diff --git a/packages/core/src/shared/matcher.ts b/packages/core/src/shared/matcher.ts index ef9e1660..98f1a40b 100644 --- a/packages/core/src/shared/matcher.ts +++ b/packages/core/src/shared/matcher.ts @@ -5,13 +5,13 @@ import type { RequestMethod } from "./request"; interface RouteMatcher { - add(path: string, method: RequestMethod | "all", payload: T): this + add(path: string, method: RequestMethod | "all", payload: T): this; - match(path: string, method: RequestMethod | "all"): [T | null, Record | null] + match(path: string, method: RequestMethod | "all"): [T | null, Record | null]; - remove(path: string, method?: RequestMethod): boolean + remove(path: string, method?: RequestMethod): boolean; - traverse(callback: (payload: T, path: string, method: RequestMethod | "all") => void): void + traverse(callback: (payload: T, path: string, method: RequestMethod | "all") => void): void; } const NODE_TYPES = { @@ -23,13 +23,13 @@ const NODE_TYPES = { type NodeType = typeof NODE_TYPES[keyof typeof NODE_TYPES]; export interface RouteNode { - type: NodeType - children: Map> - parent: RouteNode | null - wildcardChildNode: RouteNode | null - placeholderChildNode: RouteNode | null - paramName: string | null - payload: Map + type: NodeType; + children: Map>; + parent: RouteNode | null; + wildcardChildNode: RouteNode | null; + placeholderChildNode: RouteNode | null; + paramName: string | null; + payload: Map; } function createRouteNode(options: Partial> = {}): RouteNode { @@ -45,10 +45,10 @@ function createRouteNode(options: Partial> = {}): RouteNode { } export interface RouteMatcherOptions { - caseSensitive?: boolean - strictTrailingSlash?: boolean - notAllowedRaiseError?: boolean - cache?: boolean + caseSensitive?: boolean; + strictTrailingSlash?: boolean; + notAllowedRaiseError?: boolean; + cache?: boolean; } /** diff --git a/packages/core/src/shared/meta.ts b/packages/core/src/shared/meta.ts index d01a9b98..affec6c9 100644 --- a/packages/core/src/shared/meta.ts +++ b/packages/core/src/shared/meta.ts @@ -1,10 +1,10 @@ import { isObject } from "../utils"; export interface MetaInstance> { - readonly meta: Meta - setMeta(key: string, value: any): This - setMeta(meta: Meta): This - getMeta(key: string): T | undefined + readonly meta: Meta; + setMeta(key: string, value: any): This; + setMeta(meta: Meta): This; + getMeta(key: string): T | undefined; } export function injectMeta>(instance: This, meta: This["meta"] = {}): MetaInstance { diff --git a/packages/core/src/shared/props.ts b/packages/core/src/shared/props.ts index ac16a4e3..a6a8d30f 100644 --- a/packages/core/src/shared/props.ts +++ b/packages/core/src/shared/props.ts @@ -14,7 +14,8 @@ export declare type ExtractPropTypes = { } & GlobalProps; export type ExtractPropTypesWithIn< - O, In extends PropIn + O, +In extends PropIn > = ExtractPropTypes>>; export type ExtractDefaultPropTypes

> = { @@ -27,29 +28,29 @@ export type LooseRequired = { export type DefaultKeys = { [K in keyof T]: T[K] extends { - default: any + default: any; } | BooleanConstructor | { - type: BooleanConstructor + type: BooleanConstructor; } ? T[K] extends { - type: BooleanConstructor - required: true + type: BooleanConstructor; + required: true; } ? never : K : never; }[keyof T]; export type RequiredKeys = { [K in keyof T]: T[K] extends | { - required: true + required: true; } | { - default: any + default: any; } | BooleanConstructor | { - type: BooleanConstructor + type: BooleanConstructor; } ? T[K] extends { - default: undefined | (() => undefined) + default: undefined | (() => undefined); } ? never : K @@ -60,7 +61,7 @@ export type OptionalKeys = Exclude>; export type InKeys = { [K in keyof T]: T[K] extends { - in: In + in: In; } ? K : never; @@ -72,36 +73,36 @@ export type InferPropType = [T] extends [null] ? any : [T] extends [ { - type: null | true + type: null | true; } ] ? any : [T] extends [ - | ObjectConstructor - | { - type: ObjectConstructor - } + | ObjectConstructor + | { + type: ObjectConstructor; + } ] ? Record : [T] extends [ - | BooleanConstructor - | { - type: BooleanConstructor - } + | BooleanConstructor + | { + type: BooleanConstructor; + } ] ? boolean : [T] extends [ - | DateConstructor - | { - type: DateConstructor - } + | DateConstructor + | { + type: DateConstructor; + } ] ? Date : [T] extends [ - | (infer U)[] - | { - type: (infer U)[] - } + | (infer U)[] + | { + type: (infer U)[]; + } ] ? U extends DateConstructor ? Date | InferPropType @@ -124,10 +125,10 @@ type Prop = PropOptions | PropType; type PropConstructor = | { - new(...args: any[]): T & {} + new(...args: any[]): NonNullable; } | { - (): T + (): T; } | PropMethod; @@ -135,29 +136,29 @@ type PropMethod = [T] extends [ ((...args: any) => any) | undefined ] ? { - new(): TConstructor - (): T - readonly prototype: TConstructor + new(): TConstructor; + (): T; + readonly prototype: TConstructor; } : never; export interface PropOptions { - type: PropType - required?: boolean - default?: Default | DefaultFactory | null | undefined | object - validator?(value: unknown): boolean - transform?(value: unknown): Type - meta?: Record - in?: PropIn + type: PropType; + required?: boolean; + default?: Default | DefaultFactory | null | undefined | object; + validator?(value: unknown): boolean; + transform?(value: unknown): Type; + meta?: Record; + in?: PropIn; } export interface NormalizedProps extends PropOptions { - meta: Record - in?: PropIn - required: boolean - type: PropType - default?: Default | DefaultFactory | null | undefined | object + meta: Record; + in?: PropIn; + required: boolean; + type: PropType; + default?: Default | DefaultFactory | null | undefined | object; } declare type DefaultFactory = (props: DefaultData) => T | null | undefined; @@ -166,7 +167,7 @@ export type PropType = PropConstructor | PropConstructor[]; export function isExtends(types: PropType, value: PropType): boolean { if (Array.isArray(types)) { - return types.some((e) => isExtends(e, value)); + return types.some(e => isExtends(e, value)); } return value === types; } @@ -192,7 +193,7 @@ function getType(fn: PropType) { */ export function isInstanceOf(type: PropType | PropType[], value: any): value is D { if (Array.isArray(type)) { - return type.some((e) => isInstanceOf(e, value)); + return type.some(e => isInstanceOf(e, value)); } const expectedType = getType(type); let valid = true; @@ -239,7 +240,7 @@ export function normalizeProps( result[key] = { type: prop, in: "query", - required: prop.some((p) => isExtends(p as PropType, Boolean)), + required: prop.some(p => isExtends(p as PropType, Boolean)), meta: {} }; continue; @@ -261,7 +262,10 @@ export function normalizeProps( } export function withDefaults< - T = Record, P extends ObjectProps = ObjectProps, D = ExtractPropTypes

, Defaults = ExtractDefaultPropTypes

+ T = Record, +P extends ObjectProps = ObjectProps, +D = ExtractPropTypes

, +Defaults = ExtractDefaultPropTypes

>(props: Partial & Omit, propsOptions: P, propIn?: PropIn): D { if (Array.isArray(propsOptions)) { return props as D; @@ -287,7 +291,7 @@ export function withDefaults< if (propIn) { continue; } - if (opt.some((e) => isExtends(e, Boolean))) { + if (opt.some(e => isExtends(e, Boolean))) { rs[k] = false as D[typeof k]; } continue; @@ -326,10 +330,9 @@ export function validateProps( } } - export function defineExtends

(props: P): ({ - (): P - (extraProps: E): P & E + (): P; + (extraProps: E): P & E; }) { return (extraProps?: E) => { return { @@ -338,4 +341,3 @@ export function defineExtends

(props: P): ({ }; }; } - diff --git a/packages/core/src/shared/request.ts b/packages/core/src/shared/request.ts index fffb769c..4831034f 100644 --- a/packages/core/src/shared/request.ts +++ b/packages/core/src/shared/request.ts @@ -28,57 +28,62 @@ export const FOURZE_METHODS = [ export type RequestMethod = typeof FOURZE_METHODS[number]; export interface FourzeRequestOptions { - url: string - method?: string - headers?: PolyfillHeaderInit - body?: any - params?: Record - query?: Record - meta?: Record - request?: IncomingMessage - contentTypeParsers?: Map any> + url: string; + method?: string; + headers?: PolyfillHeaderInit; + body?: any; + params?: Record; + query?: Record; + meta?: Record; + request?: IncomingMessage; + contentTypeParsers?: Map any>; } export interface FourzeRequest< - Props extends ObjectProps = DefaultData, Meta = FourzeRouteMeta, Data = ExtractPropTypes, Query = ExtractPropTypesWithIn, Body = ExtractPropTypesWithIn, Params = ExtractPropTypesWithIn + Props extends ObjectProps = DefaultData, +Meta = FourzeRouteMeta, +Data = ExtractPropTypes, +Query = ExtractPropTypesWithIn, +Body = ExtractPropTypesWithIn, +Params = ExtractPropTypesWithIn > extends IncomingMessage { - url: string - method: string - headers: Record + url: string; + method: string; + headers: Record; - route: FourzeRoute + route: FourzeRoute; - app?: FourzeApp + app?: FourzeApp; - meta: Meta & FourzeRouteMeta + meta: Meta & FourzeRouteMeta; - contextPath: string + contextPath: string; - setRoute(route: FourzeRoute, matchParams?: Record | null): void + setRoute(route: FourzeRoute, matchParams?: Record | null): void; - withScope(scope: string): FourzeRequest + withScope(scope: string): FourzeRequest; - readonly contentType: string + readonly contentType: string; - readonly req?: IncomingMessage + readonly req?: IncomingMessage; - readonly originalPath: string + readonly originalPath: string; - readonly params: Params + readonly params: Params; - readonly query: Query + readonly query: Query; - readonly body: Body + readonly body: Body; /** * {...query, ...params, ...body} */ - readonly data: Data + readonly data: Data; - readonly raw: string + readonly raw: string; - readonly path: string + readonly path: string; - readonly [FourzeRequestFlag]: true + readonly [FourzeRequestFlag]: true; } export function createRequest(options: FourzeRequestOptions) { diff --git a/packages/core/src/shared/response.ts b/packages/core/src/shared/response.ts index cdd4d6e1..22ee8245 100644 --- a/packages/core/src/shared/response.ts +++ b/packages/core/src/shared/response.ts @@ -6,10 +6,10 @@ import { FourzeError } from "./error"; import type { FourzeRequest } from "./request"; export interface FourzeResponseOptions { - url: string - method: string - request: FourzeRequest - response?: OutgoingMessage + url: string; + method: string; + request: FourzeRequest; + response?: OutgoingMessage; } const FourzeResponseFlag = "__isFourzeResponse"; @@ -17,75 +17,75 @@ const FourzeResponseFlag = "__isFourzeResponse"; export interface FourzeBaseResponse extends ServerResponse { } export interface FourzeResponse extends FourzeBaseResponse { - json(payload: any): this + json(payload: any): this; - image(payload: Buffer): this + image(payload: Buffer): this; - text(payload: string): this + text(payload: string): this; - binary(payload: Buffer): this + binary(payload: Buffer): this; - redirect(url: string): this + redirect(url: string): this; - appendHeader(key: string, value: string | string[]): this + appendHeader(key: string, value: string | string[]): this; - removeHeader(key: string): this + removeHeader(key: string): this; /** * 发送数据 * @param payload * @param contentType */ - send(payload: any, contentType?: string | null): this + send(payload: any, contentType?: string | null): this; - send(payload: any, statusCode?: number): this + send(payload: any, statusCode?: number): this; - send(payload: any, statusCode?: number, contentType?: string | null): this + send(payload: any, statusCode?: number, contentType?: string | null): this; /** * 获取Content-Type * @param payload 如果没有指定contentType,则会根据payload的类型自动推断 */ - getContentType(payload?: any): string | undefined + getContentType(payload?: any): string | undefined; /** * 设置Content-Type * @param contentType */ - setContentType(contentType: string): this + setContentType(contentType: string): this; - status(code: number): this + status(code: number): this; /** * 发送错误 * @param code * @param error */ - sendError(code: number, error?: string | Error): this + sendError(code: number, error?: string | Error): this; /** * 发送错误 * @param error */ - sendError(error?: string | Error): this + sendError(error?: string | Error): this; /** * 等待所有的异步操作完成 */ - done(): Promise + done(): Promise; - sent: boolean + sent: boolean; - readonly res?: OutgoingMessage + readonly res?: OutgoingMessage; - readonly request: FourzeRequest + readonly request: FourzeRequest; - readonly url: string + readonly url: string; - readonly payload: any + readonly payload: any; - readonly error: FourzeError | undefined + readonly error: FourzeError | undefined; - readonly [FourzeResponseFlag]: true + readonly [FourzeResponseFlag]: true; } export function createResponse(options: FourzeResponseOptions) { @@ -181,7 +181,7 @@ export function createResponse(options: FourzeResponseOptions) { name, [oldValue, value] .flat() - .filter((r) => !!r) + .filter(r => !!r) .join(",") ); } else { diff --git a/packages/core/src/shared/route.ts b/packages/core/src/shared/route.ts index 699ce781..b9192dda 100644 --- a/packages/core/src/shared/route.ts +++ b/packages/core/src/shared/route.ts @@ -8,39 +8,45 @@ import type { FourzeHandle } from "./interface"; const FourzeRouteFlag = "__isFourzeRoute"; export interface FourzeRouteOptions { - method?: RequestMethod - props?: Props - meta?: Meta & FourzeRouteMeta + method?: RequestMethod; + props?: Props; + meta?: Meta & FourzeRouteMeta; } export interface FourzeBaseRoute< - Result = unknown, Props extends ObjectProps = DefaultData, Meta = FourzeRouteMeta + Result = unknown, +Props extends ObjectProps = DefaultData, +Meta = FourzeRouteMeta > { - path: string - method?: RequestMethod - handle: FourzeHandle - meta?: Meta - props?: Props + path: string; + method?: RequestMethod; + handle: FourzeHandle; + meta?: Meta; + props?: Props; } export interface FourzeRoute< - Result = unknown, Props extends ObjectProps = DefaultData, Meta = FourzeRouteMeta + Result = unknown, +Props extends ObjectProps = DefaultData, +Meta = FourzeRouteMeta > extends FourzeBaseRoute { - readonly [FourzeRouteFlag]: true - readonly props: Props - readonly meta: Meta + readonly [FourzeRouteFlag]: true; + readonly props: Props; + readonly meta: Meta; } export type FourzeRouteGenerator = { [K in RequestMethod]: { < - Result = any, Props extends ObjectProps = DefaultData, Meta = FourzeRouteMeta + Result = any, +Props extends ObjectProps = DefaultData, +Meta = FourzeRouteMeta >( path: string, options: FourzeRouteOptions, handle: FourzeHandle - ): This - (path: string, handle: FourzeHandle): This + ): This; + (path: string, handle: FourzeHandle): This; }; }; @@ -60,7 +66,9 @@ export function defineRouteProps( } export function defineRoute< - Result = unknown, Props extends ObjectProps = DefaultData, Meta = FourzeRouteMeta + Result = unknown, +Props extends ObjectProps = DefaultData, +Meta = FourzeRouteMeta >( route: FourzeBaseRoute & { base?: string } ): FourzeRoute { @@ -91,4 +99,3 @@ export function defineRoute< } }; } - diff --git a/packages/core/src/utils/array.ts b/packages/core/src/utils/array.ts index cf7eca6e..c0b07f4a 100644 --- a/packages/core/src/utils/array.ts +++ b/packages/core/src/utils/array.ts @@ -11,168 +11,168 @@ export type PredicateParameter = [PredicateFn] | [keyof T, ...T[keyof T][] export type MapParameter = keyof T | MapFn; export interface Predicate extends PredicateFn { - and(...args: PredicateParameter): this - or(...args: PredicateParameter): this + and(...args: PredicateParameter): this; + or(...args: PredicateParameter): this; } export interface ExtraArrayMethods { - where(fn: PredicateFn): CollectionQuery - select(mapFn: MapFn): CollectionQuery - select(): CollectionQuery + where(fn: PredicateFn): CollectionQuery; + select(mapFn: MapFn): CollectionQuery; + select(): CollectionQuery; } export interface MathQuery { - max(fn?: MapFn): typeof fn extends undefined ? T extends number ? T : never : number - min(fn?: MapFn): typeof fn extends undefined ? T extends number ? T : never : number - sum(fn?: MapFn): typeof fn extends undefined ? T extends number ? T : never : number - average(fn?: MapFn): typeof fn extends undefined ? T extends number ? T : never : number + max(fn?: MapFn): typeof fn extends undefined ? T extends number ? T : never : number; + min(fn?: MapFn): typeof fn extends undefined ? T extends number ? T : never : number; + sum(fn?: MapFn): typeof fn extends undefined ? T extends number ? T : never : number; + average(fn?: MapFn): typeof fn extends undefined ? T extends number ? T : never : number; } export interface ArrayQuery extends Iterable { join( separator?: string - ): string + ): string; - at(index: number): T | undefined + at(index: number): T | undefined; - fill(value: T, start?: number, end?: number): this - sort(compareFn?: CompareFn): this - reverse(): this + fill(value: T, start?: number, end?: number): this; + sort(compareFn?: CompareFn): this; + reverse(): this; - includes(value: T, fromIndex?: number): boolean + includes(value: T, fromIndex?: number): boolean; - some(fn: PredicateFn): boolean - every(fn: PredicateFn): boolean + some(fn: PredicateFn): boolean; + every(fn: PredicateFn): boolean; - find(fn: PredicateFn): T | undefined - findIndex(fn: PredicateFn): number - findLast(fn: PredicateFn): T | undefined - findLastIndex(fn: PredicateFn): number + find(fn: PredicateFn): T | undefined; + findIndex(fn: PredicateFn): number; + findLast(fn: PredicateFn): T | undefined; + findLastIndex(fn: PredicateFn): number; reduce( callbackfn: (previousValue: U, currentValue: T, currentIndex: number) => U, initialValue: U - ): U + ): U; reduceRight( callbackfn: (previousValue: U, currentValue: T, currentIndex: number) => U, initialValue: U - ): U - forEach(fn: (item: T, index: number) => void): void + ): U; + forEach(fn: (item: T, index: number) => void): void; - indexOf(value: T, fromIndex?: number): number - lastIndexOf(value: T, fromIndex?: number): number + indexOf(value: T, fromIndex?: number): number; + lastIndexOf(value: T, fromIndex?: number): number; } export interface CollectionBase extends Iterable { - append(...items: T[]): this - prepend(...items: T[]): this - insert(index: number, ...items: T[]): this - delete(index: number): this - delete(fn: PredicateFn, deleteLimit?: number): this - replace(fn: PredicateFn, item: T): this - set(index: number, value: T): this - get(index: number): T | undefined - clear(): this - reset(source?: Iterable): this - clone(): this - first(): T | undefined - last(): T | undefined - [key: number]: T - length: number + append(...items: T[]): this; + prepend(...items: T[]): this; + insert(index: number, ...items: T[]): this; + delete(index: number): this; + delete(fn: PredicateFn, deleteLimit?: number): this; + replace(fn: PredicateFn, item: T): this; + set(index: number, value: T): this; + get(index: number): T | undefined; + clear(): this; + reset(source?: Iterable): this; + clone(): this; + first(): T | undefined; + last(): T | undefined; + [key: number]: T; + length: number; } export interface CollectionQuery extends CollectionBase, ArrayQuery, MathQuery { - where(fn: PredicateFn): CollectionQuery - where(key: K, ...values: V[]): CollectionQuery + where(fn: PredicateFn): CollectionQuery; + where(key: K, ...values: V[]): CollectionQuery; - select(mapFn: MapFn): CollectionQuery - select(key: K): CollectionQuery - select(): CollectionQuery + select(mapFn: MapFn): CollectionQuery; + select(key: K): CollectionQuery; + select(): CollectionQuery; - chunk(size: number): CollectionQuery + chunk(size: number): CollectionQuery; - union(...collections: T[]): this + union(...collections: T[]): this; - distinct(): this - distinct(selector: MapFn): this - distinct(selector: keyof T): this + distinct(): this; + distinct(selector: MapFn): this; + distinct(selector: keyof T): this; - intersect(...collections: Iterable[]): this - except(...collections: Iterable[]): this + intersect(...collections: Iterable[]): this; + except(...collections: Iterable[]): this; - zip(collection: Iterable): CollectionQuery<[T, U]> + zip(collection: Iterable): CollectionQuery<[T, U]>; zip( collection: Iterable, mapFn: (a: T, b: U) => R - ): CollectionQuery + ): CollectionQuery; - groupBy(mapFn: MapParameter): CollectionQuery<[K, T[]]> + groupBy(mapFn: MapParameter): CollectionQuery<[K, T[]]>; - orderBy(fn: CompareFn): this - orderBy(key: K, desc?: boolean, nullsFirst?: boolean): this + orderBy(fn: CompareFn): this; + orderBy(key: K, desc?: boolean, nullsFirst?: boolean): this; - countBy(mapFn: MapParameter): CollectionQuery<[K, number]> + countBy(mapFn: MapParameter): CollectionQuery<[K, number]>; - crossJoin(collection: Iterable): CollectionQuery<[T, U]> + crossJoin(collection: Iterable): CollectionQuery<[T, U]>; crossJoin( collection: Iterable, fn: (a: T, b: U) => R - ): CollectionQuery + ): CollectionQuery; innerJoin( collection: Iterable, outerKeySelector: MapFn, innerKeySelector: MapFn, resultSelector: (a: T, b: U) => R - ): CollectionQuery + ): CollectionQuery; leftJoin( collection: Iterable, outerKeySelector: MapFn, innerKeySelector: MapFn, resultSelector: (a: T, b: U | undefined) => R - ): CollectionQuery + ): CollectionQuery; groupJoin( collection: Iterable, outerKeySelector: MapParameter, innerKeySelector: MapParameter, resultSelector: (a: T, b: U[]) => R - ): CollectionQuery + ): CollectionQuery; - concat(...collections: (ConcatArray | T)[]): CollectionQuery - flat(depth?: D): CollectionQuery> - flatMap(mapFn: MapFn): CollectionQuery + concat(...collections: (ConcatArray | T)[]): CollectionQuery; + flat(depth?: D): CollectionQuery>; + flatMap(mapFn: MapFn): CollectionQuery; - map(mapFn: MapFn): CollectionQuery - filter(fn: PredicateFn): CollectionQuery - slice(start?: number, end?: number): CollectionQuery + map(mapFn: MapFn): CollectionQuery; + filter(fn: PredicateFn): CollectionQuery; + slice(start?: number, end?: number): CollectionQuery; - toArray(): T[] - toSet(): Set + toArray(): T[]; + toSet(): Set; toMap( keySelector: MapFn - ): Map + ): Map; toMap( keySelector: MapFn, valueSelector: MapFn - ): Map + ): Map; - toJSON(): T[] + toJSON(): T[]; - toString(): string + toString(): string; } -const getPredicateFn = (...args: PredicateParameter) => { +function getPredicateFn(...args: PredicateParameter) { const [fn] = args; if (isFunction(fn)) { return fn; } const values = args.slice(1) as T[keyof T][]; return (item: T) => values.includes(item[fn]); -}; +} export function createPredicate( ...args: PredicateParameter @@ -198,7 +198,7 @@ export function createPredicate( return predicate; } -const normalizeMapFn = (fn: MapParameter) => { +function normalizeMapFn(fn: MapParameter) { if (isDef(fn)) { if (isFunction(fn)) { return fn as MapFn; @@ -206,7 +206,7 @@ const normalizeMapFn = (fn: MapParameter) => { return (item: T) => item[fn as keyof T]; } return (item: T) => item; -}; +} function normalizeIndex(index: number, length: number) { return index < 0 ? length + index : index; @@ -345,21 +345,21 @@ export class CollectionQueryClass implements ArrayLike { max(fn?: MapFn) { if (!fn) { - fn = (item) => isNumber(item) ? item : 0; + fn = item => isNumber(item) ? item : 0; } return Math.max(...this.source.map(fn)); } min(fn?: MapFn) { if (!fn) { - fn = (item) => isNumber(item) ? item : 0; + fn = item => isNumber(item) ? item : 0; } return Math.min(...this.source.map(fn)); } sum(fn?: MapFn) { if (!fn) { - fn = (item) => isNumber(item) ? item : 0; + fn = item => isNumber(item) ? item : 0; } return this.source.map(fn).reduce((a, b) => a + b, 0); } @@ -388,8 +388,8 @@ export class CollectionQueryClass implements ArrayLike { } intersect(...collections: Iterable[]) { - const set = new Set(collections.flatMap((c) => Array.from(c))); - const array = this.source.filter((item) => set.has(item)); + const set = new Set(collections.flatMap(c => Array.from(c))); + const array = this.source.filter(item => set.has(item)); return this.reset(array); } @@ -402,13 +402,13 @@ export class CollectionQueryClass implements ArrayLike { } union(...collections: Iterable[]) { - this.source.push(...collections.flatMap((c) => Array.from(c))); + this.source.push(...collections.flatMap(c => Array.from(c))); return this; } except(...collections: Iterable[]) { - const set = new Set(collections.flatMap((c) => Array.from(c))); - const array = this.source.filter((item) => !set.has(item)); + const set = new Set(collections.flatMap(c => Array.from(c))); + const array = this.source.filter(item => !set.has(item)); return this.reset(array); } @@ -499,7 +499,7 @@ export class CollectionQueryClass implements ArrayLike { resultSelector: (a: T, b: U) => R = (a, b) => [a, b] as R ) { const array = Array.from(collection); - const result = this.source.flatMap((item) => array.map((i) => resultSelector(item, i))); + const result = this.source.flatMap(item => array.map(i => resultSelector(item, i))); return createQuery(result); } @@ -514,7 +514,7 @@ export class CollectionQueryClass implements ArrayLike { const result = this.source.flatMap((item, index) => { const key = outerKeySelector(item, index, this.source); const inner = array.filter((i, iIndex) => innerKeySelector(i, iIndex, innerSource) === key); - return inner.map((i) => resultSelector(item, i)); + return inner.map(i => resultSelector(item, i)); }); return createQuery(result); } diff --git a/packages/core/src/utils/faker.ts b/packages/core/src/utils/faker.ts index 3fcc449c..8c3bcfd1 100644 --- a/packages/core/src/utils/faker.ts +++ b/packages/core/src/utils/faker.ts @@ -26,8 +26,8 @@ export function parseFakerNumber(num: MaybeArray): number { } export interface MockObjectOption { - deep?: boolean - context?: Record + deep?: boolean; + context?: Record; } const transformSign = ["|", "-", "{", "}", "$"]; @@ -135,7 +135,7 @@ export function parseFakerObject( options.context = options.context ?? {}; if (Array.isArray(obj)) { - return obj.map((v) => parseFakerObject(v, options)); + return obj.map(v => parseFakerObject(v, options)); } if (isPrimitive(obj)) { @@ -145,7 +145,7 @@ export function parseFakerObject( return Object.fromEntries( Object.entries(obj).map(([k, v]) => { if (Array.isArray(v)) { - return [k, v.map((f) => parseFakerObject(f, options))]; + return [k, v.map(f => parseFakerObject(f, options))]; } return [k, parseFakerObject(v, options)]; }) diff --git a/packages/core/src/utils/html.ts b/packages/core/src/utils/html.ts index f261c51e..95dca5f5 100644 --- a/packages/core/src/utils/html.ts +++ b/packages/core/src/utils/html.ts @@ -16,23 +16,23 @@ const htmlTemplateString = ` `; export interface ScriptTagAttributes extends Record { - src: string - lang?: string - type?: string + src: string; + lang?: string; + type?: string; } export interface StyleTagAttributes extends Record { - type?: string - media?: string - rel?: string - href?: string + type?: string; + media?: string; + rel?: string; + href?: string; } export interface HtmlTag { - tag: string - attributes?: Record - content?: string - in?: "body" | "head" | "html" + tag: string; + attributes?: Record; + content?: string; + in?: "body" | "head" | "html"; } export interface HtmlHeadTag extends Omit { @@ -41,15 +41,15 @@ export interface HtmlHeadTag extends Omit { export interface HtmlBodyTag extends Omit { } export interface RenderHtmlOptions { - language?: string - favicon?: string | string[] - title?: string - meta?: Record[] - tags?: HtmlTag[] - head?: HtmlHeadTag[] - body?: HtmlBodyTag[] - script?: (string | ScriptTagAttributes)[] - style?: (string | StyleTagAttributes)[] + language?: string; + favicon?: string | string[]; + title?: string; + meta?: Record[]; + tags?: HtmlTag[]; + head?: HtmlHeadTag[]; + body?: HtmlBodyTag[]; + script?: (string | ScriptTagAttributes)[]; + style?: (string | StyleTagAttributes)[]; } const notCloseTags = ["img", "br", "hr", "input", "meta", "link", "area"]; @@ -65,7 +65,7 @@ export function renderElement(tag: string, props: any = {}, ...children: any[]) function renderChildren(children: any[]): string { if (Array.isArray(children)) { - return children.map((c) => (Array.isArray(c) ? renderChildren(c) : c)).join(""); + return children.map(c => (Array.isArray(c) ? renderChildren(c) : c)).join(""); } return children; } @@ -96,20 +96,20 @@ export function renderHtml(options: RenderHtmlOptions = {}) { } if (options.meta?.length) { - headTags.push(...options.meta.map(r => { + headTags.push(...options.meta.map((r) => { return { tag: "meta", attributes: r }; })); } if (options.favicon) { const favicon = Array.isArray(options.favicon) ? options.favicon : [options.favicon]; - headTags.push(...favicon.map(r => { + headTags.push(...favicon.map((r) => { return { tag: "link", attributes: { rel: "icon", href: r } }; })); } if (options.style?.length) { - headTags.push(...options.style.map(r => { + headTags.push(...options.style.map((r) => { if (isString(r)) { return { tag: "link", attributes: { href: r, rel: "stylesheet" } }; } @@ -120,7 +120,7 @@ export function renderHtml(options: RenderHtmlOptions = {}) { const bodyTags: HtmlTag[] = [...tags.filter(r => r.in === "body"), ...options.body ?? []]; if (options.script?.length) { - bodyTags.push(...options.script.map(r => { + bodyTags.push(...options.script.map((r) => { if (isString(r)) { return { tag: "script", attributes: { src: r } }; } diff --git a/packages/core/src/utils/is.ts b/packages/core/src/utils/is.ts index ef405842..c292c66f 100644 --- a/packages/core/src/utils/is.ts +++ b/packages/core/src/utils/is.ts @@ -41,7 +41,7 @@ export function isConstructor(value: unknown): value is Constructor { } export function isBuffer(value: unknown): value is Buffer { - return isObject(value) && !!globalThis.Buffer && Buffer.isBuffer(value); + return isObject(value) && !!globalThis.Buffer && globalThis.Buffer.isBuffer(value); } export function isUint8Array(value: unknown): value is Uint8Array { @@ -118,8 +118,8 @@ export const isBrowser = () => !isNode(); export type Constructor = | { - new (...args: any[]): T & {} + new (...args: any[]): NonNullable; } | { - (): T + (): T; }; diff --git a/packages/core/src/utils/object.ts b/packages/core/src/utils/object.ts index 61d13017..743841bc 100644 --- a/packages/core/src/utils/object.ts +++ b/packages/core/src/utils/object.ts @@ -44,7 +44,7 @@ export function aliasObjectMap = Record); const inheritKeys = (isBoolean(inherit) ? (inherit ? Object.keys(obj) : []) : inherit) as string[]; - inheritKeys.forEach(key => { + inheritKeys.forEach((key) => { rs[key] = rs[key] ?? obj[key]; }); diff --git a/packages/core/src/utils/overload.ts b/packages/core/src/utils/overload.ts index 8e890eda..f36eb04f 100644 --- a/packages/core/src/utils/overload.ts +++ b/packages/core/src/utils/overload.ts @@ -17,12 +17,12 @@ type ExtractPropTypes< } & Record; export interface OverloadOptions { - type: PropType - required?: boolean - default?: ((value: Type) => Default) | Default - transform?: (value: Type) => any - match?: (value: Type) => boolean - rest?: boolean + type: PropType; + required?: boolean; + default?: ((value: Type) => Default) | Default; + transform?: (value: Type) => any; + match?: (value: Type) => boolean; + rest?: boolean; } export function defineOverload( diff --git a/packages/core/src/utils/promise.ts b/packages/core/src/utils/promise.ts index 7e78a54f..a077eec4 100644 --- a/packages/core/src/utils/promise.ts +++ b/packages/core/src/utils/promise.ts @@ -12,16 +12,16 @@ export type DelayMsType = MaybeFunction>; export function delay(ms: DelayMsType) { ms = isFunction(ms) ? ms() : ms; const tmp = parseFakerNumber(ms); - return new Promise((resolve) => setTimeout(() => resolve(tmp), tmp)); + return new Promise(resolve => setTimeout(() => resolve(tmp), tmp)); } export interface SingletonPromiseReturn { - (): Promise + (): Promise; /** * Reset current staled promise. * Await it to have proper shutdown. */ - reset: () => Promise + reset: () => Promise; } /** @@ -58,51 +58,51 @@ export interface MemoizeReturn { /** * Memoize function */ - (...args: P): R + (...args: P): R; /** * Get raw function * @param args * @returns */ - raw: (...args: P) => R + raw: (...args: P) => R; /** * Force cache by key * @param args * @returns */ - force: (...args: P) => R + force: (...args: P) => R; /** * Set cache by key * @param key * @param value */ - set(key: K | P, value: R): void + set(key: K | P, value: R): void; /** * Get cache by key * @param key */ - get(key: K | P): R | undefined + get(key: K | P): R | undefined; - delete(key: K | P): boolean + delete(key: K | P): boolean; /** * Clear cache * @returns */ - clear: () => void + clear: () => void; - readonly cache: Map + readonly cache: Map; - readonly size: number + readonly size: number; } export interface MemoizeOptions<_, P extends any[], K extends string | number | symbol> { - serialize?: (...args: P) => K - maxCount?: number + serialize?: (...args: P) => K; + maxCount?: number; } /** * Create memoize promise function @@ -174,4 +174,3 @@ export function memoize( source: T[], callback?: (value: T, index: number, array: T[]) => U ): U { - callback = callback ?? ((value) => value as any); + callback = callback ?? (value => value as any); const index = randomInt(source.length); return callback(source[index], index, source); } diff --git a/packages/core/src/utils/storage.ts b/packages/core/src/utils/storage.ts index 3d3dda0b..017f141d 100644 --- a/packages/core/src/utils/storage.ts +++ b/packages/core/src/utils/storage.ts @@ -2,27 +2,27 @@ import { isDef, isNode } from "./is"; import { parseJson } from "./string"; export interface Storage { - readonly length: number - clear(): void - getItem(key: string): any - key(index: number): string | null - removeItem(key: string): void - setItem(key: string, value: any): void - hasItem(key: string): boolean - [name: string]: any + readonly length: number; + clear(): void; + getItem(key: string): any; + key(index: number): string | null; + removeItem(key: string): void; + setItem(key: string, value: any): void; + hasItem(key: string): boolean; + [name: string]: any; } interface StorageOptions { - id?: string - persistence?: boolean + id?: string; + persistence?: boolean; /** * only for browser */ - target?: "local" | "session" + target?: "local" | "session"; /** * only for node */ - dir?: string + dir?: string; } export function createStorage(options: StorageOptions = {}): Storage { @@ -54,7 +54,7 @@ export function createStorage(options: StorageOptions = {}): Storage { }; case "clear": return () => { - Object.keys(target).forEach((key) => + Object.keys(target).forEach(key => Reflect.deleteProperty(target, key) ); emitChange(); diff --git a/packages/core/test/matcher.test.ts b/packages/core/test/matcher.test.ts index 03739aa2..2eed22c7 100644 --- a/packages/core/test/matcher.test.ts +++ b/packages/core/test/matcher.test.ts @@ -1,7 +1,7 @@ -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; import { createRouteMatcher } from "../src/shared/matcher"; -test("mock-matcher", async () => { +it("mock-matcher", async () => { const matcher = createRouteMatcher(); matcher.add("/hello/1", "get", "hello-1"); diff --git a/packages/core/test/overload.test.ts b/packages/core/test/overload.test.ts index 557a8a2d..ed6cf1cc 100644 --- a/packages/core/test/overload.test.ts +++ b/packages/core/test/overload.test.ts @@ -1,5 +1,5 @@ import { defineOverload } from "@fourze/core"; -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; const overload = defineOverload({ path: { @@ -22,7 +22,7 @@ const overload = defineOverload({ } }); -test("should overload", () => { +it("should overload", () => { const data = overload([ "/test", { diff --git a/packages/core/test/request.test.ts b/packages/core/test/request.test.ts index 03534894..c473f7e9 100644 --- a/packages/core/test/request.test.ts +++ b/packages/core/test/request.test.ts @@ -1,7 +1,7 @@ -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; import { createRequest } from "../src/shared/request"; -test("query", () => { +it("query", () => { const request = createRequest({ url: "/api/test?name=hello&age=18&male=true", method: "POST", diff --git a/packages/core/test/router.test.ts b/packages/core/test/router.test.ts index d16c2aa4..d7d9878e 100644 --- a/packages/core/test/router.test.ts +++ b/packages/core/test/router.test.ts @@ -1,9 +1,9 @@ -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; import { createApp, defineRouter } from "@fourze/core"; -test("router-send", async () => { +it("router-send", async () => { const app = createApp(); - app.use(defineRouter(router => { + app.use(defineRouter((router) => { router.route("/hello", (_, res) => { res.send("hello,world!"); }); @@ -16,9 +16,9 @@ test("router-send", async () => { expect(response.sent).toBe(true); }); -test("router-return", async () => { +it("router-return", async () => { const app = createApp(); - app.use(defineRouter(router => { + app.use(defineRouter((router) => { router.route("/hello", () => { return "hello,world!"; }); @@ -31,9 +31,9 @@ test("router-return", async () => { expect(response.sent).toBe(true); }); -test("router-undefined", async () => { +it("router-undefined", async () => { const app = createApp(); - app.use(defineRouter(router => { + app.use(defineRouter((router) => { router.route("/hello", () => { return undefined; }); diff --git a/packages/core/test/shared.test.ts b/packages/core/test/shared.test.ts index 5c194bbc..dd0480a1 100644 --- a/packages/core/test/shared.test.ts +++ b/packages/core/test/shared.test.ts @@ -1,8 +1,7 @@ import { createApp } from "@fourze/core"; -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; - -test("test-isAllow", async () => { +it("test-isAllow", async () => { const app = createApp({ base: "/api", allow: ["/api/test", "/api/hello", "/api/add"], diff --git a/packages/core/test/utils/array.test.ts b/packages/core/test/utils/array.test.ts index 5c170f3a..e6b417e5 100644 --- a/packages/core/test/utils/array.test.ts +++ b/packages/core/test/utils/array.test.ts @@ -1,7 +1,7 @@ -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; import { createPredicate, createQuery, deleteBy, restoreArray } from "../../src/utils/array"; -test("mock-query", async () => { +it("mock-query", async () => { const query = createQuery(); query.set(0, "test"); query.set(1, "test2"); @@ -46,7 +46,7 @@ test("mock-query", async () => { expect(query[2]).toEqual(undefined); }); -test("mock-query-2", async () => { +it("mock-query-2", async () => { const magnus = { name: "Hedlund, Magnus" }; const terry = { name: "Adams, Terry" }; const charlotte = { name: "Weiss, Charlotte" }; @@ -62,7 +62,7 @@ test("mock-query-2", async () => { const query = createQuery(people).groupJoin(pets, "name", p => p.owner.name, (person, petCollection) => { return { name: person.name, - pets: petCollection.map((pet) => pet.name) + pets: petCollection.map(pet => pet.name) }; }); @@ -72,7 +72,7 @@ test("mock-query-2", async () => { expect(query[2]).toEqual({ name: "Weiss, Charlotte", pets: ["Whiskers"] }); }); -test("mock-query-math", async () => { +it("mock-query-math", async () => { const query = createQuery([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); expect(query.sum()).toEqual(55); expect(query.average()).toEqual(5.5); @@ -81,17 +81,17 @@ test("mock-query-math", async () => { expect(query.length).toEqual(10); }); -test("mock-query-distinct", async () => { +it("mock-query-distinct", async () => { const query = createQuery([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); expect(query.distinct().length).toEqual(10); const query2 = createQuery([{ name: "test" }, { name: "test2" }, { name: "test" }, { name: "test2" }]); expect(query2.distinct("name").toArray()).toEqual([{ name: "test" }, { name: "test2" }]); }); -test("mock-query-where", async () => { +it("mock-query-where", async () => { const query = createQuery([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); - expect(query.where((x) => x > 5).select().length).toEqual(5); + expect(query.where(x => x > 5).select().length).toEqual(5); query.sort().select(); @@ -100,19 +100,19 @@ test("mock-query-where", async () => { expect(query2.where("order", 1).select("name").toArray()).toEqual(["test", "test2", "test", "test2"]); }); -test("mock-array-deleteBy", async () => { +it("mock-array-deleteBy", async () => { expect(deleteBy([1, 2, 3, 4, 5, 6], r => r % 2 === 0)).toSatisfy((r: number[]) => { - return r.every((r) => r % 2 === 1); + return r.every(r => r % 2 === 1); }); }); -test("mock-array-restore", async () => { +it("mock-array-restore", async () => { const a = [1, 3, 5]; restoreArray(a, [2, 4, 6]); expect(a).toEqual([2, 4, 6]); }); -test("mock-predicate", async () => { +it("mock-predicate", async () => { let predicate = createPredicate((r: number) => r % 2 === 0); expect([2, 4, 6].every(predicate)).toBeTruthy(); expect([2, 4, 6, 7, 14, 21].every(predicate)).toBeFalsy(); diff --git a/packages/core/test/utils/faker.test.ts b/packages/core/test/utils/faker.test.ts index 0a55cab6..2277a34c 100644 --- a/packages/core/test/utils/faker.test.ts +++ b/packages/core/test/utils/faker.test.ts @@ -1,7 +1,7 @@ -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; import { parseFakerNumber, parseFakerObject } from "../../src/utils/faker"; -test("test-faker-number", () => { +it("test-faker-number", () => { expect(parseFakerNumber("200")).toBe(200); expect(parseFakerNumber(300)).toBe(300); expect(parseFakerNumber("abc")).toBeNaN(); @@ -11,7 +11,7 @@ test("test-faker-number", () => { expect(tmp).greaterThanOrEqual(200).lessThanOrEqual(1200); }); -test("test-faker-object", () => { +it("test-faker-object", () => { const [obj] = parseFakerObject([{ a: "{100}", b: "{300-600}", @@ -28,13 +28,11 @@ test("test-faker-object", () => { tof: "{true|false}", num: "{100|200|300}", mixin: "{'a'|b|c}-{100-200|300-600|700-900}" - }], - { + }], { context: { a: "123412" } - } - ); + }); expect(obj.a).toBe(100); expect(obj.b).toBeLessThan(600); expect(obj.b).toBeGreaterThan(300); diff --git a/packages/core/test/utils/html.test.ts b/packages/core/test/utils/html.test.ts index c37aaea2..5fb9e82c 100644 --- a/packages/core/test/utils/html.test.ts +++ b/packages/core/test/utils/html.test.ts @@ -1,7 +1,7 @@ -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; import { renderElement } from "../../src/utils/html"; -test("test-utils-html", () => { +it("test-utils-html", () => { expect(renderElement("div", { class: "test" }, "hello")).toBe("

hello
"); expect(renderElement("div", { class: "test" }, "hello", "world")).toBe("
helloworld
"); }); diff --git a/packages/core/test/utils/is.dom.test.ts b/packages/core/test/utils/is.dom.test.ts index f1140bdc..ac9a6dee 100644 --- a/packages/core/test/utils/is.dom.test.ts +++ b/packages/core/test/utils/is.dom.test.ts @@ -1,13 +1,12 @@ // @vitest-environment jsdom -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; import { isBrowser, isFormData } from "../../src/utils/is"; -test("is-type-dom", () => { +it("is-type-dom", () => { expect(isFormData(new FormData())).toBe(true); expect(isBrowser()).toBe(true); }); - diff --git a/packages/core/test/utils/is.test.ts b/packages/core/test/utils/is.test.ts index b730b3b5..20bd9149 100644 --- a/packages/core/test/utils/is.test.ts +++ b/packages/core/test/utils/is.test.ts @@ -1,15 +1,34 @@ -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; import { - isArray, isBoolean, isBuffer, isConstructor, isDef, - isError, isFalse, isFalsy, isFunction, isNode, isNull, - isNumber, isObject, isPlainObject, isPrimitive, - isPromise, isRegExp, isString, isSymbol, isTrue, - isTruthy, isURL, isUint8Array, isUndef, + isArray, + isBoolean, + isBuffer, + isConstructor, + isDef, + isError, + isFalse, + isFalsy, + isFunction, + isNode, + isNull, + isNumber, + isObject, + isPlainObject, + isPrimitive, + isPromise, + isRegExp, + isString, + isSymbol, + isTrue, + isTruthy, + isURL, + isUint8Array, + isUndef, isUndefined, toRawType } from "../../src/utils/is"; -test("is-type", () => { +it("is-type", () => { expect(isNumber(1)).toBe(true); expect(isNumber("1")).toBe(false); expect(isString("1")).toBe(true); @@ -90,7 +109,7 @@ test("is-type", () => { expect(isNode()).toBe(true); }); -test("toRawType", () => { +it("toRawType", () => { expect(toRawType(1)).toBe("Number"); expect(toRawType("1")).toBe("String"); expect(toRawType(true)).toBe("Boolean"); diff --git a/packages/core/test/utils/object.test.ts b/packages/core/test/utils/object.test.ts index cd7b545e..d4c6b2a4 100644 --- a/packages/core/test/utils/object.test.ts +++ b/packages/core/test/utils/object.test.ts @@ -1,7 +1,7 @@ -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; import { aliasObjectMap, isKeyOf, objectMap } from "../../src/utils/object"; -test("test-utils-object-aliasObjectMap", async () => { +it("test-utils-object-aliasObjectMap", async () => { const obj = { name: "test", age: 12, @@ -34,11 +34,11 @@ test("test-utils-object-aliasObjectMap", async () => { expect(alias.inherit).toBe(obj.inherit); }); -test("test-utils-object-isKeyOf", () => { +it("test-utils-object-isKeyOf", () => { expect(isKeyOf({ name: "test" }, "name")).toBe(true); }); -test("test-utils-object-objectMap", () => { +it("test-utils-object-objectMap", () => { expect(objectMap({ name: "test", age: 12 }, (key, value) => { if (key === "name") { return ["name2", value]; diff --git a/packages/core/test/utils/path.test.ts b/packages/core/test/utils/path.test.ts index 5b603f95..7b752268 100644 --- a/packages/core/test/utils/path.test.ts +++ b/packages/core/test/utils/path.test.ts @@ -1,11 +1,10 @@ -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; import { withBase, withoutBase } from "../../src/utils/path"; - -test("test-relativePath", () => { +it("test-relativePath", () => { const path = "/abc/def/ghi"; const path2 = "/abc/def/ghi/"; const path3 = "/abc/"; @@ -21,11 +20,10 @@ test("test-relativePath", () => { expect(withoutBase(path, normalBase)).toBe("/abc/def/ghi"); }); -test("test-resolvePath", () => { +it("test-resolvePath", () => { const base = "https://test.com"; const path = "/api"; expect(withBase(path, base)).toBe("https://test.com/api"); expect(withBase("/swagger-ui.css", "/swagger-ui/")).toBe("/swagger-ui/swagger-ui.css"); }); - diff --git a/packages/core/test/utils/promise.test.ts b/packages/core/test/utils/promise.test.ts index 01577672..0b30b64d 100644 --- a/packages/core/test/utils/promise.test.ts +++ b/packages/core/test/utils/promise.test.ts @@ -1,9 +1,9 @@ -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; import type { DelayMsType } from "../../src/utils/promise"; import { createSingletonPromise, delay, memoize } from "../../src/utils/promise"; import { randomInt } from "../../src/utils/random"; -test("test-utils-promise-delay", async () => { +it("test-utils-promise-delay", async () => { const start = performance.now(); await delay("200-300"); const end = performance.now(); @@ -12,7 +12,7 @@ test("test-utils-promise-delay", async () => { expect(time).toBeLessThanOrEqual(300); }); -test("test-utils-promise-createSingletonPromise", async () => { +it("test-utils-promise-createSingletonPromise", async () => { const createInstance = () => randomInt("374-9197"); const fn = createSingletonPromise(createInstance); @@ -29,7 +29,7 @@ test("test-utils-promise-createSingletonPromise", async () => { fn.reset(); const [r0, r1] = await Promise.all( - [delayFn(300), delayFn("200-700")].map((r) => r()) + [delayFn(300), delayFn("200-700")].map(r => r()) ); expect(r0).not.toBe(r); @@ -39,7 +39,7 @@ test("test-utils-promise-createSingletonPromise", async () => { expect(r2).toBe(r0); }); -test("memoize", async () => { +it("memoize", async () => { const fn = async (a: number, b: number) => performance.now() + a + b; const memoized = memoize(fn); const r = await memoized(1, 2); @@ -51,4 +51,3 @@ test("memoize", async () => { const r4 = await memoized(1, 2); expect(r4).not.toBe(r); }); - diff --git a/packages/core/test/utils/random.test.ts b/packages/core/test/utils/random.test.ts index cdd3baac..37cc6285 100644 --- a/packages/core/test/utils/random.test.ts +++ b/packages/core/test/utils/random.test.ts @@ -1,7 +1,7 @@ -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; import { randomArray, randomBoolean, randomDate, randomInt, randomItem, randomUnique } from "../../src/utils/random"; -test("random-array", () => { +it("random-array", () => { const array = randomArray( (index) => { return { @@ -17,7 +17,7 @@ test("random-array", () => { expect(array).include(item); }); -test("random-int", () => { +it("random-int", () => { // by string template const num = randomInt("200-500"); expect(num).toBeGreaterThanOrEqual(200); @@ -29,12 +29,12 @@ test("random-int", () => { expect(num2).toBeLessThanOrEqual(500); }); -test("random-date", () => { +it("random-date", () => { const date = randomDate("2020-01-01", "2022-01-01"); expect(date.getTime()).toBeGreaterThanOrEqual(new Date("2020-01-01").getTime()); }); -test("random-unique", () => { +it("random-unique", () => { const random = randomUnique([1, 2, 2, 3, 3, 3]); const r1 = random(); const r2 = random(); @@ -44,7 +44,7 @@ test("random-unique", () => { expect(r1).not.toBe(r3); }); -test("random-boolean", () => { +it("random-boolean", () => { const bool = randomBoolean(); expect(bool).toBeTypeOf("boolean"); }); diff --git a/packages/core/test/utils/string.test.ts b/packages/core/test/utils/string.test.ts index 0b5d7a6d..c54bcae1 100644 --- a/packages/core/test/utils/string.test.ts +++ b/packages/core/test/utils/string.test.ts @@ -1,19 +1,19 @@ -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; import { escapeStringRegexp, normalizeRoute, parseJson, stringifyJson, transformTemplate } from "../../src/utils/string"; -test("test-utils-normalizeRoute", () => { +it("test-utils-normalizeRoute", () => { expect(normalizeRoute("/api/hello", "get")).toBe("[GET] /api/hello"); }); -test("test-utils-string-template", () => { +it("test-utils-string-template", () => { expect(transformTemplate("hello, <% name %><%empty%>, age is <% age %>", { name: "world", age: 13 })).toBe("hello, world, age is 13"); }); -test("test-utils-string-escapeStringRegexp", () => { +it("test-utils-string-escapeStringRegexp", () => { expect(escapeStringRegexp("How much $ for a 🦄?")).toBe("How much \\$ for a 🦄\\?"); }); -test("test-utils-string-json", () => { +it("test-utils-string-json", () => { const original = { name: "test", age: 12, diff --git a/packages/integrations/nuxt/README.md b/packages/integrations/nuxt/README.md index dc60dfc3..1944cfb6 100644 --- a/packages/integrations/nuxt/README.md +++ b/packages/integrations/nuxt/README.md @@ -12,5 +12,4 @@ export default defineNuxtConfig({ base: "/api" } }); - -``` \ No newline at end of file +``` diff --git a/packages/integrations/nuxt/package.json b/packages/integrations/nuxt/package.json index 03393a2c..bab56702 100644 --- a/packages/integrations/nuxt/package.json +++ b/packages/integrations/nuxt/package.json @@ -15,8 +15,8 @@ "exports": { ".": { "types": "./dist/module.d.ts", - "require": "./dist/module.cjs", - "import": "./dist/module.mjs" + "import": "./dist/module.mjs", + "require": "./dist/module.cjs" } }, "main": "./dist/module.cjs", @@ -32,14 +32,14 @@ "dependencies": { "@fourze/server": "workspace:*", "@fourze/vite": "workspace:*", - "@nuxt/kit": "^3.9.3", + "@nuxt/kit": "^3.10.0", "dedent": "^1.5.1", "pathe": "^1.1.2" }, "devDependencies": { "@nuxt/module-builder": "^0.5.5", - "@nuxt/schema": "^3.9.3", + "@nuxt/schema": "^3.10.0", "@types/dedent": "^0.7.2", - "nuxt": "^3.9.3" + "nuxt": "^3.10.0" } } diff --git a/packages/integrations/swagger-middleware/package.json b/packages/integrations/swagger-middleware/package.json index 4fe3a56d..a4dfed38 100644 --- a/packages/integrations/swagger-middleware/package.json +++ b/packages/integrations/swagger-middleware/package.json @@ -19,8 +19,8 @@ "exports": { ".": { "types": "./dist/index.d.ts", - "require": "./dist/index.cjs", - "import": "./dist/index.mjs" + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" } }, "main": "dist/index.cjs", diff --git a/packages/integrations/swagger-middleware/src/index.ts b/packages/integrations/swagger-middleware/src/index.ts index 166c5197..45047f17 100644 --- a/packages/integrations/swagger-middleware/src/index.ts +++ b/packages/integrations/swagger-middleware/src/index.ts @@ -43,8 +43,8 @@ export function createSwaggerMiddleware( return async (req, res) => { await app.ready(); const routers = createQuery(app.middlewares) - .where((r) => isRouter(r) && r.meta.swagger !== false) - .select((r) => r as FourzeRouter); + .where(r => isRouter(r) && r.meta.swagger !== false) + .select(r => r as FourzeRouter); const tags = routers.select((e) => { return { @@ -56,7 +56,7 @@ export function createSwaggerMiddleware( const routes = routers .select((router) => { return router.routes - .filter((r) => r.meta.swagger !== false) + .filter(r => r.meta.swagger !== false) .map((r) => { const tags = Array.isArray(r.meta.tags) ? r.meta.tags : []; return { @@ -70,7 +70,6 @@ export function createSwaggerMiddleware( }) .flat(); - function getDefinitions(baseDefinitions?: Record) { const definitionsMap = new Map>( Object.entries(baseDefinitions ?? {}) @@ -99,7 +98,7 @@ export function createSwaggerMiddleware( string, Record | SwaggerPathSchema >(); - const groups = routes.groupBy((e) => e.path); + const groups = routes.groupBy(e => e.path); for (const [path, routes] of groups) { const map = new Map(); for (const route of routes) { diff --git a/packages/integrations/swagger-middleware/src/types.ts b/packages/integrations/swagger-middleware/src/types.ts index 01e6107d..017ce8dc 100644 --- a/packages/integrations/swagger-middleware/src/types.ts +++ b/packages/integrations/swagger-middleware/src/types.ts @@ -1,33 +1,31 @@ import type { RequestMethod } from "@fourze/core"; import type { OpenAPIV2 } from "openapi-types"; - export interface SwaggerPathSchema { - swagger?: boolean - tags?: string[] - responses?: OpenAPIV2.ResponsesObject - description?: string - summary?: string - operationId?: string - produces?: string[] - consumes?: string[] - deprecated?: boolean + swagger?: boolean; + tags?: string[]; + responses?: OpenAPIV2.ResponsesObject; + description?: string; + summary?: string; + operationId?: string; + produces?: string[]; + consumes?: string[]; + deprecated?: boolean; } - export interface SwaggerUIInitOptions { - url?: string - urls?: string[] + url?: string; + urls?: string[]; } export interface SwaggerOptions { - defaultMethod?: RequestMethod - info?: OpenAPIV2.InfoObject - schemas?: string[] - consumes?: string[] - produces?: string[] - host?: string - basePath?: string + defaultMethod?: RequestMethod; + info?: OpenAPIV2.InfoObject; + schemas?: string[]; + consumes?: string[]; + produces?: string[]; + host?: string; + basePath?: string; } declare module "@fourze/core" { @@ -35,12 +33,12 @@ declare module "@fourze/core" { } interface FourzeAppMeta { - definitions?: OpenAPIV2.DefinitionsObject - info?: OpenAPIV2.InfoObject - host?: string - basePath?: string - schemas?: string[] - consumes?: string[] - produces?: string[] + definitions?: OpenAPIV2.DefinitionsObject; + info?: OpenAPIV2.InfoObject; + host?: string; + basePath?: string; + schemas?: string[]; + consumes?: string[]; + produces?: string[]; } } diff --git a/packages/integrations/swagger/package.json b/packages/integrations/swagger/package.json index 9eb98feb..0f1b29d0 100644 --- a/packages/integrations/swagger/package.json +++ b/packages/integrations/swagger/package.json @@ -22,8 +22,8 @@ "exports": { ".": { "types": "./dist/index.d.ts", - "require": "./dist/index.cjs", - "import": "./dist/index.mjs" + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" } }, "main": "dist/index.cjs", @@ -50,7 +50,7 @@ "@fourze/server": "workspace:*", "@fourze/swagger-middleware": "workspace:*", "fs-extra": "^11.2.0", - "swagger-ui-dist": "^5.11.1" + "swagger-ui-dist": "^5.11.2" }, "devDependencies": { "@types/swagger-ui-dist": "^3.30.4" diff --git a/packages/integrations/swagger/src/build.ts b/packages/integrations/swagger/src/build.ts index 72afe7be..f5ffff19 100644 --- a/packages/integrations/swagger/src/build.ts +++ b/packages/integrations/swagger/src/build.ts @@ -1,4 +1,5 @@ import path from "node:path"; +import process from "node:process"; import type { FourzeHmrApp } from "@fourze/server"; import type { InlineConfig } from "vite"; @@ -23,18 +24,18 @@ export interface SwaggerUIBuildOptions { /** * @default "dist" */ - distPath?: string + distPath?: string; - assetsFilter?: (src: string) => boolean + assetsFilter?: (src: string) => boolean; - vite?: InlineConfig + vite?: InlineConfig; - swagger?: SwaggerOptions + swagger?: SwaggerOptions; /** * @default ".fourze-swagger" */ - tmpDir?: string + tmpDir?: string; } @@ -50,7 +51,7 @@ function createMockDocsCode(options: SwaggerOptions = {}) { } export function getModuleAlias() { - return ["@fourze/core", "@fourze/mock", "@fourze/swagger", "@fourze/swagger-middleware"].map(r => { + return ["@fourze/core", "@fourze/mock", "@fourze/swagger", "@fourze/swagger-middleware"].map((r) => { return { find: r, replacement: require.resolve(r) diff --git a/packages/integrations/swagger/src/index.ts b/packages/integrations/swagger/src/index.ts index 4b6b829b..014dbf13 100644 --- a/packages/integrations/swagger/src/index.ts +++ b/packages/integrations/swagger/src/index.ts @@ -3,4 +3,3 @@ export { createSwaggerMiddleware } from "@fourze/swagger-middleware"; export * from "./service"; export * from "./build"; - diff --git a/packages/integrations/swagger/src/service.ts b/packages/integrations/swagger/src/service.ts index feea8f34..131c4da3 100644 --- a/packages/integrations/swagger/src/service.ts +++ b/packages/integrations/swagger/src/service.ts @@ -7,8 +7,8 @@ import { staticFile } from "@fourze/server"; import { renderIndexHtml } from "./ui"; export interface SwaggerUIServiceOptions extends SwaggerOptions { - uiBase?: string - documentPath?: string + uiBase?: string; + documentPath?: string; } // 包括swagger-ui的服务 diff --git a/packages/integrations/swagger/src/ui.ts b/packages/integrations/swagger/src/ui.ts index f4401008..09d65f43 100644 --- a/packages/integrations/swagger/src/ui.ts +++ b/packages/integrations/swagger/src/ui.ts @@ -79,7 +79,7 @@ function stringifyOptions(obj: Record): string { } export interface RenderSwaggerUIOptions extends RenderHtmlOptions { - url?: string + url?: string; } export function renderIndexHtml(root: string, options: RenderSwaggerUIOptions = {}) { diff --git a/packages/integrations/swagger/test/swagger.test.ts b/packages/integrations/swagger/test/swagger.test.ts index e7a7dc13..74b237d5 100644 --- a/packages/integrations/swagger/test/swagger.test.ts +++ b/packages/integrations/swagger/test/swagger.test.ts @@ -3,10 +3,10 @@ import { connect, normalizeAddress } from "@fourze/server"; import express from "express"; import { createApp, defineRouter, randomInt, withBase } from "@fourze/core"; import { service } from "@fourze/swagger"; -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; import axios from "axios"; -test("test-swagger", async () => { +it("test-swagger", async () => { const app = createApp({ base: "/api", allow: ["/api/test", "/api/hello", "/api/add"], @@ -36,7 +36,7 @@ test("test-swagger", async () => { expressApp.use(connect(swaggerRouter)); - const server: Server = await new Promise(resolve => { + const server: Server = await new Promise((resolve) => { const _server = expressApp.listen(0, "localhost", () => { resolve(_server); }); diff --git a/packages/integrations/unplugin/package.json b/packages/integrations/unplugin/package.json index e2904172..c6fd6807 100644 --- a/packages/integrations/unplugin/package.json +++ b/packages/integrations/unplugin/package.json @@ -19,8 +19,8 @@ "exports": { ".": { "types": "./dist/index.d.ts", - "require": "./dist/index.cjs", - "import": "./dist/index.mjs" + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" } }, "main": "dist/index.cjs", diff --git a/packages/integrations/unplugin/src/index.ts b/packages/integrations/unplugin/src/index.ts index 2a53fe3f..eb077f43 100644 --- a/packages/integrations/unplugin/src/index.ts +++ b/packages/integrations/unplugin/src/index.ts @@ -40,84 +40,84 @@ export interface SwaggerPluginOption { /** * @default vite.base + "/swagger-ui/" */ - base?: string + base?: string; - generateDocument?: boolean + generateDocument?: boolean; - defaultMethod?: RequestMethod + defaultMethod?: RequestMethod; } export type MockEnable = boolean | "auto"; export interface MockOptions { - enable?: MockEnable - mode?: FourzeMockAppOptions["mode"] - injectScript?: boolean - host?: string | string[] + enable?: MockEnable; + mode?: FourzeMockAppOptions["mode"]; + injectScript?: boolean; + host?: string | string[]; } export interface UnpluginFourzeOptions { /** * @default 'src/mock' */ - dir?: string + dir?: string; /** * @default '/api' */ - base?: string + base?: string; /** * @default env.command == 'build' || env.mode === 'mock' */ - mock?: MockOptions | boolean + mock?: MockOptions | boolean; /** * @default true * */ - hmr?: boolean + hmr?: boolean; /** * @default "info" */ - logLevel?: FourzeLogLevelKey | number + logLevel?: FourzeLogLevelKey | number; server?: { /** * */ - host?: string + host?: string; /** * */ - port?: number - } + port?: number; + }; files?: - | { + | { /** - * @default ["*.ts","*.js"] - */ - include?: string[] - exclude?: string[] - } - | string[] + * @default ["*.ts","*.js"] + */ + include?: string[]; + exclude?: string[]; + } + | string[]; - delay?: DelayMsType + delay?: DelayMsType; /** * @default 5000 */ - timeout?: number + timeout?: number; - allow?: string[] + allow?: string[]; - deny?: string[] + deny?: string[]; - swagger?: SwaggerPluginOption | boolean + swagger?: SwaggerPluginOption | boolean; - transformCode?: typeof createMockClient + transformCode?: typeof createMockClient; } const createFourzePlugin = createUnplugin( diff --git a/packages/integrations/vite/README.md b/packages/integrations/vite/README.md index bdc45843..3aabb458 100644 --- a/packages/integrations/vite/README.md +++ b/packages/integrations/vite/README.md @@ -15,7 +15,6 @@ export default defineConfig({ }) ], }); - ``` -then you can fetch `/api/hello` to get response. \ No newline at end of file +then you can fetch `/api/hello` to get response. diff --git a/packages/integrations/vite/package.json b/packages/integrations/vite/package.json index ff2aba84..507fb361 100644 --- a/packages/integrations/vite/package.json +++ b/packages/integrations/vite/package.json @@ -19,8 +19,8 @@ "exports": { ".": { "types": "./dist/index.d.ts", - "require": "./dist/index.cjs", - "import": "./dist/index.mjs" + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" } }, "main": "dist/index.cjs", diff --git a/packages/integrations/vite/src/index.ts b/packages/integrations/vite/src/index.ts index 34507006..e512bac2 100644 --- a/packages/integrations/vite/src/index.ts +++ b/packages/integrations/vite/src/index.ts @@ -3,4 +3,3 @@ import { UnpluginFourzeOptions, createFourzePlugin } from "@fourze/unplugin"; const createFourzeVitePlugin = createFourzePlugin.vite; export { UnpluginFourzeOptions, createFourzeVitePlugin, createFourzeVitePlugin as default }; - diff --git a/packages/integrations/webpack/package.json b/packages/integrations/webpack/package.json index a2ce9c68..5288100c 100644 --- a/packages/integrations/webpack/package.json +++ b/packages/integrations/webpack/package.json @@ -19,8 +19,8 @@ "exports": { ".": { "types": "./dist/index.d.ts", - "require": "./dist/index.cjs", - "import": "./dist/index.mjs" + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" } }, "main": "dist/index.cjs", diff --git a/packages/middlewares/REAMDE.md b/packages/middlewares/REAMDE.md index b106c06a..4a35b973 100644 --- a/packages/middlewares/REAMDE.md +++ b/packages/middlewares/REAMDE.md @@ -11,11 +11,10 @@ const app = createApp({ }); app.use(createDelayMiddleware("100-300")); - ``` ## Resolve - + ```ts import { createApp, defineRouter } from "@fourze/core"; import { createResolveMiddleware } from "@fourze/middlewares"; @@ -35,7 +34,7 @@ app.use(createDelayMiddleware("100-300")); } })); - app.use(defineRouter(router => { + app.use(defineRouter((router) => { router.get("/hello", (_, res) => { res.send({ hello: "world" @@ -45,8 +44,7 @@ app.use(createDelayMiddleware("100-300")); const server = createServer(app); server.listen(7609); - - ``` +``` ` GET http://localhost:7609/api/hello ` ``` { @@ -57,7 +55,7 @@ app.use(createDelayMiddleware("100-300")); } } ``` - + ## HEADER ```ts @@ -74,4 +72,4 @@ app.use(createHeaderMiddleware({ "Access-Control-Allow-Methods": "PUT, POST, GET, DELETE, OPTIONS", "Access-Control-Allow-Credentials": "true" })); -``` \ No newline at end of file +``` diff --git a/packages/middlewares/package.json b/packages/middlewares/package.json index 67c7a032..d4582063 100644 --- a/packages/middlewares/package.json +++ b/packages/middlewares/package.json @@ -19,8 +19,8 @@ "exports": { ".": { "types": "./dist/index.d.ts", - "require": "./dist/index.cjs", - "import": "./dist/index.mjs" + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" } }, "main": "dist/index.cjs", diff --git a/packages/middlewares/src/middlewares/delay.ts b/packages/middlewares/src/middlewares/delay.ts index 89d058ef..3b6ef5ec 100644 --- a/packages/middlewares/src/middlewares/delay.ts +++ b/packages/middlewares/src/middlewares/delay.ts @@ -25,4 +25,3 @@ export function createDelayMiddleware(ms: DelayMsType): FourzeMiddleware { } }); } - diff --git a/packages/middlewares/src/middlewares/filter.ts b/packages/middlewares/src/middlewares/filter.ts index 10bbf4cc..01757479 100644 --- a/packages/middlewares/src/middlewares/filter.ts +++ b/packages/middlewares/src/middlewares/filter.ts @@ -3,8 +3,8 @@ import type { FourzeMiddleware } from "@fourze/core"; import { createFilter, defineMiddleware } from "@fourze/core"; interface MatchMiddlewareOptions { - includes?: MaybeRegex[] - excludes?: MaybeRegex[] + includes?: MaybeRegex[]; + excludes?: MaybeRegex[]; } export function createFilterMiddleware( middleware: FourzeMiddleware, diff --git a/packages/middlewares/src/middlewares/resolve.ts b/packages/middlewares/src/middlewares/resolve.ts index b1ff313f..e954dd0e 100644 --- a/packages/middlewares/src/middlewares/resolve.ts +++ b/packages/middlewares/src/middlewares/resolve.ts @@ -9,8 +9,8 @@ type RejectFunction = (error: any) => MaybePromise; export const RESOLVE_HEADER = "Fourze-Response-Resolve"; export interface ResolveHookOptions { - resolve: ResolveFunction - reject?: RejectFunction + resolve: ResolveFunction; + reject?: RejectFunction; } export function createResolveMiddleware(options: ResolveHookOptions): FourzeMiddleware; @@ -71,4 +71,3 @@ export function createResolveMiddleware( await next(); }); } - diff --git a/packages/mock/REAMDE.md b/packages/mock/REAMDE.md index b8683630..949dfe93 100644 --- a/packages/mock/REAMDE.md +++ b/packages/mock/REAMDE.md @@ -20,7 +20,6 @@ app.use( }); }) ); - ``` ` GET http://localhost:7609/api/hello ` @@ -29,4 +28,4 @@ app.use( { "hello": "world" } -``` \ No newline at end of file +``` diff --git a/packages/mock/package.json b/packages/mock/package.json index 0ca3b6e0..2d3a8c7c 100644 --- a/packages/mock/package.json +++ b/packages/mock/package.json @@ -14,8 +14,8 @@ "exports": { ".": { "types": "./dist/index.d.ts", - "require": "./dist/index.cjs", - "import": "./dist/index.mjs" + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" } }, "main": "dist/index.cjs", diff --git a/packages/mock/src/app.ts b/packages/mock/src/app.ts index 514b138f..a56da2ec 100644 --- a/packages/mock/src/app.ts +++ b/packages/mock/src/app.ts @@ -135,7 +135,7 @@ export function createMockApp( app.enable = (_mode?: FourzeMockRequestMode[]) => { _mode = _mode ?? Array.from(mode); - _mode.forEach((m) => activeMode.add(m)); + _mode.forEach(m => activeMode.add(m)); if (injectGlobal) { if (_mode.includes("xhr")) { @@ -157,7 +157,7 @@ export function createMockApp( app.disable = function (_mode?: FourzeMockRequestMode[]) { _mode = _mode ?? Array.from(mode); - _mode.forEach((m) => activeMode.delete(m)); + _mode.forEach(m => activeMode.delete(m)); if (injectGlobal) { if (_mode.includes("xhr")) { globalThis.XMLHttpRequest = app.originalXMLHttpRequest; @@ -215,4 +215,3 @@ export function getGlobalMockApp() { export function isMockApp(app: any): app is FourzeMockApp { return !!app && app[FourzeMockAppFlag]; } - diff --git a/packages/mock/src/code.ts b/packages/mock/src/code.ts index 8cb254c0..02ce2989 100644 --- a/packages/mock/src/code.ts +++ b/packages/mock/src/code.ts @@ -41,4 +41,3 @@ export const HTTP_STATUS_CODES = { 504: "Gateway Timeout", 505: "HTTP Version Not Supported" }; - diff --git a/packages/mock/src/request.ts b/packages/mock/src/request.ts index 92c6348f..6aada2af 100644 --- a/packages/mock/src/request.ts +++ b/packages/mock/src/request.ts @@ -25,10 +25,10 @@ type RequestCallback = (res: IncomingMessage) => void; type WriteCallback = (error?: Error | null) => void; interface ProxyRequestOptions extends ClientRequestArgs { - nativeProtocols?: Record - nativeRequest?: typeof http.request | typeof https.request - agents?: Record - logger?: FourzeLogger + nativeProtocols?: Record; + nativeRequest?: typeof http.request | typeof https.request; + agents?: Record; + logger?: FourzeLogger; } function optionsToURL(options: RequestOptions): URL { diff --git a/packages/mock/src/shared.ts b/packages/mock/src/shared.ts index 8732caec..c3c9363e 100644 --- a/packages/mock/src/shared.ts +++ b/packages/mock/src/shared.ts @@ -5,49 +5,48 @@ import type { DelayMsType, FourzeApp, FourzeAppOptions } from "@fourze/core"; export type FourzeMockRequestMode = "xhr" | "fetch" | "request"; export interface FourzeMockAppOptions extends Exclude { - base?: string + base?: string; /** * @default ["xhr","fetch"] */ - mode?: FourzeMockRequestMode[] + mode?: FourzeMockRequestMode[]; - host?: string | string[] + host?: string | string[]; - protocol?: "http" | "https" + protocol?: "http" | "https"; - autoEnable?: boolean + autoEnable?: boolean; - global?: boolean + global?: boolean; - delay?: DelayMsType + delay?: DelayMsType; - timeout?: number + timeout?: number; } export const FourzeMockAppFlag = "__isFourzeMockApp"; export interface FourzeMockApp extends FourzeApp { - originalFetch: typeof fetch - originalXMLHttpRequest: typeof XMLHttpRequest - originalHttpRequest: typeof http.request - originalHttpsRequest: typeof https.request + originalFetch: typeof fetch; + originalXMLHttpRequest: typeof XMLHttpRequest; + originalHttpRequest: typeof http.request; + originalHttpsRequest: typeof https.request; - XMLHttpRequest: typeof XMLHttpRequest - fetch: typeof fetch - request: typeof http.request + XMLHttpRequest: typeof XMLHttpRequest; + fetch: typeof fetch; + request: typeof http.request; - enabled: boolean + enabled: boolean; - enable(): this + enable(): this; - enable(modes: FourzeMockRequestMode[]): this + enable(modes: FourzeMockRequestMode[]): this; - disable(): this + disable(): this; - disable(modes: FourzeMockRequestMode[]): this + disable(modes: FourzeMockRequestMode[]): this; - activeModes: FourzeMockRequestMode[] + activeModes: FourzeMockRequestMode[]; - [FourzeMockAppFlag]: true + [FourzeMockAppFlag]: true; } - diff --git a/packages/mock/src/types.d.ts b/packages/mock/src/types.d.ts index e331198c..72e4d289 100644 --- a/packages/mock/src/types.d.ts +++ b/packages/mock/src/types.d.ts @@ -1,4 +1,6 @@ -import { FourzeMockApp } from "./shared"; +/* eslint-disable no-var */ +/* eslint-disable vars-on-top */ +import type { FourzeMockApp } from "./shared"; declare global { var __FOURZE_MOCK_APP__: FourzeMockApp; @@ -6,4 +8,4 @@ declare global { var __FOURZE_VERSION__: string; } -export {} +export {}; diff --git a/packages/mock/test/fetch.test.ts b/packages/mock/test/fetch.test.ts index 569e5470..d560be33 100644 --- a/packages/mock/test/fetch.test.ts +++ b/packages/mock/test/fetch.test.ts @@ -1,14 +1,14 @@ import { defineRouter, randomInt, setLoggerLevel } from "@fourze/core"; import { createMockApp } from "@fourze/mock"; -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; -test("mock-base", async () => { +it("mock-base", async () => { const app = createMockApp({ delay: "200-500", mode: ["fetch"], base: "/api" }); - app.use(defineRouter(router => { + app.use(defineRouter((router) => { router.route("/hello", () => { return { name: "test" @@ -22,7 +22,7 @@ test("mock-base", async () => { }); }); -test("mock-fetch", async () => { +it("mock-fetch", async () => { const testData = { name: "test", count: randomInt(200) @@ -39,7 +39,7 @@ test("mock-fetch", async () => { await next?.(); }); - const router = defineRouter(router => { + const router = defineRouter((router) => { router.route("/hello", () => { return { ...testData diff --git a/packages/mock/test/hooks.test.ts b/packages/mock/test/hooks.test.ts index 19270f3f..71b25881 100644 --- a/packages/mock/test/hooks.test.ts +++ b/packages/mock/test/hooks.test.ts @@ -1,9 +1,9 @@ import { defineRouter } from "@fourze/core"; import { createMockApp } from "@fourze/mock"; -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; import nodeFetch from "node-fetch"; -test("test-hooks", async () => { +it("test-hooks", async () => { globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch; const data = { @@ -39,8 +39,8 @@ test("test-hooks", async () => { } await next?.(); }) - .use("/api", defineRouter(router => { - router.route("GET /test", req => { + .use("/api", defineRouter((router) => { + router.route("GET /test", (req) => { return { token: req.meta.token }; diff --git a/packages/server/README.md b/packages/server/README.md index 31c995ff..6acb3dfe 100644 --- a/packages/server/README.md +++ b/packages/server/README.md @@ -1,6 +1,5 @@ # Fourze Server - ## Usage ``` diff --git a/packages/server/package.json b/packages/server/package.json index 98a63520..ef00863c 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -14,8 +14,8 @@ "exports": { ".": { "types": "./dist/index.d.ts", - "require": "./dist/index.cjs", - "import": "./dist/index.mjs" + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" } }, "main": "dist/index.cjs", diff --git a/packages/server/src/hmr.ts b/packages/server/src/hmr.ts index 595d948a..f48b7f7f 100644 --- a/packages/server/src/hmr.ts +++ b/packages/server/src/hmr.ts @@ -1,3 +1,4 @@ +import process from "node:process"; import { basename, extname, join, normalize, resolve } from "pathe"; import fs from "fs-extra"; import glob from "fast-glob"; @@ -23,34 +24,34 @@ import { createImporter } from "./importer"; export interface FourzeHmrOptions extends Exclude { - dir?: string + dir?: string; files?: { - include?: string[] - exclude?: string[] - } | string[] + include?: string[]; + exclude?: string[]; + } | string[]; } export interface FourzeHmrBuildConfig { - define?: Record - alias?: Record + define?: Record; + alias?: Record; } export interface FourzeHmrApp extends FourzeApp { - watch(): this - watch(dir: string): this - watch(watcher: FSWatcher): this - watch(dir: string, watcher: FSWatcher): this - proxy(p: string | FourzeProxyOption): this - configure(config: FourzeHmrBuildConfig): this - delay?: DelayMsType - readonly base: string - readonly moduleNames: string[] + watch(): this; + watch(dir: string): this; + watch(watcher: FSWatcher): this; + watch(dir: string, watcher: FSWatcher): this; + proxy(p: string | FourzeProxyOption): this; + configure(config: FourzeHmrBuildConfig): this; + delay?: DelayMsType; + readonly base: string; + readonly moduleNames: string[]; } export interface FourzeProxyOption extends Omit { - target?: string + target?: string; } export function createHmrApp(options: FourzeHmrOptions = {}): FourzeHmrApp { @@ -102,8 +103,8 @@ export function createHmrApp(options: FourzeHmrOptions = {}): FourzeHmrApp { const stat = await fs.promises.stat(moduleName); if (stat.isDirectory()) { const files = await glob(fsInclude, { cwd: moduleName, onlyFiles: false, markDirectories: true }); - const tasks = files.map((name) => load(join(moduleName, name))); - return await Promise.all(tasks).then((r) => r.some((f) => f)); + const tasks = files.map(name => load(join(moduleName, name))); + return await Promise.all(tasks).then(r => r.some(f => f)); } else if (stat.isFile()) { if (!micromatch.some(moduleName, fsInclude, { dot: true, diff --git a/packages/server/src/importer.ts b/packages/server/src/importer.ts index 584cedd6..e9a53d95 100644 --- a/packages/server/src/importer.ts +++ b/packages/server/src/importer.ts @@ -14,12 +14,12 @@ import type { Loader, TransformOptions } from "esbuild"; import { transformSync } from "esbuild"; export interface ModuleImporterOptions { - esbuild?: TransformOptions - define?: Record - interopDefault?: boolean - requireCache?: boolean - extensions?: string[] - alias?: Record | null + esbuild?: TransformOptions; + define?: Record; + interopDefault?: boolean; + requireCache?: boolean; + extensions?: string[]; + alias?: Record | null; } type Require = typeof require; @@ -40,10 +40,10 @@ const defaults: ModuleImporterOptions = { }; export interface ModuleImporter extends Require { - (id: string): any - remove(id: string): void - clear(): void - configure(options: ModuleImporterOptions): void + (id: string): any; + remove(id: string): void; + clear(): void; + configure(options: ModuleImporterOptions): void; } export function readNearestPackageJSON(path: string): PackageJson | undefined { @@ -101,7 +101,7 @@ export function createImporter(_filename: string, opts: ModuleImporterOptions = const isNativeRe = new RegExp( `node_modules/(${nativeModules - .map((m) => escapeStringRegexp(m)) + .map(m => escapeStringRegexp(m)) .join("|")})/` ); @@ -111,7 +111,7 @@ export function createImporter(_filename: string, opts: ModuleImporterOptions = } const _additionalExts = [...(opts.extensions as string[])].filter( - (ext) => ext !== ".js" + ext => ext !== ".js" ); let resolved, err; @@ -270,7 +270,7 @@ export function createImporter(_filename: string, opts: ModuleImporterOptions = mod.path = dirname(filename); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // eslint-disable-next-line ts/ban-ts-comment // @ts-expect-error mod.paths = Module._nodeModulePaths(mod.path); diff --git a/packages/server/src/renderer.ts b/packages/server/src/renderer.ts index d67916ac..5e840b89 100644 --- a/packages/server/src/renderer.ts +++ b/packages/server/src/renderer.ts @@ -1,5 +1,6 @@ import fs from "node:fs"; import path from "node:path"; +import process from "node:process"; import type { FourzeComponent, FourzeLogger, @@ -24,27 +25,27 @@ export interface FourzeRendererOptions { /** * 根路径 */ - base?: string + base?: string; /** * 目录 */ - dir?: string + dir?: string; /** * 模板 */ - templates?: FourzeRenderTemplate[] + templates?: FourzeRenderTemplate[]; /** * 文件不存在时跳转到该目录的根路径 */ - fallbacks?: string[] | Record + fallbacks?: string[] | Record; } export interface FourzeRenderer extends FourzeMiddleware { - templates: FourzeRenderTemplate[] - use: (...middlewares: FourzeRenderTemplate[]) => this + templates: FourzeRenderTemplate[]; + use: (...middlewares: FourzeRenderTemplate[]) => this; } export type FourzeRenderTemplate = ( @@ -54,20 +55,20 @@ export type FourzeRenderTemplate = ( ) => any; export interface FourzeRendererContext { - file: string + file: string; /** * @see FourzeRendererOptions["dir"] */ - dir: string + dir: string; - logger: FourzeLogger + logger: FourzeLogger; } export interface FourzeStaticFileOptions { - maybes?: string[] - includes?: string[] - excludes?: string[] + maybes?: string[]; + includes?: string[]; + excludes?: string[]; } function hasFile(file: string) { @@ -115,7 +116,7 @@ export function renderFile( let p: string | undefined = context.file; const extensions = ["html", "htm"]; const maybes = [p].concat( - extensions.map((ext) => path.normalize(`${p}/index.${ext}`)) + extensions.map(ext => path.normalize(`${p}/index.${ext}`)) ); do { p = maybes.shift(); @@ -143,7 +144,7 @@ export async function renderTsx( const maybes = file.match(/\.[jt|]sx$/) ? [file] : []; maybes.push( - ...["index.tsx", "index.jsx"].map((ext) => path.normalize(`${file}/${ext}`)) + ...["index.tsx", "index.jsx"].map(ext => path.normalize(`${file}/${ext}`)) ); for (const maybe of maybes) { @@ -190,7 +191,7 @@ export function createRenderer( const _fallbacks = (isOptions ? options.fallbacks : []) ?? []; const fallbacks = Array.isArray(_fallbacks) - ? _fallbacks.map((f) => [f, f]) + ? _fallbacks.map(f => [f, f]) : Object.entries(_fallbacks); const logger = createLogger("@fourze/renderer"); diff --git a/packages/server/src/server.ts b/packages/server/src/server.ts index 29b7e4b8..93dd83e2 100644 --- a/packages/server/src/server.ts +++ b/packages/server/src/server.ts @@ -2,6 +2,7 @@ import type EventEmitter from "node:events"; import type { IncomingMessage, OutgoingMessage, Server } from "node:http"; import http from "node:http"; import https from "node:https"; +import process from "node:process"; import { FOURZE_VERSION, createApp, @@ -23,31 +24,31 @@ import type { import { isAddressInfo, normalizeAddress } from "./utils"; export interface FourzeServerOptions { - host?: string - port?: number - server?: Server - protocol?: "http" | "https" - logger?: FourzeLogger + host?: string; + port?: number; + server?: Server; + protocol?: "http" | "https"; + logger?: FourzeLogger; } export interface FourzeServer extends EventEmitter, CommonMiddleware { - host: string - port: number + host: string; + port: number; - readonly origin: string + readonly origin: string; - readonly server?: Server + readonly server?: Server; - readonly protocol: "http" | "https" + readonly protocol: "http" | "https"; - listen(port?: number, host?: string): Promise + listen(port?: number, host?: string): Promise; - use(path: string, ...modules: FourzeModule[]): this + use(path: string, ...modules: FourzeModule[]): this; - use(...modules: FourzeModule[]): this + use(...modules: FourzeModule[]): this; - close(): Promise + close(): Promise; } export function createServer(): FourzeServer; diff --git a/packages/server/src/utils.ts b/packages/server/src/utils.ts index b1ffea7a..e49f66d2 100644 --- a/packages/server/src/utils.ts +++ b/packages/server/src/utils.ts @@ -42,9 +42,9 @@ string | undefined export interface Hostname { /** undefined sets the default behaviour of server.listen */ - host: string | undefined + host: string | undefined; /** resolve to localhost when possible */ - name: string + name: string; } export async function resolveHostname( @@ -80,13 +80,13 @@ export function isAddressInfo(value: any): value is AddressInfo { } interface ResolvedServerUrls { - local: string[] - network: string[] + local: string[]; + network: string[]; } export interface ResolveServerOptions { - host?: string - https?: boolean + host?: string; + https?: boolean; } /** * @see https://github.com/vitejs/vite/blob/main/packages/vite/src/node/utils.ts @@ -119,12 +119,12 @@ export async function resolveServerUrls(server: Server, options: ResolveServerOp } else { Object.values(os.networkInterfaces()) .flatMap(nInterface => nInterface ?? []) - .filter(detail => { + .filter((detail) => { return detail && detail.address && ((isString(detail.family) && detail.family === "IPv4") - || (isNumber(detail.family) && detail.family === 4)); - }).forEach(detail => { + || (isNumber(detail.family) && detail.family === 4)); + }).forEach((detail) => { let host = detail.address.replace("127.0.0.1", hostname.name); // ipv6 host if (net.isIPv6(host)) { @@ -146,12 +146,12 @@ export async function resolveServerUrls(server: Server, options: ResolveServerOp } export interface NormalizedAddressOptions { - protocol?: "http" | "https" | false - hostname?: string + protocol?: "http" | "https" | false; + hostname?: string; /** * @default "" */ - base?: string + base?: string; } /** diff --git a/packages/server/test/data.test.ts b/packages/server/test/data.test.ts index 6d34063c..9482531a 100644 --- a/packages/server/test/data.test.ts +++ b/packages/server/test/data.test.ts @@ -1,9 +1,9 @@ import { defineRouter, randomInt, setLoggerLevel } from "@fourze/core"; import { createServer } from "@fourze/server"; import axios from "axios"; -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; -test("mock-data", async () => { +it("mock-data", async () => { const testData = { name: "test", count: randomInt(200) @@ -65,7 +65,7 @@ test("mock-data", async () => { const { name } = await axiosInstance .post("/hello", testData) - .then((r) => r.data); + .then(r => r.data); expect(name).toEqual(testData.name); diff --git a/packages/server/test/server.test.ts b/packages/server/test/server.test.ts index f867f432..a22bc8fe 100644 --- a/packages/server/test/server.test.ts +++ b/packages/server/test/server.test.ts @@ -3,9 +3,9 @@ import { createApp, defineRouter, randomInt, withBase } from "@fourze/core"; import { connect, createServer, normalizeAddress } from "@fourze/server"; import express from "connect"; import axios from "axios"; -import { expect, test } from "vitest"; +import { expect, it } from "vitest"; -test("run-server", async () => { +it("run-server", async () => { const host = "localhost"; const port = 0; @@ -34,12 +34,12 @@ test("run-server", async () => { const returnData = await axios .get(withBase("/api/test", server.origin)) - .then((r) => r.data); + .then(r => r.data); expect(returnData).toEqual(testData); }); -test("run-connect", async () => { +it("run-connect", async () => { const host = "localhost"; const port = 0; @@ -58,7 +58,7 @@ test("run-connect", async () => { app.use("/api/", connect(router)); - const server: Server = await new Promise(resolve => { + const server: Server = await new Promise((resolve) => { const server = app.listen(port, host, () => { resolve(server); }); @@ -73,7 +73,7 @@ test("run-connect", async () => { const returnData = await axios .get(url) - .then((r) => r.data); + .then(r => r.data); expect(returnData).toEqual(testData); }); diff --git a/playgrounds/nuxt-app/app.vue b/playgrounds/nuxt-app/app.vue index 88de12da..7b486a47 100644 --- a/playgrounds/nuxt-app/app.vue +++ b/playgrounds/nuxt-app/app.vue @@ -7,9 +7,9 @@ import type { MaybeAsyncFunction } from "maybe-types"; import { computed, ref } from "vue"; export interface ResponseData { - code: number - data: any - msg: string + code: number; + data: any; + msg: string; } const t = ref(0); @@ -65,7 +65,7 @@ function end() { endTime.value = Date.now(); } -const recoding = (fn: MaybeAsyncFunction) => { +function recoding(fn: MaybeAsyncFunction) { return async () => { start(); try { @@ -75,11 +75,11 @@ const recoding = (fn: MaybeAsyncFunction) => { } end(); }; -}; +} const handleFetch = recoding(async () => { result.value = await fetch(`/api/search/${Math.floor(Math.random() * 9)}`, { method: "post", body: JSON.stringify({ phone: 2 }) }) - .then(r => { + .then((r) => { serverDelay.value = Number(r.headers.get("Fourze-Delay")); return r.json(); }) diff --git a/playgrounds/nuxt-app/global.d.ts b/playgrounds/nuxt-app/global.d.ts index 6b2228d5..01e4b579 100644 --- a/playgrounds/nuxt-app/global.d.ts +++ b/playgrounds/nuxt-app/global.d.ts @@ -1,4 +1,4 @@ -import { MaybeDate } from "maybe-types"; +import type { MaybeDate } from "maybe-types"; declare global { export interface ResponseData { diff --git a/playgrounds/nuxt-app/mock/index.ts b/playgrounds/nuxt-app/mock/index.ts index ab85b384..36fd2491 100644 --- a/playgrounds/nuxt-app/mock/index.ts +++ b/playgrounds/nuxt-app/mock/index.ts @@ -16,12 +16,12 @@ import { } from "../utils/setup-mock"; interface Pagination { - page: number - pageSize: number + page: number; + pageSize: number; } export interface SwaggerMeta extends Record { - summary: string + summary: string; } export default defineRouter((router) => { @@ -94,15 +94,16 @@ export default defineRouter((router) => { const handleSearch: FourzeHandle< PagingData, ObjectProps, - any> = async (req) => { - const { - page = 1, - pageSize = 10, - keyword = "" - } = req.query as unknown as Pagination & { keyword?: string }; - const items = data.filter((item) => item.username.includes(keyword)); - return slicePage(items, { page, pageSize }); - }; + any +> = async (req) => { + const { + page = 1, + pageSize = 10, + keyword = "" + } = req.query as unknown as Pagination & { keyword?: string }; + const items = data.filter(item => item.username.includes(keyword)); + return slicePage(items, { page, pageSize }); +}; router.post("/search/{id}", handleSearch); diff --git a/playgrounds/nuxt-app/utils/setup-mock.ts b/playgrounds/nuxt-app/utils/setup-mock.ts index 98f9609b..74495e21 100644 --- a/playgrounds/nuxt-app/utils/setup-mock.ts +++ b/playgrounds/nuxt-app/utils/setup-mock.ts @@ -1,26 +1,26 @@ export type RequestPath = `${"get" | "post" | "delete"}:${string}` | string; export interface Pagination { - page?: number - pageSize?: number - total?: number + page?: number; + pageSize?: number; + total?: number; } export interface ResponseData { - code: number - data: any - msg: string + code: number; + data: any; + msg: string; } export interface PageData { - currentPageIndex: number - items: T[] - nextIndex: number - pageSize: number - previousIndex: number - startIndex: number - totalCount: number - totalPageCount: number + currentPageIndex: number; + items: T[]; + nextIndex: number; + pageSize: number; + previousIndex: number; + startIndex: number; + totalCount: number; + totalPageCount: number; } export function slicePage(content: T[], pagination: Pagination): PageData { const { page = 1, pageSize = 10 } = pagination; @@ -38,7 +38,7 @@ export function slicePage(content: T[], pagination: Pagination): PageData }; } -export const successResponseWrap = (data?: unknown, contentType: string | null = "application/json") => { +export function successResponseWrap(data?: unknown, contentType: string | null = "application/json") { if (contentType?.startsWith("application/json")) { return { data, @@ -47,11 +47,11 @@ export const successResponseWrap = (data?: unknown, contentType: string | null = }; } return data; -}; +} -export const failResponseWrap = (msg: string) => { +export function failResponseWrap(msg: string) { return { code: "Error", msg }; -}; +} diff --git a/playgrounds/server/main.ts b/playgrounds/server/main.ts index 6305fa9b..61b32e14 100644 --- a/playgrounds/server/main.ts +++ b/playgrounds/server/main.ts @@ -1,5 +1,6 @@ import fs from "node:fs"; import path from "node:path"; +import process from "node:process"; import comporession from "compression"; import ejs from "ejs"; import express from "express"; @@ -10,7 +11,7 @@ import { defineRouter } from "@fourze/core"; import type { FourzeRendererContext } from "@fourze/server"; import { createRenderer, createServer } from "@fourze/server"; -const router = defineRouter(router => { +const router = defineRouter((router) => { router.route("/hello").get(() => { return "Hello World"; }); @@ -35,7 +36,7 @@ app.use(renderer); app.use(comporession({ threshold: 0 }) as CommonMiddleware); const app2 = createServer(); -app2.use(defineRouter(router => { +app2.use(defineRouter((router) => { router.route("/hello").get(() => { return "Hello World"; }); diff --git a/playgrounds/server/tsx/index.tsx b/playgrounds/server/tsx/index.tsx index 1d5df617..7558edf1 100644 --- a/playgrounds/server/tsx/index.tsx +++ b/playgrounds/server/tsx/index.tsx @@ -16,7 +16,7 @@ export default () => {
-
{"Hello,World"}
+
Hello,World
{list.map(item => ( {item} ))} diff --git a/playgrounds/vite/src/app.vue b/playgrounds/vite/src/app.vue index 086c7be5..1140c4d0 100644 --- a/playgrounds/vite/src/app.vue +++ b/playgrounds/vite/src/app.vue @@ -66,20 +66,22 @@ const columns: TableColumns = [ title: "Operation", width: 160, render({ record }) { - return
- Edit - deleteById(record.id)}>Delete -
; + return ( +
+ Edit + deleteById(record.id)}>Delete +
+ ); } } ]; interface RequestOptions { - url: string - method?: string - params?: Record - type?: "jquery" | "fetch" | "axios" - data?: Record + url: string; + method?: string; + params?: Record; + type?: "jquery" | "fetch" | "axios"; + data?: Record; } async function request(options: RequestOptions) { diff --git a/playgrounds/vite/src/components/base/loading.vue b/playgrounds/vite/src/components/base/loading.vue index f0dad4f3..1d8f39ef 100644 --- a/playgrounds/vite/src/components/base/loading.vue +++ b/playgrounds/vite/src/components/base/loading.vue @@ -1,5 +1,6 @@