better-call 1.3.7 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +862 -0
- package/dist/_virtual/_rolldown/runtime.cjs +7 -13
- package/dist/adapters/node/request.cjs +3 -4
- package/dist/adapters/node/request.cjs.map +1 -1
- package/dist/adapters/node/request.d.cts +1 -6
- package/dist/adapters/node/request.d.mts +1 -6
- package/dist/adapters/node/request.mjs +1 -2
- package/dist/adapters/node/request.mjs.map +1 -1
- package/dist/client.cjs +3 -5
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +5 -6
- package/dist/client.d.mts +5 -6
- package/dist/client.mjs +1 -2
- package/dist/client.mjs.map +1 -1
- package/dist/context.cjs +6 -7
- package/dist/context.cjs.map +1 -1
- package/dist/context.d.cts +32 -29
- package/dist/context.d.mts +32 -29
- package/dist/context.mjs +3 -4
- package/dist/context.mjs.map +1 -1
- package/dist/cookies.cjs +3 -4
- package/dist/cookies.cjs.map +1 -1
- package/dist/cookies.mjs +2 -3
- package/dist/cookies.mjs.map +1 -1
- package/dist/crypto.cjs +2 -4
- package/dist/crypto.cjs.map +1 -1
- package/dist/crypto.mjs +2 -3
- package/dist/crypto.mjs.map +1 -1
- package/dist/endpoint.cjs +21 -10
- package/dist/endpoint.cjs.map +1 -1
- package/dist/endpoint.d.cts +22 -20
- package/dist/endpoint.d.mts +22 -20
- package/dist/endpoint.mjs +18 -7
- package/dist/endpoint.mjs.map +1 -1
- package/dist/error.cjs +8 -3
- package/dist/error.cjs.map +1 -1
- package/dist/error.d.cts +0 -1
- package/dist/error.d.mts +0 -1
- package/dist/error.mjs +7 -1
- package/dist/error.mjs.map +1 -1
- package/dist/helper.d.cts +4 -4
- package/dist/helper.d.mts +4 -4
- package/dist/index.cjs +10 -11
- package/dist/index.d.cts +4 -4
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +2 -3
- package/dist/middleware.cjs +4 -6
- package/dist/middleware.cjs.map +1 -1
- package/dist/middleware.d.cts +10 -21
- package/dist/middleware.d.mts +10 -21
- package/dist/middleware.mjs +1 -3
- package/dist/middleware.mjs.map +1 -1
- package/dist/node.cjs +3 -4
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.cts +1 -2
- package/dist/node.d.mts +1 -2
- package/dist/node.mjs +1 -2
- package/dist/node.mjs.map +1 -1
- package/dist/openapi.cjs +1 -3
- package/dist/openapi.cjs.map +1 -1
- package/dist/openapi.d.cts +2 -3
- package/dist/openapi.d.mts +2 -3
- package/dist/openapi.mjs +1 -2
- package/dist/openapi.mjs.map +1 -1
- package/dist/router.cjs +7 -9
- package/dist/router.cjs.map +1 -1
- package/dist/router.d.cts +2 -3
- package/dist/router.d.mts +2 -3
- package/dist/router.mjs +3 -4
- package/dist/router.mjs.map +1 -1
- package/dist/to-response.cjs +3 -5
- package/dist/to-response.cjs.map +1 -1
- package/dist/to-response.mjs +2 -4
- package/dist/to-response.mjs.map +1 -1
- package/dist/utils.cjs +2 -3
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.mjs +1 -2
- package/dist/utils.mjs.map +1 -1
- package/dist/validator.cjs +2 -3
- package/dist/validator.cjs.map +1 -1
- package/dist/validator.mjs +2 -2
- package/dist/validator.mjs.map +1 -1
- package/package.json +10 -11
package/dist/context.d.cts
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { CookieOptions, CookiePrefixOptions } from "./cookies.cjs";
|
|
2
2
|
import { StandardSchemaV1 } from "./standard-schema.cjs";
|
|
3
3
|
import { Status, statusCodes } from "./error.cjs";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { IsEmptyObject, Prettify, UnionToIntersection } from "./helper.cjs";
|
|
5
|
+
import { MiddlewareHandler, MiddlewareOptions } from "./middleware.cjs";
|
|
6
6
|
import { EndpointOptions } from "./endpoint.cjs";
|
|
7
|
-
|
|
7
|
+
import { InferRouteParams } from "rou3";
|
|
8
8
|
//#region src/context.d.ts
|
|
9
9
|
type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
|
|
10
10
|
type Method = HTTPMethod | "*";
|
|
11
|
-
type InferBodyInput<Options extends EndpointOptions | MiddlewareOptions, Body =
|
|
11
|
+
type InferBodyInput<Options extends EndpointOptions | MiddlewareOptions, Body = Options["metadata"] extends {
|
|
12
12
|
$Infer: {
|
|
13
13
|
body: infer B;
|
|
14
14
|
};
|
|
15
|
-
} ? B : Options["body"] extends StandardSchemaV1 ? StandardSchemaV1.InferInput<Options["body"]> : undefined
|
|
15
|
+
} ? B : Options["body"] extends StandardSchemaV1 ? StandardSchemaV1.InferInput<Options["body"]> : undefined> = undefined extends Body ? {
|
|
16
16
|
body?: Body;
|
|
17
17
|
} : {
|
|
18
18
|
body: Body;
|
|
@@ -22,11 +22,11 @@ type InferBody<Options extends EndpointOptions | MiddlewareOptions> = Options["m
|
|
|
22
22
|
body: infer Body;
|
|
23
23
|
};
|
|
24
24
|
} ? Body : Options["body"] extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<Options["body"]> : any;
|
|
25
|
-
type InferQueryInput<Options extends EndpointOptions | MiddlewareOptions, Query =
|
|
25
|
+
type InferQueryInput<Options extends EndpointOptions | MiddlewareOptions, Query = Options["metadata"] extends {
|
|
26
26
|
$Infer: {
|
|
27
27
|
query: infer Query;
|
|
28
28
|
};
|
|
29
|
-
} ? Query : Options["query"] extends StandardSchemaV1 ? StandardSchemaV1.InferInput<Options["query"]> : Record<string, any> | undefined
|
|
29
|
+
} ? Query : Options["query"] extends StandardSchemaV1 ? StandardSchemaV1.InferInput<Options["query"]> : Record<string, any> | undefined> = undefined extends Query ? {
|
|
30
30
|
query?: Query;
|
|
31
31
|
} : {
|
|
32
32
|
query: Query;
|
|
@@ -37,18 +37,22 @@ type InferQuery<Options extends EndpointOptions | MiddlewareOptions> = Options["
|
|
|
37
37
|
};
|
|
38
38
|
} ? Query : Options["query"] extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<Options["query"]> : Record<string, any> | undefined;
|
|
39
39
|
type InferMethod<Options extends EndpointOptions> = Options["method"] extends Array<Method> ? Options["method"][number] : Options["method"] extends "*" ? HTTPMethod : Options["method"];
|
|
40
|
-
type InferInputMethod<Options extends EndpointOptions, Method =
|
|
40
|
+
type InferInputMethod<Options extends EndpointOptions, Method = Options["method"] extends Array<any> ? Options["method"][number] | undefined : Options["method"] extends "*" ? HTTPMethod : Options["method"] | undefined> = undefined extends Method ? {
|
|
41
41
|
method?: Method;
|
|
42
42
|
} : {
|
|
43
43
|
method: Method;
|
|
44
44
|
};
|
|
45
|
-
type
|
|
46
|
-
type
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
params?: Record<string,
|
|
45
|
+
type TrailingWildcardKey<Path extends string> = Path extends `${infer Prefix}/*${"" | "/"}` ? Exclude<keyof InferRouteParams<Path>, keyof InferRouteParams<Prefix>> : never;
|
|
46
|
+
type RouteParams<Path extends string> = { [Key in keyof InferRouteParams<Path>]: Key extends TrailingWildcardKey<Path> ? InferRouteParams<Path>[Key] | undefined : InferRouteParams<Path>[Key]; };
|
|
47
|
+
type InferParam<Path extends string> = string extends Path ? Record<string, string | undefined> | undefined : [Path] extends [never] ? Record<string, string | undefined> | undefined : IsEmptyObject<RouteParams<Path>> extends true ? Record<string, string | undefined> | undefined : Prettify<RouteParams<Path>>;
|
|
48
|
+
type InferParamInput<Path extends string> = string extends Path ? {
|
|
49
|
+
params?: Record<string, string | undefined>;
|
|
50
|
+
} : [Path] extends [never] ? {
|
|
51
|
+
params?: Record<string, string | undefined>;
|
|
52
|
+
} : IsEmptyObject<RouteParams<Path>> extends true ? {
|
|
53
|
+
params?: Record<string, string | undefined>;
|
|
50
54
|
} : {
|
|
51
|
-
params: Prettify<
|
|
55
|
+
params: Prettify<RouteParams<Path>>;
|
|
52
56
|
};
|
|
53
57
|
type InferRequest<Option extends EndpointOptions | MiddlewareOptions> = Option["requireRequest"] extends true ? Request : Request | undefined;
|
|
54
58
|
type InferRequestInput<Option extends EndpointOptions | MiddlewareOptions> = Option["requireRequest"] extends true ? {
|
|
@@ -62,21 +66,20 @@ type InferHeadersInput<Option extends EndpointOptions | MiddlewareOptions> = Opt
|
|
|
62
66
|
} : {
|
|
63
67
|
headers?: HeadersInit;
|
|
64
68
|
};
|
|
65
|
-
type
|
|
69
|
+
type InferMiddlewareContext<T> = T extends ((...args: never[]) => infer Result) ? unknown extends Awaited<Result> ? never : Extract<Awaited<Result>, object> : never;
|
|
70
|
+
type InferMiddlewareContexts<Opts extends EndpointOptions["use"]> = Opts extends MiddlewareHandler[] ? InferMiddlewareContext<Opts[number]> : never;
|
|
71
|
+
type InferUse<Opts extends EndpointOptions["use"]> = [InferMiddlewareContexts<Opts>] extends [never] ? object : UnionToIntersection<InferMiddlewareContexts<Opts>>;
|
|
66
72
|
type InferMiddlewareBody<Options extends MiddlewareOptions> = Options["body"] extends StandardSchemaV1<infer T> ? T : any;
|
|
67
73
|
type InferMiddlewareQuery<Options extends MiddlewareOptions> = Options["query"] extends StandardSchemaV1<infer T> ? T : Record<string, any> | undefined;
|
|
68
74
|
type InputContext<Path extends string, Options extends EndpointOptions> = InferBodyInput<Options> & InferInputMethod<Options> & InferQueryInput<Options> & InferParamInput<Path> & InferRequestInput<Options> & InferHeadersInput<Options> & {
|
|
69
75
|
asResponse?: boolean;
|
|
70
76
|
returnHeaders?: boolean;
|
|
71
77
|
returnStatus?: boolean;
|
|
72
|
-
use?:
|
|
78
|
+
use?: MiddlewareHandler[];
|
|
73
79
|
path?: string;
|
|
74
80
|
context?: Record<string, any>;
|
|
75
81
|
};
|
|
76
|
-
declare const createInternalContext: (context: InputContext<any, any>, {
|
|
77
|
-
options,
|
|
78
|
-
path
|
|
79
|
-
}: {
|
|
82
|
+
declare const createInternalContext: (context: InputContext<any, any>, { options, path }: {
|
|
80
83
|
options: EndpointOptions;
|
|
81
84
|
path?: string;
|
|
82
85
|
}) => Promise<{
|
|
@@ -87,7 +90,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
87
90
|
returned: any;
|
|
88
91
|
headers: HeadersInit | undefined;
|
|
89
92
|
request: Request | undefined;
|
|
90
|
-
params: Record<string,
|
|
93
|
+
params: Record<string, string | undefined> | undefined;
|
|
91
94
|
method: any;
|
|
92
95
|
setHeader: (key: string, value: string) => void;
|
|
93
96
|
getHeader: (key: string) => string | null;
|
|
@@ -142,7 +145,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
142
145
|
asResponse?: boolean;
|
|
143
146
|
returnHeaders?: boolean;
|
|
144
147
|
returnStatus?: boolean;
|
|
145
|
-
use?:
|
|
148
|
+
use?: MiddlewareHandler[];
|
|
146
149
|
} | {
|
|
147
150
|
body: any;
|
|
148
151
|
query: any;
|
|
@@ -151,7 +154,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
151
154
|
returned: any;
|
|
152
155
|
headers: HeadersInit | undefined;
|
|
153
156
|
request: Request | undefined;
|
|
154
|
-
params: Record<string,
|
|
157
|
+
params: Record<string, string | undefined> | undefined;
|
|
155
158
|
method: any;
|
|
156
159
|
setHeader: (key: string, value: string) => void;
|
|
157
160
|
getHeader: (key: string) => string | null;
|
|
@@ -206,7 +209,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
206
209
|
asResponse?: boolean;
|
|
207
210
|
returnHeaders?: boolean;
|
|
208
211
|
returnStatus?: boolean;
|
|
209
|
-
use?:
|
|
212
|
+
use?: MiddlewareHandler[];
|
|
210
213
|
} | {
|
|
211
214
|
body: any;
|
|
212
215
|
query: any;
|
|
@@ -215,7 +218,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
215
218
|
returned: any;
|
|
216
219
|
headers: HeadersInit | undefined;
|
|
217
220
|
request: Request | undefined;
|
|
218
|
-
params: Record<string,
|
|
221
|
+
params: Record<string, string | undefined> | undefined;
|
|
219
222
|
method: any;
|
|
220
223
|
setHeader: (key: string, value: string) => void;
|
|
221
224
|
getHeader: (key: string) => string | null;
|
|
@@ -270,7 +273,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
270
273
|
asResponse?: boolean;
|
|
271
274
|
returnHeaders?: boolean;
|
|
272
275
|
returnStatus?: boolean;
|
|
273
|
-
use?:
|
|
276
|
+
use?: MiddlewareHandler[];
|
|
274
277
|
} | {
|
|
275
278
|
body: any;
|
|
276
279
|
query: any;
|
|
@@ -279,7 +282,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
279
282
|
returned: any;
|
|
280
283
|
headers: HeadersInit | undefined;
|
|
281
284
|
request: Request | undefined;
|
|
282
|
-
params: Record<string,
|
|
285
|
+
params: Record<string, string | undefined> | undefined;
|
|
283
286
|
method: any;
|
|
284
287
|
setHeader: (key: string, value: string) => void;
|
|
285
288
|
getHeader: (key: string) => string | null;
|
|
@@ -334,7 +337,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
334
337
|
asResponse?: boolean;
|
|
335
338
|
returnHeaders?: boolean;
|
|
336
339
|
returnStatus?: boolean;
|
|
337
|
-
use?:
|
|
340
|
+
use?: MiddlewareHandler[];
|
|
338
341
|
}>;
|
|
339
342
|
//#endregion
|
|
340
343
|
export { HTTPMethod, InferBody, InferBodyInput, InferHeaders, InferHeadersInput, InferInputMethod, InferMethod, InferMiddlewareBody, InferMiddlewareQuery, InferParam, InferParamInput, InferQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse, InputContext, Method, createInternalContext };
|
package/dist/context.d.mts
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { CookieOptions, CookiePrefixOptions } from "./cookies.mjs";
|
|
2
2
|
import { StandardSchemaV1 } from "./standard-schema.mjs";
|
|
3
3
|
import { Status, statusCodes } from "./error.mjs";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { IsEmptyObject, Prettify, UnionToIntersection } from "./helper.mjs";
|
|
5
|
+
import { MiddlewareHandler, MiddlewareOptions } from "./middleware.mjs";
|
|
6
6
|
import { EndpointOptions } from "./endpoint.mjs";
|
|
7
|
-
|
|
7
|
+
import { InferRouteParams } from "rou3";
|
|
8
8
|
//#region src/context.d.ts
|
|
9
9
|
type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
|
|
10
10
|
type Method = HTTPMethod | "*";
|
|
11
|
-
type InferBodyInput<Options extends EndpointOptions | MiddlewareOptions, Body =
|
|
11
|
+
type InferBodyInput<Options extends EndpointOptions | MiddlewareOptions, Body = Options["metadata"] extends {
|
|
12
12
|
$Infer: {
|
|
13
13
|
body: infer B;
|
|
14
14
|
};
|
|
15
|
-
} ? B : Options["body"] extends StandardSchemaV1 ? StandardSchemaV1.InferInput<Options["body"]> : undefined
|
|
15
|
+
} ? B : Options["body"] extends StandardSchemaV1 ? StandardSchemaV1.InferInput<Options["body"]> : undefined> = undefined extends Body ? {
|
|
16
16
|
body?: Body;
|
|
17
17
|
} : {
|
|
18
18
|
body: Body;
|
|
@@ -22,11 +22,11 @@ type InferBody<Options extends EndpointOptions | MiddlewareOptions> = Options["m
|
|
|
22
22
|
body: infer Body;
|
|
23
23
|
};
|
|
24
24
|
} ? Body : Options["body"] extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<Options["body"]> : any;
|
|
25
|
-
type InferQueryInput<Options extends EndpointOptions | MiddlewareOptions, Query =
|
|
25
|
+
type InferQueryInput<Options extends EndpointOptions | MiddlewareOptions, Query = Options["metadata"] extends {
|
|
26
26
|
$Infer: {
|
|
27
27
|
query: infer Query;
|
|
28
28
|
};
|
|
29
|
-
} ? Query : Options["query"] extends StandardSchemaV1 ? StandardSchemaV1.InferInput<Options["query"]> : Record<string, any> | undefined
|
|
29
|
+
} ? Query : Options["query"] extends StandardSchemaV1 ? StandardSchemaV1.InferInput<Options["query"]> : Record<string, any> | undefined> = undefined extends Query ? {
|
|
30
30
|
query?: Query;
|
|
31
31
|
} : {
|
|
32
32
|
query: Query;
|
|
@@ -37,18 +37,22 @@ type InferQuery<Options extends EndpointOptions | MiddlewareOptions> = Options["
|
|
|
37
37
|
};
|
|
38
38
|
} ? Query : Options["query"] extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<Options["query"]> : Record<string, any> | undefined;
|
|
39
39
|
type InferMethod<Options extends EndpointOptions> = Options["method"] extends Array<Method> ? Options["method"][number] : Options["method"] extends "*" ? HTTPMethod : Options["method"];
|
|
40
|
-
type InferInputMethod<Options extends EndpointOptions, Method =
|
|
40
|
+
type InferInputMethod<Options extends EndpointOptions, Method = Options["method"] extends Array<any> ? Options["method"][number] | undefined : Options["method"] extends "*" ? HTTPMethod : Options["method"] | undefined> = undefined extends Method ? {
|
|
41
41
|
method?: Method;
|
|
42
42
|
} : {
|
|
43
43
|
method: Method;
|
|
44
44
|
};
|
|
45
|
-
type
|
|
46
|
-
type
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
params?: Record<string,
|
|
45
|
+
type TrailingWildcardKey<Path extends string> = Path extends `${infer Prefix}/*${"" | "/"}` ? Exclude<keyof InferRouteParams<Path>, keyof InferRouteParams<Prefix>> : never;
|
|
46
|
+
type RouteParams<Path extends string> = { [Key in keyof InferRouteParams<Path>]: Key extends TrailingWildcardKey<Path> ? InferRouteParams<Path>[Key] | undefined : InferRouteParams<Path>[Key]; };
|
|
47
|
+
type InferParam<Path extends string> = string extends Path ? Record<string, string | undefined> | undefined : [Path] extends [never] ? Record<string, string | undefined> | undefined : IsEmptyObject<RouteParams<Path>> extends true ? Record<string, string | undefined> | undefined : Prettify<RouteParams<Path>>;
|
|
48
|
+
type InferParamInput<Path extends string> = string extends Path ? {
|
|
49
|
+
params?: Record<string, string | undefined>;
|
|
50
|
+
} : [Path] extends [never] ? {
|
|
51
|
+
params?: Record<string, string | undefined>;
|
|
52
|
+
} : IsEmptyObject<RouteParams<Path>> extends true ? {
|
|
53
|
+
params?: Record<string, string | undefined>;
|
|
50
54
|
} : {
|
|
51
|
-
params: Prettify<
|
|
55
|
+
params: Prettify<RouteParams<Path>>;
|
|
52
56
|
};
|
|
53
57
|
type InferRequest<Option extends EndpointOptions | MiddlewareOptions> = Option["requireRequest"] extends true ? Request : Request | undefined;
|
|
54
58
|
type InferRequestInput<Option extends EndpointOptions | MiddlewareOptions> = Option["requireRequest"] extends true ? {
|
|
@@ -62,21 +66,20 @@ type InferHeadersInput<Option extends EndpointOptions | MiddlewareOptions> = Opt
|
|
|
62
66
|
} : {
|
|
63
67
|
headers?: HeadersInit;
|
|
64
68
|
};
|
|
65
|
-
type
|
|
69
|
+
type InferMiddlewareContext<T> = T extends ((...args: never[]) => infer Result) ? unknown extends Awaited<Result> ? never : Extract<Awaited<Result>, object> : never;
|
|
70
|
+
type InferMiddlewareContexts<Opts extends EndpointOptions["use"]> = Opts extends MiddlewareHandler[] ? InferMiddlewareContext<Opts[number]> : never;
|
|
71
|
+
type InferUse<Opts extends EndpointOptions["use"]> = [InferMiddlewareContexts<Opts>] extends [never] ? object : UnionToIntersection<InferMiddlewareContexts<Opts>>;
|
|
66
72
|
type InferMiddlewareBody<Options extends MiddlewareOptions> = Options["body"] extends StandardSchemaV1<infer T> ? T : any;
|
|
67
73
|
type InferMiddlewareQuery<Options extends MiddlewareOptions> = Options["query"] extends StandardSchemaV1<infer T> ? T : Record<string, any> | undefined;
|
|
68
74
|
type InputContext<Path extends string, Options extends EndpointOptions> = InferBodyInput<Options> & InferInputMethod<Options> & InferQueryInput<Options> & InferParamInput<Path> & InferRequestInput<Options> & InferHeadersInput<Options> & {
|
|
69
75
|
asResponse?: boolean;
|
|
70
76
|
returnHeaders?: boolean;
|
|
71
77
|
returnStatus?: boolean;
|
|
72
|
-
use?:
|
|
78
|
+
use?: MiddlewareHandler[];
|
|
73
79
|
path?: string;
|
|
74
80
|
context?: Record<string, any>;
|
|
75
81
|
};
|
|
76
|
-
declare const createInternalContext: (context: InputContext<any, any>, {
|
|
77
|
-
options,
|
|
78
|
-
path
|
|
79
|
-
}: {
|
|
82
|
+
declare const createInternalContext: (context: InputContext<any, any>, { options, path }: {
|
|
80
83
|
options: EndpointOptions;
|
|
81
84
|
path?: string;
|
|
82
85
|
}) => Promise<{
|
|
@@ -87,7 +90,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
87
90
|
returned: any;
|
|
88
91
|
headers: HeadersInit | undefined;
|
|
89
92
|
request: Request | undefined;
|
|
90
|
-
params: Record<string,
|
|
93
|
+
params: Record<string, string | undefined> | undefined;
|
|
91
94
|
method: any;
|
|
92
95
|
setHeader: (key: string, value: string) => void;
|
|
93
96
|
getHeader: (key: string) => string | null;
|
|
@@ -142,7 +145,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
142
145
|
asResponse?: boolean;
|
|
143
146
|
returnHeaders?: boolean;
|
|
144
147
|
returnStatus?: boolean;
|
|
145
|
-
use?:
|
|
148
|
+
use?: MiddlewareHandler[];
|
|
146
149
|
} | {
|
|
147
150
|
body: any;
|
|
148
151
|
query: any;
|
|
@@ -151,7 +154,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
151
154
|
returned: any;
|
|
152
155
|
headers: HeadersInit | undefined;
|
|
153
156
|
request: Request | undefined;
|
|
154
|
-
params: Record<string,
|
|
157
|
+
params: Record<string, string | undefined> | undefined;
|
|
155
158
|
method: any;
|
|
156
159
|
setHeader: (key: string, value: string) => void;
|
|
157
160
|
getHeader: (key: string) => string | null;
|
|
@@ -206,7 +209,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
206
209
|
asResponse?: boolean;
|
|
207
210
|
returnHeaders?: boolean;
|
|
208
211
|
returnStatus?: boolean;
|
|
209
|
-
use?:
|
|
212
|
+
use?: MiddlewareHandler[];
|
|
210
213
|
} | {
|
|
211
214
|
body: any;
|
|
212
215
|
query: any;
|
|
@@ -215,7 +218,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
215
218
|
returned: any;
|
|
216
219
|
headers: HeadersInit | undefined;
|
|
217
220
|
request: Request | undefined;
|
|
218
|
-
params: Record<string,
|
|
221
|
+
params: Record<string, string | undefined> | undefined;
|
|
219
222
|
method: any;
|
|
220
223
|
setHeader: (key: string, value: string) => void;
|
|
221
224
|
getHeader: (key: string) => string | null;
|
|
@@ -270,7 +273,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
270
273
|
asResponse?: boolean;
|
|
271
274
|
returnHeaders?: boolean;
|
|
272
275
|
returnStatus?: boolean;
|
|
273
|
-
use?:
|
|
276
|
+
use?: MiddlewareHandler[];
|
|
274
277
|
} | {
|
|
275
278
|
body: any;
|
|
276
279
|
query: any;
|
|
@@ -279,7 +282,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
279
282
|
returned: any;
|
|
280
283
|
headers: HeadersInit | undefined;
|
|
281
284
|
request: Request | undefined;
|
|
282
|
-
params: Record<string,
|
|
285
|
+
params: Record<string, string | undefined> | undefined;
|
|
283
286
|
method: any;
|
|
284
287
|
setHeader: (key: string, value: string) => void;
|
|
285
288
|
getHeader: (key: string) => string | null;
|
|
@@ -334,7 +337,7 @@ declare const createInternalContext: (context: InputContext<any, any>, {
|
|
|
334
337
|
asResponse?: boolean;
|
|
335
338
|
returnHeaders?: boolean;
|
|
336
339
|
returnStatus?: boolean;
|
|
337
|
-
use?:
|
|
340
|
+
use?: MiddlewareHandler[];
|
|
338
341
|
}>;
|
|
339
342
|
//#endregion
|
|
340
343
|
export { HTTPMethod, InferBody, InferBodyInput, InferHeaders, InferHeadersInput, InferInputMethod, InferMethod, InferMiddlewareBody, InferMiddlewareQuery, InferParam, InferParamInput, InferQuery, InferQueryInput, InferRequest, InferRequestInput, InferUse, InputContext, Method, createInternalContext };
|
package/dist/context.mjs
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
|
+
import { getCryptoKey, verifySignature } from "./crypto.mjs";
|
|
1
2
|
import { APIError, ValidationError } from "./error.mjs";
|
|
2
3
|
import { isRequest } from "./utils.mjs";
|
|
3
|
-
import { runValidation } from "./validator.mjs";
|
|
4
|
-
import { getCryptoKey, verifySignature } from "./crypto.mjs";
|
|
5
4
|
import { getCookieKey, parseCookies, serializeCookie, serializeSignedCookie } from "./cookies.mjs";
|
|
6
|
-
|
|
5
|
+
import { runValidation } from "./validator.mjs";
|
|
7
6
|
//#region src/context.ts
|
|
8
7
|
const createInternalContext = async (context, { options, path }) => {
|
|
9
8
|
const headers = new Headers();
|
|
@@ -97,7 +96,7 @@ const createInternalContext = async (context, { options, path }) => {
|
|
|
97
96
|
}
|
|
98
97
|
return internalContext;
|
|
99
98
|
};
|
|
100
|
-
|
|
101
99
|
//#endregion
|
|
102
100
|
export { createInternalContext };
|
|
101
|
+
|
|
103
102
|
//# sourceMappingURL=context.mjs.map
|
package/dist/context.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.mjs","names":[],"sources":["../src/context.ts"],"sourcesContent":["import type { EndpointOptions } from \"./endpoint\";\nimport {\n\ttype statusCodes,\n\tAPIError,\n\tValidationError,\n\ttype Status,\n} from \"./error\";\nimport type {\n\tInferParamPath,\n\tInferParamWildCard,\n\tIsEmptyObject,\n\tPrettify,\n\tUnionToIntersection,\n} from \"./helper\";\nimport type {\n\tMiddleware,\n\tMiddlewareContext,\n\tMiddlewareOptions,\n} from \"./middleware\";\nimport { runValidation } from \"./validator\";\nimport {\n\tgetCookieKey,\n\tparseCookies,\n\tserializeCookie,\n\tserializeSignedCookie,\n\ttype CookieOptions,\n\ttype CookiePrefixOptions,\n} from \"./cookies\";\nimport { getCryptoKey, verifySignature } from \"./crypto\";\nimport type { StandardSchemaV1 } from \"./standard-schema\";\nimport { isRequest } from \"./utils\";\n\nexport type HTTPMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\nexport type Method = HTTPMethod | \"*\";\n\nexport type InferBodyInput<\n\tOptions extends EndpointOptions | MiddlewareOptions,\n\tBody = Options[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tbody: infer B;\n\t\t};\n\t}\n\t\t? B\n\t\t: Options[\"body\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferInput<Options[\"body\"]>\n\t\t\t: undefined,\n> = undefined extends Body\n\t? {\n\t\t\tbody?: Body;\n\t\t}\n\t: {\n\t\t\tbody: Body;\n\t\t};\n\nexport type InferBody<Options extends EndpointOptions | MiddlewareOptions> =\n\tOptions[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tbody: infer Body;\n\t\t};\n\t}\n\t\t? Body\n\t\t: Options[\"body\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferOutput<Options[\"body\"]>\n\t\t\t: any;\n\nexport type InferQueryInput<\n\tOptions extends EndpointOptions | MiddlewareOptions,\n\tQuery = Options[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tquery: infer Query;\n\t\t};\n\t}\n\t\t? Query\n\t\t: Options[\"query\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferInput<Options[\"query\"]>\n\t\t\t: Record<string, any> | undefined,\n> = undefined extends Query\n\t? {\n\t\t\tquery?: Query;\n\t\t}\n\t: {\n\t\t\tquery: Query;\n\t\t};\n\nexport type InferQuery<Options extends EndpointOptions | MiddlewareOptions> =\n\tOptions[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tquery: infer Query;\n\t\t};\n\t}\n\t\t? Query\n\t\t: Options[\"query\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferOutput<Options[\"query\"]>\n\t\t\t: Record<string, any> | undefined;\n\nexport type InferMethod<Options extends EndpointOptions> =\n\tOptions[\"method\"] extends Array<Method>\n\t\t? Options[\"method\"][number]\n\t\t: Options[\"method\"] extends \"*\"\n\t\t\t? HTTPMethod\n\t\t\t: Options[\"method\"];\n\nexport type InferInputMethod<\n\tOptions extends EndpointOptions,\n\tMethod = Options[\"method\"] extends Array<any>\n\t\t? Options[\"method\"][number] | undefined\n\t\t: Options[\"method\"] extends \"*\"\n\t\t\t? HTTPMethod\n\t\t\t: Options[\"method\"] | undefined,\n> = undefined extends Method\n\t? {\n\t\t\tmethod?: Method;\n\t\t}\n\t: {\n\t\t\tmethod: Method;\n\t\t};\n\nexport type InferParam<Path extends string> = [Path] extends [never]\n\t? Record<string, any> | undefined\n\t: IsEmptyObject<InferParamPath<Path> & InferParamWildCard<Path>> extends true\n\t\t? Record<string, any> | undefined\n\t\t: Prettify<InferParamPath<Path> & InferParamWildCard<Path>>;\n\nexport type InferParamInput<Path extends string> = [Path] extends [never]\n\t? { params?: Record<string, any> }\n\t: IsEmptyObject<InferParamPath<Path> & InferParamWildCard<Path>> extends true\n\t\t? {\n\t\t\t\tparams?: Record<string, any>;\n\t\t\t}\n\t\t: {\n\t\t\t\tparams: Prettify<InferParamPath<Path> & InferParamWildCard<Path>>;\n\t\t\t};\n\nexport type InferRequest<Option extends EndpointOptions | MiddlewareOptions> =\n\tOption[\"requireRequest\"] extends true ? Request : Request | undefined;\n\nexport type InferRequestInput<\n\tOption extends EndpointOptions | MiddlewareOptions,\n> = Option[\"requireRequest\"] extends true\n\t? {\n\t\t\trequest: Request;\n\t\t}\n\t: {\n\t\t\trequest?: Request;\n\t\t};\n\nexport type InferHeaders<Option extends EndpointOptions | MiddlewareOptions> =\n\tOption[\"requireHeaders\"] extends true ? Headers : Headers | undefined;\n\nexport type InferHeadersInput<\n\tOption extends EndpointOptions | MiddlewareOptions,\n> = Option[\"requireHeaders\"] extends true\n\t? {\n\t\t\theaders: HeadersInit;\n\t\t}\n\t: {\n\t\t\theaders?: HeadersInit;\n\t\t};\n\nexport type InferUse<Opts extends EndpointOptions[\"use\"]> =\n\tOpts extends Middleware[]\n\t\t? UnionToIntersection<Awaited<ReturnType<Opts[number]>>>\n\t\t: {};\n\nexport type InferMiddlewareBody<Options extends MiddlewareOptions> =\n\tOptions[\"body\"] extends StandardSchemaV1<infer T> ? T : any;\n\nexport type InferMiddlewareQuery<Options extends MiddlewareOptions> =\n\tOptions[\"query\"] extends StandardSchemaV1<infer T>\n\t\t? T\n\t\t: Record<string, any> | undefined;\n\nexport type InputContext<\n\tPath extends string,\n\tOptions extends EndpointOptions,\n> = InferBodyInput<Options> &\n\tInferInputMethod<Options> &\n\tInferQueryInput<Options> &\n\tInferParamInput<Path> &\n\tInferRequestInput<Options> &\n\tInferHeadersInput<Options> & {\n\t\tasResponse?: boolean;\n\t\treturnHeaders?: boolean;\n\t\treturnStatus?: boolean;\n\t\tuse?: Middleware[];\n\t\tpath?: string;\n\t\tcontext?: Record<string, any>;\n\t};\n\nexport const createInternalContext = async (\n\tcontext: InputContext<any, any>,\n\t{\n\t\toptions,\n\t\tpath,\n\t}: {\n\t\toptions: EndpointOptions;\n\t\tpath?: string;\n\t},\n) => {\n\tconst headers = new Headers();\n\tlet responseStatus: Status | undefined = undefined;\n\n\tconst { data, error } = await runValidation(options, context);\n\tif (error) {\n\t\tthrow new ValidationError(error.message, error.issues);\n\t}\n\tconst requestHeaders: Headers | null =\n\t\t\"headers\" in context\n\t\t\t? context.headers instanceof Headers\n\t\t\t\t? context.headers\n\t\t\t\t: new Headers(context.headers)\n\t\t\t: \"request\" in context && isRequest(context.request)\n\t\t\t\t? context.request.headers\n\t\t\t\t: null;\n\tconst requestCookies = requestHeaders?.get(\"cookie\");\n\tconst parsedCookies = requestCookies\n\t\t? parseCookies(requestCookies)\n\t\t: undefined;\n\n\tconst internalContext = {\n\t\t...context,\n\t\tbody: data.body,\n\t\tquery: data.query,\n\t\tpath: context.path || path || \"virtual:\",\n\t\tcontext: \"context\" in context && context.context ? context.context : {},\n\t\treturned: undefined as any,\n\t\theaders: context?.headers,\n\t\trequest: context?.request,\n\t\tparams: \"params\" in context ? context.params : undefined,\n\t\tmethod:\n\t\t\tcontext.method ??\n\t\t\t(Array.isArray(options.method)\n\t\t\t\t? options.method[0]\n\t\t\t\t: options.method === \"*\"\n\t\t\t\t\t? \"GET\"\n\t\t\t\t\t: options.method),\n\t\tsetHeader: (key: string, value: string) => {\n\t\t\theaders.set(key, value);\n\t\t},\n\t\tgetHeader: (key: string) => {\n\t\t\tif (!requestHeaders) return null;\n\t\t\treturn requestHeaders.get(key);\n\t\t},\n\t\tgetCookie: (key: string, prefix?: CookiePrefixOptions) => {\n\t\t\tconst finalKey = getCookieKey(key, prefix);\n\t\t\tif (!finalKey) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn parsedCookies?.get(finalKey) || null;\n\t\t},\n\t\tgetSignedCookie: async (\n\t\t\tkey: string,\n\t\t\tsecret: string,\n\t\t\tprefix?: CookiePrefixOptions,\n\t\t) => {\n\t\t\tconst finalKey = getCookieKey(key, prefix);\n\t\t\tif (!finalKey) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst value = parsedCookies?.get(finalKey);\n\t\t\tif (!value) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst signatureStartPos = value.lastIndexOf(\".\");\n\t\t\tif (signatureStartPos < 1) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst signedValue = value.substring(0, signatureStartPos);\n\t\t\tconst signature = value.substring(signatureStartPos + 1);\n\t\t\tif (signature.length !== 44 || !signature.endsWith(\"=\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst secretKey = await getCryptoKey(secret);\n\t\t\tconst isVerified = await verifySignature(\n\t\t\t\tsignature,\n\t\t\t\tsignedValue,\n\t\t\t\tsecretKey,\n\t\t\t);\n\t\t\treturn isVerified ? signedValue : false;\n\t\t},\n\t\tsetCookie: (key: string, value: string, options?: CookieOptions) => {\n\t\t\tconst cookie = serializeCookie(key, value, options);\n\t\t\theaders.append(\"set-cookie\", cookie);\n\t\t\treturn cookie;\n\t\t},\n\t\tsetSignedCookie: async (\n\t\t\tkey: string,\n\t\t\tvalue: string,\n\t\t\tsecret: string,\n\t\t\toptions?: CookieOptions,\n\t\t) => {\n\t\t\tconst cookie = await serializeSignedCookie(key, value, secret, options);\n\t\t\theaders.append(\"set-cookie\", cookie);\n\t\t\treturn cookie;\n\t\t},\n\t\tredirect: (url: string) => {\n\t\t\theaders.set(\"location\", url);\n\t\t\treturn new APIError(\"FOUND\", undefined, headers);\n\t\t},\n\t\terror: (\n\t\t\tstatus: keyof typeof statusCodes | Status,\n\t\t\tbody?:\n\t\t\t\t| {\n\t\t\t\t\t\tmessage?: string;\n\t\t\t\t\t\tcode?: string;\n\t\t\t\t }\n\t\t\t\t| undefined,\n\t\t\theaders?: HeadersInit,\n\t\t) => {\n\t\t\treturn new APIError(status, body, headers);\n\t\t},\n\t\tsetStatus: (status: Status) => {\n\t\t\tresponseStatus = status;\n\t\t},\n\t\tjson: (\n\t\t\tjson: Record<string, any>,\n\t\t\trouterResponse?:\n\t\t\t\t| {\n\t\t\t\t\t\tstatus?: number;\n\t\t\t\t\t\theaders?: Record<string, string>;\n\t\t\t\t\t\tresponse?: Response;\n\t\t\t\t\t\tbody?: Record<string, any>;\n\t\t\t\t }\n\t\t\t\t| Response,\n\t\t) => {\n\t\t\tif (!context.asResponse) {\n\t\t\t\treturn json;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tbody: routerResponse?.body || json,\n\t\t\t\trouterResponse,\n\t\t\t\t_flag: \"json\",\n\t\t\t};\n\t\t},\n\t\tresponseHeaders: headers,\n\t\tget responseStatus() {\n\t\t\treturn responseStatus;\n\t\t},\n\t};\n\t//if context was shimmed through the input we want to apply it\n\tfor (const middleware of options.use || []) {\n\t\tconst response = (await middleware({\n\t\t\t...internalContext,\n\t\t\treturnHeaders: true,\n\t\t\tasResponse: false,\n\t\t})) as {\n\t\t\tresponse?: any;\n\t\t\theaders?: Headers;\n\t\t};\n\t\tif (response.response) {\n\t\t\tObject.assign(internalContext.context, response.response);\n\t\t}\n\t\t/**\n\t\t * Apply headers from the middleware to the endpoint headers\n\t\t */\n\t\tif (response.headers) {\n\t\t\tresponse.headers.forEach((value, key) => {\n\t\t\t\tinternalContext.responseHeaders.set(key, value);\n\t\t\t});\n\t\t}\n\t}\n\treturn internalContext;\n};\n"],"m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ACxC,mBAAgB,gBAAgB,IAAI,KAAK,MAAM;IAC9C;;AAGJ,QAAO"}
|
|
1
|
+
{"version":3,"file":"context.mjs","names":[],"sources":["../src/context.ts"],"sourcesContent":["import type { InferRouteParams } from \"rou3\";\nimport type { CookieOptions, CookiePrefixOptions } from \"./cookies\";\nimport {\n\tgetCookieKey,\n\tparseCookies,\n\tserializeCookie,\n\tserializeSignedCookie,\n} from \"./cookies\";\nimport { getCryptoKey, verifySignature } from \"./crypto\";\nimport type { EndpointOptions } from \"./endpoint\";\nimport type { Status, statusCodes } from \"./error\";\nimport { APIError, ValidationError } from \"./error\";\nimport type { IsEmptyObject, Prettify, UnionToIntersection } from \"./helper\";\nimport type { MiddlewareHandler, MiddlewareOptions } from \"./middleware\";\nimport type { StandardSchemaV1 } from \"./standard-schema\";\nimport { isRequest } from \"./utils\";\nimport { runValidation } from \"./validator\";\n\nexport type HTTPMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\nexport type Method = HTTPMethod | \"*\";\n\nexport type InferBodyInput<\n\tOptions extends EndpointOptions | MiddlewareOptions,\n\tBody = Options[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tbody: infer B;\n\t\t};\n\t}\n\t\t? B\n\t\t: Options[\"body\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferInput<Options[\"body\"]>\n\t\t\t: undefined,\n> = undefined extends Body\n\t? {\n\t\t\tbody?: Body;\n\t\t}\n\t: {\n\t\t\tbody: Body;\n\t\t};\n\nexport type InferBody<Options extends EndpointOptions | MiddlewareOptions> =\n\tOptions[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tbody: infer Body;\n\t\t};\n\t}\n\t\t? Body\n\t\t: Options[\"body\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferOutput<Options[\"body\"]>\n\t\t\t: any;\n\nexport type InferQueryInput<\n\tOptions extends EndpointOptions | MiddlewareOptions,\n\tQuery = Options[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tquery: infer Query;\n\t\t};\n\t}\n\t\t? Query\n\t\t: Options[\"query\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferInput<Options[\"query\"]>\n\t\t\t: Record<string, any> | undefined,\n> = undefined extends Query\n\t? {\n\t\t\tquery?: Query;\n\t\t}\n\t: {\n\t\t\tquery: Query;\n\t\t};\n\nexport type InferQuery<Options extends EndpointOptions | MiddlewareOptions> =\n\tOptions[\"metadata\"] extends {\n\t\t$Infer: {\n\t\t\tquery: infer Query;\n\t\t};\n\t}\n\t\t? Query\n\t\t: Options[\"query\"] extends StandardSchemaV1\n\t\t\t? StandardSchemaV1.InferOutput<Options[\"query\"]>\n\t\t\t: Record<string, any> | undefined;\n\nexport type InferMethod<Options extends EndpointOptions> =\n\tOptions[\"method\"] extends Array<Method>\n\t\t? Options[\"method\"][number]\n\t\t: Options[\"method\"] extends \"*\"\n\t\t\t? HTTPMethod\n\t\t\t: Options[\"method\"];\n\nexport type InferInputMethod<\n\tOptions extends EndpointOptions,\n\tMethod = Options[\"method\"] extends Array<any>\n\t\t? Options[\"method\"][number] | undefined\n\t\t: Options[\"method\"] extends \"*\"\n\t\t\t? HTTPMethod\n\t\t\t: Options[\"method\"] | undefined,\n> = undefined extends Method\n\t? {\n\t\t\tmethod?: Method;\n\t\t}\n\t: {\n\t\t\tmethod: Method;\n\t\t};\n\ntype TrailingWildcardKey<Path extends string> =\n\tPath extends `${infer Prefix}/*${\"\" | \"/\"}`\n\t\t? Exclude<keyof InferRouteParams<Path>, keyof InferRouteParams<Prefix>>\n\t\t: never;\n\ntype RouteParams<Path extends string> = {\n\t[Key in keyof InferRouteParams<Path>]: Key extends TrailingWildcardKey<Path>\n\t\t? InferRouteParams<Path>[Key] | undefined\n\t\t: InferRouteParams<Path>[Key];\n};\n\nexport type InferParam<Path extends string> = string extends Path\n\t? Record<string, string | undefined> | undefined\n\t: [Path] extends [never]\n\t\t? Record<string, string | undefined> | undefined\n\t\t: IsEmptyObject<RouteParams<Path>> extends true\n\t\t\t? Record<string, string | undefined> | undefined\n\t\t\t: Prettify<RouteParams<Path>>;\n\nexport type InferParamInput<Path extends string> = string extends Path\n\t? { params?: Record<string, string | undefined> }\n\t: [Path] extends [never]\n\t\t? { params?: Record<string, string | undefined> }\n\t\t: IsEmptyObject<RouteParams<Path>> extends true\n\t\t\t? {\n\t\t\t\t\tparams?: Record<string, string | undefined>;\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tparams: Prettify<RouteParams<Path>>;\n\t\t\t\t};\n\nexport type InferRequest<Option extends EndpointOptions | MiddlewareOptions> =\n\tOption[\"requireRequest\"] extends true ? Request : Request | undefined;\n\nexport type InferRequestInput<\n\tOption extends EndpointOptions | MiddlewareOptions,\n> = Option[\"requireRequest\"] extends true\n\t? {\n\t\t\trequest: Request;\n\t\t}\n\t: {\n\t\t\trequest?: Request;\n\t\t};\n\nexport type InferHeaders<Option extends EndpointOptions | MiddlewareOptions> =\n\tOption[\"requireHeaders\"] extends true ? Headers : Headers | undefined;\n\nexport type InferHeadersInput<\n\tOption extends EndpointOptions | MiddlewareOptions,\n> = Option[\"requireHeaders\"] extends true\n\t? {\n\t\t\theaders: HeadersInit;\n\t\t}\n\t: {\n\t\t\theaders?: HeadersInit;\n\t\t};\n\ntype InferMiddlewareContext<T> = T extends (...args: never[]) => infer Result\n\t? unknown extends Awaited<Result>\n\t\t? never\n\t\t: Extract<Awaited<Result>, object>\n\t: never;\n\ntype InferMiddlewareContexts<Opts extends EndpointOptions[\"use\"]> =\n\tOpts extends MiddlewareHandler[]\n\t\t? InferMiddlewareContext<Opts[number]>\n\t\t: never;\n\nexport type InferUse<Opts extends EndpointOptions[\"use\"]> = [\n\tInferMiddlewareContexts<Opts>,\n] extends [never]\n\t? object\n\t: UnionToIntersection<InferMiddlewareContexts<Opts>>;\n\nexport type InferMiddlewareBody<Options extends MiddlewareOptions> =\n\tOptions[\"body\"] extends StandardSchemaV1<infer T> ? T : any;\n\nexport type InferMiddlewareQuery<Options extends MiddlewareOptions> =\n\tOptions[\"query\"] extends StandardSchemaV1<infer T>\n\t\t? T\n\t\t: Record<string, any> | undefined;\n\nexport type InputContext<\n\tPath extends string,\n\tOptions extends EndpointOptions,\n> = InferBodyInput<Options> &\n\tInferInputMethod<Options> &\n\tInferQueryInput<Options> &\n\tInferParamInput<Path> &\n\tInferRequestInput<Options> &\n\tInferHeadersInput<Options> & {\n\t\tasResponse?: boolean;\n\t\treturnHeaders?: boolean;\n\t\treturnStatus?: boolean;\n\t\tuse?: MiddlewareHandler[];\n\t\tpath?: string;\n\t\tcontext?: Record<string, any>;\n\t};\n\nexport const createInternalContext = async (\n\tcontext: InputContext<any, any>,\n\t{\n\t\toptions,\n\t\tpath,\n\t}: {\n\t\toptions: EndpointOptions;\n\t\tpath?: string;\n\t},\n) => {\n\tconst headers = new Headers();\n\tlet responseStatus: Status | undefined = undefined;\n\n\tconst { data, error } = await runValidation(options, context);\n\tif (error) {\n\t\tthrow new ValidationError(error.message, error.issues);\n\t}\n\tconst requestHeaders: Headers | null =\n\t\t\"headers\" in context\n\t\t\t? context.headers instanceof Headers\n\t\t\t\t? context.headers\n\t\t\t\t: new Headers(context.headers)\n\t\t\t: \"request\" in context && isRequest(context.request)\n\t\t\t\t? context.request.headers\n\t\t\t\t: null;\n\tconst requestCookies = requestHeaders?.get(\"cookie\");\n\tconst parsedCookies = requestCookies\n\t\t? parseCookies(requestCookies)\n\t\t: undefined;\n\n\tconst internalContext = {\n\t\t...context,\n\t\tbody: data.body,\n\t\tquery: data.query,\n\t\tpath: context.path || path || \"virtual:\",\n\t\tcontext: \"context\" in context && context.context ? context.context : {},\n\t\treturned: undefined as any,\n\t\theaders: context?.headers,\n\t\trequest: context?.request,\n\t\tparams: \"params\" in context ? context.params : undefined,\n\t\tmethod:\n\t\t\tcontext.method ??\n\t\t\t(Array.isArray(options.method)\n\t\t\t\t? options.method[0]\n\t\t\t\t: options.method === \"*\"\n\t\t\t\t\t? \"GET\"\n\t\t\t\t\t: options.method),\n\t\tsetHeader: (key: string, value: string) => {\n\t\t\theaders.set(key, value);\n\t\t},\n\t\tgetHeader: (key: string) => {\n\t\t\tif (!requestHeaders) return null;\n\t\t\treturn requestHeaders.get(key);\n\t\t},\n\t\tgetCookie: (key: string, prefix?: CookiePrefixOptions) => {\n\t\t\tconst finalKey = getCookieKey(key, prefix);\n\t\t\tif (!finalKey) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn parsedCookies?.get(finalKey) || null;\n\t\t},\n\t\tgetSignedCookie: async (\n\t\t\tkey: string,\n\t\t\tsecret: string,\n\t\t\tprefix?: CookiePrefixOptions,\n\t\t) => {\n\t\t\tconst finalKey = getCookieKey(key, prefix);\n\t\t\tif (!finalKey) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst value = parsedCookies?.get(finalKey);\n\t\t\tif (!value) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst signatureStartPos = value.lastIndexOf(\".\");\n\t\t\tif (signatureStartPos < 1) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst signedValue = value.substring(0, signatureStartPos);\n\t\t\tconst signature = value.substring(signatureStartPos + 1);\n\t\t\tif (signature.length !== 44 || !signature.endsWith(\"=\")) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst secretKey = await getCryptoKey(secret);\n\t\t\tconst isVerified = await verifySignature(\n\t\t\t\tsignature,\n\t\t\t\tsignedValue,\n\t\t\t\tsecretKey,\n\t\t\t);\n\t\t\treturn isVerified ? signedValue : false;\n\t\t},\n\t\tsetCookie: (key: string, value: string, options?: CookieOptions) => {\n\t\t\tconst cookie = serializeCookie(key, value, options);\n\t\t\theaders.append(\"set-cookie\", cookie);\n\t\t\treturn cookie;\n\t\t},\n\t\tsetSignedCookie: async (\n\t\t\tkey: string,\n\t\t\tvalue: string,\n\t\t\tsecret: string,\n\t\t\toptions?: CookieOptions,\n\t\t) => {\n\t\t\tconst cookie = await serializeSignedCookie(key, value, secret, options);\n\t\t\theaders.append(\"set-cookie\", cookie);\n\t\t\treturn cookie;\n\t\t},\n\t\tredirect: (url: string) => {\n\t\t\theaders.set(\"location\", url);\n\t\t\treturn new APIError(\"FOUND\", undefined, headers);\n\t\t},\n\t\terror: (\n\t\t\tstatus: keyof typeof statusCodes | Status,\n\t\t\tbody?:\n\t\t\t\t| {\n\t\t\t\t\t\tmessage?: string;\n\t\t\t\t\t\tcode?: string;\n\t\t\t\t }\n\t\t\t\t| undefined,\n\t\t\theaders?: HeadersInit,\n\t\t) => {\n\t\t\treturn new APIError(status, body, headers);\n\t\t},\n\t\tsetStatus: (status: Status) => {\n\t\t\tresponseStatus = status;\n\t\t},\n\t\tjson: (\n\t\t\tjson: Record<string, any>,\n\t\t\trouterResponse?:\n\t\t\t\t| {\n\t\t\t\t\t\tstatus?: number;\n\t\t\t\t\t\theaders?: Record<string, string>;\n\t\t\t\t\t\tresponse?: Response;\n\t\t\t\t\t\tbody?: Record<string, any>;\n\t\t\t\t }\n\t\t\t\t| Response,\n\t\t) => {\n\t\t\tif (!context.asResponse) {\n\t\t\t\treturn json;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tbody: routerResponse?.body || json,\n\t\t\t\trouterResponse,\n\t\t\t\t_flag: \"json\",\n\t\t\t};\n\t\t},\n\t\tresponseHeaders: headers,\n\t\tget responseStatus() {\n\t\t\treturn responseStatus;\n\t\t},\n\t};\n\t//if context was shimmed through the input we want to apply it\n\tfor (const middleware of options.use || []) {\n\t\tconst response = (await middleware({\n\t\t\t...internalContext,\n\t\t\treturnHeaders: true,\n\t\t\tasResponse: false,\n\t\t})) as {\n\t\t\tresponse?: any;\n\t\t\theaders?: Headers;\n\t\t};\n\t\tif (response.response) {\n\t\t\tObject.assign(internalContext.context, response.response);\n\t\t}\n\t\t/**\n\t\t * Apply headers from the middleware to the endpoint headers\n\t\t */\n\t\tif (response.headers) {\n\t\t\tresponse.headers.forEach((value, key) => {\n\t\t\t\tinternalContext.response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,IAAI,SAAS,UACZ,OAAO,OAAO,gBAAgB,SAAS,SAAS,QAAQ;;;;EAKzD,IAAI,SAAS,SACZ,SAAS,QAAQ,SAAS,OAAO,QAAQ;GACxC,gBAAgB,gBAAgB,IAAI,KAAK,KAAK;EAC/C,CAAC;CAEH;CACA,OAAO;AACR"}
|
package/dist/cookies.cjs
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
const
|
|
2
|
-
const
|
|
3
|
-
|
|
1
|
+
const require_crypto = require("./crypto.cjs");
|
|
2
|
+
const require_utils = require("./utils.cjs");
|
|
4
3
|
//#region src/cookies.ts
|
|
5
4
|
const getCookieKey = (key, prefix) => {
|
|
6
5
|
let finalKey = key;
|
|
@@ -78,10 +77,10 @@ const serializeSignedCookie = async (key, value, secret, opt) => {
|
|
|
78
77
|
value = await require_crypto.signCookieValue(value, secret);
|
|
79
78
|
return _serialize(key, value, opt);
|
|
80
79
|
};
|
|
81
|
-
|
|
82
80
|
//#endregion
|
|
83
81
|
exports.getCookieKey = getCookieKey;
|
|
84
82
|
exports.parseCookies = parseCookies;
|
|
85
83
|
exports.serializeCookie = serializeCookie;
|
|
86
84
|
exports.serializeSignedCookie = serializeSignedCookie;
|
|
85
|
+
|
|
87
86
|
//# sourceMappingURL=cookies.cjs.map
|
package/dist/cookies.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cookies.cjs","names":["tryDecode","signCookieValue"],"sources":["../src/cookies.ts"],"sourcesContent":["import { signCookieValue } from \"./crypto\";\nimport { tryDecode } from \"./utils\";\n\nexport type CookiePrefixOptions = \"host\" | \"secure\";\n\nexport type CookieOptions = {\n\t/**\n\t * Domain of the cookie\n\t *\n\t * The Domain attribute specifies which server can receive a cookie. If specified, cookies are\n\t * available on the specified server and its subdomains. If the it is not\n\t * specified, the cookies are available on the server that sets it but not on\n\t * its subdomains.\n\t *\n\t * @example\n\t * `domain: \"example.com\"`\n\t */\n\tdomain?: string;\n\t/**\n\t * A lifetime of a cookie. Permanent cookies are deleted after the date specified in the\n\t * Expires attribute:\n\t *\n\t * Expires has been available for longer than Max-Age, however Max-Age is less error-prone, and\n\t * takes precedence when both are set. The rationale behind this is that when you set an\n\t * Expires date and time, they're relative to the client the cookie is being set on. If the\n\t * server is set to a different time, this could cause errors\n\t */\n\texpires?: Date;\n\t/**\n\t * Forbids JavaScript from accessing the cookie, for example, through the Document.cookie\n\t * property. Note that a cookie that has been created with HttpOnly will still be sent with\n\t * JavaScript-initiated requests, for example, when calling XMLHttpRequest.send() or fetch().\n\t * This mitigates attacks against cross-site scripting\n\t */\n\thttpOnly?: boolean;\n\t/**\n\t * Indicates the number of seconds until the cookie expires. A zero or negative number will\n\t * expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.\n\t *\n\t * @example 604800 - 7 days\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Indicates the path that must exist in the requested URL for the browser to send the Cookie\n\t * header.\n\t *\n\t * @example\n\t * \"/docs\"\n\t * // -> the request paths /docs, /docs/, /docs/Web/, and /docs/Web/HTTP will all match. the request paths /, /fr/docs will not match.\n\t */\n\tpath?: string;\n\t/**\n\t * Indicates that the cookie is sent to the server only when a request is made with the https:\n\t * scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.\n\t */\n\tsecure?: boolean;\n\t/**\n\t * Controls whether or not a cookie is sent with cross-site requests, providing some protection\n\t * against cross-site request forgery attacks (CSRF).\n\t *\n\t * Strict - Means that the browser sends the cookie only for same-site requests, that is,\n\t * requests originating from the same site that set the cookie. If a request originates from a\n\t * different domain or scheme (even with the same domain), no cookies with the SameSite=Strict\n\t * attribute are sent.\n\t *\n\t * Lax - Means that the cookie is not sent on cross-site requests, such as on requests to load\n\t * images or frames, but is sent when a user is navigating to the origin site from an external\n\t * site (for example, when following a link). This is the default behavior if the SameSite\n\t * attribute is not specified.\n\t *\n\t * None - Means that the browser sends the cookie with both cross-site and same-site requests.\n\t * The Secure attribute must also be set when setting this value.\n\t */\n\tsameSite?: \"Strict\" | \"Lax\" | \"None\" | \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Indicates that the cookie should be stored using partitioned storage. Note that if this is\n\t * set, the Secure directive must also be set.\n\t *\n\t * @see https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies\n\t */\n\tpartitioned?: boolean;\n\t/**\n\t * Cooke Prefix\n\t *\n\t * - secure: `__Secure-` -> `__Secure-cookie-name`\n\t * - host: `__Host-` -> `__Host-cookie-name`\n\t *\n\t * `secure` must be set to true to use prefixes\n\t */\n\tprefix?: CookiePrefixOptions;\n};\n\nexport const getCookieKey = (key: string, prefix?: CookiePrefixOptions) => {\n\tlet finalKey = key;\n\tif (prefix) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\treturn finalKey;\n};\n\n/**\n * Parse an HTTP Cookie header string and returning an object of all cookie\n * name-value pairs.\n *\n * Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts\n *\n * @param str the string representing a `Cookie` header value\n */\nexport function parseCookies(str: string) {\n\tif (typeof str !== \"string\") {\n\t\tthrow new TypeError(\"argument str must be a string\");\n\t}\n\n\tconst cookies: Map<string, string> = new Map();\n\n\tlet index = 0;\n\twhile (index < str.length) {\n\t\tconst eqIdx = str.indexOf(\"=\", index);\n\n\t\tif (eqIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlet endIdx = str.indexOf(\";\", index);\n\n\t\tif (endIdx === -1) {\n\t\t\tendIdx = str.length;\n\t\t} else if (endIdx < eqIdx) {\n\t\t\tindex = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst key = str.slice(index, eqIdx).trim();\n\t\tif (!cookies.has(key)) {\n\t\t\tlet val = str.slice(eqIdx + 1, endIdx).trim();\n\t\t\tif (val.codePointAt(0) === 0x22) {\n\t\t\t\tval = val.slice(1, -1);\n\t\t\t}\n\t\t\tcookies.set(key, tryDecode(val));\n\t\t}\n\n\t\tindex = endIdx + 1;\n\t}\n\n\treturn cookies;\n}\n\nconst _serialize = (key: string, value: string, opt: CookieOptions = {}) => {\n\tlet cookie: string;\n\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = `${`__Secure-${key}`}=${value}`;\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = `${`__Host-${key}`}=${value}`;\n\t} else {\n\t\tcookie = `${key}=${value}`;\n\t}\n\n\tif (key.startsWith(\"__Secure-\") && !opt.secure) {\n\t\topt.secure = true;\n\t}\n\n\tif (key.startsWith(\"__Host-\")) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\topt.path = \"/\";\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\topt.domain = undefined;\n\t\t}\n\t}\n\n\tif (opt && typeof opt.maxAge === \"number\" && opt.maxAge >= 0) {\n\t\tif (opt.maxAge > 34560000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Max-Age=${Math.floor(opt.maxAge)}`;\n\t}\n\n\tif (opt.domain && opt.prefix !== \"host\") {\n\t\tcookie += `; Domain=${opt.domain}`;\n\t}\n\n\tif (opt.path) {\n\t\tcookie += `; Path=${opt.path}`;\n\t}\n\n\tif (opt.expires) {\n\t\tif (opt.expires.getTime() - Date.now() > 34560000_000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Expires=${opt.expires.toUTCString()}`;\n\t}\n\n\tif (opt.httpOnly) {\n\t\tcookie += \"; HttpOnly\";\n\t}\n\n\tif (opt.secure) {\n\t\tcookie += \"; Secure\";\n\t}\n\n\tif (opt.sameSite) {\n\t\tcookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;\n\t}\n\n\tif (opt.partitioned) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\t\tcookie += \"; Partitioned\";\n\t}\n\n\treturn cookie;\n};\n\nexport const serializeCookie = (\n\tkey: string,\n\tvalue: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(key, value, opt);\n};\n\nexport const serializeSignedCookie = async (\n\tkey: string,\n\tvalue: string,\n\tsecret: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = await signCookieValue(value, secret);\n\treturn _serialize(key, value, opt);\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"cookies.cjs","names":["tryDecode","signCookieValue"],"sources":["../src/cookies.ts"],"sourcesContent":["import { signCookieValue } from \"./crypto\";\nimport { tryDecode } from \"./utils\";\n\nexport type CookiePrefixOptions = \"host\" | \"secure\";\n\nexport type CookieOptions = {\n\t/**\n\t * Domain of the cookie\n\t *\n\t * The Domain attribute specifies which server can receive a cookie. If specified, cookies are\n\t * available on the specified server and its subdomains. If the it is not\n\t * specified, the cookies are available on the server that sets it but not on\n\t * its subdomains.\n\t *\n\t * @example\n\t * `domain: \"example.com\"`\n\t */\n\tdomain?: string;\n\t/**\n\t * A lifetime of a cookie. Permanent cookies are deleted after the date specified in the\n\t * Expires attribute:\n\t *\n\t * Expires has been available for longer than Max-Age, however Max-Age is less error-prone, and\n\t * takes precedence when both are set. The rationale behind this is that when you set an\n\t * Expires date and time, they're relative to the client the cookie is being set on. If the\n\t * server is set to a different time, this could cause errors\n\t */\n\texpires?: Date;\n\t/**\n\t * Forbids JavaScript from accessing the cookie, for example, through the Document.cookie\n\t * property. Note that a cookie that has been created with HttpOnly will still be sent with\n\t * JavaScript-initiated requests, for example, when calling XMLHttpRequest.send() or fetch().\n\t * This mitigates attacks against cross-site scripting\n\t */\n\thttpOnly?: boolean;\n\t/**\n\t * Indicates the number of seconds until the cookie expires. A zero or negative number will\n\t * expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.\n\t *\n\t * @example 604800 - 7 days\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Indicates the path that must exist in the requested URL for the browser to send the Cookie\n\t * header.\n\t *\n\t * @example\n\t * \"/docs\"\n\t * // -> the request paths /docs, /docs/, /docs/Web/, and /docs/Web/HTTP will all match. the request paths /, /fr/docs will not match.\n\t */\n\tpath?: string;\n\t/**\n\t * Indicates that the cookie is sent to the server only when a request is made with the https:\n\t * scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.\n\t */\n\tsecure?: boolean;\n\t/**\n\t * Controls whether or not a cookie is sent with cross-site requests, providing some protection\n\t * against cross-site request forgery attacks (CSRF).\n\t *\n\t * Strict - Means that the browser sends the cookie only for same-site requests, that is,\n\t * requests originating from the same site that set the cookie. If a request originates from a\n\t * different domain or scheme (even with the same domain), no cookies with the SameSite=Strict\n\t * attribute are sent.\n\t *\n\t * Lax - Means that the cookie is not sent on cross-site requests, such as on requests to load\n\t * images or frames, but is sent when a user is navigating to the origin site from an external\n\t * site (for example, when following a link). This is the default behavior if the SameSite\n\t * attribute is not specified.\n\t *\n\t * None - Means that the browser sends the cookie with both cross-site and same-site requests.\n\t * The Secure attribute must also be set when setting this value.\n\t */\n\tsameSite?: \"Strict\" | \"Lax\" | \"None\" | \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Indicates that the cookie should be stored using partitioned storage. Note that if this is\n\t * set, the Secure directive must also be set.\n\t *\n\t * @see https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies\n\t */\n\tpartitioned?: boolean;\n\t/**\n\t * Cooke Prefix\n\t *\n\t * - secure: `__Secure-` -> `__Secure-cookie-name`\n\t * - host: `__Host-` -> `__Host-cookie-name`\n\t *\n\t * `secure` must be set to true to use prefixes\n\t */\n\tprefix?: CookiePrefixOptions;\n};\n\nexport const getCookieKey = (key: string, prefix?: CookiePrefixOptions) => {\n\tlet finalKey = key;\n\tif (prefix) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\treturn finalKey;\n};\n\n/**\n * Parse an HTTP Cookie header string and returning an object of all cookie\n * name-value pairs.\n *\n * Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts\n *\n * @param str the string representing a `Cookie` header value\n */\nexport function parseCookies(str: string) {\n\tif (typeof str !== \"string\") {\n\t\tthrow new TypeError(\"argument str must be a string\");\n\t}\n\n\tconst cookies: Map<string, string> = new Map();\n\n\tlet index = 0;\n\twhile (index < str.length) {\n\t\tconst eqIdx = str.indexOf(\"=\", index);\n\n\t\tif (eqIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlet endIdx = str.indexOf(\";\", index);\n\n\t\tif (endIdx === -1) {\n\t\t\tendIdx = str.length;\n\t\t} else if (endIdx < eqIdx) {\n\t\t\tindex = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst key = str.slice(index, eqIdx).trim();\n\t\tif (!cookies.has(key)) {\n\t\t\tlet val = str.slice(eqIdx + 1, endIdx).trim();\n\t\t\tif (val.codePointAt(0) === 0x22) {\n\t\t\t\tval = val.slice(1, -1);\n\t\t\t}\n\t\t\tcookies.set(key, tryDecode(val));\n\t\t}\n\n\t\tindex = endIdx + 1;\n\t}\n\n\treturn cookies;\n}\n\nconst _serialize = (key: string, value: string, opt: CookieOptions = {}) => {\n\tlet cookie: string;\n\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = `${`__Secure-${key}`}=${value}`;\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = `${`__Host-${key}`}=${value}`;\n\t} else {\n\t\tcookie = `${key}=${value}`;\n\t}\n\n\tif (key.startsWith(\"__Secure-\") && !opt.secure) {\n\t\topt.secure = true;\n\t}\n\n\tif (key.startsWith(\"__Host-\")) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\topt.path = \"/\";\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\topt.domain = undefined;\n\t\t}\n\t}\n\n\tif (opt && typeof opt.maxAge === \"number\" && opt.maxAge >= 0) {\n\t\tif (opt.maxAge > 34560000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Max-Age=${Math.floor(opt.maxAge)}`;\n\t}\n\n\tif (opt.domain && opt.prefix !== \"host\") {\n\t\tcookie += `; Domain=${opt.domain}`;\n\t}\n\n\tif (opt.path) {\n\t\tcookie += `; Path=${opt.path}`;\n\t}\n\n\tif (opt.expires) {\n\t\tif (opt.expires.getTime() - Date.now() > 34560000_000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Expires=${opt.expires.toUTCString()}`;\n\t}\n\n\tif (opt.httpOnly) {\n\t\tcookie += \"; HttpOnly\";\n\t}\n\n\tif (opt.secure) {\n\t\tcookie += \"; Secure\";\n\t}\n\n\tif (opt.sameSite) {\n\t\tcookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;\n\t}\n\n\tif (opt.partitioned) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\t\tcookie += \"; Partitioned\";\n\t}\n\n\treturn cookie;\n};\n\nexport const serializeCookie = (\n\tkey: string,\n\tvalue: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(key, value, opt);\n};\n\nexport const serializeSignedCookie = async (\n\tkey: string,\n\tvalue: string,\n\tsecret: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = await signCookieValue(value, secret);\n\treturn _serialize(key, value, opt);\n};\n"],"mappings":";;;AA4FA,MAAa,gBAAgB,KAAa,WAAiC;CAC1E,IAAI,WAAW;CACf,IAAI,QACH,IAAI,WAAW,UACd,WAAW,cAAc;MACnB,IAAI,WAAW,QACrB,WAAW,YAAY;MAEvB;CAGF,OAAO;AACR;;;;;;;;;AAUA,SAAgB,aAAa,KAAa;CACzC,IAAI,OAAO,QAAQ,UAClB,MAAM,IAAI,UAAU,+BAA+B;CAGpD,MAAM,0BAA+B,IAAI,IAAI;CAE7C,IAAI,QAAQ;CACZ,OAAO,QAAQ,IAAI,QAAQ;EAC1B,MAAM,QAAQ,IAAI,QAAQ,KAAK,KAAK;EAEpC,IAAI,UAAU,IACb;EAGD,IAAI,SAAS,IAAI,QAAQ,KAAK,KAAK;EAEnC,IAAI,WAAW,IACd,SAAS,IAAI;OACP,IAAI,SAAS,OAAO;GAC1B,QAAQ,IAAI,YAAY,KAAK,QAAQ,CAAC,IAAI;GAC1C;EACD;EAEA,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC,KAAK;EACzC,IAAI,CAAC,QAAQ,IAAI,GAAG,GAAG;GACtB,IAAI,MAAM,IAAI,MAAM,QAAQ,GAAG,MAAM,CAAC,CAAC,KAAK;GAC5C,IAAI,IAAI,YAAY,CAAC,MAAM,IAC1B,MAAM,IAAI,MAAM,GAAG,EAAE;GAEtB,QAAQ,IAAI,KAAKA,cAAAA,UAAU,GAAG,CAAC;EAChC;EAEA,QAAQ,SAAS;CAClB;CAEA,OAAO;AACR;AAEA,MAAM,cAAc,KAAa,OAAe,MAAqB,CAAC,MAAM;CAC3E,IAAI;CAEJ,IAAI,KAAK,WAAW,UACnB,SAAS,GAAG,YAAY,MAAM,GAAG;MAC3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AO,GAAG;AAClC"}
|
package/dist/cookies.mjs
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { tryDecode } from "./utils.mjs";
|
|
2
1
|
import { signCookieValue } from "./crypto.mjs";
|
|
3
|
-
|
|
2
|
+
import { tryDecode } from "./utils.mjs";
|
|
4
3
|
//#region src/cookies.ts
|
|
5
4
|
const getCookieKey = (key, prefix) => {
|
|
6
5
|
let finalKey = key;
|
|
@@ -78,7 +77,7 @@ const serializeSignedCookie = async (key, value, secret, opt) => {
|
|
|
78
77
|
value = await signCookieValue(value, secret);
|
|
79
78
|
return _serialize(key, value, opt);
|
|
80
79
|
};
|
|
81
|
-
|
|
82
80
|
//#endregion
|
|
83
81
|
export { getCookieKey, parseCookies, serializeCookie, serializeSignedCookie };
|
|
82
|
+
|
|
84
83
|
//# sourceMappingURL=cookies.mjs.map
|
package/dist/cookies.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cookies.mjs","names":[],"sources":["../src/cookies.ts"],"sourcesContent":["import { signCookieValue } from \"./crypto\";\nimport { tryDecode } from \"./utils\";\n\nexport type CookiePrefixOptions = \"host\" | \"secure\";\n\nexport type CookieOptions = {\n\t/**\n\t * Domain of the cookie\n\t *\n\t * The Domain attribute specifies which server can receive a cookie. If specified, cookies are\n\t * available on the specified server and its subdomains. If the it is not\n\t * specified, the cookies are available on the server that sets it but not on\n\t * its subdomains.\n\t *\n\t * @example\n\t * `domain: \"example.com\"`\n\t */\n\tdomain?: string;\n\t/**\n\t * A lifetime of a cookie. Permanent cookies are deleted after the date specified in the\n\t * Expires attribute:\n\t *\n\t * Expires has been available for longer than Max-Age, however Max-Age is less error-prone, and\n\t * takes precedence when both are set. The rationale behind this is that when you set an\n\t * Expires date and time, they're relative to the client the cookie is being set on. If the\n\t * server is set to a different time, this could cause errors\n\t */\n\texpires?: Date;\n\t/**\n\t * Forbids JavaScript from accessing the cookie, for example, through the Document.cookie\n\t * property. Note that a cookie that has been created with HttpOnly will still be sent with\n\t * JavaScript-initiated requests, for example, when calling XMLHttpRequest.send() or fetch().\n\t * This mitigates attacks against cross-site scripting\n\t */\n\thttpOnly?: boolean;\n\t/**\n\t * Indicates the number of seconds until the cookie expires. A zero or negative number will\n\t * expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.\n\t *\n\t * @example 604800 - 7 days\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Indicates the path that must exist in the requested URL for the browser to send the Cookie\n\t * header.\n\t *\n\t * @example\n\t * \"/docs\"\n\t * // -> the request paths /docs, /docs/, /docs/Web/, and /docs/Web/HTTP will all match. the request paths /, /fr/docs will not match.\n\t */\n\tpath?: string;\n\t/**\n\t * Indicates that the cookie is sent to the server only when a request is made with the https:\n\t * scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.\n\t */\n\tsecure?: boolean;\n\t/**\n\t * Controls whether or not a cookie is sent with cross-site requests, providing some protection\n\t * against cross-site request forgery attacks (CSRF).\n\t *\n\t * Strict - Means that the browser sends the cookie only for same-site requests, that is,\n\t * requests originating from the same site that set the cookie. If a request originates from a\n\t * different domain or scheme (even with the same domain), no cookies with the SameSite=Strict\n\t * attribute are sent.\n\t *\n\t * Lax - Means that the cookie is not sent on cross-site requests, such as on requests to load\n\t * images or frames, but is sent when a user is navigating to the origin site from an external\n\t * site (for example, when following a link). This is the default behavior if the SameSite\n\t * attribute is not specified.\n\t *\n\t * None - Means that the browser sends the cookie with both cross-site and same-site requests.\n\t * The Secure attribute must also be set when setting this value.\n\t */\n\tsameSite?: \"Strict\" | \"Lax\" | \"None\" | \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Indicates that the cookie should be stored using partitioned storage. Note that if this is\n\t * set, the Secure directive must also be set.\n\t *\n\t * @see https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies\n\t */\n\tpartitioned?: boolean;\n\t/**\n\t * Cooke Prefix\n\t *\n\t * - secure: `__Secure-` -> `__Secure-cookie-name`\n\t * - host: `__Host-` -> `__Host-cookie-name`\n\t *\n\t * `secure` must be set to true to use prefixes\n\t */\n\tprefix?: CookiePrefixOptions;\n};\n\nexport const getCookieKey = (key: string, prefix?: CookiePrefixOptions) => {\n\tlet finalKey = key;\n\tif (prefix) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\treturn finalKey;\n};\n\n/**\n * Parse an HTTP Cookie header string and returning an object of all cookie\n * name-value pairs.\n *\n * Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts\n *\n * @param str the string representing a `Cookie` header value\n */\nexport function parseCookies(str: string) {\n\tif (typeof str !== \"string\") {\n\t\tthrow new TypeError(\"argument str must be a string\");\n\t}\n\n\tconst cookies: Map<string, string> = new Map();\n\n\tlet index = 0;\n\twhile (index < str.length) {\n\t\tconst eqIdx = str.indexOf(\"=\", index);\n\n\t\tif (eqIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlet endIdx = str.indexOf(\";\", index);\n\n\t\tif (endIdx === -1) {\n\t\t\tendIdx = str.length;\n\t\t} else if (endIdx < eqIdx) {\n\t\t\tindex = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst key = str.slice(index, eqIdx).trim();\n\t\tif (!cookies.has(key)) {\n\t\t\tlet val = str.slice(eqIdx + 1, endIdx).trim();\n\t\t\tif (val.codePointAt(0) === 0x22) {\n\t\t\t\tval = val.slice(1, -1);\n\t\t\t}\n\t\t\tcookies.set(key, tryDecode(val));\n\t\t}\n\n\t\tindex = endIdx + 1;\n\t}\n\n\treturn cookies;\n}\n\nconst _serialize = (key: string, value: string, opt: CookieOptions = {}) => {\n\tlet cookie: string;\n\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = `${`__Secure-${key}`}=${value}`;\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = `${`__Host-${key}`}=${value}`;\n\t} else {\n\t\tcookie = `${key}=${value}`;\n\t}\n\n\tif (key.startsWith(\"__Secure-\") && !opt.secure) {\n\t\topt.secure = true;\n\t}\n\n\tif (key.startsWith(\"__Host-\")) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\topt.path = \"/\";\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\topt.domain = undefined;\n\t\t}\n\t}\n\n\tif (opt && typeof opt.maxAge === \"number\" && opt.maxAge >= 0) {\n\t\tif (opt.maxAge > 34560000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Max-Age=${Math.floor(opt.maxAge)}`;\n\t}\n\n\tif (opt.domain && opt.prefix !== \"host\") {\n\t\tcookie += `; Domain=${opt.domain}`;\n\t}\n\n\tif (opt.path) {\n\t\tcookie += `; Path=${opt.path}`;\n\t}\n\n\tif (opt.expires) {\n\t\tif (opt.expires.getTime() - Date.now() > 34560000_000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Expires=${opt.expires.toUTCString()}`;\n\t}\n\n\tif (opt.httpOnly) {\n\t\tcookie += \"; HttpOnly\";\n\t}\n\n\tif (opt.secure) {\n\t\tcookie += \"; Secure\";\n\t}\n\n\tif (opt.sameSite) {\n\t\tcookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;\n\t}\n\n\tif (opt.partitioned) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\t\tcookie += \"; Partitioned\";\n\t}\n\n\treturn cookie;\n};\n\nexport const serializeCookie = (\n\tkey: string,\n\tvalue: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(key, value, opt);\n};\n\nexport const serializeSignedCookie = async (\n\tkey: string,\n\tvalue: string,\n\tsecret: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = await signCookieValue(value, secret);\n\treturn _serialize(key, value, opt);\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"cookies.mjs","names":[],"sources":["../src/cookies.ts"],"sourcesContent":["import { signCookieValue } from \"./crypto\";\nimport { tryDecode } from \"./utils\";\n\nexport type CookiePrefixOptions = \"host\" | \"secure\";\n\nexport type CookieOptions = {\n\t/**\n\t * Domain of the cookie\n\t *\n\t * The Domain attribute specifies which server can receive a cookie. If specified, cookies are\n\t * available on the specified server and its subdomains. If the it is not\n\t * specified, the cookies are available on the server that sets it but not on\n\t * its subdomains.\n\t *\n\t * @example\n\t * `domain: \"example.com\"`\n\t */\n\tdomain?: string;\n\t/**\n\t * A lifetime of a cookie. Permanent cookies are deleted after the date specified in the\n\t * Expires attribute:\n\t *\n\t * Expires has been available for longer than Max-Age, however Max-Age is less error-prone, and\n\t * takes precedence when both are set. The rationale behind this is that when you set an\n\t * Expires date and time, they're relative to the client the cookie is being set on. If the\n\t * server is set to a different time, this could cause errors\n\t */\n\texpires?: Date;\n\t/**\n\t * Forbids JavaScript from accessing the cookie, for example, through the Document.cookie\n\t * property. Note that a cookie that has been created with HttpOnly will still be sent with\n\t * JavaScript-initiated requests, for example, when calling XMLHttpRequest.send() or fetch().\n\t * This mitigates attacks against cross-site scripting\n\t */\n\thttpOnly?: boolean;\n\t/**\n\t * Indicates the number of seconds until the cookie expires. A zero or negative number will\n\t * expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.\n\t *\n\t * @example 604800 - 7 days\n\t */\n\tmaxAge?: number;\n\t/**\n\t * Indicates the path that must exist in the requested URL for the browser to send the Cookie\n\t * header.\n\t *\n\t * @example\n\t * \"/docs\"\n\t * // -> the request paths /docs, /docs/, /docs/Web/, and /docs/Web/HTTP will all match. the request paths /, /fr/docs will not match.\n\t */\n\tpath?: string;\n\t/**\n\t * Indicates that the cookie is sent to the server only when a request is made with the https:\n\t * scheme (except on localhost), and therefore, is more resistant to man-in-the-middle attacks.\n\t */\n\tsecure?: boolean;\n\t/**\n\t * Controls whether or not a cookie is sent with cross-site requests, providing some protection\n\t * against cross-site request forgery attacks (CSRF).\n\t *\n\t * Strict - Means that the browser sends the cookie only for same-site requests, that is,\n\t * requests originating from the same site that set the cookie. If a request originates from a\n\t * different domain or scheme (even with the same domain), no cookies with the SameSite=Strict\n\t * attribute are sent.\n\t *\n\t * Lax - Means that the cookie is not sent on cross-site requests, such as on requests to load\n\t * images or frames, but is sent when a user is navigating to the origin site from an external\n\t * site (for example, when following a link). This is the default behavior if the SameSite\n\t * attribute is not specified.\n\t *\n\t * None - Means that the browser sends the cookie with both cross-site and same-site requests.\n\t * The Secure attribute must also be set when setting this value.\n\t */\n\tsameSite?: \"Strict\" | \"Lax\" | \"None\" | \"strict\" | \"lax\" | \"none\";\n\t/**\n\t * Indicates that the cookie should be stored using partitioned storage. Note that if this is\n\t * set, the Secure directive must also be set.\n\t *\n\t * @see https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies\n\t */\n\tpartitioned?: boolean;\n\t/**\n\t * Cooke Prefix\n\t *\n\t * - secure: `__Secure-` -> `__Secure-cookie-name`\n\t * - host: `__Host-` -> `__Host-cookie-name`\n\t *\n\t * `secure` must be set to true to use prefixes\n\t */\n\tprefix?: CookiePrefixOptions;\n};\n\nexport const getCookieKey = (key: string, prefix?: CookiePrefixOptions) => {\n\tlet finalKey = key;\n\tif (prefix) {\n\t\tif (prefix === \"secure\") {\n\t\t\tfinalKey = \"__Secure-\" + key;\n\t\t} else if (prefix === \"host\") {\n\t\t\tfinalKey = \"__Host-\" + key;\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\treturn finalKey;\n};\n\n/**\n * Parse an HTTP Cookie header string and returning an object of all cookie\n * name-value pairs.\n *\n * Inspired by https://github.com/unjs/cookie-es/blob/main/src/cookie/parse.ts\n *\n * @param str the string representing a `Cookie` header value\n */\nexport function parseCookies(str: string) {\n\tif (typeof str !== \"string\") {\n\t\tthrow new TypeError(\"argument str must be a string\");\n\t}\n\n\tconst cookies: Map<string, string> = new Map();\n\n\tlet index = 0;\n\twhile (index < str.length) {\n\t\tconst eqIdx = str.indexOf(\"=\", index);\n\n\t\tif (eqIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\n\t\tlet endIdx = str.indexOf(\";\", index);\n\n\t\tif (endIdx === -1) {\n\t\t\tendIdx = str.length;\n\t\t} else if (endIdx < eqIdx) {\n\t\t\tindex = str.lastIndexOf(\";\", eqIdx - 1) + 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst key = str.slice(index, eqIdx).trim();\n\t\tif (!cookies.has(key)) {\n\t\t\tlet val = str.slice(eqIdx + 1, endIdx).trim();\n\t\t\tif (val.codePointAt(0) === 0x22) {\n\t\t\t\tval = val.slice(1, -1);\n\t\t\t}\n\t\t\tcookies.set(key, tryDecode(val));\n\t\t}\n\n\t\tindex = endIdx + 1;\n\t}\n\n\treturn cookies;\n}\n\nconst _serialize = (key: string, value: string, opt: CookieOptions = {}) => {\n\tlet cookie: string;\n\n\tif (opt?.prefix === \"secure\") {\n\t\tcookie = `${`__Secure-${key}`}=${value}`;\n\t} else if (opt?.prefix === \"host\") {\n\t\tcookie = `${`__Host-${key}`}=${value}`;\n\t} else {\n\t\tcookie = `${key}=${value}`;\n\t}\n\n\tif (key.startsWith(\"__Secure-\") && !opt.secure) {\n\t\topt.secure = true;\n\t}\n\n\tif (key.startsWith(\"__Host-\")) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\n\t\tif (opt.path !== \"/\") {\n\t\t\topt.path = \"/\";\n\t\t}\n\n\t\tif (opt.domain) {\n\t\t\topt.domain = undefined;\n\t\t}\n\t}\n\n\tif (opt && typeof opt.maxAge === \"number\" && opt.maxAge >= 0) {\n\t\tif (opt.maxAge > 34560000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Max-Age=${Math.floor(opt.maxAge)}`;\n\t}\n\n\tif (opt.domain && opt.prefix !== \"host\") {\n\t\tcookie += `; Domain=${opt.domain}`;\n\t}\n\n\tif (opt.path) {\n\t\tcookie += `; Path=${opt.path}`;\n\t}\n\n\tif (opt.expires) {\n\t\tif (opt.expires.getTime() - Date.now() > 34560000_000) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.\",\n\t\t\t);\n\t\t}\n\t\tcookie += `; Expires=${opt.expires.toUTCString()}`;\n\t}\n\n\tif (opt.httpOnly) {\n\t\tcookie += \"; HttpOnly\";\n\t}\n\n\tif (opt.secure) {\n\t\tcookie += \"; Secure\";\n\t}\n\n\tif (opt.sameSite) {\n\t\tcookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`;\n\t}\n\n\tif (opt.partitioned) {\n\t\tif (!opt.secure) {\n\t\t\topt.secure = true;\n\t\t}\n\t\tcookie += \"; Partitioned\";\n\t}\n\n\treturn cookie;\n};\n\nexport const serializeCookie = (\n\tkey: string,\n\tvalue: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = encodeURIComponent(value);\n\treturn _serialize(key, value, opt);\n};\n\nexport const serializeSignedCookie = async (\n\tkey: string,\n\tvalue: string,\n\tsecret: string,\n\topt?: CookieOptions,\n) => {\n\tvalue = await signCookieValue(value, secret);\n\treturn _serialize(key, value, opt);\n};\n"],"mappings":";;;AA4FA,MAAa,gBAAgB,KAAa,WAAiC;CAC1E,IAAI,WAAW;CACf,IAAI,QACH,IAAI,WAAW,UACd,WAAW,cAAc;MACnB,IAAI,WA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I,SAAS,KAAA;CAEf;CAEA,IAAI,OAAO,OAAO,IAAI,WAAW,YAAY,IAAI,UAAU,GAAG;EAC7D,IAAI,IAAI,SAAS,QAChB,MAAM,IAAI,MACT,qFACD;EAED,UAAU,aAAa,KAAK,MAAM,IAAI,MAAM;CAC7C;CAEA,IAAI,IAAI,UAAU,IAAI,WAAW,QAChC,UAAU,YAAY,IAAI;CAG3B,IAAI,IAAI,MACP,UAAU,UAAU,IAAI;CAGzB,IAAI,IAAI,SAAS;EAChB,IAAI,IAAI,QAAQ,QAAQ,IAAI,KAAK,IAAI,IAAI,QACxC,MAAM,IAAI,MACT,uFACD;EAED,UAAU,aAAa,IAAI,QAAQ,YAAY;CAChD;CAEA,IAAI,IAAI,UACP,UAAU;CAGX,IAAI,IAAI,QACP,UAAU;CAGX,IAAI,IAAI,UACP,UAAU,cAAc,IAAI,SAAS,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,IAAI,SAAS,MAAM,CAAC;CAGpF,IAAI,IAAI,aAAa;EACpB,IAAI,CAAC,IAAI,QACR,IAAI,SAAS;EAEd,UAAU;CACX;CAEA,OAAO;AACR;AAEA,MAAa,mBACZ,KACA,OACA,QACI;CACJ,QAAQ,mBAAmB,KAAK;CAChC,OAAO,WAAW,KAAK,OAAO,GAAG;AAClC;AAEA,MAAa,wBAAwB,OACpC,KACA,OACA,QACA,QACI;CACJ,QAAQ,MAAM,gBAAgB,OAAO,MAAM;CAC3C,OAAO,WAAW,KAAK,OAAO,GAAG;AAClC"}
|
package/dist/crypto.cjs
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
|
|
2
1
|
let _better_auth_utils = require("@better-auth/utils");
|
|
3
|
-
|
|
4
2
|
//#region src/crypto.ts
|
|
5
3
|
const algorithm = {
|
|
6
4
|
name: "HMAC",
|
|
@@ -16,7 +14,7 @@ const verifySignature = async (base64Signature, value, secret) => {
|
|
|
16
14
|
const signature = new Uint8Array(signatureBinStr.length);
|
|
17
15
|
for (let i = 0, len = signatureBinStr.length; i < len; i++) signature[i] = signatureBinStr.charCodeAt(i);
|
|
18
16
|
return await (0, _better_auth_utils.getWebcryptoSubtle)().verify(algorithm, secret, signature, new TextEncoder().encode(value));
|
|
19
|
-
} catch
|
|
17
|
+
} catch {
|
|
20
18
|
return false;
|
|
21
19
|
}
|
|
22
20
|
};
|
|
@@ -31,9 +29,9 @@ const signCookieValue = async (value, secret) => {
|
|
|
31
29
|
value = encodeURIComponent(value);
|
|
32
30
|
return value;
|
|
33
31
|
};
|
|
34
|
-
|
|
35
32
|
//#endregion
|
|
36
33
|
exports.getCryptoKey = getCryptoKey;
|
|
37
34
|
exports.signCookieValue = signCookieValue;
|
|
38
35
|
exports.verifySignature = verifySignature;
|
|
36
|
+
|
|
39
37
|
//# sourceMappingURL=crypto.cjs.map
|