Skip to content

Commit

Permalink
style: format with prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Jan 3, 2023
1 parent 2fb1124 commit 920c386
Show file tree
Hide file tree
Showing 60 changed files with 1,953 additions and 1,114 deletions.
6 changes: 5 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
"unicorn/prefer-code-point": 0,
"unicorn/text-encoding-identifier-case": 0,
"prefer-rest-params": 0,
"prefer-spread": 0
"prefer-spread": 0,
"unicorn/number-literal-case": 0,
"generator-star-spacing": 0,
"indent": 0,
"unicorn/no-nested-ternary": 0
}
}
1 change: 1 addition & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
],
"scripts": {
"build": "unbuild",
"lint": "eslint --ext .ts .",
"lint": "eslint --ext .ts . && prettier -c src",
"prepack": "unbuild",
"release": "standard-version && pnpm publish && git push --follow-tags"
},
Expand All @@ -41,6 +41,7 @@
"consola": "^2.15.3",
"eslint": "^8.31.0",
"eslint-config-unjs": "^0.0.3",
"prettier": "^2.8.1",
"standard-version": "^9.5.0",
"typescript": "^4.9.4",
"unbuild": "^1.0.2"
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 6 additions & 5 deletions src/env.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import type { Preset, Environment } from "./types";

export function env (...presets: Preset[]): Environment {
export function env(...presets: Preset[]): Environment {
const _env: Environment = {
alias: {},
inject: {},
polyfill: [],
external: []
external: [],
};

for (const preset of presets) {
// Alias
if (preset.alias) {
// Sort aliases from specific to general (ie. fs/promises before fs)
const aliases = Object.keys(preset.alias).sort((a, b) =>
(b.split("/").length - a.split("/").length) || (b.length - a.length)
const aliases = Object.keys(preset.alias).sort(
(a, b) =>
b.split("/").length - a.split("/").length || b.length - a.length
);
for (const from of aliases) {
_env.alias[from] = preset.alias[from];
Expand All @@ -34,7 +35,7 @@ export function env (...presets: Preset[]): Environment {

// Polyfill
if (preset.polyfill) {
_env.polyfill.push(...preset.polyfill.filter(Boolean) as string[]);
_env.polyfill.push(...(preset.polyfill.filter(Boolean) as string[]));
}

// External
Expand Down
10 changes: 3 additions & 7 deletions src/presets/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,10 @@ export default {
"node-fetch": "unenv/runtime/npm/node-fetch",
"cross-fetch": "unenv/runtime/npm/cross-fetch",
"cross-fetch/polyfill": "unenv/runtime/mock/empty",
"isomorphic-fetch": "unenv/runtime/mock/empty"
"isomorphic-fetch": "unenv/runtime/mock/empty",
},

polyfill: [
"node-fetch-native/polyfill"
],
polyfill: ["node-fetch-native/polyfill"],

external: [
...NodeBuiltinModules
]
external: [...NodeBuiltinModules],
} as Preset;
44 changes: 22 additions & 22 deletions src/presets/nodeless.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,25 @@ const nodeless: Preset & { alias: Map<string, string> } = {
...mapArrToVal("unenv/runtime/mock/proxy-cjs", NodeBuiltinModules),

// Built-ins implemented by unenv
...Object.fromEntries([
"buffer",
"events",
"fs",
"fs/promises",
"http",
"net",
"path",
"process",
"stream",
"stream/promises",
"stream/consumers",
"stream/web",
"url",
"util",
"util/types"
].map(m => [m, `unenv/runtime/node/${m}/index`])),
...Object.fromEntries(
[
"buffer",
"events",
"fs",
"fs/promises",
"http",
"net",
"path",
"process",
"stream",
"stream/promises",
"stream/consumers",
"stream/web",
"url",
"util",
"util/types",
].map((m) => [m, `unenv/runtime/node/${m}/index`])
),

// npm
etag: "unenv/runtime/mock/noop",
Expand All @@ -38,17 +40,15 @@ const nodeless: Preset & { alias: Map<string, string> } = {
"cross-fetch": "unenv/runtime/npm/cross-fetch",
"cross-fetch/polyfill": "unenv/runtime/mock/empty",
"isomorphic-fetch": "unenv/runtime/mock/empty",
inherits: "unenv/runtime/npm/inherits"
inherits: "unenv/runtime/npm/inherits",
},

inject: {
process: "unenv/runtime/polyfill/process",
Buffer: ["buffer", "Buffer"]
Buffer: ["buffer", "Buffer"],
},

polyfill: [
"unenv/runtime/polyfill/process"
]
polyfill: ["unenv/runtime/polyfill/process"],
};

// Add node: aliases
Expand Down
6 changes: 3 additions & 3 deletions src/runtime/_internal/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export type Callback<E = Error | null | undefined> = (error?: E) => void
export type HeadersObject = { [key: string]: string | string[] | undefined }
export type BufferEncoding = any // TODO
export type Callback<E = Error | null | undefined> = (error?: E) => void;
export type HeadersObject = { [key: string]: string | string[] | undefined };
export type BufferEncoding = any; // TODO
10 changes: 6 additions & 4 deletions src/runtime/_internal/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { HeadersObject } from "./types";

export function rawHeaders (headers: HeadersObject) {
export function rawHeaders(headers: HeadersObject) {
const rawHeaders = [];
for (const key in headers) {
if (Array.isArray(headers[key])) {
Expand All @@ -15,14 +15,16 @@ export function rawHeaders (headers: HeadersObject) {
}

type Fn = (...args: any[]) => any;
export function mergeFns (...functions: Fn[]) {
export function mergeFns(...functions: Fn[]) {
return function (...args: any[]) {
for (const fn of functions) {
fn(...args);
}
};
}

export function notImplemented (name: string) {
return () : any => { throw new Error(`[unenv] ${name} is not implemented yet!`); };
export function notImplemented(name: string) {
return (): any => {
throw new Error(`[unenv] ${name} is not implemented yet!`);
};
}
41 changes: 24 additions & 17 deletions src/runtime/fetch/call.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,47 @@
import { IncomingMessage } from "../node/http/_request";
import { ServerResponse } from "../node/http/_response";

export type Handle = (req: IncomingMessage, res: ServerResponse) => Promise <any>
export type Handle = (
req: IncomingMessage,
res: ServerResponse
) => Promise<any>;

export type CallHandle = ReturnType<typeof createCall>
export type CallHandle = ReturnType<typeof createCall>;

export interface CallContext {
[key: string]: any
url?: string
method?: string
headers?: Headers | { [key: string]: string | string[] }
protocol?: string
body?: any
[key: string]: any;
url?: string;
method?: string;
headers?: Headers | { [key: string]: string | string[] };
protocol?: string;
body?: any;
}

export function createCall (handle: Handle) {
return function callHandle (context: CallContext) {
export function createCall(handle: Handle) {
return function callHandle(context: CallContext) {
const req = new IncomingMessage();
const res = new ServerResponse(req);

req.url = context.url || "/";
req.method = context.method || "GET";
req.headers = {};
if (context.headers) {
const headerEntries = typeof context.headers.entries === "function"
? context.headers.entries()
: Object.entries(context.headers);
const headerEntries =
typeof context.headers.entries === "function"
? context.headers.entries()
: Object.entries(context.headers);
for (const [name, value] of headerEntries) {
if (!value) { continue; }
if (!value) {
continue;
}
req.headers[name.toLowerCase()] = value;
}
}
req.headers.host = req.headers.host || context.host || "localhost";

// @ts-ignore
req.connection.encrypted = req.connection.encrypted || context.protocol === "https";
req.connection.encrypted =
req.connection.encrypted || context.protocol === "https";

// @ts-ignore
req.body = context.body || null;
Expand All @@ -43,10 +50,10 @@ export function createCall (handle: Handle) {
// TODO: Ensure _data is either of BodyInit (or narrower) types
// Blob | ArrayBUffer | TypedArray | DataView | FormData | ReadableStream | URLSearchParams | String
const r = {
body: res._data as BodyInit || "",
body: (res._data as BodyInit) || "",
headers: res._headers,
status: res.statusCode,
statusText: res.statusMessage
statusText: res.statusMessage,
};

req.destroy();
Expand Down
20 changes: 13 additions & 7 deletions src/runtime/fetch/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { CallContext, CallHandle } from "./call";
export * from "./call";

export type FetchOptions = globalThis.RequestInit & CallContext
export type FetchOptions = globalThis.RequestInit & CallContext;

export function createFetch (call: CallHandle, _fetch = global.fetch) {
return async function ufetch (input: string | Request, init: FetchOptions): Promise<Response> {
export function createFetch(call: CallHandle, _fetch = global.fetch) {
return async function ufetch(
input: string | Request,
init: FetchOptions
): Promise<Response> {
const url = input.toString();
if (!url.startsWith("/")) {
return _fetch(url, init);
Expand All @@ -14,14 +17,17 @@ export function createFetch (call: CallHandle, _fetch = global.fetch) {
return new Response(r.body, {
status: r.status,
statusText: r.statusText,
headers: Object.fromEntries(Object.entries(r.headers).map(
([name, value]) => [name, Array.isArray(value) ? value.join(",") : (value || "")])
)
headers: Object.fromEntries(
Object.entries(r.headers).map(([name, value]) => [
name,
Array.isArray(value) ? value.join(",") : value || "",
])
),
});
} catch (error: any) {
return new Response(error.toString(), {
status: Number.parseInt(error.statusCode || error.code) || 500,
statusText: error.statusText
statusText: error.statusText,
});
}
};
Expand Down
27 changes: 17 additions & 10 deletions src/runtime/mock/proxy.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,32 @@
const fn = function () {};

function createMock (name: string, overrides: any = {}): any {
function createMock(name: string, overrides: any = {}): any {
fn.prototype.name = name;
const props: any = {};
return new Proxy(fn, {
get (_target, prop) {
if (prop === "caller") { return null; }
if (prop === "__createMock__") { return createMock; }
if (prop in overrides) { return overrides[prop]; }
get(_target, prop) {
if (prop === "caller") {
return null;
}
if (prop === "__createMock__") {
return createMock;
}
if (prop in overrides) {
return overrides[prop];
}
// @ts-ignore
return (props[prop] = props[prop] || createMock(`${name}.${prop.toString()}`));
return (props[prop] =
props[prop] || createMock(`${name}.${prop.toString()}`));
},
apply (_target, _this, _args) {
apply(_target, _this, _args) {
return createMock(`${name}()`);
},
construct (_target, _args, _newT) {
construct(_target, _args, _newT) {
return createMock(`[${name}]`) as object;
},
enumerate (_target) {
enumerate(_target) {
return [];
}
},
});
}

Expand Down
Loading

0 comments on commit 920c386

Please sign in to comment.