UNPKG

2.31 kBTypeScriptView Raw
1import type { ServerRequest, Params } from 'worktop/request';
2import type { ServerResponse } from 'worktop/response';
3
4export interface Config {
5 /**
6 * The specific origin to allow.
7 * Sets the `Access-Control-Allow-Origin` header.
8 * @default "*" – Allows all origins by default.
9 * @example "https://example.com"
10 */
11 origin: string;
12 /**
13 * The duration (in seconds) that a preflight results can be cached.
14 * Sets the `Access-Control-Max-Age` header.
15 * @example 3600 – Caches for 1 hour
16 */
17 maxage?: number;
18 /**
19 * The methods allowed when accessing the resource
20 * Sets the `Access-Control-Allow-Methods` header.
21 * @default ['GET','HEAD','PUT','PATCH','POST','DELETE']
22 */
23 methods?: string[];
24 /**
25 * Whether or not the actual request can be made using credentials.
26 * Sets the `Access-Control-Allow-Credentials` header.
27 * @default false
28 */
29 credentials?: boolean;
30 /**
31 * The HTTP headers that can be used when making the actual request.
32 * Sets the `Access-Control-Allow-Headers` header.
33 * @default request.headers.get('Access-Control-Request-Headers') || []
34 */
35 headers?: string[];
36 /**
37 * The HTTP response header names that a client is allowed to access.
38 * Sets the `Access-Control-Expose-Headers` header.
39 * @default []
40 */
41 expose?: string[];
42}
43
44/**
45 * The defaults used for CORS construction.
46 */
47export const config: Config;
48
49/**
50 * Apply CORS headers.
51 * Conditionallyy sets headers for preflight (aka OPTIONS) requests.
52 * @NOTE Values in `options` are given priority, otherwise the `config` defaults are used.
53 */
54export function headers(res: ServerResponse, options?: Partial<Config>, isPreflight?: boolean): void;
55
56type PreflightConfig = Omit<Config, 'origin'> & {
57 /**
58 * When a string, only requests from the specified value are allowed.
59 * When `true`, the incoming `Origin` header will always be allowed.
60 * When a RegExp, matching `Origin` header values will be allowed.
61 * When `false`, allows any origin – equivalent to `"*"` value.
62 * @default "*"
63 */
64 origin?: string | boolean | RegExp;
65}
66
67/**
68 * Apply all CORS headers (see `headers` export)
69 * Will also handle preflight (aka, OPTIONS) requests.
70 */
71export function preflight(options?: PreflightConfig): <P extends Params = Params>(req: ServerRequest<P>, res: ServerResponse) => void;