Skip to content

Commit

Permalink
chore: restructure and change exports (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
james-elicx authored Oct 3, 2024
1 parent 4acd97f commit 0b51657
Show file tree
Hide file tree
Showing 56 changed files with 118 additions and 149 deletions.
2 changes: 1 addition & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

"import/no-extraneous-dependencies": [
"error",
{ "devDependencies": ["**/*.spec.ts", "vite.config.ts"] },
{ "devDependencies": ["**/*.spec.ts", "vite.config.ts", "fixtures/**/*.ts"] },
],
"import/extensions": ["error", "never"],
"no-console": "error",
Expand Down
4 changes: 2 additions & 2 deletions fixtures/check-route-match/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { VercelConfig } from '@/types/vercel-config';
import type { Config } from '@/router';

export const config: VercelConfig = {
export const config: Config = {
version: 3,
routes: [
{ src: '^/valid-src-only$', dest: '/' },
Expand Down
3 changes: 1 addition & 2 deletions fixtures/check-route-match/file-system.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { BuildOutput } from '@/types/build-output';

import type { BuildOutput } from '../run-test-set';
import { functionAsset, htmlAsset } from '../run-test-set';

export const fileSystem: BuildOutput = {
Expand Down
4 changes: 2 additions & 2 deletions fixtures/dynamic-routes/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { VercelConfig } from '@/types/vercel-config';
import type { Config } from '@/router';

export const config: VercelConfig = {
export const config: Config = {
version: 3,
routes: [
{
Expand Down
3 changes: 1 addition & 2 deletions fixtures/dynamic-routes/file-system.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { BuildOutput } from '@/types/build-output';

import type { BuildOutput } from '../run-test-set';
import { functionAsset, htmlAsset, staticAsset } from '../run-test-set';

export const fileSystem: BuildOutput = {
Expand Down
4 changes: 2 additions & 2 deletions fixtures/i18n/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { VercelConfig } from '@/types/vercel-config';
import type { Config } from '@/router';

export const config: VercelConfig = {
export const config: Config = {
version: 3,
routes: [
{
Expand Down
3 changes: 1 addition & 2 deletions fixtures/i18n/file-system.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { BuildOutput } from '@/types/build-output';

import type { BuildOutput } from '../run-test-set';
import { functionAsset, htmlAsset, staticAsset } from '../run-test-set';

export const staticLocales = ['en', 'fr', 'nl', 'es'] as const;
Expand Down
4 changes: 2 additions & 2 deletions fixtures/infinite-loop/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { VercelConfig } from '@/types/vercel-config';
import type { Config } from '@/router';

export const config: VercelConfig = {
export const config: Config = {
version: 3,
routes: [
{ src: '^/invalid$', dest: '/invalid/new', status: 404 },
Expand Down
3 changes: 1 addition & 2 deletions fixtures/infinite-loop/file-system.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { BuildOutput } from '@/types/build-output';

import type { BuildOutput } from '../run-test-set';
import { functionAsset, htmlAsset } from '../run-test-set';

export const fileSystem: BuildOutput = {
Expand Down
39 changes: 26 additions & 13 deletions fixtures/run-test-set.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,29 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';

// eslint-disable-next-line import/no-extraneous-dependencies
import { expect, suite, test, vi } from 'vitest';

import type { BuildOutputItem, EdgeFunction, ExecutionContext } from '@/types/build-output';
import type { Assets, Fetcher } from '@/types/request-context';
import type { VercelConfig } from '@/types/vercel-config';
import { applyHeaders, applySearchParams, createRouteRequest } from '@/utils/http';
import { collectLocalesFromRoutes, groupRoutesByPhase } from '@/utils/routing';
import type { Config } from '@/router';
import { applyHeaders, applySearchParams, createRouteRequest } from '@/router/http';
import { collectLocalesFromRoutes, groupRoutesByPhase } from '@/router/utils';

import type { RequestContext } from '../src';
import { Router } from '../src';

export type BuildOutputItem =
| { type: 'function' | 'middleware'; entrypoint: string }
| { type: 'static'; path?: string; headers?: Record<string, string> };

export type BuildOutput = Record<string, BuildOutputItem>;

type Fetcher = {
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
};

type EdgeFunction = {
default: (request: Request, context: RequestContext['ctx']) => Response | Promise<Response>;
};

type TestCase = {
name: string;
paths: string[];
Expand Down Expand Up @@ -64,7 +76,7 @@ export const functionAsset = (path: string) =>
export const runTestSet = (ctx: {
name: string;
desc: string;
config: VercelConfig;
config: Config;
fileSystem: Record<string, BuildOutputItem>;
cases: TestCase[];
}) => {
Expand All @@ -77,9 +89,7 @@ export const runTestSet = (ctx: {

const outputDir = join(__dirname, ctx.name, 'output');

const executionContext: ExecutionContext = {
waitUntil: () => null,
};
const executionCtx: RequestContext['ctx'] = { waitUntil: () => null };

const assetsFetcher: Fetcher = {
fetch: (input: RequestInfo | URL) => {
Expand Down Expand Up @@ -108,14 +118,17 @@ export const runTestSet = (ctx: {
const request = new Request(url, { method, headers });
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => null);

const assets: Assets = {
const assets: RequestContext['assets'] = {
has: (p) => p in ctx.fileSystem,
get: (p) => {
const entry = ctx.fileSystem[p];
if (!entry) return null;

return {
kind: entry.type,
isStaticAsset: entry.type === 'static',
isMiddleware: entry.type === 'middleware',
isRouteFunction: entry.type === 'function',
fetch: async ({ path, searchParams }) => {
let resp: Response | undefined;

Expand All @@ -129,7 +142,7 @@ export const runTestSet = (ctx: {
const edgeFuncJs = readFileSync(join(outputDir, entry.entrypoint)).toString();
// eslint-disable-next-line no-eval
const edgeFunction: EdgeFunction = eval(edgeFuncJs.toString());
resp = await edgeFunction.default(req, executionContext);
resp = await edgeFunction.default(req, executionCtx);
break;
}
case 'static': {
Expand All @@ -151,7 +164,7 @@ export const runTestSet = (ctx: {
},
};

const res = await router.fetch({ request, assets, ctx: executionContext });
const res = await router.fetch({ request, assets, ctx: executionCtx });

expect(res.status).toEqual(expected.status);
const textContent = await res.text();
Expand Down
4 changes: 2 additions & 2 deletions fixtures/trailing-slash/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { VercelConfig } from '@/types/vercel-config';
import type { Config } from '@/router';

export const config: VercelConfig = {
export const config: Config = {
version: 3,
routes: [
{
Expand Down
3 changes: 1 addition & 2 deletions fixtures/trailing-slash/file-system.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { BuildOutput } from '@/types/build-output';

import type { BuildOutput } from '../run-test-set';
import { functionAsset, htmlAsset, staticAsset } from '../run-test-set';

export const fileSystem: BuildOutput = {
Expand Down
33 changes: 8 additions & 25 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,32 +11,15 @@
"require": "./dist/index.cjs",
"types": "./dist/index.d.ts"
},
"./types/build-output": {
"types": "./dist/types/build-output/index.d.ts"
"./router": {
"import": "./dist/router/index.js",
"require": "./dist/router/index.cjs",
"types": "./dist/router/index.d.ts"
},
"./types/images": {
"types": "./dist/types/images/index.d.ts"
},
"./types/request-context": {
"types": "./dist/types/request-context/index.d.ts"
},
"./types/vercel-config": {
"types": "./dist/types/vercel-config/index.d.ts"
},
"./utils/http": {
"import": "./dist/utils/http/index.js",
"require": "./dist/utils/http/index.cjs",
"types": "./dist/utils/http/index.d.ts"
},
"./utils/images": {
"import": "./dist/utils/images/index.js",
"require": "./dist/utils/images/index.cjs",
"types": "./dist/utils/images/index.d.ts"
},
"./utils/routing": {
"import": "./dist/utils/routing/index.js",
"require": "./dist/utils/routing/index.cjs",
"types": "./dist/utils/routing/index.d.ts"
"./images": {
"import": "./dist/images/index.js",
"require": "./dist/images/index.cjs",
"types": "./dist/images/index.d.ts"
}
},
"publishConfig": {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { expect, suite, test } from 'vitest';

import type { ImagesConfig } from '@/types/images';

import { formatResizingResponse } from './format-resizing-response';
import type { ImagesConfig } from './types';

const baseConfig: ImagesConfig = {
domains: ['example.com'],
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { ImagesConfig } from '@/types/images';
import { applyHeaders, createMutableResponse } from '@/router/http';

import { applyHeaders, createMutableResponse } from '../http';
import type { ImagesConfig } from './types';

/**
* Formats the given response to match the images configuration spec from the build output
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { expect, suite, test } from 'vitest';

import type { ImagesConfig } from '@/types/images';

import { getResizingProperties } from './get-resizing-properties';
import type { ImagesConfig } from './types';

const baseUrl = 'https://localhost/_next/image?url=';
const baseValidUrl = `${baseUrl}%2Fimages%2F1.jpg`;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import type { ImageFormatWithoutPrefix, ImagesConfig } from '@/types/images';
import type { Maybe } from '@/types/utilities';

import { isRemotePatternMatch } from './is-remote-pattern-match';
import type { ImageFormatWithoutPrefix, ImagesConfig } from './types';

export type ResizingProperties = {
isRelative: boolean;
Expand Down Expand Up @@ -57,9 +55,9 @@ export const getResizingProperties = (
}

const acceptHeader = request.headers.get('Accept') ?? '';
const format = config?.formats
?.find((f) => acceptHeader.includes(f))
?.replace('image/', '') as Maybe<ImageFormatWithoutPrefix>;
const format = config?.formats?.find((f) => acceptHeader.includes(f))?.replace('image/', '') as
| ImageFormatWithoutPrefix
| undefined;

return {
isRelative,
Expand Down
1 change: 1 addition & 0 deletions src/utils/images/index.ts → src/images/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './format-resizing-response';
export * from './get-resizing-properties';
export * from './is-remote-pattern-match';
export * from './types';
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { expect, suite, test } from 'vitest';

import type { RemotePattern } from '@/types/images';

import { isRemotePatternMatch } from './is-remote-pattern-match';
import type { RemotePattern } from './types';

suite('isRemotePatternMatch', () => {
test('hostname matches correctly', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { RemotePattern } from '@/types/images';
import type { RemotePattern } from './types';

/**
* Checks whether the given URL matches the given remote pattern from the build output images
Expand Down
10 changes: 5 additions & 5 deletions src/types/images/index.ts → src/images/types.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import type { StripPrefix } from '@/types/utilities';

export type ImageFormat = 'image/avif' | 'image/webp';
export type ImageFormatWithoutPrefix = StripPrefix<ImageFormat, 'image/'>;

export type RemotePattern = {
protocol?: 'http' | 'https';
hostname: string;
port?: string;
pathname?: string;
};

type StripPrefix<T extends string, K extends string> = T extends `${K}${infer V}` ? V : T;

export type ImageFormat = 'image/avif' | 'image/webp';
export type ImageFormatWithoutPrefix = StripPrefix<ImageFormat, 'image/'>;

export type ImagesConfig = {
sizes: number[];
domains: string[];
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './router';
export type { Assets, RequestContext } from './router';
export { Router } from './router';
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { expect, suite, test } from 'vitest';

import type { MatchPCREResult } from '@/utils/pcre';

import type { MatchPCREResult } from '../pcre';
import { applyHeaders } from './apply-headers';

suite('applyHeaders', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { MatchPCREResult } from '@/utils/pcre';
import { applyPCREMatches } from '@/utils/pcre';
import type { MatchPCREResult } from '../pcre';
import { applyPCREMatches } from '../pcre';

/**
* Applies a set of headers to a response.
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
5 changes: 5 additions & 0 deletions src/router/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export { applyHeaders, applySearchParams } from './http';
export * from './request-context';
export * from './router';
export * from './types';
export { collectLocalesFromRoutes, groupRoutesByPhase } from './utils';
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { expect, suite, test } from 'vitest';

import type { SourceRoute } from '@/types/build-output';

import type { SourceRoute } from '../types';
import { applyPCREMatches } from './apply-pcre-matches';
import { matchPCRE } from './match-pcre';

Expand Down
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { expect, suite, test } from 'vitest';

import type { SourceRoute } from '@/types/build-output';

import type { SourceRoute } from '../types';
import { matchPCRE } from './match-pcre';

type TestCase = {
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import type { ExecutionContext } from '@/types/build-output';

export type Assets = {
has: (path: string) => boolean;
get: (path: string) => {
kind: 'static' | 'middleware' | 'function';
isStaticAsset: boolean;
isMiddleware: boolean;
isRouteFunction: boolean;
fetch: (data: { path: string; searchParams: URLSearchParams }) => Promise<Response>;
} | null;
};

export type Fetcher = {
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
type ExecutionContext = {
waitUntil: (promise: Promise<unknown>) => void;
};

export type RequestContext = {
Expand Down
6 changes: 3 additions & 3 deletions src/router.ts → src/router/router.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { RoutesGroupedByPhase } from '@/types/build-output';
import type { RequestContext } from '@/types/request-context';
import { applyHeaders, applySearchParams, isUrl } from '@/utils/http';
import { applyHeaders, applySearchParams, isUrl } from '@/router/http';

import type { RequestContext } from './request-context';
import type { ConfigMetadata, RoutingMatch } from './routes-matcher';
import { RoutesMatcher } from './routes-matcher';
import type { RoutesGroupedByPhase } from './types';

export class Router {
constructor(
Expand Down
Loading

0 comments on commit 0b51657

Please sign in to comment.